hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ee8ded60586fa797d88bc85505e874510f3c8424 | 445 | hpp | C++ | include/protocol/v7_6/protocol.hpp | Gronis/gloomhaven-helper-rfid | f04947c94e05e8fa3f2d17ded4dacb807bcf8677 | [
"MIT"
] | 11 | 2019-08-23T11:42:04.000Z | 2022-03-18T22:59:38.000Z | include/protocol/v7_6/protocol.hpp | Gronis/gloomhaven-helper-rfid | f04947c94e05e8fa3f2d17ded4dacb807bcf8677 | [
"MIT"
] | 4 | 2020-02-05T08:28:40.000Z | 2020-08-02T14:20:34.000Z | include/protocol/v7_6/protocol.hpp | Gronis/gloomhaven-helper-rfid | f04947c94e05e8fa3f2d17ded4dacb807bcf8677 | [
"MIT"
] | 3 | 2020-02-05T08:26:18.000Z | 2020-12-12T23:34:51.000Z | #ifndef __PROTOCOL_V7_6_PROTOCOL_H__
#define __PROTOCOL_V7_6_PROTOCOL_H__
#include "protocol/buffer.hpp"
#include "model/gameState.hpp"
namespace ghh
{
namespace protocol
{
namespace v7_6
{
void readGameState(ghh::GameState &state, ghh::protocol::Buffer &msg);
void writeGameState(const ghh::GameState &state, ghh::protocol::Buffer &msg);
} // namespace v7_6
} // namespace protocol
} // namespace ghh
#endif // __PROTOCOL_V7_6_PROTOCOL_H__ | 21.190476 | 77 | 0.779775 | [
"model"
] |
ee8e8063ea089d8fd48805d8e1a9193abeebb456 | 2,648 | cpp | C++ | source/QtDataVisualization/QScatter3DSeriesSlots.cpp | orangesocks/Qt5xHb | 03aa383d9ae86cdadf7289d846018f8a3382a0e4 | [
"MIT"
] | 11 | 2017-01-30T14:19:11.000Z | 2020-05-30T13:39:16.000Z | source/QtDataVisualization/QScatter3DSeriesSlots.cpp | orangesocks/Qt5xHb | 03aa383d9ae86cdadf7289d846018f8a3382a0e4 | [
"MIT"
] | 1 | 2017-02-24T20:57:32.000Z | 2018-05-29T13:43:05.000Z | source/QtDataVisualization/QScatter3DSeriesSlots.cpp | orangesocks/Qt5xHb | 03aa383d9ae86cdadf7289d846018f8a3382a0e4 | [
"MIT"
] | 5 | 2017-01-30T14:19:12.000Z | 2020-03-28T08:54:56.000Z | /*
Qt5xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 5
Copyright (C) 2021 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>
*/
/*
DO NOT EDIT THIS FILE - the content was created using a source code generator
*/
#include "QScatter3DSeriesSlots.h"
QScatter3DSeriesSlots::QScatter3DSeriesSlots( QObject *parent ) : QObject( parent )
{
}
QScatter3DSeriesSlots::~QScatter3DSeriesSlots()
{
}
void QScatter3DSeriesSlots::dataProxyChanged( QScatterDataProxy * proxy )
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "dataProxyChanged(QScatterDataProxy*)" );
if( cb )
{
PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QSCATTER3DSERIES" );
PHB_ITEM pproxy = Qt5xHb::Signals_return_qobject( (QObject *) proxy, "QSCATTERDATAPROXY" );
hb_vmEvalBlockV( cb, 2, psender, pproxy );
hb_itemRelease( psender );
hb_itemRelease( pproxy );
}
}
void QScatter3DSeriesSlots::itemSizeChanged( float size )
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "itemSizeChanged(float)" );
if( cb )
{
PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QSCATTER3DSERIES" );
PHB_ITEM psize = hb_itemPutND( NULL, size );
hb_vmEvalBlockV( cb, 2, psender, psize );
hb_itemRelease( psender );
hb_itemRelease( psize );
}
}
void QScatter3DSeriesSlots::selectedItemChanged( int index )
{
QObject *object = qobject_cast<QObject *>(sender());
PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "selectedItemChanged(int)" );
if( cb )
{
PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QSCATTER3DSERIES" );
PHB_ITEM pindex = hb_itemPutNI( NULL, index );
hb_vmEvalBlockV( cb, 2, psender, pindex );
hb_itemRelease( psender );
hb_itemRelease( pindex );
}
}
void QScatter3DSeriesSlots_connect_signal( const QString & signal, const QString & slot )
{
QScatter3DSeries * obj = (QScatter3DSeries *) Qt5xHb::itemGetPtrStackSelfItem();
if( obj )
{
QScatter3DSeriesSlots * s = QCoreApplication::instance()->findChild<QScatter3DSeriesSlots *>();
if( s == NULL )
{
s = new QScatter3DSeriesSlots();
s->moveToThread( QCoreApplication::instance()->thread() );
s->setParent( QCoreApplication::instance() );
}
hb_retl( Qt5xHb::Signals_connection_disconnection( s, signal, slot ) );
}
else
{
hb_retl( false );
}
}
| 26.747475 | 100 | 0.67636 | [
"object"
] |
ee93486db97f196274494ac8896a9ae2d518cbb9 | 2,618 | hpp | C++ | Nostra Utils/src/header/nostrautils/dat_alg/BinarySearch.hpp | Lehks/NostraUtils | ef1b2d492a1358775752a2a7621c714d86bf96b2 | [
"MIT"
] | 10 | 2018-01-07T01:00:11.000Z | 2021-09-16T14:08:45.000Z | NostraUtils/Nostra Utils/src/header/nostrautils/dat_alg/BinarySearch.hpp | Lehks/NostraEngine | 0d610dcd97ba482fd8f183795140c38728c3a6b3 | [
"MIT"
] | 107 | 2018-04-06T10:15:47.000Z | 2018-09-28T07:13:46.000Z | NostraUtils/Nostra Utils/src/header/nostrautils/dat_alg/BinarySearch.hpp | Lehks/NostraEngine | 0d610dcd97ba482fd8f183795140c38728c3a6b3 | [
"MIT"
] | null | null | null | #ifndef NOU_DAT_ALG_BINARY_SEARCH_HPP
#define NOU_DAT_ALG_BINARY_SEARCH_HPP
#include "nostrautils/dat_alg/Vector.hpp"
/**
\file dat_alg/BinarySearch.hpp
\author Lukas Gross
\since 1.0.0
\version 1.0.0
\brief This file provides a binary search algorithm.
*/
namespace NOU::NOU_DAT_ALG
{
/**
\tparam T The type of the array.
\param vec A pointer to the array.
\param key A reference to the value, you want to search for.
\param start The start index of your search.
\param end The end index of your search.
\param insertionIndex A pointer to the index of the array where a new value would be inserted to stay
in a sorted order.
\return -1 if the object was not found or the index of the object if it was found.
\brief Makes a binary search for the key in a passed array.
*/
template<typename T>
int64 binarySearch
(const T *vec, const T &key, int64 start, int64 end, int64 *insertionIndex = nullptr);
/**
\tparam T The type of the array.
\param vec A reference to a nostra::utils::dat_alg::Vector.
\param key A reference to the value, you want to search for.
\param start The start index of your search.
\param end The end index of your search. If the parameter is -1 the binarySearch() will
be called with end set to vec.size() - 1.
\param insertionIndex A pointer to the index of the array where a new value would be inserted to stay in
a sorted order.
\return -1 if the object was not found or the index of the object if it was found.
\brief Makes a binary search for the key in a passed array.
\details Performs a binary search for the nostra::utils::dat_alg::Vector.
*/
template<typename T>
int64 binarySearch(const NOU::NOU_DAT_ALG::Vector<T> &vec, const T &key,
int64 start = 0, int64 end = -1, int64 *insertionIndex = nullptr);
template<typename T>
int64 binarySearch(const T *vec, const T &key,
int64 start, int64 end, int64 *insertionIndex)
{
if (start > end)
{
if (insertionIndex != nullptr)
*insertionIndex = start;
return -1;
}
const int64 middle = start + ((end - start) / 2);
if (vec[middle] == key)
{
return middle;
}
else if (vec[middle] > key)
{
return binarySearch(vec, key, start, middle - 1, insertionIndex);
}
return binarySearch(vec, key, middle + 1, end, insertionIndex);
}
template<typename T>
int64 binarySearch(const NOU::NOU_DAT_ALG::Vector<T> &vec, const T &key,
int64 start, int64 end, int64 *insertionIndex)
{
return binarySearch(vec.data(), key, start, (end == -1) ? vec.size() - 1 : end, insertionIndex);
}
}
#endif | 30.44186 | 105 | 0.692513 | [
"object",
"vector"
] |
ee9748ceae0fcccf0c62e5db3b332026583fe302 | 1,356 | hpp | C++ | libs/boost_1_72_0/tools/quickbook/src/quickbook.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | libs/boost_1_72_0/tools/quickbook/src/quickbook.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | libs/boost_1_72_0/tools/quickbook/src/quickbook.hpp | henrywarhurst/matrix | 317a2a7c35c1c7e3730986668ad2270dc19809ef | [
"BSD-3-Clause"
] | null | null | null | /*=============================================================================
Copyright (c) 2009 Daniel James
Copyright (c) 2002 2004 2006 Joel de Guzman
Copyright (c) 2004 Eric Niebler
http://spirit.sourceforge.net/
Use, modification and distribution is subject to the Boost Software
License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#if !defined(BOOST_SPIRIT_QUICKBOOK_QUICKBOOK_HPP)
#define BOOST_SPIRIT_QUICKBOOK_QUICKBOOK_HPP
#include "fwd.hpp"
#include "values.hpp"
#include <boost/filesystem/path.hpp>
#include <string>
#include <time.h>
#include <vector>
namespace quickbook {
namespace fs = boost::filesystem;
extern tm *current_time; // the current time
extern tm *current_gm_time; // the current UTC time
extern bool debug_mode;
extern bool self_linked_headers;
extern std::vector<fs::path> include_path;
extern std::vector<std::string> preset_defines;
extern fs::path image_location;
void parse_file(quickbook::state &state, value include_doc_id = value(),
bool nested_file = false);
// Some initialisation methods
//
// Declared here to avoid including other headers
namespace detail {
void initialise_markups();
}
} // namespace quickbook
#endif
| 30.818182 | 79 | 0.663717 | [
"vector"
] |
ee97bfcfc99eeec19d3956b33151af3d4db195e1 | 3,679 | ipp | C++ | include/dens/df.ipp | riturajkaushik/stats | 4f0bb60f3dde4acd3a860ecf03a34924223a0d2b | [
"Apache-2.0"
] | null | null | null | include/dens/df.ipp | riturajkaushik/stats | 4f0bb60f3dde4acd3a860ecf03a34924223a0d2b | [
"Apache-2.0"
] | null | null | null | include/dens/df.ipp | riturajkaushik/stats | 4f0bb60f3dde4acd3a860ecf03a34924223a0d2b | [
"Apache-2.0"
] | null | null | null | /*################################################################################
##
## Copyright (C) 2011-2018 Keith O'Hara
##
## This file is part of the StatsLib C++ library.
##
## 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.
##
################################################################################*/
/*
* pdf of the F distribution
*/
//
// single input
template<typename T>
statslib_constexpr
T
df_int_adj(const T x, const T ratio_abx)
{
return ( ratio_abx * (T(1) - x*ratio_abx) );
}
template<typename T>
statslib_constexpr
T
df_int(const T x, const T a_par, const T b_par, const T abx, const bool log_form)
{
return ( log_form == true ? \
// if
dbeta(abx/(T(1)+abx),a_par,b_par,true) + stmath::log(df_int_adj(x,(a_par/b_par)/(T(1) + abx))) :
// else
dbeta(abx/(T(1)+abx),a_par,b_par,false) * df_int_adj(x,(a_par/b_par)/(T(1) + abx)) );
}
template<typename T>
statslib_constexpr
T
df_check(const T x, const T df1_par, const T df2_par, const bool log_form)
{
return df_int(x,df1_par/T(2),df2_par/T(2),df1_par*x/df2_par,log_form);
}
template<typename Ta, typename Tb>
statslib_constexpr
return_t<Ta>
df(const Ta x, const Tb df1_par, const Tb df2_par, const bool log_form)
{
return df_check<return_t<Ta>>(x,df1_par,df2_par,log_form);
}
//
// matrix/vector input
template<typename Ta, typename Tb, typename Tc>
statslib_inline
void
df_int(const Ta* __stats_pointer_settings__ vals_in, const Tb df1_par, const Tb df2_par, const bool log_form,
Tc* __stats_pointer_settings__ vals_out, const uint_t num_elem)
{
#ifdef STATS_USE_OPENMP
#pragma omp parallel for
#endif
for (uint_t j=0U; j < num_elem; j++)
{
vals_out[j] = df(vals_in[j],df1_par,df2_par,log_form);
}
}
#ifdef STATS_USE_ARMA
template<typename Ta, typename Tb, typename Tc>
statslib_inline
ArmaMat<Tc>
df(const ArmaMat<Ta>& X, const Tb df1_par, const Tb df2_par, const bool log_form)
{
ArmaMat<Tc> mat_out(X.n_rows,X.n_cols);
df_int<Ta,Tb,Tc>(X.memptr(),df1_par,df2_par,log_form,mat_out.memptr(),mat_out.n_elem);
return mat_out;
}
template<typename mT, typename tT, typename Tb>
statslib_inline
mT
df(const ArmaGen<mT,tT>& X, const Tb df1_par, const Tb df2_par, const bool log_form)
{
return df(X.eval(),df1_par,df2_par,log_form);
}
#endif
#ifdef STATS_USE_BLAZE
template<typename Ta, typename Tb, typename Tc, bool To>
statslib_inline
BlazeMat<Tc,To>
df(const BlazeMat<Ta,To>& X, const Tb df1_par, const Tb df2_par, const bool log_form)
{
BlazeMat<Tc,To> mat_out(X.rows(),X.columns());
df_int<Ta,Tb,Tc>(X.data(),df1_par,df2_par,log_form,mat_out.data(),X.rows()*X.spacing());
return mat_out;
}
#endif
#ifdef STATS_USE_EIGEN
template<typename Ta, typename Tb, typename Tc, int iTr, int iTc>
statslib_inline
EigMat<Tc,iTr,iTc>
df(const EigMat<Ta,iTr,iTc>& X, const Tb df1_par, const Tb df2_par, const bool log_form)
{
EigMat<Tc,iTr,iTc> mat_out(X.rows(),X.cols());
df_int<Ta,Tb,Tc>(X.data(),df1_par,df2_par,log_form,mat_out.data(),mat_out.size());
return mat_out;
}
#endif
| 28.083969 | 113 | 0.661865 | [
"vector"
] |
ee9806f14e726f4023849441a5b8b3bd71709287 | 3,152 | cpp | C++ | 0641-Design Circular Deque/0641-Design Circular Deque.cpp | zhuangli1987/LeetCode-1 | e81788abf9e95e575140f32a58fe983abc97fa4a | [
"MIT"
] | 49 | 2018-05-05T02:53:10.000Z | 2022-03-30T12:08:09.000Z | 0601-0700/0641-Design Circular Deque/0641-Design Circular Deque.cpp | jolly-fellow/LeetCode | ab20b3ec137ed05fad1edda1c30db04ab355486f | [
"MIT"
] | 11 | 2017-12-15T22:31:44.000Z | 2020-10-02T12:42:49.000Z | 0601-0700/0641-Design Circular Deque/0641-Design Circular Deque.cpp | jolly-fellow/LeetCode | ab20b3ec137ed05fad1edda1c30db04ab355486f | [
"MIT"
] | 28 | 2017-12-05T10:56:51.000Z | 2022-01-26T18:18:27.000Z | class MyCircularDeque {
public:
/** Initialize your data structure here. Set the size of the deque to be k. */
MyCircularDeque(int k) {
head = nullptr;
tail = nullptr;
sz = k;
len = 0;
}
/** Adds an item at the front of Deque. Return true if the operation is successful. */
bool insertFront(int value) {
if (isFull()) {
return false;
}
Node* node = new Node(value);
node->next = head;
if (head) {
head->prev = node;
}
else {
tail = node;
}
head = node;
++len;
return true;
}
/** Adds an item at the rear of Deque. Return true if the operation is successful. */
bool insertLast(int value) {
if (isFull()) {
return false;
}
Node* node = new Node(value);
if (isEmpty()) {
head = node;
}
else {
tail->next = node;
node->prev = tail;
}
tail = node;
++len;
return true;
}
/** Deletes an item from the front of Deque. Return true if the operation is successful. */
bool deleteFront() {
if (isEmpty()) {
return false;
}
Node* node = head;
head = node->next;
if (len == 1) {
tail = nullptr;
}
else {
head->prev = nullptr;
}
--len;
delete node;
return true;
}
/** Deletes an item from the rear of Deque. Return true if the operation is successful. */
bool deleteLast() {
if (isEmpty()) {
return false;
}
Node* node = tail;
tail = node->prev;
if (len == 1) {
head = nullptr;
}
else {
tail->next = nullptr;
}
--len;
delete node;
return true;
}
/** Get the front item from the deque. */
int getFront() {
if (isEmpty()) {
return -1;
}
return head->val;
}
/** Get the last item from the deque. */
int getRear() {
if (isEmpty()) {
return -1;
}
return tail->val;
}
/** Checks whether the circular deque is empty or not. */
bool isEmpty() {
return len == 0;
}
/** Checks whether the circular deque is full or not. */
bool isFull() {
return len == sz;
}
private:
struct Node {
int val;
Node *prev, *next;
Node(int v): val(v), prev(nullptr), next(nullptr) {}
};
Node *head, *tail;
int sz, len;
};
/**
* Your MyCircularDeque object will be instantiated and called as such:
* MyCircularDeque obj = new MyCircularDeque(k);
* bool param_1 = obj.insertFront(value);
* bool param_2 = obj.insertLast(value);
* bool param_3 = obj.deleteFront();
* bool param_4 = obj.deleteLast();
* int param_5 = obj.getFront();
* int param_6 = obj.getRear();
* bool param_7 = obj.isEmpty();
* bool param_8 = obj.isFull();
*/
| 23.699248 | 95 | 0.477792 | [
"object"
] |
ee98155cdf320b20265e0031b207c736c5ab34d6 | 1,849 | cpp | C++ | leetcode/stone-game-ii.cpp | amsubhash/competitive-programming | 02c801c631d5a830e9a4c41914091c3ac7eaf39e | [
"MIT"
] | null | null | null | leetcode/stone-game-ii.cpp | amsubhash/competitive-programming | 02c801c631d5a830e9a4c41914091c3ac7eaf39e | [
"MIT"
] | null | null | null | leetcode/stone-game-ii.cpp | amsubhash/competitive-programming | 02c801c631d5a830e9a4c41914091c3ac7eaf39e | [
"MIT"
] | null | null | null | #include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <list>
#include <map>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#define assertm(exp, msg) \
cout << "testing: " << msg << endl; \
assert(exp); \
cout << "passed" << endl;
#define M_PILES 105
#define MAX 105
#define INF -1000000
using namespace std;
class Solution {
public:
int best(vector<int> &p, int dp[MAX][M_PILES], int N, int M, int x) {
if (x >= N) {
return 0;
}
int i, result, sum;
int max_ = INF;
if (dp[M][x] > INF) {
return dp[M][x];
}
sum = p[x];
for (i = 1; i <= M * 2 && x + i <= N; i++) {
result = sum - best(p, dp, N, max(M, i), x + i);
if (max_ < result) {
max_ = result;
}
sum += p[x + i];
}
dp[M][x] = max_;
return dp[M][x];
};
int stoneGameII(vector<int> &piles) {
int dp[MAX][M_PILES];
int i, j;
for (i = 0; i < MAX; i++)
for (j = 0; j < MAX; j++)
dp[i][j] = INF;
int a = best(piles, dp, piles.size(), 1, 0);
int total = 0;
for (i = 0; i < piles.size(); i++) {
total += piles[i];
}
return (total + a) / 2;
}
};
int main() {
Solution sol = Solution();
struct testCase {
vector<int> input;
int result;
};
testCase t[] = {{{2, 7, 9, 4, 4}, 10},
{{2, 7, 9, 4, 49, 4, 5, 2, 1, 90}, 107},
{{1, 2, 3, 4, 5, 100}, 104}};
cout << "Testing ......\n";
for (testCase tc : t) {
double ress = sol.stoneGameII(tc.input);
assertm(ress == tc.result, ress)
}
cout << endl;
}
| 21.752941 | 80 | 0.457545 | [
"vector"
] |
ee9c336021ca29443a3704dd87c7eb345038d82d | 7,785 | cpp | C++ | source/adios2/toolkit/transportman/wanman/WANMan.cpp | philip-davis/ADIOS2 | e0195f731c12bb2a231faca22a719134ad6bb272 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | source/adios2/toolkit/transportman/wanman/WANMan.cpp | philip-davis/ADIOS2 | e0195f731c12bb2a231faca22a719134ad6bb272 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2020-01-15T15:07:21.000Z | 2020-01-15T15:07:21.000Z | source/adios2/toolkit/transportman/wanman/WANMan.cpp | philip-davis/ADIOS2 | e0195f731c12bb2a231faca22a719134ad6bb272 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* WANMan.cpp
*
* Created on: Jun 1, 2017
* Author: Jason Wang wangr1@ornl.gov
*/
#include <fstream> //TODO go away
#include <iostream> //TODO go away
#include "WANMan.h"
#include "adios2/ADIOSMacros.h"
#include "adios2/helper/adiosFunctions.h"
#ifdef ADIOS2_HAVE_ZEROMQ
#include "adios2/toolkit/transport/socket/SocketZmqPubSub.h"
#endif
namespace adios2
{
namespace transportman
{
WANMan::WANMan(MPI_Comm mpiComm, const bool debugMode)
: m_MpiComm(mpiComm), m_DebugMode(debugMode)
{
}
WANMan::~WANMan()
{
auto start_time = std::chrono::system_clock::now();
while (true)
{
int s = 0;
m_Mutex.lock();
for (const auto &i : m_BufferQueue)
{
if (i.size() != 0)
{
++s;
}
}
m_Mutex.unlock();
if (s == 0)
{
break;
}
auto now_time = std::chrono::system_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::seconds>(
now_time - start_time);
if (duration.count() > m_Timeout)
{
break;
}
// add a sleep here because this loop is occupying the buffer queue
// lock, and this sleep would make time for reader or writer thread and
// help it finish sooner.
std::this_thread::sleep_for(std::chrono::microseconds(1));
}
for (auto &readThread : m_ReadThreads)
{
m_Reading = false;
readThread.join();
}
for (auto &writeThread : m_WriteThreads)
{
m_Writing = false;
writeThread.join();
}
}
void WANMan::SetMaxReceiveBuffer(size_t size) { m_MaxReceiveBuffer = size; }
void WANMan::OpenTransports(const std::vector<Params> ¶msVector,
const Mode mode, const std::string &workflowMode,
const bool profile)
{
m_TransportsParameters = paramsVector;
m_BufferQueue.resize(paramsVector.size());
for (size_t i = 0; i < paramsVector.size(); ++i)
{
// Get parameters
std::string library;
GetStringParameter(paramsVector[i], "Library", library);
std::string ip;
GetStringParameter(paramsVector[i], "IPAddress", ip);
std::string port;
GetStringParameter(paramsVector[i], "Port", port);
GetIntParameter(paramsVector[i], "Timeout", m_Timeout);
std::string name;
GetStringParameter(paramsVector[i], "Name", name);
// Calculate port number
int mpiRank, mpiSize;
MPI_Comm_rank(m_MpiComm, &mpiRank);
MPI_Comm_size(m_MpiComm, &mpiSize);
if (port.empty())
{
port = std::to_string(stoi(port) + i * mpiSize);
}
port = std::to_string(stoi(port) + mpiRank);
if (library == "zmq" || library == "ZMQ")
{
#ifdef ADIOS2_HAVE_ZEROMQ
std::shared_ptr<transport::SocketZmq> wanTransport;
wanTransport =
std::make_shared<transport::SocketZmqPubSub>(m_Timeout);
std::string fullIP = "tcp://" + ip + ":" + port;
wanTransport->Open(fullIP, mode);
m_Transports.emplace(i, wanTransport);
// launch thread
if (mode == Mode::Read)
{
m_Reading = true;
m_ReadThreads.emplace_back(
std::thread(&WANMan::ReadThread, this, wanTransport));
}
else if (mode == Mode::Write)
{
m_Writing = true;
m_WriteThreads.emplace_back(
std::thread(&WANMan::WriteThread, this, wanTransport, i));
}
#else
throw std::invalid_argument(
"ERROR: this version of ADIOS2 didn't compile with "
"ZMQ library, in call to Open\n");
#endif
}
else
{
if (m_DebugMode)
{
throw std::invalid_argument("ERROR: wan transport " + library +
" not supported or not "
"provided in IO AddTransport, "
"in call to Open\n");
}
}
}
}
void WANMan::Write(std::shared_ptr<std::vector<char>> buffer, size_t id)
{
PushBufferQueue(buffer, id);
}
void WANMan::Write(const std::vector<char> &buffer, size_t transportId)
{
if (transportId >= m_Transports.size())
{
throw std::runtime_error(
"ERROR: No valid transports found, from WANMan::WriteSocket()");
}
m_Transports[transportId]->Write(buffer.data(), buffer.size());
}
std::shared_ptr<std::vector<char>> WANMan::Read(size_t id)
{
return PopBufferQueue(id);
}
void WANMan::PushBufferQueue(std::shared_ptr<std::vector<char>> v, size_t id)
{
std::lock_guard<std::mutex> l(m_Mutex);
m_BufferQueue[id].push(v);
}
std::shared_ptr<std::vector<char>> WANMan::PopBufferQueue(size_t id)
{
std::lock_guard<std::mutex> l(m_Mutex);
if (m_BufferQueue[id].size() > 0)
{
std::shared_ptr<std::vector<char>> vec = m_BufferQueue[id].front();
m_BufferQueue[id].pop();
return vec;
}
return nullptr;
}
void WANMan::WriteThread(std::shared_ptr<transport::SocketZmq> transport,
size_t id)
{
while (m_Writing)
{
std::shared_ptr<std::vector<char>> buffer = PopBufferQueue(id);
if (buffer != nullptr)
{
if (buffer->size() > 0)
{
transport->Write(buffer->data(), buffer->size());
}
}
}
}
void WANMan::ReadThread(std::shared_ptr<transport::SocketZmq> transport)
{
std::vector<char> buffer(m_MaxReceiveBuffer);
while (m_Reading)
{
int ret = transport->Read(buffer.data(), m_MaxReceiveBuffer);
if (ret > 0)
{
std::shared_ptr<std::vector<char>> bufferQ =
std::make_shared<std::vector<char>>(ret);
std::memcpy(bufferQ->data(), buffer.data(), ret);
PushBufferQueue(bufferQ, 0);
}
}
}
bool WANMan::GetBoolParameter(const Params ¶ms, const std::string &key)
{
auto itKey = params.find(key);
if (itKey != params.end())
{
std::string value = itKey->second;
std::transform(value.begin(), value.end(), value.begin(), ::tolower);
if (value == "yes" || value == "true")
{
return true;
}
else if (value == "no" || value == "false")
{
return false;
}
}
return false;
}
bool WANMan::GetStringParameter(const Params ¶ms, const std::string &key,
std::string &value)
{
auto it = params.find(key);
if (it != params.end())
{
value = it->second;
return true;
}
return false;
}
bool WANMan::GetIntParameter(const Params ¶ms, const std::string &key,
int &value)
{
auto it = params.find(key);
if (it != params.end())
{
try
{
value = std::stoi(it->second);
return true;
}
catch (std::exception &e)
{
std::cout << "Parameter " << key
<< " should be an integer in string format. However, "
<< e.what()
<< " has been caught while trying to convert "
"the value to an integer."
<< std::endl;
return false;
}
}
return false;
}
} // end namespace transportman
} // end namespace adios2
| 27.803571 | 79 | 0.543224 | [
"vector",
"transform"
] |
eea27feeff1f1749e441aca5b42065c185b7ddc0 | 2,568 | hpp | C++ | src/parse.hpp | icmccorm/cadical | bc0e4c5b22faad831cd7ffb8aebe2d6ccf6a2c74 | [
"MIT"
] | null | null | null | src/parse.hpp | icmccorm/cadical | bc0e4c5b22faad831cd7ffb8aebe2d6ccf6a2c74 | [
"MIT"
] | null | null | null | src/parse.hpp | icmccorm/cadical | bc0e4c5b22faad831cd7ffb8aebe2d6ccf6a2c74 | [
"MIT"
] | null | null | null | #ifndef _parse_hpp_INCLUDED
#define _parse_hpp_INCLUDED
#include <cassert>
#include <vector>
namespace CaDiCaL {
// Factors out common functions for parsing of DIMACS and solution files.
class File;
struct External;
struct Internal;
class Parser {
Solver * solver;
Internal * internal;
External * external;
File * file;
void perr (const char * fmt, ...)
CADICAL_ATTRIBUTE_FORMAT (2, 3);
int parse_char ();
enum {
FORCED = 0, // Force reading even if header is broken.
RELAXED = 1, // Relaxed white space treatment in header.
STRICT = 2, // Strict white space and header compliance.
};
const char * parse_string (const char * str, char prev);
const char * parse_positive_int (int & ch, int & res, const char * name);
const char * parse_lit (int & ch, int & lit, int & vars, int strict);
const char * parse_dimacs_non_profiled (int & vars, int strict);
const char * parse_solution_non_profiled ();
bool * parse_inccnf_too;
vector<int> * cubes;
public:
// Parse a DIMACS CNF or ICNF file.
//
// Return zero if successful. Otherwise parse error.
Parser(Solver *s, File *f, bool *i, vector<int> *c) :
solver(s), internal(s->internal), external(s->external), file(f),
parse_inccnf_too (i), cubes (c)
{}
// Parse a DIMACS file. Return zero if successful. Otherwise a parse
// error is return. The parsed clauses are added to the solver and the
// maximum variable index found is returned in the 'vars' argument. The
// 'strict' argument can be '0' in which case the numbers in the header
// can be arbitrary, e.g., 'p cnf 0 0' all the time, without producing a
// parse error. Only for this setting the parsed literals are not checked
// to overflow the maximum variable index of the header. The strictest
// form of parsing is enforced for the value '2' of 'strict', in which
// case the header can not have additional white space, while a value of
// '1' exactly relaxes this, e.g., 'p cnf \t 1 3 \r\n' becomes legal.
//
const char * parse_dimacs (int & vars, int strict);
// Parse a solution file as used in the SAT competition, e.g., with
// comment lines 'c ...', a status line 's ...' and value lines 'v ...'.
// Returns zero if successful. Otherwise a string is returned describing
// the parse error. The parsed solution is saved in 'solution' and can be
// accessed with 'sol (int lit)'. We use it for checking learned clauses.
//
const char * parse_solution ();
const char * parse_aux ();
};
}
#endif
| 33.350649 | 76 | 0.674455 | [
"vector"
] |
eea33a68a10ecfb596022103bd761b5bbf518216 | 16,807 | cpp | C++ | BOT PROGRAMMING - Legend League/Coders_Strike_Back.cpp | Thomaw/CodeinGame | 185164f6dbad7c9f8bcf622d56ea8b8ef677fad6 | [
"MIT"
] | 1 | 2021-09-19T16:45:08.000Z | 2021-09-19T16:45:08.000Z | BOT PROGRAMMING - Legend League/Coders_Strike_Back.cpp | Thomaw/CodeinGame | 185164f6dbad7c9f8bcf622d56ea8b8ef677fad6 | [
"MIT"
] | null | null | null | BOT PROGRAMMING - Legend League/Coders_Strike_Back.cpp | Thomaw/CodeinGame | 185164f6dbad7c9f8bcf622d56ea8b8ef677fad6 | [
"MIT"
] | null | null | null | #pragma GCC optimize("Ofast")
#pragma GCC optimize("inline")
#pragma GCC optimize("omit-frame-pointer")
#pragma GCC optimize("unroll-loops")
#include "stdio.h"
#include "math.h"
#include <iostream>
#include <algorithm>
#include <memory>
#include <chrono>
#include <vector>
using namespace std;
using namespace std::chrono;
high_resolution_clock::time_point now = high_resolution_clock::now();
#define TIME duration_cast<duration<double>>(high_resolution_clock::now() - now).count()
class Point;
class Unit;
class Pod;
class Collision;
class Checkpoint;
class Solution;
class Bot;
void load();
void play();
void print_move(int, float, Pod*);
constexpr int CP = 0;
constexpr int POD = 1;
constexpr int DEPTH = 6;
constexpr float SHIELD_PROB = 10;
constexpr int MAX_THRUST = 100;
constexpr float E = 0.00001;
int r = -1;
int turn = 0;
int sols_ct = 0;
bool is_p2 = false;
int cp_ct, laps;
Pod* pods[4];
Checkpoint* cps[10];
inline int fastrand() {
static unsigned int g_seed = 42;
g_seed = (214013*g_seed+2531011);
return (g_seed>>16)&0x7FFF;
}
inline int rnd(int b) {
return fastrand() % b;
}
inline int rnd(int a, int b) {
return a + rnd(b - a + 1);
}
class Collision {
public:
Unit* a;
Unit* b;
float t;
Collision() {}
Collision(Unit* a, Unit* b, float t) {
this->a = a;
this->b = b;
this->t = t;
}
};
class Point {
public:
float x, y;
Point() {};
Point(float x, float y) {
this->x = x;
this->y = y;
}
inline virtual float dist(Point p) {
return sqrt(pow((x - p.x), 2) + pow((y - p.y), 2));
}
inline virtual float dist(Point* p) {
return sqrt(dist2(p));
}
inline virtual float dist2(Point* p) {
return pow((x - p->x), 2) + pow((y - p->y), 2);
}
Point closest(Point* a, Point* b) {
float da = b->y - a->y;
float db = a->x - b->x;
float c1 = da*a->x + db*a->y;
float c2 = -db*x + da*y;
float det = da*da + db*db;
float cx, cy;
if (det != 0) {
cx = (da*c1 - db*c2) / det;
cy = (da*c2 + db*c1) / det;
} else {
cx = x, cy = y;
}
return Point(cx, cy);
}
};
class Unit: public Point {
private:
float cache[5];
public:
int id, type;
float r, vx, vy;
virtual void bounce(Unit* u) {};
inline float collision_time(Unit* u) {
if (vx == u->vx && vy == u->vy) {
return -1;
}
float sr2 = u->type == CP ? 357604 : 640000;
float dx = x - u->x;
float dy = y - u->y;
float dvx = vx - u->vx;
float dvy = vy - u->vy;
float a = dvx*dvx + dvy*dvy;
if (a < E) return -1;
float b = -2.0*(dx*dvx + dy*dvy);
float delta = b*b - 4.0*a*(dx*dx + dy*dy - sr2);
if (delta < 0.0) return -1;
float t = (b - sqrt(delta))*(1.0/(2.0*a));
if (t <= 0.0 || t > 1.0) return -1;
return t;
}
void save() {
cache[0] = x;
cache[1] = y;
cache[2] = vx;
cache[3] = vy;
}
void load() {
x = cache[0];
y = cache[1];
vx = cache[2];
vy = cache[3];
}
};
class Checkpoint: public Unit {
public:
Checkpoint(int id, float x, float y) {
this->id = id;
this->x = x;
this->y = y;
this->vx = this->vy = 0;
this->type = CP;
this->r = 600;
}
void bounce(Unit*) {}
};
class Pod: public Unit {
public:
float angle = -1;
float next_angle = -1;
bool has_boost;
int ncpid, checked, timeout, shield;
Pod* partner;
// TODO maybe replace cache array with primitives?
float cache[10];
Pod(int id) {
this->id = id;
this->r = 400;
this->type = POD;
this->ncpid = 1;
// TODO move timeout to global/team var
this->timeout = 100;
this->has_boost = true;
this->checked = this->shield = 0;
}
float score() {
return checked*50000 - this->dist(cps[this->ncpid]);
}
void apply(int thrust, float angle) {
angle = max((float)-18., min((float)18., angle));
this->angle += angle;
if (this->angle >= 360.) {
this->angle = this->angle - 360.;
} else if (this->angle < 0.0) {
this->angle += 360.;
}
if (thrust == -1) {
this->shield = 4;
} else {
boost(thrust);
}
}
void rotate(Point* p) {
float a = diff_angle(p);
a = max((float)-18., min((float)18., a));
angle += a;
if (angle >= 360.) {
angle = angle - 360.;
} else if (angle < 0.0) {
angle += 360.;
}
}
void boost(int thrust) {
if (shield > 0) return;
float ra = angle * M_PI / 180.0;
vx += cos(ra) * thrust;
vy += sin(ra) * thrust;
}
void move(float t) {
x += vx * t;
y += vy * t;
}
void end() {
x = round(x);
y = round(y);
vx = trunc(vx * 0.85);
vy = trunc(vy * 0.85);
if (checked >= cp_ct * laps) {
ncpid = 0;
checked = cp_ct * laps;
}
timeout--;
if (shield > 0) shield--;
}
void bounce(Unit* u) {
if (u->type == CP) {
checked += 1;
timeout = partner->timeout = 100;
ncpid = (ncpid + 1) % cp_ct;
return;
}
bounce_w_pod(static_cast<Pod*>(u));
}
void bounce_w_pod(Pod* u) {
float m1 = shield == 4 ? 10. : 1.;
float m2 = u->shield == 4 ? 10. : 1.;
float mcoeff = (m1 + m2) / (m1 * m2);
float nx = x - u->x;
float ny = y - u->y;
float dst2 = nx*nx + ny*ny;
float dvx = vx - u->vx;
float dvy = vy - u->vy;
float prod = (nx*dvx + ny*dvy) / (dst2 * mcoeff);
float fx = nx * prod;
float fy = ny * prod;
float m1_inv = 1.0 / m1;
float m2_inv = 1.0 / m2;
vx -= fx * m1_inv;
vy -= fy * m1_inv;
u->vx += fx * m2_inv;
u->vy += fy * m2_inv;
float impulse = sqrt(fx*fx + fy*fy);
if (impulse < 120.) {
float df = 120.0 / impulse;
fx *= df;
fy *= df;
}
vx -= fx * m1_inv;
vy -= fy * m1_inv;
u->vx += fx * m2_inv;
u->vy += fy * m2_inv;
}
inline float diff_angle(Point* p) {
float a = get_angle(p);
float right = angle <= a ? a - angle : 360. - angle + a;
float left = angle >= a ? angle - a : angle + 360. - a;
if (right < left) {
return right;
}
return -left;
}
inline float get_angle(Point* p) {
float d = this->dist(p);
float dx = (p->x - x) / d;
float dy = (p->y - y) / d;
float a = acos(dx) * 180 / M_PI;
if (dy < 0) {
a = 360 - a;
}
return a;
}
void update(int x, int y, int vx, int vy, float angle, int ncpid) {
if (shield > 0) shield--;
if (ncpid != this->ncpid) {
timeout = partner->timeout = 100;
checked++;
} else {
timeout--;
}
this->x = x;
this->y = y;
this->vx = vx;
this->vy = vy;
this->ncpid = ncpid;
if (is_p2 && id > 1) swap(angle, this->next_angle);
this->angle = angle;
if (::r == 0) this->angle = 1 + diff_angle(cps[1]);
save();
}
void update(int shield, bool has_boost) {
this->shield = shield;
this->has_boost = has_boost;
}
void save() {
Unit::save();
cache[0] = ncpid;
cache[1] = checked;
cache[2] = timeout;
cache[3] = shield;
cache[4] = angle;
cache[5] = has_boost;
}
void load() {
Unit::load();
ncpid = cache[0];
checked = cache[1];
timeout = cache[2];
shield = cache[3];
angle = cache[4];
has_boost = cache[5];
}
};
class Solution {
public:
float score = -1;
int thrusts[DEPTH*2];
float angles[DEPTH*2];
Solution(bool with_rnd = false) {
if (with_rnd) randomize();
}
void shift() {
for (int i = 1; i < DEPTH; i++) {
angles[i-1] = angles[i];
thrusts[i-1] = thrusts[i];
angles[i-1+DEPTH] = angles[i+DEPTH];
thrusts[i-1+DEPTH] = thrusts[i+DEPTH];
}
randomize(DEPTH-1, true);
randomize(2*DEPTH-1, true);
score = -1;
}
void mutate() {
randomize(rnd(2*DEPTH));
}
void mutate(Solution* child) {
copy(begin(angles), end(angles), begin(child->angles));
copy(begin(thrusts), end(thrusts), begin(child->thrusts));
child->mutate();
child->score = -1;
}
void randomize(int idx, bool full = false) {
int r = rnd(2);
if (full || r == 0) angles[idx] = max(-18, min(18, rnd(-40, 40)));
if (full || r == 1) {
if (rnd(100) >= SHIELD_PROB) {
thrusts[idx] = max(0, min(MAX_THRUST, rnd((int) -0.5*MAX_THRUST, 2*MAX_THRUST)));
} else {
thrusts[idx] = -1;
}
}
score = -1;
}
void randomize() {
for (int i = 0; i < 2*DEPTH; i++) randomize(i, true);
}
};
class Bot {
public:
int id = 0;
Bot() {};
Bot(int id) {
this->id = id;
}
virtual void move() = 0;
Pod* runner() {
return runner(pods[id], pods[id+1]);
}
Pod* blocker() {
return blocker(pods[id], pods[id+1]);
}
Pod* runner(Pod* pod0, Pod* pod1) {
return pod0->score() - pod1->score() >= -1000 ? pod0 : pod1;
}
Pod* blocker(Pod* pod0, Pod* pod1) {
return runner(pod0, pod1)->partner;
}
};
class ReflexBot : public Bot {
public:
ReflexBot() {}
ReflexBot(int id) {
this->id = id;
}
void move() {
move_runner();
move_blocker();
}
void move_as_main() {
move_runner(true);
move_blocker(true);
}
void move_runner(bool for_output = false) {
Pod* pod = !for_output ? runner() : pods[0];
Checkpoint* cp = cps[pod->ncpid];
Point t(cp->x - 3*pod->vx, cp->y - 3*pod->vy);
float raw_angle = pod->diff_angle(&t);
int thrust = abs(raw_angle) < 90 ? MAX_THRUST : 0;
float angle = max((float) -18, min((float) 18, raw_angle));
if (!for_output) pod->apply(thrust, angle);
else print_move(thrust, angle, pod);
}
void move_blocker(bool for_output = false) {
Pod* pod = !for_output ? blocker() : pods[1];
Checkpoint* cp = cps[pod->ncpid];
Point t(cp->x - 3*pod->vx, cp->y - 3*pod->vy);
float raw_angle = pod->diff_angle(&t);
int thrust = abs(raw_angle) < 90 ? MAX_THRUST : 0;
float angle = max((float) -18, min((float) 18, raw_angle));
if (!for_output) pod->apply(thrust, angle);
else print_move(thrust, angle, pod);
}
};
class SearchBot : public Bot {
public:
Solution sol;
vector<Bot*> oppBots;
SearchBot() {}
SearchBot(int id) {
this->id = id;
}
void move(Solution* sol) {
pods[id]->apply(sol->thrusts[turn], sol->angles[turn]);
pods[id+1]->apply(sol->thrusts[turn+DEPTH], sol->angles[turn+DEPTH]);
}
void move() {
move(&sol);
}
void solve(float time, bool with_seed = false) {
Solution best;
if (with_seed) {
best = sol;
best.shift();
} else {
best.randomize();
if (r == 0 && pods[id]->dist(cps[1]) > 4000) best.thrusts[0] = 650;
}
get_score(&best);
Solution child;
while (TIME < time) {
best.mutate(&child);
if (get_score(&child) > get_score(&best)) best = child;
}
sol = best;
}
float get_score(Solution* sol) {
if (sol->score == -1) {
vector<float> scores;
for (Bot* oppBot : oppBots) {
scores.push_back(get_bot_score(sol, oppBot));
}
sol->score = *min_element(scores.begin(), scores.end());
}
return sol->score;
}
float get_bot_score(Solution* sol, Bot* opp) {
float score = 0;
while (turn < DEPTH) {
move(sol);
opp->move();
play();
if (turn == 0) score += 0.1*evaluate();
turn++;
}
score += 0.9*evaluate();
load();
if (r > 0) sols_ct++;
return score;
}
float evaluate() {
Pod* my_runner = runner(pods[id], pods[id+1]);
Pod* my_blocker = blocker(pods[id], pods[id+1]);
Pod* opp_runner = runner(pods[(id+2) % 4], pods[(id+3) % 4]);
Pod* opp_blocker = blocker(pods[(id+2) % 4], pods[(id+3) % 4]);
float score = my_runner->score() - opp_runner->score();
// TODO maybe not a great idea? :)
score -= my_blocker->dist(my_runner);
return score;
}
};
void load() {
for (int i = 0; i < 4; i++) pods[i]->load();
turn = 0;
}
void play() {
float t = 0.0;
while (t < 1.0) {
Collision first_col = {NULL, NULL, -1};
for (int i = 0; i < 4; i++) {
for (int j = i + 1; j < 4; j++) {
float col_time = pods[i]->collision_time(pods[j]);
if (col_time > -1 && col_time + t < 1.0 && (first_col.t == -1 || col_time < first_col.t)) {
first_col.a = pods[i];
first_col.b = pods[j];
first_col.t = col_time;
}
}
// TODO this is wasteful, get rid of it
float col_time = pods[i]->collision_time(cps[pods[i]->ncpid]);
if (col_time > -1 && col_time + t < 1.0 && (first_col.t == -1 || col_time < first_col.t)) {
first_col.a = pods[i];
first_col.b = cps[pods[i]->ncpid];
first_col.t = col_time;
}
}
if (first_col.t == -1) {
for (int i = 0; i < 4; i++) {
pods[i]->move(1.0 - t);
}
t = 1.0;
} else {
for (int i = 0; i < 4; i++) {
pods[i]->move(first_col.t);
}
first_col.a->bounce(first_col.b);
t += first_col.t;
}
}
for (int i = 0; i < 4; i++) {
pods[i]->end();
}
}
void print_move(int thrust, float angle, Pod* pod) {
float a = pod->angle + angle;
if (a >= 360.0) {
a = a - 360.0;
} else if (a < 0.0) {
a += 360.0;
}
a = a * M_PI / 180.0;
float px = pod->x + cos(a) * 10000.0;
float py = pod->y + sin(a) * 10000.0;
char copyright[] = "github.com/inoryy/csb-ai-starter"; // do not remove
if (thrust == -1) {
printf("%d %d SHIELD %s\n", (int) round(px), (int) round(py), copyright);
pod->shield = 4;
} else if (thrust == 650) {
pod->has_boost = false;
printf("%d %d BOOST %s\n", (int) round(px), (int) round(py), copyright);
} else {
printf("%d %d %d %s\n", (int) round(px), (int) round(py), thrust, copyright);
}
}
int main() {
cin >> laps >> cp_ct;
for (int i = 0; i < cp_ct; i++) {
int cx, cy;
cin >> cx >> cy;
cps[i] = new Checkpoint(i, cx, cy);
}
for (int i = 0; i < 4; i++) pods[i] = new Pod(i);
pods[0]->partner = pods[1];
pods[1]->partner = pods[0];
pods[2]->partner = pods[3];
pods[3]->partner = pods[2];
ReflexBot me_reflex;
SearchBot opp(2);
opp.oppBots.push_back(&me_reflex);
SearchBot me;
me.oppBots.push_back(&opp);
while (1) {
r++;
for (int i = 0; i < 4; i++) {
int x, y, vx, vy, angle, ncpid;
cin >> x >> y >> vx >> vy >> angle >> ncpid;
if (r == 0 && i > 1 && angle > -1) is_p2 = true;
pods[i]->update(x, y, vx, vy, angle, ncpid);
}
now = high_resolution_clock::now();
float time_limit = r ? 0.142 : 0.98;
time_limit *= 0.3;
// use this to test reflex bot behavior
// me_reflex.move_as_main();
opp.solve(time_limit*0.15);
me.solve(time_limit, r > 0);
if (r > 0) cerr << "Avg iters: " << sols_ct / r << "; Avg sims: " << sols_ct*DEPTH / r << endl;
print_move(me.sol.thrusts[0], me.sol.angles[0], pods[0]);
print_move(me.sol.thrusts[DEPTH], me.sol.angles[DEPTH], pods[1]);
}
}
| 23.31068 | 107 | 0.47272 | [
"vector"
] |
eea3e7517862d3737c51ca822cb1340a4d8b3d14 | 479 | cpp | C++ | main.cpp | PengaloGit/connect-four-cpp | ba6324ef349ef0ea5a7b0a689ec4975e6f899ced | [
"MIT"
] | 3 | 2020-01-24T01:48:50.000Z | 2020-04-06T23:57:16.000Z | main.cpp | PengaloGit/connect-four-cpp | ba6324ef349ef0ea5a7b0a689ec4975e6f899ced | [
"MIT"
] | null | null | null | main.cpp | PengaloGit/connect-four-cpp | ba6324ef349ef0ea5a7b0a689ec4975e6f899ced | [
"MIT"
] | null | null | null | /*
* Connect Four
* MIT License, Copyright 2018 Loukmane Maada, Soukaina Moumou & Anas Limouri
*/
#include <iostream>
#include "Table.h"
#include "Jeu.h"
#include <vector>
#include <windows.h>
#include <mmsystem.h>
#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_audio.h>
#include <allegro5/allegro_acodec.h>
using namespace std;
int main()
{
///FreeConsole();
Jeu game;
game.commencerJeu();
}
| 19.958333 | 78 | 0.676409 | [
"vector"
] |
eea5c6e19c67d81bf0f6f98bbb66594ca7be6a5e | 7,923 | cpp | C++ | ode-0.16.1/ode/demo/demo_convex.cpp | yuemingl/ode-python-1 | a9a12d9d3b7e611874a8d30f6a5c0b83b6087f86 | [
"MIT"
] | 9 | 2020-05-31T09:22:40.000Z | 2021-09-15T18:15:15.000Z | ode-0.16.1/ode/demo/demo_convex.cpp | yuemingl/ode-python-1 | a9a12d9d3b7e611874a8d30f6a5c0b83b6087f86 | [
"MIT"
] | 1 | 2020-11-15T11:38:45.000Z | 2020-11-15T11:38:45.000Z | ode-0.16.1/ode/demo/demo_convex.cpp | yuemingl/ode-python-1 | a9a12d9d3b7e611874a8d30f6a5c0b83b6087f86 | [
"MIT"
] | 2 | 2020-11-14T21:47:01.000Z | 2021-08-03T02:28:10.000Z | /*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *
* All rights reserved. Email: russ@q12.org Web: www.q12.org *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of EITHER: *
* (1) The GNU Lesser General Public License as published by the Free *
* Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. The text of the GNU Lesser *
* General Public License is included with this library in the *
* file LICENSE.TXT. *
* (2) The BSD-style license that is included with this library in *
* the file LICENSE-BSD.TXT. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files *
* LICENSE.TXT and LICENSE-BSD.TXT for more details. *
* *
*************************************************************************/
// Convex demo.
// Serves as a test for the convex geometry.
// By Bram Stolk.
#include <assert.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#include <ode/ode.h>
#include <drawstuff/drawstuff.h>
#include "texturepath.h"
#include "halton235_geom.h"
#ifdef dDOUBLE
# define dsDrawConvex dsDrawConvexD
# define dsDrawLine dsDrawLineD
#endif
#ifdef _MSC_VER
# pragma warning(disable:4244 4305) // for VC++, no precision loss complaints
#endif
// Height at which we drop the composite block.
const dReal H=4.20;
static dWorldID world;
static dSpaceID space;
static dBodyID mbody;
static dBodyID hbody[ halton_numc ];
static dGeomID hgeom[ halton_numc ];
static dJointGroupID contactgroup;
static bool drawpos=false;
static bool solidkernel=false;
// this is called by dSpaceCollide when two objects in space are
// potentially colliding.
static void nearCallback(void *data, dGeomID o1, dGeomID o2)
{
assert(o1);
assert(o2);
if (dGeomIsSpace(o1) || dGeomIsSpace(o2))
{
// colliding a space with something
dSpaceCollide2(o1,o2,data,&nearCallback);
// Note we do not want to test intersections within a space,
// only between spaces.
return;
}
const int N = 32;
dContact contact[N];
int n = dCollide (o1,o2,N,&(contact[0].geom),sizeof(dContact));
if (n > 0)
{
for (int i=0; i<n; i++)
{
contact[i].surface.slip1 = 0.7;
contact[i].surface.slip2 = 0.7;
contact[i].surface.mode = dContactSoftERP | dContactSoftCFM | dContactApprox1 | dContactSlip1 | dContactSlip2;
contact[i].surface.mu = 500.0; // was: dInfinity
contact[i].surface.soft_erp = 0.50;
contact[i].surface.soft_cfm = 0.03;
dJointID c = dJointCreateContact (world,contactgroup,&contact[i]);
dJointAttach
(
c,
dGeomGetBody(contact[i].geom.g1),
dGeomGetBody(contact[i].geom.g2)
);
}
}
}
// start simulation - set viewpoint
static void start()
{
dAllocateODEDataForThread(dAllocateMaskAll);
static float xyz[3] = {-8,0,5};
static float hpr[3] = {0.0f,-29.5000f,0.0000f};
dsSetViewpoint (xyz,hpr);
fprintf(stderr,"Press SPACE to reset the simulation.\n");
}
static void reset()
{
dQuaternion q;
dQSetIdentity(q);
dBodySetPosition(mbody,0,0,0+H);
dBodySetQuaternion(mbody, q);
dBodySetLinearVel(mbody, 0,0,0);
dBodySetAngularVel(mbody, 0,0,0);
dBodyEnable(mbody);
for ( int i=0; i<halton_numc; ++i )
{
dBodyID body = hbody[i];
if ( !body ) continue;
dBodySetPosition(body, halton_pos[i][0], halton_pos[i][1], halton_pos[i][2]+H);
dBodySetQuaternion(body, q);
dBodySetLinearVel(body, 0,0,0);
dBodySetAngularVel(body, 0,0,0);
dBodyEnable(body);
}
}
// called when a key pressed
static void command(int cmd)
{
switch (cmd)
{
case ' ':
reset();
break;
default:
break;
}
}
static void simLoop(int pause)
{
double simstep = 1/240.0;
double dt = dsElapsedTime();
int nrofsteps = (int) ceilf(dt/simstep);
nrofsteps = nrofsteps > 8 ? 8 : nrofsteps;
for (int i=0; i<nrofsteps && !pause; i++)
{
dSpaceCollide (space,0,&nearCallback);
dWorldQuickStep (world, simstep);
dJointGroupEmpty (contactgroup);
}
dsSetColor (1,1,1);
// Draw the convex objects.
for ( int i=0; i<halton_numc; ++i )
{
dGeomID geom = hgeom[i];
dBodyID body = dGeomGetBody(geom);
//const dReal *pos = dBodyGetPosition(body);
//const dReal *rot = dBodyGetRotation(body);
const dReal *pos = dGeomGetPosition(geom);
const dReal *rot = dGeomGetRotation(geom);
dsDrawConvex
(
pos, rot,
halton_planes[i],
halton_numf[i],
halton_verts[i],
halton_numv[i],
halton_faces[i]
);
}
if (drawpos)
{
dsSetColor(1,0,0.2);
dsSetTexture(DS_NONE);
const dReal l = 0.35;
for ( int i=0; i<halton_numc; ++i )
{
dBodyID body = hbody[i];
const dReal *pos = dBodyGetPosition(body);
dReal x0[3] = { pos[0]-l, pos[1], pos[2] };
dReal x1[3] = { pos[0]+l, pos[1], pos[2] };
dReal y0[3] = { pos[0], pos[1]-l, pos[2] };
dReal y1[3] = { pos[0], pos[1]+l, pos[2] };
dReal z0[3] = { pos[0], pos[1], pos[2]-l };
dReal z1[3] = { pos[0], pos[1], pos[2]+l };
dsDrawLine(x0,x1);
dsDrawLine(y0,y1);
dsDrawLine(z0,z1);
}
}
}
int main (int argc, char **argv)
{
dMass m;
// setup pointers to drawstuff callback functions
dsFunctions fn;
fn.version = DS_VERSION;
fn.start = &start;
fn.step = &simLoop;
fn.command = &command;
fn.stop = 0;
fn.path_to_textures = DRAWSTUFF_TEXTURE_PATH;
// create world
dInitODE2(0);
world = dWorldCreate();
space = dHashSpaceCreate (0);
dHashSpaceSetLevels(space, -3, 5);
dCreatePlane(space,0,0,1,0); // Add a ground plane.
contactgroup = dJointGroupCreate (0);
dWorldSetGravity(world,0,0,-9.8);
dWorldSetQuickStepNumIterations(world, 32);
dWorldSetContactMaxCorrectingVel(world, 40);
dWorldSetMaxAngularSpeed(world, 62.8);
dWorldSetERP(world, 0.7);
dWorldSetQuickStepW(world, 0.75); // For increased stability.
dWorldSetAutoDisableFlag( world, true );
dWorldSetAutoDisableLinearThreshold( world, 0.01 );
dWorldSetAutoDisableAngularThreshold( world, 0.03 );
dWorldSetAutoDisableTime( world, 0.15f );
const float kernelrad = 0.7;
mbody = dBodyCreate(world);
dBodySetPosition(mbody, 0,0,0+H);
dMassSetSphere( &m, 5, kernelrad );
dBodySetMass( mbody, &m );
for (int i=0; i<halton_numc; ++i )
{
dGeomID geom = dCreateConvex
(
space,
halton_planes[i],
halton_numf[i],
halton_verts[i],
halton_numv[i],
halton_faces[i]
);
hgeom[i] = geom;
const dReal x = halton_pos[i][0];
const dReal y = halton_pos[i][1];
const dReal z = halton_pos[i][2];
const dReal dsqr = x*x + y*y + z*z;
if ( dsqr < kernelrad*kernelrad && solidkernel )
{
dGeomSetBody(geom, mbody);
dGeomSetOffsetPosition(geom, x,y,z);
}
else
{
dBodyID body = dBodyCreate(world);
hbody[i] = body;
dBodySetPosition(body, x,y,z+H);
dReal volu = halton_volu[i];
dReal rad = pow( volu * 3 / (4*M_PI), (1/3.0) );
dMassSetSphere( &m,5,rad );
dBodySetMass( body,&m );
#if 1
dBodySetLinearDamping (body, 0.0005);
dBodySetAngularDamping(body, 0.0300);
#endif
dGeomSetBody(geom,body);
}
}
// run simulation
const int w=1280;
const int h=720;
dsSimulationLoop (argc,argv,w,h,&fn);
dJointGroupEmpty (contactgroup);
dJointGroupDestroy (contactgroup);
dSpaceDestroy (space);
dWorldDestroy (world);
dCloseODE();
return 0;
}
| 25.724026 | 113 | 0.622491 | [
"geometry"
] |
eeae262ccc865bd02d02971d5f9e1a3c5e4d7f11 | 16,982 | cpp | C++ | src/plugins/geofence/gstgeofencebase.cpp | AIoT-IST/EVA_Show-Case | 14474d97c233b4740c8216ba6564454cd954129c | [
"MIT"
] | 4 | 2021-05-26T07:14:50.000Z | 2022-01-10T00:15:32.000Z | src/plugins/geofence/gstgeofencebase.cpp | maxpark/EVA_Show-Case | c21fdf7d81efaaf4b63b071eeaf8911791336058 | [
"MIT"
] | 2 | 2021-06-07T16:00:14.000Z | 2021-07-06T13:35:38.000Z | src/plugins/geofence/gstgeofencebase.cpp | maxpark/EVA_Show-Case | c21fdf7d81efaaf4b63b071eeaf8911791336058 | [
"MIT"
] | 3 | 2021-08-19T02:27:59.000Z | 2022-01-10T07:40:22.000Z | #ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <gst/gst.h>
#include <gst/video/video.h>
#include <gst/video/gstvideofilter.h>
#include "gstgeofencebase.h"
#include <chrono>
#include <iostream>
#include <fstream>
#include <regex>
#include <string>
#include <vector>
#include "gstadmeta.h"
#include "utils.h"
////#define DEFAULT_ALERT_TYPE "BreakIn"
GST_DEBUG_CATEGORY_STATIC (gst_geofencebase_debug_category);
#define GST_CAT_DEFAULT gst_geofencebase_debug_category
static void gst_geofencebase_set_property (GObject * object, guint property_id, const GValue * value, GParamSpec * pspec);
static void gst_geofencebase_get_property (GObject * object, guint property_id, GValue * value, GParamSpec * pspec);
static void gst_geofencebase_dispose (GObject * object);
static void gst_geofencebase_finalize (GObject * object);
static gboolean gst_geofencebase_start (GstBaseTransform * trans);
static gboolean gst_geofencebase_stop (GstBaseTransform * trans);
static gboolean gst_geofencebase_set_info (GstVideoFilter * filter, GstCaps * incaps, GstVideoInfo * in_info, GstCaps * outcaps, GstVideoInfo * out_info);
//static GstFlowReturn gst_geofencebase_transform_frame (GstVideoFilter * filter, GstVideoFrame * inframe, GstVideoFrame * outframe);
static GstFlowReturn gst_geofencebase_transform_frame_ip (GstVideoFilter * filter, GstVideoFrame * frame);
static void mapGstVideoFrame2OpenCVMat(GstGeofencebase *geofencebase, GstVideoFrame *frame, GstMapInfo &info);
static void getDetectedPerson(GstGeofencebase *geofencebase, GstBuffer* buffer);
static void doAlgorithm(GstGeofencebase *geofencebase, GstBuffer* buffer);
static void drawAlertArea(GstGeofencebase *geofencebase);
struct _GstGeoFenceBasePrivate
{
std::string alert_definition_path;
std::vector<std::vector<double>> ratio_vec;
std::vector<cv::Point> area_point_vec;
std::vector<std::vector<cv::Point>> person_vec;
bool area_display;
bool person_display;
bool alert;
std::vector<int> map_vec;
//std::string alertType;
gchar* alertType;
};
enum
{
PROP_0,
PROP_ALERT_AREA_DEFINITION,
PROP_ALERT_AREA_DISPLAY,
PROP_ALERT_PERSON_DISPLAY,
PROP_ALERT_TYPE,
};
#define DEBUG_INIT GST_DEBUG_CATEGORY_INIT(GST_CAT_DEFAULT, "gstgeofencebase", 0, "debug category for gstgeofencebase element");
G_DEFINE_TYPE_WITH_CODE(GstGeofencebase, gst_geofencebase, GST_TYPE_VIDEO_FILTER, G_ADD_PRIVATE(GstGeofencebase) DEBUG_INIT)
/* pad templates */
/* FIXME: add/remove formats you can handle */
#define VIDEO_SRC_CAPS \
GST_VIDEO_CAPS_MAKE("{ BGR }")
/* FIXME: add/remove formats you can handle */
#define VIDEO_SINK_CAPS \
GST_VIDEO_CAPS_MAKE("{ BGR }")
/* class initialization */
static void gst_geofencebase_class_init (GstGeofencebaseClass * klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
GstBaseTransformClass *base_transform_class = GST_BASE_TRANSFORM_CLASS (klass);
GstVideoFilterClass *video_filter_class = GST_VIDEO_FILTER_CLASS (klass);
/* Setting up pads and setting metadata should be moved to
base_class_init if you intend to subclass this class. */
gst_element_class_add_pad_template (GST_ELEMENT_CLASS(klass),
gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS,
gst_caps_from_string (VIDEO_SRC_CAPS)));
gst_element_class_add_pad_template (GST_ELEMENT_CLASS(klass),
gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS,
gst_caps_from_string (VIDEO_SINK_CAPS)));
gst_element_class_set_static_metadata (GST_ELEMENT_CLASS(klass),
"Adlink Geo-Fence-Base video filter", "Filter/Video", "An ADLINK Geo-Fencing-Base demo video filter", "Dr. Paul Lin <paul.lin@adlinktech.com>");
gobject_class->set_property = gst_geofencebase_set_property;
gobject_class->get_property = gst_geofencebase_get_property;
// Install the properties to GObjectClass
g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_ALERT_AREA_DEFINITION,
g_param_spec_string ("alert-area-def", "Alert-area-def", "The definition file location of the alert area respect the frame based on the specific resolution.", "", (GParamFlags)(G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_ALERT_TYPE,
g_param_spec_string ("alert-type", "Alert-Type", "The alert type name when event occurred.", "BreakIn\0"/*DEFAULT_ALERT_TYPE*/, (GParamFlags)(G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_ALERT_AREA_DISPLAY,
g_param_spec_boolean("area-display", "Area-display", "Show alert area in frame.", FALSE, G_PARAM_READWRITE));
g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_ALERT_PERSON_DISPLAY,
g_param_spec_boolean("person-display", "Person-display", "Show inferenced person region in frame.", FALSE, G_PARAM_READWRITE));
gobject_class->dispose = gst_geofencebase_dispose;
gobject_class->finalize = gst_geofencebase_finalize;
base_transform_class->start = GST_DEBUG_FUNCPTR (gst_geofencebase_start);
base_transform_class->stop = GST_DEBUG_FUNCPTR (gst_geofencebase_stop);
video_filter_class->set_info = GST_DEBUG_FUNCPTR (gst_geofencebase_set_info);
//video_filter_class->transform_frame = GST_DEBUG_FUNCPTR (gst_geofencebase_transform_frame);
video_filter_class->transform_frame_ip = GST_DEBUG_FUNCPTR (gst_geofencebase_transform_frame_ip);
}
static void gst_geofencebase_init (GstGeofencebase *geofencebase)
{
/*< private >*/
geofencebase->priv = (GstGeofencebasePrivate *)gst_geofencebase_get_instance_private (geofencebase);
geofencebase->priv->area_display = false;
geofencebase->priv->person_display = false;
geofencebase->priv->alert = false;
geofencebase->eventTick = 0;
geofencebase->lastEventTick = 0;
geofencebase->priv->alertType = "BreakIn\0";//DEFAULT_ALERT_TYPE;
}
void gst_geofencebase_set_property (GObject * object, guint property_id, const GValue * value, GParamSpec * pspec)
{
GstGeofencebase *geofencebase = GST_GEOFENCEBASE (object);
GST_DEBUG_OBJECT (geofencebase, "set_property");
switch (property_id)
{
case PROP_ALERT_AREA_DEFINITION:
{
geofencebase->priv->alert_definition_path = g_value_dup_string(value);
GST_MESSAGE(std::string("geofencebase->priv->alert_definition_path = " + geofencebase->priv->alert_definition_path).c_str());
GST_MESSAGE("Start parsing definition file...");
std::ifstream infile(geofencebase->priv->alert_definition_path);
if(!infile)
{
std::cout << "Cannot open input file.\n";
break;
}
std::string lineString;
while (std::getline(infile, lineString))
{
std::vector<std::string> ratioVec = split(lineString);
double x = std::atof(ratioVec[0].c_str());
double y = std::atof(ratioVec[1].c_str());
std::vector<double> vec;
vec.push_back(x);
vec.push_back(y);
geofencebase->priv->ratio_vec.push_back(vec);
}
GST_MESSAGE("Parsing definition file done!");
break;
}
case PROP_ALERT_TYPE:
{
geofencebase->priv->alertType = g_value_dup_string(value);
break;
}
case PROP_ALERT_AREA_DISPLAY:
{
geofencebase->priv->area_display = g_value_get_boolean(value);
if(geofencebase->priv->area_display)
GST_MESSAGE("Display area is enabled!");
break;
}
case PROP_ALERT_PERSON_DISPLAY:
{
geofencebase->priv->person_display = g_value_get_boolean(value);
if(geofencebase->priv->person_display)
GST_MESSAGE("Display inferenced person is enabled!");
break;
}
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
void gst_geofencebase_get_property (GObject * object, guint property_id, GValue * value, GParamSpec * pspec)
{
GstGeofencebase *geofencebase = GST_GEOFENCEBASE (object);
GST_DEBUG_OBJECT (geofencebase, "get_property");
switch (property_id)
{
case PROP_ALERT_AREA_DEFINITION:
g_value_set_string (value, geofencebase->priv->alert_definition_path.c_str());
break;
case PROP_ALERT_TYPE:
//g_value_set_string (value, geofencebase->priv->alertType.c_str());
g_value_set_string (value, geofencebase->priv->alertType);
break;
case PROP_ALERT_AREA_DISPLAY:
g_value_set_boolean(value, geofencebase->priv->area_display);
break;
case PROP_ALERT_PERSON_DISPLAY:
g_value_set_boolean(value, geofencebase->priv->person_display);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
break;
}
}
void gst_geofencebase_dispose (GObject * object)
{
GstGeofencebase *geofencebase = GST_GEOFENCEBASE (object);
GST_DEBUG_OBJECT (geofencebase, "dispose");
/* clean up as possible. may be called multiple times */
G_OBJECT_CLASS (gst_geofencebase_parent_class)->dispose (object);
}
void gst_geofencebase_finalize (GObject * object)
{
GstGeofencebase *geofencebase = GST_GEOFENCEBASE(object);
GST_DEBUG_OBJECT (geofencebase, "finalize");
/* clean up object here */
G_OBJECT_CLASS (gst_geofencebase_parent_class)->finalize (object);
}
static gboolean gst_geofencebase_start (GstBaseTransform * trans)
{
GstGeofencebase *geofencebase = GST_GEOFENCEBASE (trans);
GST_DEBUG_OBJECT (geofencebase, "start");
return TRUE;
}
static gboolean gst_geofencebase_stop (GstBaseTransform * trans)
{
GstGeofencebase *geofencebase = GST_GEOFENCEBASE (trans);
GST_DEBUG_OBJECT (geofencebase, "stop");
return TRUE;
}
static gboolean gst_geofencebase_set_info (GstVideoFilter * filter, GstCaps * incaps, GstVideoInfo * in_info, GstCaps * outcaps, GstVideoInfo * out_info)
{
GstGeofencebase *geofencebase = GST_GEOFENCEBASE (filter);
GST_DEBUG_OBJECT (geofencebase, "set_info");
// Start to parse the real area point
int width = in_info->width;
int height = in_info->height;
for(uint id = 0; id < geofencebase->priv->ratio_vec.size(); ++id)
{
cv::Point2d p;
p.x = (int)(width * geofencebase->priv->ratio_vec[id][0]);
p.y = (int)(height * geofencebase->priv->ratio_vec[id][1]);
geofencebase->priv->area_point_vec.push_back(p);
}
return TRUE;
}
/* transform */
// static GstFlowReturn gst_geofencebase_transform_frame (GstVideoFilter * filter, GstVideoFrame * inframe, GstVideoFrame * outframe)
// {
// GstGeofencebase *geofencebase = GST_GEOFENCEBASE (filter);
//
// GST_DEBUG_OBJECT (geofencebase, "transform_frame");
//
// return GST_FLOW_OK;
// }
static GstFlowReturn gst_geofencebase_transform_frame_ip (GstVideoFilter * filter, GstVideoFrame * frame)
{
GstGeofencebase *geofencebase = GST_GEOFENCEBASE (filter);
GstMapInfo info;
GST_DEBUG_OBJECT (geofencebase, "transform_frame_ip");
gst_buffer_map(frame->buffer, &info, GST_MAP_READ);
// map frame data from stream to geofencebase srcMat
mapGstVideoFrame2OpenCVMat(geofencebase, frame, info);
// get inference detected persons
getDetectedPerson(geofencebase, frame->buffer);
// do algorithm
doAlgorithm(geofencebase, frame->buffer);
// draw alert area
drawAlertArea(geofencebase);
gst_buffer_unmap(frame->buffer, &info);
return GST_FLOW_OK;
}
static void mapGstVideoFrame2OpenCVMat(GstGeofencebase *geofencebase, GstVideoFrame *frame, GstMapInfo &info)
{
if(geofencebase->srcMat.cols == 0 || geofencebase->srcMat.rows == 0)
geofencebase->srcMat = cv::Mat(frame->info.height, frame->info.width, CV_8UC3, info.data);
else if((geofencebase->srcMat.cols != frame->info.width) || (geofencebase->srcMat.rows != frame->info.height))
{
geofencebase->srcMat.release();
geofencebase->srcMat = cv::Mat(frame->info.height, frame->info.width, CV_8UC3, info.data);
}
else
geofencebase->srcMat.data = info.data;
}
static void getDetectedPerson(GstGeofencebase *geofencebase, GstBuffer* buffer)
{
// reset for each frame
geofencebase->priv->person_vec.clear();
geofencebase->priv->map_vec.clear();
GstAdBatchMeta *meta = gst_buffer_get_ad_batch_meta(buffer);
if (meta == NULL)
GST_MESSAGE("Adlink metadata is not exist!");
else
{
AdBatch &batch = meta->batch;
bool frame_exist = batch.frames.size() > 0 ? true : false;
if(frame_exist)
{
VideoFrameData frame_info = batch.frames[0];
int detectionBoxResultNumber = frame_info.detection_results.size();
int width = geofencebase->srcMat.cols;
int height = geofencebase->srcMat.rows;
for(int i = 0 ; i < detectionBoxResultNumber ; ++i)
{
adlink::ai::DetectionBoxResult detection_result = frame_info.detection_results[i];
if(detection_result.obj_label.compare("person") == 0)
{
int x1 = (int)(width * detection_result.x1);
int y1 = (int)(height * detection_result.y1);
int x2 = (int)(width * detection_result.x2);
int y2 = (int)(height * detection_result.y2);
std::vector<cv::Point> personPoint_vec;
personPoint_vec.push_back(cv::Point2d(x1, y1));
personPoint_vec.push_back(cv::Point2d(x2, y1));
personPoint_vec.push_back(cv::Point2d(x2, y2));
personPoint_vec.push_back(cv::Point2d(x1, y2));
geofencebase->priv->person_vec.push_back(personPoint_vec);
// record the mapping index
geofencebase->priv->map_vec.push_back(i);
int current_id = geofencebase->priv->person_vec.size() - 1;
if(geofencebase->priv->person_display)
cv::rectangle(geofencebase->srcMat, cv::Point(geofencebase->priv->person_vec[current_id][0].x, geofencebase->priv->person_vec[current_id][0].y), cv::Point(geofencebase->priv->person_vec[current_id][2].x, geofencebase->priv->person_vec[current_id][2].y), cv::Scalar(0,128,128), 3, cv::LINE_8);
}
}
}
}
}
static void doAlgorithm(GstGeofencebase *geofencebase, GstBuffer* buffer)
{
// If no region, return directly. Points must larger than 2.
if(geofencebase->priv->area_point_vec.size() <= 2)
return;
// If metadata does not exist, return directly.
GstAdBatchMeta *meta = gst_buffer_get_ad_batch_meta(buffer);
if (meta == NULL)
{
GST_MESSAGE("Adlink metadata is not exist!");
return;
}
AdBatch &batch = meta->batch;
bool frame_exist = batch.frames.size() > 0 ? true : false;
// Reset region
if((cv::getTickCount() - geofencebase->eventTick)/ cv::getTickFrequency() > 2)
geofencebase->priv->alert = false;
std::vector<cv::Point> intersectionPolygon;
int num_person_detected = geofencebase->priv->person_vec.size();
for(int id = 0; id < num_person_detected; ++id)
{
float intersectArea = cv::intersectConvexConvex(geofencebase->priv->area_point_vec, geofencebase->priv->person_vec[id], intersectionPolygon, true);
if(intersectArea > 0)
{
geofencebase->eventTick = cv::getTickCount();
geofencebase->priv->alert = true;
// mark the alert data to metadata
if(frame_exist)
{
// alert message format:",type<time>", must used append.
std::string alertMessage = "," + std::string(geofencebase->priv->alertType) + "<" + return_current_time_and_date() + ">";
// write alert message to meta use pointer
meta->batch.frames[0].detection_results[geofencebase->priv->map_vec[id]].meta += alertMessage;
}
}
}
}
static void drawAlertArea(GstGeofencebase *geofencebase)
{
if(geofencebase->priv->area_display)
{
int lineType = cv::LINE_8;
int pt_num = geofencebase->priv->area_point_vec.size();
cv::Scalar color = geofencebase->priv->alert == true ? cv::Scalar(0, 0, 255) : cv::Scalar(255, 0, 0);
int thickness = geofencebase->priv->alert == true ? 6 : 2;
for(int i = 0; i < pt_num; ++i)
cv::line(geofencebase->srcMat, geofencebase->priv->area_point_vec[i%pt_num], geofencebase->priv->area_point_vec[(i+1)%pt_num], color, thickness, lineType);
}
}
| 38.334086 | 316 | 0.684548 | [
"object",
"vector",
"transform"
] |
eeb56a6b8895f29becd44150b0a239c9a49ccc84 | 1,440 | cc | C++ | HeterogeneousCore/SonicTriton/src/triton_utils.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 4 | 2015-10-12T10:31:12.000Z | 2018-02-26T20:40:58.000Z | HeterogeneousCore/SonicTriton/src/triton_utils.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 524 | 2018-01-29T15:50:45.000Z | 2021-08-04T14:03:21.000Z | HeterogeneousCore/SonicTriton/src/triton_utils.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 7 | 2018-02-19T11:17:13.000Z | 2020-10-12T21:57:00.000Z | #include "HeterogeneousCore/SonicTriton/interface/triton_utils.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/Utilities/interface/Exception.h"
#include <sstream>
#include <experimental/iterator>
namespace triton_utils {
template <typename C>
std::string printColl(const C& coll, const std::string& delim) {
if (coll.empty())
return "";
std::stringstream msg;
//avoid trailing delim
std::copy(std::begin(coll), std::end(coll), std::experimental::make_ostream_joiner(msg, delim));
return msg.str();
}
void throwIfError(const Error& err, std::string_view msg) {
if (!err.IsOk())
throw cms::Exception("TritonServerFailure") << msg << ": " << err;
}
bool warnIfError(const Error& err, std::string_view msg) {
if (!err.IsOk())
edm::LogWarning("TritonServerWarning") << msg << ": " << err;
return err.IsOk();
}
} // namespace triton_utils
template std::string triton_utils::printColl(const edm::Span<std::vector<int64_t>::const_iterator>& coll,
const std::string& delim);
template std::string triton_utils::printColl(const std::vector<uint8_t>& coll, const std::string& delim);
template std::string triton_utils::printColl(const std::vector<float>& coll, const std::string& delim);
template std::string triton_utils::printColl(const std::unordered_set<std::string>& coll, const std::string& delim);
| 37.894737 | 116 | 0.686111 | [
"vector"
] |
eeb62f3d81d53035077007c50590fd06db7b347e | 2,990 | hpp | C++ | STest/STest/Scenario/ScenarioArray.hpp | SSteve/fprime | 12c478bd79c2c4ba2d9f9e634e47f8b6557c54a8 | [
"Apache-2.0"
] | 4 | 2021-02-20T13:38:25.000Z | 2021-05-04T17:20:34.000Z | STest/STest/Scenario/ScenarioArray.hpp | SSteve/fprime | 12c478bd79c2c4ba2d9f9e634e47f8b6557c54a8 | [
"Apache-2.0"
] | 42 | 2021-06-10T23:31:10.000Z | 2021-06-25T00:35:31.000Z | STest/STest/Scenario/ScenarioArray.hpp | SSteve/fprime | 12c478bd79c2c4ba2d9f9e634e47f8b6557c54a8 | [
"Apache-2.0"
] | 5 | 2019-09-06T23:25:26.000Z | 2021-06-22T03:01:07.000Z | // ======================================================================
// \title ScenarioArray.hpp
// \author bocchino
// \brief An array of scenarios
//
// \copyright
// Copyright (C) 2017 California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
// ======================================================================
#ifndef STest_ScenarioArray_HPP
#define STest_ScenarioArray_HPP
#include <assert.h>
#include "STest/Random/Random.hpp"
namespace STest {
//! An array of scenarios
template<typename State>class ScenarioArray {
public:
// ----------------------------------------------------------------------
// Constructors and destructors
// ----------------------------------------------------------------------
//! Construct a ScenarioArray object
ScenarioArray (
Scenario<State>** scenarios, //!< The scenarios in the array
const U32 size //!< The number of scenarios in the array
) :
size(size),
scenarios(scenarios),
sequenceIndex(0)
{
}
public:
// ----------------------------------------------------------------------
// Public instance methods
// ----------------------------------------------------------------------
//! Get a random index into the array
//! \return The index
U32 getRandomIndex(void) const {
const U32 index = Random::startLength(0, this->size);
assert(index < this->size);
return index;
}
//! Reset the sequence index and reset all child scenarios
void reset(void) {
this->sequenceIndex = 0;
for (U32 i = 0; i < this->size; ++i) {
this->scenarios[i]->reset();
}
}
//! Return the next scenario in the sequence
Scenario<State>* nextScenario(void) {
Scenario<State>* scenario = NULL;
if (this->sequenceIndex < this->size) {
scenario = this->scenarios[this->sequenceIndex];
++this->sequenceIndex;
}
if (scenario != NULL) {
scenario->reset();
}
return scenario;
}
//! Get the scenarios
Scenario<State>** getScenarios(void) const {
assert(this->scenarios != NULL);
return this->scenarios;
}
public:
// ----------------------------------------------------------------------
// Public member variables
// ----------------------------------------------------------------------
//! The number of scenarios in the array
const U32 size;
private:
// ----------------------------------------------------------------------
// Private member variables
// ----------------------------------------------------------------------
//! The scenarios in the array
Scenario<State>** scenarios;
//! The sequence index
U32 sequenceIndex;
};
}
#endif
| 27.431193 | 79 | 0.435452 | [
"object"
] |
eec6263e3e2dc6ea496c097a0ff8883620855a02 | 3,951 | cpp | C++ | anno/RestDatasetFilesystem.cpp | urobots-io/anno | 8e240185e6fc0908687b15a39c892814a6bddee6 | [
"MIT"
] | 9 | 2020-07-17T05:28:52.000Z | 2022-03-03T18:26:12.000Z | anno/RestDatasetFilesystem.cpp | urobots-io/anno | 8e240185e6fc0908687b15a39c892814a6bddee6 | [
"MIT"
] | null | null | null | anno/RestDatasetFilesystem.cpp | urobots-io/anno | 8e240185e6fc0908687b15a39c892814a6bddee6 | [
"MIT"
] | null | null | null | // This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com
//
// Anno Labeling Tool
// 2020-2021 (c) urobots GmbH, https://urobots.io
#include "RestDatasetFilesystem.h"
#include "rest.h"
#include <QFileInfo>
#include <QVariant>
using namespace std;
using namespace rest;
RestDatasetFilesystem::RestDatasetFilesystem(QString dataset_object_address, QString root_path)
: dataset_object_address_(dataset_object_address)
, root_path_(root_path) {
if (!root_path_.endsWith("/"))
root_path_ += "/";
}
QJsonObject RestDatasetFilesystem::Params(QString path) {
QJsonObject json;
json.insert("path", QJsonValue::fromVariant(root_path_ + path));
return json;
}
QString RestDatasetFilesystem::FunctionUrl(QString function) {
return dataset_object_address_ + "/attrs/" + function + "/call/";
}
QByteArray RestDatasetFilesystem::CallDatasetFunction(QString function, QJsonObject params, QString accept_type) {
return ExchangeData(FunctionUrl(function), params, accept_type);
}
vector<FileTreeItemInfo> RestDatasetFilesystem::LoadFolder(QStringList path) {
QByteArray json_content;
try {
json_content = CallDatasetFunction("dir", Params(path.join("/")), ContentType::json);
}
catch (exception&) {
return {};
}
QJsonDocument json = QJsonDocument().fromJson(json_content);
if (json.isNull()) {
return{};
}
auto retval = json.object()["retval"].toObject();
vector<FileTreeItemInfo> result;
int ifolder = 0;
foreach(const QString& key, retval.keys()) {
auto type = retval.value(key).toString();
if (type == "file") {
result.push_back({ key, false });
}
else {
result.insert(result.begin() + ifolder, { key, true });
++ifolder;
}
}
return result;
}
QByteArray RestDatasetFilesystem::LoadFile(QString filename) {
QByteArray bytes;
try {
bytes = CallDatasetFunction("read_file", Params(filename), ContentType::binary);
}
catch (exception&) {
return{};
}
return bytes;
}
bool RestDatasetFilesystem::Remove(QString filename) {
QByteArray bytes;
try {
bytes = CallDatasetFunction("remove", Params(filename), ContentType::json);
}
catch (exception&) {
return false;
}
return true;
}
bool RestDatasetFilesystem::CreateSubfolder(const QStringList destination, QString name) {
auto dir = (QStringList() << destination << name).join("/");
auto params = Params(dir);
params.insert("exist_ok", QJsonValue::fromVariant(false));
QByteArray bytes;
try {
bytes = CallDatasetFunction("makedirs", params, ContentType::json);
}
catch (exception&) {
return false;
}
return true;
}
bool RestDatasetFilesystem::CopyLocalFile(const QStringList destination, QString source_path) {
QString file_name = QFileInfo(source_path).fileName();
auto dir = (QStringList() << destination << file_name).join("/");
auto params = Params(dir);
QFile file(source_path);
if (!file.open(QIODevice::ReadOnly)) {
return false;
}
QByteArray file_data = file.readAll();
QByteArray bytes;
try {
bytes = ExchangeData(FunctionUrl("write_file"), params, "data", file_name, file_data, ContentType::json);
}
catch (exception&) {
return false;
}
return false;
}
bool RestDatasetFilesystem::Rename(const QStringList path, const QStringList new_path) {
auto params = Params(path.join("/"));
params.insert("new_path", QJsonValue::fromVariant(root_path_ + new_path.join("/")));
QByteArray bytes;
try {
bytes = CallDatasetFunction("move", params, ContentType::json);
}
catch (exception&) {
return false;
}
return true;
}
| 28.630435 | 122 | 0.65629 | [
"object",
"vector"
] |
eec866027043d674b75cb58720d8dd0b16d9c743 | 2,222 | cpp | C++ | Engine/src/Engine/Renderer/Window.cpp | CloseRange/GameEngine | 6b42aa383fa78c22aec8df2c51386d05eee0c0cb | [
"Apache-2.0"
] | null | null | null | Engine/src/Engine/Renderer/Window.cpp | CloseRange/GameEngine | 6b42aa383fa78c22aec8df2c51386d05eee0c0cb | [
"Apache-2.0"
] | null | null | null | Engine/src/Engine/Renderer/Window.cpp | CloseRange/GameEngine | 6b42aa383fa78c22aec8df2c51386d05eee0c0cb | [
"Apache-2.0"
] | null | null | null | #include "enpch.h"
#include "Window.h"
#include "Shader/Shader.h"
#include "Model/VertexBuffer.h"
#include "Model/IndexBuffer.h"
#include "Model/VertexArray.h"
#include "Textures/Texture.h"
#include "Renderer.h"
#include <math.h>
namespace Renderer {
Window::Window(int width, int height, const char* name) {
if (!glfwInit()) {
isValid = -1;
LOG_ERROR("Could not initilize Window '{0}'\nError code {1}: GLFW has not been initalized", name, isValid);
return;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
window = glfwCreateWindow(width, height, name, NULL, NULL);
if (!window) {
glfwTerminate();
isValid = -2;
LOG_ERROR("Could not initilize Window '{0}'\nError code {1}: window failed to create", name, isValid);
return;
}
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
{
int status = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
LOG_FATAL(status, "Failed to initalize ModernGL with Glad!");
Renderer::LogDetails();
float vertices[] = {
-0.5f, -0.5f, 0.0f, 0.0f,
0.5f, -0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.0f, 1.0f
};
unsigned int indices[] = { 0, 1, 2, 2, 3, 0 };
VertexArray va;
VertexBuffer vb(vertices, 4 * 4 * sizeof(float));
VertexLayout layout;
layout.Push<float>(2);
layout.Push<float>(2);
va.AddBuffer(vb, layout);
IndexBuffer ib(indices, 6);
Shader shader("res/shaders/Base.shader");
Texture texture("res/textures/taco.png");
texture.Bind();
float texI[] = { 0.0f };
shader.SetData("u_Texture", texI);
va.Unbind();
vb.Unbind();
shader.Unbind();
ib.Unbind();
int s = 0;
while (!glfwWindowShouldClose(window)) {
s++;
float r = (sin(s / 10.0f) + 1.0f) / 2.0f;
float g = (cos(s / 10.0f) + 1.0f) / 2.0f;
float b = (tan(s / 10.0f) + 1.0f) / 2.0f;
float t[] = { r, g, .5f };
shader.SetData("u_Color", t);
Renderer::Clear();
Renderer::Draw(va, ib, shader);
glfwSwapBuffers(window);
glfwPollEvents();
}
}
glfwTerminate();
}
Window::~Window() {
delete window;
}
}
| 22.444444 | 110 | 0.630513 | [
"model"
] |
eec915137f6d1286eb641534f402c4ff3dd90086 | 1,167 | cpp | C++ | euphony/src/main/cpp/tests/base2Test.cpp | aiclaudev/euphony | a1ad79a8c3d89aaa7e33b41623a65d1e0830f88b | [
"Apache-2.0"
] | 18 | 2019-07-08T16:44:15.000Z | 2021-08-03T04:28:55.000Z | euphony/src/main/cpp/tests/base2Test.cpp | aiclaudev/euphony | a1ad79a8c3d89aaa7e33b41623a65d1e0830f88b | [
"Apache-2.0"
] | 39 | 2021-08-09T14:09:51.000Z | 2021-10-19T15:18:44.000Z | euphony/src/main/cpp/tests/base2Test.cpp | aiclaudev/euphony | a1ad79a8c3d89aaa7e33b41623a65d1e0830f88b | [
"Apache-2.0"
] | 20 | 2019-11-25T13:08:09.000Z | 2021-08-03T09:28:17.000Z | #include <gtest/gtest.h>
#include <Definitions.h>
#include <Base2.h>
#include <tuple>
using namespace Euphony;
typedef std::tuple<std::vector<u_int8_t>, std::string> TestParamType;
class Base2TranslationFixture : public ::testing::TestWithParam<TestParamType> {
public:
Base* base2 = nullptr;
};
TEST_P(Base2TranslationFixture, DefaultBase2Test)
{
std::vector<u_int8_t> source;
std::string expectedEncodedResult;
std::tie(source, expectedEncodedResult) = GetParam();
HexVector hv = HexVector(source);
base2 = new Base2(hv);
std::string actualResult = base2->getBaseString();
EXPECT_EQ(actualResult, expectedEncodedResult);
}
INSTANTIATE_TEST_SUITE_P(
Base2TranslationTest,
Base2TranslationFixture,
::testing::Values(
TestParamType(std::vector<u_int8_t>{ 0x61 }, "01100001"),
TestParamType(std::vector<u_int8_t>{ 0x62 }, "01100010"),
TestParamType(std::vector<u_int8_t>{ 0x63 }, "01100011"),
TestParamType(std::vector<u_int8_t>{ 0x61, 0x62, 0x63 }, "011000010110001001100011"),
TestParamType(std::vector<u_int8_t>{ 0x78, 0x79, 0x7a }, "011110000111100101111010")
)); | 32.416667 | 93 | 0.706941 | [
"vector"
] |
eed35b0c037313e570ead913752afcc8486bbd91 | 7,513 | cpp | C++ | bench/BenchSpan.cpp | flier/zipkin-cpp | f86357f6e302c98ab8a070267e3f7ba85ec2c59f | [
"Apache-2.0"
] | 48 | 2017-03-06T05:07:26.000Z | 2022-03-18T08:19:36.000Z | bench/BenchSpan.cpp | flier/zipkin-cpp | f86357f6e302c98ab8a070267e3f7ba85ec2c59f | [
"Apache-2.0"
] | 19 | 2017-02-25T03:25:30.000Z | 2021-02-10T17:28:12.000Z | bench/BenchSpan.cpp | flier/zipkin-cpp | f86357f6e302c98ab8a070267e3f7ba85ec2c59f | [
"Apache-2.0"
] | 19 | 2017-04-11T09:23:42.000Z | 2022-03-08T05:24:31.000Z | #include <benchmark/benchmark_api.h>
#include <utility>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/protocol/TBinaryProtocol.h>
#define RAPIDJSON_HAS_STDSTRING 1
#include <rapidjson/stringbuffer.h>
#include <rapidjson/prettywriter.h>
#include "Span.h"
#include "Tracer.h"
void bench_span_reuse(benchmark::State &state)
{
std::unique_ptr<zipkin::Tracer> tracer(zipkin::Tracer::create(nullptr));
std::vector<zipkin::Span *> spans(state.range(0));
while (state.KeepRunning())
{
for (int i = 0; i < spans.size(); i++)
{
spans[i] = tracer->span("bench");
}
for (int i = 0; i < spans.size(); i++)
{
spans[i]->release();
}
}
state.SetItemsProcessed(state.iterations() * spans.size());
}
BENCHMARK(bench_span_reuse)->RangeMultiplier(4)->Range(1, 512)->ThreadPerCpu();
void bench_span_annonate(benchmark::State &state)
{
zipkin::Span span(nullptr, "bench");
while (state.KeepRunning())
{
span << zipkin::TraceKeys::CLIENT_SEND;
}
state.SetItemsProcessed(span.message().annotations.size());
}
BENCHMARK(bench_span_annonate);
void bench_span_annonate_with_endpoint(benchmark::State &state)
{
zipkin::Span span(nullptr, "bench");
zipkin::Endpoint endpoint("bench");
while (state.KeepRunning())
{
span << zipkin::TraceKeys::CLIENT_SEND << endpoint;
}
state.SetItemsProcessed(span.message().annotations.size());
}
BENCHMARK(bench_span_annonate_with_endpoint);
void bench_span_annonate_bool(benchmark::State &state)
{
zipkin::Span span(nullptr, "bench");
while (state.KeepRunning())
{
span << std::make_pair(zipkin::TraceKeys::CLIENT_SEND, false);
}
state.SetItemsProcessed(span.message().binary_annotations.size());
}
BENCHMARK(bench_span_annonate_bool);
void bench_span_annonate_bool_with_endpoint(benchmark::State &state)
{
zipkin::Span span(nullptr, "bench");
zipkin::Endpoint endpoint("bench");
while (state.KeepRunning())
{
span << std::make_pair(zipkin::TraceKeys::CLIENT_SEND, false) << endpoint;
}
state.SetItemsProcessed(span.message().binary_annotations.size());
}
BENCHMARK(bench_span_annonate_bool_with_endpoint);
void bench_span_annonate_int16(benchmark::State &state)
{
zipkin::Span span(nullptr, "bench");
while (state.KeepRunning())
{
span << std::make_pair(zipkin::TraceKeys::CLIENT_SEND, (int16_t)123);
}
state.SetItemsProcessed(span.message().binary_annotations.size());
}
BENCHMARK(bench_span_annonate_int16);
void bench_span_annonate_int32(benchmark::State &state)
{
zipkin::Span span(nullptr, "bench");
while (state.KeepRunning())
{
span << std::make_pair(zipkin::TraceKeys::CLIENT_SEND, (int32_t)123);
}
state.SetItemsProcessed(span.message().binary_annotations.size());
}
BENCHMARK(bench_span_annonate_int32);
void bench_span_annonate_int64(benchmark::State &state)
{
zipkin::Span span(nullptr, "bench");
while (state.KeepRunning())
{
span << std::make_pair(zipkin::TraceKeys::CLIENT_SEND, (int64_t)123);
}
state.SetItemsProcessed(span.message().binary_annotations.size());
}
BENCHMARK(bench_span_annonate_int64);
void bench_span_annonate_double(benchmark::State &state)
{
zipkin::Span span(nullptr, "bench");
while (state.KeepRunning())
{
span << std::make_pair(zipkin::TraceKeys::CLIENT_SEND, (double)12.3);
}
state.SetItemsProcessed(span.message().binary_annotations.size());
}
BENCHMARK(bench_span_annonate_double);
void bench_span_annonate_cstr(benchmark::State &state)
{
zipkin::Span span(nullptr, "bench");
while (state.KeepRunning())
{
span << std::make_pair(zipkin::TraceKeys::CLIENT_SEND, "hello world");
}
state.SetItemsProcessed(span.message().binary_annotations.size());
}
BENCHMARK(bench_span_annonate_cstr);
void bench_span_annonate_string(benchmark::State &state)
{
zipkin::Span span(nullptr, "bench");
std::string value("hello");
while (state.KeepRunning())
{
span << std::make_pair(zipkin::TraceKeys::CLIENT_SEND, value);
}
state.SetItemsProcessed(span.message().binary_annotations.size());
}
BENCHMARK(bench_span_annonate_string);
void bench_span_annonate_string_with_endpoint(benchmark::State &state)
{
zipkin::Span span(nullptr, "bench");
std::string value("hello");
zipkin::Endpoint endpoint("bench");
while (state.KeepRunning())
{
span << std::make_pair(zipkin::TraceKeys::CLIENT_SEND, value) << endpoint;
}
state.SetItemsProcessed(span.message().binary_annotations.size());
}
BENCHMARK(bench_span_annonate_string_with_endpoint);
void bench_span_annonate_wcstr(benchmark::State &state)
{
zipkin::Span span(nullptr, "bench");
while (state.KeepRunning())
{
span << std::make_pair(zipkin::TraceKeys::CLIENT_SEND, L"hello world");
}
state.SetItemsProcessed(span.message().binary_annotations.size());
}
BENCHMARK(bench_span_annonate_wcstr);
void bench_span_annonate_wstring(benchmark::State &state)
{
zipkin::Span span(nullptr, "bench");
std::wstring value(L"hello world");
while (state.KeepRunning())
{
span << std::make_pair(zipkin::TraceKeys::CLIENT_SEND, value);
}
state.SetItemsProcessed(span.message().binary_annotations.size());
}
BENCHMARK(bench_span_annonate_wstring);
void bench_span_serialize_binary(benchmark::State &state)
{
zipkin::Span span(nullptr, "bench");
zipkin::Endpoint endpoint("bench");
span << zipkin::TraceKeys::CLIENT_SEND
<< std::make_pair(zipkin::TraceKeys::CLIENT_SEND, false) << endpoint
<< std::make_pair(zipkin::TraceKeys::CLIENT_SEND, L"hello world");
boost::shared_ptr<apache::thrift::transport::TMemoryBuffer> buf(new apache::thrift::transport::TMemoryBuffer());
apache::thrift::protocol::TBinaryProtocol protocol(buf);
while (state.KeepRunning())
{
span.serialize_binary(protocol);
buf->resetBuffer();
}
state.SetItemsProcessed(state.iterations());
}
BENCHMARK(bench_span_serialize_binary);
void bench_span_serialize_json(benchmark::State &state)
{
zipkin::Span span(nullptr, "bench");
zipkin::Endpoint endpoint("bench");
span << zipkin::TraceKeys::CLIENT_SEND
<< std::make_pair(zipkin::TraceKeys::CLIENT_SEND, false) << endpoint
<< std::make_pair(zipkin::TraceKeys::CLIENT_SEND, L"hello world");
rapidjson::StringBuffer buffer;
while (state.KeepRunning())
{
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
span.serialize_json(writer);
buffer.Clear();
}
state.SetItemsProcessed(state.iterations());
}
BENCHMARK(bench_span_serialize_json);
void bench_span_serialize_pretty_json(benchmark::State &state)
{
zipkin::Span span(nullptr, "bench");
zipkin::Endpoint endpoint("bench");
span << zipkin::TraceKeys::CLIENT_SEND
<< std::make_pair(zipkin::TraceKeys::CLIENT_SEND, false) << endpoint
<< std::make_pair(zipkin::TraceKeys::CLIENT_SEND, L"hello world");
rapidjson::StringBuffer buffer;
while (state.KeepRunning())
{
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
span.serialize_json(writer);
buffer.Clear();
}
state.SetItemsProcessed(state.iterations());
}
BENCHMARK(bench_span_serialize_pretty_json);
BENCHMARK_MAIN(); | 25.554422 | 116 | 0.690536 | [
"vector"
] |
eed4f9a2f05f44e5afe6fb8b8b215c2209ed1575 | 10,683 | cpp | C++ | src/plugins/openmpt/libopenmpt/soundlib/Load_okt.cpp | frranck/HippoPlayer | ede5c13db160b215018ca24216131414e06d5f1f | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-17T17:14:30.000Z | 2021-07-17T17:14:30.000Z | src/plugins/openmpt/libopenmpt/soundlib/Load_okt.cpp | frranck/HippoPlayer | ede5c13db160b215018ca24216131414e06d5f1f | [
"Apache-2.0",
"MIT"
] | null | null | null | src/plugins/openmpt/libopenmpt/soundlib/Load_okt.cpp | frranck/HippoPlayer | ede5c13db160b215018ca24216131414e06d5f1f | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Load_okt.cpp
* ------------
* Purpose: OKT (Oktalyzer) module loader
* Notes : (currently none)
* Authors: Storlek (Original author - http://schismtracker.org/ - code ported with permission)
* Johannes Schultz (OpenMPT Port, tweaks)
* The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
*/
#include "stdafx.h"
#include "Loaders.h"
OPENMPT_NAMESPACE_BEGIN
struct OktIffChunk
{
// IFF chunk names
enum ChunkIdentifiers
{
idCMOD = MAGIC4BE('C','M','O','D'),
idSAMP = MAGIC4BE('S','A','M','P'),
idSPEE = MAGIC4BE('S','P','E','E'),
idSLEN = MAGIC4BE('S','L','E','N'),
idPLEN = MAGIC4BE('P','L','E','N'),
idPATT = MAGIC4BE('P','A','T','T'),
idPBOD = MAGIC4BE('P','B','O','D'),
idSBOD = MAGIC4BE('S','B','O','D'),
};
uint32be signature; // IFF chunk name
uint32be chunksize; // chunk size without header
};
MPT_BINARY_STRUCT(OktIffChunk, 8)
struct OktSample
{
char name[20];
uint32be length; // length in bytes
uint16be loopStart; // *2 for real value
uint16be loopLength; // ditto
uint16be volume; // default volume
uint16be type; // 7-/8-bit sample
};
MPT_BINARY_STRUCT(OktSample, 32)
// Parse the sample header block
static void ReadOKTSamples(FileReader &chunk, std::vector<bool> &sample7bit, CSoundFile &sndFile)
{
sndFile.m_nSamples = std::min<SAMPLEINDEX>(static_cast<SAMPLEINDEX>(chunk.BytesLeft() / sizeof(OktSample)), MAX_SAMPLES - 1u);
sample7bit.resize(sndFile.GetNumSamples());
for(SAMPLEINDEX smp = 1; smp <= sndFile.GetNumSamples(); smp++)
{
ModSample &mptSmp = sndFile.GetSample(smp);
OktSample oktSmp;
chunk.ReadStruct(oktSmp);
oktSmp.length = oktSmp.length;
oktSmp.loopStart = oktSmp.loopStart * 2;
oktSmp.loopLength = oktSmp.loopLength * 2;
oktSmp.volume = oktSmp.volume;
oktSmp.type = oktSmp.type;
mptSmp.Initialize();
mpt::String::Read<mpt::String::maybeNullTerminated>(sndFile.m_szNames[smp], oktSmp.name);
mptSmp.nC5Speed = 8287;
mptSmp.nGlobalVol = 64;
mptSmp.nVolume = MIN(oktSmp.volume, 64) * 4;
mptSmp.nLength = oktSmp.length & ~1; // round down
// parse loops
if (oktSmp.loopLength > 2 && static_cast<SmpLength>(oktSmp.loopStart) + static_cast<SmpLength>(oktSmp.loopLength) <= mptSmp.nLength)
{
mptSmp.nSustainStart = oktSmp.loopStart;
mptSmp.nSustainEnd = oktSmp.loopStart + oktSmp.loopLength;
if (mptSmp.nSustainStart < mptSmp.nLength && mptSmp.nSustainEnd <= mptSmp.nLength)
mptSmp.uFlags |= CHN_SUSTAINLOOP;
else
mptSmp.nSustainStart = mptSmp.nSustainEnd = 0;
}
sample7bit[smp - 1] = (oktSmp.type == 0 || oktSmp.type == 2);
}
}
// Parse a pattern block
static void ReadOKTPattern(FileReader &chunk, PATTERNINDEX nPat, CSoundFile &sndFile)
{
if(!chunk.CanRead(2))
{
return;
}
ROWINDEX rows = Clamp(static_cast<ROWINDEX>(chunk.ReadUint16BE()), ROWINDEX(1), MAX_PATTERN_ROWS);
if(!sndFile.Patterns.Insert(nPat, rows))
{
return;
}
const CHANNELINDEX chns = sndFile.GetNumChannels();
for(ROWINDEX row = 0; row < rows; row++)
{
ModCommand *m = sndFile.Patterns[nPat].GetRow(row);
for(CHANNELINDEX chn = 0; chn < chns; chn++, m++)
{
uint8 note = chunk.ReadUint8();
uint8 instr = chunk.ReadUint8();
uint8 effect = chunk.ReadUint8();
m->param = chunk.ReadUint8();
if(note > 0 && note <= 36)
{
m->note = note + 48;
m->instr = instr + 1;
} else
{
m->instr = 0;
}
switch(effect)
{
case 0: // Nothing
m->param = 0;
break;
case 1: // 1 Portamento Down (Period)
m->command = CMD_PORTAMENTOUP;
m->param &= 0x0F;
break;
case 2: // 2 Portamento Up (Period)
m->command = CMD_PORTAMENTODOWN;
m->param &= 0x0F;
break;
#if 0
/* these aren't like Jxx: "down" means to *subtract* the offset from the note.
For now I'm going to leave these unimplemented. */
case 10: // A Arpeggio 1 (down, orig, up)
case 11: // B Arpeggio 2 (orig, up, orig, down)
if (m->param)
m->command = CMD_ARPEGGIO;
break;
#endif
// This one is close enough to "standard" arpeggio -- I think!
case 12: // C Arpeggio 3 (up, up, orig)
if (m->param)
m->command = CMD_ARPEGGIO;
break;
case 13: // D Slide Down (Notes)
if (m->param)
{
m->command = CMD_NOTESLIDEDOWN;
m->param = 0x10 | MIN(0x0F, m->param);
}
break;
case 30: // U Slide Up (Notes)
if (m->param)
{
m->command = CMD_NOTESLIDEUP;
m->param = 0x10 | MIN(0x0F, m->param);
}
break;
/* We don't have fine note slide, but this is supposed to happen once
per row. Sliding every 5 (non-note) ticks kind of works (at least at
speed 6), but implementing fine slides would of course be better. */
case 21: // L Slide Down Once (Notes)
if (m->param)
{
m->command = CMD_NOTESLIDEDOWN;
m->param = 0x50 | MIN(0x0F, m->param);
}
break;
case 17: // H Slide Up Once (Notes)
if (m->param)
{
m->command = CMD_NOTESLIDEUP;
m->param = 0x50 | MIN(0x0F, m->param);
}
break;
case 15: // F Set Filter <>00:ON
// Not implemented, but let's import it anyway...
m->command = CMD_MODCMDEX;
m->param = !!m->param;
break;
case 25: // P Pos Jump
m->command = CMD_POSITIONJUMP;
break;
case 27: // R Release sample (apparently not listed in the help!)
m->Clear();
m->note = NOTE_KEYOFF;
break;
case 28: // S Speed
m->command = CMD_SPEED; // or tempo?
break;
case 31: // V Volume
m->command = CMD_VOLUMESLIDE;
switch (m->param >> 4)
{
case 4:
if (m->param != 0x40)
{
m->param &= 0x0F; // D0x
break;
}
// 0x40 is set volume -- fall through
MPT_FALLTHROUGH;
case 0: case 1: case 2: case 3:
m->volcmd = VOLCMD_VOLUME;
m->vol = m->param;
m->command = CMD_NONE;
m->param = 0;
break;
case 5:
m->param = (m->param & 0x0F) << 4; // Dx0
break;
case 6:
m->param = 0xF0 | MIN(m->param & 0x0F, 0x0E); // DFx
break;
case 7:
m->param = (MIN(m->param & 0x0F, 0x0E) << 4) | 0x0F; // DxF
break;
default:
// Junk.
m->command = CMD_NONE;
m->param = 0;
break;
}
break;
#if 0
case 24: // O Old Volume (???)
m->command = CMD_VOLUMESLIDE;
m->param = 0;
break;
#endif
default:
m->command = m->param = 0;
break;
}
}
}
}
CSoundFile::ProbeResult CSoundFile::ProbeFileHeaderOKT(MemoryFileReader file, const uint64 *pfilesize)
{
if(!file.CanRead(8))
{
return ProbeWantMoreData;
}
if(!file.ReadMagic("OKTASONG"))
{
return ProbeFailure;
}
OktIffChunk iffHead;
if(!file.ReadStruct(iffHead))
{
return ProbeWantMoreData;
}
if(iffHead.chunksize == 0)
{
return ProbeFailure;
}
if((iffHead.signature & 0x7f7f7f7fu) != iffHead.signature) // ASCII?
{
return ProbeFailure;
}
MPT_UNREFERENCED_PARAMETER(pfilesize);
return ProbeSuccess;
}
bool CSoundFile::ReadOKT(FileReader &file, ModLoadingFlags loadFlags)
{
file.Rewind();
if(!file.ReadMagic("OKTASONG"))
{
return false;
}
// prepare some arrays to store offsets etc.
std::vector<FileReader> patternChunks;
std::vector<FileReader> sampleChunks;
std::vector<bool> sample7bit; // 7-/8-bit sample
ORDERINDEX numOrders = 0;
InitializeGlobals(MOD_TYPE_OKT);
// Go through IFF chunks...
while(file.CanRead(sizeof(OktIffChunk)))
{
OktIffChunk iffHead;
if(!file.ReadStruct(iffHead))
{
break;
}
FileReader chunk = file.ReadChunk(iffHead.chunksize);
if(!chunk.IsValid())
{
break;
}
switch(iffHead.signature)
{
case OktIffChunk::idCMOD:
// Read that weird channel setup table
if(m_nChannels > 0 || chunk.GetLength() < 8)
{
break;
}
for(CHANNELINDEX chn = 0; chn < 4; chn++)
{
uint8 ch1 = chunk.ReadUint8(), ch2 = chunk.ReadUint8();
if(ch1 || ch2)
{
ChnSettings[m_nChannels].Reset();
ChnSettings[m_nChannels++].nPan = (((chn & 3) == 1) || ((chn & 3) == 2)) ? 0xC0 : 0x40;
}
ChnSettings[m_nChannels].Reset();
ChnSettings[m_nChannels++].nPan = (((chn & 3) == 1) || ((chn & 3) == 2)) ? 0xC0 : 0x40;
}
if(loadFlags == onlyVerifyHeader)
{
return true;
}
break;
case OktIffChunk::idSAMP:
// Convert sample headers
if(m_nSamples > 0)
{
break;
}
ReadOKTSamples(chunk, sample7bit, *this);
break;
case OktIffChunk::idSPEE:
// Read default speed
if(chunk.GetLength() >= 2)
{
m_nDefaultSpeed = Clamp(chunk.ReadUint16BE(), uint16(1), uint16(255));
}
break;
case OktIffChunk::idSLEN:
// Number of patterns, we don't need this.
break;
case OktIffChunk::idPLEN:
// Read number of valid orders
if(chunk.GetLength() >= 2)
{
numOrders = chunk.ReadUint16BE();
}
break;
case OktIffChunk::idPATT:
// Read the orderlist
ReadOrderFromFile<uint8>(Order(), chunk, chunk.GetLength(), 0xFF, 0xFE);
break;
case OktIffChunk::idPBOD:
// Don't read patterns for now, as the number of channels might be unknown at this point.
if(patternChunks.size() < 256)
{
patternChunks.push_back(chunk);
}
break;
case OktIffChunk::idSBOD:
// Sample data - same as with patterns, as we need to know the sample format / length
if(sampleChunks.size() < MAX_SAMPLES - 1 && chunk.GetLength() > 0)
{
sampleChunks.push_back(chunk);
}
break;
}
}
// If there wasn't even a CMOD chunk, we can't really load this.
if(m_nChannels == 0)
return false;
m_nDefaultTempo.Set(125);
m_nDefaultGlobalVolume = MAX_GLOBAL_VOLUME;
m_nSamplePreAmp = m_nVSTiVolume = 48;
m_nMinPeriod = 0x71 * 4;
m_nMaxPeriod = 0x358 * 4;
// Fix orderlist
Order().resize(numOrders);
// Read patterns
if(loadFlags & loadPatternData)
{
Patterns.ResizeArray(static_cast<PATTERNINDEX>(patternChunks.size()));
for(PATTERNINDEX pat = 0; pat < patternChunks.size(); pat++)
{
if(patternChunks[pat].GetLength() > 0)
ReadOKTPattern(patternChunks[pat], pat, *this);
else
Patterns.Insert(pat, 64); // Invent empty pattern
}
}
// Read samples
size_t fileSmp = 0;
for(SAMPLEINDEX smp = 1; smp < m_nSamples; smp++)
{
if(fileSmp >= sampleChunks.size() || !(loadFlags & loadSampleData))
break;
ModSample &mptSample = Samples[smp];
if(mptSample.nLength == 0)
continue;
// Weird stuff?
LimitMax(mptSample.nLength, mpt::saturate_cast<SmpLength>(sampleChunks[fileSmp].GetLength()));
SampleIO(
SampleIO::_8bit,
SampleIO::mono,
SampleIO::bigEndian,
sample7bit[smp - 1] ? SampleIO::PCM7to8 : SampleIO::signedPCM)
.ReadSample(mptSample, sampleChunks[fileSmp]);
fileSmp++;
}
return true;
}
OPENMPT_NAMESPACE_END
| 23.634956 | 134 | 0.635215 | [
"vector"
] |
4acbfa7cedb55147b3ccd3fc1ccaf0b5aa800f17 | 7,384 | cc | C++ | tensorflow/contrib/rnn/ops/lstm_ops_test.cc | jdehotin/TensorFlow | a6c5f8e4e013e54fed8dfcf49fb6de365f018022 | [
"Apache-2.0"
] | 1 | 2021-06-10T23:59:44.000Z | 2021-06-10T23:59:44.000Z | tensorflow/contrib/rnn/ops/lstm_ops_test.cc | jdehotin/TensorFlow | a6c5f8e4e013e54fed8dfcf49fb6de365f018022 | [
"Apache-2.0"
] | null | null | null | tensorflow/contrib/rnn/ops/lstm_ops_test.cc | jdehotin/TensorFlow | a6c5f8e4e013e54fed8dfcf49fb6de365f018022 | [
"Apache-2.0"
] | 1 | 2020-07-09T22:02:18.000Z | 2020-07-09T22:02:18.000Z | /* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (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 "tensorflow/c/c_api.h"
#include "tensorflow/core/framework/node_def_builder.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference_testutil.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
class LSTMOpsTest : public ::testing::Test {
public:
static void SetUpTestCase() {
TF_Status* status = TF_NewStatus();
auto* lib = TF_LoadLibrary(
"tensorflow/contrib/rnn/python/ops/_lstm_ops.so", status);
CHECK_EQ(TF_OK, TF_GetCode(status));
TF_DeleteLibraryHandle(lib);
TF_DeleteStatus(status);
}
};
static string JoinedCopies(string s, int copies) {
string res;
for (int i = 0; i < copies; ++i) {
strings::StrAppend(&res, i > 0 ? ";" : "", s);
}
return res;
}
TEST_F(LSTMOpsTest, LSTMBlockCell_ShapeFn) {
ShapeInferenceTestOp op("LSTMBlockCell");
// Last 6 inputs don't affect shape inference.
string input_suffix = strings::StrCat(";", JoinedCopies("?", 6));
// Rank checks.
INFER_ERROR("must be rank 2", op, "[?];?" + input_suffix);
INFER_ERROR("must be rank 2", op, "?;[?]" + input_suffix);
// Output
INFER_OK(op, "?;?" + input_suffix, JoinedCopies("[?,?]", 7));
INFER_OK(op, "[?,?];[?,?]" + input_suffix, JoinedCopies("[d0_0,d1_1]", 7));
}
TEST_F(LSTMOpsTest, LSTMBlockCellGrad_ShapeFn) {
ShapeInferenceTestOp op("LSTMBlockCellGrad");
// Last 14 inputs don't affect shape inference.
string input_suffix = strings::StrCat(";", JoinedCopies("?", 14));
// Rank checks.
INFER_ERROR("must be rank 2", op, "[?];?" + input_suffix);
INFER_ERROR("must be rank 2", op, "?;[?]" + input_suffix);
// Output
INFER_OK(op, "?;?" + input_suffix, "[?,?];[?,?];[?];[?];[?]");
INFER_OK(op, "[?,?];[?,?]" + input_suffix,
"[d0_0,d1_1];[d0_0,?];[d1_1];[d1_1];[d1_1]");
INFER_OK(op, "[1,2];[3,4]" + input_suffix,
"[d0_0,d1_1];[d0_0,16];[d1_1];[d1_1];[d1_1]");
}
TEST_F(LSTMOpsTest, BlockLSTM_ShapeFn) {
ShapeInferenceTestOp op("BlockLSTM");
auto set_op = [&op](int max_len) {
std::vector<NodeDefBuilder::NodeOut> x_list;
for (int i = 0; i < max_len; ++i) x_list.emplace_back("a", 0, DT_FLOAT);
TF_ASSERT_OK(NodeDefBuilder("test", "BlockLSTM")
.Input({"seq_len_max", 0, DT_INT64})
.Input(x_list)
.Input({"cs_prev", 0, DT_FLOAT})
.Input({"h_prev", 0, DT_FLOAT})
.Input({"w", 0, DT_FLOAT})
.Input({"wci", 0, DT_FLOAT})
.Input({"wcf", 0, DT_FLOAT})
.Input({"wco", 0, DT_FLOAT})
.Input({"b", 0, DT_FLOAT})
.Attr("max_len", max_len)
.Finalize(&op.node_def));
};
for (int max_len = 1; max_len < 11; max_len += 3) {
set_op(max_len);
int num_in = max_len + 8;
int num_out = max_len * 7;
// Middle inputs don't affect shape inference.
string infix = ";" + JoinedCopies("?", num_in - 3) + ";";
// Rank checks.
INFER_ERROR("must be rank 2", op, "?;[?]" + infix + "?");
INFER_ERROR("must be rank 1", op, "?;?" + infix + "[?,?]");
// Output
INFER_OK(op, "?;?" + infix + "?", JoinedCopies("[?,?]", num_out));
INFER_OK(op, "?;[?,?]" + infix + "?", JoinedCopies("[d1_0,?]", num_out));
INFER_OK(op, "?;[?,?]" + infix + "[?]", JoinedCopies("[d1_0,?]", num_out));
INFER_OK(op, "?;[?,?]" + infix + "[20]", JoinedCopies("[d1_0,5]", num_out));
// cell_size must be divisible by 4.
INFER_ERROR("must be evenly divisible", op, "?;?" + infix + "[11]");
}
}
TEST_F(LSTMOpsTest, BlockLSTMGrad_ShapeFn) {
ShapeInferenceTestOp op("BlockLSTMGrad");
auto set_op = [&op](int max_len) {
std::vector<NodeDefBuilder::NodeOut> x_list;
for (int i = 0; i < max_len; ++i) x_list.emplace_back("a", 0, DT_FLOAT);
TF_ASSERT_OK(NodeDefBuilder("test", "BlockLSTMGrad")
.Input({"seq_len_max", 0, DT_INT64})
.Input(x_list)
.Input({"cs_prev", 0, DT_FLOAT})
.Input({"h_prev", 0, DT_FLOAT})
.Input({"w", 0, DT_FLOAT})
.Input({"wci", 0, DT_FLOAT})
.Input({"wcf", 0, DT_FLOAT})
.Input({"wco", 0, DT_FLOAT})
.Input({"b", 0, DT_FLOAT})
.Input(x_list)
.Input(x_list)
.Input(x_list)
.Input(x_list)
.Input(x_list)
.Input(x_list)
.Input(x_list)
.Input(x_list)
.Input(x_list)
.Attr("max_len", max_len)
.Finalize(&op.node_def));
};
for (int max_len = 1; max_len < 11; max_len += 3) {
set_op(max_len);
int num_in = max_len * 10 + 8;
int num_out = max_len + 7;
// Last inputs don't affect shape inference.
string suffix = ";" + JoinedCopies("?", 9 * max_len);
// Rank check for x
string invalid_x = JoinedCopies("[?]", max_len);
INFER_ERROR("must be rank 2", op,
"?;" + invalid_x + ";?;?;?;?;?;?;?" + suffix);
// Rank checks for cs_prev through b.
string unknown_x = JoinedCopies("?", max_len);
INFER_ERROR("must be rank 2", op,
"?;" + unknown_x + ";[1];?;?;?;?;?;?" + suffix);
INFER_ERROR("must be rank 2", op,
"?;" + unknown_x + ";?;[1];?;?;?;?;?" + suffix);
INFER_ERROR("must be rank 2", op,
"?;" + unknown_x + ";?;?;[1];?;?;?;?" + suffix);
INFER_ERROR("must be rank 1", op,
"?;" + unknown_x + ";?;?;?;[1,?];?;?;?" + suffix);
INFER_ERROR("must be rank 1", op,
"?;" + unknown_x + ";?;?;?;?;[1,?];?;?" + suffix);
INFER_ERROR("must be rank 1", op,
"?;" + unknown_x + ";?;?;?;?;?;[1,?];?" + suffix);
INFER_ERROR("must be rank 1", op,
"?;" + unknown_x + ";?;?;?;?;?;?;[1,?]" + suffix);
// Output with all input knowns makes known rank outputs.
INFER_OK(op, JoinedCopies("?", num_in),
JoinedCopies("[?,?]", num_out - 4) + ";" + JoinedCopies("[?]", 4));
// Output with copies input shapes to output.
string input = strings::StrCat("?;", JoinedCopies("[?,?]", max_len + 3),
";", JoinedCopies("[?]", 4), suffix);
string expected = JoinedCopies("in1", max_len); // copies of x;
for (int i = max_len; i < num_out; ++i) {
strings::StrAppend(&expected, ";in", (i + 1));
}
INFER_OK(op, input, expected);
}
}
} // namespace tensorflow
| 37.482234 | 80 | 0.540628 | [
"shape",
"vector"
] |
4ad6d2b07b4a87f827a7425031ec935611e61b42 | 1,099 | cpp | C++ | client/InputAxis.cpp | KnuckStudio/RPG | 8abc4582be879f0a51506e89f6d13b2793a73d92 | [
"Apache-2.0"
] | null | null | null | client/InputAxis.cpp | KnuckStudio/RPG | 8abc4582be879f0a51506e89f6d13b2793a73d92 | [
"Apache-2.0"
] | null | null | null | client/InputAxis.cpp | KnuckStudio/RPG | 8abc4582be879f0a51506e89f6d13b2793a73d92 | [
"Apache-2.0"
] | null | null | null | #include "InputAxis.h"
#include "Math.h"
InputAxis::InputAxis(const std::vector<KeyMapping>& mappings) :
m_mappings(mappings),
m_sensitivity(1.0f),
m_gravity(1.0f),
m_value(0.0f),
m_range(-1.0f, 1.0f),
m_defaultValue(0.0f)
{
}
InputAxis::~InputAxis()
{
}
const std::vector<InputAxis::KeyMapping>& InputAxis::getMappings() const
{
return m_mappings;
}
void InputAxis::setSensitivity(float sensitivity)
{
m_sensitivity = sensitivity;
}
float InputAxis::getSensitivity() const
{
return m_sensitivity;
}
void InputAxis::setGravity(float gravity)
{
m_gravity = gravity;
}
float InputAxis::getGravity() const
{
return m_gravity;
}
void InputAxis::setValue(float value)
{
m_value = value;
}
float InputAxis::getValue() const
{
return m_value;
}
void InputAxis::setRange(const sf::Vector2f & range)
{
m_range = range;
m_value = math::clamp(m_value, range.x, range.y);
}
sf::Vector2f InputAxis::getRange() const
{
return m_range;
}
void InputAxis::setDefaultValue(float value)
{
m_defaultValue = value;
}
float InputAxis::getDefaultValue() const
{
return m_defaultValue;
}
| 14.851351 | 72 | 0.726115 | [
"vector"
] |
4adc7b23f275178c829f572305db7318f5e31e26 | 1,243 | cpp | C++ | tests/WordSearchIITest.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 43 | 2015-10-10T12:59:52.000Z | 2018-07-11T18:07:00.000Z | tests/WordSearchIITest.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | null | null | null | tests/WordSearchIITest.cpp | yanzhe-chen/LeetCode | d82f0b9721ea613ab216c78e7286671d0e9e4187 | [
"MIT"
] | 11 | 2015-10-10T14:41:11.000Z | 2018-07-28T06:03:16.000Z | #include "catch.hpp"
#include "WordSearchII.hpp"
using namespace std;
TEST_CASE("Word Search II") {
WordSearchII s;
SECTION("Sample test") {
vector<string> words{"oath", "pea", "eat", "rain"};
vector<vector<char>> board{
{'o', 'a', 'a', 'n'},
{'e', 't', 'a', 'e'},
{'i', 'h', 'k', 'r'},
{'i', 'f', 'l', 'v'}
};
vector<string> expected{"eat", "oath"};
vector<string> result = s.findWords(board, words);
REQUIRE(expected.size() == result.size());
for (int i = 0; i < result.size(); i++) {
REQUIRE_FALSE(find(expected.begin(), expected.end(),
result[i]) == expected.end());
}
}
SECTION("Duplicates") {
vector<string> words{"a"};
vector<vector<char>> board{
{'a', 'a'}
};
vector<string> expected{"a"};
vector<string> result = s.findWords(board, words);
REQUIRE(expected.size() == result.size());
for (int i = 0; i < result.size(); i++) {
REQUIRE_FALSE(find(expected.begin(), expected.end(),
result[i]) == expected.end());
}
}
}
| 30.317073 | 64 | 0.459372 | [
"vector"
] |
4adf47bab612271a6df28e5fa16ed566f4ebf5c0 | 1,614 | cpp | C++ | projects/USDExporter/source/CalcSurfaceArea.cpp | ft-lab/Shade3D_USDExporter | 981494219a510d679369726229decbb9c7dac36e | [
"MIT"
] | 5 | 2019-10-13T00:53:45.000Z | 2021-02-15T15:43:39.000Z | projects/USDExporter/source/CalcSurfaceArea.cpp | ft-lab/Shade3D_USDExporter | 981494219a510d679369726229decbb9c7dac36e | [
"MIT"
] | null | null | null | projects/USDExporter/source/CalcSurfaceArea.cpp | ft-lab/Shade3D_USDExporter | 981494219a510d679369726229decbb9c7dac36e | [
"MIT"
] | 1 | 2021-08-13T10:54:47.000Z | 2021-08-13T10:54:47.000Z | /**
* Meshの表面積を計算.
*/
#include "CalcSurfaceArea.h"
#include "MathUtil.h"
namespace
{
/**
* 多角形の三角形分割クラス.
*/
std::vector<int> m_triangleIndex;
class CDivideTrianglesOutput : public sxsdk::shade_interface::output_function_class {
private:
public:
virtual void output (int i0 , int i1 , int i2 , int i3) {
const int offset = m_triangleIndex.size();
m_triangleIndex.resize(offset + 3);
m_triangleIndex[offset + 0] = i0;
m_triangleIndex[offset + 1] = i1;
m_triangleIndex[offset + 2] = i2;
}
};
}
double MathUtil::calcSurfaceArea (sxsdk::scene_interface* scene, const CNodeMeshData& meshD)
{
double areaV = 0.0;
::m_triangleIndex.clear();
::CDivideTrianglesOutput divC;
int iPos = 0;
std::vector<sxsdk::vec3> vertices;
vertices.resize(50);
for (size_t loop = 0; loop < meshD.faceVertexCounts.size(); ++loop) {
// 面の頂点座標を取得.
const int vCou = meshD.faceVertexCounts[loop];
if (vCou < 3) continue;
if (vCou >= (int)vertices.size()) {
vertices.resize(vCou + 16);
}
for (int i = 0; i < vCou; ++i) {
vertices[i] = meshD.vertices[ meshD.faceIndices[i + iPos] ];
}
if (vCou == 3) {
areaV += MathUtil::calcTriangleArea(vertices[0], vertices[1], vertices[2]);
continue;
}
// 多角形を三角形分割.
scene->divide_polygon(divC, vCou, &(vertices[0]), true);
const int triCou = ::m_triangleIndex.size() / 3;
for (int i = 0; i < ::m_triangleIndex.size(); i += 3) {
areaV += MathUtil::calcTriangleArea(vertices[ ::m_triangleIndex[i + 0] ], vertices[ ::m_triangleIndex[i + 1] ], vertices[ ::m_triangleIndex[i + 2] ]);
}
iPos += vCou;
}
return areaV;
}
| 24.830769 | 153 | 0.653036 | [
"vector"
] |
4adf94ca59fa33c584876078d246beaa82fb0a0c | 9,376 | cpp | C++ | src/runtime.cpp | viroulep/replay_tool | 6eeae5fee1dfc2fe1a96977aa16e06ecdf8fa2e1 | [
"MIT"
] | null | null | null | src/runtime.cpp | viroulep/replay_tool | 6eeae5fee1dfc2fe1a96977aa16e06ecdf8fa2e1 | [
"MIT"
] | null | null | null | src/runtime.cpp | viroulep/replay_tool | 6eeae5fee1dfc2fe1a96977aa16e06ecdf8fa2e1 | [
"MIT"
] | null | null | null | #include "runtime.hpp"
#include "KernelsBlas.hpp"
#include "KernelsBandwidth.hpp"
#include <pthread.h>
using namespace std;
map<string, KernelFunction> Runtime::kernels_;
set<string> Runtime::watchedKernels_;
void dummy(const vector<Param *> *)
{}
uint64_t inline getCycles() {
uint64_t low, high;
asm volatile("rdtsc" : "=a" (low), "=d" (high));
return low | (high << 32);
}
void Executable::operator()() const {
Callback(FunctionPtr);
}
void AbstractWatcher::headers(list<AbstractWatcher *> watcherList)
{
if (watcherList.empty())
return;
cout << "Exp total_cores kernel thread";
for (auto &watcher : watcherList)
cout << watcher->dataHeader();
cout << "\n";
}
void AbstractWatcher::summarize(const string &prefix, int totalThread, int tId, list<AbstractWatcher *> watcherList)
{
if (watcherList.empty())
return;
auto keys = watcherList.front()->keys();
for (const string &kernelName : keys) {
for (int i = 0; i < watcherList.front()->size(); i++) {
cout << prefix << " " << totalThread << " " << kernelName << " " << tId << " ";
for (auto &watcher : watcherList) {
cout << watcher->dataEntry(kernelName, i);
}
cout << "\n";
}
}
}
void CycleWatcher::before()
{
if (start_) {
cyclesBefore_ = getCycles() - start_;
} else {
start_ = getCycles();
}
}
void CycleWatcher::after(const string &name)
{
watchMap_[name].push_back(getCycles() - cyclesBefore_);
}
void ArraySizeWatcher::before()
{}
void ArraySizeWatcher::after(const string &name)
{
watchMap_[name].push_back(size_);
}
void TimeWatcher::before()
{
timeBefore_ = TimeClock::now();
}
void TimeWatcher::after(const string &name)
{
watchMap_[name].push_back(TimeClock::now() - timeBefore_);
}
void SyncWatcher::before()
{
begin = getCycles();
}
void SyncWatcher::after(const string &name)
{
watchMap_[name].push_back(begin);
}
void PerfCtrWatcher::before()
{
if (!started_) {
if (PAPI_start_counters(events.data(), numEvents) != PAPI_OK) {
cerr << "Before::Can't read PAPI counters, exiting\n";
}
started_ = true;
} else {
if (PAPI_read_counters(valuesBefore_.data(), numEvents) != PAPI_OK) {
cerr << "Before::Can't read PAPI counters, ignoring and continuing\n";
}
}
}
void PerfCtrWatcher::after(const string &name)
{
PerfRecordValue now;
//if (PAPI_stop_counters(now.data(), numEvents) != PAPI_OK) {
//cerr << "After::Can't read PAPI counters, exiting\n";
//exit(EXIT_FAILURE);
//}
if (PAPI_read_counters(now.data(), numEvents) != PAPI_OK) {
cerr << "After::Can't read PAPI counters, ignoring and continuing\n";
}
for (int i = 0; i < numEvents; i++)
now[i] -= valuesBefore_[i];
watchMap_[name].push_back(now);
}
string CycleWatcher::dataHeader() const
{
return " cycle";
}
string TimeWatcher::dataHeader() const
{
return " time-ms";
}
string ArraySizeWatcher::dataHeader() const
{
return " size";
}
string PerfCtrWatcher::dataHeader() const
{
stringstream ss;
for (const string &name : eventsNames)
ss << " " << name;
return ss.str();
}
string FlopsWatcher::dataHeader() const
{
return " gflops";
}
string SyncWatcher::dataHeader() const
{
return " cycle-sync";
}
string PerfCtrWatcher::dataEntry(const string &name, int iteration) const
{
stringstream ss;
auto &entry = watchMap_.at(name)[iteration];
for (int i = 0; i < numEvents; i++)
ss << " " << entry[i];
return ss.str();
}
PerfCtrWatcher::PerfCtrWatcher(int threadId,
vector<string> &eventsVector) : Watcher(threadId), numEvents(eventsVector.size())
{
if (PAPI_library_init(PAPI_VER_CURRENT) != PAPI_VER_CURRENT) {
cerr << "Can't init papi\n";
exit(EXIT_FAILURE);
}
//cerr << this_thread::get_id();
if (PAPI_thread_init((unsigned long (*)())this_thread::get_id) != PAPI_OK) {
cerr << "Can't init multithread support in papi\n";
exit(EXIT_FAILURE);
}
if (eventsVector.size() > events.size()) {
cerr << "Too many events!";
exit(EXIT_FAILURE);
}
int i = 0;
for (string &s : eventsVector) {
int eventCode;
if (PAPI_event_name_to_code(const_cast<char *>(s.c_str()), &eventCode) != PAPI_OK) {
cerr << "Couldn't find counter '" << s << "', exiting\n";
exit(EXIT_FAILURE);
}
events[i] = eventCode;
eventsNames[i++] = s;
}
}
string ArraySizeWatcher::dataEntry(const std::string &name, int iteration) const
{
std::stringstream ss;
ss << " " << (watchMap_.at(name)[iteration]*8);
return ss.str();
}
string SyncWatcher::dataEntry(const std::string &name, int iteration) const
{
std::stringstream ss;
ss << " " << watchMap_.at(name)[iteration];
return ss.str();
}
string CycleWatcher::dataEntry(const std::string &name, int iteration) const
{
std::stringstream ss;
ss << " " << watchMap_.at(name)[iteration];
return ss.str();
}
string TimeWatcher::dataEntry(const string &name, int iteration) const
{
stringstream ss;
ss << " " << chrono::duration_cast<chrono::duration<double, milli>>(watchMap_.at(name)[iteration]).count();
return ss.str();
}
string FlopsWatcher::dataEntry(const string &name, int iteration) const
{
stringstream ss;
ss << " " << (1e-9*FLOPS)/watchMap_.at(name)[iteration].count();
return ss.str();
}
void Runtime::work(int threadId) {
//FIXME some check on boundaries
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(threadId, &cpuset);
int rc = pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
if (rc != 0) {
cerr << "Error calling pthread_setaffinity_np: " << rc << "\n";
cerr << "With thread id " << threadId << "\n";
cerr << EFAULT << "\n";
cerr << EINVAL << "\n";
cerr << ESRCH << "\n";
}
Thread &thread = threads[threadId];
auto &myQueue = thread.q;
while (thread.go || !myQueue.empty()) {
if (!myQueue.empty()) {
unique_lock<mutex> guard(thread.m);
Task *task = myQueue.front();
myQueue.pop_front();
guard.unlock();
if (task->sync) {
// This gives roughly <200 cycles between the start of two synchronous tasks
int localCurrent = current.load(std::memory_order_acquire);
int position = there[localCurrent]++;
if (position + 1 == MAX_THREADS) {
current.store(1 - current);
there[current] = 0;
go[current] = 0;
go[localCurrent].store(1, std::memory_order_release);
} else {
while (!go[localCurrent].load(std::memory_order_acquire))
;
}
#if 0
// This solution through condition variable gives bad synchronous start time:
// roughly 100000 cycles between starting tasks.
//
// 'there' is an atomic, ++ goes through fetch_add
int position = there++;
if (position + 1 == max) {
there = 0;
cond_.notify_all();
} else {
unique_lock<mutex> lock(mutex_);
cond_.wait(lock);
}
#endif
}
for (int i = 0; i < task->repeat; i++) {
if (task->kernelName == "dpotrf") {
// FIXME: beurk
make_symmetric_positive_definite(task->kernelParams);
}
if (task->flush) {
flush_cache();
}
for (AbstractWatcher *w : thread.watchers_) {
if (task->kernelName != "dummy" && task->kernelName != "init_blas_bloc" && task->kernelName != "init_symmetric" && task->kernelName != "init_array")
w->before();
}
//TODO flush
if (kernels_.find(task->kernelName) != kernels_.end()) {
kernels_[task->kernelName](task->kernelParams);
} else {
cout << "Can't find the kernel " << task->kernelName << ", fatal error\n";
exit(EXIT_FAILURE);
}
for (AbstractWatcher *w : thread.watchers_) {
if (task->kernelName != "dummy" && task->kernelName != "init_blas_bloc" && task->kernelName != "init_symmetric" && task->kernelName != "init_array")
w->after(task->name);
}
}
delete task;
}
//this_thread::sleep_for(chrono::seconds(1));
}
}
void Runtime::run(int thread, Task *code)
{
if (threads.count(thread) != 1) {
cerr << "Trying to run on a non declared thread (" << thread << "), aborting\n";
exit(EXIT_FAILURE);
}
Thread &t = threads[thread];
lock_guard<mutex> guard(t.m);
t.q.push_back(code);
}
void Runtime::done()
{
// Two separate loop to avoid thread spinning on 'go' while joining!
for (auto &entry : threads)
entry.second.go = 0;
for (auto &entry : threads) {
std::thread &t = entry.second.t;
t.join();
}
AbstractWatcher::headers(threads.begin()->second.watchers_);
for (auto &entry : threads) {
AbstractWatcher::summarize(name_, MAX_THREADS, entry.first, entry.second.watchers_);
for (AbstractWatcher *w : entry.second.watchers_)
delete w;
}
}
void Runtime::initThreads(const set<int> &physIds)
{
Runtime::kernels_.insert(make_pair("dummy", dummy));
for (int cpuId : physIds) {
Thread &t = threads[cpuId];
t.q.push_back(new Task("dummy", nullptr, true, false, 1, "start_sync"));
}
for (int cpuId : physIds)
threads[cpuId].t = thread([this, cpuId] {work(cpuId);});
}
Runtime::Runtime(const set<int> &physIds, const string &name) : MAX_THREADS(physIds.size()), name_(name)
{
initThreads(physIds);
}
| 26.411268 | 158 | 0.623827 | [
"vector"
] |
4adfd4a4cfb2b7cbda04978038614d34d482eefe | 1,083 | cpp | C++ | src/JSPromise.cpp | Superxwolf/JavascriptCorePP | f5e336b98284cd21fa48b03304438d6b3a55446b | [
"MIT"
] | 5 | 2021-03-22T09:05:37.000Z | 2021-12-12T22:39:52.000Z | src/JSPromise.cpp | Superxwolf/JavascriptCorePP | f5e336b98284cd21fa48b03304438d6b3a55446b | [
"MIT"
] | null | null | null | src/JSPromise.cpp | Superxwolf/JavascriptCorePP | f5e336b98284cd21fa48b03304438d6b3a55446b | [
"MIT"
] | 1 | 2021-02-15T06:04:25.000Z | 2021-02-15T06:04:25.000Z | #include "JavaScriptCorePP/JSPromise.h"
namespace JavaScriptCorePP
{
JSPromise::JSPromise(const JSContext& context, JSObjectRef promiseObj, JSObjectRef resolveFunc, JSObjectRef rejectFunc) :
_context(context), _promise(context, promiseObj), _resolve(context, resolveFunc), _reject(context, rejectFunc) {}
JSPromise::JSPromise(const JSContext& context, const JSObject& promiseObj, const JSFunction& resolveFunc, const JSFunction& rejectFunc) :
_context(context), _promise(promiseObj), _resolve(resolveFunc), _reject(rejectFunc) {}
JSValue JSPromise::Resolve() const
{
return _resolve.Call();
}
JSValue JSPromise::Reject() const
{
return _reject.Call();
}
JSValue JSPromise::Resolve(const std::vector<JSValue>& args) const
{
return _resolve.Call(args);
}
JSValue JSPromise::Reject(const std::vector<JSValue>& args) const
{
return _reject.Call(args);
}
JSObject JSPromise::GetPromise() const
{
return _promise;
}
JSFunction JSPromise::GetResolve() const
{
return _resolve;
}
JSFunction JSPromise::GetReject() const
{
return _reject;
}
} | 24.066667 | 138 | 0.748846 | [
"vector"
] |
4ae0bb1efacce4efd9b5aefd363380dda9820873 | 1,396 | cpp | C++ | Problems/Timus/1788_On_the_Benefits_of_Umbrellas/src/main.cpp | grand87/timus | 8edcae276ab74b68fff18da3722460f492534a8a | [
"MIT"
] | null | null | null | Problems/Timus/1788_On_the_Benefits_of_Umbrellas/src/main.cpp | grand87/timus | 8edcae276ab74b68fff18da3722460f492534a8a | [
"MIT"
] | 1 | 2019-05-09T19:17:00.000Z | 2019-05-09T19:17:00.000Z | Problems/Timus/1788_On_the_Benefits_of_Umbrellas/src/main.cpp | grand87/timus | 8edcae276ab74b68fff18da3722460f492534a8a | [
"MIT"
] | null | null | null | /*
* @author v.sharayenko (grand87@yandex.ru)
*/
#pragma comment(linker, "/STACK:16777216")
#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;
//#define ONLINE_JUDGE
typedef vector<size_t> VectorInt;
size_t getSumOfUpset(const VectorInt& upSets, size_t boys, size_t k)
{
size_t sum = 0;
for(size_t b = 0; b < boys; ++b)
sum += upSets[b] * k;
return sum;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "rt", stdin);
freopen("output.txt", "wt", stdout);
#endif
size_t girls = 0;
scanf("%d", &girls);
size_t boys = 0;
scanf("%d", &boys);
VectorInt girlUpset(girls);
VectorInt boyUpset(boys);
for(size_t i = 0; i < girls; ++i)
scanf("%d", &girlUpset[i]);
for(size_t i = 0; i < boys; ++i)
scanf("%d", &boyUpset[i]);
sort(girlUpset.begin(), girlUpset.end());
sort(boyUpset.begin(), boyUpset.end());
size_t minUpset = getSumOfUpset(girlUpset, girls, 1) + getSumOfUpset(boyUpset, boys, 0);
for(size_t g = 1; g <= girls; ++g)
{
if(g > boys)
break;
size_t gu = getSumOfUpset(girlUpset, girls - g, 1);
size_t bu = 0;
if(boys >= girls)
bu = getSumOfUpset(boyUpset, boys - g, g);
if(gu + bu < minUpset)
minUpset = gu + bu;
}
printf("%d", minUpset);
return 0;
}
| 19.942857 | 92 | 0.567335 | [
"vector"
] |
4ae641316737782c8ea81a2bd682df5d0e1a0abd | 5,037 | hpp | C++ | perftest/perf_test.hpp | kiwicom/catboost-cxx | 7ae872fe9418215b6592e1a947d1cd4bc5b10b3d | [
"MIT"
] | 5 | 2021-02-17T14:46:26.000Z | 2021-08-28T20:10:02.000Z | perftest/perf_test.hpp | kiwicom/catboost-cxx | 7ae872fe9418215b6592e1a947d1cd4bc5b10b3d | [
"MIT"
] | null | null | null | perftest/perf_test.hpp | kiwicom/catboost-cxx | 7ae872fe9418215b6592e1a947d1cd4bc5b10b3d | [
"MIT"
] | 3 | 2020-12-18T07:43:29.000Z | 2021-04-26T13:29:43.000Z | #pragma once
#include <sys/time.h>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
inline double ftime() {
struct timeval tv;
gettimeofday(&tv, nullptr);
return double(tv.tv_sec) + double(tv.tv_usec) / 1000000.0;
}
struct TestData {
std::vector<double> label;
std::vector<std::vector<float>> data;
std::vector<std::string> split_string(const std::string& s, const std::string& delimiter) {
std::vector<std::string> res;
size_t begin = 0;
for (;;) {
auto next = s.find(delimiter, begin);
if (next == std::string::npos) {
res.push_back(s.substr(begin, s.size() - begin));
return res;
}
res.push_back(s.substr(begin, next - begin));
begin = next + delimiter.size();
}
return res; // unreachable
}
double parse_double(const std::string& s) {
char* end = nullptr;
double res = std::strtod(s.data(), &end);
if (!end || end == s.data()) {
throw std::runtime_error("Can't parse float");
}
return res;
}
void load_tsv(const std::string& fnm) {
std::string line;
std::ifstream f{fnm};
if (!f.is_open()) {
throw std::runtime_error("Can't open file");
}
while (std::getline(f, line)) {
// Parse line:
auto sline = split_string(line.substr(0, line.size() - 1), "\t");
if (sline.size() < 2) {
throw std::runtime_error("Invalid dataset");
}
label.push_back(parse_double(sline[0]));
std::vector<float> x;
for (size_t i = 1; i < sline.size(); ++i) {
x.push_back(parse_double(sline[i]));
}
data.emplace_back(std::move(x));
}
f.close();
}
};
template <typename Model>
inline void perf_test(Model& model, const TestData& test_data, int iters = 1) {
double begin = ftime();
double best_time = 0.0;
for (int iter = 0; iter < iters; ++iter) {
std::cerr << "BEGIN ITERATION: " << (iter + 1) << std::endl;
double iter_begin = ftime();
double sum_deltas = 0.0;
for (size_t i = 0; i < test_data.data.size(); ++i) {
double y = model.predict(test_data.data[i]);
double delta = y - test_data.label[i];
if (delta < 0.0) delta = -delta;
sum_deltas += delta;
}
double iter_end = ftime();
double delta_time = iter_end - iter_begin;
sum_deltas /= test_data.data.size();
std::cerr << "END ITERATION: " << (iter + 1) << " (" << delta_time << " seconds)"
<< " Q = " << sum_deltas << std::endl;
if (iter == 0 || best_time > delta_time) {
best_time = delta_time;
}
}
double end = ftime();
double sum_time = end - begin;
std::cerr << iters << " iterations have finished in " << (end - begin) << " seconds." << std::endl;
std::cerr << "Best time is " << best_time << " (" << (best_time / test_data.data.size()) << " per prediction, "
<< (test_data.data.size() / best_time) << " predictions/sec)" << std::endl;
std::cerr << "Average time is " << (sum_time / iters) << "(" << (sum_time / iters / test_data.data.size())
<< " per prediction)" << std::endl;
}
template <typename Model>
inline void perf_test_buckets(Model& model, const TestData& test_data, int iters = 1) {
double begin = ftime();
double best_time = 0.0;
for (int iter = 0; iter < iters; ++iter) {
std::vector<double> y;
y.reserve(test_data.data.size());
std::cerr << "BEGIN ITERATION: " << (iter + 1) << std::endl;
double iter_begin = ftime();
double sum_deltas = 0.0;
model.predict(test_data.data, y);
for (size_t i = 0; i < test_data.data.size(); ++i) {
double delta = y[i] - test_data.label[i];
if (delta < 0.0) delta = -delta;
sum_deltas += delta;
}
double iter_end = ftime();
double delta_time = iter_end - iter_begin;
sum_deltas /= test_data.data.size();
std::cerr << "END ITERATION: " << (iter + 1) << " (" << delta_time << " seconds)"
<< " Q = " << sum_deltas << std::endl;
if (iter == 0 || best_time > delta_time) {
best_time = delta_time;
}
}
double end = ftime();
double sum_time = end - begin;
std::cerr << iters << " iterations have finished in " << (end - begin) << " seconds." << std::endl;
std::cerr << "Best time is " << best_time << " (" << (best_time / test_data.data.size()) << " per prediction, "
<< (test_data.data.size() / best_time) << " predictions/sec)" << std::endl;
std::cerr << "Average time is " << (sum_time / iters) << "(" << (sum_time / iters / test_data.data.size())
<< " per prediction)" << std::endl;
}
| 34.265306 | 115 | 0.526305 | [
"vector",
"model"
] |
4aed5f5f530569b7a84fdc1174164b34183c4cdf | 12,607 | cpp | C++ | race_obstacle_detector/src/wait_until_unblocked_action.cpp | buzzer/tams_pr2 | 73eada99f88c300858f05d57b868e6a8109a800c | [
"BSD-2-Clause"
] | null | null | null | race_obstacle_detector/src/wait_until_unblocked_action.cpp | buzzer/tams_pr2 | 73eada99f88c300858f05d57b868e6a8109a800c | [
"BSD-2-Clause"
] | null | null | null | race_obstacle_detector/src/wait_until_unblocked_action.cpp | buzzer/tams_pr2 | 73eada99f88c300858f05d57b868e6a8109a800c | [
"BSD-2-Clause"
] | null | null | null | #include <ros/ros.h>
#include <actionlib/server/simple_action_server.h>
#include <actionlib/client/simple_action_client.h>
#include <race_obstacle_detector/WaitUntilUnblockedAction.h>
#include <race_msgs/BoundingBox.h>
#include <pr2_controllers_msgs/PointHeadAction.h>
#include <tf/transform_listener.h>
#include "geometry_msgs/PointStamped.h"
#include "sensor_msgs/PointCloud2.h"
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl_ros/transforms.h>
#include <pcl/surface/convex_hull.h>
#include <visualization_msgs/Marker.h>
#include <boost/thread.hpp>
const float HUMAN_MIN = 1.2;
const float OBS_MIN = 0.1;
// Our Action interface type, provided as a typedef for convenience
typedef actionlib::SimpleActionClient<pr2_controllers_msgs::PointHeadAction> PointHeadClient;
class WaitUntilUnblockedAction
{
protected:
ros::NodeHandle nh_;
actionlib::SimpleActionServer<race_obstacle_detector::WaitUntilUnblockedAction> as_;
std::string action_name_;
// create messages that are used to published feedback/result
race_obstacle_detector::WaitUntilUnblockedFeedback feedback_;
race_obstacle_detector::WaitUntilUnblockedResult result_;
// Point head
PointHeadClient* point_head_client_;
// TF
tf::TransformListener tf_listener;
// human detection
// TODO add mutex for activated
bool activated;
bool obstacle_detected;
bool human_detected;
struct BoundingBox { float x_min, x_max, y_min, y_max, z_min, z_max; } cloud_bb;
boost::mutex bb_mutex;
boost::mutex obstacle_mutex;
ros::Publisher marker_pub;
public:
WaitUntilUnblockedAction (std::string name) :
as_(nh_, name, boost::bind(&WaitUntilUnblockedAction::executeCB, this, _1), false),
action_name_(name)
{
// Point head
//Initialize the client for the Action interface to the head controller
point_head_client_ = new
PointHeadClient("/head_traj_controller/point_head_action", true);
//wait for head controller action server to come up
while(!point_head_client_->waitForServer(ros::Duration(5.0)))
{
ROS_INFO("Waiting for the point_head_action server to come up");
}
// human detection
activated = false;
human_detected = false;
obstacle_detected = false;
marker_pub = nh_.advertise<visualization_msgs::Marker>("obstacle_boundingbox", 1);
as_.start();
}
~WaitUntilUnblockedAction(void)
{
delete point_head_client_;
}
void executeCB(const race_obstacle_detector::WaitUntilUnblockedGoalConstPtr &goal)
{
std::string obstacle_class = "unknown"; // means also there is NO obstacle
// publish info to the console for the user
ROS_INFO("%s: Executing, with pose %4.2f,%4.2f,%4.2f",
action_name_.c_str(),
goal->boundingbox.pose_stamped.pose.position.x,
goal->boundingbox.pose_stamped.pose.position.y,
goal->boundingbox.pose_stamped.pose.position.z
);
//Point the head
pointHead(goal->boundingbox, 1.3);
//add timeout
ros::Duration duration;
if ( goal->timeout <= ros::Duration(0.0) )
duration = ros::Duration(1000000.0); // wait "forever"
else
duration = goal->timeout;
ros::Time exp_time = ros::Time::now() + duration;
ROS_INFO("timeout duration: %4.2f, at time: %4.2f", duration.toSec(), exp_time.toSec());
// Action takes until it is canceled, timeout occured or no obstacle has
// been detected
// TODO average obstacle check over time
while (true)
{
// check that preempt has not been requested by the client
if (as_.isPreemptRequested() || !ros::ok())
{
ROS_INFO("%s: Preempted", action_name_.c_str());
// set the action state to preempted
as_.setPreempted();
return;
}
// check if the timeout has occured
if (exp_time <= ros::Time::now())
{
ROS_INFO("Timeout hit at %4.2f", ros::Time::now().toSec());
ROS_INFO("%s: Aborted", action_name_.c_str());
as_.setAborted();
return;
}
//==========Obstacle Decisions here===============
obstacle_mutex.lock();
feedback_.obstacle = obstacle_detected;
if (!obstacle_detected)
obstacle_class = "unknown";
else if (human_detected)
obstacle_class = "human";
else
obstacle_class = "table";
obstacle_mutex.unlock();
//================================================
feedback_.obstacle_type = obstacle_class ;
feedback_.confidence = 0.0; // dummy value
feedback_.boundingbox.pose_stamped.header.frame_id="/base_link";
feedback_.boundingbox.pose_stamped.header.stamp=ros::Time::now();
//ROS_INFO("before lock");
//mutex lock cloud_bb
bb_mutex.lock();
feedback_.boundingbox.pose_stamped.pose.position.x=(cloud_bb.x_max+cloud_bb.x_min)/2;
feedback_.boundingbox.pose_stamped.pose.position.y=(cloud_bb.y_max+cloud_bb.y_min)/2;
feedback_.boundingbox.pose_stamped.pose.position.z=(cloud_bb.z_max+cloud_bb.z_min)/2;
feedback_.boundingbox.pose_stamped.pose.orientation.x=0;
feedback_.boundingbox.pose_stamped.pose.orientation.y=0;
feedback_.boundingbox.pose_stamped.pose.orientation.z=0;
feedback_.boundingbox.pose_stamped.pose.orientation.w=1;
feedback_.boundingbox.dimensions.x=cloud_bb.x_max-cloud_bb.x_min;
feedback_.boundingbox.dimensions.y=cloud_bb.y_max-cloud_bb.y_min;
feedback_.boundingbox.dimensions.z=cloud_bb.z_max-cloud_bb.z_min;
bb_mutex.unlock();
//obstacle = feedback_.obstacle;
ROS_INFO("%s: Feedback publishing, obstacle: %s", action_name_.c_str(), obstacle_class .c_str());
// publish feedback here
as_.publishFeedback(feedback_);
//finally set action to succeeded
if (false == obstacle_detected)
{
as_.setSucceeded(result_);
ROS_INFO("%s: Succeeded..", action_name_.c_str());
return;
}
ros::Duration(1.0).sleep();
}
}
bool pointHead (race_msgs::BoundingBox bb, float z=1.0)
{
bool success = true;
//the goal message we will be sending
pr2_controllers_msgs::PointHeadGoal goal;
//the point to be looking at is expressed in the "base_link" frame
geometry_msgs::PointStamped point;
//point.header.frame_id = bb.pose_stamped.header.frame_id;
//point.point.x = bb.pose_stamped.pose.position.x;
//point.point.y = bb.pose_stamped.pose.position.y;
point.header.frame_id = "/base_link";
point.point.x = 1.0;
point.point.y = 0.0;
point.point.z = z;
goal.target = point;
//we want the X axis of the camera frame to be pointing at the target
goal.pointing_frame = "high_def_frame";
goal.pointing_axis.x = 1;
goal.pointing_axis.y = 0;
goal.pointing_axis.z = 0;
//take at least 0.5 seconds to get there
goal.min_duration = ros::Duration(0.5);
//and go no faster than 1 rad/s
goal.max_velocity = 1.0;
//send the goal
point_head_client_->sendGoal(goal);
//wait for it to get there (abort after 2 secs to prevent getting stuck)
point_head_client_->waitForResult(ros::Duration(2));
return success;
}
void getBoundingBox(pcl::PointCloud<pcl::PointXYZ> & input, BoundingBox & cloud_bb)
{
if (input.points.size() > 0)
{
pcl::PointCloud<pcl::PointXYZ>::iterator pc_it = input.points.begin();
// initialize bounding box with first point
cloud_bb.x_max = cloud_bb.x_min = pc_it->x;
cloud_bb.y_max = cloud_bb.y_min = pc_it->y;
cloud_bb.z_max = pc_it->z;
// Assumption: obstacle stands on the ground
cloud_bb.z_min = 0.0;
for ( ; pc_it < input.points.end(); ++pc_it)
{
if(pc_it->x < cloud_bb.x_min)
cloud_bb.x_min = pc_it->x;
else if (pc_it->x > cloud_bb.x_max)
cloud_bb.x_max= pc_it->x;
if(pc_it->y < cloud_bb.y_min)
cloud_bb.y_min = pc_it->y;
else if (pc_it->y > cloud_bb.y_max)
cloud_bb.y_max= pc_it->y;
if (pc_it->z > cloud_bb.z_max)
cloud_bb.z_max= pc_it->z;
}
}
else
{
cloud_bb.x_max=cloud_bb.y_max=cloud_bb.z_max=0.0;
cloud_bb.x_min=cloud_bb.y_min=cloud_bb.z_min=0.0;
}
}
void publishMarker(BoundingBox & cloud_bb)
{
visualization_msgs::Marker marker;
marker.header.frame_id = "/base_link";
marker.header.stamp = ros::Time::now();
marker.ns = "obstacle_detector";
marker.id = 0;
marker.type = visualization_msgs::Marker::CUBE;
marker.action = visualization_msgs::Marker::ADD;
marker.lifetime = ros::Duration(2.0);
//Set the pose of the marker. This is a full 6DOF pose relative to the
//frame/time specified in the header
marker.pose.position.x = (cloud_bb.x_max+cloud_bb.x_min)/2;
marker.pose.position.y = (cloud_bb.y_max+cloud_bb.y_min)/2;
marker.pose.position.z = (cloud_bb.z_max+cloud_bb.z_min)/2;
marker.pose.orientation.x = 0.0;
marker.pose.orientation.y = 0.0;
marker.pose.orientation.z = 0.0;
marker.pose.orientation.w = 1.0;
// Set the scale of the marker -- 1x1x1 here
//means 1m on a side
marker.scale.x = cloud_bb.x_max-cloud_bb.x_min;
marker.scale.y = cloud_bb.y_max-cloud_bb.y_min;
marker.scale.z = cloud_bb.z_max-cloud_bb.z_min;
// Set the color -- be sure to set
//alpha to something non-zero!
marker.color.r = 1.0f;
marker.color.g = 0.0f;
marker.color.b = 0.0f;
marker.color.a = 0.5;
// Publish the marker
marker_pub.publish(marker);
}
//only called on obstacle detected
//Relies on empty point clouds is still being published!
void pcCallback(const sensor_msgs::PointCloud2::ConstPtr& msg)
{
//if (activated == true)
//{
static uint8_t obstacle_state = 0;
static ros::Time last_time = ros::Time::now();
ros::Duration duration(3.0);
ros::Time cur_time = ros::Time::now();
//ROS_INFO("cur_time %.2f and last_time %.2f and duration %.2f", cur_time.toSec(), last_time.toSec(), duration.toSec());
if ((cur_time - last_time) > duration)
{
ROS_INFO("Resetting obstacle state");
obstacle_state = 0;
}
//ROS_INFO("Got point cloud detection result..");
pcl::PointCloud<pcl::PointXYZ>::Ptr input (new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZ>::Ptr output (new pcl::PointCloud<pcl::PointXYZ>);
pcl::fromROSMsg(*msg.get(), *input.get());
// transform
pcl_ros::transformPointCloud("/base_link", *input, *output, tf_listener);
// mutex lock cloud_bb
bb_mutex.lock();
// calculate bounding box
getBoundingBox(*output, cloud_bb);
float bb_zmax = cloud_bb.z_max;
if (bb_zmax > 0)
{
publishMarker(cloud_bb);
}
bb_mutex.unlock();
if (bb_zmax > HUMAN_MIN)
{
human_detected = true;
obstacle_mutex.lock();
obstacle_detected = true;
obstacle_mutex.unlock();
if (obstacle_state != 1)
{
ROS_INFO("Obstacle detected (%.2fm): human", bb_zmax);
obstacle_state = 1;
}
}
else if (bb_zmax > OBS_MIN) // higher than the ground
{
human_detected = false;
obstacle_mutex.lock();
obstacle_detected = true;
obstacle_mutex.unlock();
if (obstacle_state != 2)
{
ROS_INFO("Obstacle detected (%.2fm): static object", bb_zmax);
obstacle_state = 2;
}
}//probably no obstacle
else
{
obstacle_mutex.lock();
obstacle_detected = false;
obstacle_mutex.unlock();
}
last_time = cur_time;
}
//}
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "wait_until_unblocked_action");
WaitUntilUnblockedAction wait_until_unblocked_action("wait_until_unblocked_action");
// subscribe to topic
ros::NodeHandle n;
// point cloud detector
ros::Subscriber sub2 = n.subscribe(
"/pc_detector/rgbd_out",
10,
&WaitUntilUnblockedAction::pcCallback,
&wait_until_unblocked_action);
ros::spin();
return 0;
}
| 33.263852 | 126 | 0.634806 | [
"object",
"transform"
] |
4af30a5d9d392a867d415c4c585f5487282479b6 | 8,406 | cpp | C++ | ann_benchmark/src/vespa/ann_benchmark/vespa_ann_benchmark.cpp | Rexiome/vespa | 23e9dd2577e9d5bd32e410e2759a82aad6e185ee | [
"Apache-2.0"
] | null | null | null | ann_benchmark/src/vespa/ann_benchmark/vespa_ann_benchmark.cpp | Rexiome/vespa | 23e9dd2577e9d5bd32e410e2759a82aad6e185ee | [
"Apache-2.0"
] | null | null | null | ann_benchmark/src/vespa/ann_benchmark/vespa_ann_benchmark.cpp | Rexiome/vespa | 23e9dd2577e9d5bd32e410e2759a82aad6e185ee | [
"Apache-2.0"
] | null | null | null | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <vespa/searchcommon/attribute/hnsw_index_params.h>
#include <vespa/searchlib/attribute/attributevector.h>
#include <vespa/searchlib/attribute/attributefactory.h>
#include <vespa/searchlib/tensor/dense_tensor_attribute.h>
#include <vespa/searchlib/tensor/nearest_neighbor_index.h>
#include <vespa/searchcommon/attribute/config.h>
#include <vespa/eval/eval/value.h>
#include <vespa/vespalib/test/insertion_operators.h>
#include <ostream>
#include <sstream>
#include <limits>
namespace py = pybind11;
using search::AttributeFactory;
using search::AttributeVector;
using search::attribute::BasicType;
using search::attribute::Config;
using search::attribute::CollectionType;
using search::attribute::DistanceMetric;
using search::attribute::HnswIndexParams;
using search::tensor::NearestNeighborIndex;
using search::tensor::TensorAttribute;
using vespalib::eval::CellType;
using vespalib::eval::DenseValueView;
using vespalib::eval::TypedCells;
using vespalib::eval::ValueType;
using vespalib::eval::Value;
namespace vespa_ann_benchmark {
using TopKResult = std::vector<std::pair<uint32_t, double>>;
namespace {
std::string
make_tensor_spec(uint32_t dim_size)
{
std::ostringstream os;
os << "tensor<float>(x[" << dim_size << "])";
return os.str();
}
constexpr uint32_t lid_bias = 1; // lid 0 is reserved
}
/*
* Class exposing the Vespa implementation of an HNSW index for nearest neighbor search over data points in a high dimensional vector space.
*
* A tensor attribute field (https://docs.vespa.ai/en/reference/schema-reference.html#type:tensor) is used to store the vectors in memory.
* This class only supports single-threaded access (both for indexing and searching),
* and should only be used for low-level benchmarking.
* To use nearest neighbor search in a Vespa application,
* see https://docs.vespa.ai/en/approximate-nn-hnsw.html for more details.
*/
class HnswIndex
{
ValueType _tensor_type;
HnswIndexParams _hnsw_index_params;
std::shared_ptr<AttributeVector> _attribute;
TensorAttribute* _tensor_attribute;
const NearestNeighborIndex* _nearest_neighbor_index;
size_t _dim_size;
bool _normalize_vectors;
bool check_lid(uint32_t lid);
bool check_value(const char *op, const std::vector<float>& value);
TypedCells get_typed_cells(const std::vector<float>& value, std::vector<float>& normalized_value);
public:
HnswIndex(uint32_t dim_size, const HnswIndexParams &hnsw_index_params, bool normalize_vectors);
virtual ~HnswIndex();
void set_vector(uint32_t lid, const std::vector<float>& value);
std::vector<float> get_vector(uint32_t lid);
void clear_vector(uint32_t lid);
TopKResult find_top_k(uint32_t k, const std::vector<float>& value, uint32_t explore_k);
};
HnswIndex::HnswIndex(uint32_t dim_size, const HnswIndexParams &hnsw_index_params, bool normalize_vectors)
: _tensor_type(ValueType::error_type()),
_hnsw_index_params(hnsw_index_params),
_attribute(),
_tensor_attribute(nullptr),
_nearest_neighbor_index(nullptr),
_dim_size(0u),
_normalize_vectors(normalize_vectors)
{
Config cfg(BasicType::TENSOR, CollectionType::SINGLE);
_tensor_type = ValueType::from_spec(make_tensor_spec(dim_size));
assert(_tensor_type.is_dense());
assert(_tensor_type.count_indexed_dimensions() == 1u);
_dim_size = _tensor_type.dimensions()[0].size;
cfg.setTensorType(_tensor_type);
cfg.set_distance_metric(hnsw_index_params.distance_metric());
cfg.set_hnsw_index_params(hnsw_index_params);
_attribute = AttributeFactory::createAttribute("tensor", cfg);
_tensor_attribute = dynamic_cast<TensorAttribute *>(_attribute.get());
assert(_tensor_attribute != nullptr);
_nearest_neighbor_index = _tensor_attribute->nearest_neighbor_index();
assert(_nearest_neighbor_index != nullptr);
}
HnswIndex::~HnswIndex() = default;
bool
HnswIndex::check_lid(uint32_t lid)
{
if (lid >= std::numeric_limits<uint32_t>::max() - lid_bias) {
std::cerr << "lid is too high" << std::endl;
return false;
}
return true;
}
bool
HnswIndex::check_value(const char *op, const std::vector<float>& value)
{
if (value.size() != _dim_size) {
std::cerr << op << " failed, expected vector with size " << _dim_size << ", got vector with size " << value.size() << std::endl;
return false;
}
return true;
}
TypedCells
HnswIndex::get_typed_cells(const std::vector<float>& value, std::vector<float>& normalized_value)
{
if (!_normalize_vectors) {
return {&value[0], CellType::FLOAT, value.size()};
}
float sum_of_squared = 0.0f;
for (auto elem : value) {
sum_of_squared += elem * elem;
}
float factor = 1.0f / (sqrtf(sum_of_squared) + 1e-40f);
normalized_value.reserve(value.size());
normalized_value.clear();
for (auto elem : value) {
normalized_value.emplace_back(elem * factor);
}
return {&normalized_value[0], CellType::FLOAT, normalized_value.size()};
}
void
HnswIndex::set_vector(uint32_t lid, const std::vector<float>& value)
{
if (!check_lid(lid)) {
return;
}
if (!check_value("set_vector", value)) {
return;
}
/*
* Not thread safe against concurrent set_vector().
*/
std::vector<float> normalized_value;
auto typed_cells = get_typed_cells(value, normalized_value);
DenseValueView tensor_view(_tensor_type, typed_cells);
while (size_t(lid + lid_bias) >= _attribute->getNumDocs()) {
uint32_t new_lid = 0;
_attribute->addDoc(new_lid);
}
_tensor_attribute->setTensor(lid + lid_bias, tensor_view); // lid 0 is special in vespa
_attribute->commit();
}
std::vector<float>
HnswIndex::get_vector(uint32_t lid)
{
if (!check_lid(lid)) {
return {};
}
TypedCells typed_cells = _tensor_attribute->extract_cells_ref(lid + lid_bias);
assert(typed_cells.size == _dim_size);
const float* data = static_cast<const float* >(typed_cells.data);
return {data, data + _dim_size};
return {};
}
void
HnswIndex::clear_vector(uint32_t lid)
{
if (!check_lid(lid)) {
return;
}
if (size_t(lid + lid_bias) < _attribute->getNumDocs()) {
_attribute->clearDoc(lid + lid_bias);
_attribute->commit();
}
}
TopKResult
HnswIndex::find_top_k(uint32_t k, const std::vector<float>& value, uint32_t explore_k)
{
if (!check_value("find_top_k", value)) {
return {};
}
/*
* Not thread safe against concurrent set_vector() since attribute
* read guard is not taken here.
*/
TopKResult result;
std::vector<float> normalized_value;
auto typed_cells = get_typed_cells(value, normalized_value);
auto raw_result = _nearest_neighbor_index->find_top_k(k, typed_cells, explore_k, std::numeric_limits<double>::max());
result.reserve(raw_result.size());
switch (_hnsw_index_params.distance_metric()) {
case DistanceMetric::Euclidean:
for (auto &raw : raw_result) {
result.emplace_back(raw.docid - lid_bias, sqrt(raw.distance));
}
break;
default:
for (auto &raw : raw_result) {
result.emplace_back(raw.docid - lid_bias, raw.distance);
}
}
// Results are sorted by lid, not by distance
return result;
}
}
using vespa_ann_benchmark::HnswIndex;
PYBIND11_MODULE(vespa_ann_benchmark, m) {
m.doc() = "vespa_ann_benchmark plugin";
py::enum_<DistanceMetric>(m, "DistanceMetric")
.value("Euclidean", DistanceMetric::Euclidean)
.value("Angular", DistanceMetric::Angular)
.value("InnerProduct", DistanceMetric::InnerProduct);
py::class_<HnswIndexParams>(m, "HnswIndexParams")
.def(py::init<uint32_t, uint32_t, DistanceMetric, bool>());
py::class_<HnswIndex>(m, "HnswIndex")
.def(py::init<uint32_t, const HnswIndexParams&, bool>())
.def("set_vector", &HnswIndex::set_vector)
.def("get_vector", &HnswIndex::get_vector)
.def("clear_vector", &HnswIndex::clear_vector)
.def("find_top_k", &HnswIndex::find_top_k);
}
| 33.895161 | 140 | 0.694266 | [
"vector"
] |
4af48b028f4a2b875872537fbb4f9cad262266d5 | 17,995 | hpp | C++ | modules/cudaarithm/include/opencv2/cudaarithm.hpp | Nerei/opencv | 92d5f8744c872ccf63b17334f018343973353e47 | [
"BSD-3-Clause"
] | 1 | 2015-04-22T14:10:46.000Z | 2015-04-22T14:10:46.000Z | modules/cudaarithm/include/opencv2/cudaarithm.hpp | lastlegion/opencv | 4b31b9cb8cbc673ca8db95fdec8a3e707d04fef2 | [
"BSD-3-Clause"
] | null | null | null | modules/cudaarithm/include/opencv2/cudaarithm.hpp | lastlegion/opencv | 4b31b9cb8cbc673ca8db95fdec8a3e707d04fef2 | [
"BSD-3-Clause"
] | 2 | 2018-05-03T21:08:19.000Z | 2020-09-26T06:27:08.000Z | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#ifndef __OPENCV_CUDAARITHM_HPP__
#define __OPENCV_CUDAARITHM_HPP__
#ifndef __cplusplus
# error cudaarithm.hpp header must be compiled as C++
#endif
#include "opencv2/core/cuda.hpp"
namespace cv { namespace cuda {
//! adds one matrix to another (dst = src1 + src2)
CV_EXPORTS void add(InputArray src1, InputArray src2, OutputArray dst, InputArray mask = noArray(), int dtype = -1, Stream& stream = Stream::Null());
//! subtracts one matrix from another (dst = src1 - src2)
CV_EXPORTS void subtract(InputArray src1, InputArray src2, OutputArray dst, InputArray mask = noArray(), int dtype = -1, Stream& stream = Stream::Null());
//! computes element-wise weighted product of the two arrays (dst = scale * src1 * src2)
CV_EXPORTS void multiply(InputArray src1, InputArray src2, OutputArray dst, double scale = 1, int dtype = -1, Stream& stream = Stream::Null());
//! computes element-wise weighted quotient of the two arrays (dst = scale * (src1 / src2))
CV_EXPORTS void divide(InputArray src1, InputArray src2, OutputArray dst, double scale = 1, int dtype = -1, Stream& stream = Stream::Null());
//! computes element-wise weighted reciprocal of an array (dst = scale/src2)
static inline void divide(double src1, InputArray src2, OutputArray dst, int dtype = -1, Stream& stream = Stream::Null())
{
divide(src1, src2, dst, 1.0, dtype, stream);
}
//! computes element-wise absolute difference of two arrays (dst = abs(src1 - src2))
CV_EXPORTS void absdiff(InputArray src1, InputArray src2, OutputArray dst, Stream& stream = Stream::Null());
//! computes absolute value of each matrix element
CV_EXPORTS void abs(InputArray src, OutputArray dst, Stream& stream = Stream::Null());
//! computes square of each pixel in an image
CV_EXPORTS void sqr(InputArray src, OutputArray dst, Stream& stream = Stream::Null());
//! computes square root of each pixel in an image
CV_EXPORTS void sqrt(InputArray src, OutputArray dst, Stream& stream = Stream::Null());
//! computes exponent of each matrix element
CV_EXPORTS void exp(InputArray src, OutputArray dst, Stream& stream = Stream::Null());
//! computes natural logarithm of absolute value of each matrix element
CV_EXPORTS void log(InputArray src, OutputArray dst, Stream& stream = Stream::Null());
//! computes power of each matrix element:
//! (dst(i,j) = pow( src(i,j) , power), if src.type() is integer
//! (dst(i,j) = pow(fabs(src(i,j)), power), otherwise
CV_EXPORTS void pow(InputArray src, double power, OutputArray dst, Stream& stream = Stream::Null());
//! compares elements of two arrays (dst = src1 <cmpop> src2)
CV_EXPORTS void compare(InputArray src1, InputArray src2, OutputArray dst, int cmpop, Stream& stream = Stream::Null());
//! performs per-elements bit-wise inversion
CV_EXPORTS void bitwise_not(InputArray src, OutputArray dst, InputArray mask = noArray(), Stream& stream = Stream::Null());
//! calculates per-element bit-wise disjunction of two arrays
CV_EXPORTS void bitwise_or(InputArray src1, InputArray src2, OutputArray dst, InputArray mask = noArray(), Stream& stream = Stream::Null());
//! calculates per-element bit-wise conjunction of two arrays
CV_EXPORTS void bitwise_and(InputArray src1, InputArray src2, OutputArray dst, InputArray mask = noArray(), Stream& stream = Stream::Null());
//! calculates per-element bit-wise "exclusive or" operation
CV_EXPORTS void bitwise_xor(InputArray src1, InputArray src2, OutputArray dst, InputArray mask = noArray(), Stream& stream = Stream::Null());
//! pixel by pixel right shift of an image by a constant value
//! supports 1, 3 and 4 channels images with integers elements
CV_EXPORTS void rshift(InputArray src, Scalar_<int> val, OutputArray dst, Stream& stream = Stream::Null());
//! pixel by pixel left shift of an image by a constant value
//! supports 1, 3 and 4 channels images with CV_8U, CV_16U or CV_32S depth
CV_EXPORTS void lshift(InputArray src, Scalar_<int> val, OutputArray dst, Stream& stream = Stream::Null());
//! computes per-element minimum of two arrays (dst = min(src1, src2))
CV_EXPORTS void min(InputArray src1, InputArray src2, OutputArray dst, Stream& stream = Stream::Null());
//! computes per-element maximum of two arrays (dst = max(src1, src2))
CV_EXPORTS void max(InputArray src1, InputArray src2, OutputArray dst, Stream& stream = Stream::Null());
//! computes the weighted sum of two arrays (dst = alpha*src1 + beta*src2 + gamma)
CV_EXPORTS void addWeighted(InputArray src1, double alpha, InputArray src2, double beta, double gamma, OutputArray dst,
int dtype = -1, Stream& stream = Stream::Null());
//! adds scaled array to another one (dst = alpha*src1 + src2)
static inline void scaleAdd(InputArray src1, double alpha, InputArray src2, OutputArray dst, Stream& stream = Stream::Null())
{
addWeighted(src1, alpha, src2, 1.0, 0.0, dst, -1, stream);
}
//! applies fixed threshold to the image
CV_EXPORTS double threshold(InputArray src, OutputArray dst, double thresh, double maxval, int type, Stream& stream = Stream::Null());
//! computes magnitude of complex (x(i).re, x(i).im) vector
//! supports only CV_32FC2 type
CV_EXPORTS void magnitude(InputArray xy, OutputArray magnitude, Stream& stream = Stream::Null());
//! computes squared magnitude of complex (x(i).re, x(i).im) vector
//! supports only CV_32FC2 type
CV_EXPORTS void magnitudeSqr(InputArray xy, OutputArray magnitude, Stream& stream = Stream::Null());
//! computes magnitude of each (x(i), y(i)) vector
//! supports only floating-point source
CV_EXPORTS void magnitude(InputArray x, InputArray y, OutputArray magnitude, Stream& stream = Stream::Null());
//! computes squared magnitude of each (x(i), y(i)) vector
//! supports only floating-point source
CV_EXPORTS void magnitudeSqr(InputArray x, InputArray y, OutputArray magnitude, Stream& stream = Stream::Null());
//! computes angle of each (x(i), y(i)) vector
//! supports only floating-point source
CV_EXPORTS void phase(InputArray x, InputArray y, OutputArray angle, bool angleInDegrees = false, Stream& stream = Stream::Null());
//! converts Cartesian coordinates to polar
//! supports only floating-point source
CV_EXPORTS void cartToPolar(InputArray x, InputArray y, OutputArray magnitude, OutputArray angle, bool angleInDegrees = false, Stream& stream = Stream::Null());
//! converts polar coordinates to Cartesian
//! supports only floating-point source
CV_EXPORTS void polarToCart(InputArray magnitude, InputArray angle, OutputArray x, OutputArray y, bool angleInDegrees = false, Stream& stream = Stream::Null());
//! makes multi-channel array out of several single-channel arrays
CV_EXPORTS void merge(const GpuMat* src, size_t n, OutputArray dst, Stream& stream = Stream::Null());
CV_EXPORTS void merge(const std::vector<GpuMat>& src, OutputArray dst, Stream& stream = Stream::Null());
//! copies each plane of a multi-channel array to a dedicated array
CV_EXPORTS void split(InputArray src, GpuMat* dst, Stream& stream = Stream::Null());
CV_EXPORTS void split(InputArray src, std::vector<GpuMat>& dst, Stream& stream = Stream::Null());
//! transposes the matrix
//! supports matrix with element size = 1, 4 and 8 bytes (CV_8UC1, CV_8UC4, CV_16UC2, CV_32FC1, etc)
CV_EXPORTS void transpose(InputArray src1, OutputArray dst, Stream& stream = Stream::Null());
//! reverses the order of the rows, columns or both in a matrix
//! supports 1, 3 and 4 channels images with CV_8U, CV_16U, CV_32S or CV_32F depth
CV_EXPORTS void flip(InputArray src, OutputArray dst, int flipCode, Stream& stream = Stream::Null());
//! transforms 8-bit unsigned integers using lookup table: dst(i)=lut(src(i))
//! destination array will have the depth type as lut and the same channels number as source
//! supports CV_8UC1, CV_8UC3 types
class CV_EXPORTS LookUpTable : public Algorithm
{
public:
virtual void transform(InputArray src, OutputArray dst, Stream& stream = Stream::Null()) = 0;
};
CV_EXPORTS Ptr<LookUpTable> createLookUpTable(InputArray lut);
//! copies 2D array to a larger destination array and pads borders with user-specifiable constant
CV_EXPORTS void copyMakeBorder(InputArray src, OutputArray dst, int top, int bottom, int left, int right, int borderType,
Scalar value = Scalar(), Stream& stream = Stream::Null());
//! computes norm of array
//! supports NORM_INF, NORM_L1, NORM_L2
//! supports all matrices except 64F
CV_EXPORTS double norm(InputArray src1, int normType, InputArray mask, GpuMat& buf);
static inline double norm(InputArray src, int normType)
{
GpuMat buf;
return norm(src, normType, GpuMat(), buf);
}
static inline double norm(InputArray src, int normType, GpuMat& buf)
{
return norm(src, normType, GpuMat(), buf);
}
//! computes norm of the difference between two arrays
//! supports NORM_INF, NORM_L1, NORM_L2
//! supports only CV_8UC1 type
CV_EXPORTS double norm(InputArray src1, InputArray src2, GpuMat& buf, int normType=NORM_L2);
static inline double norm(InputArray src1, InputArray src2, int normType=NORM_L2)
{
GpuMat buf;
return norm(src1, src2, buf, normType);
}
//! computes sum of array elements
//! supports only single channel images
CV_EXPORTS Scalar sum(InputArray src, InputArray mask, GpuMat& buf);
static inline Scalar sum(InputArray src)
{
GpuMat buf;
return sum(src, GpuMat(), buf);
}
static inline Scalar sum(InputArray src, GpuMat& buf)
{
return sum(src, GpuMat(), buf);
}
//! computes sum of array elements absolute values
//! supports only single channel images
CV_EXPORTS Scalar absSum(InputArray src, InputArray mask, GpuMat& buf);
static inline Scalar absSum(InputArray src)
{
GpuMat buf;
return absSum(src, GpuMat(), buf);
}
static inline Scalar absSum(InputArray src, GpuMat& buf)
{
return absSum(src, GpuMat(), buf);
}
//! computes squared sum of array elements
//! supports only single channel images
CV_EXPORTS Scalar sqrSum(InputArray src, InputArray mask, GpuMat& buf);
static inline Scalar sqrSum(InputArray src)
{
GpuMat buf;
return sqrSum(src, GpuMat(), buf);
}
static inline Scalar sqrSum(InputArray src, GpuMat& buf)
{
return sqrSum(src, GpuMat(), buf);
}
//! finds global minimum and maximum array elements and returns their values
CV_EXPORTS void minMax(InputArray src, double* minVal, double* maxVal, InputArray mask, GpuMat& buf);
static inline void minMax(InputArray src, double* minVal, double* maxVal=0, InputArray mask=noArray())
{
GpuMat buf;
minMax(src, minVal, maxVal, mask, buf);
}
//! finds global minimum and maximum array elements and returns their values with locations
CV_EXPORTS void minMaxLoc(InputArray src, double* minVal, double* maxVal, Point* minLoc, Point* maxLoc,
InputArray mask, GpuMat& valbuf, GpuMat& locbuf);
static inline void minMaxLoc(InputArray src, double* minVal, double* maxVal=0, Point* minLoc=0, Point* maxLoc=0,
InputArray mask=noArray())
{
GpuMat valBuf, locBuf;
minMaxLoc(src, minVal, maxVal, minLoc, maxLoc, mask, valBuf, locBuf);
}
//! counts non-zero array elements
CV_EXPORTS int countNonZero(InputArray src, GpuMat& buf);
static inline int countNonZero(const GpuMat& src)
{
GpuMat buf;
return countNonZero(src, buf);
}
//! reduces a matrix to a vector
CV_EXPORTS void reduce(InputArray mtx, OutputArray vec, int dim, int reduceOp, int dtype = -1, Stream& stream = Stream::Null());
//! computes mean value and standard deviation of all or selected array elements
//! supports only CV_8UC1 type
CV_EXPORTS void meanStdDev(InputArray mtx, Scalar& mean, Scalar& stddev, GpuMat& buf);
static inline void meanStdDev(InputArray src, Scalar& mean, Scalar& stddev)
{
GpuMat buf;
meanStdDev(src, mean, stddev, buf);
}
//! computes the standard deviation of integral images
//! supports only CV_32SC1 source type and CV_32FC1 sqr type
//! output will have CV_32FC1 type
CV_EXPORTS void rectStdDev(InputArray src, InputArray sqr, OutputArray dst, Rect rect, Stream& stream = Stream::Null());
//! scales and shifts array elements so that either the specified norm (alpha) or the minimum (alpha) and maximum (beta) array values get the specified values
CV_EXPORTS void normalize(InputArray src, OutputArray dst, double alpha, double beta,
int norm_type, int dtype, InputArray mask, GpuMat& norm_buf, GpuMat& cvt_buf);
static inline void normalize(InputArray src, OutputArray dst, double alpha = 1, double beta = 0,
int norm_type = NORM_L2, int dtype = -1, InputArray mask = noArray())
{
GpuMat norm_buf;
GpuMat cvt_buf;
normalize(src, dst, alpha, beta, norm_type, dtype, mask, norm_buf, cvt_buf);
}
//! computes the integral image
//! sum will have CV_32S type, but will contain unsigned int values
//! supports only CV_8UC1 source type
CV_EXPORTS void integral(InputArray src, OutputArray sum, GpuMat& buffer, Stream& stream = Stream::Null());
static inline void integralBuffered(InputArray src, OutputArray sum, GpuMat& buffer, Stream& stream = Stream::Null())
{
integral(src, sum, buffer, stream);
}
static inline void integral(InputArray src, OutputArray sum, Stream& stream = Stream::Null())
{
GpuMat buffer;
integral(src, sum, buffer, stream);
}
//! computes squared integral image
//! result matrix will have 64F type, but will contain 64U values
//! supports source images of 8UC1 type only
CV_EXPORTS void sqrIntegral(InputArray src, OutputArray sqsum, GpuMat& buf, Stream& stream = Stream::Null());
static inline void sqrIntegral(InputArray src, OutputArray sqsum, Stream& stream = Stream::Null())
{
GpuMat buffer;
sqrIntegral(src, sqsum, buffer, stream);
}
CV_EXPORTS void gemm(InputArray src1, InputArray src2, double alpha,
InputArray src3, double beta, OutputArray dst, int flags = 0, Stream& stream = Stream::Null());
//! performs per-element multiplication of two full (not packed) Fourier spectrums
//! supports 32FC2 matrixes only (interleaved format)
CV_EXPORTS void mulSpectrums(InputArray src1, InputArray src2, OutputArray dst, int flags, bool conjB=false, Stream& stream = Stream::Null());
//! performs per-element multiplication of two full (not packed) Fourier spectrums
//! supports 32FC2 matrixes only (interleaved format)
CV_EXPORTS void mulAndScaleSpectrums(InputArray src1, InputArray src2, OutputArray dst, int flags, float scale, bool conjB=false, Stream& stream = Stream::Null());
//! Performs a forward or inverse discrete Fourier transform (1D or 2D) of floating point matrix.
//! Param dft_size is the size of DFT transform.
//!
//! If the source matrix is not continous, then additional copy will be done,
//! so to avoid copying ensure the source matrix is continous one. If you want to use
//! preallocated output ensure it is continuous too, otherwise it will be reallocated.
//!
//! Being implemented via CUFFT real-to-complex transform result contains only non-redundant values
//! in CUFFT's format. Result as full complex matrix for such kind of transform cannot be retrieved.
//!
//! For complex-to-real transform it is assumed that the source matrix is packed in CUFFT's format.
CV_EXPORTS void dft(InputArray src, OutputArray dst, Size dft_size, int flags=0, Stream& stream = Stream::Null());
//! computes convolution (or cross-correlation) of two images using discrete Fourier transform
//! supports source images of 32FC1 type only
//! result matrix will have 32FC1 type
class CV_EXPORTS Convolution : public Algorithm
{
public:
virtual void convolve(InputArray image, InputArray templ, OutputArray result, bool ccorr = false, Stream& stream = Stream::Null()) = 0;
};
CV_EXPORTS Ptr<Convolution> createConvolution(Size user_block_size = Size());
}} // namespace cv { namespace cuda {
#endif /* __OPENCV_CUDAARITHM_HPP__ */
| 47.986667 | 163 | 0.735871 | [
"vector",
"transform"
] |
4af71cb99b2678aaca38f1901a02e80dcd19609d | 3,432 | cpp | C++ | code/engine.vc2008/xrGame/doors_manager.cpp | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 7 | 2018-03-27T12:36:07.000Z | 2020-06-26T11:31:52.000Z | code/engine.vc2008/xrGame/doors_manager.cpp | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 2 | 2018-05-26T23:17:14.000Z | 2019-04-14T18:33:27.000Z | code/engine.vc2008/xrGame/doors_manager.cpp | Rikoshet-234/xray-oxygen | eaac3fa4780639152684f3251b8b4452abb8e439 | [
"Apache-2.0"
] | 3 | 2019-10-20T19:35:34.000Z | 2022-02-28T01:42:10.000Z | ////////////////////////////////////////////////////////////////////////////
// Created : 23.06.2009
// Author : Dmitriy Iassenev
// Copyright (C) GSC Game World - 2009
////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "doors_manager.h"
#include "gameobject.h"
#include "doors_door.h"
#include "doors_actor.h"
using doors::actor;
using doors::manager;
using doors::door;
manager::manager ( Fbox const& bounding_box ) :
m_doors ( bounding_box, 2.f, 512, 2048 )
{
}
manager::~manager ( )
{
VERIFY_FORMAT ( m_doors.empty(), "there are %d still registered doors", m_doors.size());
}
//#include "level.h"
//#include "script_game_object.h"
//
//void manager::check_bug_door ( ) const
//{
// CObject const* const object = Level().Objects.FindObjectByName("shkaf_work_01_door_0000");
// if ( !object ) {
// Msg ( "there is now object[\"shkaf_work_01_door_0000\"] found" );
// return;
// }
//
// CGameObject const* const game_object = smart_cast<CGameObject const*>(object);
// VERIFY ( game_object );
// if ( !game_object->lua_game_object()->m_door ) {
// Msg ( "object[\"shkaf_work_01_door_0000\"] has not been registered as a door yet" );
// return;
// }
//
// door const* const found = m_doors.find( game_object->lua_game_object()->m_door->position() );
// if ( !found ) {
// Msg ( "object[\"shkaf_work_01_door_0000\"] has been unregistered already[0x%08x]?", game_object->lua_game_object()->m_door );
// return;
// }
//
// Msg ( "object[\"shkaf_work_01_door_0000\"] has been registered as a door" );
//}
//
door* manager::register_door ( CPhysicObject& object )
{
door* const result = xr_new<door>( &object );
//if ( !xr_strcmp(result->get_name(),"shkaf_work_01_door_0000") ) {
// Msg ( "registering door[\"shkaf_work_01_door_0000\"][%f][%f][%f]", VPUSH(result->position()) );
//}
//check_bug_door ( );
m_doors.insert ( result );
//check_bug_door ( );
return result;
}
void manager::unregister_door ( door*& door )
{
//if ( !xr_strcmp(door->get_name(),"shkaf_work_01_door_0000") ) {
// Msg ( "UNregistering door[\"shkaf_work_01_door_0000\"][%f][%f][%f]", VPUSH(door->position()) );
//}
//check_bug_door ( );
m_doors.remove ( door );
//check_bug_door ( );
xr_delete ( door );
}
bool manager::actualize_doors_state ( actor& actor, float const average_speed )
{
float const radius = average_speed*g_door_open_time + g_door_length;
Fvector const& position = actor.get_position();
//check_bug_door ( );
m_doors.nearest ( position, radius, m_nearest_doors );
//check_bug_door ( );
if ( m_nearest_doors.empty() && !actor.need_update() )
return true;
return actor.update_doors( m_nearest_doors, average_speed );
}
void manager::on_door_is_open ( door* door )
{
door->on_change_state ( door_state_open );
}
void manager::on_door_is_closed ( door* door )
{
door->on_change_state ( door_state_closed );
}
bool manager::is_door_locked ( door const* door ) const
{
return door->is_locked( doors::door_state_open ) || door->is_locked( doors::door_state_closed );
}
void manager::lock_door ( door* const door )
{
door->lock ( );
}
void manager::unlock_door ( door* const door )
{
door->unlock ( );
}
bool manager::is_door_blocked ( door* const door ) const
{
return door->is_blocked(door_state_open) || door->is_blocked(door_state_closed);
} | 29.084746 | 133 | 0.637821 | [
"object"
] |
4af892bf8e2ccad50ce8ed619fb5ee70246ba952 | 26,591 | hpp | C++ | src/share/types.hpp | IvanRublev/Karabiner-Elements | b1f4e1077f639484eea14066a277722304d0e760 | [
"Unlicense"
] | 271 | 2016-10-03T22:35:55.000Z | 2022-02-14T05:40:39.000Z | src/share/types.hpp | IvanRublev/Karabiner-Elements | b1f4e1077f639484eea14066a277722304d0e760 | [
"Unlicense"
] | 2 | 2017-02-03T03:16:21.000Z | 2017-06-10T09:52:46.000Z | src/share/types.hpp | IvanRublev/Karabiner-Elements | b1f4e1077f639484eea14066a277722304d0e760 | [
"Unlicense"
] | 25 | 2016-10-06T19:20:13.000Z | 2021-06-17T03:02:09.000Z | #pragma once
#include "boost_defs.hpp"
#include "Karabiner-VirtualHIDDevice/dist/include/karabiner_virtual_hid_device_methods.hpp"
#include "apple_hid_usage_tables.hpp"
#include "system_preferences.hpp"
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/hid/IOHIDUsageTables.h>
#include <IOKit/hidsystem/IOHIDShared.h>
#include <IOKit/hidsystem/ev_keymap.h>
#include <boost/optional.hpp>
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
namespace krbn {
enum class operation_type : uint8_t {
none,
// console_user_server -> grabber
connect,
system_preferences_values_updated,
clear_simple_modifications,
add_simple_modification,
clear_fn_function_keys,
add_fn_function_key,
virtual_hid_keyboard_configuration_updated,
clear_devices,
add_device,
complete_devices,
};
enum class connect_from : uint8_t {
console_user_server,
};
enum class event_type : uint32_t {
key_down,
key_up,
};
enum class key_code : uint32_t {
// 0x00 - 0xff are keys in keyboard_or_keypad usage page.
return_or_enter = kHIDUsage_KeyboardReturnOrEnter,
delete_or_backspace = kHIDUsage_KeyboardDeleteOrBackspace,
caps_lock = kHIDUsage_KeyboardCapsLock,
f1 = kHIDUsage_KeyboardF1,
f2 = kHIDUsage_KeyboardF2,
f3 = kHIDUsage_KeyboardF3,
f4 = kHIDUsage_KeyboardF4,
f5 = kHIDUsage_KeyboardF5,
f6 = kHIDUsage_KeyboardF6,
f7 = kHIDUsage_KeyboardF7,
f8 = kHIDUsage_KeyboardF8,
f9 = kHIDUsage_KeyboardF9,
f10 = kHIDUsage_KeyboardF10,
f11 = kHIDUsage_KeyboardF11,
f12 = kHIDUsage_KeyboardF12,
f13 = kHIDUsage_KeyboardF13,
f14 = kHIDUsage_KeyboardF14,
f15 = kHIDUsage_KeyboardF15,
f16 = kHIDUsage_KeyboardF16,
f17 = kHIDUsage_KeyboardF17,
f18 = kHIDUsage_KeyboardF18,
f19 = kHIDUsage_KeyboardF19,
f20 = kHIDUsage_KeyboardF20,
f21 = kHIDUsage_KeyboardF21,
f22 = kHIDUsage_KeyboardF22,
f23 = kHIDUsage_KeyboardF23,
f24 = kHIDUsage_KeyboardF24,
right_arrow = kHIDUsage_KeyboardRightArrow,
left_arrow = kHIDUsage_KeyboardLeftArrow,
down_arrow = kHIDUsage_KeyboardDownArrow,
up_arrow = kHIDUsage_KeyboardUpArrow,
keypad_slash = kHIDUsage_KeypadSlash,
keypad_asterisk = kHIDUsage_KeypadAsterisk,
keypad_hyphen = kHIDUsage_KeypadHyphen,
keypad_plus = kHIDUsage_KeypadPlus,
keypad_enter = kHIDUsage_KeypadEnter,
keypad_1 = kHIDUsage_Keypad1,
keypad_2 = kHIDUsage_Keypad2,
keypad_3 = kHIDUsage_Keypad3,
keypad_4 = kHIDUsage_Keypad4,
keypad_5 = kHIDUsage_Keypad5,
keypad_6 = kHIDUsage_Keypad6,
keypad_7 = kHIDUsage_Keypad7,
keypad_8 = kHIDUsage_Keypad8,
keypad_9 = kHIDUsage_Keypad9,
keypad_0 = kHIDUsage_Keypad0,
keypad_period = kHIDUsage_KeypadPeriod,
keypad_equal_sign = kHIDUsage_KeypadEqualSign,
keypad_comma = kHIDUsage_KeypadComma,
home = kHIDUsage_KeyboardHome,
page_up = kHIDUsage_KeyboardPageUp,
delete_forward = kHIDUsage_KeyboardDeleteForward,
end = kHIDUsage_KeyboardEnd,
page_down = kHIDUsage_KeyboardPageDown,
mute = kHIDUsage_KeyboardMute,
volume_decrement = kHIDUsage_KeyboardVolumeDown,
volume_increment = kHIDUsage_KeyboardVolumeUp,
// 0x1000 - are karabiner own virtual key codes or keys not in keyboard_or_keypad usage page.
extra_ = 0x1000,
// A pseudo key that does not send any event.
vk_none,
// Keys that are not in generic keyboard_or_keypad usage_page.
fn,
display_brightness_decrement,
display_brightness_increment,
dashboard,
launchpad,
mission_control,
illumination_decrement,
illumination_increment,
rewind,
play_or_pause,
fastforward,
eject,
apple_display_brightness_decrement,
apple_display_brightness_increment,
apple_top_case_display_brightness_decrement,
apple_top_case_display_brightness_increment,
};
enum class pointing_button : uint32_t {
zero,
button1,
button2,
button3,
button4,
button5,
button6,
button7,
button8,
button9,
button10,
button11,
button12,
button13,
button14,
button15,
button16,
button17,
button18,
button19,
button20,
button21,
button22,
button23,
button24,
button25,
button26,
button27,
button28,
button29,
button30,
button31,
button32,
end_,
};
enum class pointing_event : uint32_t {
button,
x,
y,
vertical_wheel,
horizontal_wheel,
};
enum class modifier_flag : uint32_t {
zero,
none,
caps_lock,
left_control,
left_shift,
left_option,
left_command,
right_control,
right_shift,
right_option,
right_command,
fn,
prepared_modifier_flag_end_
};
enum class led_state : uint32_t {
on,
off,
};
enum class vendor_id : uint32_t {
};
enum class product_id : uint32_t {
};
enum class location_id : uint32_t {
};
enum class keyboard_type : uint32_t {
none = 0,
ansi = 40,
iso = 41,
jis = 42,
};
struct virtual_hid_keyboard_configuration_struct {
virtual_hid_keyboard_configuration_struct(void) : keyboard_type(keyboard_type::ansi),
caps_lock_delay_milliseconds(0) {}
bool operator==(const virtual_hid_keyboard_configuration_struct& other) const {
return keyboard_type == other.keyboard_type &&
caps_lock_delay_milliseconds == other.caps_lock_delay_milliseconds;
}
keyboard_type keyboard_type;
uint32_t caps_lock_delay_milliseconds;
};
struct device_identifiers_struct {
vendor_id vendor_id;
product_id product_id;
bool is_keyboard;
bool is_pointing_device;
};
struct device_configuration_struct {
bool ignore;
bool disable_built_in_keyboard_if_exists;
};
class types final {
public:
static modifier_flag get_modifier_flag(key_code key_code) {
switch (static_cast<uint32_t>(key_code)) {
case kHIDUsage_KeyboardLeftControl:
return modifier_flag::left_control;
case kHIDUsage_KeyboardLeftShift:
return modifier_flag::left_shift;
case kHIDUsage_KeyboardLeftAlt:
return modifier_flag::left_option;
case kHIDUsage_KeyboardLeftGUI:
return modifier_flag::left_command;
case kHIDUsage_KeyboardRightControl:
return modifier_flag::right_control;
case kHIDUsage_KeyboardRightShift:
return modifier_flag::right_shift;
case kHIDUsage_KeyboardRightAlt:
return modifier_flag::right_option;
case kHIDUsage_KeyboardRightGUI:
return modifier_flag::right_command;
case static_cast<uint32_t>(key_code::fn):
return modifier_flag::fn;
default:
return modifier_flag::zero;
}
}
// string -> hid usage map
static const std::unordered_map<std::string, key_code>& get_key_code_map(void) {
static std::unordered_map<std::string, key_code> map({
// From IOHIDUsageTables.h
{"a", key_code(kHIDUsage_KeyboardA)},
{"b", key_code(kHIDUsage_KeyboardB)},
{"c", key_code(kHIDUsage_KeyboardC)},
{"d", key_code(kHIDUsage_KeyboardD)},
{"e", key_code(kHIDUsage_KeyboardE)},
{"f", key_code(kHIDUsage_KeyboardF)},
{"g", key_code(kHIDUsage_KeyboardG)},
{"h", key_code(kHIDUsage_KeyboardH)},
{"i", key_code(kHIDUsage_KeyboardI)},
{"j", key_code(kHIDUsage_KeyboardJ)},
{"k", key_code(kHIDUsage_KeyboardK)},
{"l", key_code(kHIDUsage_KeyboardL)},
{"m", key_code(kHIDUsage_KeyboardM)},
{"n", key_code(kHIDUsage_KeyboardN)},
{"o", key_code(kHIDUsage_KeyboardO)},
{"p", key_code(kHIDUsage_KeyboardP)},
{"q", key_code(kHIDUsage_KeyboardQ)},
{"r", key_code(kHIDUsage_KeyboardR)},
{"s", key_code(kHIDUsage_KeyboardS)},
{"t", key_code(kHIDUsage_KeyboardT)},
{"u", key_code(kHIDUsage_KeyboardU)},
{"v", key_code(kHIDUsage_KeyboardV)},
{"w", key_code(kHIDUsage_KeyboardW)},
{"x", key_code(kHIDUsage_KeyboardX)},
{"y", key_code(kHIDUsage_KeyboardY)},
{"z", key_code(kHIDUsage_KeyboardZ)},
{"1", key_code(kHIDUsage_Keyboard1)},
{"2", key_code(kHIDUsage_Keyboard2)},
{"3", key_code(kHIDUsage_Keyboard3)},
{"4", key_code(kHIDUsage_Keyboard4)},
{"5", key_code(kHIDUsage_Keyboard5)},
{"6", key_code(kHIDUsage_Keyboard6)},
{"7", key_code(kHIDUsage_Keyboard7)},
{"8", key_code(kHIDUsage_Keyboard8)},
{"9", key_code(kHIDUsage_Keyboard9)},
{"0", key_code(kHIDUsage_Keyboard0)},
{"return_or_enter", key_code(kHIDUsage_KeyboardReturnOrEnter)},
{"escape", key_code(kHIDUsage_KeyboardEscape)},
{"delete_or_backspace", key_code(kHIDUsage_KeyboardDeleteOrBackspace)},
{"tab", key_code(kHIDUsage_KeyboardTab)},
{"spacebar", key_code(kHIDUsage_KeyboardSpacebar)},
{"hyphen", key_code(kHIDUsage_KeyboardHyphen)},
{"equal_sign", key_code(kHIDUsage_KeyboardEqualSign)},
{"open_bracket", key_code(kHIDUsage_KeyboardOpenBracket)},
{"close_bracket", key_code(kHIDUsage_KeyboardCloseBracket)},
{"backslash", key_code(kHIDUsage_KeyboardBackslash)},
{"non_us_pound", key_code(kHIDUsage_KeyboardNonUSPound)},
{"semicolon", key_code(kHIDUsage_KeyboardSemicolon)},
{"quote", key_code(kHIDUsage_KeyboardQuote)},
{"grave_accent_and_tilde", key_code(kHIDUsage_KeyboardGraveAccentAndTilde)},
{"comma", key_code(kHIDUsage_KeyboardComma)},
{"period", key_code(kHIDUsage_KeyboardPeriod)},
{"slash", key_code(kHIDUsage_KeyboardSlash)},
{"caps_lock", key_code(kHIDUsage_KeyboardCapsLock)},
{"f1", key_code(kHIDUsage_KeyboardF1)},
{"f2", key_code(kHIDUsage_KeyboardF2)},
{"f3", key_code(kHIDUsage_KeyboardF3)},
{"f4", key_code(kHIDUsage_KeyboardF4)},
{"f5", key_code(kHIDUsage_KeyboardF5)},
{"f6", key_code(kHIDUsage_KeyboardF6)},
{"f7", key_code(kHIDUsage_KeyboardF7)},
{"f8", key_code(kHIDUsage_KeyboardF8)},
{"f9", key_code(kHIDUsage_KeyboardF9)},
{"f10", key_code(kHIDUsage_KeyboardF10)},
{"f11", key_code(kHIDUsage_KeyboardF11)},
{"f12", key_code(kHIDUsage_KeyboardF12)},
{"print_screen", key_code(kHIDUsage_KeyboardPrintScreen)},
{"scroll_lock", key_code(kHIDUsage_KeyboardScrollLock)},
{"pause", key_code(kHIDUsage_KeyboardPause)},
{"insert", key_code(kHIDUsage_KeyboardInsert)},
{"home", key_code(kHIDUsage_KeyboardHome)},
{"page_up", key_code(kHIDUsage_KeyboardPageUp)},
{"delete_forward", key_code(kHIDUsage_KeyboardDeleteForward)},
{"end", key_code(kHIDUsage_KeyboardEnd)},
{"page_down", key_code(kHIDUsage_KeyboardPageDown)},
{"right_arrow", key_code(kHIDUsage_KeyboardRightArrow)},
{"left_arrow", key_code(kHIDUsage_KeyboardLeftArrow)},
{"down_arrow", key_code(kHIDUsage_KeyboardDownArrow)},
{"up_arrow", key_code(kHIDUsage_KeyboardUpArrow)},
{"keypad_num_lock", key_code(kHIDUsage_KeypadNumLock)},
{"keypad_slash", key_code(kHIDUsage_KeypadSlash)},
{"keypad_asterisk", key_code(kHIDUsage_KeypadAsterisk)},
{"keypad_hyphen", key_code(kHIDUsage_KeypadHyphen)},
{"keypad_plus", key_code(kHIDUsage_KeypadPlus)},
{"keypad_enter", key_code(kHIDUsage_KeypadEnter)},
{"keypad_1", key_code(kHIDUsage_Keypad1)},
{"keypad_2", key_code(kHIDUsage_Keypad2)},
{"keypad_3", key_code(kHIDUsage_Keypad3)},
{"keypad_4", key_code(kHIDUsage_Keypad4)},
{"keypad_5", key_code(kHIDUsage_Keypad5)},
{"keypad_6", key_code(kHIDUsage_Keypad6)},
{"keypad_7", key_code(kHIDUsage_Keypad7)},
{"keypad_8", key_code(kHIDUsage_Keypad8)},
{"keypad_9", key_code(kHIDUsage_Keypad9)},
{"keypad_0", key_code(kHIDUsage_Keypad0)},
{"keypad_period", key_code(kHIDUsage_KeypadPeriod)},
{"non_us_backslash", key_code(kHIDUsage_KeyboardNonUSBackslash)},
{"application", key_code(kHIDUsage_KeyboardApplication)},
{"power", key_code(kHIDUsage_KeyboardPower)},
{"keypad_equal_sign", key_code(kHIDUsage_KeypadEqualSign)},
{"f13", key_code(kHIDUsage_KeyboardF13)},
{"f14", key_code(kHIDUsage_KeyboardF14)},
{"f15", key_code(kHIDUsage_KeyboardF15)},
{"f16", key_code(kHIDUsage_KeyboardF16)},
{"f17", key_code(kHIDUsage_KeyboardF17)},
{"f18", key_code(kHIDUsage_KeyboardF18)},
{"f19", key_code(kHIDUsage_KeyboardF19)},
{"f20", key_code(kHIDUsage_KeyboardF20)},
{"f21", key_code(kHIDUsage_KeyboardF21)},
{"f22", key_code(kHIDUsage_KeyboardF22)},
{"f23", key_code(kHIDUsage_KeyboardF23)},
{"f24", key_code(kHIDUsage_KeyboardF24)},
{"execute", key_code(kHIDUsage_KeyboardExecute)},
{"help", key_code(kHIDUsage_KeyboardHelp)},
{"menu", key_code(kHIDUsage_KeyboardMenu)},
{"select", key_code(kHIDUsage_KeyboardSelect)},
{"stop", key_code(kHIDUsage_KeyboardStop)},
{"again", key_code(kHIDUsage_KeyboardAgain)},
{"undo", key_code(kHIDUsage_KeyboardUndo)},
{"cut", key_code(kHIDUsage_KeyboardCut)},
{"copy", key_code(kHIDUsage_KeyboardCopy)},
{"paste", key_code(kHIDUsage_KeyboardPaste)},
{"find", key_code(kHIDUsage_KeyboardFind)},
{"mute", key_code(kHIDUsage_KeyboardMute)},
{"volume_decrement", key_code(kHIDUsage_KeyboardVolumeDown)},
{"volume_increment", key_code(kHIDUsage_KeyboardVolumeUp)},
{"locking_caps_lock", key_code(kHIDUsage_KeyboardLockingCapsLock)},
{"locking_num_lock", key_code(kHIDUsage_KeyboardLockingNumLock)},
{"locking_scroll_lock", key_code(kHIDUsage_KeyboardLockingScrollLock)},
{"keypad_comma", key_code(kHIDUsage_KeypadComma)},
{"keypad_equal_sign_as400", key_code(kHIDUsage_KeypadEqualSignAS400)},
{"international1", key_code(kHIDUsage_KeyboardInternational1)},
{"international2", key_code(kHIDUsage_KeyboardInternational2)},
{"international3", key_code(kHIDUsage_KeyboardInternational3)},
{"international4", key_code(kHIDUsage_KeyboardInternational4)},
{"international5", key_code(kHIDUsage_KeyboardInternational5)},
{"international6", key_code(kHIDUsage_KeyboardInternational6)},
{"international7", key_code(kHIDUsage_KeyboardInternational7)},
{"international8", key_code(kHIDUsage_KeyboardInternational8)},
{"international9", key_code(kHIDUsage_KeyboardInternational9)},
{"lang1", key_code(kHIDUsage_KeyboardLANG1)},
{"lang2", key_code(kHIDUsage_KeyboardLANG2)},
{"lang3", key_code(kHIDUsage_KeyboardLANG3)},
{"lang4", key_code(kHIDUsage_KeyboardLANG4)},
{"lang5", key_code(kHIDUsage_KeyboardLANG5)},
{"lang6", key_code(kHIDUsage_KeyboardLANG6)},
{"lang7", key_code(kHIDUsage_KeyboardLANG7)},
{"lang8", key_code(kHIDUsage_KeyboardLANG8)},
{"lang9", key_code(kHIDUsage_KeyboardLANG9)},
{"alternate_erase", key_code(kHIDUsage_KeyboardAlternateErase)},
{"sys_req_or_attention", key_code(kHIDUsage_KeyboardSysReqOrAttention)},
{"cancel", key_code(kHIDUsage_KeyboardCancel)},
{"clear", key_code(kHIDUsage_KeyboardClear)},
{"prior", key_code(kHIDUsage_KeyboardPrior)},
{"return", key_code(kHIDUsage_KeyboardReturn)},
{"separator", key_code(kHIDUsage_KeyboardSeparator)},
{"out", key_code(kHIDUsage_KeyboardOut)},
{"oper", key_code(kHIDUsage_KeyboardOper)},
{"clear_or_again", key_code(kHIDUsage_KeyboardClearOrAgain)},
{"cr_sel_or_props", key_code(kHIDUsage_KeyboardCrSelOrProps)},
{"ex_sel", key_code(kHIDUsage_KeyboardExSel)},
{"left_control", key_code(kHIDUsage_KeyboardLeftControl)},
{"left_shift", key_code(kHIDUsage_KeyboardLeftShift)},
{"left_alt", key_code(kHIDUsage_KeyboardLeftAlt)},
{"left_gui", key_code(kHIDUsage_KeyboardLeftGUI)},
{"right_control", key_code(kHIDUsage_KeyboardRightControl)},
{"right_shift", key_code(kHIDUsage_KeyboardRightShift)},
{"right_alt", key_code(kHIDUsage_KeyboardRightAlt)},
{"right_gui", key_code(kHIDUsage_KeyboardRightGUI)},
// Extra
{"vk_none", key_code::vk_none},
{"fn", key_code::fn},
{"display_brightness_decrement", key_code::display_brightness_decrement},
{"display_brightness_increment", key_code::display_brightness_increment},
{"mission_control", key_code::mission_control},
{"launchpad", key_code::launchpad},
{"dashboard", key_code::dashboard},
{"illumination_decrement", key_code::illumination_decrement},
{"illumination_increment", key_code::illumination_increment},
{"rewind", key_code::rewind},
{"play_or_pause", key_code::play_or_pause},
{"fastforward", key_code::fastforward},
{"eject", key_code::eject},
{"apple_display_brightness_decrement", key_code::apple_display_brightness_decrement},
{"apple_display_brightness_increment", key_code::apple_display_brightness_increment},
{"apple_top_case_display_brightness_decrement", key_code::apple_top_case_display_brightness_decrement},
{"apple_top_case_display_brightness_increment", key_code::apple_top_case_display_brightness_increment},
// Aliases
{"left_option", key_code(kHIDUsage_KeyboardLeftAlt)},
{"left_command", key_code(kHIDUsage_KeyboardLeftGUI)},
{"right_option", key_code(kHIDUsage_KeyboardRightAlt)},
{"right_command", key_code(kHIDUsage_KeyboardRightGUI)},
{"japanese_eisuu", key_code(kHIDUsage_KeyboardLANG2)},
{"japanese_kana", key_code(kHIDUsage_KeyboardLANG1)},
{"japanese_pc_nfer", key_code(kHIDUsage_KeyboardInternational5)},
{"japanese_pc_xfer", key_code(kHIDUsage_KeyboardInternational4)},
{"japanese_pc_katakana", key_code(kHIDUsage_KeyboardInternational2)},
{"vk_consumer_brightness_down", key_code::display_brightness_decrement},
{"vk_consumer_brightness_up", key_code::display_brightness_increment},
{"vk_mission_control", key_code::mission_control},
{"vk_launchpad", key_code::launchpad},
{"vk_dashboard", key_code::dashboard},
{"vk_consumer_illumination_down", key_code::illumination_decrement},
{"vk_consumer_illumination_up", key_code::illumination_increment},
{"vk_consumer_previous", key_code::rewind},
{"vk_consumer_play", key_code::play_or_pause},
{"vk_consumer_next", key_code::fastforward},
{"volume_down", key_code(kHIDUsage_KeyboardVolumeDown)},
{"volume_up", key_code(kHIDUsage_KeyboardVolumeUp)},
});
return map;
}
static boost::optional<key_code> get_key_code(const std::string& name) {
auto& map = get_key_code_map();
auto it = map.find(name);
if (it == map.end()) {
return boost::none;
}
return it->second;
}
static boost::optional<key_code> get_key_code(uint32_t usage_page, uint32_t usage) {
switch (usage_page) {
case kHIDPage_KeyboardOrKeypad:
if (kHIDUsage_KeyboardErrorUndefined < usage && usage < kHIDUsage_Keyboard_Reserved) {
return krbn::key_code(usage);
}
break;
case kHIDPage_AppleVendorTopCase:
if (usage == kHIDUsage_AV_TopCase_KeyboardFn) {
return krbn::key_code::fn;
}
break;
case kHIDPage_AppleVendorKeyboard:
if (usage == kHIDUsage_AppleVendorKeyboard_Function) {
return krbn::key_code::fn;
}
break;
}
return boost::none;
}
static boost::optional<pqrs::karabiner_virtual_hid_device::usage_page> get_usage_page(key_code key_code) {
switch (key_code) {
case key_code::fn:
case key_code::illumination_decrement:
case key_code::illumination_increment:
case key_code::apple_top_case_display_brightness_decrement:
case key_code::apple_top_case_display_brightness_increment:
return pqrs::karabiner_virtual_hid_device::usage_page::apple_vendor_top_case;
case key_code::dashboard:
case key_code::launchpad:
case key_code::mission_control:
case key_code::apple_display_brightness_decrement:
case key_code::apple_display_brightness_increment:
return pqrs::karabiner_virtual_hid_device::usage_page::apple_vendor_keyboard;
case key_code::mute:
case key_code::volume_decrement:
case key_code::volume_increment:
case key_code::display_brightness_decrement:
case key_code::display_brightness_increment:
case key_code::rewind:
case key_code::play_or_pause:
case key_code::fastforward:
case key_code::eject:
return pqrs::karabiner_virtual_hid_device::usage_page::consumer;
default:
return pqrs::karabiner_virtual_hid_device::usage_page::keyboard_or_keypad;
}
}
static boost::optional<pqrs::karabiner_virtual_hid_device::usage> get_usage(key_code key_code) {
switch (key_code) {
case key_code::fn:
return pqrs::karabiner_virtual_hid_device::usage::av_top_case_keyboard_fn;
case key_code::illumination_decrement:
return pqrs::karabiner_virtual_hid_device::usage::av_top_case_illumination_down;
case key_code::illumination_increment:
return pqrs::karabiner_virtual_hid_device::usage::av_top_case_illumination_up;
case key_code::apple_top_case_display_brightness_decrement:
return pqrs::karabiner_virtual_hid_device::usage::av_top_case_brightness_down;
case key_code::apple_top_case_display_brightness_increment:
return pqrs::karabiner_virtual_hid_device::usage::av_top_case_brightness_up;
case key_code::dashboard:
return pqrs::karabiner_virtual_hid_device::usage::apple_vendor_keyboard_dashboard;
case key_code::launchpad:
return pqrs::karabiner_virtual_hid_device::usage::apple_vendor_keyboard_launchpad;
case key_code::mission_control:
return pqrs::karabiner_virtual_hid_device::usage::apple_vendor_keyboard_expose_all;
case key_code::apple_display_brightness_decrement:
return pqrs::karabiner_virtual_hid_device::usage::apple_vendor_keyboard_brightness_down;
case key_code::apple_display_brightness_increment:
return pqrs::karabiner_virtual_hid_device::usage::apple_vendor_keyboard_brightness_up;
case key_code::mute:
return pqrs::karabiner_virtual_hid_device::usage::csmr_mute;
case key_code::volume_decrement:
return pqrs::karabiner_virtual_hid_device::usage::csmr_volume_decrement;
case key_code::volume_increment:
return pqrs::karabiner_virtual_hid_device::usage::csmr_volume_increment;
case key_code::display_brightness_decrement:
return pqrs::karabiner_virtual_hid_device::usage::csmr_display_brightness_decrement;
case key_code::display_brightness_increment:
return pqrs::karabiner_virtual_hid_device::usage::csmr_display_brightness_increment;
case key_code::rewind:
return pqrs::karabiner_virtual_hid_device::usage::csmr_rewind;
case key_code::play_or_pause:
return pqrs::karabiner_virtual_hid_device::usage::csmr_play_or_pause;
case key_code::fastforward:
return pqrs::karabiner_virtual_hid_device::usage::csmr_fastforward;
case key_code::eject:
return pqrs::karabiner_virtual_hid_device::usage::csmr_eject;
default:
return pqrs::karabiner_virtual_hid_device::usage(key_code);
}
}
static boost::optional<pointing_button> get_pointing_button(uint32_t usage_page, uint32_t usage) {
if (usage_page == kHIDPage_Button) {
return krbn::pointing_button(usage);
}
return boost::none;
}
static const std::unordered_map<std::string, keyboard_type>& get_keyboard_type_map(void) {
static std::unordered_map<std::string, keyboard_type> map({
{"none", keyboard_type::none},
{"ansi", keyboard_type::ansi},
{"iso", keyboard_type::iso},
{"jis", keyboard_type::jis},
});
return map;
}
static boost::optional<keyboard_type> get_keyboard_type(const std::string& name) {
auto& map = get_keyboard_type_map();
auto it = map.find(name);
if (it == map.end()) {
return boost::none;
}
return it->second;
}
};
struct operation_type_connect_struct {
operation_type_connect_struct(void) : operation_type(operation_type::connect) {}
const operation_type operation_type;
connect_from connect_from;
pid_t pid;
};
struct operation_type_system_preferences_values_updated_struct {
operation_type_system_preferences_values_updated_struct(void) : operation_type(operation_type::system_preferences_values_updated) {}
const operation_type operation_type;
system_preferences::values values;
};
struct operation_type_clear_simple_modifications_struct {
operation_type_clear_simple_modifications_struct(void) : operation_type(operation_type::clear_simple_modifications) {}
const operation_type operation_type;
};
struct operation_type_add_simple_modification_struct {
operation_type_add_simple_modification_struct(void) : operation_type(operation_type::add_simple_modification) {}
const operation_type operation_type;
key_code from_key_code;
key_code to_key_code;
};
struct operation_type_clear_fn_function_keys_struct {
operation_type_clear_fn_function_keys_struct(void) : operation_type(operation_type::clear_fn_function_keys) {}
const operation_type operation_type;
};
struct operation_type_add_fn_function_key_struct {
operation_type_add_fn_function_key_struct(void) : operation_type(operation_type::add_fn_function_key) {}
const operation_type operation_type;
key_code from_key_code;
key_code to_key_code;
};
struct operation_type_virtual_hid_keyboard_configuration_updated_struct {
operation_type_virtual_hid_keyboard_configuration_updated_struct(void) : operation_type(operation_type::virtual_hid_keyboard_configuration_updated) {}
const operation_type operation_type;
virtual_hid_keyboard_configuration_struct virtual_hid_keyboard_configuration_struct;
};
struct operation_type_clear_devices_struct {
operation_type_clear_devices_struct(void) : operation_type(operation_type::clear_devices) {}
const operation_type operation_type;
};
struct operation_type_add_device_struct {
operation_type_add_device_struct(void) : operation_type(operation_type::add_device) {}
const operation_type operation_type;
device_identifiers_struct device_identifiers_struct;
device_configuration_struct device_configuration_struct;
};
struct operation_type_complete_devices_struct {
operation_type_complete_devices_struct(void) : operation_type(operation_type::complete_devices) {}
const operation_type operation_type;
};
}
| 37.034819 | 152 | 0.732165 | [
"vector"
] |
ab007de5ffbefaf6e85ec7ebe70e859387cecd03 | 4,788 | cpp | C++ | day10a.cpp | henbr/aoc2019 | 30f6ff902c5c48536db188bac1516df5dff2cb48 | [
"MIT"
] | null | null | null | day10a.cpp | henbr/aoc2019 | 30f6ff902c5c48536db188bac1516df5dff2cb48 | [
"MIT"
] | null | null | null | day10a.cpp | henbr/aoc2019 | 30f6ff902c5c48536db188bac1516df5dff2cb48 | [
"MIT"
] | null | null | null | #include <vector>
#include <string>
#include <iostream>
#include <numeric>
#include <limits>
using namespace std;
vector<string> input = {
/*
"#.#...#.#.",
".###....#.",
".#....#...",
"##.#.#.#.#",
"....#.#.#.",
".##..###.#",
"..#...##..",
"..##....##",
"......#...",
".####.###.",*/
/*
"#.........",
"...A......",
"...B..a...",
".EDCG....a",
"..F.c.b...",
".....c....",
"..efd.c.gb",
".......c..",
"....f...c.",
"...e..d..c",*/
/*
// 1234
".#..#",// 0
".....",// 1
"#####",// 2
"....#",// 3
"...##",// 4*/
"##.###.#.......#.#....#....#..........#.",
"....#..#..#.....#.##.............#......",
"...#.#..###..#..#.....#........#......#.",
"#......#.....#.##.#.##.##...#...#......#",
".............#....#.....#.#......#.#....",
"..##.....#..#..#.#.#....##.......#.....#",
".#........#...#...#.#.....#.....#.#..#.#",
"...#...........#....#..#.#..#...##.#.#..",
"#.##.#.#...#..#...........#..........#..",
"........#.#..#..##.#.##......##.........",
"................#.##.#....##.......#....",
"#............#.........###...#...#.....#",
"#....#..#....##.#....#...#.....#......#.",
".........#...#.#....#.#.....#...#...#...",
".............###.....#.#...##...........",
"...#...#.......#....#.#...#....#...#....",
".....#..#...#.#.........##....#...#.....",
"....##.........#......#...#...#....#..#.",
"#...#..#..#.#...##.#..#.............#.##",
".....#...##..#....#.#.##..##.....#....#.",
"..#....#..#........#.#.......#.##..###..",
"...#....#..#.#.#........##..#..#..##....",
".......#.##.....#.#.....#...#...........",
"........#.......#.#...........#..###..##",
"...#.....#..#.#.......##.###.###...#....",
"...............#..#....#.#....#....#.#..",
"#......#...#.....#.#........##.##.#.....",
"###.......#............#....#..#.#......",
"..###.#.#....##..#.......#.............#",
"##.#.#...#.#..........##.#..#...##......",
"..#......#..........#.#..#....##........",
"......##.##.#....#....#..........#...#..",
"#.#..#..#.#...........#..#.......#..#.#.",
"#.....#.#.........#............#.#..##.#",
".....##....#.##....#.....#..##....#..#..",
".#.......#......#.......#....#....#..#..",
"...#........#.#.##..#.#..#..#........#..",
"#........#.#......#..###....##..#......#",
"...#....#...#.....#.....#.##.#..#...#...",
"#.#.....##....#...........#.....#...#...",
};
struct Point {
int x = 0;
int y = 0;
int divisor = 0;
};
vector<vector<Point>> lookup = vector<vector<Point>>(input.size(), vector<Point>(input[0].length()));
void init_lookup() {
for (int y = 0; y < lookup.size(); y++) {
for (int x = 0; x < lookup[0].size(); x++) {
int divisor = gcd(x, y);
if (divisor != 0) {
lookup[y][x].divisor = divisor;
lookup[y][x].x = x / divisor;
lookup[y][x].y = y / divisor;
}
}
}
}
const Point get_gcd(int x, int y) {
const int ax = abs(x);
const int ay = abs(y);
auto res = lookup[ay][ax];
res.x = x < 0 ? res.x * -1 : res.x;
res.y = y < 0 ? res.y * -1 : res.y;
return res;
}
int get_num_visible_astroids(int xpos, int ypos) {
vector<vector<bool>> vis = vector<vector<bool>>(input.size(), vector<bool>(input[0].length(), false));
int count = 0;
for (int y = 0; y < input.size(); y++) {
for (int x = 0; x < input[0].length(); x++) {
if (input[y][x] == '.') {
continue;
}
if (x == xpos && y == ypos) {
continue;
}
const int dx = x - xpos;
const int dy = y - ypos;
const auto dgcd = get_gcd(dx, dy);
int vx = xpos + dgcd.x;
int vy = ypos + dgcd.y;
if (!vis[vy][vx]) {
// cout << x << ", " << y << endl;
count++;
vis[vy][vx] = true;
}
}
}
return count;
}
int main() {
init_lookup();
int max_count = numeric_limits<int>::min();
int maxx = 0;
int maxy = 0;
for (int y = 0; y < input.size(); y++) {
for (int x = 0; x < input[0].length(); x++) {
if (input[y][x] == '.') {
continue;
}
auto res = get_num_visible_astroids(x, y);
if (max_count < res) {
max_count = res;
maxx = x;
maxy = y;
}
}
}
// int max_count = get_num_visible_astroids(3,4);
cout << "Max: " << max_count << " at: " << maxx << ", " << maxy << endl;
return 0;
}
| 26.021739 | 106 | 0.225564 | [
"vector"
] |
ab0fba7c258e65d800b165dd09a07da3f61761ac | 3,117 | cpp | C++ | solutions/LeetCode/C++/955.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 854 | 2018-11-09T08:06:16.000Z | 2022-03-31T06:05:53.000Z | solutions/LeetCode/C++/955.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 29 | 2019-06-02T05:02:25.000Z | 2021-11-15T04:09:37.000Z | solutions/LeetCode/C++/955.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 347 | 2018-12-23T01:57:37.000Z | 2022-03-12T14:51:21.000Z | __________________________________________________________________________________________________
sample 8 ms submission
auto _ = []() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
return 0;
} ();
class Solution {
public:
int minDeletionSize(const vector<string>& a) {
int arrLen = int(a.size());
if (arrLen <= 1) {
return 0;
}
int strLen = int(a[0].size());
if (strLen == 0) {
return 0;
}
std::unordered_set<int> deletedIndices;
foo(deletedIndices, a, strLen, 0, arrLen - 1, 0);
return int(deletedIndices.size());
}
private:
void foo(std::unordered_set<int> & deletedIndices, const vector<string>& a, int strLen, int arrFromIndex, int arrToIndex, int strIndex) {
while (strIndex < strLen) {
char lastValue = 0;
int i = arrFromIndex;
while (i <= arrToIndex) {
char curValue = a[i][strIndex];
if (lastValue < curValue) {
++i;
} else if (lastValue > curValue) {
deletedIndices.insert(strIndex);
do {
++strIndex;
} while (deletedIndices.find(strIndex) != deletedIndices.end());
break;
} else {
int nextFromIndex = i - 1;
int nextToIndex = i + 1;
while (nextToIndex < arrToIndex && a[nextToIndex][strIndex] == lastValue) {
++nextToIndex;
}
i = nextToIndex;
int nextStrIndex = strIndex;
do {
++nextStrIndex;
} while (deletedIndices.find(nextStrIndex) != deletedIndices.end());
foo(deletedIndices, a, strLen, nextFromIndex, nextToIndex - 1, nextStrIndex);
}
lastValue = curValue;
}
if (i > arrToIndex) {
return;
}
}
}
};
__________________________________________________________________________________________________
sample 10072 kb submission
class Solution {
public:
int minDeletionSize(vector<string>& A) {
int N = (int)A.size(), M = (int)A[0].size();
int row, col;
vector<bool>sorted(N,false);
int res = 0;
for(col = 0; col < M; col++) {
for(row = 0; row < N -1; row ++) {
if(!sorted[row] && A[row][col] > A[row+1][col]){// not sorted, may just =, cannot >, can =
res++;
break;
}
}
if(row != N - 1) continue;//because res++
for(row = 0; row < N-1 ;row++) { // already < , so following col = or > is OK
if(A[row][col] < A[row+1][col])
sorted[row] = true;
}
}
return res;
}
};
__________________________________________________________________________________________________
| 35.420455 | 141 | 0.49984 | [
"vector"
] |
ab14741d4c671ab10e452e4eb342944d17965109 | 5,134 | cpp | C++ | src/messagedigest/windows/DigestEngineImpl.cpp | commshare/easyhttpcpp | 757ec75679c1cbc5f04c81a30133f4bcd3e780f4 | [
"MIT"
] | 147 | 2017-10-05T01:42:02.000Z | 2022-01-21T08:15:05.000Z | src/messagedigest/windows/DigestEngineImpl.cpp | commshare/easyhttpcpp | 757ec75679c1cbc5f04c81a30133f4bcd3e780f4 | [
"MIT"
] | 20 | 2018-05-17T01:55:16.000Z | 2021-04-20T07:27:00.000Z | src/messagedigest/windows/DigestEngineImpl.cpp | commshare/easyhttpcpp | 757ec75679c1cbc5f04c81a30133f4bcd3e780f4 | [
"MIT"
] | 32 | 2018-05-05T13:04:34.000Z | 2022-03-25T16:57:11.000Z | /*
* Copyright 2017 Sony Corporation
*/
#include "easyhttpcpp/common/CoreLogger.h"
#include "easyhttpcpp/common/StringUtil.h"
#include "easyhttpcpp/messagedigest/DigestConstants.h"
#include "easyhttpcpp/messagedigest/DigestUtil.h"
#include "easyhttpcpp/messagedigest/MessageDigestException.h"
#include "DigestEngineImpl.h"
using easyhttpcpp::common::Byte;
using easyhttpcpp::common::StringUtil;
namespace easyhttpcpp {
namespace messagedigest {
static const std::string Tag = "DigestEngineImpl";
DigestEngineImpl::DigestEngineImpl(const std::string& algorithm)
{
if (!CryptAcquireContext(&m_cspHandle, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) {
std::string message = StringUtil::format("Error occurred while acquiring crypto context. Details: 0x%08x",
GetLastError());
EASYHTTPCPP_LOG_D(Tag, message.c_str());
throw MessageDigestExecutionException(message);
}
m_algorithmId = getAlgorithmIdFromString(algorithm);
if (!CryptCreateHash(m_cspHandle, m_algorithmId, 0, 0, &m_hashHandle)) {
std::string message = StringUtil::format("Error occurred while creating hash object. Details: 0x%08x",
GetLastError());
EASYHTTPCPP_LOG_D(Tag, message.c_str());
throw MessageDigestExecutionException(message);
}
}
DigestEngineImpl::~DigestEngineImpl()
{
if (m_hashHandle) {
CryptDestroyHash(m_hashHandle);
}
if (m_cspHandle) {
CryptReleaseContext(m_cspHandle, 0);
}
}
void DigestEngineImpl::update(const Byte* data, size_t length)
{
if (!CryptHashData(m_hashHandle, static_cast<const BYTE*>(data), static_cast<DWORD>(length), 0)) {
std::string message = StringUtil::format("Error occurred while updating the digest with given data. Details: 0x%08x",
GetLastError());
EASYHTTPCPP_LOG_D(Tag, message.c_str());
throw MessageDigestExecutionException(message);
}
}
void DigestEngineImpl::reset()
{
if (m_hashHandle) {
CryptDestroyHash(m_hashHandle);
}
if (!CryptCreateHash(m_cspHandle, m_algorithmId, 0, 0, &m_hashHandle)) {
std::string message = StringUtil::format("Error occurred while resetting the engine. Details: 0x%08x",
GetLastError());
EASYHTTPCPP_LOG_D(Tag, message.c_str());
throw MessageDigestExecutionException(message);
}
}
std::vector<unsigned char> DigestEngineImpl::digest()
{
// allocate the buffer which store the hash value.
PBYTE pHashData = NULL;
try {
DWORD dataLength = 0;
if (!CryptGetHashParam(m_hashHandle, HP_HASHVAL, NULL, &dataLength, 0)) {
std::string message = StringUtil::format("Error occurred while calculating hash size. Details: 0x%08x",
GetLastError());
EASYHTTPCPP_LOG_D(Tag, message.c_str());
throw MessageDigestExecutionException(message);
}
pHashData = (BYTE*)malloc(dataLength);
if (!pHashData) {
std::string message = StringUtil::format("Unable to allocate memory for hash calculation.");
EASYHTTPCPP_LOG_D(Tag, message.c_str());
throw MessageDigestExecutionException(message);
}
// get hash value
if (!CryptGetHashParam(m_hashHandle, HP_HASHVAL, pHashData, &dataLength, 0)) {
std::string message = StringUtil::format("Error occurred while calculating hash. Details: 0x%08x",
GetLastError());
EASYHTTPCPP_LOG_D(Tag, message.c_str());
throw MessageDigestExecutionException(message);
}
std::vector<unsigned char> hashData;
hashData.assign(&pHashData[0], &pHashData[dataLength]);
// reset the engine
reset();
free(pHashData);
return hashData;
} catch (const MessageDigestException& e) {
EASYHTTPCPP_LOG_D(Tag, "Error occurred while calculating hash. Details: %s", e.getMessage().c_str());
free(pHashData);
throw;
}
}
std::string DigestEngineImpl::digestToHex(const std::vector<unsigned char>& digest)
{
static const char digits[] = "0123456789abcdef";
std::string result;
result.reserve(digest.size() * 2);
for (std::vector<unsigned char>::const_iterator it = digest.begin(); it != digest.end(); ++it) {
unsigned char c = *it;
result += digits[(c >> 4) & 0xF];
result += digits[c & 0xF];
}
return result;
}
unsigned int DigestEngineImpl::getAlgorithmIdFromString(const std::string algorithm)
{
if (algorithm == DigestConstants::MessageDigestAlgorithmSha256) {
return CALG_SHA_256;
} else if (algorithm == DigestConstants::MessageDigestAlgorithmSha1) {
return CALG_SHA1;
} else if (algorithm == DigestConstants::MessageDigestAlgorithmMd5) {
return CALG_MD5;
} else {
std::string message = StringUtil::format("Unsupported algorithm. algorithm: %s", algorithm.c_str());
EASYHTTPCPP_LOG_D(Tag, message.c_str());
throw MessageDigestExecutionException(message);
}
}
} /* namespace messagedigest */
} /* namespace easyhttpcpp */
| 35.164384 | 125 | 0.673744 | [
"object",
"vector"
] |
ab1f0b7b1d80490ed5d4418c5bf375f0dd2d7c15 | 9,864 | cc | C++ | src/primitives/matrix_test.cc | elp2/ray-tracer-challenge | 685ed92c1c0b4483d6f18ccbc7c678a55d0eb541 | [
"Apache-2.0"
] | 1 | 2020-12-23T05:00:13.000Z | 2020-12-23T05:00:13.000Z | src/primitives/matrix_test.cc | elp2/ray-tracer-challenge | 685ed92c1c0b4483d6f18ccbc7c678a55d0eb541 | [
"Apache-2.0"
] | null | null | null | src/primitives/matrix_test.cc | elp2/ray-tracer-challenge | 685ed92c1c0b4483d6f18ccbc7c678a55d0eb541 | [
"Apache-2.0"
] | 1 | 2021-05-18T22:19:08.000Z | 2021-05-18T22:19:08.000Z | #include "gtest/gtest.h"
#include "primitives/matrix.h"
#include "primitives/tuple.h"
class MatrixTest : public ::testing::Test {
protected:
MatrixTest() {};
~MatrixTest() {};
};
TEST(MatrixTest, SetGet) {
Matrix m = Matrix(3, 4);
ASSERT_FLOAT_EQ(m(0, 0), 0.0);
m.Set(1.0, 1, 1);
ASSERT_FLOAT_EQ(m(1, 1), 1.0);
}
TEST(MatrixTest, FourByFour) {
std::vector<float> values = {1, 2, 3, 4,
5.5, 6.5, 7.5, 8.5,
9, 10, 11, 12,
13.5, 14.5, 15.5, 16.5};
Matrix m = Matrix(4, 4, values);
ASSERT_FLOAT_EQ(m(0, 0), 1);
ASSERT_FLOAT_EQ(m(1, 0), 5.5);
ASSERT_FLOAT_EQ(m(0, 3), 4);
ASSERT_FLOAT_EQ(m(1, 2), 7.5);
ASSERT_FLOAT_EQ(m(2, 2), 11);
ASSERT_FLOAT_EQ(m(3, 0), 13.5);
ASSERT_FLOAT_EQ(m(3, 2), 15.5);
}
TEST(MatrixTest, TwoByTwo) {
std::vector<float> values = {-3, 5,
1, -2};
Matrix m = Matrix(2, 2, values);
ASSERT_FLOAT_EQ(m(0, 0), -3);
ASSERT_FLOAT_EQ(m(0, 1), 5);
ASSERT_FLOAT_EQ(m(1, 0), 1);
ASSERT_FLOAT_EQ(m(1, 1), -2);
}
TEST(MatrixTest, ThreeByThree) {
std::vector<float> values = {-3, 5, 0,
1, -2, -7,
0, 1, 1};
Matrix m = Matrix(3, 3, values);
ASSERT_FLOAT_EQ(m(0, 0), -3);
ASSERT_FLOAT_EQ(m(1, 1), -2);
ASSERT_FLOAT_EQ(m(2, 2), 1);
}
TEST(MatrixTest, Equal) {
std::vector<float> values = {1, 2, 3, 4,
5, 6, 7, 8,
9, 8, 7, 6,
5, 4, 3, 2};
Matrix a = Matrix(4, 4, values);
Matrix b = Matrix(4, 4, values);
ASSERT_EQ(a, b);
}
TEST(MatrixTest, NotEqual) {
std::vector<float> values = {1, 2, 3, 4,
5, 6, 7, 8,
9, 8, 7, 6,
5, 4, 3, 2};
Matrix a = Matrix(4, 4, values);
for (int i = 0; i < 16; ++i) {
float orig = values[i];
values[i] = 99;
Matrix b = Matrix(4, 4, values);
ASSERT_NE(a, b);
values[i] = orig;
}
Matrix b = Matrix(4, 4, values);
ASSERT_EQ(a, b);
}
TEST(MatrixTest, MultiplyMatrix) {
std::vector<float> avalues = {1, 2, 3, 4,
5, 6, 7, 8,
9, 8, 7, 6,
5, 4, 3, 2};
Matrix a = Matrix(4, 4, avalues);
std::vector<float> bvalues = {-2, 1, 2, 3,
3, 2, 1, -1,
4, 3, 6, 5,
1, 2, 7, 8};
Matrix b = Matrix(4, 4, bvalues);
Matrix mult = a * b;
std::vector<float> expected = {20, 22, 50, 48,
44, 54, 114, 108,
40, 58, 110, 102,
16, 26, 46, 42};
Matrix exp = Matrix(4, 4, expected);
ASSERT_EQ(mult, exp);
}
TEST(MatrixTest, MultiplyTuple) {
std::vector<float> values = {1, 2, 3, 4,
2, 4, 4, 2,
8, 6, 4, 1,
0, 0, 0, 1};
Matrix m = Matrix(4, 4, values);
Tuple t = Tuple(1, 2, 3, 1);
Tuple ret = m * t;
ASSERT_EQ(Tuple(18, 24, 33, 1), ret);
}
TEST(MatrixTest, MultiplyIdentity) {
std::vector<float> values = {1, 2, 3, 4,
2, 4, 4, 2,
8, 6, 4, 1,
0, 0, 0, 1};
Matrix m = Matrix(4, 4, values);
ASSERT_EQ(m, m * IdentityMatrix(4));
}
TEST(MatrixTest, MultiplyTupleIdentity) {
Tuple t = Tuple(1, 2, 3, 1);
ASSERT_EQ(t, IdentityMatrix(4) * t);
}
TEST(MatrixTest, Transpose) {
Matrix m = Matrix(4, 4, std::vector<float> { 0, 9, 3, 0,
9, 8, 0, 8,
1, 8, 5, 3,
0, 0, 5, 8 });
Matrix t = Matrix(4, 4, std::vector<float> { 0, 9, 1, 0,
9, 8, 8, 0,
3, 0, 5, 5,
0, 8, 3, 8 });
ASSERT_EQ(m.Transpose(), t);
}
TEST(MatrixTest, DeterminantOf2x2) {
Matrix m = Matrix(2, 2, std::vector<float> { 1, 5,
-3, 2 });
ASSERT_FLOAT_EQ(m.Determinant(), 17);
}
TEST(MatrixTest, SubmatrixOf3x3Is2x2) {
Matrix three = Matrix(3, 3, std::vector<float> { 1, 5, 0,
-3, 2, 7,
0, 6, -3 });
Matrix sub = Matrix(2, 2, std::vector<float> { -3, 2,
0, 6 });
ASSERT_EQ(three.SubMatrix(0, 2), sub);
}
TEST(MatrixTest, SubmatrixOf4x4Is3x3) {
Matrix fourx4 = Matrix(4, 4, std::vector<float> { -6, 1, 1, 6,
-8, 5, 8, 6,
-1, 0, 8, 2,
-7, 1, -1, 1 });
Matrix threex3 = Matrix(3, 3, std::vector<float> { -6, 1, 6,
-8, 8, 6,
-7, -1, 1 });
ASSERT_EQ(fourx4.SubMatrix(2, 1), threex3);
}
TEST(MatrixTest, MinorOf3x3) {
Matrix three = Matrix(3, 3, std::vector<float> { 3, 5, 0,
2, -1, -7,
6, -1, 5 });
ASSERT_FLOAT_EQ(three.Minor(1, 0), 25);
}
TEST(MatrixTest, CofactorOf3x3) {
Matrix three = Matrix(3, 3, std::vector<float> { 3, 5, 0,
2, -1, -7,
6, -1, 5 });
ASSERT_FLOAT_EQ(three.Minor(0, 0), -12);
ASSERT_FLOAT_EQ(three.Cofactor(0, 0), -12);
ASSERT_FLOAT_EQ(three.Minor(1, 0), 25);
ASSERT_FLOAT_EQ(three.Cofactor(1, 0), -25);
}
TEST(MatrixTest, DeterminantOf3x3) {
Matrix m = Matrix(3, 3, std::vector<float> { 1, 2, 6,
-5, 8, -4,
2, 6, 4 });
ASSERT_FLOAT_EQ(m.Cofactor(0, 0), 56);
ASSERT_FLOAT_EQ(m.Cofactor(0, 1), 12);
ASSERT_FLOAT_EQ(m.Cofactor(0, 2), -46);
ASSERT_FLOAT_EQ(m.Determinant(), -196);
}
TEST(MatrixTest, DeterminantOf4x4) {
Matrix m = Matrix(4, 4, std::vector<float> { -2, -8, 3, 5,
-3, 1, 7, 3,
1, 2, -9, 6,
-6, 7, 7, -9 });
ASSERT_FLOAT_EQ(m.Cofactor(0, 0), 690);
ASSERT_FLOAT_EQ(m.Cofactor(0, 1), 447);
ASSERT_FLOAT_EQ(m.Cofactor(0, 2), 210);
ASSERT_FLOAT_EQ(m.Cofactor(0, 3), 51);
ASSERT_FLOAT_EQ(m.Determinant(), -4071);
}
TEST(MatrixTest, IsInvertable) {
Matrix m = Matrix(4, 4, std::vector<float> { 6, 4, 4, 4,
5, 5, 7, 6,
4, -9, 3, -7,
9, 1, 7, -6});
ASSERT_FLOAT_EQ(m.Determinant(), -2120);
ASSERT_TRUE(m.Invertible());
}
TEST(MatrixTest, NotInvertable) {
Matrix m = Matrix(4, 4, std::vector<float> { -4, 2, -2, -3,
9, 6, 2, 6,
0, -5, 1, -5,
0, 0, 0, 0 });
ASSERT_FLOAT_EQ(m.Determinant(), 0);
ASSERT_FALSE(m.Invertible());
}
TEST(MatrixTest, InverseOfMatrix) {
Matrix a = Matrix(4, 4, std::vector<float> { -5, 2, 6, -8,
1, -5, 1, 8,
7, 7, -6, -7,
1, -3, 7, 4 });
Matrix b = a.Inverse();
ASSERT_FLOAT_EQ(a.Determinant(), 532.0);
ASSERT_FLOAT_EQ(a.Cofactor(2, 3), -160.0);
ASSERT_FLOAT_EQ(b(3, 2), -160.0 / 532.0);
ASSERT_FLOAT_EQ(a.Cofactor(3, 2), 105.0);
ASSERT_FLOAT_EQ(b(2, 3), 105.0 / 532.0);
Matrix b_expected = Matrix(4, 4, std::vector<float> {0.21805, 0.45113, 0.24060, -0.04511,
-0.80827, -1.45677, -0.44361, 0.52068,
-0.07895, -0.22368, -0.05263, 0.19737,
-0.52256, -0.81391, -0.30075, 0.30639 });
ASSERT_EQ(b, b_expected);
}
TEST(MatrixTest, InverseA) {
Matrix a = Matrix(4, 4, std::vector<float> { 8, -5, 9, 2,
7, 5, 6, 1,
-6, 0, 9, 6,
-3, 0, -9, -4 });
Matrix expected = Matrix(4, 4, std::vector<float> { -0.15385, -0.15385, -0.28205, -0.53846,
-0.07692, 0.12308, 0.02564, 0.03077,
0.35897, 0.35897, 0.43590, 0.92308,
-0.69231, -0.69231, -0.76923, -1.92308});
ASSERT_EQ(a.Inverse(), expected);
}
TEST(MatrixTest, InverseB) {
Matrix a = Matrix(4, 4, std::vector<float> { 9, 3, 0, 9,
-5, -2, -6, -3,
-4, 9, 6, 4,
-7, 6, 6, 2 });
Matrix expected = Matrix(4, 4, std::vector<float> {
-0.04074, -0.07778, 0.14444, -0.22222,
-0.07778, 0.03333, 0.36667, -0.33333,
-0.02901, -0.14630, -0.10926, 0.12963,
0.17778, 0.06667, -0.26667, 0.33333
});
ASSERT_EQ(a.Inverse(), expected);
}
TEST(MatrixTest, MultiplyProductByInverse) {
Matrix a = Matrix(4, 4, std::vector<float> {
3, -9, 7, 3,
3, -8, 2, -9,
-4, 4, 4, 1,
-6, 5, -1, 1
});
Matrix b = Matrix(4, 4, std::vector<float> {
8, 2, 2, 2,
3, -1, 7, 0,
7, 0, 5, 4,
6, -2, 0, 5
});
Matrix c = a * b;
ASSERT_EQ(c * b.Inverse(), a);
}
| 34.013793 | 95 | 0.410381 | [
"vector"
] |
ab239aaf51e8d9c93dfa2be9e543b38eaaf200b5 | 508 | cpp | C++ | Disruptor.PerfTests/EventCountingWorkHandler.cpp | ulricheck/Disruptor-cpp | fd2cef124f5bf2dbbe399137fd69e85844b90a6b | [
"Apache-2.0"
] | 250 | 2017-12-21T15:19:30.000Z | 2022-03-30T05:55:24.000Z | Disruptor.PerfTests/EventCountingWorkHandler.cpp | ulricheck/Disruptor-cpp | fd2cef124f5bf2dbbe399137fd69e85844b90a6b | [
"Apache-2.0"
] | 14 | 2018-06-21T22:57:47.000Z | 2022-01-26T07:48:47.000Z | Disruptor.PerfTests/EventCountingWorkHandler.cpp | ulricheck/Disruptor-cpp | fd2cef124f5bf2dbbe399137fd69e85844b90a6b | [
"Apache-2.0"
] | 84 | 2018-01-06T13:55:54.000Z | 2022-01-20T07:15:55.000Z | #include "stdafx.h"
#include "EventCountingWorkHandler.h"
namespace Disruptor
{
namespace PerfTests
{
EventCountingWorkHandler::EventCountingWorkHandler(const std::vector< std::shared_ptr< PaddedLong > >& counters, std::int32_t index)
: m_counters(counters)
, m_index(index)
{
}
void EventCountingWorkHandler::onEvent(ValueEvent& /*evt*/)
{
m_counters[m_index]->value = m_counters[m_index]->value + 1L;
}
} // namespace PerfTests
} // namespace Disruptor
| 22.086957 | 136 | 0.688976 | [
"vector"
] |
ab23fe923097466b86438a8a7c645dbed9442f7e | 3,357 | cpp | C++ | Fierce-Engine/src/system/render/vulkan/VK_Renderpass.cpp | TB989/Fierce-Engine-V1 | 007d41dec19b461a66595a6c5d4dae5e3ce8880d | [
"Apache-2.0"
] | null | null | null | Fierce-Engine/src/system/render/vulkan/VK_Renderpass.cpp | TB989/Fierce-Engine-V1 | 007d41dec19b461a66595a6c5d4dae5e3ce8880d | [
"Apache-2.0"
] | null | null | null | Fierce-Engine/src/system/render/vulkan/VK_Renderpass.cpp | TB989/Fierce-Engine-V1 | 007d41dec19b461a66595a6c5d4dae5e3ce8880d | [
"Apache-2.0"
] | null | null | null | #include "VK_Renderpass.h"
#include "VK_Device.h"
VK_Renderpass::VK_Renderpass(VK_Device* device){
m_device = device;
}
VK_Renderpass::~VK_Renderpass(){
vkDestroyRenderPass(m_device->getDevice(), renderpass,nullptr);
}
void VK_Renderpass::create() {
VkSubpassDescription subpass{};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = attachmentReferences.size();
subpass.pColorAttachments = attachmentReferences.data();
subpass.flags = 0;
subpass.inputAttachmentCount = 0;
subpass.pInputAttachments = nullptr;
subpass.pDepthStencilAttachment = nullptr;
subpass.preserveAttachmentCount = 0;
subpass.pPreserveAttachments = nullptr;
subpass.pResolveAttachments = nullptr;
std::vector<VkSubpassDependency> dependencies;
dependencies.push_back(VkSubpassDependency{});
dependencies.push_back(VkSubpassDependency{});
dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL;
dependencies[0].dstSubpass = 0;
dependencies[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
dependencies[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT;
dependencies[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
dependencies[1].srcSubpass = 0;
dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL;
dependencies[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
dependencies[1].dstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
dependencies[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
dependencies[1].dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
VkRenderPassCreateInfo renderPassInfo{};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
renderPassInfo.flags = 0;
renderPassInfo.pNext = nullptr;
renderPassInfo.attachmentCount = attachments.size();
renderPassInfo.pAttachments = attachments.data();
renderPassInfo.subpassCount = 1;
renderPassInfo.pSubpasses = &subpass;
renderPassInfo.dependencyCount = dependencies.size();
renderPassInfo.pDependencies = dependencies.data();
CHECK_VK(vkCreateRenderPass(m_device->getDevice(), &renderPassInfo, nullptr, &renderpass), "Failed to create render pass.");
}
void VK_Renderpass::addAttachment(VkImageLayout initialLayout, VkImageLayout finalLayout,VkImageLayout layout) {
VkAttachmentDescription attachment{};
attachment.flags = 0;
attachment.format = m_device->getSurfaceData()->swapchainFormat.format;
attachment.samples = VK_SAMPLE_COUNT_1_BIT;
attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachment.initialLayout = initialLayout;
attachment.finalLayout = finalLayout;
attachments.push_back(attachment);
VkAttachmentReference reference{};
reference.attachment = counter;
reference.layout = layout;
attachmentReferences.push_back(reference);
counter++;
} | 41.444444 | 128 | 0.785523 | [
"render",
"vector"
] |
ab2b1607e08a0ee3865c82dc227be6cdc5e30fde | 7,892 | cpp | C++ | SDL_Core/src/components/JSONHandler/src/RPC2ObjectsImpl/NsRPC2Communication/UI/AlertMarshaller.cpp | tizenorg/profile.ivi.smartdevicelink | fed006e168bb6fa6bdab49c7e07031cd3eb495fc | [
"BSD-3-Clause"
] | null | null | null | SDL_Core/src/components/JSONHandler/src/RPC2ObjectsImpl/NsRPC2Communication/UI/AlertMarshaller.cpp | tizenorg/profile.ivi.smartdevicelink | fed006e168bb6fa6bdab49c7e07031cd3eb495fc | [
"BSD-3-Clause"
] | null | null | null | SDL_Core/src/components/JSONHandler/src/RPC2ObjectsImpl/NsRPC2Communication/UI/AlertMarshaller.cpp | tizenorg/profile.ivi.smartdevicelink | fed006e168bb6fa6bdab49c7e07031cd3eb495fc | [
"BSD-3-Clause"
] | null | null | null | //
// Copyright (c) 2013, Ford Motor Company
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with the
// distribution.
//
// Neither the name of the Ford Motor Company nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
#include "../src/../include/JSONHandler/RPC2Objects/NsRPC2Communication/UI/Alert.h"
#include "../src/SDLRPCObjectsImpl/V2/TTSChunkMarshaller.h"
#include "../src/SDLRPCObjectsImpl/V2/SoftButtonMarshaller.h"
#include "../src/SDLRPCObjectsImpl/V2/ResultMarshaller.h"
#include "../src/../src/RPC2ObjectsImpl//NsRPC2Communication/UI/AlertMarshaller.h"
/*
interface NsRPC2Communication::UI
version 1.2
generated at Thu Jan 24 06:41:15 2013
source stamp Wed Jan 23 13:56:28 2013
author RC
*/
using namespace NsRPC2Communication::UI;
bool AlertMarshaller::checkIntegrity(Alert& s)
{
return checkIntegrityConst(s);
}
bool AlertMarshaller::fromString(const std::string& s,Alert& e)
{
try
{
Json::Reader reader;
Json::Value json;
if(!reader.parse(s,json,false)) return false;
if(!fromJSON(json,e)) return false;
}
catch(...)
{
return false;
}
return true;
}
const std::string AlertMarshaller::toString(const Alert& e)
{
Json::FastWriter writer;
return checkIntegrityConst(e) ? writer.write(toJSON(e)) : "";
}
bool AlertMarshaller::checkIntegrityConst(const Alert& s)
{
if(s.AlertText1 && (s.AlertText1[0].length()>500)) return false;
if(s.AlertText2 && (s.AlertText2[0].length()>500)) return false;
if(s.AlertText3 && (s.AlertText3[0].length()>500)) return false;
if(s.ttsChunks)
{
unsigned int i=s.ttsChunks[0].size();
if(i<1) return false;
if(i>100) return false;
}
if(s.duration && (s.duration[0]<3000 || s.duration[0]>10000)) return false;
if(s.softButtons)
{
unsigned int i=s.softButtons[0].size();
if(i<0) return false;
if(i>4) return false;
}
return true;
}
Json::Value AlertMarshaller::toJSON(const Alert& e)
{
Json::Value json(Json::objectValue);
if(!checkIntegrityConst(e))
return Json::Value(Json::nullValue);
json["jsonrpc"]=Json::Value("2.0");
json["method"]=Json::Value("UI.Alert");
json["id"]=Json::Value(e.getId());
json["params"]=Json::Value(Json::objectValue);
if(e.AlertText1)
json["params"]["AlertText1"]=Json::Value(e.AlertText1[0]);;
if(e.AlertText2)
json["params"]["AlertText2"]=Json::Value(e.AlertText2[0]);;
if(e.AlertText3)
json["params"]["AlertText3"]=Json::Value(e.AlertText3[0]);;
if(e.ttsChunks)
{
unsigned int i=e.ttsChunks[0].size();
Json::Value j=Json::Value(Json::arrayValue);
j.resize(i);
while(i--)
j[i]=NsSmartDeviceLinkRPCV2::TTSChunkMarshaller::toJSON(e.ttsChunks[0][i]);
json["params"]["ttsChunks"]=j;
}
if(e.duration)
json["params"]["duration"]=Json::Value(e.duration[0]);;
if(e.playTone)
json["params"]["playTone"]=Json::Value(e.playTone[0]);;
if(e.softButtons)
{
unsigned int i=e.softButtons[0].size();
Json::Value j=Json::Value(Json::arrayValue);
j.resize(i);
while(i--)
j[i]=NsSmartDeviceLinkRPCV2::SoftButtonMarshaller::toJSON(e.softButtons[0][i]);
json["params"]["softButtons"]=j;
}
json["params"]["appId"]=Json::Value(e.appId);;
return json;
}
bool AlertMarshaller::fromJSON(const Json::Value& json,Alert& c)
{
try
{
if(!json.isObject()) return false;
if(!json.isMember("jsonrpc") || !json["jsonrpc"].isString() || json["jsonrpc"].asString().compare("2.0")) return false;
if(!json.isMember("method") || !json["method"].isString() || json["method"].asString().compare("UI.Alert")) return false;
if(!json.isMember("id") || !json["id"].isInt()) return false;
c.setId(json["id"].asInt());
if(!json.isMember("params")) return false;
Json::Value js=json["params"];
if(!js.isObject()) return false;
if(c.AlertText1) delete c.AlertText1;
c.AlertText1=0;
if(js.isMember("AlertText1"))
{
if(!js["AlertText1"].isString()) return false;
c.AlertText1=new std::string();
c.AlertText1[0]=js["AlertText1"].asString();
if(c.AlertText1[0].length()>500) return false;
}
if(c.AlertText2) delete c.AlertText2;
c.AlertText2=0;
if(js.isMember("AlertText2"))
{
if(!js["AlertText2"].isString()) return false;
c.AlertText2=new std::string();
c.AlertText2[0]=js["AlertText2"].asString();
if(c.AlertText2[0].length()>500) return false;
}
if(c.AlertText3) delete c.AlertText3;
c.AlertText3=0;
if(js.isMember("AlertText3"))
{
if(!js["AlertText3"].isString()) return false;
c.AlertText3=new std::string();
c.AlertText3[0]=js["AlertText3"].asString();
if(c.AlertText3[0].length()>500) return false;
}
if(c.ttsChunks) delete c.ttsChunks;
c.ttsChunks=0;
if(js.isMember("ttsChunks"))
{
if(!js["ttsChunks"].isArray()) return false;
unsigned int i=js["ttsChunks"].size();
if(i<1) return false;
if(i>100) return false;
c.ttsChunks=new std::vector<NsSmartDeviceLinkRPCV2::TTSChunk>();
c.ttsChunks->resize(js["ttsChunks"].size());
while(i--)
if(!NsSmartDeviceLinkRPCV2::TTSChunkMarshaller::fromJSON(js["ttsChunks"][i],c.ttsChunks[0][i])) return false;
}
if(c.duration) delete c.duration;
c.duration=0;
if(js.isMember("duration"))
{
if(!js["duration"].isInt()) return false;
c.duration=new unsigned int();
c.duration[0]=js["duration"].asInt();
if(c.duration[0]<3000 || c.duration[0]>10000) return false;
}
if(c.playTone) delete c.playTone;
c.playTone=0;
if(js.isMember("playTone"))
{
if(!js["playTone"].isBool()) return false;
c.playTone=new bool();
c.playTone[0]=js["playTone"].asBool();
}
if(c.softButtons) delete c.softButtons;
c.softButtons=0;
if(js.isMember("softButtons"))
{
if(!js["softButtons"].isArray()) return false;
unsigned int i=js["softButtons"].size();
if(i<0) return false;
if(i>4) return false;
c.softButtons=new std::vector<NsSmartDeviceLinkRPCV2::SoftButton>();
c.softButtons->resize(js["softButtons"].size());
while(i--)
if(!NsSmartDeviceLinkRPCV2::SoftButtonMarshaller::fromJSON(js["softButtons"][i],c.softButtons[0][i])) return false;
}
if(!js.isMember("appId") || !js["appId"].isInt()) return false;
c.appId=js["appId"].asInt();
}
catch(...)
{
return false;
}
return checkIntegrity(c);
}
| 29.781132 | 126 | 0.661556 | [
"vector"
] |
ab2d008e9a55bb23fbdde4fe590af61c5787705e | 2,674 | cpp | C++ | src/strategy/generic/ConserveManaStrategy.cpp | htc16/mod-playerbots | 2307e3f980035a244bfb4fedefda5bc55903d470 | [
"MIT"
] | 12 | 2022-03-23T05:14:53.000Z | 2022-03-30T12:12:58.000Z | src/strategy/generic/ConserveManaStrategy.cpp | htc16/mod-playerbots | 2307e3f980035a244bfb4fedefda5bc55903d470 | [
"MIT"
] | 24 | 2022-03-23T13:56:37.000Z | 2022-03-31T18:23:32.000Z | src/strategy/generic/ConserveManaStrategy.cpp | htc16/mod-playerbots | 2307e3f980035a244bfb4fedefda5bc55903d470 | [
"MIT"
] | 3 | 2022-03-24T21:47:10.000Z | 2022-03-31T06:21:46.000Z | /*
* Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU GPL v2 license, you may redistribute it and/or modify it under version 2 of the License, or (at your option), any later version.
*/
#include "ConserveManaStrategy.h"
#include "GenericSpellActions.h"
#include "LastSpellCastValue.h"
#include "Playerbots.h"
float ConserveManaMultiplier::GetValue(Action* action)
{
if (!action)
return 1.0f;
uint8 health = AI_VALUE2(uint8, "health", "self target");
uint8 targetHealth = AI_VALUE2(uint8, "health", "current target");
uint8 mana = AI_VALUE2(uint8, "mana", "self target");
bool hasMana = AI_VALUE2(bool, "has mana", "self target");
bool mediumMana = hasMana && mana < sPlayerbotAIConfig->mediumMana;
if (health < sPlayerbotAIConfig->lowHealth)
return 1.0f;
Unit* target = AI_VALUE(Unit*, "current target");
if (action->GetTarget() != target)
return 1.0f;
CastSpellAction* spellAction = dynamic_cast<CastSpellAction*>(action);
if (!spellAction)
return 1.0f;
std::string const spell = spellAction->getName();
uint32 spellId = AI_VALUE2(uint32, "spell id", spell);
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
if (!spellInfo || spellInfo->PowerType != POWER_MANA)
return 1.0f;
if (mediumMana && dynamic_cast<CastBuffSpellAction*>(action))
return 0.0f;
if (target && ((int)target->getLevel() - (int)bot->getLevel()) >= 0)
return 1.0f;
return 1.0f;
}
float SaveManaMultiplier::GetValue(Action* action)
{
if (!action)
return 1.0f;
if (action->GetTarget() != AI_VALUE(Unit*, "current target"))
return 1.0f;
double saveLevel = AI_VALUE(double, "mana save level");
if (saveLevel <= 1.0)
return 1.0f;
CastSpellAction* spellAction = dynamic_cast<CastSpellAction*>(action);
if (!spellAction)
return 1.0f;
std::string const spell = spellAction->getName();
uint32 spellId = AI_VALUE2(uint32, "spell id", spell);
SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
if (!spellInfo || spellInfo->PowerType != POWER_MANA)
return 1.0f;
int32 cost = spellInfo->ManaCost;
if (!cost)
return 1.0f;
time_t lastCastTime = AI_VALUE2(time_t, "last spell cast time", spell);
if (!lastCastTime)
return 1.0f;
time_t elapsed = time(nullptr) - lastCastTime;
if ((double)elapsed < 10 * saveLevel)
return 0.0f;
return 1.0f;
}
void ConserveManaStrategy::InitMultipliers(std::vector<Multiplier*>& multipliers)
{
multipliers.push_back(new ConserveManaMultiplier(botAI));
}
| 30.386364 | 205 | 0.664174 | [
"vector"
] |
ab496e1d377f978727a5efa04fd07b9a3225a585 | 4,935 | hpp | C++ | src/Emulators/nestopiaue/core/api/NstApiCheats.hpp | slajerek/RetroDebugger | e761e4f9efd103a05e65ef283423b142fa4324c7 | [
"Apache-2.0",
"MIT"
] | 34 | 2021-05-29T07:04:17.000Z | 2022-03-10T20:16:03.000Z | src/Emulators/nestopiaue/core/api/NstApiCheats.hpp | slajerek/RetroDebugger | e761e4f9efd103a05e65ef283423b142fa4324c7 | [
"Apache-2.0",
"MIT"
] | 6 | 2021-12-25T13:05:21.000Z | 2022-01-19T17:35:17.000Z | src/Emulators/nestopiaue/core/api/NstApiCheats.hpp | slajerek/RetroDebugger | e761e4f9efd103a05e65ef283423b142fa4324c7 | [
"Apache-2.0",
"MIT"
] | 6 | 2021-12-24T18:37:41.000Z | 2022-02-06T23:06:02.000Z | ////////////////////////////////////////////////////////////////////////////////////////
//
// Nestopia - NES/Famicom emulator written in C++
//
// Copyright (C) 2003-2008 Martin Freij
//
// This file is part of Nestopia.
//
// Nestopia is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// Nestopia is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Nestopia; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
////////////////////////////////////////////////////////////////////////////////////////
#ifndef NST_API_CHEATS_H
#define NST_API_CHEATS_H
#include "NstApi.hpp"
#ifdef NST_PRAGMA_ONCE
#pragma once
#endif
#if NST_ICC >= 810
#pragma warning( push )
#pragma warning( disable : 444 )
#elif NST_MSVC >= 1200
#pragma warning( push )
#pragma warning( disable : 4512 )
#endif
namespace Nes
{
namespace Api
{
/**
* Cheats interface.
*/
class Cheats : public Base
{
struct Lut;
public:
/**
* Interface constructor.
*
* @param instance emulator instance
*/
template<typename T>
Cheats(T& instance)
: Base(instance) {}
/**
* Cheat code.
*/
struct Code
{
/**
* Address.
*/
ushort address;
/**
* Value.
*/
uchar value;
/**
* Compare-value.
*/
uchar compare;
/**
* Compare-value enable.
*/
bool useCompare;
/**
* Constructor.
*
* @param a address
* @param v value
* @param c compare-value
* @param u compare-value enable
*/
Code(ushort a=0,uchar v=0,uchar c=0,bool u=false)
: address(a), value(v), compare(c), useCompare(u) {}
};
/**
* Adds a new code.
*
* @param code code, any existing code using the same address will be replaced
* @return result code
*/
Result SetCode(const Code& code) throw();
/**
* Returns an existing code.
*
* @param index code index
* @param code object to be filled
* @return result code
*/
Result GetCode(ulong index,Code& code) const throw();
/**
* Returns attributes of an existing code.
*
* @param index code index
* @param address address to be filled or NULL if not needed
* @param value value to be filled or NULL if not needed
* @param compare compare-value to be filled or NULL if not needed
* @param useCompare compare-value enable to be filled or NULL if not needed
* @return result code
*/
Result GetCode(ulong index,ushort* address,uchar* value,uchar* compare,bool* useCompare) const throw();
/**
* Removes an existing code.
*
* @param index code index
* @return result code
*/
Result DeleteCode(ulong index) throw();
/**
* Returns current number of codes.
*
* @return number
*/
ulong NumCodes() const throw();
/**
* Removes all existing codes.
*
* @return result code
*/
Result ClearCodes() throw();
enum
{
RAM_SIZE = 0x800
};
/**
* CPU RAM pointer reference.
*/
typedef const uchar (&Ram)[RAM_SIZE];
/**
* Returns read-only content of CPU RAM.
*
* @return CPU RAM
*/
Ram GetRam() const throw();
/**
* Encodes into a Game Genie code.
*
* @param code code to be encoded
* @param string Game Genie code string to be filled
* @return result code
*/
static Result NST_CALL GameGenieEncode(const Code& code,char (&string)[9]) throw();
/**
* Decodes a Game Genie code.
*
* @param string Game Genie encoded string
* @param code object to be filled
* @return result code
*/
static Result NST_CALL GameGenieDecode(const char* string,Code& code) throw();
/**
* Encodes into a Pro-Action Rocky code.
*
* @param code code to be encoded
* @param string Pro-Action Rocky code string to be filled
* @return result code
*/
static Result NST_CALL ProActionRockyEncode(const Code& code,char (&string)[9]) throw();
/**
* Decodes a Pro-Action Rocky code.
*
* @param string Pro-Action Rocky encoded string
* @param code object to be filled
* @return result
*/
static Result NST_CALL ProActionRockyDecode(const char* string,Code& code) throw();
};
}
}
#if NST_MSVC >= 1200 || NST_ICC >= 810
#pragma warning( pop )
#endif
#endif
| 23.5 | 107 | 0.589463 | [
"object"
] |
ab4c89aee947e6d08b6ff898863f2cdb83702ecc | 7,795 | hpp | C++ | pybnesian/models/DynamicBayesianNetwork.hpp | davenza/PyBNesian | 3ed65e6a24d8e16ee00bf8c47ab6828692463499 | [
"MIT"
] | 8 | 2021-06-22T19:21:12.000Z | 2022-03-26T13:08:05.000Z | pybnesian/models/DynamicBayesianNetwork.hpp | davenza/PyBNesian | 3ed65e6a24d8e16ee00bf8c47ab6828692463499 | [
"MIT"
] | null | null | null | pybnesian/models/DynamicBayesianNetwork.hpp | davenza/PyBNesian | 3ed65e6a24d8e16ee00bf8c47ab6828692463499 | [
"MIT"
] | 3 | 2021-08-20T13:44:46.000Z | 2022-03-27T02:57:02.000Z | #ifndef PYBNESIAN_MODELS_DYNAMICBAYESIANNETWORK_HPP
#define PYBNESIAN_MODELS_DYNAMICBAYESIANNETWORK_HPP
#include <dataset/dynamic_dataset.hpp>
#include <factors/continuous/LinearGaussianCPD.hpp>
#include <factors/continuous/CKDE.hpp>
#include <factors/discrete/DiscreteFactor.hpp>
#include <models/BayesianNetwork.hpp>
#include <util/temporal.hpp>
using dataset::DynamicDataFrame;
using factors::continuous::LinearGaussianCPD, factors::continuous::CKDE, factors::discrete::DiscreteFactor;
using models::BayesianNetworkBase;
namespace models {
class DynamicBayesianNetworkBase : public clone_inherit<abstract_class<DynamicBayesianNetworkBase>> {
public:
virtual ~DynamicBayesianNetworkBase() = default;
virtual BayesianNetworkBase& static_bn() = 0;
virtual const BayesianNetworkBase& static_bn() const = 0;
virtual ConditionalBayesianNetworkBase& transition_bn() = 0;
virtual const ConditionalBayesianNetworkBase& transition_bn() const = 0;
virtual int markovian_order() const = 0;
virtual int num_variables() const = 0;
virtual const std::vector<std::string>& variables() const = 0;
virtual bool contains_variable(const std::string& name) const = 0;
virtual void add_variable(const std::string& name) = 0;
virtual void remove_variable(const std::string& name) = 0;
virtual bool fitted() const = 0;
virtual void fit(const DataFrame& df, const Arguments& construction_args = Arguments()) = 0;
virtual VectorXd logl(const DataFrame& df) const = 0;
virtual double slogl(const DataFrame& df) const = 0;
virtual std::shared_ptr<BayesianNetworkType> type() const = 0;
virtual BayesianNetworkType& type_ref() const = 0;
virtual DataFrame sample(int n, unsigned int seed = std::random_device{}()) const = 0;
virtual py::tuple __getstate__() const = 0;
virtual void save(std::string name, bool include_cpd = false) const = 0;
virtual std::string ToString() const = 0;
};
class DynamicBayesianNetwork : public clone_inherit<DynamicBayesianNetwork, DynamicBayesianNetworkBase> {
public:
DynamicBayesianNetwork(std::shared_ptr<BayesianNetworkType> type,
const std::vector<std::string>& variables,
int markovian_order)
: m_variables(variables), m_markovian_order(markovian_order), m_static(), m_transition() {
if (type == nullptr) throw std::runtime_error("Type of Bayesian network must be non-null.");
std::vector<std::string> static_nodes;
std::vector<std::string> transition_nodes;
for (const auto& v : variables) {
transition_nodes.push_back(util::temporal_name(v, 0));
}
for (int i = 1; i <= markovian_order; ++i) {
for (const auto& v : variables) {
static_nodes.push_back(util::temporal_name(v, i));
}
}
m_static = type->new_bn(static_nodes);
m_transition = type->new_cbn(transition_nodes, static_nodes);
}
DynamicBayesianNetwork(const std::vector<std::string>& variables,
int markovian_order,
std::shared_ptr<BayesianNetworkBase> static_bn,
std::shared_ptr<ConditionalBayesianNetworkBase> transition_bn)
: m_variables(variables), m_markovian_order(markovian_order), m_static(static_bn), m_transition(transition_bn) {
if (static_bn == nullptr) throw std::runtime_error("Static Bayesian network must be non-null.");
if (transition_bn == nullptr) throw std::runtime_error("Transition Bayesian network must be non-null.");
if (static_bn->type_ref() != transition_bn->type_ref())
throw std::invalid_argument("Static and transition Bayesian networks do not have the same type.");
for (const auto& v : variables) {
auto present_name = util::temporal_name(v, 0);
if (!m_transition->contains_node(present_name))
throw std::invalid_argument("Node " + present_name + " not present in transition BayesianNetwork.");
for (int i = 1; i <= m_markovian_order; ++i) {
auto name = util::temporal_name(v, i);
if (!m_static->contains_node(name))
throw std::invalid_argument("Node " + name + " not present in static BayesianNetwork.");
if (!m_transition->contains_interface_node(name))
throw std::invalid_argument("Interface node " + name +
" not present in transition BayesianNetwork.");
}
}
}
BayesianNetworkBase& static_bn() override { return *m_static; }
const BayesianNetworkBase& static_bn() const override { return *m_static; }
ConditionalBayesianNetworkBase& transition_bn() override { return *m_transition; }
const ConditionalBayesianNetworkBase& transition_bn() const override { return *m_transition; }
int markovian_order() const override { return m_markovian_order; }
int num_variables() const override { return m_variables.size(); }
const std::vector<std::string>& variables() const override { return m_variables.elements(); }
bool contains_variable(const std::string& name) const override { return m_variables.contains(name); }
void add_variable(const std::string& name) override;
void remove_variable(const std::string& name) override;
bool fitted() const override { return m_static->fitted() && m_transition->fitted(); }
void fit(const DataFrame& df, const Arguments& construction_args = Arguments()) override {
DynamicDataFrame ddf(df, m_markovian_order);
m_static->fit(ddf.static_df(), construction_args);
m_transition->fit(ddf.transition_df(), construction_args);
}
void check_fitted() const {
if (!fitted()) {
throw std::invalid_argument(
"DynamicBayesianNetwork currently not fitted. "
"Call fit() method, or add_cpds() for static_bn() and transition_bn()");
}
}
VectorXd logl(const DataFrame& df) const override;
double slogl(const DataFrame& df) const override;
std::shared_ptr<BayesianNetworkType> type() const override { return m_transition->type(); }
BayesianNetworkType& type_ref() const override { return m_transition->type_ref(); }
DataFrame sample(int n, unsigned int seed) const override;
std::string ToString() const override { return "Dynamic" + type_ref().ToString(); }
void save(std::string name, bool include_cpd = false) const override;
py::tuple __getstate__() const override;
bool include_cpd() const { return m_include_cpd; }
void set_include_cpd(bool include_cpd) const { m_include_cpd = include_cpd; }
private:
std::unordered_map<std::string, std::shared_ptr<arrow::DataType>> check_same_datatypes() const;
BidirectionalMapIndex<std::string> m_variables;
int m_markovian_order;
std::shared_ptr<BayesianNetworkBase> m_static;
std::shared_ptr<ConditionalBayesianNetworkBase> m_transition;
mutable bool m_include_cpd;
};
void __nonderived_dbn_setstate__(py::object& self, py::tuple& t);
template <typename DerivedBN>
std::shared_ptr<DerivedBN> __derived_dbn_setstate__(py::tuple& t) {
if (t.size() != 4) throw std::runtime_error("Not valid DynamicBayesianNetwork");
auto variables = t[0].cast<std::vector<std::string>>();
auto markovian_order = t[1].cast<int>();
auto static_bn = t[2].cast<std::shared_ptr<BayesianNetworkBase>>();
auto transition_bn = t[3].cast<std::shared_ptr<ConditionalBayesianNetworkBase>>();
return std::make_shared<DerivedBN>(variables, markovian_order, static_bn, transition_bn);
}
} // namespace models
#endif // PYBNESIAN_MODELS_DYNAMICBAYESIANNETWORK_HPP | 44.798851 | 120 | 0.690443 | [
"object",
"vector"
] |
ab4f29893c1c8cb7e7152b8fc242f243a3c5b5cd | 1,815 | cpp | C++ | game/prefabs/CheckPointPrefab.cpp | Khuongnb1997/game-aladdin | 74b13ffcd623de0d6f799b0669c7e8917eef3b14 | [
"MIT"
] | 2 | 2017-11-08T16:27:25.000Z | 2018-08-10T09:08:35.000Z | game/prefabs/CheckPointPrefab.cpp | Khuongnb1997/game-aladdin | 74b13ffcd623de0d6f799b0669c7e8917eef3b14 | [
"MIT"
] | null | null | null | game/prefabs/CheckPointPrefab.cpp | Khuongnb1997/game-aladdin | 74b13ffcd623de0d6f799b0669c7e8917eef3b14 | [
"MIT"
] | 4 | 2017-11-08T16:25:30.000Z | 2021-05-23T06:14:59.000Z | #include "CheckpointPrefab.h"
#include "../Define.h"
#include "../scripts/CheckpointController.h"
USING_NAMESPACE_ALA;
ALA_CLASS_SOURCE_1(CheckpointPrefab, ala::PrefabV2)
void CheckpointPrefab::doInstantiate( ala::GameObject* object, std::istringstream& argsStream ) const {
// args
const auto index = nextInt( argsStream );
// constants
const auto gameManager = GameManager::get();
// components
const auto spriteRenderer = new SpriteRenderer( object, "items.png" );
const auto animator = new Animator( object, "checkpoint_off", "items.anm" );
const auto onAudio = new AudioSource( object, "Continue Point.wav" );
const auto stateManager = new StateManager( object, "off" );
const auto body = new Rigidbody( object, PhysicsMaterial(), ALA_BODY_TYPE_STATIC );
const auto collider = new Collider( object, true, Vec2( 0, 0 ), Size( 20, 30 ), 1, 0 );
const auto controller = new CheckpointController( object, index );
// helpers
const auto transform = object->getTransform();
// collider renderers
// new ColliderRenderer( collider );
// flags
collider->setFlags( COLLIDE_ALADDIN_FLAG | STATIC_FLAG );
collider->ignoreIfHasAnyFlags( STATIC_FLAG );
// configurations
object->setLayer( "Mass Character" );
// states
new State( stateManager, "off",
[=] {
animator->setAction( "checkpoint_off" );
}, NULL, NULL );
new State( stateManager, "on",
[=] {
// animation effect
{
animator->setAction( "checkpoint_on" );
}
// audio
{
onAudio->play();
}
}, NULL, NULL );
new StateTransition( stateManager, "off", "on", [=] {
return controller->isChecked();
} );
}
| 27.089552 | 103 | 0.619835 | [
"object",
"transform"
] |
ab52aabec92260dda16c3b8d43403d6543f0ff51 | 1,806 | cpp | C++ | client/demo/main.cpp | andywang0607/ScreenCaptureService | a421520283e6586cc25760894753acce576ee60a | [
"MIT"
] | null | null | null | client/demo/main.cpp | andywang0607/ScreenCaptureService | a421520283e6586cc25760894753acce576ee60a | [
"MIT"
] | null | null | null | client/demo/main.cpp | andywang0607/ScreenCaptureService | a421520283e6586cc25760894753acce576ee60a | [
"MIT"
] | null | null | null | #include <opencv2/opencv.hpp>
#include "threadsafe_queue.hpp"
#include "include/ScreenCaptureApi.h"
#include <thread>
#include <chrono>
#include <spdlog/spdlog.h>
static ScreenCaptureApi *api = nullptr;
threadsafe_queue<cv::Mat> imgQueue;
class MySpi : public ScreenCaptureSpi
{
void onStreamRtn(unsigned char *data, int length) override
{
auto mat = cv::imdecode(std::vector<unsigned char>(data, data+length), cv::IMREAD_COLOR);
imgQueue.push(mat);
}
void onImageRtn(unsigned char *data, int length) override
{
auto mat = cv::imdecode(std::vector<unsigned char>(data, data + length), cv::IMREAD_COLOR);
cv::imwrite("screen.jpg", mat);
}
void onConnectRspRtn(int imgWidth, int imgHeight) override
{
spdlog::info("[MySpi] onConnectRspRtn\n imgWidth: {}\n imgHeight: {}", imgWidth, imgHeight);
}
void onStartQueryScreenStreamRspRtn(const char *msg) override
{
spdlog::info("[MySpi] onStartQueryScreenStreamRspRtn\n msg: {}", msg);
}
void onStopQueryScreenStreamRspRtn(const char *msg) override
{
spdlog::info("[MySpi] onStopQueryScreenStreamRspRtn\n msg: {}", msg);
}
void onDisConnectRspRtn(const char *msg) override
{
spdlog::info("[MySpi] onDisConnectRspRtn\n msg: {}", msg);
}
} mySpi;
int main()
{
api = ScreenCaptureApi::create(mySpi);
api->connect("127.0.0.1", 8080);
api->queryScreenImage();
api->startQueryScreenStream();
while (true) {
auto img = imgQueue.wait_and_pop();
cv::imshow("Screen", *img);
if (cv::waitKey(1) == 'q') {
break;
}
}
api->stopQueryScreenStream();
std::this_thread::sleep_for(std::chrono::seconds(1));
api->disconnect();
return 0;
} | 25.43662 | 100 | 0.63732 | [
"vector"
] |
ab5b21c791d672e51f39b5f1273d9555044e32a1 | 28,013 | hpp | C++ | sparta/sparta/statistics/Expression.hpp | debjyoti0891/map | abdae67964420d7d36255dcbf83e4240a1ef4295 | [
"MIT"
] | 44 | 2019-12-13T06:39:13.000Z | 2022-03-29T23:09:28.000Z | sparta/sparta/statistics/Expression.hpp | debjyoti0891/map | abdae67964420d7d36255dcbf83e4240a1ef4295 | [
"MIT"
] | 222 | 2020-01-14T21:58:56.000Z | 2022-03-31T20:05:12.000Z | sparta/sparta/statistics/Expression.hpp | debjyoti0891/map | abdae67964420d7d36255dcbf83e4240a1ef4295 | [
"MIT"
] | 19 | 2020-01-03T19:03:22.000Z | 2022-01-09T08:36:20.000Z | // <Expression.hpp> -*- C++ -*-
#pragma once
#include <iostream>
#include <sstream>
#include <memory>
#include "sparta/simulation/TreeNode.hpp"
#include "sparta/utils/SpartaAssert.hpp"
#include "sparta/utils/SpartaException.hpp"
#include "sparta/statistics/ExpressionNode.hpp"
#include "sparta/statistics/ExpressionNodeTypes.hpp"
namespace sparta {
class StatisticInstance;
class Clock;
/*!
* \brief Namespace containing methods for computing and generating
* statistical information using instrumentation extracted from sparta
* structures such as Counters
*/
namespace statistics {
/*!
* \brief Namespace containing methods for parsing, building, and
* evaluating statistical expressions in sparta
*/
namespace expression {
/*!
* \brief Expression container/builder. Contains a single ExpressionNode
* representing the root of an expression tree. This is the object on which the
* parser operates to build an expression incrementally through basic operators.
* \note Any TreeNodes referenced by an expression should outlast it. It is not
* safe to evaluate or even print the expression if any its references are
* destructed because they will leave dangling pointers.
*
* Expressions have an inherit computation window built in (like StatisticDef).
* This means that when the expression is created, any counter or stat-def
* referenced is treated as if it was 0 at that point. When the expression is
* later evaluated, the delta for those counters or stat-defs is used.
* This can be avoided simply by evaluating with evaluateAbsolute (generally not
* recommended)
*
* If expressions created during different simulation states are joined
* together, then they may see different windows. This is intentional so that
* comparisons can be made between different simulation time windows in a single
* expression (most users will not need to do this). This issue can be avoided
* by manually calling start()
*
*/
class Expression
{
/*!
* \brief Content of this expression (e.g. a operation, variable, constant,
* etc.).
* \note if nullptr, this Expression can do nothing and cannot be evaluated
*/
std::unique_ptr<ExpressionNode> content_;
public:
/*!
* \brief Constructs an expression containing no content
*/
Expression()
{
//std::cout << "Construction " << this << std::endl;
}
/*!
* \brief Copy Constructor
*/
Expression(const Expression& rhp)
{
//std::cout << "Copying " << this << " <- " << &rhp << std::endl;
if(rhp.content_ != nullptr){
content_.reset(rhp.content_->clone());
}
}
/*!
* \brief Move Constructor
*/
Expression(Expression&& rhp) :
content_(std::move(rhp.content_))
{
//std::cout << "Moving " << this << " <- " << &rhp << std::endl;
}
/*!
* \brief Construct with string expression
* \param expr String containing an arithmetic expression
* \param context TreeNode from which variables in the expression
* will be searched for. Must not be nullptr
*/
Expression(const std::string& expression,
TreeNode* context);
/*!
* \brief Construct with string expression
* \param expr String containing an arithmetic expression
* \param context Optional TreeNode from which variables in the expression
* will be searched for. Must not be nullptr
* \param already_used TreeNodes already in an expression containing this
* expression
*/
Expression(const std::string& expression,
TreeNode* context,
std::vector<const TreeNode*>& already_used);
/*!
* \brief Blind content constructor
* \param item Expression item to contain. Takes ownership
*/
Expression(ExpressionNode* item) :
Expression()
{
sparta_assert(item != nullptr);
content_.reset(item);
}
/*!
* \brief Constant construction
*/
Expression(double d);
/*!
* \brief Operation construction
*/
Expression(operation_t type,
ExpressionNode * op1,
ExpressionNode * op2=nullptr,
ExpressionNode * op3=nullptr);
/*!
* \brief Stat/Counter/Parameter construction
* \param[in] n Node to use (StatisticDef, Parameter, or Counter variant)
* \param[in] used Vector of nodes already used higher up in an enclosing
* expression (for preventing cycles). Use a dummy object if
* there is no chance of cyclic expressions
*/
Expression(const TreeNode* n,
std::vector<const TreeNode*>& used);
/*!
* \brief Unary function construction
* \tparam RetT Return type of function pointer. Must be convertable to
* double
* \tparam ArgT Argument type of function pointer.
*/
template<typename RetT, typename ArgT>
Expression(const std::string& name,
RetT(*fxn)(ArgT),
const Expression& a);
/*!
* \brief Unary function construction
* \tparam RetT Return type of functor. Must be convertable to
* double
* \tparam ArgT Argument type of functor.
*/
template<typename RetT, typename ArgT>
Expression(const std::string& name,
std::function<RetT (ArgT)>&,
const Expression& a);
/*!
* \brief Binary function construction
* \tparam RetT Return type of function pointer. Must be convertable to
* double
* \tparam ArgT Argument type of function pointer.
*/
template<typename RetT, typename ArgT>
Expression(const std::string& name,
RetT(*fxn)(ArgT, ArgT),
const Expression& a,
const Expression& b);
/*!
* \brief Binary function construction
* \tparam RetT Return type of functor. Must be convertable to
* double
* \tparam ArgT Argument type of functor.
*/
template<typename RetT>
Expression(const std::string& name,
const RetT& functor,
const Expression& a,
const Expression& b);
/*!
* \brief Ternary function construction
* \tparam RetT Return type of function pointer. Must be convertable to
* double
* \tparam ArgT Argument type of function pointer.
*/
template<typename RetT, typename ArgT>
Expression(const std::string& name,
RetT(*fxn)(ArgT, ArgT, ArgT),
const Expression& a,
const Expression& b,
const Expression& c);
/*!
* \brief Virtual destructor
*/
virtual ~Expression();
/*!
* \brief Assignment operator. Clones the content of rhp and discards
* current expression content
* \param rhp Expression to copy content from
*/
Expression& operator=(const Expression& rhp)
{
//std::cout << "Assignment " << this << " <- " << &rhp << std::endl;
if(rhp.content_ != nullptr){
content_.reset(rhp.content_->clone());
}
return *this;
}
/*!
* \brief Assignment operator with move. Moves content of rhp and discards
* current expression content
* \param rhp Expression to move content from
*/
Expression& operator=(Expression&& rhp)
{
//std::cout << "Move " << this << " <- " << &rhp << std::endl;
content_ = std::move(rhp.content_);
return *this;
}
/*!
* \brief Makes a clone of the content of this expression.
* \throw SpartaException if this node has null content
*/
ExpressionNode* cloneContent() const {
if(content_ == nullptr){
throw SpartaException("Cannot clone content of an expression with null content");
}
return content_->clone();
}
/*!
* \brief Gets the statistics present in this expression
* \return Number of stats added to results
* \param results Vector of pointers to StatisticInstances. All statistics
* within this class will be appended to the results vector.
* These pointers are valid until this expression is modified or deleted
*/
uint32_t getStats(std::vector<const StatisticInstance*>& results) const {
return getStats_(results);
}
/*!
* \brief Does this expression have content.
* \note This does not necessarily imply that the expression will be
* successfully evaluated
*/
bool hasContent() const {
return content_ != nullptr;
}
/*!
* \brief Construct a unary function having the given name and function
* \tparam RetT Return type of function pointer. Must be convertable to
* double
* \tparam ArgT Argument type of function pointer.
* \param name Name of the function (e.g. fabs)
* \param fxn Function pointer to invoke to compute the value. Must not be
* nullptr
* \param a Operand of the unary function
*/
template<typename RetT, typename ArgT>
Expression ufunc(const std::string& name,
RetT(*fxn)(ArgT),
const Expression& a) const;
/*!
* \brief Construct a unary function having the given name and functor
* \tparam RetT Return type of functor. Must be convertable to
* double
* \tparam ArgT Argument type of functor.
* \param name Name of the function (e.g. fabs)
* \param fxn Functor to invoke to compute the value. Must not be
* null
* \param a Operand of the unary function
*/
template<typename RetT, typename ArgT>
Expression ufunc(const std::string& name,
std::function<RetT (ArgT)>&,
const Expression& a) const;
/*!
* \brief Construct a binary function having the given name and function
* \tparam RetT Return type of function pointer. Must be convertable to
* double
* \tparam ArgT Argument type of function pointer.
* \param name Name of the function (e.g. fabs)
* \param fxn Function pointer to invoke to compute the value. Must not be
* nullptr
* \param a Operand 1 of the binary function
* \param b Operand 2 of the binary function
*/
template<typename RetT, typename ArgT>
Expression bfunc(const std::string& name,
RetT(*fxn)(ArgT, ArgT),
const Expression& a,
const Expression& b) const;
/*!
* \brief Construct a binary function having the given name and functor
* \tparam RetT Return type of functor. Must be convertable to
* double
* \tparam ArgT Argument type of functor.
* \param name Name of the function (e.g. fabs)
* \param fxn Functor to invoke to compute the value. Must not be
* null
* \param a Operand 1 of the binary function
* \param b Operand 2 of the binary function
*/
template<typename RetT>
Expression bfunc(const std::string& name,
const RetT& functor,
const Expression& a,
const Expression& b) const;
/*!
* \brief Construct a ternary function having the given name and function
* \tparam RetT Return type of function pointer. Must be convertable to
* double
* \tparam ArgT Argument type of function pointer.
* \param name Name of the function (e.g. fabs)
* \param fxn Function pointer to invoke to compute the value. Must not be
* nullptr
* \param a Operand 1 of the binary function
* \param b Operand 2 of the binary function
* \param c Operand 3 of the binary function
*/
template<typename RetT, typename ArgT>
Expression tfunc(const std::string& name,
RetT(*fxn)(ArgT, ArgT, ArgT),
const Expression& a,
const Expression& b,
const Expression& c) const;
/*!
* \brief Construct a constant node
* \note that this is a non-const operation
* \return *this
*/
Expression& operator=(double d);
/*!
* \brief Return this expression with no effect
*/
Expression operator+() const;
/*!
* \brief Return this expression with a negation inserted
*/
Expression operator-() const;
/*!
* \brief Return a new expression of: *this + rhp
*/
Expression operator+(const Expression& rhp) const;
/*!
* \brief Return a new expression of: *this - rhp
*/
Expression operator-(const Expression& rhp) const;
/*!
* \brief Return a new expression of: *this * rhp
*/
Expression operator*(const Expression& rhp) const;
/*!
* \brief Return a new expression of: *this / rhp
*/
Expression operator/(const Expression& rhp) const;
/*!
* \brief Return this expression with a node adding rhp
*/
Expression& operator+=(const Expression& rhp);
/*!
* \brief Return this expression with a node subtracting rhp
*/
Expression& operator-=(const Expression& rhp);
/*!
* \brief Return this expression with a node multiplying by rhp
*/
Expression& operator*=(const Expression& rhp);
/*!
* \brief Return this expression with a node dividing by rhp
*/
Expression& operator/=(const Expression& rhp);
/*!
* \brief Compute value of this operate in simulation for the current
* computation window
*/
double evaluate() const {
if(content_ == nullptr){
throw SpartaException("Cannot evaluate expression because it has no content. Test with "
"hasContent before blindly evaluating foreign expressions");
}
return content_->evaluate();
};
/*!
* \brief Notify every item in this expression to start a new computation
* window
* \note Has no effect if this expression has no content
* \see sparta::StatisticInstance
* \see hasContent
*/
void start() {
if(content_){
content_->start();
}
}
/*!
* \brief Notify every item in this expression to end the current
* computation window
* \note Has no effect if this expression has no content
* \see sparta::StatisticInstance
* \see hasContent
*/
void end() {
if(content_){
content_->end();
}
}
/*!
* \brief Write the content of this entire expression to an ostream
* \note Does not evaluate the expression
* \param o Ostream to write to
* \param show_range Should the range be shown in any subexpression
* nodes.
* \param resolve_subexprs Should any referenced statistic defs be
* expanded to their full expressions so that this becomes an expression
* containing only counters.
*/
void dump(std::ostream& o,
bool show_range=true,
bool resolve_subexprs=true) const {
if(!content_){
o << "???";
}else{
content_->dump(o, show_range, resolve_subexprs);
}
}
bool supportsCompression() const {
if (content_ == nullptr) {
return false;
}
return content_->supportsCompression();
}
/*!
* \brief Return a string representing this expression including any
* TreeNode dependencies.
* \warning It is not safe to call this if the expression depends on any
* destructed TreeNodes.
* \param show_range See dump
* \param resolve_subexprs See dump
* \return String representation of this expression
*/
std::string stringize(bool show_range=true,
bool resolve_subexprs=true) const {
std::stringstream ss;
dump(ss, show_range, resolve_subexprs);
return ss.str();
}
/*!
* \brief Gets the clock associated with the content of this expression.
* This is done by finding all TreeNodes on which the Expression depends
* \return The clock if at least one TreeNode is found in this expression
* and all found TreeNodes have the same clock. Returns nullptr if this
* Expression contains no TreeNodes or none of those nodes have associated
* Clocks.
*/
const Clock* getClock() {
std::vector<const Clock*> clocks;
getClocks(clocks);
if(clocks.size() == 0){
return nullptr;
}
const Clock* result = *(clocks.begin());
for(auto itr = clocks.begin()+1; itr != clocks.end(); ++itr){
if(*itr != result){
throw SpartaException("Multiple TreeNodes found with different clocks when "
"attempting to determine the clock associated with the "
"expression: ") << stringize();
}
}
return result;
}
/*!
* \brief Gets all clocks associated with this Expression.
* \param clocks Vector of clocks to which all clocks contained in this
* Expression will be added. Does not clear this vector.
*/
void getClocks(std::vector<const Clock*>& clocks) const{
if(content_){
content_->getClocks(clocks);
}
}
private:
/*!
* \brief Implements getStats
*/
uint32_t getStats_(std::vector<const StatisticInstance*>& results) const {
return content_ ? content_->getStats(results) : 0;
}
/*!
* \brief Parse an expression to generate the internal representation
* \note To be used ONLY by the constructors of this class
* \post sets content_
* \throw SpartaException if expression cannot be evaluated and resolved
*/
void parse_(const std::string& expression,
TreeNode* context,
std::vector<const TreeNode*>& already_used);
};
inline Expression::Expression(double d) :
Expression()
{
content_.reset(new Constant(d));
}
inline Expression::Expression(operation_t type,
ExpressionNode * op1,
ExpressionNode * op2,
ExpressionNode * op3) :
Expression()
{
content_.reset(new Operation(type, op1, op2, op3));
}
template <typename RetT, typename ArgT>
inline Expression::Expression(const std::string& name,
RetT(*fxn)(ArgT),
const Expression& a) {
sparta_assert(fxn != nullptr,
"function pointer of unary function \"" << fxn << "\" must not be nullptr");
content_.reset(new UnaryFunction<RetT, ArgT>(name, fxn, a.cloneContent()));
}
template <typename RetT, typename ArgT>
inline Expression::Expression(const std::string& name,
std::function<RetT (ArgT)>& fxn,
const Expression& a) {
sparta_assert(fxn,
"function pointer of unary function \"" << "\" must not be nullptr");
content_.reset(new UnaryFunction<RetT, ArgT, std::function<RetT (ArgT)>>(name, fxn, a.cloneContent()));
}
template <typename RetT, typename ArgT>
inline Expression::Expression(const std::string& name,
RetT(*fxn)(ArgT, ArgT),
const Expression& a,
const Expression& b) {
sparta_assert(fxn != nullptr,
"function pointer of binary function \"" << fxn << "\" must not be nullptr");
content_.reset(new BinaryFunction<RetT, ArgT>(name, fxn, a.cloneContent(), b.cloneContent()));
}
template <typename RetT>
inline Expression::Expression(const std::string& name,
const RetT& functor,
const Expression& a,
const Expression& b) {
content_.reset(new BinaryFunction<RetT>(name, functor, a.cloneContent(), b.cloneContent()));
}
template <typename RetT, typename ArgT>
inline Expression::Expression(const std::string& name,
RetT(*fxn)(ArgT, ArgT, ArgT),
const Expression& a,
const Expression& b,
const Expression& c) {
sparta_assert(fxn != nullptr,
"function pointer of ternary function \"" << fxn << "\" must not be nullptr");
content_.reset(new TernaryFunction<RetT, ArgT>(name, fxn, a.cloneContent(), b.cloneContent(), c.cloneContent()));
}
template <typename RetT, typename ArgT>
inline Expression Expression::ufunc(const std::string& name,
RetT(*fxn)(ArgT),
const Expression& a) const {
sparta_assert(fxn != nullptr,
"function pointer of unary function \"" << fxn << "\" must not be nullptr");
//std::cout << "unary func \"" << name << "\"" << std::endl;
return Expression(new UnaryFunction<RetT, ArgT>(name, fxn, a.cloneContent()));
}
template <typename RetT, typename ArgT>
inline Expression Expression::ufunc(const std::string& name,
std::function<RetT (ArgT)>& fxn,
const Expression& a) const {
sparta_assert(fxn,
"function pointer of unary function \"" << "\" must not be nullptr");
return Expression(new UnaryFunction<RetT, ArgT, std::function<RetT (ArgT)>>(name, fxn, a.cloneContent()));
}
template <typename RetT, typename ArgT>
inline Expression Expression::bfunc(const std::string& name,
RetT(*fxn)(ArgT, ArgT),
const Expression& a,
const Expression& b) const {
sparta_assert(fxn != nullptr,
"function pointer of binary function \"" << fxn << "\" must not be nullptr");
return Expression(new BinaryFunction<RetT, ArgT>(name, fxn, a.cloneContent(), b.cloneContent()));
}
template <typename RetT>
inline Expression Expression::bfunc(const std::string& name,
const RetT& functor,
const Expression& a,
const Expression& b) const {
return Expression(new BinaryFunction<RetT>(name, functor, a.cloneContent(), b.cloneContent()));
}
template <typename RetT, typename ArgT>
inline Expression Expression::tfunc(const std::string& name,
RetT(*fxn)(ArgT, ArgT, ArgT),
const Expression& a,
const Expression& b,
const Expression& c) const {
sparta_assert(fxn != nullptr,
"function pointer of ternary function \"" << fxn << "\" must not be nullptr");
return Expression(new TernaryFunction<RetT, ArgT>(name, fxn, a.cloneContent(), b.cloneContent(), c.cloneContent()));
}
inline Expression& Expression::operator=(double d)
{
sparta_assert(content_ == nullptr, "Cannot call operator= on an expression which already has an item. Item would ""be discarded");
content_.reset(new Constant(d));
return *this;
}
inline Expression Expression::operator+() const
{
sparta_assert(content_ != nullptr, "Cannot call operator+() on an expression which has no item. A lhp is ""required in order to promote");
return Expression(new Operation(OP_PROMOTE,
cloneContent()));
}
inline Expression Expression::operator-() const
{
sparta_assert(content_ != nullptr, "Cannot call operator-() on an expression which has no item. A lhp is ""required in order to negate");
return Expression(new Operation(OP_NEGATE,
cloneContent()));
}
inline Expression Expression::operator+(const Expression& rhp) const
{
sparta_assert(content_ != nullptr, "Cannot call operator+(rhp) on an expression which has no item. A lhp is ""required in order to add");
return Expression(new Operation(OP_ADD, // Operation
cloneContent(), // Takes ownership of content
rhp.cloneContent() // Clones content
));
}
inline Expression Expression::operator-(const Expression& rhp) const
{
sparta_assert(content_ != nullptr, "Cannot call operator-(rhp) on an expression which has no item. A lhp is ""required in order to subtract");
return Expression(new Operation(OP_SUB, // Operation
cloneContent(), // Takes ownership of content
rhp.cloneContent() // Clones content
));
}
inline Expression Expression::operator*(const Expression& rhp) const
{
sparta_assert(content_ != nullptr, "Cannot call operator*(rhp) on an expression which has no item. A lhp is ""required in order to multiply");
return Expression(new Operation(OP_MUL, // Operation
cloneContent(), // Takes ownership of content
rhp.cloneContent() // Clones content
));
}
inline Expression Expression::operator/(const Expression& rhp) const
{
sparta_assert(content_ != nullptr, "Cannot call operator/(rhp) on an expression which has no item. A lhp is ""required in order to divide");
return Expression(new Operation(OP_DIV, // Operation
cloneContent(), // Takes ownership of content
rhp.cloneContent() // Clones content
));
}
inline Expression& Expression::operator+=(const Expression& rhp)
{
sparta_assert(content_ != nullptr, "Cannot call operator+=(rhp) on an expression which has no item. A lhp is ""required in order to add");
content_.reset(new Operation(OP_ADD, // Operation
cloneContent(), // Takes ownership of content
rhp.cloneContent() // Clones content
));
return *this;
}
inline Expression& Expression::operator-=(const Expression& rhp)
{
sparta_assert(content_ != nullptr, "Cannot call operator-=(rhp) on an expression which has no item. A lhp is ""required in order to subtract");
content_.reset(new Operation(OP_SUB, // Operation
cloneContent(), // Takes ownership of content
rhp.cloneContent() // Clones content
));
return *this;
}
inline Expression& Expression::operator*=(const Expression& rhp)
{
sparta_assert(content_ != nullptr, "Cannot call operator*=(rhp) on an expression which has no item. A lhp is ""required in order to divide");
content_.reset(new Operation(OP_MUL, // Operation
cloneContent(), // Takes ownership of content
rhp.cloneContent() // Clones content
));
return *this;
}
inline Expression& Expression::operator/=(const Expression& rhp)
{
sparta_assert(content_ != nullptr, "Cannot call operator/=(rhp) on an expression which has no item. A lhp is ""required in order to divide");
content_.reset(new Operation(OP_DIV, // Operation
cloneContent(), // Takes ownership of content
rhp.cloneContent() // Clones content
));
return *this;
}
/*!
* \brief Ostream printing function for Expressions
*/
inline std::ostream& operator<<(std::ostream& o, const sparta::statistics::expression::Expression& ex){
ex.dump(o);
return o;
}
} // namespace expression
} // namespace statistics
} // namespace sparta
#pragma once
| 35.776501 | 147 | 0.598222 | [
"object",
"vector"
] |
ab5ba9108af72c9a9a04a23a69fd39fc5d30e05d | 3,155 | cpp | C++ | leetcode/30_days_challenge/2021_3_March/28.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | 1 | 2020-05-05T13:06:51.000Z | 2020-05-05T13:06:51.000Z | leetcode/30_days_challenge/2021_3_March/28.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | null | null | null | leetcode/30_days_challenge/2021_3_March/28.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | null | null | null | /****************************************************
Date: March 28th
link: https://leetcode.com/explore/challenge/card/march-leetcoding-challenge-2021/591/week-4-march-22nd-march-28th/3681/
****************************************************/
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <string>
#include <stack>
#include <queue>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <cmath>
#include <limits.h>
using namespace std;
/*
Q: Reconstruct Original Digits from English
Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order.
Note:
Input contains only lowercase English letters.
Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as "abc" or "zerone" are not permitted.
Input length is less than 50,000.
Example 1:
Input: "owoztneoer"
Output: "012"
Example 2:
Input: "fviefuro"
Output: "45"
*/
class Solution
{
private:
void getNums(int num, vector<int>& freq, vector<string>& ans)
{
int count = 0;
string numInStr;
switch(num)
{
case 0: //zero
count = freq['z'-'a'];
numInStr = "zero";
break;
case 1: //one
count = freq['o'-'a'];
numInStr = "one";
break;
case 2: //two
count = freq['w'-'a'];
numInStr = "two";
break;
case 3: //three
count = freq['h'-'a'];
numInStr = "three";
break;
case 4: //four
count = freq['u'-'a'];
numInStr = "four";
break;
case 5: //five
count = freq['f'-'a'];
numInStr = "five";
break;
case 6: //six
count = freq['x'-'a'];
numInStr = "six";
break;
case 7: //seven
count = freq['s'-'a'];
numInStr = "seven";
break;
case 8: //eight
count = freq['g'-'a'];
numInStr = "eight";
break;
case 9: //nine
count = freq['i'-'a'];
numInStr = "nine";
break;
default:
break;
}
for(char& ch : numInStr)
{
freq[ch-'a'] -= count;
}
if(count > 0)
{
string digit = std::to_string(num);
while(count > 0)
{
ans[num] += digit;
count--;
}
}
}
public:
string originalDigits(string s)
{
vector<int> freq(26, 0);
for(char& ch : s)
{
freq[ch-'a']++;
}
vector<string> nums(10, "");
getNums(0, freq, nums);
getNums(6, freq, nums);
getNums(2, freq, nums);
getNums(4, freq, nums);
getNums(8, freq, nums);
getNums(3, freq, nums);
getNums(1, freq, nums);
getNums(5, freq, nums);
getNums(7, freq, nums);
getNums(9, freq, nums);
string ans = "";
for(string& n : nums)
{
if(!n.empty())
{
ans += n;
}
}
return ans;
}
};
| 20.620915 | 153 | 0.489065 | [
"vector"
] |
ab615726230f29a35bdd6ccc12820335a8001878 | 5,102 | cpp | C++ | tests/unit/parse/control/capture.cpp | qedalab/vcd_assert | 40da307e60600fc4a814d4bba4679001f49f4375 | [
"BSD-2-Clause"
] | 1 | 2019-04-30T17:56:23.000Z | 2019-04-30T17:56:23.000Z | tests/unit/parse/control/capture.cpp | qedalab/vcd_assert | 40da307e60600fc4a814d4bba4679001f49f4375 | [
"BSD-2-Clause"
] | null | null | null | tests/unit/parse/control/capture.cpp | qedalab/vcd_assert | 40da307e60600fc4a814d4bba4679001f49f4375 | [
"BSD-2-Clause"
] | 4 | 2018-08-01T08:32:00.000Z | 2019-12-18T06:34:33.000Z | #include "parse/actions/apply/integer.hpp"
#include "parse/actions/apply/string.hpp"
#include "parse/actions/apply/value.hpp"
#include "parse/actions/command/apply.hpp"
#include "parse/actions/command/apply0.hpp"
#include "parse/actions/command/inner_action.hpp"
#include "parse/actions/control.hpp"
#include "parse/actions/dispatch.hpp"
#include "parse/actions/storage/member.hpp"
#include "parse/actions/storage/push_back.hpp"
#include <catch2/catch.hpp>
#include <tao/pegtl/parse.hpp>
#include <variant>
#include "./json.hpp"
using namespace Parse;
struct JSONObjectStorage {
static bool store(JSONObject &parent, JSONObjectKeyPair child) {
parent[std::move(child.key)] = std::move(child.value);
return true;
}
};
struct JSONValuePtrStorage {
template <class InnerValue>
static bool store(JSONValuePtr &value_ptr, InnerValue value) {
if constexpr (std::is_same_v<JSONValuePtr, InnerValue>) {
value_ptr = std::move(value);
} else {
value_ptr = std::make_unique<JSONValue>(std::move(value));
}
return true;
}
};
struct JSONValueAction;
struct JSONBoolAction : multi_dispatch<
json_grammar::false_, apply0<Apply::value<false>>,
json_grammar::true_, apply0<Apply::value<true>>
> {
using state = bool;
};
struct JSONStringAction : single_dispatch<
json_grammar::string_content, apply<Apply::string>
>{
using state = JSONString;
};
struct JSONArrayAction : single_dispatch<
json_grammar::value, inner_action<JSONValueAction, Storage::push_back>
> {
using state = JSONArray;
};
struct JSONKeyAction : single_dispatch<
json_grammar::key_content, apply<Apply::string>
> {
using state = JSONString;
};
struct JSONMemberAction : multi_dispatch<
json_grammar::value, inner_action<JSONValueAction, Storage::member<&JSONObjectKeyPair::value>>,
json_grammar::key, inner_action<JSONKeyAction, Storage::member<&JSONObjectKeyPair::key>>
> {
using state = JSONObjectKeyPair;
};
struct JSONObjectAction : single_dispatch<
json_grammar::member, inner_action<JSONMemberAction, JSONObjectStorage>
> {
using state = JSONObject;
};
struct JSONNumberAction : single_dispatch<
json_grammar::number, apply<Apply::integer>
> {
using state = JSONNumber;
};
struct JSONValueAction : multi_dispatch<
json_grammar::array, inner_action<JSONArrayAction, JSONValuePtrStorage>,
json_grammar::object, inner_action<JSONObjectAction, JSONValuePtrStorage>,
json_grammar::false_, inner_action<JSONBoolAction, JSONValuePtrStorage>,
json_grammar::true_, inner_action<JSONBoolAction, JSONValuePtrStorage>,
json_grammar::number, inner_action<JSONNumberAction, JSONValuePtrStorage>,
json_grammar::string, inner_action <JSONStringAction, JSONValuePtrStorage>
> {
using state = JSONValuePtr;
};
using rule_one = tao::pegtl::one<'1'>;
struct rule_one_with_error : rule_one {
static constexpr auto error() {
return "error";
}
};
TEST_CASE("Parse.CaptureControl") {
SECTION("raise") {
std::string_view raise_input = "asdf";
tao::pegtl::memory_input<> input(std::addressof(raise_input.front()), raise_input.size(), "raise");
CHECK_THROWS(tao::pegtl::parse<tao::pegtl::must<rule_one_with_error>, tao::pegtl::nothing, capture_control>(input));
CHECK_THROWS(tao::pegtl::parse<tao::pegtl::must<rule_one>, tao::pegtl::nothing, capture_control>(input));
}
SECTION("JSON") {
JSONValuePtr json;
tao::pegtl::memory_input<> input(std::addressof(json_example.front()), json_example.size(), "json_example");
bool success = tao::pegtl::parse<json_grammar::text, make_pegtl_template<JSONValueAction>::type,
capture_control>(input, json);
REQUIRE(success);
// Make sure that the main object exists
REQUIRE(bool(json));
REQUIRE(std::holds_alternative<JSONObject>(*json));
JSONObject* main_object = &std::get<JSONObject>(*json);
// Ensure that there are not excessive keys in the object
REQUIRE(main_object->size() == 3);
// Check that name == "John
JSONValuePtr& name_value = main_object->at("name");
REQUIRE(bool(name_value));
REQUIRE(std::holds_alternative<JSONString>(*name_value));
REQUIRE(std::get<JSONString>(*name_value) == "John");
// Check that age == 30
JSONValuePtr& age_value = main_object->at("age");
REQUIRE(std::holds_alternative<JSONNumber>(*age_value));
REQUIRE(std::get<JSONNumber>(*age_value) == Approx(30));
// Check that cars == ["Ford", "BMW", "Fiat"]
JSONValuePtr& cars_value = main_object->at("cars");
REQUIRE(std::holds_alternative<JSONArray>(*cars_value));
auto& cars_array = std::get<JSONArray>(*cars_value);
REQUIRE(cars_array.size() == 3);
REQUIRE(std::holds_alternative<JSONString>(*cars_array[0]));
REQUIRE(std::get<JSONString>(*cars_array[0]) == "Ford");
REQUIRE(std::holds_alternative<JSONString>(*cars_array[1]));
REQUIRE(std::get<JSONString>(*cars_array[1]) == "BMW");
REQUIRE(std::holds_alternative<JSONString>(*cars_array[2]));
REQUIRE(std::get<JSONString>(*cars_array[2]) == "Fiat");
}
}
| 32.08805 | 120 | 0.715406 | [
"object"
] |
ab63e3db9c41d94454852f4428173deef620189a | 1,720 | hh | C++ | MCDataProducts/inc/CaloHitMC.hh | lborrel/Offline | db9f647bad3c702171ab5ffa5ccc04c82b3f8984 | [
"Apache-2.0"
] | 1 | 2021-06-23T22:09:28.000Z | 2021-06-23T22:09:28.000Z | MCDataProducts/inc/CaloHitMC.hh | lborrel/Offline | db9f647bad3c702171ab5ffa5ccc04c82b3f8984 | [
"Apache-2.0"
] | 125 | 2020-04-03T13:44:30.000Z | 2021-10-15T21:29:57.000Z | MCDataProducts/inc/CaloHitMC.hh | lborrel/Offline | db9f647bad3c702171ab5ffa5ccc04c82b3f8984 | [
"Apache-2.0"
] | null | null | null | //
// This calss contains CaloMCEdep for each CaloDigi, matching deposited energy at MC level to reco digi hits
// Notes:
// CaloEdepMC: the list of CaloEDepMC is ordered by energy - most energetic first.
// time: taken as the time of the most energetic contribution.
//
//
#ifndef MCDataProducts_CaloHitMC_hh
#define MCDataProducts_CaloHitMC_hh
#include "MCDataProducts/inc/CaloEDepMC.hh"
#include "MCDataProducts/inc/SimParticleRemapping.hh"
#include <vector>
namespace mu2e
{
class CaloHitMC
{
public:
CaloHitMC() : edeps_() {};
CaloHitMC(const std::vector<CaloEDepMC>& edeps) : edeps_(edeps) {};
// reset SimParticle Ptrs
void resetSim(SimParticleRemapping const& remap) {
for(auto& edep : edeps_){
auto newsim = remap.at(edep.sim());
edep.resetSim(newsim);
}
}
const std::vector<CaloEDepMC>& energyDeposits () const {return edeps_; }
std::vector<CaloEDepMC>& energyDeposits () {return edeps_; }
const CaloEDepMC& energyDeposit (unsigned i) const {return edeps_.at(i); }
unsigned nParticles () const {return edeps_.size();}
float time () const {return edeps_.at(0).time();}
float totalEnergyDep () const;
float totalEnergyDepG4() const;
private:
std::vector<CaloEDepMC> edeps_;
};
using CaloHitMCCollection = std::vector<mu2e::CaloHitMC>;
}
#endif
| 35.833333 | 108 | 0.55 | [
"vector"
] |
0365a8b99532d4c22cf4ce3c9578e2e85536ae78 | 78,397 | cpp | C++ | Tools/KLEE_Platform/stp/build/lib/Parser/lexsmt.cpp | seclab-ucr/SCENT | f2fbfc5902b2dbd7dc72c8dc23ff28e24c31e50a | [
"MIT"
] | 3 | 2019-10-24T00:49:51.000Z | 2020-12-16T13:34:49.000Z | Tools/KLEE_Platform/stp/build/lib/Parser/lexsmt.cpp | seclab-ucr/SCENT | f2fbfc5902b2dbd7dc72c8dc23ff28e24c31e50a | [
"MIT"
] | null | null | null | Tools/KLEE_Platform/stp/build/lib/Parser/lexsmt.cpp | seclab-ucr/SCENT | f2fbfc5902b2dbd7dc72c8dc23ff28e24c31e50a | [
"MIT"
] | 1 | 2020-11-14T03:08:53.000Z | 2020-11-14T03:08:53.000Z | #line 2 "/home/yue/Work/stp/build/lib/Parser/lexsmt.cpp"
#line 4 "/home/yue/Work/stp/build/lib/Parser/lexsmt.cpp"
#define YY_INT_ALIGNED short int
/* A lexical scanner generated by flex */
#define yy_create_buffer smt_create_buffer
#define yy_delete_buffer smt_delete_buffer
#define yy_flex_debug smt_flex_debug
#define yy_init_buffer smt_init_buffer
#define yy_flush_buffer smt_flush_buffer
#define yy_load_buffer_state smt_load_buffer_state
#define yy_switch_to_buffer smt_switch_to_buffer
#define yyin smtin
#define yyleng smtleng
#define yylex smtlex
#define yylineno smtlineno
#define yyout smtout
#define yyrestart smtrestart
#define yytext smttext
#define yywrap smtwrap
#define yyalloc smtalloc
#define yyrealloc smtrealloc
#define yyfree smtfree
#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 6
#define YY_FLEX_SUBMINOR_VERSION 0
#if YY_FLEX_SUBMINOR_VERSION > 0
#define FLEX_BETA
#endif
/* First, we deal with platform-specific or compiler-specific issues. */
/* begin standard C headers. */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
/* end standard C headers. */
/* flex integer type definitions */
#ifndef FLEXINT_H
#define FLEXINT_H
/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
* if you want the limit (max/min) macros for int types.
*/
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS 1
#endif
#include <inttypes.h>
typedef int8_t flex_int8_t;
typedef uint8_t flex_uint8_t;
typedef int16_t flex_int16_t;
typedef uint16_t flex_uint16_t;
typedef int32_t flex_int32_t;
typedef uint32_t flex_uint32_t;
#else
typedef signed char flex_int8_t;
typedef short int flex_int16_t;
typedef int flex_int32_t;
typedef unsigned char flex_uint8_t;
typedef unsigned short int flex_uint16_t;
typedef unsigned int flex_uint32_t;
/* Limits of integral types. */
#ifndef INT8_MIN
#define INT8_MIN (-128)
#endif
#ifndef INT16_MIN
#define INT16_MIN (-32767-1)
#endif
#ifndef INT32_MIN
#define INT32_MIN (-2147483647-1)
#endif
#ifndef INT8_MAX
#define INT8_MAX (127)
#endif
#ifndef INT16_MAX
#define INT16_MAX (32767)
#endif
#ifndef INT32_MAX
#define INT32_MAX (2147483647)
#endif
#ifndef UINT8_MAX
#define UINT8_MAX (255U)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX (65535U)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (4294967295U)
#endif
#endif /* ! C99 */
#endif /* ! FLEXINT_H */
#ifdef __cplusplus
/* The "const" storage-class-modifier is valid. */
#define YY_USE_CONST
#else /* ! __cplusplus */
/* C99 requires __STDC__ to be defined as 1. */
#if defined (__STDC__)
#define YY_USE_CONST
#endif /* defined (__STDC__) */
#endif /* ! __cplusplus */
#ifdef YY_USE_CONST
#define yyconst const
#else
#define yyconst
#endif
/* Returned upon end-of-file. */
#define YY_NULL 0
/* Promotes a possibly negative, possibly signed char to an unsigned
* integer for use as an array index. If the signed char is negative,
* we want to instead treat it as an 8-bit unsigned char, hence the
* double cast.
*/
#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
/* Enter a start condition. This macro really ought to take a parameter,
* but we do it the disgusting crufty way forced on us by the ()-less
* definition of BEGIN.
*/
#define BEGIN (yy_start) = 1 + 2 *
/* Translate the current start state into a value that can be later handed
* to BEGIN to return to the state. The YYSTATE alias is for lex
* compatibility.
*/
#define YY_START (((yy_start) - 1) / 2)
#define YYSTATE YY_START
/* Action number for EOF rule of a given start state. */
#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
/* Special action meaning "start processing a new file". */
#define YY_NEW_FILE smtrestart(smtin )
#define YY_END_OF_BUFFER_CHAR 0
/* Size of default input buffer. */
#ifndef YY_BUF_SIZE
#ifdef __ia64__
/* On IA-64, the buffer size is 16k, not 8k.
* Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case.
* Ditto for the __ia64__ case accordingly.
*/
#define YY_BUF_SIZE 32768
#else
#define YY_BUF_SIZE 16384
#endif /* __ia64__ */
#endif
/* The state buf must be large enough to hold one state per character in the main buffer.
*/
#define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type))
#ifndef YY_TYPEDEF_YY_BUFFER_STATE
#define YY_TYPEDEF_YY_BUFFER_STATE
typedef struct yy_buffer_state *YY_BUFFER_STATE;
#endif
#ifndef YY_TYPEDEF_YY_SIZE_T
#define YY_TYPEDEF_YY_SIZE_T
typedef size_t yy_size_t;
#endif
extern yy_size_t smtleng;
extern FILE *smtin, *smtout;
#define EOB_ACT_CONTINUE_SCAN 0
#define EOB_ACT_END_OF_FILE 1
#define EOB_ACT_LAST_MATCH 2
/* Note: We specifically omit the test for yy_rule_can_match_eol because it requires
* access to the local variable yy_act. Since yyless() is a macro, it would break
* existing scanners that call yyless() from OUTSIDE smtlex.
* One obvious solution it to make yy_act a global. I tried that, and saw
* a 5% performance hit in a non-smtlineno scanner, because yy_act is
* normally declared as a register variable-- so it is not worth it.
*/
#define YY_LESS_LINENO(n) \
do { \
int yyl;\
for ( yyl = n; yyl < smtleng; ++yyl )\
if ( smttext[yyl] == '\n' )\
--smtlineno;\
}while(0)
#define YY_LINENO_REWIND_TO(dst) \
do {\
const char *p;\
for ( p = yy_cp-1; p >= (dst); --p)\
if ( *p == '\n' )\
--smtlineno;\
}while(0)
/* Return all but the first "n" matched characters back to the input stream. */
#define yyless(n) \
do \
{ \
/* Undo effects of setting up smttext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
*yy_cp = (yy_hold_char); \
YY_RESTORE_YY_MORE_OFFSET \
(yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
YY_DO_BEFORE_ACTION; /* set up smttext again */ \
} \
while ( 0 )
#define unput(c) yyunput( c, (yytext_ptr) )
#ifndef YY_STRUCT_YY_BUFFER_STATE
#define YY_STRUCT_YY_BUFFER_STATE
struct yy_buffer_state
{
FILE *yy_input_file;
char *yy_ch_buf; /* input buffer */
char *yy_buf_pos; /* current position in input buffer */
/* Size of input buffer in bytes, not including room for EOB
* characters.
*/
yy_size_t yy_buf_size;
/* Number of characters read into yy_ch_buf, not including EOB
* characters.
*/
int yy_n_chars;
/* Whether we "own" the buffer - i.e., we know we created it,
* and can realloc() it to grow it, and should free() it to
* delete it.
*/
int yy_is_our_buffer;
/* Whether this is an "interactive" input source; if so, and
* if we're using stdio for input, then we want to use getc()
* instead of fread(), to make sure we stop fetching input after
* each newline.
*/
int yy_is_interactive;
/* Whether we're considered to be at the beginning of a line.
* If so, '^' rules will be active on the next match, otherwise
* not.
*/
int yy_at_bol;
int yy_bs_lineno; /**< The line count. */
int yy_bs_column; /**< The column count. */
/* Whether to try to fill the input buffer when we reach the
* end of it.
*/
int yy_fill_buffer;
int yy_buffer_status;
#define YY_BUFFER_NEW 0
#define YY_BUFFER_NORMAL 1
/* When an EOF's been seen but there's still some text to process
* then we mark the buffer as YY_EOF_PENDING, to indicate that we
* shouldn't try reading from the input source any more. We might
* still have a bunch of tokens to match, though, because of
* possible backing-up.
*
* When we actually see the EOF, we change the status to "new"
* (via smtrestart()), so that the user can continue scanning by
* just pointing smtin at a new input file.
*/
#define YY_BUFFER_EOF_PENDING 2
};
#endif /* !YY_STRUCT_YY_BUFFER_STATE */
/* Stack of input buffers. */
static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */
static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */
static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */
/* We provide macros for accessing buffer states in case in the
* future we want to put the buffer states in a more general
* "scanner state".
*
* Returns the top of the stack, or NULL.
*/
#define YY_CURRENT_BUFFER ( (yy_buffer_stack) \
? (yy_buffer_stack)[(yy_buffer_stack_top)] \
: NULL)
/* Same as previous macro, but useful when we know that the buffer stack is not
* NULL or when we need an lvalue. For internal use only.
*/
#define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)]
/* yy_hold_char holds the character lost when smttext is formed. */
static char yy_hold_char;
static int yy_n_chars; /* number of characters read into yy_ch_buf */
yy_size_t smtleng;
/* Points to current character in buffer. */
static char *yy_c_buf_p = (char *) 0;
static int yy_init = 0; /* whether we need to initialize */
static int yy_start = 0; /* start state number */
/* Flag which is used to allow smtwrap()'s to do buffer switches
* instead of setting up a fresh smtin. A bit of a hack ...
*/
static int yy_did_buffer_switch_on_eof;
void smtrestart (FILE *input_file );
void smt_switch_to_buffer (YY_BUFFER_STATE new_buffer );
YY_BUFFER_STATE smt_create_buffer (FILE *file,int size );
void smt_delete_buffer (YY_BUFFER_STATE b );
void smt_flush_buffer (YY_BUFFER_STATE b );
void smtpush_buffer_state (YY_BUFFER_STATE new_buffer );
void smtpop_buffer_state (void );
static void smtensure_buffer_stack (void );
static void smt_load_buffer_state (void );
static void smt_init_buffer (YY_BUFFER_STATE b,FILE *file );
#define YY_FLUSH_BUFFER smt_flush_buffer(YY_CURRENT_BUFFER )
YY_BUFFER_STATE smt_scan_buffer (char *base,yy_size_t size );
YY_BUFFER_STATE smt_scan_string (yyconst char *yy_str );
YY_BUFFER_STATE smt_scan_bytes (yyconst char *bytes,yy_size_t len );
void *smtalloc (yy_size_t );
void *smtrealloc (void *,yy_size_t );
void smtfree (void * );
#define yy_new_buffer smt_create_buffer
#define yy_set_interactive(is_interactive) \
{ \
if ( ! YY_CURRENT_BUFFER ){ \
smtensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
smt_create_buffer(smtin,YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
}
#define yy_set_bol(at_bol) \
{ \
if ( ! YY_CURRENT_BUFFER ){\
smtensure_buffer_stack (); \
YY_CURRENT_BUFFER_LVALUE = \
smt_create_buffer(smtin,YY_BUF_SIZE ); \
} \
YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
}
#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
/* Begin user sect3 */
#define smtwrap() (/*CONSTCOND*/1)
#define YY_SKIP_YYWRAP
typedef unsigned char YY_CHAR;
FILE *smtin = (FILE *) 0, *smtout = (FILE *) 0;
typedef int yy_state_type;
extern int smtlineno;
int smtlineno = 1;
extern char *smttext;
#ifdef yytext_ptr
#undef yytext_ptr
#endif
#define yytext_ptr smttext
static yy_state_type yy_get_previous_state (void );
static yy_state_type yy_try_NUL_trans (yy_state_type current_state );
static int yy_get_next_buffer (void );
#if defined(__GNUC__) && __GNUC__ >= 3
__attribute__((__noreturn__))
#endif
static void yy_fatal_error (yyconst char msg[] );
/* Done after the current pattern has been matched and before the
* corresponding action - sets up smttext.
*/
#define YY_DO_BEFORE_ACTION \
(yytext_ptr) = yy_bp; \
smtleng = (size_t) (yy_cp - yy_bp); \
(yy_hold_char) = *yy_cp; \
*yy_cp = '\0'; \
(yy_c_buf_p) = yy_cp;
#define YY_NUM_RULES 113
#define YY_END_OF_BUFFER 114
/* This struct is not used in this scanner,
but its presence is necessary. */
struct yy_trans_info
{
flex_int32_t yy_verify;
flex_int32_t yy_nxt;
};
static yyconst flex_int16_t yy_accept[394] =
{ 0,
0, 0, 0, 0, 0, 0, 0, 0, 114, 112,
1, 1, 8, 61, 59, 60, 2, 56, 5, 63,
62, 111, 111, 111, 57, 58, 112, 111, 111, 111,
111, 111, 111, 111, 111, 111, 111, 111, 111, 111,
111, 111, 111, 111, 12, 7, 6, 11, 113, 10,
11, 16, 15, 16, 14, 2, 111, 111, 111, 111,
111, 111, 111, 111, 111, 111, 111, 111, 111, 111,
111, 111, 111, 111, 111, 111, 111, 111, 111, 111,
111, 111, 111, 111, 26, 111, 111, 111, 111, 111,
111, 111, 111, 111, 111, 111, 111, 9, 13, 111,
111, 25, 111, 111, 111, 111, 111, 3, 111, 111,
111, 111, 111, 111, 111, 111, 111, 111, 111, 111,
111, 111, 111, 111, 111, 111, 111, 111, 111, 28,
111, 23, 111, 29, 111, 111, 65, 21, 111, 111,
111, 39, 111, 111, 111, 111, 111, 111, 111, 111,
111, 27, 111, 111, 111, 111, 111, 111, 4, 111,
111, 111, 111, 111, 111, 88, 111, 111, 87, 111,
111, 111, 111, 80, 111, 111, 111, 111, 111, 111,
111, 111, 111, 111, 111, 111, 111, 111, 111, 111,
111, 111, 111, 111, 111, 30, 111, 33, 111, 111,
111, 111, 64, 111, 111, 111, 111, 111, 111, 111,
111, 111, 111, 19, 111, 111, 111, 18, 111, 111,
111, 111, 111, 111, 69, 79, 111, 111, 90, 89,
111, 72, 111, 78, 83, 71, 111, 102, 98, 66,
101, 97, 111, 111, 70, 111, 96, 92, 95, 91,
111, 111, 81, 111, 111, 111, 111, 111, 111, 111,
20, 111, 111, 111, 111, 38, 31, 34, 111, 111,
111, 111, 32, 111, 111, 55, 111, 40, 111, 17,
111, 37, 111, 110, 111, 68, 103, 67, 82, 74,
100, 99, 77, 76, 73, 94, 93, 75, 84, 111,
85, 111, 111, 111, 111, 111, 111, 111, 111, 111,
111, 111, 111, 106, 111, 54, 111, 47, 44, 111,
111, 111, 111, 111, 111, 111, 111, 111, 111, 86,
111, 111, 111, 43, 111, 22, 111, 111, 111, 41,
111, 111, 111, 111, 48, 111, 111, 53, 111, 111,
111, 111, 111, 52, 111, 111, 111, 111, 111, 46,
111, 111, 111, 111, 50, 111, 111, 111, 111, 111,
111, 111, 42, 111, 36, 45, 35, 51, 49, 111,
111, 111, 111, 111, 109, 111, 107, 111, 105, 104,
24, 108, 0
} ;
static yyconst YY_CHAR yy_ec[256] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 2, 3,
1, 2, 2, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 2, 1, 4, 1, 5, 1, 1, 6, 7,
8, 1, 1, 1, 1, 6, 1, 9, 9, 9,
9, 9, 9, 9, 9, 9, 9, 10, 11, 1,
12, 1, 13, 1, 14, 15, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 17, 16, 16, 16, 16,
18, 19, 20, 1, 21, 1, 22, 23, 24, 25,
26, 27, 28, 29, 30, 16, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
45, 46, 47, 1, 48, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1
} ;
static yyconst flex_uint16_t yy_base[400] =
{ 0,
0, 0, 653, 652, 46, 48, 50, 51, 654, 657,
657, 657, 657, 657, 657, 657, 644, 657, 657, 657,
657, 614, 621, 0, 657, 657, 0, 22, 29, 38,
32, 606, 46, 49, 53, 50, 611, 610, 48, 70,
609, 612, 610, 618, 657, 657, 657, 657, 657, 657,
0, 657, 657, 43, 657, 634, 0, 604, 601, 0,
615, 600, 608, 603, 596, 600, 102, 594, 599, 605,
67, 591, 598, 603, 590, 593, 36, 590, 599, 590,
583, 594, 587, 46, 0, 594, 583, 578, 577, 584,
587, 39, 73, 573, 62, 575, 574, 657, 657, 589,
593, 0, 568, 573, 583, 597, 573, 595, 78, 568,
76, 81, 561, 87, 563, 119, 100, 80, 574, 575,
568, 570, 556, 93, 556, 554, 560, 553, 551, 0,
558, 0, 561, 0, 558, 562, 0, 560, 560, 558,
561, 0, 556, 547, 540, 541, 538, 539, 550, 541,
552, 0, 538, 527, 545, 537, 536, 539, 558, 116,
541, 540, 535, 530, 525, 0, 524, 531, 0, 527,
524, 529, 89, 0, 526, 78, 523, 114, 519, 527,
529, 521, 119, 123, 524, 514, 510, 519, 524, 511,
514, 513, 508, 519, 514, 0, 498, 0, 509, 507,
495, 511, 0, 495, 494, 510, 491, 506, 508, 489,
503, 485, 499, 0, 489, 483, 501, 0, 497, 484,
480, 485, 475, 472, 0, 0, 477, 478, 0, 0,
475, 0, 487, 0, 0, 0, 469, 473, 0, 0,
472, 0, 483, 474, 0, 464, 468, 0, 467, 0,
470, 464, 0, 466, 460, 469, 474, 463, 457, 126,
0, 463, 468, 467, 470, 0, 0, 0, 451, 464,
449, 462, 0, 461, 447, 0, 442, 0, 458, 0,
443, 0, 460, 0, 441, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 442,
0, 439, 437, 453, 446, 435, 433, 435, 437, 449,
436, 430, 440, 0, 446, 0, 422, 0, 0, 431,
420, 433, 424, 423, 415, 429, 426, 417, 421, 0,
421, 428, 415, 0, 431, 0, 425, 123, 410, 0,
409, 413, 416, 424, 0, 410, 404, 0, 409, 403,
416, 400, 368, 0, 339, 334, 337, 332, 323, 0,
332, 321, 308, 313, 0, 285, 284, 290, 290, 288,
281, 280, 0, 272, 0, 0, 0, 0, 0, 272,
124, 129, 131, 108, 0, 97, 0, 57, 0, 0,
0, 0, 657, 165, 213, 261, 304, 345, 391
} ;
static yyconst flex_int16_t yy_def[400] =
{ 0,
393, 1, 394, 394, 395, 395, 396, 396, 393, 393,
393, 393, 393, 393, 393, 393, 393, 393, 393, 393,
393, 397, 397, 397, 393, 393, 398, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 393, 393, 393, 393, 393, 393,
399, 393, 393, 393, 393, 393, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 393, 393, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 0, 393, 393, 393, 393, 393, 393
} ;
static yyconst flex_uint16_t yy_nxt[706] =
{ 0,
10, 11, 12, 13, 14, 10, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 24, 25, 10, 26,
27, 28, 29, 30, 31, 32, 33, 24, 24, 34,
24, 35, 24, 36, 37, 38, 24, 39, 40, 41,
42, 24, 24, 43, 24, 44, 45, 10, 49, 50,
49, 50, 53, 53, 64, 61, 129, 70, 65, 68,
62, 71, 130, 66, 51, 63, 51, 73, 54, 54,
67, 83, 69, 87, 80, 77, 145, 74, 81, 146,
75, 78, 88, 137, 84, 138, 76, 82, 79, 99,
99, 89, 150, 122, 147, 90, 392, 55, 55, 91,
151, 165, 161, 238, 92, 123, 167, 148, 171, 93,
108, 162, 172, 186, 187, 166, 163, 239, 193, 168,
169, 173, 391, 109, 182, 110, 235, 183, 236, 111,
194, 184, 390, 112, 113, 114, 115, 185, 223, 241,
116, 224, 117, 175, 247, 118, 176, 177, 249, 306,
178, 179, 307, 242, 355, 389, 180, 388, 248, 181,
356, 308, 250, 387, 309, 46, 46, 46, 46, 46,
46, 46, 46, 46, 46, 46, 46, 46, 46, 46,
46, 46, 46, 46, 46, 46, 46, 46, 46, 46,
46, 46, 46, 46, 46, 46, 46, 46, 46, 46,
46, 46, 46, 46, 46, 46, 46, 46, 46, 46,
46, 46, 46, 48, 48, 48, 48, 48, 48, 48,
48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
48, 48, 48, 48, 48, 48, 48, 48, 48, 48,
48, 52, 52, 52, 52, 52, 52, 52, 52, 52,
52, 52, 52, 52, 52, 52, 52, 52, 52, 52,
52, 52, 52, 52, 52, 52, 52, 52, 52, 52,
52, 52, 52, 52, 52, 52, 52, 52, 52, 52,
52, 52, 52, 52, 52, 52, 52, 52, 52, 57,
386, 385, 57, 384, 383, 382, 381, 57, 57, 57,
57, 380, 379, 378, 57, 57, 57, 57, 57, 57,
57, 57, 57, 57, 57, 57, 57, 57, 57, 57,
57, 57, 57, 57, 57, 57, 57, 57, 57, 57,
60, 377, 376, 60, 375, 374, 373, 372, 60, 60,
60, 60, 371, 370, 369, 60, 60, 60, 60, 60,
60, 60, 60, 60, 60, 60, 60, 60, 60, 60,
60, 60, 60, 60, 60, 60, 60, 60, 60, 60,
60, 98, 98, 368, 98, 98, 98, 98, 98, 98,
98, 98, 98, 98, 98, 98, 98, 98, 98, 98,
98, 98, 98, 98, 98, 98, 98, 98, 98, 98,
98, 98, 98, 98, 98, 98, 98, 98, 98, 98,
98, 98, 98, 98, 98, 98, 98, 98, 98, 367,
366, 365, 364, 363, 362, 361, 360, 359, 358, 357,
354, 353, 352, 351, 350, 349, 348, 347, 346, 345,
344, 343, 342, 341, 340, 339, 338, 337, 336, 335,
334, 333, 332, 331, 330, 329, 328, 327, 326, 325,
324, 323, 322, 321, 320, 319, 318, 317, 316, 315,
314, 313, 312, 311, 310, 305, 304, 303, 302, 301,
300, 299, 298, 297, 296, 295, 294, 293, 292, 291,
290, 289, 288, 287, 286, 285, 284, 283, 282, 281,
280, 279, 278, 277, 276, 275, 274, 273, 272, 271,
270, 269, 268, 267, 266, 265, 264, 263, 262, 261,
260, 259, 258, 257, 256, 255, 254, 253, 252, 251,
246, 245, 244, 243, 240, 237, 234, 233, 232, 231,
230, 229, 228, 227, 226, 225, 159, 222, 221, 220,
219, 218, 217, 216, 215, 214, 213, 212, 211, 210,
209, 208, 207, 206, 205, 204, 203, 202, 201, 200,
199, 198, 197, 196, 195, 192, 191, 190, 189, 188,
174, 170, 164, 108, 160, 159, 158, 157, 156, 155,
154, 153, 152, 149, 144, 143, 142, 141, 140, 139,
136, 135, 134, 133, 132, 131, 128, 127, 126, 125,
124, 121, 120, 119, 107, 106, 105, 104, 103, 102,
101, 100, 56, 97, 96, 95, 94, 86, 85, 72,
59, 58, 56, 393, 47, 47, 9, 393, 393, 393,
393, 393, 393, 393, 393, 393, 393, 393, 393, 393,
393, 393, 393, 393, 393, 393, 393, 393, 393, 393,
393, 393, 393, 393, 393, 393, 393, 393, 393, 393,
393, 393, 393, 393, 393, 393, 393, 393, 393, 393,
393, 393, 393, 393, 393
} ;
static yyconst flex_int16_t yy_chk[706] =
{ 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 5, 5,
6, 6, 7, 8, 29, 28, 77, 31, 29, 30,
28, 31, 77, 29, 5, 28, 6, 33, 7, 8,
29, 36, 30, 39, 35, 34, 92, 33, 35, 92,
33, 34, 39, 84, 36, 84, 33, 35, 34, 54,
54, 40, 95, 71, 93, 40, 388, 7, 8, 40,
95, 111, 109, 176, 40, 71, 112, 93, 114, 40,
67, 109, 114, 118, 118, 111, 109, 176, 124, 112,
112, 114, 386, 67, 117, 67, 173, 117, 173, 67,
124, 117, 384, 67, 67, 67, 67, 117, 160, 178,
67, 160, 67, 116, 183, 67, 116, 116, 184, 260,
116, 116, 260, 178, 338, 383, 116, 382, 183, 116,
338, 260, 184, 381, 260, 394, 394, 394, 394, 394,
394, 394, 394, 394, 394, 394, 394, 394, 394, 394,
394, 394, 394, 394, 394, 394, 394, 394, 394, 394,
394, 394, 394, 394, 394, 394, 394, 394, 394, 394,
394, 394, 394, 394, 394, 394, 394, 394, 394, 394,
394, 394, 394, 395, 395, 395, 395, 395, 395, 395,
395, 395, 395, 395, 395, 395, 395, 395, 395, 395,
395, 395, 395, 395, 395, 395, 395, 395, 395, 395,
395, 395, 395, 395, 395, 395, 395, 395, 395, 395,
395, 395, 395, 395, 395, 395, 395, 395, 395, 395,
395, 396, 396, 396, 396, 396, 396, 396, 396, 396,
396, 396, 396, 396, 396, 396, 396, 396, 396, 396,
396, 396, 396, 396, 396, 396, 396, 396, 396, 396,
396, 396, 396, 396, 396, 396, 396, 396, 396, 396,
396, 396, 396, 396, 396, 396, 396, 396, 396, 397,
380, 374, 397, 372, 371, 370, 369, 397, 397, 397,
397, 368, 367, 366, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
397, 397, 397, 397, 397, 397, 397, 397, 397, 397,
398, 364, 363, 398, 362, 361, 359, 358, 398, 398,
398, 398, 357, 356, 355, 398, 398, 398, 398, 398,
398, 398, 398, 398, 398, 398, 398, 398, 398, 398,
398, 398, 398, 398, 398, 398, 398, 398, 398, 398,
398, 399, 399, 353, 399, 399, 399, 399, 399, 399,
399, 399, 399, 399, 399, 399, 399, 399, 399, 399,
399, 399, 399, 399, 399, 399, 399, 399, 399, 399,
399, 399, 399, 399, 399, 399, 399, 399, 399, 399,
399, 399, 399, 399, 399, 399, 399, 399, 399, 352,
351, 350, 349, 347, 346, 344, 343, 342, 341, 339,
337, 335, 333, 332, 331, 329, 328, 327, 326, 325,
324, 323, 322, 321, 320, 317, 315, 313, 312, 311,
310, 309, 308, 307, 306, 305, 304, 303, 302, 300,
285, 283, 281, 279, 277, 275, 274, 272, 271, 270,
269, 265, 264, 263, 262, 259, 258, 257, 256, 255,
254, 252, 251, 249, 247, 246, 244, 243, 241, 238,
237, 233, 231, 228, 227, 224, 223, 222, 221, 220,
219, 217, 216, 215, 213, 212, 211, 210, 209, 208,
207, 206, 205, 204, 202, 201, 200, 199, 197, 195,
194, 193, 192, 191, 190, 189, 188, 187, 186, 185,
182, 181, 180, 179, 177, 175, 172, 171, 170, 168,
167, 165, 164, 163, 162, 161, 159, 158, 157, 156,
155, 154, 153, 151, 150, 149, 148, 147, 146, 145,
144, 143, 141, 140, 139, 138, 136, 135, 133, 131,
129, 128, 127, 126, 125, 123, 122, 121, 120, 119,
115, 113, 110, 108, 107, 106, 105, 104, 103, 101,
100, 97, 96, 94, 91, 90, 89, 88, 87, 86,
83, 82, 81, 80, 79, 78, 76, 75, 74, 73,
72, 70, 69, 68, 66, 65, 64, 63, 62, 61,
59, 58, 56, 44, 43, 42, 41, 38, 37, 32,
23, 22, 17, 9, 4, 3, 393, 393, 393, 393,
393, 393, 393, 393, 393, 393, 393, 393, 393, 393,
393, 393, 393, 393, 393, 393, 393, 393, 393, 393,
393, 393, 393, 393, 393, 393, 393, 393, 393, 393,
393, 393, 393, 393, 393, 393, 393, 393, 393, 393,
393, 393, 393, 393, 393
} ;
/* Table of booleans, true if rule could match eol. */
static yyconst flex_int32_t yy_rule_can_match_eol[114] =
{ 0,
1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };
static yy_state_type yy_last_accepting_state;
static char *yy_last_accepting_cpos;
extern int smt_flex_debug;
int smt_flex_debug = 0;
/* The intent behind this definition is that it'll catch
* any uses of REJECT which flex missed.
*/
#define REJECT reject_used_but_not_detected
#define yymore() yymore_used_but_not_detected
#define YY_MORE_ADJ 0
#define YY_RESTORE_YY_MORE_OFFSET
char *smttext;
#line 1 "/home/yue/Work/stp/lib/Parser/smt.lex"
#line 2 "/home/yue/Work/stp/lib/Parser/smt.lex"
/********************************************************************
* AUTHORS: Vijay Ganesh, David L. Dill, Trevor Hansen
*
* BEGIN DATE: July, 2006
*
* This file is modified version of the CVCL's smtlib.lex file. Please
* see CVCL license below
********************************************************************/
/********************************************************************
* \file smtlib.lex
*
* Author: Sergey Berezin, Clark Barrett
*
* Created: Apr 30 2005
*
* <hr>
* Copyright (C) 2004 by the Board of Trustees of Leland Stanford
* Junior University and by New York University.
*
* License to use, copy, modify, sell and/or distribute this software
* and its documentation for any purpose is hereby granted without
* royalty, subject to the terms and conditions defined in the \ref
* LICENSE file provided with this distribution. In particular:
*
* - The above copyright notice and this permission notice must appear
* in all copies of the software and related documentation.
*
* - THE SOFTWARE IS PROVIDED "AS-IS", WITHOUT ANY WARRANTIES,
* EXPRESSED OR IMPLIED. USE IT AT YOUR OWN RISK.
*
* <hr>
********************************************************************/
#include <iostream>
#include "stp/Parser/parser.h"
#include "parsesmt.tab.h"
#include "stp/cpp_interface.h"
using namespace std;
using namespace stp;
extern char *smttext;
extern int smterror (const char *msg);
// File-static (local to this file) variables and functions
static THREAD_LOCAL std::string _string_lit;
static char escapeChar(char c) {
switch(c) {
case 'n': return '\n';
case 't': return '\t';
default: return c;
}
}
#line 852 "/home/yue/Work/stp/build/lib/Parser/lexsmt.cpp"
#define INITIAL 0
#define COMMENT 1
#define STRING_LITERAL 2
#define USER_VALUE 3
#ifndef YY_NO_UNISTD_H
/* Special case for "unistd.h", since it is non-ANSI. We include it way
* down here because we want the user's section 1 to have been scanned first.
* The user has a chance to override it with an option.
*/
#include <unistd.h>
#endif
#ifndef YY_EXTRA_TYPE
#define YY_EXTRA_TYPE void *
#endif
static int yy_init_globals (void );
/* Accessor methods to globals.
These are made visible to non-reentrant scanners for convenience. */
int smtlex_destroy (void );
int smtget_debug (void );
void smtset_debug (int debug_flag );
YY_EXTRA_TYPE smtget_extra (void );
void smtset_extra (YY_EXTRA_TYPE user_defined );
FILE *smtget_in (void );
void smtset_in (FILE * _in_str );
FILE *smtget_out (void );
void smtset_out (FILE * _out_str );
yy_size_t smtget_leng (void );
char *smtget_text (void );
int smtget_lineno (void );
void smtset_lineno (int _line_number );
/* Macros after this point can all be overridden by user definitions in
* section 1.
*/
#ifndef YY_SKIP_YYWRAP
#ifdef __cplusplus
extern "C" int smtwrap (void );
#else
extern int smtwrap (void );
#endif
#endif
#ifndef YY_NO_UNPUT
#endif
#ifndef yytext_ptr
static void yy_flex_strncpy (char *,yyconst char *,int );
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * );
#endif
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (void );
#else
static int input (void );
#endif
#endif
/* Amount of stuff to slurp up with each read. */
#ifndef YY_READ_BUF_SIZE
#ifdef __ia64__
/* On IA-64, the buffer size is 16k, not 8k */
#define YY_READ_BUF_SIZE 16384
#else
#define YY_READ_BUF_SIZE 8192
#endif /* __ia64__ */
#endif
/* Copy whatever the last rule matched to the standard output. */
#ifndef ECHO
/* This used to be an fputs(), but since the string might contain NUL's,
* we now use fwrite().
*/
#define ECHO do { if (fwrite( smttext, smtleng, 1, smtout )) {} } while (0)
#endif
/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL,
* is returned in "result".
*/
#ifndef YY_INPUT
#define YY_INPUT(buf,result,max_size) \
if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
{ \
int c = '*'; \
size_t n; \
for ( n = 0; n < max_size && \
(c = getc( smtin )) != EOF && c != '\n'; ++n ) \
buf[n] = (char) c; \
if ( c == '\n' ) \
buf[n++] = (char) c; \
if ( c == EOF && ferror( smtin ) ) \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
result = n; \
} \
else \
{ \
errno=0; \
while ( (result = fread(buf, 1, max_size, smtin))==0 && ferror(smtin)) \
{ \
if( errno != EINTR) \
{ \
YY_FATAL_ERROR( "input in flex scanner failed" ); \
break; \
} \
errno=0; \
clearerr(smtin); \
} \
}\
\
#endif
/* No semi-colon after return; correct usage is to write "yyterminate();" -
* we don't want an extra ';' after the "return" because that will cause
* some compilers to complain about unreachable statements.
*/
#ifndef yyterminate
#define yyterminate() return YY_NULL
#endif
/* Number of entries by which start-condition stack grows. */
#ifndef YY_START_STACK_INCR
#define YY_START_STACK_INCR 25
#endif
/* Report a fatal error. */
#ifndef YY_FATAL_ERROR
#define YY_FATAL_ERROR(msg) yy_fatal_error( msg )
#endif
/* end tables serialization structures and prototypes */
/* Default declaration of generated scanner - a define so the user can
* easily add parameters.
*/
#ifndef YY_DECL
#define YY_DECL_IS_OURS 1
extern int smtlex (void);
#define YY_DECL int smtlex (void)
#endif /* !YY_DECL */
/* Code executed at the beginning of each rule, after smttext and smtleng
* have been set up.
*/
#ifndef YY_USER_ACTION
#define YY_USER_ACTION
#endif
/* Code executed at the end of each rule. */
#ifndef YY_BREAK
#define YY_BREAK /*LINTED*/break;
#endif
#define YY_RULE_SETUP \
YY_USER_ACTION
/** The main scanner function which does all the work.
*/
YY_DECL
{
yy_state_type yy_current_state;
char *yy_cp, *yy_bp;
int yy_act;
if ( !(yy_init) )
{
(yy_init) = 1;
#ifdef YY_USER_INIT
YY_USER_INIT;
#endif
if ( ! (yy_start) )
(yy_start) = 1; /* first start state */
if ( ! smtin )
smtin = stdin;
if ( ! smtout )
smtout = stdout;
if ( ! YY_CURRENT_BUFFER ) {
smtensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
smt_create_buffer(smtin,YY_BUF_SIZE );
}
smt_load_buffer_state( );
}
{
#line 73 "/home/yue/Work/stp/lib/Parser/smt.lex"
#line 1073 "/home/yue/Work/stp/build/lib/Parser/lexsmt.cpp"
while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */
{
yy_cp = (yy_c_buf_p);
/* Support of smttext. */
*yy_cp = (yy_hold_char);
/* yy_bp points to the position in yy_ch_buf of the start of
* the current run.
*/
yy_bp = yy_cp;
yy_current_state = (yy_start);
yy_match:
do
{
YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ;
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
++yy_cp;
}
while ( yy_current_state != 393 );
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
yy_find_action:
yy_act = yy_accept[yy_current_state];
YY_DO_BEFORE_ACTION;
if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] )
{
yy_size_t yyl;
for ( yyl = 0; yyl < smtleng; ++yyl )
if ( smttext[yyl] == '\n' )
smtlineno++;
;
}
do_action: /* This label is used only to access EOF actions. */
switch ( yy_act )
{ /* beginning of action switch */
case 0: /* must back up */
/* undo the effects of YY_DO_BEFORE_ACTION */
*yy_cp = (yy_hold_char);
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
goto yy_find_action;
case 1:
/* rule 1 can match eol */
YY_RULE_SETUP
#line 74 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ /* sk'ip whitespace */ }
YY_BREAK
case 2:
YY_RULE_SETUP
#line 75 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ smtlval.uintval = strtoul(smttext, NULL, 10); return NUMERAL_TOK; }
YY_BREAK
case 3:
YY_RULE_SETUP
#line 78 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ smtlval.str = new std::string(smttext+2); return BVCONST_TOK; }
YY_BREAK
case 4:
YY_RULE_SETUP
#line 80 "/home/yue/Work/stp/lib/Parser/smt.lex"
{
char c = smttext[3];
if (c == '1') {
smtlval.node = new stp::ASTNode(GlobalParserInterface->CreateOneConst(1));
}
else {
smtlval.node = new stp::ASTNode(GlobalParserInterface->CreateZeroConst(1));
}
return BITCONST_TOK;
};
YY_BREAK
case 5:
YY_RULE_SETUP
#line 92 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ BEGIN COMMENT; }
YY_BREAK
case 6:
/* rule 6 can match eol */
YY_RULE_SETUP
#line 93 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ BEGIN INITIAL; /* return to normal mode */}
YY_BREAK
case 7:
YY_RULE_SETUP
#line 94 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ /* stay in comment mode */ }
YY_BREAK
case 8:
YY_RULE_SETUP
#line 96 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ BEGIN STRING_LITERAL;
_string_lit.erase(_string_lit.begin(),
_string_lit.end()); }
YY_BREAK
case 9:
YY_RULE_SETUP
#line 99 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ /* escape characters (like \n or \") */
_string_lit.insert(_string_lit.end(),
escapeChar(smttext[1])); }
YY_BREAK
case 10:
YY_RULE_SETUP
#line 102 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ BEGIN INITIAL; /* return to normal mode */
smtlval.str = new std::string(_string_lit);
return STRING_TOK; }
YY_BREAK
case 11:
YY_RULE_SETUP
#line 105 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ _string_lit.insert(_string_lit.end(),*smttext); }
YY_BREAK
case 12:
YY_RULE_SETUP
#line 108 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ BEGIN USER_VALUE;
_string_lit.erase(_string_lit.begin(),
_string_lit.end()); }
YY_BREAK
case 13:
YY_RULE_SETUP
#line 111 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ /* escape characters */
_string_lit.insert(_string_lit.end(),smttext[1]); }
YY_BREAK
case 14:
YY_RULE_SETUP
#line 114 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ BEGIN INITIAL; /* return to normal mode */
smtlval.str = new std::string(_string_lit);
return USER_VAL_TOK; }
YY_BREAK
case 15:
/* rule 15 can match eol */
YY_RULE_SETUP
#line 117 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ _string_lit.insert(_string_lit.end(),'\n');}
YY_BREAK
case 16:
YY_RULE_SETUP
#line 118 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ _string_lit.insert(_string_lit.end(),*smttext); }
YY_BREAK
case 17:
YY_RULE_SETUP
#line 120 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BITVEC_TOK;}
YY_BREAK
case 18:
YY_RULE_SETUP
#line 121 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return ARRAY_TOK;}
YY_BREAK
case 19:
YY_RULE_SETUP
#line 122 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return TRUE_TOK; }
YY_BREAK
case 20:
YY_RULE_SETUP
#line 123 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return FALSE_TOK; }
YY_BREAK
case 21:
YY_RULE_SETUP
#line 124 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return NOT_TOK; }
YY_BREAK
case 22:
YY_RULE_SETUP
#line 125 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return IMPLIES_TOK; }
YY_BREAK
case 23:
YY_RULE_SETUP
#line 126 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return ITE_TOK;}
YY_BREAK
case 24:
YY_RULE_SETUP
#line 127 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return ITE_TOK;} // This is in the SMTLIB benchmarks.
YY_BREAK
case 25:
YY_RULE_SETUP
#line 128 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return AND_TOK; }
YY_BREAK
case 26:
YY_RULE_SETUP
#line 129 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return OR_TOK; }
YY_BREAK
case 27:
YY_RULE_SETUP
#line 130 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return XOR_TOK; }
YY_BREAK
case 28:
YY_RULE_SETUP
#line 131 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return IFF_TOK; }
YY_BREAK
case 29:
YY_RULE_SETUP
#line 132 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return LET_TOK; }
YY_BREAK
case 30:
YY_RULE_SETUP
#line 133 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return FLET_TOK; }
YY_BREAK
case 31:
YY_RULE_SETUP
#line 134 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return NOTES_TOK; }
YY_BREAK
case 32:
YY_RULE_SETUP
#line 135 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return SORTS_TOK; }
YY_BREAK
case 33:
YY_RULE_SETUP
#line 136 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return FUNS_TOK; }
YY_BREAK
case 34:
YY_RULE_SETUP
#line 137 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return PREDS_TOK; }
YY_BREAK
case 35:
YY_RULE_SETUP
#line 138 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return EXTENSIONS_TOK; }
YY_BREAK
case 36:
YY_RULE_SETUP
#line 139 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return DEFINITION_TOK; }
YY_BREAK
case 37:
YY_RULE_SETUP
#line 140 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return AXIOMS_TOK; }
YY_BREAK
case 38:
YY_RULE_SETUP
#line 141 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return LOGIC_TOK; }
YY_BREAK
case 39:
YY_RULE_SETUP
#line 142 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return SAT_TOK; }
YY_BREAK
case 40:
YY_RULE_SETUP
#line 143 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return UNSAT_TOK; }
YY_BREAK
case 41:
YY_RULE_SETUP
#line 144 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return UNKNOWN_TOK; }
YY_BREAK
case 42:
YY_RULE_SETUP
#line 145 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return ASSUMPTION_TOK; }
YY_BREAK
case 43:
YY_RULE_SETUP
#line 146 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return FORMULA_TOK; }
YY_BREAK
case 44:
YY_RULE_SETUP
#line 147 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return STATUS_TOK; }
YY_BREAK
case 45:
YY_RULE_SETUP
#line 148 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return DIFFICULTY_TOK; }
YY_BREAK
case 46:
YY_RULE_SETUP
#line 149 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BENCHMARK_TOK; }
YY_BREAK
case 47:
YY_RULE_SETUP
#line 150 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return SOURCE_TOK;}
YY_BREAK
case 48:
YY_RULE_SETUP
#line 151 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return CATEGORY_TOK;}
YY_BREAK
case 49:
YY_RULE_SETUP
#line 152 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return EXTRASORTS_TOK; }
YY_BREAK
case 50:
YY_RULE_SETUP
#line 153 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return EXTRAFUNS_TOK; }
YY_BREAK
case 51:
YY_RULE_SETUP
#line 154 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return EXTRAPREDS_TOK; }
YY_BREAK
case 52:
YY_RULE_SETUP
#line 155 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return LANGUAGE_TOK; }
YY_BREAK
case 53:
YY_RULE_SETUP
#line 156 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return DISTINCT_TOK; }
YY_BREAK
case 54:
YY_RULE_SETUP
#line 157 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return SELECT_TOK; }
YY_BREAK
case 55:
YY_RULE_SETUP
#line 158 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return STORE_TOK; }
YY_BREAK
case 56:
YY_RULE_SETUP
#line 159 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return COLON_TOK; }
YY_BREAK
case 57:
YY_RULE_SETUP
#line 160 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return LBRACKET_TOK; }
YY_BREAK
case 58:
YY_RULE_SETUP
#line 161 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return RBRACKET_TOK; }
YY_BREAK
case 59:
YY_RULE_SETUP
#line 162 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return LPAREN_TOK; }
YY_BREAK
case 60:
YY_RULE_SETUP
#line 163 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return RPAREN_TOK; }
YY_BREAK
case 61:
YY_RULE_SETUP
#line 164 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return DOLLAR_TOK; }
YY_BREAK
case 62:
YY_RULE_SETUP
#line 165 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return QUESTION_TOK; }
YY_BREAK
case 63:
YY_RULE_SETUP
#line 166 "/home/yue/Work/stp/lib/Parser/smt.lex"
{return EQ_TOK;}
YY_BREAK
case 64:
YY_RULE_SETUP
#line 168 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return NAND_TOK;}
YY_BREAK
case 65:
YY_RULE_SETUP
#line 169 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return NOR_TOK;}
YY_BREAK
case 66:
YY_RULE_SETUP
#line 170 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVLEFTSHIFT_1_TOK;}
YY_BREAK
case 67:
YY_RULE_SETUP
#line 171 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVRIGHTSHIFT_1_TOK;}
YY_BREAK
case 68:
YY_RULE_SETUP
#line 172 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVARITHRIGHTSHIFT_TOK;}
YY_BREAK
case 69:
YY_RULE_SETUP
#line 173 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVPLUS_TOK;}
YY_BREAK
case 70:
YY_RULE_SETUP
#line 174 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVSUB_TOK;}
YY_BREAK
case 71:
YY_RULE_SETUP
#line 175 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVNOT_TOK;}
YY_BREAK
case 72:
YY_RULE_SETUP
#line 176 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVMULT_TOK;}
YY_BREAK
case 73:
YY_RULE_SETUP
#line 177 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVDIV_TOK;}
YY_BREAK
case 74:
YY_RULE_SETUP
#line 178 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return SBVDIV_TOK;}
YY_BREAK
case 75:
YY_RULE_SETUP
#line 179 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVMOD_TOK;}
YY_BREAK
case 76:
YY_RULE_SETUP
#line 180 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return SBVREM_TOK;}
YY_BREAK
case 77:
YY_RULE_SETUP
#line 181 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return SBVMOD_TOK;}
YY_BREAK
case 78:
YY_RULE_SETUP
#line 182 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVNEG_TOK;}
YY_BREAK
case 79:
YY_RULE_SETUP
#line 183 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVAND_TOK;}
YY_BREAK
case 80:
YY_RULE_SETUP
#line 184 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVOR_TOK;}
YY_BREAK
case 81:
YY_RULE_SETUP
#line 185 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVXOR_TOK;}
YY_BREAK
case 82:
YY_RULE_SETUP
#line 186 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVNAND_TOK;}
YY_BREAK
case 83:
YY_RULE_SETUP
#line 187 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVNOR_TOK;}
YY_BREAK
case 84:
YY_RULE_SETUP
#line 188 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVXNOR_TOK;}
YY_BREAK
case 85:
YY_RULE_SETUP
#line 189 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVCONCAT_TOK;}
YY_BREAK
case 86:
YY_RULE_SETUP
#line 190 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVEXTRACT_TOK;}
YY_BREAK
case 87:
YY_RULE_SETUP
#line 191 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVLT_TOK;}
YY_BREAK
case 88:
YY_RULE_SETUP
#line 192 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVGT_TOK;}
YY_BREAK
case 89:
YY_RULE_SETUP
#line 193 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVLE_TOK;}
YY_BREAK
case 90:
YY_RULE_SETUP
#line 194 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVGE_TOK;}
YY_BREAK
case 91:
YY_RULE_SETUP
#line 195 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVLT_TOK;}
YY_BREAK
case 92:
YY_RULE_SETUP
#line 196 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVGT_TOK;}
YY_BREAK
case 93:
YY_RULE_SETUP
#line 197 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVLE_TOK;}
YY_BREAK
case 94:
YY_RULE_SETUP
#line 198 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVGE_TOK;}
YY_BREAK
case 95:
YY_RULE_SETUP
#line 199 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVLE_TOK;}
YY_BREAK
case 96:
YY_RULE_SETUP
#line 200 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVGE_TOK;}
YY_BREAK
case 97:
YY_RULE_SETUP
#line 202 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVSLT_TOK;}
YY_BREAK
case 98:
YY_RULE_SETUP
#line 203 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVSGT_TOK;}
YY_BREAK
case 99:
YY_RULE_SETUP
#line 204 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVSLE_TOK;}
YY_BREAK
case 100:
YY_RULE_SETUP
#line 205 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVSGE_TOK;}
YY_BREAK
case 101:
YY_RULE_SETUP
#line 206 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVSLE_TOK;}
YY_BREAK
case 102:
YY_RULE_SETUP
#line 207 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVSGE_TOK;}
YY_BREAK
case 103:
YY_RULE_SETUP
#line 209 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVCOMP_TOK;}
YY_BREAK
case 104:
YY_RULE_SETUP
#line 212 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVZX_TOK;}
YY_BREAK
case 105:
YY_RULE_SETUP
#line 213 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVSX_TOK;}
YY_BREAK
case 106:
YY_RULE_SETUP
#line 214 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVREPEAT_TOK;}
YY_BREAK
case 107:
YY_RULE_SETUP
#line 216 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVROTATE_LEFT_TOK;}
YY_BREAK
case 108:
YY_RULE_SETUP
#line 217 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BVROTATE_RIGHT_TOK;}
YY_BREAK
case 109:
YY_RULE_SETUP
#line 219 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BOOLEXTRACT_TOK;}
YY_BREAK
case 110:
YY_RULE_SETUP
#line 220 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ return BOOL_TO_BV_TOK;}
YY_BREAK
case 111:
YY_RULE_SETUP
#line 222 "/home/yue/Work/stp/lib/Parser/smt.lex"
{
string str(smttext);
bool found = false;
ASTNode nptr;
if (stp::GlobalParserInterface->isSymbolAlreadyDeclared(str)) // it's a symbol.
{
nptr= stp::GlobalParserInterface->LookupOrCreateSymbol(str);
found = true;
}
else if (stp::GlobalParserInterface->letMgr->isLetDeclared(str)) // a let.
{
nptr= stp::GlobalParserInterface->letMgr->resolveLet(str);
found = true;
}
if (found)
{
smtlval.node = stp::GlobalParserInterface->newNode(nptr);
if ((smtlval.node)->GetType() == stp::BOOLEAN_TYPE)
return FORMID_TOK;
else
return TERMID_TOK;
}
// It hasn't been found. So it's not already declared.
// it has not been seen before.
smtlval.str = new std::string(str);
return STRING_TOK;
}
YY_BREAK
case 112:
YY_RULE_SETUP
#line 252 "/home/yue/Work/stp/lib/Parser/smt.lex"
{ smterror("Illegal input character."); }
YY_BREAK
case 113:
YY_RULE_SETUP
#line 253 "/home/yue/Work/stp/lib/Parser/smt.lex"
ECHO;
YY_BREAK
#line 1751 "/home/yue/Work/stp/build/lib/Parser/lexsmt.cpp"
case YY_STATE_EOF(INITIAL):
case YY_STATE_EOF(COMMENT):
case YY_STATE_EOF(STRING_LITERAL):
case YY_STATE_EOF(USER_VALUE):
yyterminate();
case YY_END_OF_BUFFER:
{
/* Amount of text matched not including the EOB char. */
int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1;
/* Undo the effects of YY_DO_BEFORE_ACTION. */
*yy_cp = (yy_hold_char);
YY_RESTORE_YY_MORE_OFFSET
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
{
/* We're scanning a new file or input source. It's
* possible that this happened because the user
* just pointed smtin at a new source and called
* smtlex(). If so, then we have to assure
* consistency between YY_CURRENT_BUFFER and our
* globals. Here is the right place to do so, because
* this is the first action (other than possibly a
* back-up) that will match for the new input source.
*/
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
YY_CURRENT_BUFFER_LVALUE->yy_input_file = smtin;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
}
/* Note that here we test for yy_c_buf_p "<=" to the position
* of the first EOB in the buffer, since yy_c_buf_p will
* already have been incremented past the NUL character
* (since all states make transitions on EOB to the
* end-of-buffer state). Contrast this with the test
* in input().
*/
if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
{ /* This was really a NUL. */
yy_state_type yy_next_state;
(yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
/* Okay, we're now positioned to make the NUL
* transition. We couldn't have
* yy_get_previous_state() go ahead and do it
* for us because it doesn't know how to deal
* with the possibility of jamming (and we don't
* want to build jamming into it because then it
* will run more slowly).
*/
yy_next_state = yy_try_NUL_trans( yy_current_state );
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
if ( yy_next_state )
{
/* Consume the NUL. */
yy_cp = ++(yy_c_buf_p);
yy_current_state = yy_next_state;
goto yy_match;
}
else
{
yy_cp = (yy_last_accepting_cpos);
yy_current_state = (yy_last_accepting_state);
goto yy_find_action;
}
}
else switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_END_OF_FILE:
{
(yy_did_buffer_switch_on_eof) = 0;
if ( smtwrap( ) )
{
/* Note: because we've taken care in
* yy_get_next_buffer() to have set up
* smttext, we can now set up
* yy_c_buf_p so that if some total
* hoser (like flex itself) wants to
* call the scanner after we return the
* YY_NULL, it'll still work - another
* YY_NULL will get returned.
*/
(yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ;
yy_act = YY_STATE_EOF(YY_START);
goto do_action;
}
else
{
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
}
break;
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) =
(yytext_ptr) + yy_amount_of_matched_text;
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_match;
case EOB_ACT_LAST_MATCH:
(yy_c_buf_p) =
&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)];
yy_current_state = yy_get_previous_state( );
yy_cp = (yy_c_buf_p);
yy_bp = (yytext_ptr) + YY_MORE_ADJ;
goto yy_find_action;
}
break;
}
default:
YY_FATAL_ERROR(
"fatal flex scanner internal error--no action found" );
} /* end of action switch */
} /* end of scanning one token */
} /* end of user's declarations */
} /* end of smtlex */
/* yy_get_next_buffer - try to read in a new buffer
*
* Returns a code representing an action:
* EOB_ACT_LAST_MATCH -
* EOB_ACT_CONTINUE_SCAN - continue scanning from current position
* EOB_ACT_END_OF_FILE - end of file
*/
static int yy_get_next_buffer (void)
{
char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
char *source = (yytext_ptr);
yy_size_t number_to_move, i;
int ret_val;
if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] )
YY_FATAL_ERROR(
"fatal flex scanner internal error--end of buffer missed" );
if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
{ /* Don't try to fill the buffer, so this is an EOF. */
if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 )
{
/* We matched a single character, the EOB, so
* treat this as a final EOF.
*/
return EOB_ACT_END_OF_FILE;
}
else
{
/* We matched some text prior to the EOB, first
* process it.
*/
return EOB_ACT_LAST_MATCH;
}
}
/* Try to read more data. */
/* First move last chars to start of buffer. */
number_to_move = (yy_size_t) ((yy_c_buf_p) - (yytext_ptr)) - 1;
for ( i = 0; i < number_to_move; ++i )
*(dest++) = *(source++);
if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
/* don't do the read, it's not guaranteed to return an EOF,
* just force an EOF
*/
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0;
else
{
yy_size_t num_to_read =
YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
while ( num_to_read <= 0 )
{ /* Not enough room in the buffer - grow it. */
/* just a shorter name for the current buffer */
YY_BUFFER_STATE b = YY_CURRENT_BUFFER_LVALUE;
int yy_c_buf_p_offset =
(int) ((yy_c_buf_p) - b->yy_ch_buf);
if ( b->yy_is_our_buffer )
{
yy_size_t new_size = b->yy_buf_size * 2;
if ( new_size <= 0 )
b->yy_buf_size += b->yy_buf_size / 8;
else
b->yy_buf_size *= 2;
b->yy_ch_buf = (char *)
/* Include room in for 2 EOB chars. */
smtrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 );
}
else
/* Can't grow it, we don't own it. */
b->yy_ch_buf = 0;
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR(
"fatal error - scanner input buffer overflow" );
(yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset];
num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
number_to_move - 1;
}
if ( num_to_read > YY_READ_BUF_SIZE )
num_to_read = YY_READ_BUF_SIZE;
/* Read in more data. */
YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
(yy_n_chars), num_to_read );
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
if ( (yy_n_chars) == 0 )
{
if ( number_to_move == YY_MORE_ADJ )
{
ret_val = EOB_ACT_END_OF_FILE;
smtrestart(smtin );
}
else
{
ret_val = EOB_ACT_LAST_MATCH;
YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
YY_BUFFER_EOF_PENDING;
}
}
else
ret_val = EOB_ACT_CONTINUE_SCAN;
if ((int) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) {
/* Extend the array by 50%, plus the number we really need. */
int new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1);
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) smtrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size );
if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" );
}
(yy_n_chars) += number_to_move;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR;
YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR;
(yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
return ret_val;
}
/* yy_get_previous_state - get the state just before the EOB char was reached */
static yy_state_type yy_get_previous_state (void)
{
yy_state_type yy_current_state;
char *yy_cp;
yy_current_state = (yy_start);
for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp )
{
YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
}
return yy_current_state;
}
/* yy_try_NUL_trans - try to make a transition on the NUL character
*
* synopsis
* next_state = yy_try_NUL_trans( current_state );
*/
static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state )
{
int yy_is_jam;
char *yy_cp = (yy_c_buf_p);
YY_CHAR yy_c = 1;
if ( yy_accept[yy_current_state] )
{
(yy_last_accepting_state) = yy_current_state;
(yy_last_accepting_cpos) = yy_cp;
}
while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
{
yy_current_state = (int) yy_def[yy_current_state];
}
yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
yy_is_jam = (yy_current_state == 393);
return yy_is_jam ? 0 : yy_current_state;
}
#ifndef YY_NO_UNPUT
#endif
#ifndef YY_NO_INPUT
#ifdef __cplusplus
static int yyinput (void)
#else
static int input (void)
#endif
{
int c;
*(yy_c_buf_p) = (yy_hold_char);
if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR )
{
/* yy_c_buf_p now points to the character we want to return.
* If this occurs *before* the EOB characters, then it's a
* valid NUL; if not, then we've hit the end of the buffer.
*/
if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
/* This was really a NUL. */
*(yy_c_buf_p) = '\0';
else
{ /* need more input */
yy_size_t offset = (yy_c_buf_p) - (yytext_ptr);
++(yy_c_buf_p);
switch ( yy_get_next_buffer( ) )
{
case EOB_ACT_LAST_MATCH:
/* This happens because yy_g_n_b()
* sees that we've accumulated a
* token and flags that we need to
* try matching the token before
* proceeding. But for input(),
* there's no matching to consider.
* So convert the EOB_ACT_LAST_MATCH
* to EOB_ACT_END_OF_FILE.
*/
/* Reset buffer status. */
smtrestart(smtin );
/*FALLTHROUGH*/
case EOB_ACT_END_OF_FILE:
{
if ( smtwrap( ) )
return EOF;
if ( ! (yy_did_buffer_switch_on_eof) )
YY_NEW_FILE;
#ifdef __cplusplus
return yyinput();
#else
return input();
#endif
}
case EOB_ACT_CONTINUE_SCAN:
(yy_c_buf_p) = (yytext_ptr) + offset;
break;
}
}
}
c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */
*(yy_c_buf_p) = '\0'; /* preserve smttext */
(yy_hold_char) = *++(yy_c_buf_p);
if ( c == '\n' )
smtlineno++;
;
return c;
}
#endif /* ifndef YY_NO_INPUT */
/** Immediately switch to a different input stream.
* @param input_file A readable stream.
*
* @note This function does not reset the start condition to @c INITIAL .
*/
void smtrestart (FILE * input_file )
{
if ( ! YY_CURRENT_BUFFER ){
smtensure_buffer_stack ();
YY_CURRENT_BUFFER_LVALUE =
smt_create_buffer(smtin,YY_BUF_SIZE );
}
smt_init_buffer(YY_CURRENT_BUFFER,input_file );
smt_load_buffer_state( );
}
/** Switch to a different input buffer.
* @param new_buffer The new input buffer.
*
*/
void smt_switch_to_buffer (YY_BUFFER_STATE new_buffer )
{
/* TODO. We should be able to replace this entire function body
* with
* smtpop_buffer_state();
* smtpush_buffer_state(new_buffer);
*/
smtensure_buffer_stack ();
if ( YY_CURRENT_BUFFER == new_buffer )
return;
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
YY_CURRENT_BUFFER_LVALUE = new_buffer;
smt_load_buffer_state( );
/* We don't actually know whether we did this switch during
* EOF (smtwrap()) processing, but the only time this flag
* is looked at is after smtwrap() is called, so it's safe
* to go ahead and always set it.
*/
(yy_did_buffer_switch_on_eof) = 1;
}
static void smt_load_buffer_state (void)
{
(yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
(yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
smtin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
(yy_hold_char) = *(yy_c_buf_p);
}
/** Allocate and initialize an input buffer state.
* @param file A readable stream.
* @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
*
* @return the allocated buffer state.
*/
YY_BUFFER_STATE smt_create_buffer (FILE * file, int size )
{
YY_BUFFER_STATE b;
b = (YY_BUFFER_STATE) smtalloc(sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in smt_create_buffer()" );
b->yy_buf_size = (yy_size_t)size;
/* yy_ch_buf has to be 2 characters longer than the size given because
* we need to put in 2 end-of-buffer characters.
*/
b->yy_ch_buf = (char *) smtalloc(b->yy_buf_size + 2 );
if ( ! b->yy_ch_buf )
YY_FATAL_ERROR( "out of dynamic memory in smt_create_buffer()" );
b->yy_is_our_buffer = 1;
smt_init_buffer(b,file );
return b;
}
/** Destroy the buffer.
* @param b a buffer created with smt_create_buffer()
*
*/
void smt_delete_buffer (YY_BUFFER_STATE b )
{
if ( ! b )
return;
if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
if ( b->yy_is_our_buffer )
smtfree((void *) b->yy_ch_buf );
smtfree((void *) b );
}
/* Initializes or reinitializes a buffer.
* This function is sometimes called more than once on the same buffer,
* such as during a smtrestart() or at EOF.
*/
static void smt_init_buffer (YY_BUFFER_STATE b, FILE * file )
{
int oerrno = errno;
smt_flush_buffer(b );
b->yy_input_file = file;
b->yy_fill_buffer = 1;
/* If b is the current buffer, then smt_init_buffer was _probably_
* called from smtrestart() or through yy_get_next_buffer.
* In that case, we don't want to reset the lineno or column.
*/
if (b != YY_CURRENT_BUFFER){
b->yy_bs_lineno = 1;
b->yy_bs_column = 0;
}
b->yy_is_interactive = 0;
errno = oerrno;
}
/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
* @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
*
*/
void smt_flush_buffer (YY_BUFFER_STATE b )
{
if ( ! b )
return;
b->yy_n_chars = 0;
/* We always need two end-of-buffer characters. The first causes
* a transition to the end-of-buffer state. The second causes
* a jam in that state.
*/
b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
b->yy_buf_pos = &b->yy_ch_buf[0];
b->yy_at_bol = 1;
b->yy_buffer_status = YY_BUFFER_NEW;
if ( b == YY_CURRENT_BUFFER )
smt_load_buffer_state( );
}
/** Pushes the new state onto the stack. The new state becomes
* the current state. This function will allocate the stack
* if necessary.
* @param new_buffer The new state.
*
*/
void smtpush_buffer_state (YY_BUFFER_STATE new_buffer )
{
if (new_buffer == NULL)
return;
smtensure_buffer_stack();
/* This block is copied from smt_switch_to_buffer. */
if ( YY_CURRENT_BUFFER )
{
/* Flush out information for old buffer. */
*(yy_c_buf_p) = (yy_hold_char);
YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
}
/* Only push if top exists. Otherwise, replace top. */
if (YY_CURRENT_BUFFER)
(yy_buffer_stack_top)++;
YY_CURRENT_BUFFER_LVALUE = new_buffer;
/* copied from smt_switch_to_buffer. */
smt_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
/** Removes and deletes the top of the stack, if present.
* The next element becomes the new top.
*
*/
void smtpop_buffer_state (void)
{
if (!YY_CURRENT_BUFFER)
return;
smt_delete_buffer(YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
if ((yy_buffer_stack_top) > 0)
--(yy_buffer_stack_top);
if (YY_CURRENT_BUFFER) {
smt_load_buffer_state( );
(yy_did_buffer_switch_on_eof) = 1;
}
}
/* Allocates the stack if it does not exist.
* Guarantees space for at least one push.
*/
static void smtensure_buffer_stack (void)
{
yy_size_t num_to_alloc;
if (!(yy_buffer_stack)) {
/* First allocation is just for 2 elements, since we don't know if this
* scanner will even need a stack. We use 2 instead of 1 to avoid an
* immediate realloc on the next call.
*/
num_to_alloc = 1; /* After all that talk, this was set to 1 anyways... */
(yy_buffer_stack) = (struct yy_buffer_state**)smtalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in smtensure_buffer_stack()" );
memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
(yy_buffer_stack_top) = 0;
return;
}
if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){
/* Increase the buffer to prepare for a possible push. */
yy_size_t grow_size = 8 /* arbitrary grow size */;
num_to_alloc = (yy_buffer_stack_max) + grow_size;
(yy_buffer_stack) = (struct yy_buffer_state**)smtrealloc
((yy_buffer_stack),
num_to_alloc * sizeof(struct yy_buffer_state*)
);
if ( ! (yy_buffer_stack) )
YY_FATAL_ERROR( "out of dynamic memory in smtensure_buffer_stack()" );
/* zero only the new slots.*/
memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*));
(yy_buffer_stack_max) = num_to_alloc;
}
}
/** Setup the input buffer state to scan directly from a user-specified character buffer.
* @param base the character buffer
* @param size the size in bytes of the character buffer
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE smt_scan_buffer (char * base, yy_size_t size )
{
YY_BUFFER_STATE b;
if ( size < 2 ||
base[size-2] != YY_END_OF_BUFFER_CHAR ||
base[size-1] != YY_END_OF_BUFFER_CHAR )
/* They forgot to leave room for the EOB's. */
return 0;
b = (YY_BUFFER_STATE) smtalloc(sizeof( struct yy_buffer_state ) );
if ( ! b )
YY_FATAL_ERROR( "out of dynamic memory in smt_scan_buffer()" );
b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */
b->yy_buf_pos = b->yy_ch_buf = base;
b->yy_is_our_buffer = 0;
b->yy_input_file = 0;
b->yy_n_chars = b->yy_buf_size;
b->yy_is_interactive = 0;
b->yy_at_bol = 1;
b->yy_fill_buffer = 0;
b->yy_buffer_status = YY_BUFFER_NEW;
smt_switch_to_buffer(b );
return b;
}
/** Setup the input buffer state to scan a string. The next call to smtlex() will
* scan from a @e copy of @a str.
* @param yystr a NUL-terminated string to scan
*
* @return the newly allocated buffer state object.
* @note If you want to scan bytes that may contain NUL values, then use
* smt_scan_bytes() instead.
*/
YY_BUFFER_STATE smt_scan_string (yyconst char * yystr )
{
return smt_scan_bytes(yystr,strlen(yystr) );
}
/** Setup the input buffer state to scan the given bytes. The next call to smtlex() will
* scan from a @e copy of @a bytes.
* @param yybytes the byte buffer to scan
* @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes.
*
* @return the newly allocated buffer state object.
*/
YY_BUFFER_STATE smt_scan_bytes (yyconst char * yybytes, yy_size_t _yybytes_len )
{
YY_BUFFER_STATE b;
char *buf;
yy_size_t n;
yy_size_t i;
/* Get memory for full buffer, including space for trailing EOB's. */
n = _yybytes_len + 2;
buf = (char *) smtalloc(n );
if ( ! buf )
YY_FATAL_ERROR( "out of dynamic memory in smt_scan_bytes()" );
for ( i = 0; i < _yybytes_len; ++i )
buf[i] = yybytes[i];
buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
b = smt_scan_buffer(buf,n );
if ( ! b )
YY_FATAL_ERROR( "bad buffer in smt_scan_bytes()" );
/* It's okay to grow etc. this buffer, and we should throw it
* away when we're done.
*/
b->yy_is_our_buffer = 1;
return b;
}
#ifndef YY_EXIT_FAILURE
#define YY_EXIT_FAILURE 2
#endif
static void yy_fatal_error (yyconst char* msg )
{
(void) fprintf( stderr, "%s\n", msg );
exit( YY_EXIT_FAILURE );
}
/* Redefine yyless() so it works in section 3 code. */
#undef yyless
#define yyless(n) \
do \
{ \
/* Undo effects of setting up smttext. */ \
int yyless_macro_arg = (n); \
YY_LESS_LINENO(yyless_macro_arg);\
smttext[smtleng] = (yy_hold_char); \
(yy_c_buf_p) = smttext + yyless_macro_arg; \
(yy_hold_char) = *(yy_c_buf_p); \
*(yy_c_buf_p) = '\0'; \
smtleng = yyless_macro_arg; \
} \
while ( 0 )
/* Accessor methods (get/set functions) to struct members. */
/** Get the current line number.
*
*/
int smtget_lineno (void)
{
return smtlineno;
}
/** Get the input stream.
*
*/
FILE *smtget_in (void)
{
return smtin;
}
/** Get the output stream.
*
*/
FILE *smtget_out (void)
{
return smtout;
}
/** Get the length of the current token.
*
*/
yy_size_t smtget_leng (void)
{
return smtleng;
}
/** Get the current token.
*
*/
char *smtget_text (void)
{
return smttext;
}
/** Set the current line number.
* @param _line_number line number
*
*/
void smtset_lineno (int _line_number )
{
smtlineno = _line_number;
}
/** Set the input stream. This does not discard the current
* input buffer.
* @param _in_str A readable stream.
*
* @see smt_switch_to_buffer
*/
void smtset_in (FILE * _in_str )
{
smtin = _in_str ;
}
void smtset_out (FILE * _out_str )
{
smtout = _out_str ;
}
int smtget_debug (void)
{
return smt_flex_debug;
}
void smtset_debug (int _bdebug )
{
smt_flex_debug = _bdebug ;
}
static int yy_init_globals (void)
{
/* Initialization is the same as for the non-reentrant scanner.
* This function is called from smtlex_destroy(), so don't allocate here.
*/
/* We do not touch smtlineno unless the option is enabled. */
smtlineno = 1;
(yy_buffer_stack) = 0;
(yy_buffer_stack_top) = 0;
(yy_buffer_stack_max) = 0;
(yy_c_buf_p) = (char *) 0;
(yy_init) = 0;
(yy_start) = 0;
/* Defined in main.c */
#ifdef YY_STDINIT
smtin = stdin;
smtout = stdout;
#else
smtin = (FILE *) 0;
smtout = (FILE *) 0;
#endif
/* For future reference: Set errno on error, since we are called by
* smtlex_init()
*/
return 0;
}
/* smtlex_destroy is for both reentrant and non-reentrant scanners. */
int smtlex_destroy (void)
{
/* Pop the buffer stack, destroying each element. */
while(YY_CURRENT_BUFFER){
smt_delete_buffer(YY_CURRENT_BUFFER );
YY_CURRENT_BUFFER_LVALUE = NULL;
smtpop_buffer_state();
}
/* Destroy the stack itself. */
smtfree((yy_buffer_stack) );
(yy_buffer_stack) = NULL;
/* Reset the globals. This is important in a non-reentrant scanner so the next time
* smtlex() is called, initialization will occur. */
yy_init_globals( );
return 0;
}
/*
* Internal utility routines.
*/
#ifndef yytext_ptr
static void yy_flex_strncpy (char* s1, yyconst char * s2, int n )
{
int i;
for ( i = 0; i < n; ++i )
s1[i] = s2[i];
}
#endif
#ifdef YY_NEED_STRLEN
static int yy_flex_strlen (yyconst char * s )
{
int n;
for ( n = 0; s[n]; ++n )
;
return n;
}
#endif
void *smtalloc (yy_size_t size )
{
return (void *) malloc( size );
}
void *smtrealloc (void * ptr, yy_size_t size )
{
/* The cast to (char *) in the following accommodates both
* implementations that use char* generic pointers, and those
* that use void* generic pointers. It works with the latter
* because both ANSI C and C++ allow castless assignment from
* any pointer type to void*, and deal with argument conversions
* as though doing an assignment.
*/
return (void *) realloc( (char *) ptr, size );
}
void smtfree (void * ptr )
{
free( (char *) ptr ); /* see smtrealloc() for (char *) cast */
}
#define YYTABLES_NAME "yytables"
#line 253 "/home/yue/Work/stp/lib/Parser/smt.lex"
namespace stp {
void SMTScanString (const char *yy_str) {
smt_scan_string(yy_str);
}
FILE* getSMTIn() {
return smtin;
}
void setSMTIn(FILE* file) {
smtin = file;
}
}
| 28.612044 | 117 | 0.615342 | [
"object"
] |
0368b4f56a4a9d941df827994cd74adb32a6a8f6 | 12,533 | cpp | C++ | OBJLoader.cpp | Locky-Brand/Simple-OBJ-file-3d-model-loader | 959fbbb9320d5b1ce8f545f95196b58546d1298a | [
"MIT"
] | null | null | null | OBJLoader.cpp | Locky-Brand/Simple-OBJ-file-3d-model-loader | 959fbbb9320d5b1ce8f545f95196b58546d1298a | [
"MIT"
] | null | null | null | OBJLoader.cpp | Locky-Brand/Simple-OBJ-file-3d-model-loader | 959fbbb9320d5b1ce8f545f95196b58546d1298a | [
"MIT"
] | null | null | null | #include "OBJLoader.h"
namespace OBJFile {
OBJLoader::OBJLoader() {
}
OBJLoader::~OBJLoader() {
}
loadInfo OBJLoader::load(const char* iPath, float* iRawArray) {
std::ifstream file(iPath, std::ios_base::binary);
if (file.is_open()) {
std::vector<fileVec3> verts;
std::vector<fileVec3> norms;
std::vector<fileVec2> tex;
std::vector<fileInd> inds;
std::vector<fileInd> assembledInds;
bool hasTex = false;
bool hasNorm = false;
// extraction of data
std::string currentLine;
while (!file.eof()) {
std::getline(file, currentLine);
switch (currentLine[0]) {
case 'v':
{
switch (currentLine[1]) {
case 'n':
{
fileVec3 vec;
sscanf_s(currentLine.c_str(), "vn %f %f %f\n", &vec.x, &vec.y, &vec.z);
norms.push_back(vec);
}
break;
case 't':
{
fileVec2 vec;
sscanf_s(currentLine.c_str(), "vt %f %f\n", &vec.x, &vec.y);
tex.push_back(vec);
}
break;
default:
{
fileVec3 vec;
sscanf_s(currentLine.c_str(), "v %f %f %f\n", &vec.x, &vec.y, &vec.z);
verts.push_back(vec);
}
break;
}
}
break;
case 'f':
{
fileInd ind = { 0, 0, 0 };
unsigned int slashCount = 0;
currentLine.append(1, '\n');
std::string indStr = "";
for (auto i = 2; i < currentLine.size(); ++i) {
if (currentLine[i] == '/') {
switch (slashCount)
{
case 0:
ind.pos = atoi(indStr.c_str());
indStr.clear();
if (currentLine[i + 1] != '/') {
hasTex = true;
}
break;
case 1:
ind.tex = atoi(indStr.c_str());
indStr.clear();
hasNorm = true;
break;
default:
break;
}
++slashCount;
}
else if (currentLine[i] == ' ') {
ind.norm = atoi(indStr.c_str());
indStr.clear();
inds.push_back(ind);
slashCount = 0;
}
else if (currentLine[i] == '\n') {
ind.norm = atoi(indStr.c_str());
indStr.clear();
inds.push_back(ind);
slashCount = 0;
fileInd pinInd = inds[0];
for (int n = 2; n < assembledInds.size(); ++n) {
assembledInds.push_back(pinInd);
assembledInds.push_back(inds[n - 1]);
assembledInds.push_back(inds[n]);
}
inds.clear();
}
else if (((currentLine[i] >= '0') && (currentLine[i] <= '9')) || (currentLine[i] == '-')) {
indStr.append(1, currentLine[i]);
}
}
}
break;
}
}
file.close();
// triangulation and assembly of data
if (hasTex && hasNorm) {
std::vector <fileVertex_all> assembledVerts;
for (auto& i : assembledInds) {
assembledVerts.push_back({ verts[i.pos].x, verts[i.pos].y, verts[i.pos].z, tex[i.tex].x, tex[i.tex].y, norms[i.norm].x, norms[i.norm].y, norms[i.norm].z });
}
iRawArray = new float[assembledVerts.size() * 8];
for (auto i = 7; i < assembledVerts.size(); i += 8) {
iRawArray[i - 7] = assembledVerts[i - 7].x;
iRawArray[i - 6] = assembledVerts[i - 7].y;
iRawArray[i - 5] = assembledVerts[i - 7].z;
iRawArray[i - 4] = assembledVerts[i - 7].tx;
iRawArray[i - 3] = assembledVerts[i - 7].ty;
iRawArray[i - 2] = assembledVerts[i - 7].nx;
iRawArray[i - 1] = assembledVerts[i - 7].ny;
iRawArray[i] = assembledVerts[i - 7].nz;
}
return { loadInfo::dataLayout::POS_TEX_NORM, assembledVerts.size() * 8 };
}
else if (hasTex && !hasNorm) {
std::vector <fileVertex_tex> assembledVerts;
for (auto& i : assembledInds) {
assembledVerts.push_back({ verts[i.pos].x, verts[i.pos].y, verts[i.pos].z, tex[i.tex].x, tex[i.tex].y });
}
iRawArray = new float[assembledVerts.size() * 5];
for (auto i = 4; i < assembledVerts.size(); i += 5) {
iRawArray[i - 4] = assembledVerts[i - 4].x;
iRawArray[i - 3] = assembledVerts[i - 4].y;
iRawArray[i - 2] = assembledVerts[i - 4].z;
iRawArray[i - 1] = assembledVerts[i - 4].tx;
iRawArray[i] = assembledVerts[i - 4].ty;
}
return { loadInfo::dataLayout::POS_TEX, assembledVerts.size() * 5 };
}
else if (!hasTex && hasNorm) {
std::vector <fileVertex_norm> assembledVerts;
for (auto& i : assembledInds) {
assembledVerts.push_back({ verts[i.pos].x, verts[i.pos].y, verts[i.pos].z, norms[i.norm].x, norms[i.norm].y, norms[i.norm].z });
}
iRawArray = new float[assembledVerts.size() * 6];
for (auto i = 5; i < assembledVerts.size(); i += 6) {
iRawArray[i - 5] = assembledVerts[i - 5].x;
iRawArray[i - 4] = assembledVerts[i - 5].y;
iRawArray[i - 3] = assembledVerts[i - 5].z;
iRawArray[i - 2] = assembledVerts[i - 5].nx;
iRawArray[i - 1] = assembledVerts[i - 5].ny;
iRawArray[i] = assembledVerts[i - 5].nz;
}
return { loadInfo::dataLayout::POS_NORM, assembledVerts.size() * 6 };
}
else {
std::vector <fileVertex_pos> assembledVerts;
for (auto& i : assembledInds) {
assembledVerts.push_back({ verts[i.pos].x, verts[i.pos].y, verts[i.pos].z });
}
iRawArray = new float[assembledVerts.size() * 3];
for (auto i = 2; i < assembledVerts.size(); i += 3) {
iRawArray[i - 2] = assembledVerts[i - 2].x;
iRawArray[i - 1] = assembledVerts[i - 2].y;
iRawArray[i] = assembledVerts[i - 2].z;
}
return { loadInfo::dataLayout::POS, assembledVerts.size() * 3 };
}
}
else {
std::cout << "error: file path not found" << '\n';
return { loadInfo::dataLayout::ERROR, 0 };
}
}
loadInfo OBJLoader::load(const char* iPath, std::vector<float>& iVector) {
std::ifstream file(iPath, std::ios_base::binary);
if (file.is_open()) {
std::vector<fileVec3> verts;
std::vector<fileVec3> norms;
std::vector<fileVec2> tex;
std::vector<fileInd> inds;
std::vector<fileInd> assembledInds;
bool hasTex = false;
bool hasNorm = false;
// extraction of data
std::string currentLine;
while (!file.eof()) {
std::getline(file, currentLine);
switch (currentLine[0]) {
case 'v':
{
switch (currentLine[1]) {
case 'n':
{
fileVec3 vec;
sscanf_s(currentLine.c_str(), "vn %f %f %f\n", &vec.x, &vec.y, &vec.z);
norms.push_back(vec);
}
break;
case 't':
{
fileVec2 vec;
sscanf_s(currentLine.c_str(), "vt %f %f\n", &vec.x, &vec.y);
tex.push_back(vec);
}
break;
default:
{
fileVec3 vec;
sscanf_s(currentLine.c_str(), "v %f %f %f\n", &vec.x, &vec.y, &vec.z);
verts.push_back(vec);
}
break;
}
}
break;
case 'f':
{
fileInd ind = { 0, 0, 0 };
unsigned int slashCount = 0;
currentLine.append(1, '\n');
std::string indStr = "";
for (auto i = 2; i < currentLine.size(); ++i) {
if (currentLine[i] == '/') {
switch (slashCount)
{
case 0:
ind.pos = atoi(indStr.c_str());
indStr.clear();
if (currentLine[i + 1] != '/') {
hasTex = true;
}
break;
case 1:
ind.tex = atoi(indStr.c_str());
indStr.clear();
hasNorm = true;
break;
default:
break;
}
++slashCount;
}
else if (currentLine[i] == ' ') {
ind.norm = atoi(indStr.c_str());
indStr.clear();
inds.push_back(ind);
slashCount = 0;
}
else if (currentLine[i] == '\n') {
ind.norm = atoi(indStr.c_str());
indStr.clear();
inds.push_back(ind);
slashCount = 0;
// triangulate all file inds in struct form
fileInd pinInd = inds[0];
for (int n = 2; n < inds.size(); ++n) {
assembledInds.push_back(pinInd);
assembledInds.push_back(inds[n - 1]);
assembledInds.push_back(inds[n]);
}
inds.clear();
}
else if (((currentLine[i] >= '0') && (currentLine[i] <= '9')) || (currentLine[i] == '-')) {
indStr.append(1, currentLine[i]);
}
}
}
break;
}
}
file.close();
// triangulation and assembly of data
if (hasTex && hasNorm) {
std::vector <fileVertex_all> assembledVerts;
// get all verticies assembled
for (auto& i : assembledInds) {
assembledVerts.push_back({ verts[i.pos - 1].x, verts[i.pos - 1].y, verts[i.pos - 1].z, tex[i.tex - 1].x, tex[i.tex - 1].y, norms[i.norm - 1].x, norms[i.norm - 1].y, norms[i.norm - 1].z });
}
// push all floats into the input buffer
for (auto i = 0; i < assembledVerts.size(); ++i) {
iVector.push_back(assembledVerts[i].x);
iVector.push_back(assembledVerts[i].y);
iVector.push_back(assembledVerts[i].z);
iVector.push_back(assembledVerts[i].tx);
iVector.push_back(assembledVerts[i].ty);
iVector.push_back(assembledVerts[i].nx);
iVector.push_back(assembledVerts[i].ny);
iVector.push_back(assembledVerts[i].nz);
}
return { loadInfo::dataLayout::POS_TEX_NORM, iVector.size() };
}
else if (hasTex && !hasNorm) {
std::vector <fileVertex_tex> assembledVerts;
for (auto& i : assembledInds) {
assembledVerts.push_back({ verts[i.pos - 1].x, verts[i.pos - 1].y, verts[i.pos - 1].z, tex[i.tex - 1].x, tex[i.tex - 1].y });
}
for (auto i = 0; i < assembledVerts.size(); ++i) {
iVector.push_back(assembledVerts[i].x);
iVector.push_back(assembledVerts[i].y);
iVector.push_back(assembledVerts[i].z);
iVector.push_back(assembledVerts[i].tx);
iVector.push_back(assembledVerts[i].ty);
}
return { loadInfo::dataLayout::POS_TEX, iVector.size() };
}
else if (!hasTex && hasNorm) {
std::vector <fileVertex_norm> assembledVerts;
for (auto& i : assembledInds) {
assembledVerts.push_back({ verts[i.pos - 1].x, verts[i.pos - 1].y, verts[i.pos - 1].z, norms[i.norm - 1].x, norms[i.norm - 1].y, norms[i.norm - 1].z });
}
for (auto i = 0; i < assembledVerts.size(); ++i) {
iVector.push_back(assembledVerts[i].x);
iVector.push_back(assembledVerts[i].y);
iVector.push_back(assembledVerts[i].z);
iVector.push_back(assembledVerts[i].nx);
iVector.push_back(assembledVerts[i].ny);
iVector.push_back(assembledVerts[i].nz);
}
return { loadInfo::dataLayout::POS_NORM, iVector.size() };
}
else {
std::vector <fileVertex_pos> assembledVerts;
for (auto& i : assembledInds) {
assembledVerts.push_back({ verts[i.pos - 1].x, verts[i.pos - 1].y, verts[i.pos - 1].z });
}
for (auto i = 0; i < assembledVerts.size(); ++i) {
iVector.push_back(assembledVerts[i].x);
iVector.push_back(assembledVerts[i].y);
iVector.push_back(assembledVerts[i].z);
}
return { loadInfo::dataLayout::POS, iVector.size() };
}
}
else {
std::cout << "error: file path not found" << '\n';
return { loadInfo::dataLayout::ERROR, 0 };
}
}
void OBJLoader::loadMtlFile(const char* iPath, std::vector<mtlMaterial>& iVector) {
bool clear = false;
std::ifstream mtlFile(iPath, std::ios_base::binary);
if (mtlFile.is_open()) {
std::string currentLine;
while (!mtlFile.eof()) {
std::getline(mtlFile, currentLine);
mtlMaterial newMat;
std::string prop = currentLine.substr(0, 2);
switch (prop[0]) {
case 'K':
{
std::string vecString = currentLine.substr(3, currentLine.size());
fileVec3 vecs;
sscanf_s(vecString.c_str(), "%f %f %f\n", &vecs.x, &vecs.y, &vecs.z);
switch (prop[1]) {
case 'a':
newMat.ka = vecs;
break;
case 'd':
newMat.kd = vecs;
break;
case 's':
newMat.ks = vecs;
break;
}
}
break;
case 'N':
{
std::string vecString = currentLine.substr(3, currentLine.size());
float num;
sscanf_s(vecString.c_str(), "%f\n", &num);
switch (prop[1]) {
case 's':
newMat.ns = num;
break;
case 'i':
newMat.ni = num;
break;
}
break;
}
case 'd':
{
std::string vecString = currentLine.substr(2, currentLine.size());
sscanf_s(vecString.c_str(), "%f\n", &newMat.d);
}
break;
case 'i':
{
std::string vecString = currentLine.substr(6, currentLine.size());
sscanf_s(vecString.c_str(), "%f\n", &newMat.illum);
}
break;
}
if (currentLine == "") {
if (clear) {
iVector.push_back(newMat);
}
clear = true;
}
}
mtlFile.close();
}
else {
std::cout << "error: mtlFile not found" << '\n';
}
}
} | 27.91314 | 193 | 0.560361 | [
"vector"
] |
0371ba8c20b3116529637cbb899f7e82c18233b0 | 2,302 | cpp | C++ | hamming_distance/hamming_distance.cpp | hossein1387/random_sw_experiments | 9b5163e2e67b7f3d89f67e57e1c7aa3b8b40011c | [
"MIT"
] | 1 | 2017-05-04T03:21:06.000Z | 2017-05-04T03:21:06.000Z | hamming_distance/hamming_distance.cpp | hossein1387/random_sw_experiments | 9b5163e2e67b7f3d89f67e57e1c7aa3b8b40011c | [
"MIT"
] | null | null | null | hamming_distance/hamming_distance.cpp | hossein1387/random_sw_experiments | 9b5163e2e67b7f3d89f67e57e1c7aa3b8b40011c | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <string>
#include <bitset>
#include <fstream>
#define SIZE_OF_ARRAY 10
#define NUM_BITS 31
#define MAX_RAND_VAL (1<<NUM_BITS)
#define OUTPUT_FILE_NAME "array.txt"
unsigned int hamming_res[SIZE_OF_ARRAY];
int popcount(int v) {
int c;
v = v - ((v >> 1) & 0x55555555); // put count of each 2 bits into those 2 bits
v = (v & 0x33333333) + ((v >> 2) & 0x33333333); // put count of each 4 bits into those 4 bits
return c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
}
int min_Hamming(unsigned int tab[], unsigned int tab_size) {
unsigned int min_hamming_dist = 33;
#if DEBUG==1
unsigned int cnt = 0;
#endif
for(int i=0; i<tab_size-1; i++)
{
for(int j=i+1; j<tab_size; j++){
unsigned int hamming_dist = popcount(tab[i] ^ tab[j]);
#if DEBUG==1
hamming_res[cnt] = hamming_dist;
printf("[%3d] hamming dist %s(%10d) and %s(%10d) = %2d\n",cnt, std::bitset<32>(tab[i]).to_string().c_str(),
tab[i], std::bitset<32>(tab[j]).to_string().c_str(), tab[j], hamming_dist);
cnt++;
#endif
if(hamming_dist==0) // if there is a hamming distance of zero, noone can beat it, return!
return 0;
if(hamming_dist < min_hamming_dist)
min_hamming_dist = hamming_dist;
}
}
return min_hamming_dist;
}
int main()
{
// prepare output file
#if DEBUG==1
std::ofstream array_file;
array_file.open (OUTPUT_FILE_NAME);
#endif
// initialize random seed and test array
srand (time(NULL));
unsigned int test_array[SIZE_OF_ARRAY];
int min_hdist;
// generate random numbers between 0 and SIZE_OF_ARRAY
for(int i=0; i<SIZE_OF_ARRAY; i++){
test_array[i] = rand() % MAX_RAND_VAL;
}
// call min hamming function to compute min hamming of the array
min_hdist = min_Hamming(test_array, SIZE_OF_ARRAY);
#if DEBUG==1
int cnt = 0;
for(int i=0; i<SIZE_OF_ARRAY-1; i++){
for(int j=i+1; j<SIZE_OF_ARRAY; j++){
array_file << test_array[i] << "," << test_array[j] << "," << hamming_res[cnt] << std::endl;
cnt++;
}
}
array_file << "min_hamming_dist" << "," << min_hdist << std::endl;
array_file.close();
#endif
return 0;
}
| 28.073171 | 120 | 0.617724 | [
"3d"
] |
0371fe0dbc0d311e20a71cfb602aa783b19a9499 | 3,148 | hpp | C++ | geometry/angles.hpp | marceldallagnol/omim | 774de15a3b8c369acbf412f15a1db61717358262 | [
"Apache-2.0"
] | 2 | 2019-01-24T15:36:20.000Z | 2019-12-26T10:03:48.000Z | geometry/angles.hpp | marceldallagnol/omim | 774de15a3b8c369acbf412f15a1db61717358262 | [
"Apache-2.0"
] | 1 | 2018-03-07T15:05:23.000Z | 2018-03-07T15:05:23.000Z | geometry/angles.hpp | marceldallagnol/omim | 774de15a3b8c369acbf412f15a1db61717358262 | [
"Apache-2.0"
] | 1 | 2019-08-09T21:31:29.000Z | 2019-08-09T21:31:29.000Z | #pragma once
#include "geometry/point2d.hpp"
#include "base/matrix.hpp"
#include "std/cmath.hpp"
#include "std/string.hpp"
namespace ang
{
template <typename T>
class Angle
{
T m_val;
T m_sin;
T m_cos;
public:
Angle() : m_val(0), m_sin(0), m_cos(1) {}
Angle(T const & val) : m_val(val), m_sin(::sin(val)), m_cos(::cos(val)) {}
Angle(T const & sin, T const & cos) : m_val(::atan2(sin, cos)), m_sin(sin), m_cos(cos) {}
T const & val() const
{
return m_val;
}
T const & sin() const
{
return m_sin;
}
T const & cos() const
{
return m_cos;
}
Angle<T> const & operator*=(math::Matrix<T, 3, 3> const & m)
{
m2::Point<T> pt0(0, 0);
m2::Point<T> pt1(m_cos, m_sin);
pt1 *= m;
pt0 *= m;
m_val = atan2(pt1.y - pt0.y, pt1.x - pt0.x);
m_sin = ::sin(m_val);
m_cos = ::cos(m_val);
return *this;
}
friend string DebugPrint(Angle<T> const & ang)
{
return DebugPrint(ang.m_val);
}
};
typedef Angle<double> AngleD;
typedef Angle<float> AngleF;
template <typename T>
Angle<T> const operator*(Angle<T> const & a, math::Matrix<T, 3, 3> const & m)
{
Angle<T> ret(a);
ret *= m;
return ret;
}
/// Returns an angle of vector [p1, p2] from x-axis directed to y-axis.
/// Angle is in range [-pi, pi].
template <typename T>
inline T AngleTo(m2::Point<T> const & p1, m2::Point<T> const & p2)
{
return atan2(p2.y - p1.y, p2.x - p1.x);
}
/// Returns an angle from vector [p, p1] to vector [p, p2]. A counterclockwise rotation.
/// Angle is in range [0, 2 * pi]
template <typename T>
inline T TwoVectorsAngle(m2::Point<T> const & p, m2::Point<T> const & p1, m2::Point<T> const & p2)
{
T a = ang::AngleTo(p, p2) - ang::AngleTo(p, p1);
while (a < 0)
a += math::twicePi;
return a;
}
double AngleIn2PI(double ang);
/// @return Oriented angle (<= PI) from rad1 to rad2.
/// >0 - clockwise, <0 - counterclockwise
double GetShortestDistance(double rad1, double rad2);
double GetMiddleAngle(double a1, double a2);
/// @return If north is zero - azimuth between geographic north and [p1, p2] vector is returned.
/// If north is not zero - it is treated as azimuth of some custom direction(eg magnetic north or some other direction),
/// and azimuth between that direction and [p1, p2] is returned.
/// Azimuth is in range [0, 2 * pi]
template <typename T>
inline T Azimuth(m2::Point<T> const & p1, m2::Point<T> const & p2, T north = 0)
{
T azimuth = math::pi2 - (AngleTo(p1, p2) + north);
if (azimuth < 0)
azimuth += math::twicePi;
return azimuth;
}
/// Average angle calcker. Can't find any suitable solution, so decided to do like this:
/// Avg(i) = Avg(Avg(i-1), Ai);
class AverageCalc
{
double m_ang;
bool m_isEmpty;
public:
AverageCalc() : m_ang(0.0), m_isEmpty(true) {}
void Add(double a)
{
m_ang = (m_isEmpty ? a : GetMiddleAngle(m_ang, a));
m_isEmpty = false;
}
double GetAverage() const
{
return m_ang;
}
};
}
| 23.492537 | 122 | 0.58831 | [
"geometry",
"vector"
] |
0376fe373c8e64c7766b792233fbebf7af92f5f5 | 16,755 | cc | C++ | Chapter12/examples-ch12.cc | Vaibhav-Kashyap/Mastering-cpp-stl17-packt | b28dbbb89ad6caf65b614312102162178bd4618b | [
"MIT"
] | 89 | 2017-10-29T23:05:25.000Z | 2022-03-06T07:47:15.000Z | Chapter12/examples-ch12.cc | harkhuang/Mastering-the-Cpp17-STL | b28dbbb89ad6caf65b614312102162178bd4618b | [
"MIT"
] | null | null | null | Chapter12/examples-ch12.cc | harkhuang/Mastering-the-Cpp17-STL | b28dbbb89ad6caf65b614312102162178bd4618b | [
"MIT"
] | 43 | 2017-09-28T06:17:17.000Z | 2022-03-06T07:47:38.000Z | #include <cassert>
#include <chrono>
#include <cstdio>
#include <fstream>
#include <future>
#include <iostream>
#include <string>
#define USE_BOOST 1
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
#define u8string string
#if 0
#include <charconv>
#else
#include <system_error>
namespace std {
struct from_chars_result {
const char* ptr;
std::errc ec;
};
struct to_chars_result {
char* ptr;
std::errc ec;
};
enum class chars_format {
scientific = 1,
fixed = 2,
hex = 4,
general = fixed | scientific
};
from_chars_result from_chars(const char*, const char*, int&, int = 10) { return {}; }
from_chars_result from_chars(const char* first, const char* last, float& value, chars_format fmt = chars_format::general);
to_chars_result to_chars(char* first, char* last, int value, int base = 10);
to_chars_result to_chars(char* first, char* last, float value);
to_chars_result to_chars(char* first, char* last, float value, chars_format fmt);
to_chars_result to_chars(char* first, char* last, float value, chars_format fmt, int precision);
} // namespace std
#endif
//ex3
#if USE_CXX17
#include <filesystem>
namespace fs = std::filesystem;
#elif USE_FILESYSTEM_TS
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#elif USE_BOOST
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
#endif
//dex3
namespace std::filesystem { using fs::path; using fs::remove; };
namespace ex1 {
//ex1
using namespace std::filesystem;
void foo(path p)
{
remove(p); // What function is this?
}
//dex1
} // namespace ex1
namespace ex2 {
//ex2
namespace fs = std::filesystem;
void foo(fs::path p)
{
fs::remove(p); // Much clearer!
}
//dex2
} // namespace ex2
namespace ex4 {
void test() {
std::ifstream f;
f.exceptions(std::ios_base::failbit);
//ex4
try {
f.open("hello.txt");
// Opening succeeded.
} catch (const std::ios_base::failure&) {
// Opening failed.
}
//dex4
assert(!f.is_open());
f.exceptions(std::ios_base::goodbit);
//ex5
f.open("hello.txt");
if (f.is_open()) {
// Opening succeeded.
} else {
// Opening failed.
}
//dex5
assert(!f.is_open());
}
} // namespace ex4
namespace ex6 {
void test() {
char s[] = "hello";
using std::end;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
//ex6
// Exception-throwing approach.
try {
int i = std::stoi(s);
// Parsing succeeded.
} catch (...) {
// Parsing failed.
}
//dex6
{
//ex7
char *endptr = nullptr;
errno = 0;
long i = strtol(s, &endptr, 10);
if (endptr != s && !errno) {
// Parsing succeeded.
} else {
// Parsing failed.
}
//dex7
}{
//ex8
int i = 0;
auto [ptr, ec] = std::from_chars(s, end(s), i);
if (ec != std::errc{}) {
// Parsing succeeded.
} else {
// Parsing failed.
}
//dex8
}
#pragma GCC diagnostic pop
}
} // namespace ex4
namespace ex9 {
//ex9
uintmax_t file_size(const fs::path& p);
uintmax_t file_size(const fs::path& p,
std::error_code& ec) noexcept;
//dex9
} // namespace ex9
namespace ex10 {
namespace std { using ::std::string; }
//ex10
namespace std {
enum class errc {
// implicitly, "0" means "no error"
operation_not_permitted = EPERM,
no_such_file_or_directory = ENOENT,
no_such_process = ESRCH,
// ...
value_too_large = EOVERFLOW
};
} // namespace std
//dex10
//ex11
namespace std {
class error_category {
public:
virtual const char *name() const noexcept = 0;
virtual std::string message(int err) const = 0;
// other virtual methods not shown
bool operator==(const std::error_category& rhs) const {
return this == &rhs;
}
};
} // namespace std
//dex11
//ex12
namespace std {
class error_code {
const std::error_category *m_cat;
int m_err;
public:
const auto& category() const { return m_cat; }
int value() const { return m_err; }
std::string message() const { return m_cat->message(m_err); }
explicit operator bool() const { return m_err != 0; }
// other convenience methods not shown
};
} // namespace std
//dex12
} // namespace ex10
namespace ex13 {
struct Unreachable {};
//ex13
namespace FinickyFS {
enum class Error : int {
success = 0,
forbidden_character = 1,
forbidden_word = 2,
};
struct ErrorCategory : std::error_category
{
const char *name() const noexcept override {
return "finicky filesystem";
}
std::string message(int err) const override {
switch (err) {
case 0: return "Success";
case 1: return "Invalid filename";
case 2: return "Bad word in filename";
}
throw Unreachable();
}
static ErrorCategory& instance() {
static ErrorCategory instance;
return instance;
}
};
std::error_code make_error_code(Error err) noexcept
{
return std::error_code(int(err), ErrorCategory::instance());
}
} // namespace FinickyFS
//dex13
void test() {
//ex14
// An error fits comfortably in a statically typed
// and value-semantic std::error_code object...
std::error_code ec =
make_error_code(FinickyFS::Error::forbidden_word);
// ...Yet its "what-string" remains just as
// accessible as if it were a dynamically typed
// exception!
assert(ec.message() == "Bad word in filename");
//dex14
}
} // namespace ex13
namespace ex15 {
struct Unreachable {};
namespace FinickyFS {
enum class Error : int {
success = 0,
forbidden_character = 1,
forbidden_word = 2,
};
struct ErrorCategory : std::error_category {
const char *name() const noexcept override {
return "finicky filesystem";
}
std::string message(int err) const override {
switch (err) {
case 0: return "Success";
case 1: return "Invalid filename";
case 2: return "Bad word in filename";
}
throw Unreachable();
}
static ErrorCategory& instance() {
static ErrorCategory instance;
return instance;
}
};
std::error_code make_error_code(Error err) noexcept {
return std::error_code(int(err), ErrorCategory::instance());
}
bool is_malformed_name(std::error_code ec);
} // namespace FinickyFS
} // namespace ex15
#define FinickyFS ex15::FinickyFS
//ex15
namespace std {
template<>
struct is_error_code_enum<::FinickyFS::Error> : true_type {};
} // namespace std
//dex15
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpragmas"
#pragma GCC diagnostic ignored "-Wunknown-warning-option"
#pragma GCC diagnostic ignored "-Wterminate"
//ex19
namespace FinickyFS {
enum class Condition : int {
success = 0,
malformed_name = 1,
};
struct ConditionCategory : std::error_category {
const char *name() const noexcept override {
return "finicky filesystem";
}
std::string message(int cond) const override {
switch (cond) {
case 0: return "Success";
case 1: return "Malformed name";
}
throw Unreachable();
}
bool equivalent(const std::error_code& ec, int cond) const noexcept override {
switch (cond) {
case 0: return !ec;
case 1: return is_malformed_name(ec);
}
throw Unreachable();
}
static ConditionCategory& instance() {
static ConditionCategory instance;
return instance;
}
};
std::error_condition make_error_condition(Condition cond) noexcept {
return std::error_condition(int(cond), ConditionCategory::instance());
}
} // namespace FinickyFS
namespace std {
template<>
struct is_error_condition_enum<::FinickyFS::Condition> : true_type {};
} // namespace std
//dex19
#undef FinickyFS
#pragma GCC diagnostic pop
namespace ex15 { // must be same as above
namespace FinickyFS {
//ex18
bool is_malformed_name(std::error_code ec) {
return (
ec == FinickyFS::Error::forbidden_character ||
ec == FinickyFS::Error::forbidden_word ||
ec == std::errc::illegal_byte_sequence);
}
//dex18
} // namespace FinickyFS
void test() {
//ex17
std::error_code ec = FinickyFS::Error::forbidden_character;
// Comparisons are strongly typed.
assert(ec == FinickyFS::Error::forbidden_character);
assert(ec != std::io_errc::stream);
//dex17
}
void test2() {
//ex20
std::error_code ec = FinickyFS::Error::forbidden_word;
// RHS is implicitly converted to error_code
assert(ec == FinickyFS::Error::forbidden_word);
// RHS is implicitly converted to error_condition
assert(ec == FinickyFS::Condition::malformed_name);
//dex20
}
} // namespace ex15
namespace ex16 {
using ::std::is_error_code_enum_v;
using ::std::enable_if_t;
//ex16
class error_code {
// ...
template<
class E,
class = enable_if_t<is_error_code_enum_v<E>>
>
error_code(E err) noexcept {
*this = make_error_code(err);
}
};
//dex16
} // namespace ex16
namespace ex21 {
#define file_size file_size2
//ex21
// The lower level is error_code-based.
uintmax_t file_size(const fs::path& p,
std::error_code& ec) noexcept;
// My level is throw-based.
uintmax_t file_size(const fs::path& p)
{
std::error_code ec;
uintmax_t size = file_size(p, ec);
if (ec) {
throw std::system_error(ec);
}
return size;
}
//dex21
uintmax_t file_size(const fs::path&, std::error_code&) noexcept { return -1; }
#undef file_size
} // namespace ex21
namespace ex22::detail { enum Error : int; }
namespace std { template<> struct is_error_code_enum<::ex22::detail::Error> : true_type {}; }
namespace ex22 {
std::error_code current_exception_to_error_code();
#define file_size file_size2
//ex22
// The lower level is throw-based.
uintmax_t file_size(const fs::path& p);
// My level is error_code-based.
uintmax_t file_size(const fs::path& p,
std::error_code& ec) noexcept
{
uintmax_t size = -1;
try {
size = file_size(p);
} catch (...) {
ec = current_exception_to_error_code();
}
return size;
}
//dex22
uintmax_t file_size(const fs::path&) { return -1; }
#undef file_size
//ex23
namespace detail {
enum Error : int {
success = 0,
bad_alloc_thrown = 1,
unknown_exception_thrown = 2,
};
struct ErrorCategory : std::error_category {
const char *name() const noexcept override;
std::string message(int err) const override;
static ErrorCategory& instance();
};
std::error_code make_error_code(Error err) noexcept {
return std::error_code(int(err), ErrorCategory::instance());
}
} // namespace detail
std::error_code current_exception_to_error_code()
{
try {
throw;
} catch (const std::system_error& e) {
// also catches std::ios_base::failure
// and fs::filesystem_error
return e.code();
} catch (const std::future_error& e) {
// catches the oddball
return e.code();
} catch (const std::bad_alloc&) {
// bad_alloc is often of special interest
return detail::bad_alloc_thrown;
} catch (...) {
return detail::unknown_exception_thrown;
}
}
//dex23
} // namespace ex22
namespace ex22::detail {
struct Unreachable{};
const char *ErrorCategory::name() const noexcept {
return "current_exception_to_error_code";
}
std::string ErrorCategory::message(int err) const {
switch (err) {
case 0: return "Success";
case 1: return "std::bad_alloc";
case 2: return "unknown exception";
}
throw Unreachable();
}
ErrorCategory& ErrorCategory::instance() {
static ErrorCategory instance;
return instance;
}
} // namespace ex22::detail
namespace ex24 {
static constexpr bool IsWindows = true;
//ex24
class path {
public:
using value_type = std::conditional_t<
IsWindows, wchar_t, char
>;
using string_type = std::basic_string<value_type>;
const auto& native() const { return m_path; }
operator string_type() const { return m_path; }
auto c_str() const { return m_path.c_str(); }
// many constructors and accessors omitted
private:
string_type m_path;
};
//dex24
} // namespace ex24
namespace ex25 {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
void test() {
//ex25
fs::path p("/foo/bar");
const fs::path::value_type *a = p.c_str();
// Portable, for whatever that's worth.
const char *b = p.c_str();
// OK on POSIX; compilation error on Windows.
std::string s = p.u8string();
const char *c = s.c_str();
// OK on both POSIX and Windows.
// Performs 16-to-8 conversion on Windows.
//dex25
}
#pragma GCC diagnostic pop
} // namespace ex25
namespace ex26 {
static constexpr bool IsWindows = false;
//ex27
static fs::path operator+(fs::path a, const fs::path& b)
{
a += b;
return a;
}
//dex27
void test() {
fs::path path("c:/foo/bar/data.tar.gz");
#define X(x) auto x = path.x();
X(root_path) X(root_name) X(root_directory)
X(relative_path) X(parent_path) X(filename)
X(stem) X(extension) X(is_absolute) X(is_relative)
#undef X
//ex26
assert(root_path == root_name / root_directory);
assert(path == root_name / root_directory / relative_path);
assert(path == root_path / relative_path);
assert(path == parent_path / filename);
assert(filename == stem + extension);
assert(is_absolute == !is_relative);
if (IsWindows) {
assert(is_relative == (root_name.empty() || root_directory.empty()));
} else {
assert(is_relative == (root_name.empty() && root_directory.empty()));
}
//dex26
}
} // namespace ex26
namespace ex28 {
void test() {
//ex28
fs::path p = "/foo/bar/baz.txt";
std::vector<fs::path> v(p.begin(), p.end());
assert((v == std::vector<fs::path>{
"/", "foo", "bar", "baz.txt"
}));
//dex28
}
} // namespace ex28
#if !USE_BOOST
namespace ex29 {
void test() {
using namespace std::literals;
//ex29
fs::path p = "/tmp/foo/bar.txt";
fs::directory_entry entry(p);
// Here, we still have not touched the file system.
while (!entry.exists()) {
std::cout << entry.path() << " does not exist yet\n";
std::this_thread::sleep_for(100ms);
entry.refresh();
// Without refresh(), this would loop forever.
}
// If the file is deleted right now, the following
// line might print stale cached values, or it
// might try to refresh the cache and throw.
std::cout << entry.path() << " has size "
<< entry.file_size() << "\n";
//dex29
}
} // namespace ex29
#endif // USE_BOOST
namespace ex30 {
#if USE_BOOST
void test() {
fs::path p = fs::current_path();
// List the current directory.
for (fs::directory_entry entry : fs::directory_iterator(p)) {
std::cout << entry.path().string() << ": "
<< file_size(entry.path()) << " bytes\n";
}
}
#else
void test() {
//ex30
fs::path p = fs::current_path();
// List the current directory.
for (fs::directory_entry entry : fs::directory_iterator(p)) {
std::cout << entry.path().string() << ": "
<< entry.file_size() << " bytes\n";
}
//dex30
}
#endif // USE_BOOST
} // namespace ex30
namespace ex31 {
#if USE_BOOST
template<class F>
void walk_down(const fs::path& p, const F& callback)
{
for (auto entry : fs::directory_iterator(p)) {
if (entry.status().type() == fs::file_type::directory_file) {
walk_down(entry.path(), callback);
} else {
callback(entry);
}
}
}
#else
//ex31
template<class F>
void walk_down(const fs::path& p, const F& callback)
{
for (auto entry : fs::directory_iterator(p)) {
if (entry.is_directory()) {
walk_down(entry.path(), callback);
} else {
callback(entry);
}
}
}
//dex31
#endif
} // namespace ex31
namespace ex32 {
//ex32
template<class F>
void walk_down(const fs::path& p, const F& callback)
{
for (auto entry : fs::recursive_directory_iterator(p)) {
callback(entry);
}
}
//dex32
} // namespace ex32
namespace ex33 {
//ex33
struct space_info {
uintmax_t capacity;
uintmax_t free;
uintmax_t available;
};
//dex33
} // namespace ex33
int main()
{
ex4::test();
ex13::test();
ex15::test();
ex15::test2();
ex25::test();
ex26::test();
ex28::test();
ex30::test();
}
| 23.598592 | 126 | 0.627216 | [
"object",
"vector"
] |
037be70ad2a2b8ae7a3a4b517a8e5b321fea5a4c | 6,244 | hpp | C++ | rr_evgp/src/costmap_plugins/skeletonize.hpp | ebretl/roboracing-software | 8803c97a885500069d04e70894b19f807ae5baf9 | [
"MIT"
] | null | null | null | rr_evgp/src/costmap_plugins/skeletonize.hpp | ebretl/roboracing-software | 8803c97a885500069d04e70894b19f807ae5baf9 | [
"MIT"
] | null | null | null | rr_evgp/src/costmap_plugins/skeletonize.hpp | ebretl/roboracing-software | 8803c97a885500069d04e70894b19f807ae5baf9 | [
"MIT"
] | null | null | null | #include <opencv2/opencv.hpp>
namespace rr {
cv::Mat thinObstacles(const cv::Mat& grid_in) {
std::vector<cv::Point> points;
cv::findNonZero(grid_in, points);
cv::Rect r = cv::boundingRect(points);
// Zhang thinning "A Fast Parallel Algorithm for Thinning Digital Patterns"
// ref https://rosettacode.org/wiki/Zhang-Suen_thinning_algorithm#C.2B.2B
cv::Mat grid, grid_copy;
grid_in(r).copyTo(grid);
// eliminate border
for (int r = 0; r < grid.rows; r++) {
grid.at<uint8_t>(r, 0) = 0;
grid.at<uint8_t>(r, grid.cols - 1) = 0;
}
for (int c = 0; c < grid.cols; c++) {
grid.at<uint8_t>(0, c) = 0;
grid.at<uint8_t>(grid.rows - 1, c) = 0;
}
grid.copyTo(grid_copy);
/*
* Count the number of rising edges around the center point
* 9 2 3
* 8 * 4
* 7 6 5
*/
auto clockwise_rising_edges = [](const cv::Mat& data, int r, int c) -> int {
int sum = 0;
sum += !data.at<uint8_t>(r - 1, c) && data.at<uint8_t>(r - 1, c + 1); // 2 3
sum += !data.at<uint8_t>(r - 1, c + 1) && data.at<uint8_t>(r, c + 1); // 3 4
sum += !data.at<uint8_t>(r, c + 1) && data.at<uint8_t>(r + 1, c + 1); // 4 5
sum += !data.at<uint8_t>(r + 1, c + 1) && data.at<uint8_t>(r + 1, c); // 5 6
sum += !data.at<uint8_t>(r + 1, c) && data.at<uint8_t>(r + 1, c - 1); // 6 7
sum += !data.at<uint8_t>(r + 1, c - 1) && data.at<uint8_t>(r, c - 1); // 7 8
sum += !data.at<uint8_t>(r, c - 1) && data.at<uint8_t>(r - 1, c - 1); // 8 9
sum += !data.at<uint8_t>(r - 1, c - 1) && data.at<uint8_t>(r - 1, c); // 9 2
return sum;
};
auto num_neighbors = [](const cv::Mat& data, int r, int c) -> int {
int sum = 0;
sum += (bool)data.at<uint8_t>(r - 1, c);
sum += (bool)data.at<uint8_t>(r - 1, c + 1);
sum += (bool)data.at<uint8_t>(r, c + 1);
sum += (bool)data.at<uint8_t>(r + 1, c + 1);
sum += (bool)data.at<uint8_t>(r + 1, c);
sum += (bool)data.at<uint8_t>(r + 1, c - 1);
sum += (bool)data.at<uint8_t>(r, c - 1);
sum += (bool)data.at<uint8_t>(r - 1, c - 1);
return sum;
};
int changed_pixels;
do {
changed_pixels = 0;
// step 1
grid.copyTo(grid_copy);
for (int r = 1; r < grid.rows - 1; r++) {
for (int c = 1; c < grid.cols - 1; c++) {
if (grid.at<uint8_t>(r, c)) {
int n = num_neighbors(grid, r, c);
if (n >= 2 && n <= 6 && clockwise_rising_edges(grid, r, c) == 1 &&
!(grid.at<uint8_t>(r - 1, c) && grid.at<uint8_t>(r, c + 1) && grid.at<uint8_t>(r + 1, c)) &&
!(grid.at<uint8_t>(r, c + 1) && grid.at<uint8_t>(r + 1, c) && grid.at<uint8_t>(r, c - 1))) {
grid_copy.at<uint8_t>(r, c) = 0;
changed_pixels++;
}
}
}
}
// step 2
grid_copy.copyTo(grid);
for (int r = 1; r < grid.rows - 1; r++) {
for (int c = 1; c < grid.cols - 1; c++) {
if (grid_copy.at<uint8_t>(r, c)) {
int n = num_neighbors(grid_copy, r, c);
if (n >= 2 && n <= 6 && clockwise_rising_edges(grid_copy, r, c) == 1 &&
!(grid_copy.at<uint8_t>(r - 1, c) && grid_copy.at<uint8_t>(r, c + 1) &&
grid_copy.at<uint8_t>(r, c - 1)) &&
!(grid_copy.at<uint8_t>(r - 1, c) && grid_copy.at<uint8_t>(r + 1, c) &&
grid_copy.at<uint8_t>(r, c - 1))) {
grid.at<uint8_t>(r, c) = 0;
changed_pixels++;
}
}
}
}
} while (changed_pixels > 0);
// remove staircases
// shamelessly borrowed from https://github.com/yati-sagade/zhang-suen-thinning/blob/master/zhangsuen.cpp
for (int iter = 0; iter < 2; iter++) {
for (int i = 1; i < grid.rows - 1; i++) {
for (int j = 1; j < grid.cols - 1; j++) {
int c = grid.at<uint8_t>(i, j);
if (!c) {
continue;
}
int e = grid.at<uint8_t>(i, j + 1), ne = grid.at<uint8_t>(i - 1, j + 1), n = grid.at<uint8_t>(i - 1, j),
nw = grid.at<uint8_t>(i - 1, j - 1), w = grid.at<uint8_t>(i, j - 1),
sw = grid.at<uint8_t>(i + 1, j - 1), s = grid.at<uint8_t>(i + 1, j),
se = grid.at<uint8_t>(i + 1, j + 1);
if (iter == 0) {
// North biased staircase removal
if ((n && ((e && !ne && !sw && (!w || !s)) || (w && !nw && !se && (!e || !s))))) {
grid.at<uint8_t>(i, j) = 0;
}
} else {
// South bias staircase removal
if ((s && ((e && !se && !nw && (!w || !n)) || (w && !sw && !ne && (!e || !n))))) {
grid.at<uint8_t>(i, j) = 0;
}
}
}
}
}
cv::Mat grid_skel(grid_in.size(), CV_8U, cv::Scalar(0));
grid.copyTo(grid_skel(r));
return grid_skel;
}
cv::Mat removeSmallBranches(const cv::Mat& img, const int min_branch_length) {
cv::Mat line_kernel(3, 3, CV_8U, cv::Scalar(1));
line_kernel.at<uint8_t>(1, 1) = 10;
cv::Mat filtered_img;
cv::filter2D(img / 255, filtered_img, CV_16S, line_kernel);
cv::Mat branches;
cv::inRange(filtered_img, cv::Scalar(11), cv::Scalar(12), branches);
std::vector<std::vector<cv::Point>> contours;
cv::findContours(branches, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);
cv::Mat big_branches(img.rows, img.cols, CV_8U, cv::Scalar(0));
for (size_t i = 0; i < contours.size(); i++) {
if (cv::arcLength(contours[i], false) >= min_branch_length) {
cv::drawContours(big_branches, contours, i, cv::Scalar(255), 1);
}
}
big_branches.setTo(cv::Scalar(255), filtered_img >= 13);
thinObstacles(big_branches);
return big_branches;
}
} // namespace rr
| 39.27044 | 120 | 0.462524 | [
"vector"
] |
037dc48f1359f0f66ce2e4a215f972e3632a6d67 | 75,208 | cpp | C++ | src/ode/ode/src/ode_MT/clustering/cluster.cpp | victorhu3/webots | 60d173850f0b4714c500db004e69f2df8cfb9e8a | [
"Apache-2.0"
] | 1,561 | 2019-09-04T11:32:32.000Z | 2022-03-31T18:00:09.000Z | src/ode/ode/src/ode_MT/clustering/cluster.cpp | victorhu3/webots | 60d173850f0b4714c500db004e69f2df8cfb9e8a | [
"Apache-2.0"
] | 2,184 | 2019-09-03T11:35:02.000Z | 2022-03-31T10:01:44.000Z | src/ode/ode/src/ode_MT/clustering/cluster.cpp | victorhu3/webots | 60d173850f0b4714c500db004e69f2df8cfb9e8a | [
"Apache-2.0"
] | 1,013 | 2019-09-07T05:09:32.000Z | 2022-03-31T13:01:28.000Z | #include "cluster.h"
#include "collision_kernel.h"
#include "joints/joints.h"
#include "ode/objects.h"
#include "util.h"
#include "ode/odemath.h"
#include "collision_std.h"
#include "heightfield.h"
#include "collision_trimesh_internal.h"
// Externally defined functions
extern void addObjectToList( dObject *obj, dObject **first );
extern void removeObjectFromList(dObject *obj);
extern void checkWorld(dxWorld *_world);
#undef ALLOCA
#undef DEALLOCA
#define ALLOCA(x) malloc(x) //dALLOCA16(x)
#define DEALLOCA(x) free(x)
#include <pthread.h>
static pthread_mutex_t geomDuplicationMapMutex; // used to lock geomDuplicationMap assignment
void dxClusteredWorldAndSpace::cleanupTable(dxClusterNode **&_table)
{
if (_table == NULL) return;
for (int i = 0; i < sz; ++i)
{
dxClusterNode *node = _table[i];
dxClusterNode *temp;
while (node)
{
temp = node->next;
DEALLOCA(node);
node = temp;
}
}
DEALLOCA(_table);
_table = NULL;
}
// Note: this function is possibly called in a multithread way
unsigned long dxClusteredWorldAndSpace::getVirtualAddress (dVector3 _pos)
{
const float x = xsteps / 2.0f + _pos[0];
const float y = ysteps / 2.0f + _pos[1];
const float z = zsteps / 2.0f + _pos[2];
unsigned long retVal = (x * ysteps * zsteps) + (y * zsteps) + (z);
if (retVal >= static_cast<unsigned long>(sz))
{
ODE_IMPORTANT("OUT OF BOUNDS! Retval: %ld, sz: %d, pos: (%f, %f, %f)\n", retVal, sz, _pos[0], _pos[1], _pos[2]);
bCalculateNewSZ = true;
return sz - 1;
}
return retVal;
}
void dxClusteredWorldAndSpace::setMinMax(dReal *bounds)
{
if (bounds[0] < xmin) xmin = bounds[0];
if (bounds[1] > xmax) xmax = bounds[1];
if (bounds[2] < ymin) ymin = bounds[2];
if (bounds[3] > ymax) ymax = bounds[3];
if (bounds[4] < zmin) zmin = bounds[4];
if (bounds[5] > zmax) zmax = bounds[5];
const dReal xsize = (bounds[1] - bounds[0]);
const dReal ysize = (bounds[3] - bounds[2]);
const dReal zsize = (bounds[5] - bounds[4]);
if (xsize < xsizemin) xsizemin = xsize;
if (xsize > xsizemax) xsizemax = xsize;
if (ysize < ysizemin) ysizemin = ysize;
if (ysize > ysizemax) ysizemax = ysize;
if (zsize < zsizemin) zsizemin = zsize;
if (zsize > zsizemax) zsizemax = zsize;
xsizeavg = (xsizeavg * algoN + xsize) / (float) (algoN + 1);
ysizeavg = (ysizeavg * algoN + ysize) / (float) (algoN + 1);
zsizeavg = (zsizeavg * algoN + zsize) / (float) (algoN + 1);
}
void dxClusteredWorldAndSpace::createNewWorldAndSpace(dWorldID &_newWorld, dSpaceID &_newSpace)
{
_newWorld = util_MT::worldFunc();
_newSpace = util_MT::spaceFunc(0);
dSpaceSetCleanup(_newSpace, false);
util_MT::copyWorldParameters(_newWorld, originalWorld);
}
void dxClusteredWorldAndSpace::addClusterNodeToClusterTable(dxClusterNode *node, ClusterNode *&_tail, bool _isStatic)
{
if (node->aabb->cluster == NULL)
{
node->aabb->cluster = _tail;
node->aabb->clusterID = clusterCount;
// assign body/geom to appropriate cluster AABB
dxClusterNode *newNode = (dxClusterNode*) ALLOCA (sizeof(dxClusterNode));
newNode->aabb = node->aabb;
newNode->aabb->node = NULL;
newNode->x = newNode->y = newNode->z = -1;
newNode->nextFreeNode = NULL;
newNode->cluster = NULL;
newNode->world = NULL;
newNode->space = NULL;
newNode->tagged = false;
newNode->isStatic = _isStatic;
// update parent node for AABB. used for crossover clustering
if (clusterAABBs[clusterCount]) clusterAABBs[clusterCount]->aabb->node = newNode;
if (clusterAABBs[clusterCount]) newNode->count = clusterAABBs[clusterCount]->count + 1;
else newNode->count = 1;
newNode->next = clusterAABBs[clusterCount];
clusterAABBs[clusterCount] = newNode;
}
}
void dxClusteredWorldAndSpace::addClusterNodeToCluster(dxClusterNode *_node, ClusterNode *&_cluster, ClusterNode *&_tail, bool _bGetAllNodesInCell)
{
dUASSERT(_node != NULL, "null node passed into findNeighboringCluster!");
_node->tagged = true;
// Create new cluster node and add to head of cluster linked list
ClusterNode *newCluster = (ClusterNode*) ALLOCA (sizeof (ClusterNode));
newCluster->next = NULL;
newCluster->node = NULL;
if (_cluster) newCluster->count = _cluster->count + 1;
else newCluster->count = 1;
newCluster->node = _node;
// attach new cluster to head of clusterchain
newCluster->next = _cluster;
_cluster = newCluster;
if (_tail == NULL)
{
_tail = newCluster;
}
if (!_bGetAllNodesInCell)
addClusterNodeToClusterTable(_node, _tail, true);
else
{
// assign all geoms in current clustercell to the same cluster
for (dxClusterNode *node=_node; node && node != _node->nextFreeNode; node = node->next)
addClusterNodeToClusterTable(node, _tail, false);
}
}
void dxClusteredWorldAndSpace::findNeighboringCluster(dxClusterNode *_node, ClusterNode *&_cluster, ClusterNode *&_tail)
{
addClusterNodeToCluster(_node, _cluster, _tail, true);
// go through neighboring cells and add to clusters too
unsigned long hi;
dVector3 newpos1 = { (dReal)_node->x + 1, (dReal)_node->y, (dReal)_node->z};
hi = getVirtualAddress (newpos1) % sz;
if (table[hi] && table[hi]->tagged == false && table[hi]->nextFreeNode != table[hi]) findNeighboringCluster(table[hi], _cluster, _tail);
dVector3 newpos2 = { (dReal)_node->x - 1, (dReal)_node->y, (dReal)_node->z};
hi = getVirtualAddress (newpos2) % sz;
if (table[hi] && table[hi]->tagged == false && table[hi]->nextFreeNode != table[hi]) findNeighboringCluster(table[hi], _cluster, _tail);
dVector3 newpos3 = { (dReal)_node->x, (dReal)_node->y + 1, (dReal)_node->z};
hi = getVirtualAddress (newpos3) % sz;
if (table[hi] && table[hi]->tagged == false && table[hi]->nextFreeNode != table[hi]) findNeighboringCluster(table[hi], _cluster, _tail);
dVector3 newpos4 = { (dReal)_node->x, (dReal)_node->y - 1, (dReal)_node->z};
hi = getVirtualAddress (newpos4) % sz;
if (table[hi] && table[hi]->tagged == false && table[hi]->nextFreeNode != table[hi]) findNeighboringCluster(table[hi], _cluster, _tail);
dVector3 newpos5 = { (dReal)_node->x, (dReal)_node->y, (dReal)_node->z + 1};
hi = getVirtualAddress (newpos5) % sz;
if (table[hi] && table[hi]->tagged == false && table[hi]->nextFreeNode != table[hi]) findNeighboringCluster(table[hi], _cluster, _tail);
dVector3 newpos6 = { (dReal)_node->x, (dReal)_node->y, (dReal)_node->z - 1};
hi = getVirtualAddress (newpos6) % sz;
if (table[hi] && table[hi]->tagged == false && table[hi]->nextFreeNode != table[hi]) findNeighboringCluster(table[hi], _cluster, _tail);
}
void dxClusteredWorldAndSpace::cleanupMemory()
{
dxClusterAABB *aabb = first_aabb;
dxClusterAABB *temp;
while (aabb)
{
temp = aabb->next;
DEALLOCA(aabb);
aabb = temp;
}
first_aabb = NULL;
aabb = big_boxes;
while (aabb)
{
temp = aabb->next;
DEALLOCA(aabb);
aabb = temp;
}
big_boxes = NULL;
cleanupTable(table);
DEALLOCA(tested);
tested = NULL;
for (int i = 0; i < clusterCount; ++i)
{
ClusterNode *cluster = clusterArray[i];
while (cluster)
{
ClusterNode *temp = cluster->next;
DEALLOCA(cluster);
cluster = temp;
}
clusterArray[i] = NULL;
dxClusterNode *cluster2 = clusterAABBs[i];
while (cluster2)
{
dxClusterNode *temp2 = cluster2->next;
DEALLOCA(cluster2);
cluster2 = temp2;
}
clusterAABBs[i] = NULL;
cleanupTable(clusterTables[i]);
delete(spaces[i]);
delete(worlds[i]);
spaces[i] = NULL;
worlds[i] = NULL;
if (geomDuplicationMap.find(i) != geomDuplicationMap.end())
{
geomMap& kidMap = geomDuplicationMap[i];
for (geomMap::iterator it=kidMap.begin(); it!=kidMap.end(); ++it)
{
DEALLOCA(it->second);
}
kidMap.clear();
}
}
geomDuplicationMap.clear();
activeClusterCount = deactivatedClusterCount = 0;
}
bool dxClusteredWorldAndSpace::isGeomBig(dxGeom* geom)
{
return (geom->type == dPlaneClass || geom->aabb[0] == -dInfinity || geom->aabb[1] == dInfinity || geom->aabb[2] == -dInfinity || geom->aabb[3] == dInfinity || geom->aabb[4] == -dInfinity || geom->aabb[5] == dInfinity);
}
bool dxClusteredWorldAndSpace::isGeomStatic(dxGeom* geom)
{
return geom->is_dynamic == false;
}
bool dxClusteredWorldAndSpace::isGeomBodyless(dxGeom* geom)
{
dSpaceID parentSpace = (dxSpace*)geom;
while (parentSpace != NULL)
{
if (parentSpace->body != NULL || parentSpace->is_dynamic)
return false;
parentSpace = parentSpace->parent_space;
}
if (geom->type >= dSimpleSpaceClass)
{
for (dxGeom* geom2 = ((dxSpace*)geom)->first; geom2; geom2=geom2->next)
if (geom2->body != NULL || geom2->is_dynamic)
return false;
}
return true;
}
void dxClusteredWorldAndSpace::flagDynamicGeoms(dSpaceID _space)
{
for (dxGeom* geom=_space->first; geom; geom=geom->next)
{
if (geom->is_dynamic == false)
geom->is_dynamic = !isGeomBodyless(geom);
if (geom->type >= dSimpleSpaceClass)
flagDynamicGeoms((dxSpace*)geom);
}
}
dxGeom *dxClusteredWorldAndSpace::retrieveBodySpaceAndFlagInnerGeoms(dxBody *body)
{
if (body == NULL || body->geom == NULL)
return NULL;
// retrieve upper space containing all body's geoms
// and mark geometries contained in the space so that no additional
// dxClusterAABB is created for them
dxGeom *geom = body->geom;
dxGeom *space = geom->parent_space;
dxGeom *upper_geom = geom; // in case of a simple body with geom no upper space exists
// other than the whole scene space
while (space)
{
space->tag = true;
dxGeom *parent_space = space->parent_space;
if (parent_space != NULL && parent_space->parent_space == NULL)
{
// the upper geom associated with the current body is found
// parent_space represents the whole scene space
upper_geom = space;
break;
}
space = parent_space;
}
while (geom)
{
geom->tag = true;
geom = geom->body_next;
}
return upper_geom;
}
void dxClusteredWorldAndSpace::createAABB(dxBody *body, dxGeom *geom, dxClusterAABB *&_firstaabb, dxClusterAABB *&_bigboxes, bool isbigbox)
{
dxGeom *body_geom = geom;
if (body)
{
body_geom = retrieveBodySpaceAndFlagInnerGeoms(body);
if (body_geom == NULL)
body_geom = geom;
}
// if geom is superspace, split into its child geoms and create aabb for each.
else if (geom && isGeomStatic(geom) && geom->type >= dSimpleSpaceClass)
{
ODE_PRINT("Subspace count: %d with body %p (bigbox: %d)\n", ((dxSpace*)geom)->count, body, isbigbox);
for (dxGeom* geom2 = ((dxSpace*)geom)->first; geom2; geom2 = geom2->next)
{
ODE_PRINT(" Subspace geom: %p with body %p\n", geom2, geom2->body);
createAABB(geom2->body, geom2, _firstaabb, _bigboxes, isbigbox);
}
return;
}
dxClusterAABB *aabb = (dxClusterAABB*) ALLOCA (sizeof(dxClusterAABB));
aabb->geom = body_geom;
aabb->body = body;
aabb->cluster = NULL;
aabb->clusterID = -1;
aabb->next = NULL;
aabb->tracker = -1;
// if geometry is static, put in static objects list
if (body_geom && isGeomBig(body_geom))
{
// do nothing, this geom will not be clustered
aabb->next = _bigboxes;
_bigboxes = aabb;
bigboxCount++;
}
// if geometry is not subspace, put it in dynamic object list
else
{
// aabb goes in main list
aabb->next = _firstaabb;
_firstaabb = aabb;
aabb->level = 0;
aabb->cellsize = (dReal) ldexp (gridstep, aabb->level);
// discretize AABB position to cell size
if (body_geom)
{
for (int i = 0; i < 6; ++i)
aabb->dbounds[i] = (int) 1.0f * floorf ((body_geom->aabb[i] - hsAxis[i/2]) / aabb->cellsize);
setMinMax(body_geom->aabb);
}
aabb->index = algoN++;
}
}
void dxClusteredWorldAndSpace::updateAABBs(dxClusterAABB *_dynamicList, dxClusterAABB *_staticList)
{
xmin = 999; xmax = -999; ymin = 999; ymax = -999; zmin = 999; zmax = -999;
xsizemin = 999; xsizemax = -999; ysizemin = 999; ysizemax = -999; zsizemin = 999; zsizemax = -999;
xsizeavg = 0.0f; ysizeavg = 0.0f; zsizeavg = 0.0f;
for (dxClusterAABB *aabb=_dynamicList; aabb; aabb = aabb->next)
{
if (aabb->body) aabb->geom = retrieveBodySpaceAndFlagInnerGeoms(aabb->body);
dxGeom *geom = aabb->geom;
if (geom == NULL)
continue;
dUASSERT(geom->parent_space != NULL, "null space found");
// discretize AABB position to cell size
for (int i = 0; i < 6; ++i)
aabb->dbounds[i] = (int) 1.0f * floorf ((geom->aabb[i] - hsAxis[i/2]) / gridstep);
setMinMax(geom->aabb);
}
}
void dxClusteredWorldAndSpace::initAABBs(dxWorld *_world, dxSpace *_space, dxClusterAABB *&_dynamicList, dxClusterAABB *&_staticList)
{
xmin = 999; xmax = -999; ymin = 999; ymax = -999; zmin = 999; zmax = -999;
xsizemin = 999; xsizemax = -999; ysizemin = 999; ysizemax = -999; zsizemin = 999; zsizemax = -999;
xsizeavg = 0.0f; ysizeavg = 0.0f; zsizeavg = 0.0f;
algoN = 0;
for (dxBody *body = _world->firstbody; body; body = (dxBody*) body->next)
{
dxGeom *geom = body->geom;
if (geom) geom->tag = false;
}
for (dxGeom *geom = _space->first; geom; geom = (dxGeom*) geom->next)
{
geom->tag = false;
}
ODE_PRINT("Processing world with %d bodies and space with %d geoms\n", _world->nb, _space->count);
// First, go through all the bodies in the world and create bounding box information
for (dxBody *body = _world->firstbody; body; body = (dxBody*) body->next)
{
dxGeom* geom = body->geom;
if (geom) dUASSERT(geom->parent_space != NULL, "null space found");
if (geom && (geom->tag == true))
continue;
if (geom) geom->tag = true;
createAABB(body, geom, _dynamicList, _staticList, false);
}
bigboxCount = 0;
// Then, go through all the geometries in the space and create bounding box information
for (dxGeom *geom = _space->first; geom; geom = (dxGeom*) geom->next)
{
dUASSERT(geom->parent_space != NULL, "null space found");
if (geom->tag == true)
{
ODE_PRINT("continue: %d\n", geom->type);
continue;
}
ODE_PRINT("type: %d (%d)\n", geom->type, bigboxCount);
geom->tag = true;
createAABB(geom->body, geom, _dynamicList, _staticList, true);
}
ODE_PRINT("%d dynamic bodies, %d static bodies\n", algoN, bigboxCount);
}
void dxClusteredWorldAndSpace::calculateGridStep()
{
const dReal dx = xmax - xmin;
const dReal dy = ymax - ymin;
const dReal dz = zmax - zmin;
gridstep = util_MT::odeMax(dx, dy, dz) / gridsize;
if (gridstep < 0) gridstep *= - 1;
ODE_INFO("Gridstep value: %f\n", gridstep);
hsAxis[0] = (xmax + xmin) / 2.0f;
hsAxis[1] = (ymax + ymin) / 2.0f;
hsAxis[2] = (zmax + zmin) / 2.0f;
const dReal halfInvGridStep = 0.5 / gridstep;
xsteps = 2 * ceilf(dx * halfInvGridStep) + 3;
ysteps = 2 * ceilf(dy * halfInvGridStep) + 3;
zsteps = 2 * ceilf(dz * halfInvGridStep) + 3;
if (oldN != algoN || tested == NULL)
{
DEALLOCA(tested);
// for `n' objects, an n*n array of bits is used to record if those objects
// have been intersection-tested against each other yet. this array can
// grow large with high n, but oh well...
tested_rowsize = (algoN + 7) >> 3; // number of bytes needed for n bits
tested = (unsigned char *) ALLOCA (algoN * tested_rowsize);
}
memset (tested, 0, algoN * tested_rowsize);
oldN = algoN;
const int newHashSpaceSize = (xsteps + 1) * (ysteps + 1) * (zsteps + 1);
// create a hash table to store all AABBs. each AABB may take up to 8 cells.
// we use chaining to resolve collisions, but we use a relatively large table
// to reduce the chance of collisions.
// compute hash table size sz to be a prime > xsteps*ysteps*zsteps
if (oldHashSpaceSize != newHashSpaceSize || table == NULL)
{
ODE_INFO("Creating new table... %d to %d\n", oldHashSpaceSize > 0 ? oldHashSpaceSize : 1, newHashSpaceSize > 0 ? newHashSpaceSize : 1);
if (table != NULL)
{
cleanupTable(table);
}
sz = newHashSpaceSize > 0 ? newHashSpaceSize : 1; // the size is negative iff the there is no dGeoms
// allocate and initialize hash table node pointers
table = (dxClusterNode **) ALLOCA (sizeof(dxClusterNode*) * sz);
for (int i = 0; i < sz; ++i) table[i] = NULL;
oldHashSpaceSize = newHashSpaceSize;
}
}
void dxClusteredWorldAndSpace::makeClusters()
{
calculateGridStep();
dxClusterAABB *aabb;
// create a list of auxiliary information for all geom axis aligned bounding
// boxes. set the level for all AABBs. put AABBs larger than the space's
// global_maxlevel in the big_boxes list, check everything else against
// that list at the end. for AABBs that are not too big, record the maximum
// level that we need.
ODE_PRINT("before: %d, %d\n", originalWorld->nb, originalSpace->count);
// we need to tag nodes in table as free
for (int i = 0; i < sz; ++i)
if (table[i])
{
table[i]->nextFreeNode = table[i];
table[i]->count = 0;
table[i]->tagged = false;
}
clusterCount = 0;
int tableCount = 0;
int firstaabbCount = 0;
int oldNodeCount = 0, newNodeCount = 0;
// add each AABB to the hash table (may need to add it to up to 8 cells)
for (aabb = first_aabb; aabb; aabb = aabb->next) {
++firstaabbCount;
ClusterNode *head = NULL;
ClusterNode *tail = NULL;
bool bIsGeomStatic = false;
if (aabb->body == NULL && aabb->geom) bIsGeomStatic = isGeomStatic(aabb->geom);
// we need to recalculate bounding volumes since objects have moved and average position has changed
if (aabb->geom)
for (int i = 0; i < 6; ++i)
aabb->dbounds[i] = (float) 1.0f * floorf ((aabb->geom->aabb[i] - hsAxis[i/2]) / gridstep);
else
for (int i = 0; i < 6; ++i) aabb->dbounds[i] = 0;
const int *dbounds = aabb->dbounds;
for (int xi = dbounds[0]; (xi) <= (dbounds[1]); ++xi) {
for (int yi = dbounds[2]; (yi) <= (dbounds[3]); ++yi) {
for (int zi = dbounds[4]; (zi) <= (dbounds[5]); ++zi) {
// get the hash index
dVector3 pos = { (dReal)xi, (dReal)yi, (dReal)zi};
unsigned long hi = getVirtualAddress (pos) % sz;
++tableCount;
dxClusterNode *node = NULL;
// first check to see if we have a free node
if (table[hi] && table[hi]->nextFreeNode)
{
node = table[hi]->nextFreeNode;
table[hi]->nextFreeNode = node->next;
if (node->next) node->next->count = node->count + 1;
++oldNodeCount;
}
// add a new node to the hash table if required
else
{
node = (dxClusterNode*) ALLOCA (sizeof (dxClusterNode));
node->nextFreeNode = NULL;
if (table[hi]) node->count = table[hi]->count + 1;
else node->count = 1;
node->next = table[hi];
table[hi] = node;
++newNodeCount;
}
node->x = xi;
node->y = yi;
node->z = zi;
node->isStatic = bIsGeomStatic;
node->aabb = aabb;
node->tagged = false;
node->cluster = NULL;
node->space = NULL;
node->world = NULL;
if (bIsGeomStatic)
addClusterNodeToCluster(node, head, tail, false);
}
}
}
// if it was a static geom, add to cluster list
if (bIsGeomStatic)
{
clusterStaticTypes[clusterCount] = true;
clusterArray[clusterCount] = head;
if (aabb->geom)
staticGeomClusterIDMap[aabb->geom] = clusterCount;
clusterCount++;
for (int i=0; i<clusterCount; i++)
{
staticClusterLinks[clusterCount-1][i] = false;
staticClusterLinks[i][clusterCount-1] = false;
}
}
}
ODE_INFO("%d new nodes, %d old nodes\n", newNodeCount, oldNodeCount);
// Finally, separate clusters based on proximity of hashspace cells
// if 2 neighboring cells in the hashspace have objects inside,
// they belong to the same cluster. In this way, we only need to traverse
// the hashspace once and come with a list of clusters. Pretty fast.
int nodeCount = 0;
for (int i = 0; i < sz; ++i)
{
dxClusterNode *node = table[i];
if (node && node->isStatic==false && node->tagged == false && table[i]->nextFreeNode != table[i])
{
++nodeCount;
node->tagged = true;
ClusterNode *head = NULL;
ClusterNode *tail = NULL;
findNeighboringCluster(node, head, tail);
clusterStaticTypes[clusterCount] = false;
clusterArray[clusterCount] = head;
clusterCount++;
for (int i=0; i<clusterCount; i++)
{
staticClusterLinks[clusterCount-1][i] = false;
staticClusterLinks[i][clusterCount-1] = false;
}
}
}
#ifndef dNODEBUG
{
ODE_INFO("Geom count: %d\n", algoN);
ODE_INFO("Big box count: %d\n", bigboxCount);
ODE_INFO("Limits: (%f, %f), (%f, %f), (%f, %f)\n", xmin, xmax, ymin, ymax, zmin, zmax);
ODE_INFO("%d out of %d table additions\n", tableCount, sz);
ODE_IMPORTANT("dxClusterNode Count: %d\n", nodeCount);
ODE_IMPORTANT("gridstep: %f, sz: %d, Cluster Count: %d\n", gridstep, sz, clusterCount);
for (int i = 0; i < clusterCount; ++i)
{
ODE_INFO("Cluster %d: %d\n", i, clusterArray[i]->count);
}
}
#endif
}
void dxClusteredWorldAndSpace::attachBodyAndGeom(int &bodyCount, int &geomCount, dxBody *body, dxGeom *geom, dxWorld *oldWorld, dxSpace *oldSpace, dxWorld *newWorld, dxSpace *newSpace)
{
ODE_PRINT("--AttachBody&Geom (bodyCount=%d, geomCount=%d, body=%p, geom=%p, oldWorld=%p, oldSpace=%p, newWorld=%p, newSpace=%p)\n", bodyCount, geomCount, body, geom, oldWorld, oldSpace, newWorld, newSpace);
if (body) dUASSERT(body->world != NULL, "NULL world in body!");
if (body && oldWorld && body->world != newWorld) dUASSERT(body->world == oldWorld, "Body belongs to a different world than the one being removed!");
if (geom) dUASSERT(geom->parent_space != NULL, "NULL parent space in geom!");
if (body && newWorld && body->world != newWorld) dUASSERT(body != newWorld->firstbody, "Double insertion!");
if (geom) geom->tag = true;
if (body) body->mtTag = true;
if (oldWorld && oldWorld == newWorld)
{
ODE_PRINT("Returning because oldWorld and newWorld are the same\n");
return;
}
if (body && body->world != newWorld)
{
if (oldWorld == NULL) oldWorld = body->world;
if (newWorld == NULL) newWorld = body->old_world; //currentWorld;
removeObjectFromList(body);
addObjectToList(body, (dObject**) &newWorld->firstbody);
body->old_world = body->world;
body->world = newWorld;
newWorld->nb++;
oldWorld->nb--;
++bodyCount;
if (oldWorld->nb == 0) oldWorld->firstbody = NULL;
#ifndef dNODEBUG
dUASSERT(util_MT::findBodyCount(oldWorld) == oldWorld->nb, "Body count mismatch in world!" );
dUASSERT(util_MT::findBodyCount(newWorld) == newWorld->nb, "Body count mismatch in world!" );
#endif
}
if (oldSpace == NULL && newSpace == NULL) return;
dxGeom *g = geom;
if (oldSpace)
while (g && g->parent_space != oldSpace)
g = g->parent_space;
if (!g)
{
ODE_PRINT("returning bcz of null geom!\n\n");
return;
}
if (g->body) ODE_PRINT("Attach body 2 %p (%d) and geom %p (%d)\n", g->body, g->body->geom->tag, g, g->tag);
g->tag = true;
if (newSpace == NULL)
{
dUASSERT(g->old_space != NULL, "reverting to null space!");
dSpaceRemove(g->parent_space, g);
util_MT::addGeomToSpaceFunc(g->old_space, g);
++geomCount;
}
else if (g->parent_space != newSpace)
{
g->old_space = g->parent_space;
dSpaceRemove(g->parent_space, g);
util_MT::addGeomToSpaceFunc(newSpace, g);
++geomCount;
}
else
{
ODE_PRINT("not doin anything to geom!\n\n");
return;
}
}
void dxClusteredWorldAndSpace::attachJoint(int &jointCount, dxJoint *j, dxWorld *oldWorld, dxWorld *newWorld)
{
ODE_PRINT("Attaching joint %p from world %p to %p\n", j, oldWorld, newWorld);
if (oldWorld) dUASSERT(j->world == oldWorld, "the joint being reattached does not belong to the correct world!");
j->mtTag = true;
if (newWorld == NULL)
{
newWorld = j->old_world ? j->old_world : originalWorld;
}
// if already in correct world, abort
if (j->world == newWorld)
{
ODE_PRINT("returning bcz joint is already in the correct world\n");
return;
}
ODE_PRINT("World joint counts before: %d and %d\n", oldWorld->nj, newWorld->nj);
removeObjectFromList(j);
addObjectToList(j, (dObject**) &newWorld->firstjoint);
j->old_world = j->world;
j->world = newWorld;
newWorld->nj++;
oldWorld->nj--;
++jointCount;
if (oldWorld->nj == 0) oldWorld->firstjoint = 0;
ODE_PRINT("World joint counts after: %d and %d\n", oldWorld->nj, newWorld->nj);
}
void dxClusteredWorldAndSpace::reattachJoints(int &bodyCount, int &geomCount, int &jointCount, dxBody *body, dxGeom *geom, dxWorld *oldWorld, dxSpace *oldSpace, dxWorld *newWorld, dxSpace *newSpace, bool bTreatSpaces)
{
ODE_PRINT("-reattachjoints: bodyCount %d geomCount %d jointCount %d body %p, geom %p, oldWorld %p, newWorld %p, oldSpace %p, newSpace %p\n", bodyCount, geomCount, jointCount, body, geom, oldWorld, newWorld, oldSpace, newSpace);
if (geom) dUASSERT(geom->parent_space != NULL, "parent space null!");
bool bWorkToDo = false;
if ((body && body->mtTag == false) || (geom && geom->tag == false))
{
bWorkToDo = true;
}
if (!bWorkToDo)
{
ODE_PRINT("returning bcz no work to do\n");
return;
}
// if geometry is a subspace, add all of its children, but only update the body not the geom!
if (bTreatSpaces && geom && geom->type >= dSimpleSpaceClass)
{
ODE_PRINT("Processing subspace %p\n", geom);
dxSpace *gSpace = (dxSpace*) geom;
for (dxGeom *g = gSpace->first; g; g = (dxGeom*) g->next)
{
reattachJoints(bodyCount, geomCount, jointCount, g->body, g, oldWorld, oldSpace, newWorld, newSpace, bTreatSpaces);
}
}
// first transfer body and geometry
if (body && body->geom)
ODE_PRINT("Attach body 1 %p (%d) and geom %p (%d)\n", body, body->geom->tag, geom, geom->tag);
else if (body)
ODE_PRINT("Attach body 1 %p with no geom\n", body);
attachBodyAndGeom(bodyCount, geomCount, body, geom, oldWorld, oldSpace, newWorld, newSpace);
#ifndef dNODEBUG
if (oldWorld) dUASSERT(util_MT::findBodyCount(oldWorld) == oldWorld->nb, "Body count mismatch in world!" );
if (newWorld) {
dUASSERT(util_MT::findBodyCount(newWorld) == newWorld->nb, "Body count mismatch in world!" );
} else if (body){
dUASSERT(util_MT::findBodyCount(body->world) == body->world->nb, "Body count mismatch in world!" );
}
#endif
// then transfer all joints not connected to a tagged node
ODE_PRINT("Processing joints\n");
if (body) {
for (dxJointNode *j = body->firstjoint; j; j = j->next)
{
// attach the joint if the connected body is either null or not tagged
if (j->body == NULL || !j->body->geom || j->body->geom->tag == false)
{
dUASSERT(j->body != body, "self-joints allowed?");
attachJoint(jointCount, j->joint, j->joint->world, newWorld);
#ifndef dNODEBUG
if (oldWorld) dUASSERT(util_MT::findJointCount(oldWorld) == oldWorld->nj, "Joint count mismatch in world!" );
if (newWorld) {
dUASSERT(util_MT::findJointCount(newWorld) == newWorld->nj, "Joint count mismatch in world!" );
} else {
dUASSERT(util_MT::findJointCount(j->joint->world) == j->joint->world->nj, "Joint count mismatch in world!" );
}
#endif
dUASSERT(j->body != body, "self-joints allowed?");
}
}
}
ODE_PRINT("Processing connected bodies\n");
// finally transfer all connected bodies which are not tagged
if (body) {
for (dxJointNode *j = body->firstjoint; j; j = j->next)
{
// recurse through the joint if the connected body has either no geometry or its geometry is not tagged
dxBody *connectedBody = j->body;
if (connectedBody == NULL || connectedBody->mtTag)
{
ODE_PRINT("Not processing connected body bcz already processed\n");
continue;
}
if (!connectedBody->geom || connectedBody->geom->tag == false)
{
dUASSERT(connectedBody != body, "self-joints allowed?");
reattachJoints(bodyCount, geomCount, jointCount, connectedBody, connectedBody->geom, oldWorld, oldSpace, newWorld, newSpace, bTreatSpaces);
dUASSERT(j->body != body, "self-joints allowed?");
}
}
}
}
// Note: this function is possibly called in a multithread way
dxGeom* dxClusteredWorldAndSpace::duplicateBodyAndGeom(int &bodyCount, int &geomCount, dxBody* body, dxGeom* geom, dxWorld *oldWorld, dxSpace *oldSpace, dxWorld *newWorld, dxSpace *newSpace, int kid)
{
ODE_PRINT("Duplicating body %p and geom %p\n", body, geom);
dxGeom* newGeom = 0x0;
if (geom != 0x0)
{
switch(geom->type)
{
case dSphereClass:
{
newGeom = (dxSphere*)ALLOCA(sizeof(dxSphere));
memcpy((void*)newGeom, (void*)geom, sizeof(dxSphere));
break;
}
case dBoxClass:
{
newGeom = (dxBox*)ALLOCA(sizeof(dxBox));
memcpy((void*)newGeom, (void*)geom, sizeof(dxBox));
break;
}
case dCapsuleClass:
{
newGeom = (dxCapsule*)ALLOCA(sizeof(dxCapsule));
memcpy((void*)newGeom, (void*)geom, sizeof(dxCapsule));
break;
}
case dCylinderClass:
{
newGeom = (dxCylinder*)ALLOCA(sizeof(dxCylinder));
memcpy((void*)newGeom, (void*)geom, sizeof(dxCylinder));
break;
}
case dPlaneClass:
{
newGeom = (dxPlane*)ALLOCA(sizeof(dxPlane));
memcpy((void*)newGeom, (void*)geom, sizeof(dxPlane));
break;
}
case dRayClass:
{
newGeom = (dxRay*)ALLOCA(sizeof(dxRay));
memcpy((void*)newGeom, (void*)geom, sizeof(dxRay));
break;
}
case dConvexClass:
{
break;
}
case dGeomTransformClass:
{
newGeom = (dxGeomTransform*)ALLOCA(sizeof(dxGeomTransform));
memcpy((void*)newGeom, (void*)geom, sizeof(dxGeomTransform));
dxGeom* obj = ((dxGeomTransform*)geom)->obj;
((dxGeomTransform*)newGeom)->obj = duplicateBodyAndGeom(bodyCount, geomCount, obj->body, obj, oldWorld, oldSpace, newWorld, newSpace, kid);
break;
}
case dTriMeshClass:
{
newGeom = (dxTriMesh*)ALLOCA(sizeof(dxTriMesh));
memcpy((void*)newGeom, (void*)geom, sizeof(dxTriMesh));
break;
}
case dHeightfieldClass:
{
newGeom = (dxHeightfield*)ALLOCA(sizeof(dxHeightfield));
memcpy((void*)newGeom, (void*)geom, sizeof(dxHeightfield));
((dxHeightfield*)newGeom)->resetBufferPointers();
break;
}
default:
{
ODE_PRINT("Duplicating superspace\n");
}
}
newGeom->parent_space = 0x0;
newGeom->next = 0x0;
if (geom->parent_space != 0x0)
{
util_MT::addGeomToSpaceFunc(newSpace, newGeom);
pthread_mutex_lock(&geomDuplicationMapMutex);
geomDuplicationMap[kid][geom] = newGeom;
pthread_mutex_unlock(&geomDuplicationMapMutex);
}
// transform geom class case:
// we should also store the map transformed child -> copied children
else if (geom->parent_geom) {
pthread_mutex_lock(&geomDuplicationMapMutex);
geomDuplicationMap[kid][geom] = newGeom;
pthread_mutex_unlock(&geomDuplicationMapMutex);
}
}
return newGeom;
}
void dxClusteredWorldAndSpace::duplicateJoint(int &jointCount, dxJoint *j, dxWorld *oldWorld, dxWorld *newWorld)
{
ODE_PRINT("Duplicating joint %p\n", j);
}
// Note: this function is possibly called in a multithread way
void dxClusteredWorldAndSpace::duplicateBodiesAndGeoms(int &bodyCount, int &geomCount, int &jointCount, dxBody* body, dxGeom* geom, dxWorld *oldWorld, dxSpace *oldSpace, dxWorld *newWorld, dxSpace *newSpace, int kid)
{
ODE_PRINT("-duplicateBodiesAndGeoms: bodyCount %d geomCount %d jointCount %d body %p, geom %p, oldWorld %p, newWorld %p, oldSpace %p, newSpace %p\n", bodyCount, geomCount, jointCount, body, geom, oldWorld, newWorld, oldSpace, newSpace);
if (geom) dUASSERT(geom->parent_space != NULL, "parent space null!");
bool bWorkToDo = false;
if ((body && body->mtTag == false) || (geom && geom->tag == false))
{
bWorkToDo = true;
}
if (!bWorkToDo)
{
return;
}
// first transfer body and geometry
duplicateBodyAndGeom(bodyCount, geomCount, body, geom, oldWorld, oldSpace, newWorld, newSpace, kid);
// then transfer all joints not connected to a tagged node
if (body) {
for (dxJointNode *j = body->firstjoint; j; j = j->next)
{
// attach the joint if the connected body is either null or not tagged
if (j->body == NULL || !j->body->geom || j->body->geom->tag == false)
{
dUASSERT(j->body != body, "self-joints allowed?");
duplicateJoint(jointCount, j->joint, j->joint->world, newWorld);
dUASSERT(j->body != body, "self-joints allowed?");
}
}
}
}
void dxClusteredWorldAndSpace::recombineClusters()
{
for (int i=0; i<clusterCount && worlds[i]; i++)
util_MT::cleanTags(worlds[i], this);
// After the clusters are made, we separate the objects into different worlds, one per thread
for (int k = 0; k < clusterCount; ++k)
{
for (dxClusterNode *node = clusterAABBs[k]; node; node = (dxClusterNode*) node->next)
{
if (!node->aabb->geom || node->aabb->geom->tag == false)
{
#ifndef dNODEBUG
if (node->aabb->body)
{
for (dxJointNode *j = node->aabb->body->firstjoint; j; j = j->next)
{
dUASSERT(j->joint->world == node->aabb->body->world, "fishy business going with joints and body worlds");
if (j->body) dUASSERT(j->joint->world == j->body->world, "fishy business going with joints and body worlds");
}
}
#endif
dxWorld *nodeWorld = NULL;
if (node->aabb->body) nodeWorld = worlds[k];
dxSpace *nodeSpace = 0x0;
if (node->aabb->geom) nodeSpace = spaces[k];
int bCount = 0, gCount = 0, jCount = 0;
reattachJoints(bCount, gCount, jCount, node->aabb->body, node->aabb->geom, nodeWorld, nodeSpace, originalWorld, originalSpace, false);
ODE_INFO("%d bodies, %d geoms and %d joints reclaimed from cluster %d\n", bCount, gCount, jCount, k);
#ifndef dNODEBUG
if (nodeWorld) checkWorld(nodeWorld);
#endif
}
}
}
#ifdef TEST_COLLISIONS
// Reclaim back static geometries
for (int i = 0; i < threadCount; ++i)
{
dxGeom *g2;
for (dxGeom *g = currentClusterSpace->spaces[i]->first; g; g = g2)
{
g2 = g->next;
g->old_space = g->parent_space;
dSpaceRemove(g->parent_space, g);
addGeomToSpaceFunc(currentClusterSpace->originalSpace, g);
}
}
#endif
cleanupMemory();
clusterCount = 0;
activeClusterCount = 0;
}
// Note: this function is possibly called in a multithread way
bool dxClusteredWorldAndSpace::updateClusterAABBsAndTable(int kid)
{
// create cluster table if it doesnt already exist
if (clusterTables[kid] == NULL)
{
// allocate and initialize hash table node pointers
clusterTables[kid] = (dxClusterNode **) ALLOCA (sizeof(dxClusterNode*) * sz);
for (int i = 0; i < sz; i++) clusterTables[kid][i] = 0;
}
// else, reset free node pointers
else
{
// we need to tag nodes in table as free
for (int i = 0; i < sz; ++i)
if (clusterTables[kid][i])
{
clusterTables[kid][i]->nextFreeNode = clusterTables[kid][i];
clusterTables[kid][i]->tagged = false;
}
}
// then go through each cluster AABB and update dbounds and table
int tableCount = 0, newNodeCount = 0, oldNodeCount = 0;
int updateCount = 0;
for (dxClusterNode *node = clusterAABBs[kid]; node; node = node->next)
{
dxClusterAABB *aabb = node->aabb;
dxBody *body = aabb->body;
dxGeom *geom = aabb->geom;
dxJointNode* joint = NULL;
// if aabb does not contain geom, get geom from body
if (geom == NULL && body)
geom = body->geom;
// if we still(!) don't have a geom, we traverse the joints
// through jointnodes instead of bodies
if (body)
joint = body->firstjoint;
while (geom == NULL && joint)
{
body = joint->body;
if (body)
geom = body->geom;
joint = joint->next;
}
updateCount++;
// if geom was found, use absolute position of geom to update node aabb
if (geom) // discretize AABB position to cell size
for (int i = 0; i < 6; ++i)
aabb->dbounds[i] = (int) 1.0f * floorf ((geom->aabb[i] - hsAxis[i/2])/gridstep);
// else if no geom was found, we have a case of a geomless body possibly connected to other geomless bodies
// this is a special case, and we use the position of the body here
// WARNING: Not a generally good idea. Why?
// Because body positions are not final, theyre used as offsets to geom positions, which are final.
// EXAMPLE: Consider a robot with many geoms and bodies connected to each other
// They also connect one geomless body. Now, when this robot moves, all geoms and bodies might move coherently
// except the one body which is geomless. Using the body position now will split the robot cluster into 2 clusters
// and we have a constant hysterics where the robot cluster is declustered every frame based on proximity
// and reclustered the next frame (because of the joint connecting the geomless body).
// TODO: Find a proper way to handle geomless bodies
else
for (int i = 0; i < 6; ++i)
aabb->dbounds[i] = (int) 1.0f * floorf ((aabb->body->posr.pos[i%3] - hsAxis[i/2])/gridstep);
int *dbounds = aabb->dbounds;
for (int xi = dbounds[0]; (xi) <= (dbounds[1]); xi += 1) {
for (int yi = dbounds[2]; (yi) <= (dbounds[3]); yi += 1) {
for (int zi = dbounds[4]; (zi) <= (dbounds[5]); zi += 1) {
// get the hash index
dVector3 pos = { (dReal)xi, (dReal)yi, (dReal)zi};
unsigned long hi = getVirtualAddress (pos) % sz;
if (bCalculateNewSZ == true)
ODE_PRINT("SCENE SIZE CHANGED! Aborting current frame\n");
tableCount++;
dxClusterNode *node2 = NULL;
// first check to see if we have a free node
if (clusterTables[kid][hi] && clusterTables[kid][hi]->nextFreeNode)
{
node2 = clusterTables[kid][hi]->nextFreeNode;
clusterTables[kid][hi]->nextFreeNode = node2->next;
oldNodeCount++;
}
else
{
ODE_PRINT("%d Adding new clusternode to cluster %d\n", newNodeCount, kid);
node2 = (dxClusterNode*) ALLOCA (sizeof (dxClusterNode));
node2->nextFreeNode = NULL;
if (clusterTables[kid][hi]) node2->count = clusterTables[kid][hi]->count + 1;
else node2->count = 1;
node2->next = clusterTables[kid][hi];
clusterTables[kid][hi] = node2;
newNodeCount++;
}
node2->x = xi;
node2->y = yi;
node2->z = zi;
node2->aabb = aabb;
node2->tagged = false;
node2->cluster = NULL;
node2->space = NULL;
node2->world = NULL;
}
}
}
}
ODE_PRINT("%d geoms updated\n", updateCount);
ODE_PRINT("%d table additions\n", tableCount);
return bCalculateNewSZ;
}
void dxClusteredWorldAndSpace::recalculateActiveClusters()
{
activeClusterCount = 0;
for (int k = 0; k < clusterCount; ++k)
{
if (clusterAABBs[k] && clusterStaticTypes[k] == false)
{
activeClusters[activeClusterCount++] = k;
}
}
ODE_INFO("Recalculated cluster count to %d\n", activeClusterCount);
}
void dxClusteredWorldAndSpace::transferNodeBetweenClusters(dxClusterNode *node, int oldClusterID, int newClusterID, bool bRefreshActiveClusters)
{
ODE_PRINT("Transferring node %p from cluster %d to cluster %d\n", node, oldClusterID, newClusterID);
dxClusterAABB *aabb = node->aabb;
dxClusterNode *nodeToBeTransferred;
if (node->aabb->body) dUASSERT(node->aabb->body->world == worlds[newClusterID], "Transferring node which is in wrong world");
// if node is first in list, remove and update head
if (node->aabb->node == NULL)
{
nodeToBeTransferred = clusterAABBs[oldClusterID];
ODE_PRINT("removing head of list\n");
dUASSERT(node->aabb == clusterAABBs[oldClusterID]->aabb, "node expected to be head of cluster list.");
clusterAABBs[oldClusterID] = nodeToBeTransferred->next;
if (clusterAABBs[oldClusterID]) clusterAABBs[oldClusterID]->aabb->node = NULL;
else
{
// first off, clear the cluster table
if (clusterTables[oldClusterID]) {
for (int i = 0; i < sz; ++i)
{
dxClusterNode* node = clusterTables[oldClusterID][i];
dxClusterNode* temp;
while (node)
{
temp = node->next;
DEALLOCA(node);
node = temp;
}
clusterTables[oldClusterID][i] = 0x0;
}
}
// we have lost a cluster
ODE_PRINT("Removing cluster %d completely\n", oldClusterID);
deactivatedClusters[deactivatedClusterCount++] = oldClusterID;
if (bRefreshActiveClusters)
{
recalculateActiveClusters();
clusterChangeCallback();
}
}
}
// node not head of list, simply remove
else
{
dxClusterNode *previousNode = node->aabb->node;
nodeToBeTransferred = previousNode->next;
previousNode->next = nodeToBeTransferred->next;
if (previousNode->next) previousNode->next->aabb->node = previousNode;
}
aabb->clusterID = newClusterID;
nodeToBeTransferred->aabb->node = NULL;
// update parent node for AABB. used for crossover clustering
if (clusterAABBs[newClusterID]) {
clusterAABBs[newClusterID]->aabb->node = nodeToBeTransferred;
nodeToBeTransferred->count = clusterAABBs[newClusterID]->count + 1;
} else
nodeToBeTransferred->count = 1;
nodeToBeTransferred->next = clusterAABBs[newClusterID];
clusterAABBs[newClusterID] = nodeToBeTransferred;
}
// Note: this function is possibly called in a multithread way
void dxClusteredWorldAndSpace::crossOver(int smallerCluster, int biggerCluster, int cellID)
{
ODE_INFO("Crossover at cell %d between cluster %d and cluster %d\n", cellID, smallerCluster, biggerCluster);
if (clusterAABBs[biggerCluster] == NULL)
{
ODE_PRINT("returning because of empty cluster\n");
return;
}
// only update hashspace data if both clusters are dynamic
bool bTransferNodeBetweenClusters = false;
if (clusterStaticTypes[smallerCluster] == false && clusterStaticTypes[biggerCluster] == false)
bTransferNodeBetweenClusters = true;
else if (clusterStaticTypes[smallerCluster] == false && clusterStaticTypes[biggerCluster] == true)
// if both clusters are dynamic, smallerCluster has fewer objects
// else if one or both clusters are static, smallerCluster must be the static one.
{
ODE_PRINT("Switching small and big clusters\n");
int temp = smallerCluster;
smallerCluster = biggerCluster;
biggerCluster = temp;
}
// first off, remove AABB from old cluster and add to new one
for (dxClusterNode *node = clusterTables[smallerCluster][cellID]; node && node != clusterTables[smallerCluster][cellID]->nextFreeNode; node = node->next)
{
dxClusterAABB *aabb = node->aabb;
// Make sure node hasnt already transferred. if not, crossover
if (aabb->clusterID == biggerCluster || aabb->clusterID != smallerCluster)
{
ODE_PRINT("Continuing because node is already transferred\n");
continue;
}
//ODE_PRINT("-Crossing over geom %p (type %d) body %p from space %p to %p\n", aabb->geom, aabb->geom->type, aabb->body, aabb->geom->parent_space, newSpace);
util_MT::cleanTags(worlds[smallerCluster], this);
util_MT::cleanTags(worlds[biggerCluster], this);
// only if both clusters are dynamic do we transfer bodies/geoms between worlds/spaces
// if one of the clusters is static, we duplicate this static world/space in the dynamic cluster
int bCount = 0, gCount = 0, jCount = 0;
if (bTransferNodeBetweenClusters)
{
ODE_INFO("moving geom %p from cluster %d to cluster %d\n", aabb->geom, smallerCluster, biggerCluster);
// last parameter (treatSpaces) flag is true here since the joining of clusters might be
// triggered by a low-level geom we therefore need to transfer the whole hierarchy.
reattachJoints(bCount, gCount, jCount, aabb->body, aabb->geom, worlds[smallerCluster], spaces[smallerCluster], worlds[biggerCluster], spaces[biggerCluster], true);
ODE_INFO("%d bodies, %d geoms, %d joints transferred from cluster %d to %d\n", bCount, gCount, jCount, smallerCluster, biggerCluster);
if (aabb->body) dUASSERT(worlds[biggerCluster] == aabb->body->world, "unsuccessful reattachjoints");
checkWorld(worlds[smallerCluster]);
checkWorld(worlds[biggerCluster]);
if (bCount > 0 || gCount > 0)
transferNodeBetweenClusters(node, smallerCluster, biggerCluster);
} else
{
ODE_INFO("duplicating geom %p from cluster %d to cluster %d\n", aabb->geom, smallerCluster, biggerCluster);
duplicateBodiesAndGeoms(bCount, gCount, jCount, aabb->body, aabb->geom, worlds[smallerCluster], spaces[smallerCluster], worlds[biggerCluster], spaces[biggerCluster], biggerCluster);
ODE_INFO("%d bodies changed worlds, %d geoms changed spaces, %d joints changed worlds\n", bCount, gCount, jCount);
}
if (bTransferNodeBetweenClusters)
{
// connected bodies will have changed worlds, we need to crossover these too
dxClusterNode *node2 = clusterAABBs[smallerCluster];
while (node2)
{
dxClusterNode *temp = node2->next;
//if (node2->aabb->geom->parent_space == spaces[biggerCluster])
if ((node2->aabb->body && node2->aabb->body->world == worlds[biggerCluster]) ||
(node2->aabb->geom && node2->aabb->geom->parent_space == spaces[biggerCluster]))
transferNodeBetweenClusters(node2, smallerCluster, biggerCluster);
node2 = temp;
}
}
if (clusterTables[smallerCluster][cellID] == 0) break;
}
}
void dxClusteredWorldAndSpace::checkHashSpaceConsistency()
{
if (bCalculateNewSZ)
{
ODE_PRINT("Calculating new sz...\n");
cleanupTable(table);
for (int k = 0; k < clusterCount; ++k)
cleanupTable(clusterTables[k]);
updateAABBs(first_aabb, big_boxes);
calculateGridStep();
for (int k = 0; k < clusterCount; ++k)
updateClusterAABBsAndTable(k);
ODE_PRINT("New sz: %d\n", sz);
bCalculateNewSZ = false;
}
}
// Note: this function is possibly called in a multithread way
void dxClusteredWorldAndSpace::crossOverClusters(int kid1, int kid2, int cellId)
{
ODE_INFO("\nCrossover between clusters %d (%d) and %d (%d) in cell %d\n", kid1, clusterTables[kid1][cellId]->count, kid2, clusterTables[kid2][cellId]->count, cellId);
int cellCount1 = clusterTables[kid1][cellId]->count;
if (clusterTables[kid1][cellId]->nextFreeNode) cellCount1 -= clusterTables[kid1][cellId]->nextFreeNode->count;
int cellCount2 = clusterTables[kid2][cellId]->count;
if (clusterTables[kid2][cellId]->nextFreeNode) cellCount2 -= clusterTables[kid2][cellId]->nextFreeNode->count;
// find bigger cell and merge the smaller cell with it
int smallerCluster, biggerCluster;
if (cellCount1 < cellCount2)
{
smallerCluster = kid1;
biggerCluster = kid2;
}
else
{
smallerCluster = kid2;
biggerCluster = kid1;
}
// only if one of the clusters atleast is dynamic, crossover
if (!clusterStaticTypes[smallerCluster] || !clusterStaticTypes[biggerCluster])
{
bool bCrossOver = true;
if (clusterAABBs[smallerCluster]->aabb->body && clusterAABBs[biggerCluster]->aabb->body &&
clusterAABBs[smallerCluster]->aabb->body->world == clusterAABBs[biggerCluster]->aabb->body->world)
bCrossOver = false;
if (clusterAABBs[smallerCluster]->aabb->geom && clusterAABBs[biggerCluster]->aabb->geom &&
clusterAABBs[smallerCluster]->aabb->geom->parent_space == clusterAABBs[biggerCluster]->aabb->geom->parent_space)
bCrossOver = false;
if (clusterStaticTypes[smallerCluster] == true && staticClusterLinks[smallerCluster][biggerCluster] == true)
bCrossOver = false;
if (clusterStaticTypes[biggerCluster] == true && staticClusterLinks[biggerCluster][smallerCluster] == true)
bCrossOver = false;
if (bCrossOver)
crossOver(smallerCluster, biggerCluster, cellId);
if (clusterStaticTypes[smallerCluster] == true)
staticClusterLinks[smallerCluster][biggerCluster] = true;
if (clusterStaticTypes[biggerCluster] == true)
staticClusterLinks[biggerCluster][smallerCluster] = true;
}
}
#include <vector>
// Note: this function is possibly called in a multithread way
void dxClusteredWorldAndSpace::checkClusterConsistency(int kid)
{
std::vector<int> collidingClusterIds;
int crossoverCount = 0;
// go through the dynamic cluster and check for possible crossover with static objects
int k = kid;
for (dxClusterNode* node=clusterAABBs[k]; node; node=node->next)
{
const int *dbounds = node->aabb->dbounds;
for (int xi = dbounds[0]; (xi) <= (dbounds[1]); ++xi) {
for (int yi = dbounds[2]; (yi) <= (dbounds[3]); ++yi) {
for (int zi = dbounds[4]; (zi) <= (dbounds[5]); ++zi) {
// get the hash index
dVector3 pos = { (dReal)xi, (dReal)yi, (dReal)zi};
unsigned long hi = getVirtualAddress (pos) % sz;
for (int j=0; j<clusterCount && j!=k; j++)
{
// if dynamic cluster or already duplicated, skip
if (clusterStaticTypes[j] == false) // || staticClusterLinks[j][k] == true)
continue;
if (clusterTables[j] && clusterTables[j][hi] && clusterTables[j][hi] != clusterTables[j][hi]->nextFreeNode)
{
collidingClusterIds.push_back(j);
if (clusterTables[k][hi] && staticClusterLinks[j][k] == false)
{
ODE_PRINT("static geom %p (cluster %d) being duplicated to dynamic cluster %d\n\n", node->aabb->geom, j, k);
crossOverClusters(j, k, hi);
}
}
}
}
}
}
}
crossoverCount = collidingClusterIds.size();
if (crossoverCount == 0)
return;
// see which static objects need to be removed
for (int j=0; j<clusterCount; j++)
{
// if static cluster is already linked in a previous frame, see if it is still linked in this frame
if (staticClusterLinks[j][k] == true)
{
int l;
for (l=0; l<crossoverCount; l++)
{
if (collidingClusterIds[l] == j)
break;
}
if (l==crossoverCount)
{
//ODE_PRINT("static cluster %d needs to be removed from dynamic cluster %d\n\n", j, k);
ODE_PRINT("static geom %p (cluster %d) being removed from dynamic cluster %d\n\n", geomDuplicationMap[k][clusterAABBs[j]->aabb->geom], j, k);
dSpaceRemove(spaces[k], geomDuplicationMap[k][clusterAABBs[j]->aabb->geom]);
staticClusterLinks[j][k] = false;
}
}
}
}
void dxClusteredWorldAndSpace::addTrackerToNode(int &bodyCount, int& geomCount, int& jointCount, int kid, int _xi, int _yi, int _zi, int tracker)
{
dVector3 _pos = { (dReal)_xi, (dReal)_yi, (dReal)_zi};
unsigned long _hi = getVirtualAddress(_pos) % sz;
if (clusterTables[kid][_hi] == NULL)
return;
for (dxClusterNode* node2=clusterTables[kid][_hi]; node2 && node2!=clusterTables[kid][_hi]->nextFreeNode; node2=node2->next)
{
if (node2->aabb->tracker != tracker)
{
node2->aabb->tracker = tracker;
bodyCount++;
const int *dbounds = node2->aabb->dbounds;
for (int xi = dbounds[0]; (xi) <= (dbounds[1]); ++xi) {
for (int yi = dbounds[2]; (yi) <= (dbounds[3]); ++yi) {
for (int zi = dbounds[4]; (zi) <= (dbounds[5]); ++zi) {
// get the hash index and color all aabbs in cell
addTrackerToNode(bodyCount, geomCount, jointCount, kid, xi, yi, zi, tracker);
addTrackerToNode(bodyCount, geomCount, jointCount, kid, xi + 1, yi, zi, tracker);
addTrackerToNode(bodyCount, geomCount, jointCount, kid, xi - 1, yi, zi, tracker);
addTrackerToNode(bodyCount, geomCount, jointCount, kid, xi, yi + 1, zi, tracker);
addTrackerToNode(bodyCount, geomCount, jointCount, kid, xi, yi - 1, zi, tracker);
addTrackerToNode(bodyCount, geomCount, jointCount, kid, xi, yi, zi + 1, tracker);
addTrackerToNode(bodyCount, geomCount, jointCount, kid, xi, yi, zi - 1, tracker);
}
}
}
}
}
}
void dxClusteredWorldAndSpace::checkDynamicClusterConsistencies()
{
ODE_PRINT("CheckDynamicClusters Start. calculateNewSz=%d\n", bCalculateNewSZ);
int bCount=0, gCount=0, jCount=0;
bool bCrossover = false;
tracker++;
int ccount = activeClusterCount;
// check crossover between all dynamic clusters
for (int i=0; i<ccount; i++)
{
int count=0;
int k = activeClusters[i];
std::map<dxGeom*, int> geomTags;
for (dxClusterNode* node=clusterAABBs[k]; node; node=node->next)
{
// color current node with tracker id
if (node->aabb->tracker != tracker)
{
//ODE_PRINT("node tracker: %d actual tracker: %d\n", node->aabb->tracker, tracker);
node->aabb->tracker = ++tracker;
if (++count > 1 && !bCrossover && !bCalculateNewSZ)
{
// shit just got real. we need to add remaining geom/bodies into new cluster
int newClusterID;
if (deactivatedClusterCount > 0)
newClusterID = deactivatedClusters[--deactivatedClusterCount];
else
newClusterID = clusterCount++;
clusterStaticTypes[newClusterID] = false;
for (int l=0; l<clusterCount; l++)
{
staticClusterLinks[newClusterID][l] = false;
staticClusterLinks[l][newClusterID] = false;
}
if (newClusterID == clusterCount-1)
{
createNewWorldAndSpace(worlds[newClusterID], spaces[newClusterID]);
} else
{
dUASSERT(clusterAABBs[newClusterID] == NULL, "Previously deactivated cluster AABBs not empty!\n");
dUASSERT(worlds[newClusterID]->nb == 0, "Previously deactivated cluster world not empty!\n");
dxGeom *g,*n;
for (g = spaces[newClusterID]->first; g; g=n) {
n = g->next;
dSpaceRemove(spaces[newClusterID], g);
}
}
for (dxClusterAABB* bigbox = big_boxes; bigbox; bigbox = bigbox->next)
duplicateBodyAndGeom(bCount, gCount, bigbox->body, bigbox->geom, originalWorld, originalSpace, worlds[newClusterID], spaces[newClusterID], newClusterID);
util_MT::cleanTags(worlds[k], this);
util_MT::cleanTags(worlds[newClusterID], this);
bCount = gCount = jCount = 0;
// last parameter (treatSpaces) flag is true here since the separation of clusters might be
// triggered by a low-level geom we therefore need to transfer the whole hierarchy.
reattachJoints(bCount, gCount, jCount, node->aabb->body, node->aabb->geom, worlds[k], spaces[k], worlds[newClusterID], spaces[newClusterID], true);
ODE_INFO("%p Dynamic Cluster Split: %d bodies, %d geoms and %d joints transferred from cluster %d to cluster %d...\n", node->aabb->geom, bCount, gCount, jCount, k, newClusterID);
if (bCount > 0 || gCount > 0)
transferNodeBetweenClusters(node, k, newClusterID, false);
dxClusterNode *node2 = clusterAABBs[k];
while (node2)
{
dxClusterNode *temp = node2->next;
if ((node2->aabb->body && node2->aabb->body->world == worlds[newClusterID]) ||
(node2->aabb->geom && node2->aabb->geom->parent_space == spaces[newClusterID]))
{
transferNodeBetweenClusters(node2, k, newClusterID, false);
}
node2 = temp;
}
updateClusterAABBsAndTable(newClusterID);
recalculateActiveClusters();
clusterChangeCallback();
}
}
const int *dbounds = node->aabb->dbounds;
for (int xi = dbounds[0]; (xi) <= (dbounds[1]); ++xi) {
for (int yi = dbounds[2]; (yi) <= (dbounds[3]); ++yi) {
for (int zi = dbounds[4]; (zi) <= (dbounds[5]); ++zi) {
// get the hash index
dVector3 pos = { (dReal)xi, (dReal)yi, (dReal)zi};
unsigned long hi = getVirtualAddress (pos) % sz;
addTrackerToNode(bCount, gCount, jCount, k, xi, yi, zi, tracker);
int crossoverCount = 0;
dxMaintainedArray<int> collidingClusterIds;
for (int j=i+1; j<ccount; j++)
{
int k2 = activeClusters[j];
if (clusterTables[k2] && clusterTables[k2][hi] && clusterTables[k2][hi] != clusterTables[k2][hi]->nextFreeNode)
{
ODE_PRINT("Adding %d at cell %ld with clusterTable %p to colliding cluster Ids\n", k2, hi, clusterTables[k2][hi]);
collidingClusterIds[crossoverCount++] = k2;
}
}
// go through all colliding clusters and combine pairwise
for (int j=0; j<crossoverCount; j++)
{
if (clusterTables[k][hi] && clusterTables[collidingClusterIds[j]][hi])
{
crossOverClusters(collidingClusterIds[j], k, hi);
bCrossover = true;
}
}
}
}
}
}
if (count > 1)
ODE_PRINT("kid: %d Tracker: %d count: %d\n", k, tracker, count);
}
}
void dxClusteredWorldAndSpace::update(bool bRefreshClusters)
{
if (bCalculateNewSZ == false)
checkDynamicClusterConsistencies();
checkHashSpaceConsistency();
if (bRefreshClusters || ((originalWorld->nb > 0) && clusterCount < 1))
{
cleanupMemory();
originalSpace->cleanGeoms();
flagDynamicGeoms(originalSpace);
initAABBs(originalWorld, originalSpace, first_aabb, big_boxes);
makeClusters();
assignClustersToWorlds();
recalculateActiveClusters();
clusterChangeCallback();
for (int k = 0; k < clusterCount; ++k)
{
updateClusterAABBsAndTable(k);
if (geomDuplicationMap.find(k) == geomDuplicationMap.end())
geomDuplicationMap[k] = *(new geomMap());
}
}
}
void dxClusteredWorldAndSpace::assignClustersToWorlds()
{
// First, turn off tags for all geoms, joints and bodies, so we can test for a 1-to-1 relationship between nodes and clusters
util_MT::cleanTags(originalWorld, this);
// After the clusters are made, we separate the objects into different worlds, one per thread
int kid;
int createdClusterCount = 0;
entityCount = 0;
for (kid = 0; kid < clusterCount; ++kid)
{
ODE_PRINT("Assigning new cluster to world %p and space %p...\n", worlds[kid], spaces[kid]);
int bCount = 0, gCount = 0, jCount = 0;
if (worlds[kid] == NULL && spaces[kid] == NULL) {
createNewWorldAndSpace(worlds[kid], spaces[kid]);
createdClusterCount++;
}
dUASSERT(worlds[kid] != NULL, "Newly created world is NULL!\n");
dUASSERT(spaces[kid] != NULL, "Newly created space is NULL!\n");
// if dynamic cluster, duplicate all planes into it first
if (clusterStaticTypes[kid] != true)
{
for (dxClusterAABB* bigbox = big_boxes; bigbox; bigbox = bigbox->next)
duplicateBodyAndGeom(bCount, gCount, bigbox->body, bigbox->geom, originalWorld, originalSpace, worlds[kid], spaces[kid], kid);
}
for (dxClusterNode *node = clusterAABBs[kid]; node; node = (dxClusterNode*) node->next)
{
if (!node->aabb->geom || node->aabb->geom->tag == false)
{
#ifndef dNODEBUG
if (node->aabb->body) {
for (dxJointNode *j = node->aabb->body->firstjoint; j; j = j->next)
{
if (node->aabb->body) dUASSERT(j->joint->world == node->aabb->body->world, "fishy business going with joints and body worlds");
if (j->body) dUASSERT(j->joint->world == j->body->world, "fishy business going with joints and body worlds");
}
}
#endif
if (clusterStaticTypes[kid] != true)
{
bCount = gCount = jCount = 0;
// edge case: a geomless connected body might have been assigned to this cluster
// its connected bodies might have been assigned to a different cluster
// in this case, this body is already transferred to the same cluster as its connected bodies
// we therefore need to check if the body hasn't already been processed before over here
if ((node->aabb->body && node->aabb->body->mtTag == false) || (node->aabb->geom && node->aabb->geom->tag == false))
reattachJoints(bCount, gCount, jCount, node->aabb->body, node->aabb->geom, originalWorld, originalSpace, worlds[kid], spaces[kid], false);
else
continue;
if (node->aabb->body) dUASSERT(node->aabb->body->world == worlds[kid], "Body not successfully inserted!\n");
if (node->aabb->geom) dUASSERT(node->aabb->geom->parent_space != originalSpace, "Geom not successfully inserted!\n");
ODE_INFO("%d bodies, %d geoms, %d joints were assigned to world/space %d\n", bCount, gCount, jCount, kid);
if (bCount > 0)
entityCount++;
#ifndef dNODEBUG
checkWorld(originalWorld);
checkWorld(worlds[kid]);
#endif
}
} else
ODE_PRINT("skipping cluster %d due to already tagged or nonexistant geom\n", kid);
}
}
clusterCount = activeClusterCount = createdClusterCount;
// bodies might have changed clusters due to joints. update
for (int kid = 0; kid < clusterCount; ++kid)
{
if (!clusterAABBs[kid] || clusterStaticTypes[kid])
continue;
dxClusterNode *node = clusterAABBs[kid];
while (node)
{
dxClusterNode *temp = node->next;
if (node->aabb->body && node->aabb->body->world != worlds[kid])
{
int newKID = getWorldClusterID(node->aabb->body->world);
transferNodeBetweenClusters(node, kid, newKID);
}
node = temp;
}
}
#ifdef TEST_COLLISIONS
{
// We assume the remaining geometries from the space are all static. They belong to all subspaces
dxGeom *g2;
if (clusterCount > 0)
for (dxGeom *g = currentClusterSpace->originalSpace->first; g; g = g2)
{
g2 = g->next;
g->old_space = g->parent_space;
dSpaceRemove(g->parent_space, g);
addGeomToSpaceFunc(currentClusterSpace->spaces[0], g);
}
}
#endif
}
int dxClusteredWorldAndSpace::getSpaceClusterID(dxSpace *_space)
{
for (int kid = 0; kid < clusterCount; ++kid)
{
if (spaces[kid] == _space)
{
return kid;
}
}
return 0;
}
int dxClusteredWorldAndSpace::getWorldClusterID(dxWorld *_world)
{
for (int kid = 0; kid < clusterCount; ++kid)
{
if (worlds[kid] == _world)
{
return kid;
}
}
return 0;
}
// Note: this function is possibly called in a multithread way
void dxClusteredWorldAndSpace::cleanTags()
{
for (int k = 0; k < clusterCount; ++k)
for (dxClusterNode *node = clusterAABBs[k]; node; node = node->next)
{
if (node->aabb->geom)
{
node->aabb->geom->tag = false;
if (node->aabb->geom->type >= dSimpleSpaceClass)
{
dxSpace *gSpace = (dxSpace*) node->aabb->geom;
for (dxGeom *g = gSpace->first; g; g = (dxGeom*) g->next)
{
g->tag = false;
if (g->body) {
g->body->mtTag = false;
for (dxJointNode *j = g->body->firstjoint; j; j = (dxJointNode*) j->next)
j->joint->mtTag = false;
}
}
}
}
if (node->aabb->body) {
if (node->aabb->body->geom)
node->aabb->body->geom->tag = false;
node->aabb->body->mtTag = false;
for (dxJointNode *j = node->aabb->body->firstjoint; j; j = (dxJointNode*) j->next)
j->joint->mtTag = false;
}
}
for (int i = 0; i < clusterCount; ++i)
{
if (worlds[i] == NULL)
continue;
for (dxBody *b = worlds[i]->firstbody; b; b = (dxBody*) b->next) {
b->mtTag = false;
if (b->geom) b->geom->tag = false;
}
for (dxJoint *j = worlds[i]->firstjoint; j; j = (dxJoint*) j->next)
{
if (j->node[0].body && j->node[0].body->geom) j->node[0].body->geom->tag = false;
if (j->node[1].body && j->node[1].body->geom) j->node[1].body->geom->tag = false;
}
}
}
dxClusteredWorldAndSpace::dxClusteredWorldAndSpace(clusterChangeCallbackFunc* callback)
{
static bool first_call = true;
if (first_call) {
pthread_mutex_init(&geomDuplicationMapMutex, NULL);
first_call = false;
}
clusterChangeCallback = callback;
table = NULL;
xmin = 999, xmax = -999, ymin = 999, ymax = -999, zmin = 999, zmax = -999;
xsizemin = 999, xsizemax = -999, ysizemin = 999, ysizemax = -999, zsizemin = 999, zsizemax = -999;
xsizeavg = 0.0f, ysizeavg = 0.0f, zsizeavg = 0.0f;
sz = 0;
algoN = 0;
entityCount = 0;
gridstep = 0.2f;
gridsize = 5.0f;
tested = NULL;
tracker = 0;
oldN = 0;
oldHashSpaceSize = 0;
clusterCount = 0;
activeClusterCount = 0;
deactivatedClusterCount = 0;
first_aabb = NULL; // list of AABBs in hash table
big_boxes = NULL; // list of AABBs too big for hash table
bigboxCount = 0;
bCalculateNewSZ = false;
for (int k=0; k<clusterCount; k++)
{
worlds[k] = NULL;
spaces[k] = NULL;
clusterAABBs[k] = NULL;
clusterTables[k] = NULL;
clusterArray[k] = NULL;
activeClusters[k] = 0;
}
}
dxClusteredWorldAndSpace::~dxClusteredWorldAndSpace()
{
}
void dxClusteredWorldAndSpace::propagateGeomPosition(dxGeom *g, dReal x, dReal y, dReal z, dGeomSetPositionFunction* _func)
{
for (int i=0; i<activeClusterCount; i++)
{
int k = activeClusters[i];
if (geomDuplicationMap[k][g])
_func(geomDuplicationMap[k][g], x, y, z);
}
updateClusterAABBsAndTable(staticGeomClusterIDMap[g]);
}
void dxClusteredWorldAndSpace::propagateGeomRotation(dxGeom *g, const dMatrix3 R, dGeomSetRotationFunction* _func)
{
for (int i=0; i<activeClusterCount; i++)
{
int k = activeClusters[i];
if (geomDuplicationMap[k][g])
_func(geomDuplicationMap[k][g], R);
}
updateClusterAABBsAndTable(staticGeomClusterIDMap[g]);
}
void dxClusteredWorldAndSpace::propagateGeomQuaternion(dxGeom *g, const dQuaternion quat, dGeomSetQuaternionFunction* _func)
{
for (int i=0; i<activeClusterCount; i++)
{
int k = activeClusters[i];
if (geomDuplicationMap[k][g])
_func(geomDuplicationMap[k][g], quat);
}
updateClusterAABBsAndTable(staticGeomClusterIDMap[g]);
}
void dxClusteredWorldAndSpace::propagateGeomTransformUpdate(dxGeom *g)
{
for (int i=0; i<activeClusterCount; i++)
{
int k = activeClusters[i];
if (geomDuplicationMap[k][g]) {
dGeomMoved(geomDuplicationMap[k][g]);
geomDuplicationMap[k][g]->recomputeAABB();
}
}
updateClusterAABBsAndTable(staticGeomClusterIDMap[g]);
}
void dxClusteredWorldAndSpace::propagateGeomBoxSetLengths(dxGeom *g, dReal lx, dReal ly, dReal lz, dGeomBoxSetLengthsFunction* _func)
{
for (int i=0; i<activeClusterCount; i++)
{
int k = activeClusters[i];
if (geomDuplicationMap[k][g])
_func(geomDuplicationMap[k][g], lx, ly, lz);
}
updateClusterAABBsAndTable(staticGeomClusterIDMap[g]);
}
void dxClusteredWorldAndSpace::propagateGeomCapsuleSetParams(dxGeom *g, dReal radius, dReal length, dGeomCapsuleSetParamsFunction* _func) {
for (int i=0; i<activeClusterCount; i++)
{
int k = activeClusters[i];
if (geomDuplicationMap[k][g])
_func(geomDuplicationMap[k][g], radius, length);
}
updateClusterAABBsAndTable(staticGeomClusterIDMap[g]);
}
void dxClusteredWorldAndSpace::propagateGeomCylinderSetParams(dxGeom *g, dReal radius, dReal length, dGeomCylinderSetParamsFunction* _func) {
for (int i=0; i<activeClusterCount; i++)
{
int k = activeClusters[i];
if (geomDuplicationMap[k][g])
_func(geomDuplicationMap[k][g], radius, length);
}
updateClusterAABBsAndTable(staticGeomClusterIDMap[g]);
}
void dxClusteredWorldAndSpace::propagateGeomTriMeshSetData(dxGeom *g, dTriMeshDataID data, dGeomTriMeshSetDataFunction* _func)
{
for (int i=0; i<activeClusterCount; i++)
{
int k = activeClusters[i];
if (geomDuplicationMap[k][g])
_func(geomDuplicationMap[k][g], data);
}
updateClusterAABBsAndTable(staticGeomClusterIDMap[g]);
}
void dxClusteredWorldAndSpace::propagateGeomSphereSetRadius(dxGeom *g, dReal radius, dGeomSphereSetRadiusFunction* _func) {
for (int i=0; i<activeClusterCount; i++)
{
int k = activeClusters[i];
if (geomDuplicationMap[k][g])
_func(geomDuplicationMap[k][g], radius);
}
updateClusterAABBsAndTable(staticGeomClusterIDMap[g]);
}
void dxClusteredWorldAndSpace::propagatePlaneParams(dxGeom *g, dReal a, dReal b, dReal c, dReal d, dGeomPlaneSetParamsFunction *_func)
{
for (int i=0; i<activeClusterCount; i++)
{
int k = activeClusters[i];
if (geomDuplicationMap[k][g])
_func(geomDuplicationMap[k][g], a, b, c, d);
}
updateClusterAABBsAndTable(staticGeomClusterIDMap[g]);
}
| 36.776528 | 241 | 0.594126 | [
"geometry",
"object",
"vector",
"transform"
] |
037f97fc0eb8a2c0d15a1aaf7c37845ba4e2fd81 | 3,797 | cpp | C++ | code/sg-parser.cpp | Pascal-So/StreamGraph | 2f2954c30973d891d23476dcda9c37ab4125c77c | [
"MIT"
] | null | null | null | code/sg-parser.cpp | Pascal-So/StreamGraph | 2f2954c30973d891d23476dcda9c37ab4125c77c | [
"MIT"
] | null | null | null | code/sg-parser.cpp | Pascal-So/StreamGraph | 2f2954c30973d891d23476dcda9c37ab4125c77c | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
#include "sg-parser.hpp"
#include "sg-helpers.hpp"
std::string strip_bash_comments(std::string command){
// this variable will be set to 0 while outside a
// quote, and inside a quote it will hold the
// character used to quote.
char quote_char = 0;
// if the current character is a backslash, we need
// to ignore the next character.
bool ignore_next = false;
std::string out = "";
for(auto c:command){
if(ignore_next){
ignore_next = false;
}
else{
if(c == '\\'){
ignore_next = true;
}
else if(c == '\'' || c == '"'){
if(quote_char == 0){
quote_char = c;
}
else if(quote_char == c){
quote_char = 0;
}
else{
// do nothing, we encountered a single
// quote inside double quotes or vice
// versa
}
}
else if(c == '#'){
if(quote_char == 0){
return out;
}
}
}
out += c;
}
return out;
}
// Takes a stream of tokens and translates
// it in to the basic AST
// This function is not called recursively,
// instead an internal stack is used to
// keep track of nested groups
Group* parse(std::vector<token> tokens){
Group* out = new Group((Group*)0);
std::stack<Group*> current_stack;
current_stack.push(out);
// note that `i` is changed from within the loop in
// order to always parse the entire node or edge.
// (These have already been lexed together, therefore
// we know that the order is correct.)
for(size_t i = 0; i < tokens.size(); ++i){
token t = tokens[i];
if(t.first == "group"){
Group* new_group = new Group(current_stack.top());
new_group->name = t.second;
current_stack.top()->children_groups.push_back(new_group);
current_stack.push(new_group);
}
else if(t.first == "group_close"){
if(current_stack.size() == 1){
print_error("Found '}' but no group is currently open.");
return 0;
}
current_stack.pop();
}
else if(t.first == "edge"){
std::string source_name = tokens[++i].second;
std::string mod_source = tokens[++i].second;
std::string destination_name = tokens[++i].second;
std::string mod_destination = tokens[++i].second;
Edge* e = new Edge(source_name, mod_source, destination_name, mod_destination);
current_stack.top()->children_edges.push_back(e);
}
else if(t.first == "node"){
token node_data = tokens[++i];
if (node_data.first == "bash_command"){
std::string clean_bash_command = strip_bash_comments(node_data.second);
Bash_node* n = new Bash_node(clean_bash_command, current_stack.top());
n->name = t.second;
if(n->name == "input"){
// overriding the input node
current_stack.top()->input_node = n;
}else if (n->name == "output"){
// overriding the output node (don't know why you would do that, but
// I guess I'll add it for the sake of symmetry...)
current_stack.top()->output_node = n;
}else{
current_stack.top()->children_bash_nodes.push_back(n);
}
}
else if(node_data.first == "instance"){
Instance_node* n = new Instance_node(node_data.second, current_stack.top());
n->name = t.second;
current_stack.top()->children_instance_nodes.push_back(n);
}
else if(node_data.first == "infile" || node_data.first == "outfile"){
if(current_stack.size() > 1){
print_error("Can't add file io nodes in a group.");
return 0;
}
int file_number = stoi(node_data.second);
Io_node* n = new Io_node(node_data.first, file_number, current_stack.top());
n->name = t.second;
current_stack.top()->children_io_nodes.push_back(n);
}
}
}
if(current_stack.size() > 1){
print_error("Group \"" + current_stack.top()->name + "\" not closed.");
return 0;
}
return out;
}
| 28.125926 | 84 | 0.627337 | [
"vector"
] |
03809e78177afa7e42a898f82599be261e73e732 | 5,777 | cc | C++ | dbs/src/model/DescribeBackupPlanListResult.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | 3 | 2020-01-06T08:23:14.000Z | 2022-01-22T04:41:35.000Z | dbs/src/model/DescribeBackupPlanListResult.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | null | null | null | dbs/src/model/DescribeBackupPlanListResult.cc | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* 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 <alibabacloud/dbs/model/DescribeBackupPlanListResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Dbs;
using namespace AlibabaCloud::Dbs::Model;
DescribeBackupPlanListResult::DescribeBackupPlanListResult() :
ServiceResult()
{}
DescribeBackupPlanListResult::DescribeBackupPlanListResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
DescribeBackupPlanListResult::~DescribeBackupPlanListResult()
{}
void DescribeBackupPlanListResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allItems = value["Items"]["BackupPlanDetail"];
for (auto value : allItems)
{
BackupPlanDetail itemsObject;
if(!value["BackupPlanId"].isNull())
itemsObject.backupPlanId = value["BackupPlanId"].asString();
if(!value["SourceEndpointInstanceType"].isNull())
itemsObject.sourceEndpointInstanceType = value["SourceEndpointInstanceType"].asString();
if(!value["SourceEndpointRegion"].isNull())
itemsObject.sourceEndpointRegion = value["SourceEndpointRegion"].asString();
if(!value["SourceEndpointInstanceID"].isNull())
itemsObject.sourceEndpointInstanceID = value["SourceEndpointInstanceID"].asString();
if(!value["SourceEndpointIpPort"].isNull())
itemsObject.sourceEndpointIpPort = value["SourceEndpointIpPort"].asString();
if(!value["SourceEndpointDatabaseName"].isNull())
itemsObject.sourceEndpointDatabaseName = value["SourceEndpointDatabaseName"].asString();
if(!value["SourceEndpointUserName"].isNull())
itemsObject.sourceEndpointUserName = value["SourceEndpointUserName"].asString();
if(!value["BackupObjects"].isNull())
itemsObject.backupObjects = value["BackupObjects"].asString();
if(!value["BackupGatewayId"].isNull())
itemsObject.backupGatewayId = std::stol(value["BackupGatewayId"].asString());
if(!value["OSSBucketRegion"].isNull())
itemsObject.oSSBucketRegion = value["OSSBucketRegion"].asString();
if(!value["OSSBucketName"].isNull())
itemsObject.oSSBucketName = value["OSSBucketName"].asString();
if(!value["BackupPeriod"].isNull())
itemsObject.backupPeriod = value["BackupPeriod"].asString();
if(!value["BackupStartTime"].isNull())
itemsObject.backupStartTime = value["BackupStartTime"].asString();
if(!value["EnableBackupLog"].isNull())
itemsObject.enableBackupLog = value["EnableBackupLog"].asString() == "true";
if(!value["BackupRetentionPeriod"].isNull())
itemsObject.backupRetentionPeriod = std::stoi(value["BackupRetentionPeriod"].asString());
if(!value["DuplicationInfrequentAccessPeriod"].isNull())
itemsObject.duplicationInfrequentAccessPeriod = std::stoi(value["DuplicationInfrequentAccessPeriod"].asString());
if(!value["DuplicationArchivePeriod"].isNull())
itemsObject.duplicationArchivePeriod = std::stoi(value["DuplicationArchivePeriod"].asString());
if(!value["BackupPlanName"].isNull())
itemsObject.backupPlanName = value["BackupPlanName"].asString();
if(!value["SourceEndpointOracleSID"].isNull())
itemsObject.sourceEndpointOracleSID = value["SourceEndpointOracleSID"].asString();
if(!value["InstanceClass"].isNull())
itemsObject.instanceClass = value["InstanceClass"].asString();
if(!value["BackupMethod"].isNull())
itemsObject.backupMethod = value["BackupMethod"].asString();
if(!value["BackupPlanCreateTime"].isNull())
itemsObject.backupPlanCreateTime = std::stol(value["BackupPlanCreateTime"].asString());
if(!value["BackupPlanStatus"].isNull())
itemsObject.backupPlanStatus = value["BackupPlanStatus"].asString();
items_.push_back(itemsObject);
}
if(!value["Success"].isNull())
success_ = value["Success"].asString() == "true";
if(!value["ErrCode"].isNull())
errCode_ = value["ErrCode"].asString();
if(!value["ErrMessage"].isNull())
errMessage_ = value["ErrMessage"].asString();
if(!value["HttpStatusCode"].isNull())
httpStatusCode_ = std::stoi(value["HttpStatusCode"].asString());
if(!value["TotalPages"].isNull())
totalPages_ = std::stoi(value["TotalPages"].asString());
if(!value["PageSize"].isNull())
pageSize_ = std::stoi(value["PageSize"].asString());
if(!value["PageNum"].isNull())
pageNum_ = std::stoi(value["PageNum"].asString());
if(!value["TotalElements"].isNull())
totalElements_ = std::stoi(value["TotalElements"].asString());
}
int DescribeBackupPlanListResult::getPageSize()const
{
return pageSize_;
}
int DescribeBackupPlanListResult::getPageNum()const
{
return pageNum_;
}
int DescribeBackupPlanListResult::getHttpStatusCode()const
{
return httpStatusCode_;
}
int DescribeBackupPlanListResult::getTotalElements()const
{
return totalElements_;
}
std::vector<DescribeBackupPlanListResult::BackupPlanDetail> DescribeBackupPlanListResult::getItems()const
{
return items_;
}
int DescribeBackupPlanListResult::getTotalPages()const
{
return totalPages_;
}
std::string DescribeBackupPlanListResult::getErrMessage()const
{
return errMessage_;
}
bool DescribeBackupPlanListResult::getSuccess()const
{
return success_;
}
std::string DescribeBackupPlanListResult::getErrCode()const
{
return errCode_;
}
| 36.333333 | 116 | 0.755409 | [
"vector",
"model"
] |
0389490f992450d92f36568028345df2d357ffc3 | 16,008 | cpp | C++ | apps/examples/multi_window_example/multi_window_example_app/multi_window_example_app.cpp | themancalledjakob/island | 8925045a6ffb596e960ae17412848f40249ebe24 | [
"MIT"
] | 542 | 2020-05-28T18:15:12.000Z | 2022-03-05T19:53:59.000Z | apps/examples/multi_window_example/multi_window_example_app/multi_window_example_app.cpp | themancalledjakob/island | 8925045a6ffb596e960ae17412848f40249ebe24 | [
"MIT"
] | 23 | 2020-06-12T19:40:21.000Z | 2021-11-11T19:44:02.000Z | apps/examples/multi_window_example/multi_window_example_app/multi_window_example_app.cpp | themancalledjakob/island | 8925045a6ffb596e960ae17412848f40249ebe24 | [
"MIT"
] | 23 | 2020-05-28T19:21:50.000Z | 2021-11-11T18:56:30.000Z | #include "multi_window_example_app.h"
#include "le_window.h"
#include "le_renderer.h"
#include "le_camera.h"
#include "le_pipeline_builder.h"
#include "le_ui_event.h"
#include "le_mesh.h"
#define GLM_FORCE_DEPTH_ZERO_TO_ONE // vulkan clip space is from 0 to 1
#define GLM_FORCE_RIGHT_HANDED // glTF uses right handed coordinate system, and we're following its lead.
#define GLM_ENABLE_EXPERIMENTAL
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include <iostream>
#include <memory>
#include <sstream>
#include <vector>
typedef multi_window_example_app_o app_o;
struct le_mouse_event_data_o {
uint32_t buttonState{};
glm::vec2 cursor_pos;
};
struct multi_window_example_app_o {
le::Window window_0;
le::Window window_1;
le::Renderer renderer;
LeCameraController cameraController;
LeCamera camera;
LeMesh mesh;
};
// ----------------------------------------------------------------------
static void app_initialize() {
le::Window::init();
};
// ----------------------------------------------------------------------
static void app_terminate() {
le::Window::terminate();
};
static void reset_camera( multi_window_example_app_o *self ); // ffdecl.
// ----------------------------------------------------------------------
static multi_window_example_app_o *app_create() {
auto app = new ( multi_window_example_app_o );
le::Window::Settings settings_0;
settings_0
.setWidth( 1920 / 2 )
.setHeight( 1080 / 2 )
.setTitle( "Island // MultiWindowExampleApp- Window 0" );
le::Window::Settings settings_1;
settings_1
.setWidth( 200 )
.setHeight( 400 )
.setTitle( "Island // Window 1" );
// Setup both windows
app->window_0.setup( settings_0 );
app->window_1.setup( settings_1 );
// Attach windows to swapchains via renderer
app->renderer.setup(
le::RendererInfoBuilder()
.addSwapchain()
.asWindowSwapchain()
.setWindow( app->window_0 )
.end()
.end()
.addSwapchain()
.asWindowSwapchain()
.setWindow( app->window_1 )
.end()
.end()
.build() );
reset_camera( app ); // set up the camera
return app;
}
// ----------------------------------------------------------------------
static void reset_camera( multi_window_example_app_o *self ) {
uint32_t screenWidth{};
uint32_t screenHeight{};
self->renderer.getSwapchainExtent( &screenWidth, &screenHeight );
self->camera.setViewport( { 0, float( screenHeight ), float( screenWidth ), -float( screenHeight ), 0.f, 1.f } );
self->camera.setFovRadians( glm::radians( 60.f ) ); // glm::radians converts degrees to radians
glm::mat4 camMatrix = glm::lookAt( glm::vec3{ 0, 0, self->camera.getUnitDistance() }, glm::vec3{ 0 }, glm::vec3{ 0, 1, 0 } );
self->camera.setViewMatrix( reinterpret_cast<float const *>( &camMatrix ) );
self->camera.setClipDistances( 10, 10000 );
}
// ----------------------------------------------------------------------
static void pass_to_window_0( le_command_buffer_encoder_o *encoder_, void *user_data ) {
auto app = static_cast<multi_window_example_app_o *>( user_data );
le::Encoder encoder{ encoder_ };
uint32_t screenWidth, screenHeight;
// Note that we fetch extents for swapchain 0:
app->renderer.getSwapchainExtent( &screenWidth, &screenHeight, 0 );
// Note that we flip the viewport (negative height) so that +Y is up.
le::Viewport viewports[ 1 ] = {
{ 0.f, float( screenHeight ), float( screenWidth ), -float( screenHeight ), 0.f, 1.f },
};
app->camera.setViewport( viewports[ 0 ] );
le::Rect2D scissors[ 1 ] = {
{ 0, 0, screenWidth, screenHeight },
};
// Draw main scene
struct MVP_DefaultUbo_t {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
MVP_DefaultUbo_t mvp;
struct UniformsUbo_t {
glm::vec4 color;
} uniforms{
glm::vec4{ 1, 1, 1, 1 } };
mvp.model = glm::mat4( 1.f );
mvp.model = glm::scale( mvp.model, glm::vec3( 100 ) );
app->camera.getViewMatrix( &mvp.view[ 0 ][ 0 ] );
app->camera.getProjectionMatrix( &mvp.projection[ 0 ][ 0 ] );
// Draw mesh
static auto pipelineDefault =
LeGraphicsPipelineBuilder( encoder.getPipelineManager() )
.addShaderStage(
LeShaderModuleBuilder( encoder.getPipelineManager() )
.setShaderStage( le::ShaderStage::eVertex )
.setSourceFilePath( "./local_resources/shaders/default.vert" )
.build() )
.addShaderStage(
LeShaderModuleBuilder( encoder.getPipelineManager() )
.setShaderStage( le::ShaderStage::eFragment )
.setSourceFilePath( "./local_resources/shaders/default.frag" )
.build() )
.withRasterizationState()
.setPolygonMode( le::PolygonMode::eFill )
.setCullMode( le::CullModeFlagBits::eBack )
.setFrontFace( le::FrontFace::eCounterClockwise )
.end()
.withInputAssemblyState()
.setTopology( le::PrimitiveTopology::eTriangleList )
.end()
.withDepthStencilState()
.setDepthTestEnable( true )
.end()
.build();
uint16_t const *meshIndices = nullptr;
float const * meshVertices = nullptr;
float const * meshColours = nullptr;
float const * meshNormals = nullptr;
float const * meshUvs = nullptr;
size_t numVertices = 0;
size_t numIndices = 0;
app->mesh.getData( numVertices, numIndices, &meshVertices, &meshNormals, &meshUvs, &meshColours, &meshIndices );
encoder
.setScissors( 0, 1, scissors )
.setViewports( 0, 1, viewports ) //
;
encoder
.setVertexData( meshVertices, numVertices * 3 * sizeof( float ), 0 )
.setVertexData( meshNormals, numVertices * 3 * sizeof( float ), 1 )
.setVertexData( meshUvs, numVertices * 2 * sizeof( float ), 2 )
.setVertexData( meshColours, numVertices * 4 * sizeof( float ), 3 )
.setIndexData( meshIndices, numIndices * sizeof( uint16_t ) );
uniforms.color = { 1, 1, 1, 1 };
encoder
.bindGraphicsPipeline( pipelineDefault )
.setArgumentData( LE_ARGUMENT_NAME( "MVP_Default" ), &mvp, sizeof( MVP_DefaultUbo_t ) )
.setArgumentData( LE_ARGUMENT_NAME( "Uniform_Data" ), &uniforms, sizeof( UniformsUbo_t ) )
.setLineWidth( 1.f ) //
.drawIndexed( uint32_t( numIndices ) ) //
;
}
// ----------------------------------------------------------------------
static void pass_to_window_1( le_command_buffer_encoder_o *encoder_, void *user_data ) {
auto app = static_cast<multi_window_example_app_o *>( user_data );
le::Encoder encoder{ encoder_ };
uint32_t screenWidth, screenHeight;
app->renderer.getSwapchainExtent( &screenWidth, &screenHeight, 1 );
// Note that we flip the viewport (negative height) so that +Y is up.
le::Viewport viewports[ 1 ] = {
{ 0.f, float( screenHeight ), float( screenWidth ), -float( screenHeight ), 0.f, 1.f },
};
app->camera.setViewport( viewports[ 0 ] );
le::Rect2D scissors[ 1 ] = {
{ 0, 0, screenWidth, screenHeight },
};
// Draw main scene
struct MVP_DefaultUbo_t {
glm::mat4 model;
glm::mat4 view;
glm::mat4 projection;
};
MVP_DefaultUbo_t mvp;
struct UniformsUbo_t {
glm::vec4 color;
} uniforms{
glm::vec4{ 1, 1, 1, 1 } };
mvp.model = glm::mat4( 1.f ); // identity matrix
mvp.model = glm::scale( mvp.model, glm::vec3( 100 ) ); // scale by 100
app->camera.getViewMatrix( &mvp.view[ 0 ][ 0 ] );
app->camera.getProjectionMatrix( &mvp.projection[ 0 ][ 0 ] );
// Draw mesh
static auto pipelineWireframe =
LeGraphicsPipelineBuilder( encoder.getPipelineManager() )
.addShaderStage(
LeShaderModuleBuilder( encoder.getPipelineManager() )
.setShaderStage( le::ShaderStage::eVertex )
.setSourceFilePath( "./local_resources/shaders/default.vert" )
.build() )
.addShaderStage(
LeShaderModuleBuilder( encoder.getPipelineManager() )
.setShaderStage( le::ShaderStage::eFragment )
.setSourceFilePath( "./local_resources/shaders/default.frag" )
.setSourceDefinesString( "SHOW_MONO_COLOUR" )
.build() )
.withRasterizationState()
.setPolygonMode( le::PolygonMode::eLine )
.setCullMode( le::CullModeFlagBits::eBack )
.setFrontFace( le::FrontFace::eCounterClockwise )
.end()
.withInputAssemblyState()
.setTopology( le::PrimitiveTopology::eTriangleList )
.end()
.withDepthStencilState()
.setDepthTestEnable( true )
.end()
.build();
uint16_t const *meshIndices = nullptr;
float const * meshVertices = nullptr;
float const * meshColours = nullptr;
float const * meshNormals = nullptr;
float const * meshUvs = nullptr;
size_t numVertices = 0;
size_t numIndices = 0;
app->mesh.getData( numVertices, numIndices, &meshVertices, &meshNormals, &meshUvs, &meshColours, &meshIndices );
uniforms.color = { 1, 1, 1, 1 };
encoder
.setScissors( 0, 1, scissors )
.setViewports( 0, 1, viewports ) //
;
encoder
.setVertexData( meshVertices, numVertices * 3 * sizeof( float ), 0 )
.setVertexData( meshNormals, numVertices * 3 * sizeof( float ), 1 )
.setVertexData( meshUvs, numVertices * 2 * sizeof( float ), 2 )
.setVertexData( meshColours, numVertices * 4 * sizeof( float ), 3 )
.setIndexData( meshIndices, numIndices * sizeof( uint16_t ) );
encoder
.bindGraphicsPipeline( pipelineWireframe )
.setArgumentData( LE_ARGUMENT_NAME( "MVP_Default" ), &mvp, sizeof( MVP_DefaultUbo_t ) )
.setArgumentData( LE_ARGUMENT_NAME( "Uniform_Data" ), &uniforms, sizeof( UniformsUbo_t ) )
.setLineWidth( 1.f ) //
.drawIndexed( uint32_t( numIndices ) ) //
;
}
// ----------------------------------------------------------------------
static void app_process_ui_events( app_o *self ) {
using namespace le_window;
uint32_t numEvents;
LeUiEvent const *pEvents;
// Process keyboard events - but only on window 0
// You could repeat this to process events on window 1
window_i.get_ui_event_queue( self->window_0, &pEvents, numEvents ); // note: self->window_0
std::vector<LeUiEvent> events{ pEvents, pEvents + numEvents };
bool wantsToggle = false;
for ( auto &event : events ) {
switch ( event.event ) {
case ( LeUiEvent::Type::eKey ): {
auto &e = event.key;
if ( e.action == LeUiEvent::ButtonAction::eRelease ) {
if ( e.key == LeUiEvent::NamedKey::eF11 ) {
wantsToggle ^= true;
} else if ( e.key == LeUiEvent::NamedKey::eC ) {
float distance_to_origin =
glm::distance( glm::vec4{ 0, 0, 0, 1 },
glm::inverse( self->camera.getViewMatrixGlm() ) * glm::vec4( 0, 0, 0, 1 ) );
self->cameraController.setPivotDistance( distance_to_origin );
} else if ( e.key == LeUiEvent::NamedKey::eX ) {
self->cameraController.setPivotDistance( 0 );
} else if ( e.key == LeUiEvent::NamedKey::eZ ) {
reset_camera( self );
float distance_to_origin =
glm::distance( glm::vec4{ 0, 0, 0, 1 },
glm::inverse( self->camera.getViewMatrixGlm() ) * glm::vec4( 0, 0, 0, 1 ) );
self->cameraController.setPivotDistance( distance_to_origin );
}
} // if ButtonAction == eRelease
} break;
default:
// do nothing
break;
}
}
{
// Process camera events for window 0
auto swapchainExtent = self->renderer.getSwapchainExtent( 0 ); // Note we're using swapchain extents 0
self->cameraController.setControlRect( 0, 0, float( swapchainExtent.width ), float( swapchainExtent.height ) );
self->cameraController.processEvents( self->camera, pEvents, numEvents );
}
{
// Process camera events for window 1
window_i.get_ui_event_queue( self->window_1, &pEvents, numEvents ); // note: self->window_1
auto swapchainExtent = self->renderer.getSwapchainExtent( 1 ); // Note we're using swapchain extents 0
self->cameraController.setControlRect( 0, 0, float( swapchainExtent.width ), float( swapchainExtent.height ) );
self->cameraController.processEvents( self->camera, pEvents, numEvents );
}
if ( wantsToggle ) {
self->window_0.toggleFullscreen();
}
}
// ----------------------------------------------------------------------
static bool app_update( multi_window_example_app_o *self ) {
// Polls events for all windows -
// This means any window may trigger callbacks for any events they have callbacks registered.
le::Window::pollEvents();
if ( self->window_0.shouldClose() || self->window_1.shouldClose() ) {
return false;
}
// update interactive camera using mouse data
app_process_ui_events( self );
static bool resetCameraOnReload = false; // reload meand module reload
if ( resetCameraOnReload ) {
// Reset camera
reset_camera( self );
resetCameraOnReload = false;
}
// Creature model created by user sugamo on poly.google.com: <https://poly.google.com/user/cyypmbztDpj>
// Licensed CC-BY.
static bool result = self->mesh.loadFromPlyFile( "./local_resources/meshes/sugamo-doraemon.ply" );
static auto IMG_SWAP_0 = self->renderer.getSwapchainResource( 0 );
static auto IMG_SWAP_1 = self->renderer.getSwapchainResource( 1 );
assert( result );
using namespace le_renderer;
le::RenderModule mainModule{};
{
le_image_attachment_info_t attachmentInfo[ 2 ];
attachmentInfo[ 0 ].clearValue.color =
{ { { 0xf1 / 255.f, 0x8e / 255.f, 0x00 / 255.f, 0xff / 255.f } } };
attachmentInfo[ 1 ].clearValue.color =
{ { { 0x22 / 255.f, 0x22 / 255.f, 0x22 / 255.f, 0xff / 255.f } } };
// Define a renderpass which outputs to window_0.
auto renderPassMain =
le::RenderPass( "to_window_0", LE_RENDER_PASS_TYPE_DRAW )
.addColorAttachment( IMG_SWAP_0, attachmentInfo[ 0 ] ) // IMG_SWAP_0 == swapchain 0 attachment
.addDepthStencilAttachment( LE_IMG_RESOURCE( "DEPTH_BUFFER" ) )
.setSampleCount( le::SampleCountFlagBits::e8 )
.setExecuteCallback( self, pass_to_window_0 ) //
;
// Define a renderpass, which outputs to window_1. Note that it uses
// IMG_SWAP_1 as a color attachment.
// Because only the image resource for the default swapchain is automatically
// recognised as drawing to screen, you must set the renderpass Root manually.
// Root means that the renderpass is tagged as contributing to the final image,
// otherwise the rendergraph is free to optimise it away, and along with it any
// renderpasses that contribute to it.
auto renderPassSecond =
le::RenderPass( "to_window_1" )
.addColorAttachment( IMG_SWAP_1, attachmentInfo[ 1 ] ) // IMG_SWAP_1 == swapchain 1 attachment
.addDepthStencilAttachment( LE_IMG_RESOURCE( "DEPTH_BUFFER_1" ) )
.setExecuteCallback( self, pass_to_window_1 )
.setIsRoot( true ) // IMPORTANT!
;
mainModule
.addRenderPass( renderPassMain )
.addRenderPass( renderPassSecond );
}
self->renderer.update( mainModule );
return true; // keep app alive
}
// ----------------------------------------------------------------------
static void app_destroy( multi_window_example_app_o *self ) {
delete ( self ); // deletes camera
}
// ----------------------------------------------------------------------
LE_MODULE_REGISTER_IMPL( multi_window_example_app, api ) {
auto multi_window_example_app_api_i = static_cast<multi_window_example_app_api *>( api );
auto &multi_window_example_app_i = multi_window_example_app_api_i->multi_window_example_app_i;
multi_window_example_app_i.initialize = app_initialize;
multi_window_example_app_i.terminate = app_terminate;
multi_window_example_app_i.create = app_create;
multi_window_example_app_i.destroy = app_destroy;
multi_window_example_app_i.update = app_update;
}
| 33.630252 | 126 | 0.636057 | [
"mesh",
"vector",
"model"
] |
03928687c92920fee5f9b440d1d5058f6335b87c | 2,026 | cpp | C++ | test/cppunit_tests/WarpedUnitTest.cpp | wilseypa/warped | 8842cf88b11213b6b69e53de5e969c4e3c2c8bd5 | [
"MIT"
] | 12 | 2015-03-13T09:58:25.000Z | 2021-09-23T11:48:42.000Z | test/cppunit_tests/WarpedUnitTest.cpp | wilseypa/warped | 8842cf88b11213b6b69e53de5e969c4e3c2c8bd5 | [
"MIT"
] | 1 | 2015-12-09T05:21:44.000Z | 2015-12-17T19:37:12.000Z | test/cppunit_tests/WarpedUnitTest.cpp | wilseypa/warped | 8842cf88b11213b6b69e53de5e969c4e3c2c8bd5 | [
"MIT"
] | null | null | null | #include "WarpedUnitTest.h"
Event*
WarpedUnitTest::getEvent1() {
static Event* event1 = new UnitTestEvent(IntVTime::getIntVTimeZero(), getSimObj1ID());
return event1;
}
Event*
WarpedUnitTest::getEvent2() {
static Event* event2 = new UnitTestEvent(IntVTime::getIntVTimeZero(), getSimObj1ID());
return event2;
}
Event*
WarpedUnitTest::getEvent3() {
static Event* event3 = new UnitTestEvent(*new IntVTime(1), getSimObj1ID());
return event3;
}
Event*
WarpedUnitTest::getEvent4() {
static Event* event4 = new UnitTestEvent(IntVTime::getIntVTimeZero(), getSimObj1ID());
return event4;
}
vector<Event*>&
WarpedUnitTest::getDefaultEvents() {
static vector<Event*>* retval = new vector<Event*>;
if (retval->size() == 0) {
retval->push_back(getEvent1());
retval->push_back(getEvent2());
retval->push_back(getEvent3());
retval->push_back(getEvent4());
}
return *retval;
}
void
WarpedUnitTest::doDefaultInsert(TimeWarpEventSet* toTest) {
vector<Event*>& events = getDefaultEvents();
bool inThePast = true;
for (vector<Event*>::iterator currentEvent = events.begin();
currentEvent < events.end();
currentEvent++) {
inThePast = toTest->insert(*currentEvent);
CPPUNIT_ASSERT(inThePast == false);
}
}
void
WarpedUnitTest::checkDefaultEvents(const Event* event1,
const Event* event2,
const Event* event3,
const Event* event4) {
if (event1 != 0) {
CPPUNIT_ASSERT(event1->getReceiveTime() == IntVTime(0));
}
if (event2 != 0) {
CPPUNIT_ASSERT(event2 != event1);
CPPUNIT_ASSERT(event2->getReceiveTime() == IntVTime(0));
}
if (event3 != 0) {
CPPUNIT_ASSERT(event3 != event2 && event3 != event1);
CPPUNIT_ASSERT(event3->getReceiveTime() == IntVTime(0));
}
if (event4 != 0) {
CPPUNIT_ASSERT(event4 == getEvent3());
}
}
| 27.378378 | 90 | 0.614018 | [
"vector"
] |
039a8c3eb510e43fc34abec7d934ad27d3f69d4c | 2,241 | hpp | C++ | include/GTGE/Physics.hpp | mackron/GTGameEngine | 380d1e01774fe6bc2940979e4e5983deef0bf082 | [
"BSD-3-Clause"
] | 31 | 2015-03-19T08:44:48.000Z | 2021-12-15T20:52:31.000Z | include/GTGE/Physics.hpp | mackron/GTGameEngine | 380d1e01774fe6bc2940979e4e5983deef0bf082 | [
"BSD-3-Clause"
] | 19 | 2015-07-09T09:02:44.000Z | 2016-06-09T03:51:03.000Z | include/GTGE/Physics.hpp | mackron/GTGameEngine | 380d1e01774fe6bc2940979e4e5983deef0bf082 | [
"BSD-3-Clause"
] | 3 | 2017-10-04T23:38:18.000Z | 2022-03-07T08:27:13.000Z | // Copyright (C) 2011 - 2014 David Reid. See included LICENCE.
#ifndef GT_Physics
#define GT_Physics
#include "Physics/CollisionWorld.hpp"
#include "Physics/DynamicsWorld.hpp"
#include "Physics/SceneNodeMotionState.hpp"
#include "Physics/btEllipsoidShape.hpp"
#include "Physics/StaticMeshCollisionShape.hpp"
#include "Physics/MeshCollisionShape.hpp"
#include "Physics/CollisionShapeTypes.hpp"
#include "Math.hpp"
namespace GT
{
inline btVector3 ToBulletVector3(const glm::vec3 &v)
{
return btVector3(v.x, v.y, v.z);
}
inline btTransform ToBulletTransform(const glm::mat4 &m)
{
btTransform result;
result.setFromOpenGLMatrix(&m[0][0]);
return result;
}
inline glm::vec3 ToGLMVector3(const btVector3 &v)
{
return glm::vec3(v.x(), v.y(), v.z());
}
inline glm::quat ToGLMQuaternion(const btQuaternion &v)
{
return glm::quat(v.w(), v.x(), v.y(), v.z());
}
inline glm::mat4 ToGLMMatrix4(const btTransform &t)
{
glm::mat4 result;
t.getOpenGLMatrix(&result[0][0]);
return result;
}
namespace BulletUtils
{
/**
* \brief Helper for calculating the local inertia for a shape.
*/
inline btVector3 CalculateLocalInertia(btScalar mass, const btCollisionShape &collisionShape)
{
// No mass = no inertia. Looking through the Bullet code shows that this check is not performed in the different
// implementations of calculatelocalInertia(). I like it, so I'll do it here.
if (mass > 0.0f)
{
btVector3 localInertia;
collisionShape.calculateLocalInertia(mass, localInertia);
return localInertia;
}
return btVector3(0.0f, 0.0f, 0.0f);
}
/**
* \brief Creates a btTransform object from a glm::mat4.
*/
inline btTransform CreateTransform(const glm::mat4 &transform)
{
btTransform result;
result.setFromOpenGLMatrix(&transform[0][0]);
return result;
}
}
}
#endif | 26.678571 | 125 | 0.587238 | [
"object",
"shape",
"transform"
] |
039e80417cdc83a8a08df6edfd129f0e801efdf2 | 253 | cpp | C++ | ports/sysutils/intel-pcm/dragonfly/patch-dashboard.cpp | zrj-rimwis/DeltaPorts | 4aa1e3e6aa12300fd9dd3f3b4501cde94b12b4a9 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | ports/sysutils/intel-pcm/dragonfly/patch-dashboard.cpp | zrj-rimwis/DeltaPorts | 4aa1e3e6aa12300fd9dd3f3b4501cde94b12b4a9 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | ports/sysutils/intel-pcm/dragonfly/patch-dashboard.cpp | zrj-rimwis/DeltaPorts | 4aa1e3e6aa12300fd9dd3f3b4501cde94b12b4a9 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | --- dashboard.cpp.orig 2021-05-15 15:52:05 UTC
+++ dashboard.cpp
@@ -13,6 +13,7 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIG
#include <vector>
#include <memory>
+#include <mutex>
#include <unistd.h>
#include "cpucounters.h"
#include "dashboard.h"
| 23 | 58 | 0.683794 | [
"vector"
] |
03a1e8c10dd92acb93f47448051508fb37a77b9d | 3,073 | cpp | C++ | 3rdparty/aws-sdk-cpp-master/aws-cpp-sdk-config/source/model/Evaluation.cpp | prateek-s/mesos | 4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8 | [
"Apache-2.0"
] | 2 | 2019-02-08T21:29:57.000Z | 2021-07-27T06:59:19.000Z | 3rdparty/aws-sdk-cpp-master/aws-cpp-sdk-config/source/model/Evaluation.cpp | prateek-s/mesos | 4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8 | [
"Apache-2.0"
] | null | null | null | 3rdparty/aws-sdk-cpp-master/aws-cpp-sdk-config/source/model/Evaluation.cpp | prateek-s/mesos | 4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/config/model/Evaluation.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace ConfigService
{
namespace Model
{
Evaluation::Evaluation() :
m_complianceResourceTypeHasBeenSet(false),
m_complianceResourceIdHasBeenSet(false),
m_complianceTypeHasBeenSet(false),
m_annotationHasBeenSet(false),
m_orderingTimestampHasBeenSet(false)
{
}
Evaluation::Evaluation(const JsonValue& jsonValue) :
m_complianceResourceTypeHasBeenSet(false),
m_complianceResourceIdHasBeenSet(false),
m_complianceTypeHasBeenSet(false),
m_annotationHasBeenSet(false),
m_orderingTimestampHasBeenSet(false)
{
*this = jsonValue;
}
Evaluation& Evaluation::operator =(const JsonValue& jsonValue)
{
if(jsonValue.ValueExists("ComplianceResourceType"))
{
m_complianceResourceType = jsonValue.GetString("ComplianceResourceType");
m_complianceResourceTypeHasBeenSet = true;
}
if(jsonValue.ValueExists("ComplianceResourceId"))
{
m_complianceResourceId = jsonValue.GetString("ComplianceResourceId");
m_complianceResourceIdHasBeenSet = true;
}
if(jsonValue.ValueExists("ComplianceType"))
{
m_complianceType = ComplianceTypeMapper::GetComplianceTypeForName(jsonValue.GetString("ComplianceType"));
m_complianceTypeHasBeenSet = true;
}
if(jsonValue.ValueExists("Annotation"))
{
m_annotation = jsonValue.GetString("Annotation");
m_annotationHasBeenSet = true;
}
if(jsonValue.ValueExists("OrderingTimestamp"))
{
m_orderingTimestamp = jsonValue.GetDouble("OrderingTimestamp");
m_orderingTimestampHasBeenSet = true;
}
return *this;
}
JsonValue Evaluation::Jsonize() const
{
JsonValue payload;
if(m_complianceResourceTypeHasBeenSet)
{
payload.WithString("ComplianceResourceType", m_complianceResourceType);
}
if(m_complianceResourceIdHasBeenSet)
{
payload.WithString("ComplianceResourceId", m_complianceResourceId);
}
if(m_complianceTypeHasBeenSet)
{
payload.WithString("ComplianceType", ComplianceTypeMapper::GetNameForComplianceType(m_complianceType));
}
if(m_annotationHasBeenSet)
{
payload.WithString("Annotation", m_annotation);
}
if(m_orderingTimestampHasBeenSet)
{
payload.WithDouble("OrderingTimestamp", m_orderingTimestamp.SecondsWithMSPrecision());
}
return payload;
}
} // namespace Model
} // namespace ConfigService
} // namespace Aws | 24.388889 | 109 | 0.760169 | [
"model"
] |
03a6d484443f12c174cb8301b78978716f29e836 | 870 | cpp | C++ | codeforces/manthan16/B/main.cpp | Johniel/contests | b692eff913c20e2c1eb4ff0ce3cd4c57900594e0 | [
"Unlicense"
] | null | null | null | codeforces/manthan16/B/main.cpp | Johniel/contests | b692eff913c20e2c1eb4ff0ce3cd4c57900594e0 | [
"Unlicense"
] | 19 | 2016-05-04T02:46:31.000Z | 2021-11-27T06:18:33.000Z | codeforces/manthan16/B/main.cpp | Johniel/contests | b692eff913c20e2c1eb4ff0ce3cd4c57900594e0 | [
"Unlicense"
] | null | null | null | #include <bits/stdc++.h>
#define each(i, c) for (auto& i : c)
#define unless(cond) if (!(cond))
using namespace std;
typedef long long int lli;
typedef unsigned long long ull;
typedef complex<double> point;
template<typename P, typename Q>
ostream& operator << (ostream& os, pair<P, Q> p)
{
os << "(" << p.first << "," << p.second << ")";
return os;
}
int f(lli n)
{
int cnt = 0;
while (n && n % 5 == 0) {
n /= 5;
++cnt;
}
return cnt;
}
int main(int argc, char *argv[])
{
lli n;
while (scanf("%lld", &n) == 1) {
lli _5 = 0;
vector<lli> v;
for (int i = 5; _5 <= n; ++i) {
if (i % 5 == 0) _5 += f(i);
if (_5 == n) v.push_back(i);
}
printf("%d\n", (int)v.size());
for (int i = 0; i < v.size(); ++i) {
if (i) printf(" ");
printf("%lld", v[i]);
}
if (v.size()) puts("");
}
return 0;
}
| 18.125 | 49 | 0.493103 | [
"vector"
] |
03afd7239f569a64149d0bd8b9b872164d414f07 | 11,647 | cpp | C++ | artifact/storm/src/storm/storage/dd/sylvan/SylvanAddIterator.cpp | glatteis/tacas21-artifact | 30b4f522bd3bdb4bebccbfae93f19851084a3db5 | [
"MIT"
] | null | null | null | artifact/storm/src/storm/storage/dd/sylvan/SylvanAddIterator.cpp | glatteis/tacas21-artifact | 30b4f522bd3bdb4bebccbfae93f19851084a3db5 | [
"MIT"
] | null | null | null | artifact/storm/src/storm/storage/dd/sylvan/SylvanAddIterator.cpp | glatteis/tacas21-artifact | 30b4f522bd3bdb4bebccbfae93f19851084a3db5 | [
"MIT"
] | 1 | 2022-02-05T12:39:53.000Z | 2022-02-05T12:39:53.000Z | #include "storm/storage/dd/sylvan/SylvanAddIterator.h"
#include "storm/storage/dd/sylvan/InternalSylvanAdd.h"
#include "storm/storage/dd/DdManager.h"
#include "storm/storage/expressions/ExpressionManager.h"
#include "storm/utility/macros.h"
#include "storm/exceptions/NotImplementedException.h"
#include <cmath>
#include "storm/adapters/RationalFunctionAdapter.h"
namespace storm {
namespace dd {
template<typename ValueType>
AddIterator<DdType::Sylvan, ValueType>::AddIterator() {
// Intentionally left empty.
}
template<typename ValueType>
AddIterator<DdType::Sylvan, ValueType>::AddIterator(DdManager<DdType::Sylvan> const& ddManager, sylvan::Mtbdd mtbdd, sylvan::Bdd variables, uint_fast64_t numberOfDdVariables, bool isAtEnd, std::set<storm::expressions::Variable> const* metaVariables, bool enumerateDontCareMetaVariables) : ddManager(&ddManager), mtbdd(mtbdd), variables(variables), cube(numberOfDdVariables), leaf(), isAtEnd(isAtEnd), metaVariables(metaVariables), enumerateDontCareMetaVariables(enumerateDontCareMetaVariables), cubeCounter(0), relevantDontCareDdVariables(), currentValuation(ddManager.getExpressionManager().getSharedPointer()) {
// If the given generator is not yet at its end, we need to create the current valuation from the cube from
// scratch.
if (!this->isAtEnd) {
this->createGlobalToLocalIndexMapping();
// And then get ready for treating the first cube.
leaf = mtbdd_enum_first(mtbdd.GetMTBDD(), variables.GetBDD(), cube.data(), &mtbdd_isnonzero);
if (leaf != mtbdd_false) {
this->treatNewCube();
} else {
this->isAtEnd = true;
}
}
}
template<typename ValueType>
void AddIterator<DdType::Sylvan, ValueType>::createGlobalToLocalIndexMapping() {
// Create the global to local index mapping.
std::vector<uint_fast64_t> globalIndices;
for (auto const& metaVariable : *this->metaVariables) {
auto const& ddMetaVariable = this->ddManager->getMetaVariable(metaVariable);
for (auto const& ddVariable : ddMetaVariable.getDdVariables()) {
globalIndices.push_back(ddVariable.getIndex());
}
}
std::sort(globalIndices.begin(), globalIndices.end());
for (auto it = globalIndices.begin(), ite = globalIndices.end(); it != ite; ++it) {
globalToLocalIndexMap[*it] = std::distance(globalIndices.begin(), it);
}
}
template<typename ValueType>
AddIterator<DdType::Sylvan, ValueType> AddIterator<DdType::Sylvan, ValueType>::createBeginIterator(DdManager<DdType::Sylvan> const& ddManager, sylvan::Mtbdd mtbdd, sylvan::Bdd variables, uint_fast64_t numberOfDdVariables, std::set<storm::expressions::Variable> const* metaVariables, bool enumerateDontCareMetaVariables) {
return AddIterator<DdType::Sylvan, ValueType>(ddManager, mtbdd, variables, numberOfDdVariables, false, metaVariables, enumerateDontCareMetaVariables);
}
template<typename ValueType>
AddIterator<DdType::Sylvan, ValueType> AddIterator<DdType::Sylvan, ValueType>::createEndIterator(DdManager<DdType::Sylvan> const& ddManager) {
return AddIterator<DdType::Sylvan, ValueType>(ddManager, sylvan::Mtbdd(), sylvan::Bdd(), 0, true, nullptr, false);
}
template<typename ValueType>
AddIterator<DdType::Sylvan, ValueType>& AddIterator<DdType::Sylvan, ValueType>::operator++() {
STORM_LOG_ASSERT(!this->isAtEnd, "Illegally incrementing iterator that is already at its end.");
// If there were no (relevant) don't cares or we have enumerated all combination, we need to eliminate the
// found solutions and get the next "first" cube.
if (this->relevantDontCareDdVariables.empty() || this->cubeCounter >= std::pow(2, this->relevantDontCareDdVariables.size()) - 1) {
leaf = mtbdd_enum_next(mtbdd.GetMTBDD(), variables.GetBDD(), cube.data(), &mtbdd_isnonzero);
if (leaf != mtbdd_false) {
this->treatNewCube();
} else {
this->isAtEnd = true;
}
} else {
// Treat the next solution of the cube.
this->treatNextInCube();
}
return *this;
}
template<typename ValueType>
bool AddIterator<DdType::Sylvan, ValueType>::operator==(AddIterator<DdType::Sylvan, ValueType> const& other) const {
if (this->isAtEnd && other.isAtEnd) {
return true;
} else {
return this->ddManager == other.ddManager && this->mtbdd == other.mtbdd && this->variables == other.variables
&& this->cube == other.cube && this->leaf == other.leaf && this->isAtEnd == other.isAtEnd
&& this->metaVariables == other.metaVariables && this->cubeCounter == other.cubeCounter
&& this->relevantDontCareDdVariables == other.relevantDontCareDdVariables
&& this->currentValuation == other.currentValuation;
}
}
template<typename ValueType>
bool AddIterator<DdType::Sylvan, ValueType>::operator!=(AddIterator<DdType::Sylvan, ValueType> const& other) const {
return !(*this == other);
}
template<typename ValueType>
std::pair<storm::expressions::SimpleValuation, ValueType> AddIterator<DdType::Sylvan, ValueType>::operator*() const {
return std::make_pair(currentValuation, static_cast<ValueType>(InternalAdd<DdType::Sylvan, ValueType>::getValue(leaf)));
}
template<typename ValueType>
void AddIterator<DdType::Sylvan, ValueType>::treatNewCube() {
this->relevantDontCareDdVariables.clear();
// Now loop through the bits of all meta variables and check whether they need to be set, not set or are
// don't cares. In the latter case, we add them to a special list, so we can iterate over their concrete
// valuations later.
for (auto const& metaVariable : *this->metaVariables) {
bool metaVariableAppearsInCube = false;
std::vector<std::tuple<storm::expressions::Variable, uint_fast64_t>> localRelenvantDontCareDdVariables;
auto const& ddMetaVariable = this->ddManager->getMetaVariable(metaVariable);
if (ddMetaVariable.getType() == MetaVariableType::Bool) {
if (this->cube[globalToLocalIndexMap.at(ddMetaVariable.getDdVariables().front().getIndex())] == 0) {
metaVariableAppearsInCube = true;
currentValuation.setBooleanValue(metaVariable, false);
} else if (this->cube[globalToLocalIndexMap.at(ddMetaVariable.getDdVariables().front().getIndex())] == 1) {
metaVariableAppearsInCube = true;
currentValuation.setBooleanValue(metaVariable, true);
} else {
localRelenvantDontCareDdVariables.push_back(std::make_tuple(metaVariable, 0));
}
} else {
int_fast64_t intValue = 0;
for (uint_fast64_t bitIndex = 0; bitIndex < ddMetaVariable.getNumberOfDdVariables(); ++bitIndex) {
if (cube[globalToLocalIndexMap.at(ddMetaVariable.getDdVariables()[bitIndex].getIndex())] == 0) {
// Leave bit unset.
metaVariableAppearsInCube = true;
} else if (cube[globalToLocalIndexMap.at(ddMetaVariable.getDdVariables()[bitIndex].getIndex())] == 1) {
intValue |= 1ull << (ddMetaVariable.getNumberOfDdVariables() - bitIndex - 1);
metaVariableAppearsInCube = true;
} else {
// Temporarily leave bit unset so we can iterate trough the other option later.
// Add the bit to the relevant don't care bits.
localRelenvantDontCareDdVariables.push_back(std::make_tuple(metaVariable, ddMetaVariable.getNumberOfDdVariables() - bitIndex - 1));
}
}
if (this->enumerateDontCareMetaVariables || metaVariableAppearsInCube) {
currentValuation.setBitVectorValue(metaVariable, intValue + ddMetaVariable.getLow());
}
}
// If all meta variables are to be enumerated or the meta variable appeared in the cube, we register the
// missing bits to later enumerate all possible valuations.
if (this->enumerateDontCareMetaVariables || metaVariableAppearsInCube) {
relevantDontCareDdVariables.insert(relevantDontCareDdVariables.end(), localRelenvantDontCareDdVariables.begin(), localRelenvantDontCareDdVariables.end());
}
}
// Finally, reset the cube counter.
this->cubeCounter = 0;
}
template<typename ValueType>
void AddIterator<DdType::Sylvan, ValueType>::treatNextInCube() {
// Start by increasing the counter and check which bits we need to set/unset in the new valuation.
++this->cubeCounter;
for (uint_fast64_t index = 0; index < this->relevantDontCareDdVariables.size(); ++index) {
auto const& ddMetaVariable = this->ddManager->getMetaVariable(std::get<0>(this->relevantDontCareDdVariables[index]));
if (ddMetaVariable.getType() == MetaVariableType::Bool) {
if ((this->cubeCounter & (1ull << index)) != 0) {
currentValuation.setBooleanValue(std::get<0>(this->relevantDontCareDdVariables[index]), true);
} else {
currentValuation.setBooleanValue(std::get<0>(this->relevantDontCareDdVariables[index]), false);
}
} else {
storm::expressions::Variable const& metaVariable = std::get<0>(this->relevantDontCareDdVariables[index]);
if ((this->cubeCounter & (1ull << index)) != 0) {
currentValuation.setBitVectorValue(metaVariable, ((currentValuation.getBitVectorValue(metaVariable) - ddMetaVariable.getLow()) | (1ull << std::get<1>(this->relevantDontCareDdVariables[index]))) + ddMetaVariable.getLow());
} else {
currentValuation.setBitVectorValue(metaVariable, ((currentValuation.getBitVectorValue(metaVariable) - ddMetaVariable.getLow()) & ~(1ull << std::get<1>(this->relevantDontCareDdVariables[index]))) + ddMetaVariable.getLow());
}
}
}
}
template class AddIterator<DdType::Sylvan, double>;
template class AddIterator<DdType::Sylvan, uint_fast64_t>;
template class AddIterator<DdType::Sylvan, storm::RationalNumber>;
#ifdef STORM_HAVE_CARL
template class AddIterator<DdType::Sylvan, storm::RationalFunction>;
#endif
}
}
| 58.235 | 621 | 0.606251 | [
"vector"
] |
03c710b1d4e0fca9dbece7a6a9a532ff127a6a64 | 128,420 | cpp | C++ | 3rdparty/GPSTk/ext/lib/Geomatics/EarthOrientation.cpp | mfkiwl/ICE | e660d031bb1bcea664db1de4946fd8781be5b627 | [
"MIT"
] | 50 | 2019-10-12T01:22:20.000Z | 2022-02-15T23:28:26.000Z | 3rdparty/GPSTk/ext/lib/Geomatics/EarthOrientation.cpp | wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation | 2f1ff054b7c5059da80bb3b2f80c05861a02cc36 | [
"MIT"
] | null | null | null | 3rdparty/GPSTk/ext/lib/Geomatics/EarthOrientation.cpp | wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation | 2f1ff054b7c5059da80bb3b2f80c05861a02cc36 | [
"MIT"
] | 14 | 2019-11-05T01:50:29.000Z | 2021-08-06T06:23:44.000Z | //============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 3.0 of the License, or
// any later version.
//
// The GPSTk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with GPSTk; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
/// @file EarthOrientation.cpp
/// class EarthOrientation encapsulates the Earth orientation parameters or EOPs.
/// Also, this class includes several static functions that implement the models in
/// the IERS Conventions, many of which involve the EOPs.
/// Cf. classes EOPStore and SolarSystem.
//------------------------------------------------------------------------------------
// system includes
#include <fstream>
// GPSTk
#include "MiscMath.hpp"
#include "logstream.hpp"
#include "EarthOrientation.hpp"
//------------------------------------------------------------------------------------
using namespace std;
namespace gpstk
{
//---------------------------------------------------------------------------------
// constants
//---------------------------------------------------------------------------------
// JulianEpoch is the epoch for CoordTransTime
//const double EarthOrientation::JulianEpoch=2451545.0; // JD
const double EarthOrientation::JulianEpoch=51544.5; // MJD
const int EarthOrientation::intJulianEpoch=51544;
// pi
const double EarthOrientation::TWOPI=6.283185307179586476925287;
const double EarthOrientation::PI=(TWOPI/2.);
const double EarthOrientation::HALFPI=(TWOPI/4.);
// convert degrees to radians
const double EarthOrientation::DEG_TO_RAD=0.0174532925199432957692369;
// convert radians to degrees
const double EarthOrientation::RAD_TO_DEG=57.29577951308232087679815;
// convert arc seconds to radians
const double EarthOrientation::ARCSEC_TO_RAD=4.848136811095359935899141e-6;
// arcseconds in 360 degrees
const double EarthOrientation::ARCSEC_PER_CIRCLE=1296000.0;
//---------------------------------------------------------------------------------
ostream& operator<<(ostream& os, const EarthOrientation& eo)
{
os << " " << fixed << setw(10) << setprecision(6) << eo.xp
<< " " << setw(10) << setprecision(6) << eo.yp
<< " " << setw(11) << setprecision(7) << eo.UT1mUTC
<< " " << eo.convention.asString();
return os;
}
//---------------------------------------------------------------------------------
// EOP interpolation and correction routines - internal use only
/// Compute fundamental arguments at CoordTransTime T, which are
/// GMST+pi, L, Lp, F, D, Omega. These are valid for interpolating EOPs in both
/// IERS 2003 and 2010 conventions.
/// param T CoordTransTime for epoch of interest
/// param args array of 6 fundamental arguments at T, units radians
static void computeFundamentalArgs(const double& T, double args[6]) throw();
/// Corrections to EOPs xp,yp,UT1mUTC for diurnal and semi-diurnal variations
/// due to ocean tides. Based on IERS routine ortho_eop.f from the USNO web site
/// for the 2010 conventions (NB the 2003 version of ortho_eop is nominally
/// different, however in fact the algorithm and constants are the same; the only
/// difference is that the 2003 algorithm (FTN) is single precision).
/// param mjd time (UTC) of interest
/// param dxp correction to xp in arcseconds
/// param dyp correction to yp in arcseconds
/// param dUT correction to UT1mUTC in seconds
static void correctEOPOceanTides(const double& mjd,
double& dxp, double& dyp, double& dUT) throw();
/// Corrections to Earth rotation due to zonal tides using USNO IERS2010 algorithm.
/// param args array of 6 fundamental arguments at T, units radians
/// NB result of computeFundamentalArgs(); args[0] (=GMST+pi) is not used
/// param dUT correction to UT1mUTC in seconds
/// param dld correction to length of day in seconds/day
/// param dom correction to yp in radians per second
static void correctEarthRotationZonalTides(const double args[6],
double& dUT, double& dld, double& dom) throw();
/// Corrections to UT1 and length of day (LOD) due to zonal tides using USNO
/// IERS2003 algorithm.
/// param args array of 6 fundamental arguments at T, units radians
/// NB result of computeFundamentalArgs(); args[0] (=GMST+pi) is not used
/// param dUT correction to UT1mUTC in seconds
/// param dld correction to length of day in seconds/day
/// param dom correction to yp in radians per second
static void correctEarthRotationZonalTides2003(const double args[6],
double& dUT, double& dld, double& dom) throw();
/// Corrections to UT1 and length of day (LOD) due to subdiurnal librations
/// using USNO IERS2010 algorithm.
/// param args array of 6 fundamental arguments at T (CoordTransTime), in radians
/// NB result of computeFundamentalArgs()
/// param dUT correction to UT1mUTC in seconds
/// param dld correction to length of day in seconds/day
static void correctEarthRotationLibrations(const double args[6],
double& dUT, double& dld) throw();
// Given parallel arrays of length four containing the values from EOPStore
// for time (int MJD) and EOPs xp, yp, and UT1mUTC, where the time of interest
// t lies within the values of the time array, interpolate and apply
// corrections to determine the EOPs at t, using the algorithm prescribed
// by the given IERS convention.
// param t EphTime at which to compute EOPs
// param time vector of length 4 of consecutive MJDs from EOPStore;
// t must lie within this timespan.
// param X vector of length 4 of consecutive xp from EOPStore.
// param Y vector of length 4 of consecutive yp from EOPStore.
// param dT vector of length 4 of consecutive UT1mUTC from EOPStore.
// param conv the IERSConvention to be used.
// return EarthOrientation EOPs at time t.
void EarthOrientation::interpolateEOP(const EphTime& t,
const vector<double>& time,
const vector<double>& X,
const vector<double>& Y,
vector<double>& dT,
const IERSConvention& in_conv)
throw(InvalidRequest)
{
int i,j;
double dxp,dyp,dUT,dlod,domega;
double args[6];
// set the convention for this object
convention = in_conv;
// first get MJD(UTC), for the Lagrange interpolation
EphTime ttag(t);
ttag.convertSystemTo(TimeSystem::UTC);
double mjdUTC(ttag.dMJD());
// now convert to TT, for the corrections algorithms
ttag.convertSystemTo(TimeSystem::TT);
double mjd(ttag.dMJD());
double T = (mjd - 51544.5)/36525.0;
// ----------------------------------------------------------------
// step 1 : Lagrange interpolation of xp and yp
double err;
xp = LagrangeInterpolation(time,X,mjdUTC,err); // arcsec
yp = LagrangeInterpolation(time,Y,mjdUTC,err); // arcsec
//LOG(INFO) << " -> " << fixed << setprecision(10) << mjdUTC
// << " " << setprecision(15) << xp << " " << yp;
// 1a. remove long period tides from UT1-UTC data -------------------
// NB don't need ttag anymore but do need mjd and T.
for(i=0; i<time.size(); i++) {
ttag.setMJD(time[i]);
ttag.setTimeSystem(TimeSystem::UTC);
ttag.convertSystemTo(TimeSystem::TT);
double Ttemp = (ttag.dMJD() - 51544.5)/36525.0;
computeFundamentalArgs(Ttemp, args);
if(convention == IERSConvention::IERS2010)
correctEarthRotationZonalTides(args, dUT, dlod, domega);
else
correctEarthRotationZonalTides2003(args, dUT, dlod, domega);
dT[i] -= dUT;
//LOG(INFO) << " UT " <<fixed<< setprecision(10) << time[i] << " " << dT[i];
}
// 1b. interpolate UT1-UTC -------------------------------------------
UT1mUTC = LagrangeInterpolation(time,dT,mjdUTC,err); // seconds
//LOG(INFO) << " -> " << fixed << setprecision(10) << mjdUTC
// << " " << setprecision(15) << UT1mUTC;
// ----------------------------------------------------------------
// step 2 : Compute fundamental arguments for use in corrections
computeFundamentalArgs(T, args);
//LOG(INFO) << fixed
// << "T(" << setprecision(2) << mjd << ")=" << setprecision(15) << T
// << "\nGMST(" << setprecision(2) << mjd << ")="<<setprecision(15)<< args[0]
// << "\nL(" << setprecision(2) << mjd << ")=" << setprecision(15) << args[1]
// << "\nLp(" << setprecision(2) << mjd << ")=" << setprecision(15) << args[2]
// << "\nF(" << setprecision(2) << mjd << ")=" << setprecision(15) << args[3]
// << "\nD(" << setprecision(2) << mjd << ")=" << setprecision(15) << args[4]
// << "\nOm(" << setprecision(2) << mjd << ")=" << setprecision(15)<< args[5];
// ----------------------------------------------------------------
// step 3 : Compute corrections and apply to eop
// 3a. restore long period tides to UT1-UTC --------------------------
// Corrections to Earth rotation due to zonal tides using USNO algorithm
// differences between 2003 and 2010 are very small, and only in the Zonal tides
if(convention == IERSConvention::IERS2010)
correctEarthRotationZonalTides(args, dUT, dlod, domega);
else
correctEarthRotationZonalTides2003(args, dUT, dlod, domega);
UT1mUTC += dUT;
//LOG(INFO) << " Zonal tides UT1 correction " <<fixed<<setprecision(15) << dUT;
// step 3b. --------------------------------------
// Corrections to EOP due to diurnal and semidiurnal effects of ocean tides
// using USNO algorithm
correctEOPOceanTides(mjd, dxp, dyp, dUT);
xp += dxp;
yp += dyp;
UT1mUTC += dUT;
//LOG(INFO) << " Tides corrections " << fixed << setprecision(15)
// << dxp << " " << dyp << " " << dUT;
// step 3c. --------------------------------------
// correct for librations - a few microarcseconds but high frequency
//correctEarthRotationLibrations(args, dUT, dlod);
//UT1mUTC += dUT;
//LOG(INFO) << " Librations UT1 correction " << fixed<<setprecision(15) << dUT;
}
//---------------------------------------------------------------------------------
void computeFundamentalArgs(const double& T, double args[6]) throw()
{
// compute arguments and their time derivatives GMST+pi, L, Lp, F, D, Omega
// units are radians and radians/day
// NB to compute corrections to length of day (LOD), remove '//LOD' everywhere
//LOD double dargs[6];
//LOD static const double AS_TO_RAD_PER_DAY=(ARCSEC_TO_RAD/36525.0);
// GMST+pi
// GMST in seconds of day. NB 3155760000.0 = 876600.0*3600.0
double GMST = ::fmod( 67310.54841
+ T*(3155760000.0 + 8640184.812866
+ T*T*(0.093104 + T*(-6.2e-6))), 86400.0); // seconds of day
// convert to arcsec, then radians : 360*3600 arcsec / 24*3600 sec = 15 as/sec
GMST *= 15.0 * EarthOrientation::ARCSEC_TO_RAD;
args[0] = ::fmod(GMST + EarthOrientation::PI, EarthOrientation::TWOPI);
//LOD dargs[0] = 15.0*(876600*3600 + 8640184.812866
//LOD + T*(2.*0.093104 - T*(3.*6.2e-6))) * AS_TO_RAD_PER_DAY;
// fundamental arguments cf. IERS 2010 conventions TN36 5.7.2 eqn 5.43
// L = mean anomaly of moon
args[1] = EarthOrientation::L(T);
//LOD dargs[1] = (1717915923.2178 + T*(2.*31.8792
//LOD + T*(3.*0.051635 + T*(-4.*0.00024470)))) * AS_TO_RAD_PER_DAY;
// Lp = mean anomaly of sun
args[2] = EarthOrientation::Lp(T);
//LOD dargs[2] = (129596581.0481 + T*(-2.*0.5532
//LOD + T*(-3.*0.000136 + T*(-4.*0.00001149)))) * AS_TO_RAD_PER_DAY;
// F = mean anomaly of moon minus Omega
args[3] = EarthOrientation::F(T);
//LOD dargs[3] = (1739527262.8478 + T*(-2.*12.7512
//LOD + T*(-3.*0.001037 + T*(4.*0.00000417)))) * AS_TO_RAD_PER_DAY;
// D = mean elongation moon from sun
args[4] = EarthOrientation::D(T);
//LOD dargs[4] = (1602961601.2090 + T*(-2.*6.3706
//LOD + T*(+3.*0.006593 + T*(-4.*0.00003169)))) * AS_TO_RAD_PER_DAY;
// Omega = mean longitude of ascending node of moon
args[5] = EarthOrientation::Omega2003(T);
//LOD dargs[5] = (-6962890.2665 + T*(2.*7.4722
//LOD + T*(3.*0.007702 + T*(-4.*0.00005939)))) * AS_TO_RAD_PER_DAY;
} // end computeFundamentalArgs()
//---------------------------------------------------------------------------------
void correctEOPOceanTides(const double& mjd, double& dxp, double& dyp, double& dUT)
throw()
{
// compute time dependent part of second degree diurnal and semidiurnal
// tidal potential from the dominant spectral lines of the
// Cartwright-Tayler-Edden harmonic decomposition.
// define the orthotide weight factors
static const double fact[][2] = {
{ 0.0298, 0.0200 },
{ 0.1408, 0.0905 },
{ 0.0805, 0.0638 },
{ 0.6002, 0.3476 },
{ 0.3025, 0.1645 },
{ 0.1517, 0.0923 }
};
//for(int kk=0; kk<6; kk++)
//LOG(INFO) << "SP(" << kk << ")=" << fixed << setprecision(5)
// << setw(9) << fact[kk][0] << setw(9) << fact[kk][1];
// tidal potential model for 71 diurnal and semidiurnal lines
typedef struct {
int nj,mj; // nj is always 2!
double hs, phase, freq;
} Coeff;
static const Coeff C[] = {
{ 2, 1, -1.94, 9.0899831, 5.18688050 },
{ 2, 1, -1.25, 8.8234208, 5.38346657 },
{ 2, 1, -6.64, 12.1189598, 5.38439079 },
{ 2, 1, -1.51, 1.4425700, 5.41398343 },
{ 2, 1, -8.02, 4.7381090, 5.41490765 },
{ 2, 1, -9.47, 4.4715466, 5.61149372 },
{ 2, 1, -50.20, 7.7670857, 5.61241794 },
{ 2, 1, -1.80, -2.9093042, 5.64201057 },
{ 2, 1, -9.54, 0.3862349, 5.64293479 },
{ 2, 1, 1.52, -3.1758666, 5.83859664 },
{ 2, 1, -49.45, 0.1196725, 5.83952086 },
{ 2, 1,-262.21, 3.4152116, 5.84044508 },
{ 2, 1, 1.70, 12.8946194, 5.84433381 },
{ 2, 1, 3.43, 5.5137686, 5.87485066 },
{ 2, 1, 1.94, 6.4441883, 6.03795537 },
{ 2, 1, 1.37, -4.2322016, 6.06754801 },
{ 2, 1, 7.41, -0.9366625, 6.06847223 },
{ 2, 1, 20.62, 8.5427453, 6.07236095 },
{ 2, 1, 4.14, 11.8382843, 6.07328517 },
{ 2, 1, 3.94, 1.1618945, 6.10287781 },
{ 2, 1, -7.14, 5.9693878, 6.24878055 },
{ 2, 1, 1.37, -1.2032249, 6.26505830 },
{ 2, 1,-122.03, 2.0923141, 6.26598252 },
{ 2, 1, 1.02, -1.7847596, 6.28318449 },
{ 2, 1, 2.89, 8.0679449, 6.28318613 },
{ 2, 1, -7.30, 0.8953321, 6.29946388 },
{ 2, 1, 368.78, 4.1908712, 6.30038810 },
{ 2, 1, 50.01, 7.4864102, 6.30131232 },
{ 2, 1, -1.08, 10.7819493, 6.30223654 },
{ 2, 1, 2.93, 0.3137975, 6.31759007 },
{ 2, 1, 5.25, 6.2894282, 6.33479368 },
{ 2, 1, 3.95, 7.2198478, 6.49789839 },
{ 2, 1, 20.62, -0.1610030, 6.52841524 },
{ 2, 1, 4.09, 3.1345361, 6.52933946 },
{ 2, 1, 3.42, 2.8679737, 6.72592553 },
{ 2, 1, 1.69, -4.5128771, 6.75644239 },
{ 2, 1, 11.29, 4.9665307, 6.76033111 },
{ 2, 1, 7.23, 8.2620698, 6.76125533 },
{ 2, 1, 1.51, 11.5576089, 6.76217955 },
{ 2, 1, 2.16, 0.6146566, 6.98835826 },
{ 2, 1, 1.38, 3.9101957, 6.98928248 },
{ 2, 2, 1.80, 20.6617051, 11.45675174 },
{ 2, 2, 4.67, 13.2808543, 11.48726860 },
{ 2, 2, 16.01, 16.3098310, 11.68477889 },
{ 2, 2, 19.32, 8.9289802, 11.71529575 },
{ 2, 2, 1.30, 5.0519065, 11.73249771 },
{ 2, 2, -1.02, 15.8350306, 11.89560406 },
{ 2, 2, -4.51, 8.6624178, 11.91188181 },
{ 2, 2, 120.99, 11.9579569, 11.91280603 },
{ 2, 2, 1.13, 8.0808832, 11.93000800 },
{ 2, 2, 22.98, 4.5771061, 11.94332289 },
{ 2, 2, 1.06, 0.7000324, 11.96052486 },
{ 2, 2, -1.90, 14.9869335, 12.11031632 },
{ 2, 2, -2.18, 11.4831564, 12.12363121 },
{ 2, 2, -23.58, 4.3105437, 12.13990896 },
{ 2, 2, 631.92, 7.6060827, 12.14083318 },
{ 2, 2, 1.92, 3.7290090, 12.15803515 },
{ 2, 2, -4.66, 10.6350594, 12.33834347 },
{ 2, 2, -17.86, 3.2542086, 12.36886033 },
{ 2, 2, 4.47, 12.7336164, 12.37274905 },
{ 2, 2, 1.97, 16.0291555, 12.37367327 },
{ 2, 2, 17.20, 10.1602590, 12.54916865 },
{ 2, 2, 294.00, 6.2831853, 12.56637061 },
{ 2, 2, -2.46, 2.4061116, 12.58357258 },
{ 2, 2, -1.02, 5.0862033, 12.59985198 },
{ 2, 2, 79.96, 8.3817423, 12.60077620 },
{ 2, 2, 23.83, 11.6772814, 12.60170041 },
{ 2, 2, 2.59, 14.9728205, 12.60262463 },
{ 2, 2, 4.47, 4.0298682, 12.82880334 },
{ 2, 2, 1.95, 7.3254073, 12.82972756 },
{ 2, 2, 1.17, 9.1574019, 13.06071921 }
};
static const double dt(2.0);
static const double TWOPI(6.283185307179586476925287);
int j,k,n,m;
double a[2][3], b[2][3], dt60, pinm, alpha;
// compute time dependent potential matrix
for(k=0; k<3; ++k) {
dt60 = (mjd - (k-1)*dt) - 37076.5;
a[0][k] = a[1][k] = 0.0;
b[0][k] = b[1][k] = 0.0;
for(j=0; j<71; ++j) {
n = C[j].nj; // 2!
m = C[j].mj; // 1 or 2
pinm = double((n+m)%2) * TWOPI / 4.0;
alpha = ::fmod(C[j].phase - pinm, TWOPI)
+ ::fmod(C[j].freq * dt60, TWOPI);
a[m-1][k] += C[j].hs * ::cos(alpha);
b[m-1][k] -= C[j].hs * ::sin(alpha);
}
}
// orthogonalize response terms
double ap,am,bp,bm,p[3][2],q[3][2];
for(m=0; m<2; ++m) {
ap = a[m][2] + a[m][0];
am = a[m][2] - a[m][0];
bp = b[m][2] + b[m][0];
bm = b[m][2] - b[m][0];
p[0][m] = fact[0][m] * a[m][1];
p[1][m] = fact[1][m] * a[m][1] - fact[2][m]*ap;
p[2][m] = fact[3][m] * a[m][1] - fact[4][m]*ap + fact[5][m]*bm;
q[0][m] = fact[0][m] * b[m][1];
q[1][m] = fact[1][m] * b[m][1] - fact[2][m]*bp;
q[2][m] = fact[3][m] * b[m][1] - fact[4][m]*bp - fact[5][m]*am;
a[m][0] = p[0][m];
a[m][1] = p[1][m];
a[m][2] = p[2][m];
b[m][0] = q[0][m];
b[m][1] = q[1][m];
b[m][2] = q[2][m];
}
// fill partials vector
double h[12];
for(j=0,m=0; m<2; ++m) {
for(k=0; k<3; ++k) {
h[j] = a[m][k];
h[j+1] = b[m][k];
j += 2;
}
}
//for(k=0; k<12; k++)
//LOG(INFO) << "H(" << k << ")=" << fixed << setprecision(15) << h[k];
// orthoweights
static const double orthowts[][3] = {
{ -6.77832, 14.86283, -1.76335 },
{-14.86323, -6.77846, 1.03364 },
{ 0.47884, 1.45234, -0.27553 },
{ -1.45303, 0.47888, 0.34569 },
{ 0.16406, -0.42056, -0.12343 },
{ 0.42030, 0.16469, -0.10146 },
{ 0.09398, 15.30276, -0.47119 },
{ 25.73054, -4.30615, 1.28997 },
{ -4.77974, 0.07564, -0.19336 },
{ 0.28080, 2.28321, 0.02724 },
{ 1.94539, -0.45717, 0.08955 },
{ -0.73089, -1.62010, 0.04726 }
};
//for(k=0; k<12; k++)
//LOG(INFO) << "ORTHOW(" << k << ")=" << fixed << setprecision(5)
// << setw(9) << orthowts[k][0]
// << setw(9) << orthowts[k][1]
// << setw(9) << orthowts[k][2];
double eop[3];
for(k=0; k<3; ++k) {
eop[k] = 0.0;
for(j=0; j<12; ++j)
eop[k] += h[j] * orthowts[j][k];
}
// convert to arcsec and seconds
dxp = eop[0] * 1.e-6;
dyp = eop[1] * 1.e-6;
dUT = eop[2] * 1.e-6;
}
//---------------------------------------------------------------------------------
// Corrections to Earth rotation due to zonal tides using USNO algorithm
// param args array of 6 fundamental arguments at T, units radians
// NB args[0] (=GMST+pi) is not used
// param dUT correction to UT1mUTC in seconds
// param dld correction to length of day in seconds/day
// param dom correction to yp in radians per second
void correctEarthRotationZonalTides(const double args[6],
double& dUT, double& dld, double& dom)
throw()
{
// constants
static const double TWOPI(6.283185307179586476925287);
// luni-solar coefficients in argument multiplying L Lp F D Omega, 62 terms
// and coefficients of DUT sin, cos; DLOD cos, sin; DOMEGA cos, sin
typedef struct {
int nargs[5];
double dutsin, dutcos, dldcos, dldsin, domcos, domsin; // yes its sc cs cs
} Coeff;
static const Coeff C[] = {
{ { 1, 0, 2, 2, 2 }, -0.0235, 0.0000, 0.2617, 0.0000, -0.2209, 0.0000 },
{ { 2, 0, 2, 0, 1 }, -0.0404, 0.0000, 0.3706, 0.0000, -0.3128, 0.0000 },
{ { 2, 0, 2, 0, 2 }, -0.0987, 0.0000, 0.9041, 0.0000, -0.7630, 0.0000 },
{ { 0, 0, 2, 2, 1 }, -0.0508, 0.0000, 0.4499, 0.0000, -0.3797, 0.0000 },
{ { 0, 0, 2, 2, 2 }, -0.1231, 0.0000, 1.0904, 0.0000, -0.9203, 0.0000 },
{ { 1, 0, 2, 0, 0 }, -0.0385, 0.0000, 0.2659, 0.0000, -0.2244, 0.0000 },
{ { 1, 0, 2, 0, 1 }, -0.4108, 0.0000, 2.8298, 0.0000, -2.3884, 0.0000 },
{ { 1, 0, 2, 0, 2 }, -0.9926, 0.0000, 6.8291, 0.0000, -5.7637, 0.0000 },
{ { 3, 0, 0, 0, 0 }, -0.0179, 0.0000, 0.1222, 0.0000, -0.1031, 0.0000 },
{ {-1, 0, 2, 2, 1 }, -0.0818, 0.0000, 0.5384, 0.0000, -0.4544, 0.0000 },
{ {-1, 0, 2, 2, 2 }, -0.1974, 0.0000, 1.2978, 0.0000, -1.0953, 0.0000 },
{ { 1, 0, 0, 2, 0 }, -0.0761, 0.0000, 0.4976, 0.0000, -0.4200, 0.0000 },
{ { 2, 0, 2, -2, 2 }, 0.0216, 0.0000,-0.1060, 0.0000, 0.0895, 0.0000 },
{ { 0, 1, 2, 0, 2 }, 0.0254, 0.0000,-0.1211, 0.0000, 0.1022, 0.0000 },
{ { 0, 0, 2, 0, 0 }, -0.2989, 0.0000, 1.3804, 0.0000, -1.1650, 0.0000 },
{ { 0, 0, 2, 0, 1 }, -3.1873, 0.2010,14.6890, 0.9266,-12.3974,-0.7820 },
{ { 0, 0, 2, 0, 2 }, -7.8468, 0.5320,36.0910, 2.4469,-30.4606,-2.0652 },
{ { 2, 0, 0, 0, -1 }, 0.0216, 0.0000,-0.0988, 0.0000, 0.0834, 0.0000 },
{ { 2, 0, 0, 0, 0 }, -0.3384, 0.0000, 1.5433, 0.0000, -1.3025, 0.0000 },
{ { 2, 0, 0, 0, 1 }, 0.0179, 0.0000,-0.0813, 0.0000, 0.0686, 0.0000 },
{ { 0, -1, 2, 0, 2 }, -0.0244, 0.0000, 0.1082, 0.0000, -0.0913, 0.0000 },
{ { 0, 0, 0, 2, -1 }, 0.0470, 0.0000,-0.2004, 0.0000, 0.1692, 0.0000 },
{ { 0, 0, 0, 2, 0 }, -0.7341, 0.0000, 3.1240, 0.0000, -2.6367, 0.0000 },
{ { 0, 0, 0, 2, 1 }, -0.0526, 0.0000, 0.2235, 0.0000, -0.1886, 0.0000 },
{ { 0, -1, 0, 2, 0 }, -0.0508, 0.0000, 0.2073, 0.0000, -0.1749, 0.0000 },
{ { 1, 0, 2, -2, 1 }, 0.0498, 0.0000,-0.1312, 0.0000, 0.1107, 0.0000 },
{ { 1, 0, 2, -2, 2 }, 0.1006, 0.0000,-0.2640, 0.0000, 0.2228, 0.0000 },
{ { 1, 1, 0, 0, 0 }, 0.0395, 0.0000,-0.0968, 0.0000, 0.0817, 0.0000 },
{ {-1, 0, 2, 0, 0 }, 0.0470, 0.0000,-0.1099, 0.0000, 0.0927, 0.0000 },
{ {-1, 0, 2, 0, 1 }, 0.1767, 0.0000,-0.4115, 0.0000, 0.3473, 0.0000 },
{ {-1, 0, 2, 0, 2 }, 0.4352, 0.0000,-1.0093, 0.0000, 0.8519, 0.0000 },
{ { 1, 0, 0, 0, -1 }, 0.5339, 0.0000,-1.2224, 0.0000, 1.0317, 0.0000 },
{ { 1, 0, 0, 0, 0 }, -8.4046, 0.2500,19.1647, 0.5701,-16.1749,-0.4811 },
{ { 1, 0, 0, 0, 1 }, 0.5443, 0.0000,-1.2360, 0.0000, 1.0432, 0.0000 },
{ { 0, 0, 0, 1, 0 }, 0.0470, 0.0000,-0.1000, 0.0000, 0.0844, 0.0000 },
{ { 1, -1, 0, 0, 0 }, -0.0555, 0.0000, 0.1169, 0.0000, -0.0987, 0.0000 },
{ {-1, 0, 0, 2, -1 }, 0.1175, 0.0000,-0.2332, 0.0000, 0.1968, 0.0000 },
{ {-1, 0, 0, 2, 0 }, -1.8236, 0.0000, 3.6018, 0.0000, -3.0399, 0.0000 },
{ {-1, 0, 0, 2, 1 }, 0.1316, 0.0000,-0.2587, 0.0000, 0.2183, 0.0000 },
{ { 1, 0, -2, 2, -1 }, 0.0179, 0.0000,-0.0344, 0.0000, 0.0290, 0.0000 },
{ {-1, -1, 0, 2, 0 }, -0.0855, 0.0000, 0.1542, 0.0000, -0.1302, 0.0000 },
{ { 0, 2, 2, -2, 2 }, -0.0573, 0.0000, 0.0395, 0.0000, -0.0333, 0.0000 },
{ { 0, 1, 2, -2, 1 }, 0.0329, 0.0000,-0.0173, 0.0000, 0.0146, 0.0000 },
{ { 0, 1, 2, -2, 2 }, -1.8847, 0.0000, 0.9726, 0.0000, -0.8209, 0.0000 },
{ { 0, 0, 2, -2, 0 }, 0.2510, 0.0000,-0.0910, 0.0000, 0.0768, 0.0000 },
{ { 0, 0, 2, -2, 1 }, 1.1703, 0.0000,-0.4135, 0.0000, 0.3490, 0.0000 },
{ { 0, 0, 2, -2, 2 },-49.7174, 0.4330,17.1056, 0.1490,-14.4370,-0.1257 },
{ { 0, 2, 0, 0, 0 }, -0.1936, 0.0000, 0.0666, 0.0000, -0.0562, 0.0000 },
{ { 2, 0, 0, -2, -1 }, 0.0489, 0.0000,-0.0154, 0.0000, 0.0130, 0.0000 },
{ { 2, 0, 0, -2, 0 }, -0.5471, 0.0000, 0.1670, 0.0000, -0.1409, 0.0000 },
{ { 2, 0, 0, -2, 1 }, 0.0367, 0.0000,-0.0108, 0.0000, 0.0092, 0.0000 },
{ { 0, -1, 2, -2, 1 }, -0.0451, 0.0000, 0.0082, 0.0000, -0.0069, 0.0000 },
{ { 0, 1, 0, 0, -1 }, 0.0921, 0.0000,-0.0167, 0.0000, 0.0141, 0.0000 },
{ { 0, -1, 2, -2, 2 }, 0.8281, 0.0000,-0.1425, 0.0000, 0.1202, 0.0000 },
{ { 0, 1, 0, 0, 0 },-15.8887, 0.1530, 2.7332, 0.0267, -2.3068,-0.0222 },
{ { 0, 1, 0, 0, 1 }, -0.1382, 0.0000, 0.0225, 0.0000, -0.0190, 0.0000 },
{ { 1, 0, 0, -1, 0 }, 0.0348, 0.0000,-0.0053, 0.0000, 0.0045, 0.0000 },
{ { 2, 0, -2, 0, 0 }, -0.1372, 0.0000,-0.0079, 0.0000, 0.0066, 0.0000 },
{ {-2, 0, 2, 0, 1 }, 0.4211, 0.0000,-0.0203, 0.0000, 0.0171, 0.0000 },
{ {-1, 1, 0, 1, 0 }, -0.0404, 0.0000, 0.0008, 0.0000, -0.0007, 0.0000 },
{ { 0, 0, 0, 0, 2 }, 7.8998, 0.0000, 0.1460, 0.0000, -0.1232, 0.0000 },
{ { 0, 0, 0, 0, 1 }, -1617.2681,0.0000,-14.9471,0.0000, 12.6153,0.0000}
};
// number of coefficients
static const int N = int(sizeof(C) / sizeof(Coeff));
dUT = dld = dom = 0.0;
for(int i=0; i<N; i++) {
double arg(0.0);
for(int j=0; j<5; j++)
arg += double(C[i].nargs[j]) * args[j+1]; // NB args[0] is not used
arg = ::fmod(arg,TWOPI);
double sarg = ::sin(arg);
double carg = ::cos(arg);
dUT += C[i].dutsin * sarg + C[i].dutcos * carg;
dld += C[i].dldsin * sarg + C[i].dldcos * carg;
dom += C[i].domsin * sarg + C[i].domcos * carg;
}
// change units to seconds, seconds/day, and radians/sec
dUT *= 1.e-4;
dld *= 1.e-5;
dom *= 1.e-14;
} // end correctEarthRotationZonalTides()
//---------------------------------------------------------------------------------
// Corrections to Earth rotation due to zonal tides using USNO IERS2003 algorithm
// param args array of 6 fundamental arguments at T, units radians
// NB args[0] (=GMST+pi) is not used
// param dUT correction to UT1mUTC in seconds
// param dld correction to length of day in seconds/day
// param dom correction to yp in radians per second
void correctEarthRotationZonalTides2003(const double args[6],
double& dUT, double& dld, double& dom)
throw()
{
// constants
static const double TWOPI(6.283185307179586476925287);
// luni-solar multipliers in argument L Lp F D Omega, 62 terms
// and coefficients of DUT sin, cos; DLOD cos, sin; DOMEGA cos, sin
typedef struct {
int nargs[5];
double dutsin, dutcos, dldcos, dldsin, domcos, domsin; // yes its sc cs cs
} Coeff;
static const Coeff C[] = {
{ { 1, 0, 2, 2, 2 }, -0.02, 0.00, 0.26, 0.00, -0.22, 0.00 },
{ { 2, 0, 2, 0, 1 }, -0.04, 0.00, 0.38, 0.00, -0.32, 0.00 },
{ { 2, 0, 2, 0, 2 }, -0.10, 0.00, 0.91, 0.00, -0.76, 0.00 },
{ { 0, 0, 2, 2, 1 }, -0.05, 0.00, 0.45, 0.00, -0.38, 0.00 },
{ { 0, 0, 2, 2, 2 }, -0.12, 0.00, 1.09, 0.01, -0.92,-0.01 },
{ { 1, 0, 2, 0, 0 }, -0.04, 0.00, 0.27, 0.00, -0.22, 0.00 },
{ { 1, 0, 2, 0, 1 }, -0.41, 0.00, 2.84, 0.02, -2.40,-0.01 },
{ { 1, 0, 2, 0, 2 }, -1.00, 0.01, 6.85, 0.04, -5.78,-0.03 },
{ { 3, 0, 0, 0, 0 }, -0.02, 0.00, 0.12, 0.00, -0.11, 0.00 },
{ {-1, 0, 2, 2, 1 }, -0.08, 0.00, 0.54, 0.00, -0.46, 0.00 },
{ {-1, 0, 2, 2, 2 }, -0.20, 0.00, 1.30, 0.01, -1.10,-0.01 },
{ { 1, 0, 0, 2, 0 }, -0.08, 0.00, 0.50, 0.00, -0.42, 0.00 },
{ { 2, 0, 2,-2, 2 }, 0.02, 0.00, -0.11, 0.00, 0.09, 0.00 },
{ { 0, 1, 2, 0, 2 }, 0.03, 0.00, -0.12, 0.00, 0.10, 0.00 },
{ { 0, 0, 2, 0, 0 }, -0.30, 0.00, 1.39, 0.01, -1.17,-0.01 },
{ { 0, 0, 2, 0, 1 }, -3.22, 0.02, 14.86, 0.09,-12.54,-0.08 },
{ { 0, 0, 2, 0, 2 }, -7.79, 0.05, 35.84, 0.22,-30.25,-0.18 },
{ { 2, 0, 0, 0,-1 }, 0.02, 0.00, -0.10, 0.00, 0.08, 0.00 },
{ { 2, 0, 0, 0, 0 }, -0.34, 0.00, 1.55, 0.01, -1.31,-0.01 },
{ { 2, 0, 0, 0, 1 }, 0.02, 0.00, -0.08, 0.00, 0.07, 0.00 },
{ { 0,-1, 2, 0, 2 }, -0.02, 0.00, 0.11, 0.00, -0.09, 0.00 },
{ { 0, 0, 0, 2,-1 }, 0.05, 0.00, -0.20, 0.00, 0.17, 0.00 },
{ { 0, 0, 0, 2, 0 }, -0.74, 0.00, 3.14, 0.02, -2.65,-0.02 },
{ { 0, 0, 0, 2, 1 }, -0.05, 0.00, 0.22, 0.00, -0.19, 0.00 },
{ { 0,-1, 0, 2, 0 }, -0.05, 0.00, 0.21, 0.00, -0.17, 0.00 },
{ { 1, 0, 2,-2, 1 }, 0.05, 0.00, -0.13, 0.00, 0.11, 0.00 },
{ { 1, 0, 2,-2, 2 }, 0.10, 0.00, -0.26, 0.00, 0.22, 0.00 },
{ { 1, 1, 0, 0, 0 }, 0.04, 0.00, -0.10, 0.00, 0.08, 0.00 },
{ {-1, 0, 2, 0, 0 }, 0.05, 0.00, -0.11, 0.00, 0.09, 0.00 },
{ {-1, 0, 2, 0, 1 }, 0.18, 0.00, -0.41, 0.00, 0.35, 0.00 },
{ {-1, 0, 2, 0, 2 }, 0.44, 0.00, -1.02, -0.01, 0.86, 0.01 },
{ { 1, 0, 0, 0,-1 }, 0.54, 0.00, -1.23, -0.01, 1.04, 0.01 },
{ { 1, 0, 0, 0, 0 }, -8.33, 0.06, 18.99, 0.13,-16.03,-0.11 },
{ { 1, 0, 0, 0, 1 }, 0.55, 0.00, -1.25, -0.01, 1.05, 0.01 },
{ { 0, 0, 0, 1, 0 }, 0.05, 0.00, -0.11, 0.00, 0.09, 0.00 },
{ { 1,-1, 0, 0, 0 }, -0.06, 0.00, 0.12, 0.00, -0.10, 0.00 },
{ {-1, 0, 0, 2,-1 }, 0.12, 0.00, -0.24, 0.00, 0.20, 0.00 },
{ {-1, 0, 0, 2, 0 }, -1.84, 0.01, 3.63, 0.02, -3.07,-0.02 },
{ {-1, 0, 0, 2, 1 }, 0.13, 0.00, -0.26, 0.00, 0.22, 0.00 },
{ { 1, 0,-2, 2,-1 }, 0.02, 0.00, -0.04, 0.00, 0.03, 0.00 },
{ {-1,-1 ,0, 2, 0 }, -0.09, 0.00, 0.16, 0.00, -0.13, 0.00 },
{ { 0, 2, 2,-2, 2 }, -0.06, 0.00, 0.04, 0.00, -0.03, 0.00 },
{ { 0, 1, 2,-2, 1 }, 0.03, 0.00, -0.02, 0.00, 0.01, 0.00 },
{ { 0, 1, 2,-2, 2 }, -1.91, 0.02, 0.98, 0.01, -0.83,-0.01 },
{ { 0, 0, 2,-2, 0 }, 0.26, 0.00, -0.09, 0.00, 0.08, 0.00 },
{ { 0, 0, 2,-2, 1 }, 1.18,-0.01, -0.42, 0.00, 0.35, 0.00 },
{ { 0, 0, 2,-2, 2 },-49.06, 0.43, 16.88, 0.15,-14.25,-0.13 },
{ { 0, 2, 0, 0, 0 }, -0.20, 0.00, 0.07, 0.00, -0.06, 0.00 },
{ { 2, 0, 0,-2,-1 }, 0.05, 0.00, -0.02, 0.00, 0.01, 0.00 },
{ { 2, 0, 0,-2, 0 }, -0.56, 0.01, 0.17, 0.00, -0.14, 0.00 },
{ { 2, 0, 0,-2, 1 }, 0.04, 0.00, -0.01, 0.00, 0.01, 0.00 },
{ { 0,-1, 2,-2, 1 }, -0.05, 0.00, 0.01, 0.00, -0.01, 0.00 },
{ { 0, 1, 0, 0,-1 }, 0.09, 0.00, -0.02, 0.00, 0.01, 0.00 },
{ { 0,-1, 2,-2, 2 }, 0.82,-0.01, -0.14, 0.00, 0.12, 0.00 },
{ { 0, 1, 0, 0, 0 },-15.65, 0.15, 2.69, 0.03, -2.27,-0.02 },
{ { 0, 1, 0, 0, 1 }, -0.14, 0.00, 0.02, 0.00, -0.02, 0.00 },
{ { 1, 0, 0,-1, 0 }, 0.03, 0.00, 0.00, 0.00, 0.00, 0.00 },
{ { 2, 0,-2, 0, 0 }, -0.14, 0.00, -0.02, 0.00, 0.02, 0.00 },
{ {-2, 0, 2, 0, 1 }, 0.43,-0.01, -0.02, 0.00, 0.02, 0.00 },
{ {-1, 1, 0, 1, 0 }, -0.04, 0.00, 0.00, 0.00, 0.00, 0.00 },
{ { 0, 0, 0, 0, 2 }, 8.20, 0.11, 0.15, 0.00, -0.13, 0.00 },
{ { 0, 0, 0, 0, 1 }, -1689.54,-25.04,-15.62,0.23,13.18,-0.20}
};
// number of coefficients (62)
static const int N = int(sizeof(C) / sizeof(Coeff));
dUT = dld = dom = 0.0;
for(int i=0; i<N; i++) {
double arg(0.0);
for(int j=0; j<5; j++)
arg += double(C[i].nargs[j]) * args[j+1]; // NB args[0] is not used
arg = ::fmod(arg,TWOPI);
double sarg = ::sin(arg);
double carg = ::cos(arg);
dUT += C[i].dutsin * sarg + C[i].dutcos * carg;
dld += C[i].dldsin * sarg + C[i].dldcos * carg;
dom += C[i].domsin * sarg + C[i].domcos * carg;
}
// change units to seconds, seconds/day, and radians/sec
dUT *= 1.e-4;
dld *= 1.e-5;
dom *= 1.e-14;
} // end correctEarthRotationZonalTides2003()
//---------------------------------------------------------------------------------
// Corrections to UT1 and length of day (LOD) due to subdiurnal librations
// using USNO IERS2010 algorithm.
// param args array of 6 fundamental arguments at T (CoordTransTime), in radians
// param dUT correction to UT1mUTC in seconds
// param dld correction to length of day in seconds/day
void correctEarthRotationLibrations(const double args[6], double& dUT, double& dld)
throw()
{
//static const double TWOPI(6.283185307179586476925287);
//static const double ARCSEC_TO_RAD=4.848136811095359935899141e-6;
//static const double ARCSEC_PER_CIRCLE(1296000.0);
// Coefficients of the quasi semidiurnal terms in dUT1, dLOD
// IERS Conventions (2010), Table 5.1b
typedef struct {
int nargs[6];
double period, dutsin, dutcos, dldsin, dldcos; // NB period is not used
} Coeff;
static const Coeff C[] = {
{ { 2, -2, 0, -2, 0, -2 }, 0.5377239, 0.05, -0.03, -0.3, -0.6 },
{ { 2, 0, 0, -2, -2, -2 }, 0.5363232, 0.06, -0.03, -0.4, -0.7 },
{ { 2, -1, 0, -2, 0, -2 }, 0.5274312, 0.35, -0.20, -2.4, -4.1 },
{ { 2, 1, 0, -2, -2, -2 }, 0.5260835, 0.07, -0.04, -0.5, -0.8 },
{ { 2, 0, 0, -2, 0, -1 }, 0.5175645, -0.07, 0.04, 0.5, 0.8 },
{ { 2, 0, 0, -2, 0, -2 }, 0.5175251, 1.75, -1.01, -12.2, -21.3 },
{ { 2, 1, 0, -2, 0, -2 }, 0.5079842, -0.05, 0.03, 0.3, 0.6 },
{ { 2, 0, -1, -2, 2, -2 }, 0.5006854, 0.04, -0.03, -0.3, -0.6 },
{ { 2, 0, 0, -2, 2, -2 }, 0.5000000, 0.76, -0.44, -5.5, -9.6 },
{ { 2, 0, 0, 0, 0, 0 }, 0.4986348, 0.21, -0.12, -1.5, -2.6 },
{ { 2, 0, 0, 0, 0, -1 }, 0.4985982, 0.06, -0.04, -0.4, -0.8 }
};
// number of coefficients (11)
static const int N = int(sizeof(C) / sizeof(Coeff));
dUT = dld = 0.0;
for(int i=0; i<N; ++i) {
double arg = 0.0;
for(int j=0; j<6; ++j)
arg += C[i].nargs[j] * args[j];
arg = ::fmod(arg, EarthOrientation::TWOPI);
double sarg = ::sin(arg);
double carg = ::cos(arg);
dUT += C[i].dutsin * sarg + C[i].dutcos * carg;
dld += C[i].dldsin * sarg + C[i].dldcos * carg;
}
// convert to seconds
dUT *= 1.e-6; // seconds
dld *= 1.e-6; // seconds per day
} // end correctEarthRotationLibrations()
//---------------------------------------------------------------------------------
// private member functions, used internally
//---------------------------------------------------------------------------------
// Compute the 'coordinate transformation time' which is the time since
// epoch J2000 = January 1 2000 12h UT = 2451545.0JD, divided by 36525 days.
// This quantity is used throughout the terrestrial / inertial coordinate
// transformations.
// Throws if the TimeSystem conversion fails (if t.system==TimeSystem::Unknown)
double EarthOrientation::CoordTransTime(EphTime ttag)
throw(Exception)
{
try {
EphTime t(ttag);
t.convertSystemTo(TimeSystem::TT);
//return (t.dMJD()-JulianEpoch)/36525.0;
// do in a way to maximize precision
int in = int(t.dMJD()-0.5)-intJulianEpoch;
double frac = 0.5+t.secOfDay()/86400.0;
if(frac > 1.0) frac -= 1.0;
return (double(in)/36525.0 + frac/36525.0);
}
catch(Exception& e) { GPSTK_RETHROW(e); }
}
//---------------------------------------------------------------------------------
// Return mean longitude of lunar ascending node, in radians,
// given T, the CoordTransTime at the Epoch of interest. (Ref: F5 pg 23)
// valid for IERS1996
double EarthOrientation::Omega(double T)
throw()
{
return ::fmod( 450160.398036
+ T*(-6962890.2665 // diff Omega2003 only in .2665 vs .5431
+ T*( 7.4722
+ T*( 0.007702
+ T*( -0.00005939)))), ARCSEC_PER_CIRCLE) * ARCSEC_TO_RAD;
}
//---------------------------------------------------------------------------------
// Return mean longitude of lunar ascending node, in radians,
// given T, the CoordTransTime at the Epoch of interest.
// valid for IERS 2003, 2010
double EarthOrientation::Omega2003(double T)
throw()
{
return ::fmod( 450160.398036 // 125.04455501 * 3600
+ T*(-6962890.5431 // .2665
+ T*( 7.4722
+ T*( 0.007702
+ T*( -0.00005939)))), ARCSEC_PER_CIRCLE) * ARCSEC_TO_RAD;
}
//---------------------------------------------------------------------------------
// Return mean longitude of the moon - Omega, in radians,
// given T, the CoordTransTime at the Epoch of interest. (Ref: F3 pg 23)
// valid for IERS1996, IERS2003, IERS2010
double EarthOrientation::F(double T)
throw()
{
return ::fmod( 335779.526232 // 93.27209062 * 3600
+ T*(1739527262.8478
+ T*( -12.7512
+ T*( -0.001037
+ T*( 0.00000417)))), ARCSEC_PER_CIRCLE) * ARCSEC_TO_RAD;
}
//---------------------------------------------------------------------------------
// Return mean elongation of the moon from the sun, in radians,
// given T, the CoordTransTime at the Epoch of interest. (Ref: F4 pg 23)
// valid for IERS1996, IERS2003
double EarthOrientation::D(double T)
throw()
{
return ::fmod( 1072260.703692 // 297.85019547 * 3600
+ T*(1602961601.2090
+ T*( -6.3706
+ T*( 0.006593
+ T*( -0.00003169)))), ARCSEC_PER_CIRCLE) * ARCSEC_TO_RAD;
}
//---------------------------------------------------------------------------------
// Return mean anomaly of the moon, in radians,
// given T, the CoordTransTime at the Epoch of interest. (Ref: F1 pg 23)
// valid for IERS1996, IERS2003
double EarthOrientation::L(double T)
throw()
{
return ::fmod( 485868.249036 // 134.96340251 * 3600
+ T*(1717915923.2178
+ T*( 31.8792
+ T*( 0.051635
+ T*( -0.00024470)))), ARCSEC_PER_CIRCLE ) * ARCSEC_TO_RAD;
}
//---------------------------------------------------------------------------------
// Return mean anomaly of the sun, in radians, given T, the CoordTransTime at the
// time of interest. (Ref: F2 pg 23)
// valid for IERS1996, IERS2003
double EarthOrientation::Lp(double T)
throw()
{
return ::fmod(1287104.793048 // 357.52910918 * 3600
+ T*(129596581.0481
+ T*( -0.5532
+ T*( 0.000136 // NB this has a minus sign in interp.f
+ T*( -0.00001149)))), ARCSEC_PER_CIRCLE) * ARCSEC_TO_RAD;
}
//------------------------------------------------------------------------------
// Compute the mean longitude of Mercury, in radians, given T, the CoordTransTime
// at the time of interest. Valid for IERS2003, IERS2010
// param T coordinate transformation time.
// return LMe in radians.
double EarthOrientation::LMe(double T)
throw()
{
double lme(::fmod(4.402608842 + 2608.7903141574 * T, TWOPI));
return lme;
}
//------------------------------------------------------------------------------
// Compute the mean longitude of Venus, in radians, given T, the CoordTransTime
// at the time of interest. Valid for IERS2003, IERS2010
// param T coordinate transformation time.
// return LV in radians.
double EarthOrientation::LV(double T)
throw()
{
double lv(::fmod(3.176146697 + 1021.3285546211 * T, TWOPI));
return lv;
}
//------------------------------------------------------------------------------
// Compute the mean longitude of Earth, in radians, given T, the CoordTransTime
// at the time of interest. Valid for IERS2003, IERS2010
// param T coordinate transformation time.
// return LE in radians.
double EarthOrientation::LE(double T)
throw()
{
double le(::fmod(1.753470314 + 628.3075849991 * T, TWOPI));
return le;
}
//------------------------------------------------------------------------------
// Compute the mean longitude of Mars, in radians, given T, the CoordTransTime
// at the time of interest. Valid for IERS2003, IERS2010
// param T coordinate transformation time.
// return LMa in radians.
double EarthOrientation::LMa(double T)
throw()
{
double lma(::fmod(6.203480913 + 334.0612426700 * T, TWOPI));
return lma;
}
//------------------------------------------------------------------------------
// Compute the mean longitude of Jupiter, in radians, given T, the
// CoordTransTime at the time of interest. Valid for IERS2003, IERS2010
// param T coordinate transformation time.
// return LJ in radians.
double EarthOrientation::LJ(double T)
throw()
{
double lj(::fmod(0.599546497 + 52.9690962641 * T, TWOPI));
return lj;
}
//------------------------------------------------------------------------------
// Compute the mean longitude of Saturn, in radians, given T, the
// CoordTransTime at the time of interest. Valid for IERS2003, IERS2010
// param T coordinate transformation time.
// return LS in radians.
double EarthOrientation::LS(double T)
throw()
{
double ls(::fmod(0.874016757 + 21.3299104960 * T, TWOPI));
return ls;
}
//------------------------------------------------------------------------------
// Compute the mean longitude of Uranus, in radians, given T, the
// CoordTransTime at the time of interest. Valid for IERS2003, IERS2010
// param T coordinate transformation time.
// return LU in radians.
double EarthOrientation::LU(double T)
throw()
{
double lu(::fmod(5.481293872 + 7.4781598567 * T, TWOPI));
return lu;
}
//------------------------------------------------------------------------------
// Compute the mean longitude of Neptune, in radians, given T, the
// CoordTransTime at the time of interest. Valid for IERS2003, IERS2010
// param T coordinate transformation time.
// return LN in radians.
double EarthOrientation::LN(double T)
throw()
{
double ln(::fmod(5.311886287 + 3.8133035638 * T, TWOPI));
return ln;
}
//------------------------------------------------------------------------------
// Compute the general precession in longitude, in radians,
// given T, the CoordTransTime at the time of interest.
// Valid for IERS2003
// param T coordinate transformation time.
// return Pa in radians.
double EarthOrientation::Pa(double T)
throw()
{
double pa((0.024381750 + 0.00000538691 * T) * T);
return pa;
}
//---------------------------------------------------------------------------------
// Compute eps, the obliquity of the ecliptic, in radians,
// given T, the CoordTransTime at the time of interest.
// throw if convention is not defined
double EarthOrientation::Obliquity(double T) throw(Exception)
{
if(convention == IERSConvention::IERS1996)
return Obliquity1996(T);
else if(convention == IERSConvention::IERS2003)
return Obliquity1996(T); // same as 96
else if(convention == IERSConvention::IERS2010)
return Obliquity2010(T);
else {
Exception e("IERS convention is not defined");
GPSTK_THROW(e);
}
}
//---------------------------------------------------------------------------------
// Compute Greenwich Mean Sidereal Time, or the Greenwich hour angle of
// the mean vernal equinox (radians), given the coordinate time of interest,
// and this object's UT1-UTC (sec), which comes from the IERS bulletin.
// param t EphTime epoch of the rotation (UTC).
// param reduced, bool true when UT1mUTC is 'reduced', meaning assumes
// 'no tides', as is the case with the NGA EOPs (default=F).
// throw if convention is not defined
double EarthOrientation::GMST(const EphTime& t, bool reduced) throw(Exception)
{
try {
if(convention == IERSConvention::IERS1996)
return GMST1996(t,UT1mUTC,reduced);
else if(convention == IERSConvention::IERS2003)
return GMST2003(t,UT1mUTC);
else if(convention == IERSConvention::IERS2010)
return GMST2010(t,UT1mUTC);
else {
Exception e("IERS convention is not defined");
GPSTK_THROW(e);
}
}
catch(Exception& e) { GPSTK_RETHROW(e); }
}
//---------------------------------------------------------------------------------
// Compute Greenwich Apparent Sidereal Time, or the Greenwich hour angle of
// the true vernal equinox (radians), given the coordinate time of interest,
// and this object's UT1-UTC (sec), which comes from the IERS bulletin.
// param t EphTime epoch of the rotation.
// param reduced, bool true when UT1mUTC is 'reduced', meaning assumes
// 'no tides', as is the case with the NGA EOPs (default=F).
// throw if convention is not defined
double EarthOrientation::GAST(const EphTime& t, bool reduced) throw(Exception)
{
try {
if(convention == IERSConvention::IERS1996)
return GAST1996(t,UT1mUTC,reduced);
else if(convention == IERSConvention::IERS2003)
return GAST2003(t,UT1mUTC);
else if(convention == IERSConvention::IERS2010)
return GAST2010(t,UT1mUTC);
else {
Exception e("IERS convention is not defined");
GPSTK_THROW(e);
}
}
catch(Exception& e) { GPSTK_RETHROW(e); }
}
//---------------------------------------------------------------------------------
// Generate transformation matrix (3X3 rotation) due to the EOPs (polar motion
// angles xp and yp (arcseconds)), as found in the IERS bulletin;
// see class EarthOrientation.
// param t EphTime epoch of the rotation.
// throw if convention is not defined
Matrix<double> EarthOrientation::PolarMotionMatrix(const EphTime& t)
throw(Exception)
{
if(convention == IERSConvention::IERS1996)
return PolarMotionMatrix1996(xp,yp);
else if(convention == IERSConvention::IERS2003)
return PolarMotionMatrix2003(t,xp,yp);
else if(convention == IERSConvention::IERS2010)
return PolarMotionMatrix2003(t,xp,yp); // valid also for 2010
else {
Exception e("IERS convention is not defined");
GPSTK_THROW(e);
}
}
//---------------------------------------------------------------------------------
// Compute the precession matrix, a 3x3 rotation matrix, given T,
// the coordinate transformation time at the time of interest
// throw if convention is not defined
Matrix<double> EarthOrientation::PrecessionMatrix(const EphTime& t)
throw(Exception)
{
double T=CoordTransTime(t);
if(convention == IERSConvention::IERS1996)
return PrecessionMatrix1996(T);
else if(convention == IERSConvention::IERS2003)
return PrecessionMatrix2003(T);
else if(convention == IERSConvention::IERS2010)
return PrecessionMatrix2010(T);
else {
Exception e("IERS convention is not defined");
GPSTK_THROW(e);
}
}
//------------------------------------------------------------------------------
// Nutation of the obliquity (deps) and of the longitude (dpsi)
// param T, the coordinate transformation time at the time of interest
// param deps, nutation of the obliquity (output) in radians
// param dpsi, nutation of the longitude (output) in radians
// throw if convention is not defined
// NB this is never called internally
//void EarthOrientation::NutationAngles(double T, double& deps, double& dpsi)
// throw(Exception)
//{
// if(convention == IERSConvention::IERS1996) {
// double om;
// NutationAngles1996(T,deps,dpsi,om);
// }
// if(convention == IERSConvention::IERS2003)
// NutationAngles2003(T,deps,dpsi);
// if(convention == IERSConvention::IERS2010)
// NutationAngles2010(T,deps,dpsi);
// else {
// Exception e("IERS convention is not defined");
// GPSTK_THROW(e);
// }
//}
//---------------------------------------------------------------------------------
// Compute the nutation matrix, given coordinate transformation time T
Matrix<double> EarthOrientation::NutationMatrix(const EphTime& t) throw(Exception)
{
try {
double T = CoordTransTime(t);
if(convention == IERSConvention::IERS1996)
return NutationMatrix1996(T);
else if(convention == IERSConvention::IERS2003)
return NutationMatrix2003(T);
else if(convention == IERSConvention::IERS2010)
return NutationMatrix2010(T);
else {
Exception e("IERS convention is not defined");
GPSTK_THROW(e);
}
}
catch(Exception& e) { GPSTK_RETHROW(e); }
}
//------------------------------------------------------------------------------
// Generate precise transformation matrix (3X3 rotation) for Earth motion due
// to precession, nutation and frame bias, at the given time of interest.
// param t EphTime epoch of the rotation.
// return 3x3 rotation matrix
// throw if the TimeSystem conversion fails (if t.system==TimeSystem::Unknown)
// throw if convention is not defined
Matrix<double> EarthOrientation::PreciseEarthRotation(const EphTime& t)
throw(Exception)
{
if(convention == IERSConvention::IERS1996)
return Matrix<double>(3,3); // TD
else if(convention == IERSConvention::IERS2003)
return PreciseEarthRotation2003(CoordTransTime(t));
else if(convention == IERSConvention::IERS2010)
return PreciseEarthRotation2010(CoordTransTime(t));
else {
Exception e("IERS convention is not defined");
GPSTK_THROW(e);
}
}
//---------------------------------------------------------------------------------
// Generate the full transformation matrix (3x3 rotation) relating the ECEF
// frame to the conventional inertial frame.
// Input is the time of interest; use this object's EOPs - the polar motion angles
// xp and yp (arcseconds), and UT1-UTC (seconds) (as found in the IERS bulletin).
// throw if convention is not defined
Matrix<double> EarthOrientation::ECEFtoInertial(const EphTime& t, bool reduced)
throw(Exception)
{
try {
if(convention == IERSConvention::IERS1996)
return ECEFtoInertial1996(t,xp,yp,UT1mUTC,reduced);
else if(convention == IERSConvention::IERS2003)
return ECEFtoInertial2003(t,xp,yp,UT1mUTC);
else if(convention == IERSConvention::IERS2010)
return ECEFtoInertial2010(t,xp,yp,UT1mUTC);
else {
Exception e("IERS convention is not defined");
GPSTK_THROW(e);
}
}
catch(Exception& e) { GPSTK_RETHROW(e); }
}
//------------------------------------------------------------------------------
// Compute the transformation from ECEF to the J2000 dynamical (inertial)
// frame. This differs from the ECEFtoInertial transformation only by the
// frame bias matrix. Only available in IERS2010.
// TD this is not right
//Matrix<double> EarthOrientation::ECEFtoJ2000(const EphTime& t, bool reduced)
// throw(Exception)
//{
// try {
// if(convention != IERSConvention::IERS2010) {
// Exception e("ECEFtoJ2000 implemented only for IERS2010");
// GPSTK_THROW(e);
// }
// // get the frame bias matrix
// //double T=0.0; // T at J2000
// double gamb, phib, psib, eps;
// //FukushimaWilliams(T, gamb, phib, psib, eps);
// //eps = 0.0;
// //Matrix<double> FB = FukushimaWilliams(gamb, phib, psib, eps);
// gamb = 0.052928 * ARCSEC_TO_RAD;
// phib = 0.006891 * ARCSEC_TO_RAD;
// psib = 0.041775 * ARCSEC_TO_RAD;
// Matrix<double> FB = rotation(-psib,3)*rotation(phib,1)*rotation(gamb,3);
// // get the full ECEFtoInertial, and back out the frame bias
// Matrix<double> T2C = ECEFtoInertial2010(t, xp, yp, UT1mUTC);
// return (FB*T2C);
// }
// catch(Exception& e) { GPSTK_RETHROW(e); }
//}
//------------------------------------------------------------------------------
// private functions
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Compute the locator s which gives the position of the CIO on the equator of
// the CIP, given the coordinate transformation time T. Consistent with IAU 2000A
// (IERS2003) precession-nutation, and P03 precession (IERS2010).
// and the coordinates X,Y of the CIP. Derived in part from SOFA routine s00.c
// for IERS2003 and s06.c for IERS2010.
// param T, the coordinate transformation time at the time of interest
// param X, the X coordinate of the CIP (input)
// param Y, the Y coordinate of the CIP (input)
// param which, the IERS convention to be used (input)
// return S, the parameter that positions the CIO on the CIP equator in radians.
double EarthOrientation::S(double T, double& X, double& Y, IERSConvention which)
throw()
{
int i,j;
double s,st[6],arg;
// Fundamental arguments: all in radians
double farg[8];
farg[0] = L(T); // mean anomaly of the moon
farg[1] = Lp(T); // mean anomaly of the sun
farg[2] = F(T); // mean longitude of the moon minus Omega
farg[3] = D(T); // mean elongation of the moon from the sun
// mean longitude of lunar ascending node
if(which==IERSConvention::IERS2010)
farg[4] = Omega2003(T);
else
farg[4] = Omega(T);
farg[5] = LV(T); // mean longitude of Venus
farg[6] = LE(T); // mean longitude of Earth
farg[7] = Pa(T); // general precession in longitude
// Based on table 5.2c IERS Tech Note 32 Chap 5 (tab5.2c.txt obtained from IERS)
// also used SOFA routine s00.c
// coefficients of polynomial in T for IERS2003
static const double polycoeff[6] =
{ 94.00e-6, 3808.35e-6, -119.94e-6, -72574.09e-6, 27.70e-6, 15.61e-6 };
// same for 2010
static const double polycoeff2010[6] =
{ 94.00e-6, 3808.65e-6, -122.68e-6, -72574.11e-6, 27.98e-6, 15.62e-6 };
typedef struct {
int coeff[8]; // coefficients of l,lp,f,d,o,lv,le,pa
double sincoeff,coscoeff; // coefficients of sine and cosine
} Coeffs;
// constant terms (T^0)
static const Coeffs C0[] = {
// indexes 1-10
{{ 0, 0, 0, 0, 1, 0, 0, 0}, -2640.73e-6, 0.39e-6 },
{{ 0, 0, 0, 0, 2, 0, 0, 0}, -63.53e-6, 0.02e-6 },
{{ 0, 0, 2, -2, 3, 0, 0, 0}, -11.75e-6, -0.01e-6 },
{{ 0, 0, 2, -2, 1, 0, 0, 0}, -11.21e-6, -0.01e-6 },
{{ 0, 0, 2, -2, 2, 0, 0, 0}, 4.57e-6, 0.00e-6 },
{{ 0, 0, 2, 0, 3, 0, 0, 0}, -2.02e-6, 0.00e-6 },
{{ 0, 0, 2, 0, 1, 0, 0, 0}, -1.98e-6, 0.00e-6 },
{{ 0, 0, 0, 0, 3, 0, 0, 0}, 1.72e-6, 0.00e-6 },
{{ 0, 1, 0, 0, 1, 0, 0, 0}, 1.41e-6, 0.01e-6 },
{{ 0, 1, 0, 0, -1, 0, 0, 0}, 1.26e-6, 0.01e-6 },
// indexes 11-20
{{ 1, 0, 0, 0, -1, 0, 0, 0}, 0.63e-6, 0.00e-6 },
{{ 1, 0, 0, 0, 1, 0, 0, 0}, 0.63e-6, 0.00e-6 },
{{ 0, 1, 2, -2, 3, 0, 0, 0}, -0.46e-6, 0.00e-6 },
{{ 0, 1, 2, -2, 1, 0, 0, 0}, -0.45e-6, 0.00e-6 },
{{ 0, 0, 4, -4, 4, 0, 0, 0}, -0.36e-6, 0.00e-6 },
{{ 0, 0, 1, -1, 1, -8, 12, 0}, 0.24e-6, 0.12e-6 },
{{ 0, 0, 2, 0, 0, 0, 0, 0}, -0.32e-6, 0.00e-6 },
{{ 0, 0, 2, 0, 2, 0, 0, 0}, -0.28e-6, 0.00e-6 },
{{ 1, 0, 2, 0, 3, 0, 0, 0}, -0.27e-6, 0.00e-6 },
{{ 1, 0, 2, 0, 1, 0, 0, 0}, -0.26e-6, 0.00e-6 },
// indexes 21-30
{{ 0, 0, 2, -2, 0, 0, 0, 0}, 0.21e-6, 0.00e-6 },
{{ 0, 1, -2, 2, -3, 0, 0, 0}, -0.19e-6, 0.00e-6 },
{{ 0, 1, -2, 2, -1, 0, 0, 0}, -0.18e-6, 0.00e-6 },
{{ 0, 0, 0, 0, 0, 8,-13, -1}, 0.10e-6, -0.05e-6 },
{{ 0, 0, 0, 2, 0, 0, 0, 0}, -0.15e-6, 0.00e-6 },
{{ 2, 0, -2, 0, -1, 0, 0, 0}, 0.14e-6, 0.00e-6 },
{{ 0, 1, 2, -2, 2, 0, 0, 0}, 0.14e-6, 0.00e-6 },
{{ 1, 0, 0, -2, 1, 0, 0, 0}, -0.14e-6, 0.00e-6 },
{{ 1, 0, 0, -2, -1, 0, 0, 0}, -0.14e-6, 0.00e-6 },
{{ 0, 0, 4, -2, 4, 0, 0, 0}, -0.13e-6, 0.00e-6 },
// indexes 31-33
{{ 0, 0, 2, -2, 4, 0, 0, 0}, 0.11e-6, 0.00e-6 },
{{ 1, 0, -2, 0, -3, 0, 0, 0}, -0.11e-6, 0.00e-6 },
{{ 1, 0, -2, 0, -1, 0, 0, 0}, -0.11e-6, 0.00e-6 }
};
// First order terms (T)
// NB C1[1].sincoeff=1.71e-6 in 2003 becomes 1.73e-6 in 2010 (2nd row)
static const double C1_1_sincoeff2010 = 1.73e-6;
static const Coeffs C1[] = {
{{ 0, 0, 0, 0, 2, 0, 0, 0}, -0.07e-6, 3.57e-6 },
{{ 0, 0, 0, 0, 1, 0, 0, 0}, 1.71e-6, -0.03e-6 },
{{ 0, 0, 2, -2, 3, 0, 0, 0}, 0.00e-6, 0.48e-6 }
};
// Second order terms (T^2)
// NB C2[0].sincoeff=743.53e-6 in 2003 becomes 743.52e-6 in 2010 (1st row)
static const double C2_0_sincoeff = 743.52e-6;
static const Coeffs C2[] = {
// indexes 1-10
{{ 0, 0, 0, 0, 1, 0, 0, 0}, 743.53e-6, -0.17e-6 },
{{ 0, 0, 2, -2, 2, 0, 0, 0}, 56.91e-6, 0.06e-6 },
{{ 0, 0, 2, 0, 2, 0, 0, 0}, 9.84e-6, -0.01e-6 },
{{ 0, 0, 0, 0, 2, 0, 0, 0}, -8.85e-6, 0.01e-6 },
{{ 0, 1, 0, 0, 0, 0, 0, 0}, -6.38e-6, -0.05e-6 },
{{ 1, 0, 0, 0, 0, 0, 0, 0}, -3.07e-6, 0.00e-6 },
{{ 0, 1, 2, -2, 2, 0, 0, 0}, 2.23e-6, 0.00e-6 },
{{ 0, 0, 2, 0, 1, 0, 0, 0}, 1.67e-6, 0.00e-6 },
{{ 1, 0, 2, 0, 2, 0, 0, 0}, 1.30e-6, 0.00e-6 },
{{ 0, 1, -2, 2, -2, 0, 0, 0}, 0.93e-6, 0.00e-6 },
// indexes 11-20
{{ 1, 0, 0, -2, 0, 0, 0, 0}, 0.68e-6, 0.00e-6 },
{{ 0, 0, 2, -2, 1, 0, 0, 0}, -0.55e-6, 0.00e-6 },
{{ 1, 0, -2, 0, -2, 0, 0, 0}, 0.53e-6, 0.00e-6 },
{{ 0, 0, 0, 2, 0, 0, 0, 0}, -0.27e-6, 0.00e-6 },
{{ 1, 0, 0, 0, 1, 0, 0, 0}, -0.27e-6, 0.00e-6 },
{{ 1, 0, -2, -2, -2, 0, 0, 0}, -0.26e-6, 0.00e-6 },
{{ 1, 0, 0, 0, -1, 0, 0, 0}, -0.25e-6, 0.00e-6 },
{{ 1, 0, 2, 0, 1, 0, 0, 0}, 0.22e-6, 0.00e-6 },
{{ 2, 0, 0, -2, 0, 0, 0, 0}, -0.21e-6, 0.00e-6 },
{{ 2, 0, -2, 0, -1, 0, 0, 0}, 0.20e-6, 0.00e-6 },
// indexes 21-25
{{ 0, 0, 2, 2, 2, 0, 0, 0}, 0.17e-6, 0.00e-6 },
{{ 2, 0, 2, 0, 2, 0, 0, 0}, 0.13e-6, 0.00e-6 },
{{ 2, 0, 0, 0, 0, 0, 0, 0}, -0.13e-6, 0.00e-6 },
{{ 1, 0, 2, -2, 2, 0, 0, 0}, -0.12e-6, 0.00e-6 },
{{ 0, 0, 2, 0, 0, 0, 0, 0}, -0.11e-6, 0.00e-6 }
};
// Third order terms (T^3)
static const Coeffs C3[] = {
{{ 0, 0, 0, 0, 1, 0, 0, 0}, 0.30e-6, -23.51e-6 },
{{ 0, 0, 2, -2, 2, 0, 0, 0}, -0.03e-6, -1.39e-6 },
{{ 0, 0, 2, 0, 2, 0, 0, 0}, -0.01e-6, -0.24e-6 },
{{ 0, 0, 0, 0, 2, 0, 0, 0}, 0.00e-6, 0.22e-6 }
};
static const Coeffs C32010[] = {
{{ 0, 0, 0, 0, 1, 0, 0, 0}, 0.30e-6, -23.42e-6 },
{{ 0, 0, 2, -2, 2, 0, 0, 0}, -0.03e-6, -1.46e-6 },
{{ 0, 0, 2, 0, 2, 0, 0, 0}, -0.01e-6, -0.25e-6 },
{{ 0, 0, 0, 0, 2, 0, 0, 0}, 0.00e-6, 0.23e-6 }
};
// Fourth order terms (T^4)
static const Coeffs C4[] = {
{{ 0, 0, 0, 0, 1, 0, 0, 0}, -0.26e-6, -0.01e-6 }
};
// number of terms in each order
const int n0 = int(sizeof C0 / sizeof(Coeffs));
const int n1 = int(sizeof C1 / sizeof(Coeffs));
const int n2 = int(sizeof C2 / sizeof(Coeffs));
const int n3 = int(sizeof C3 / sizeof(Coeffs));
const int n4 = int(sizeof C4 / sizeof(Coeffs));
// initialize with the polynomial coefficients
if(which != IERSConvention::IERS2010)
for(i=0; i<6; ++i) st[i] = polycoeff[i];
else
for(i=0; i<6; ++i) st[i] = polycoeff2010[i];
// do the sums
for(i=n0-1; i>=0; --i) { // order 0
arg = 0.0;
for(j=0; j<8; ++j)
arg += C0[i].coeff[j] * farg[j];
st[0] += C0[i].sincoeff * ::sin(arg) + C0[i].coscoeff * ::cos(arg);
}
for(i=n1-1; i>=0; --i) { // order 1
arg = 0.0;
for(j=0; j<8; ++j)
arg += C1[i].coeff[j] * farg[j];
if(which == IERSConvention::IERS2010 && i==1)
st[1] += C1_1_sincoeff2010 * ::sin(arg) + C1[i].coscoeff * ::cos(arg);
else
st[1] += C1[i].sincoeff * ::sin(arg) + C1[i].coscoeff * ::cos(arg);
}
for(i=n2-1; i>=0; --i) { // order 2
arg = 0.0;
for(j=0; j<8; ++j)
arg += C2[i].coeff[j] * farg[j];
if(which == IERSConvention::IERS2010 && i==0)
st[2] += C2_0_sincoeff * ::sin(arg) + C2[i].coscoeff * ::cos(arg);
else
st[2] += C2[i].sincoeff * ::sin(arg) + C2[i].coscoeff * ::cos(arg);
}
// order 3
if(which != IERSConvention::IERS2010) // 2003
for(i=n3-1; i>=0; --i) {
arg = 0.0;
for(j=0; j<8; ++j)
arg += C3[i].coeff[j] * farg[j];
st[3] += C3[i].sincoeff * ::sin(arg) + C3[i].coscoeff * ::cos(arg);
}
else // 2010
for(i=n3-1; i>=0; --i) {
arg = 0.0;
for(j=0; j<8; ++j)
arg += C32010[i].coeff[j] * farg[j];
st[3] += C32010[i].sincoeff * ::sin(arg)+C32010[i].coscoeff * ::cos(arg);
}
for(i=n4-1; i>=0; --i) { // order 4
arg = 0.0;
for(j=0; j<8; ++j)
arg += C4[i].coeff[j] * farg[j];
st[4] += C4[i].sincoeff * ::sin(arg) + C4[i].coscoeff * ::cos(arg);
}
// combine all the terms
s = st[0] + (st[1] + (st[2] + (st[3] + (st[4] + st[5]*T)*T)*T)*T)*T;
s *= ARCSEC_TO_RAD;
s -= X*Y/2.0;
return s;
}
//------------------------------------------------------------------------------
// The position of the Terrestrial Ephemeris Origin (TEO) on the equator of the
// Celestial Intermediate Pole (CIP), as given by the quantity s'.
// Also called the Terrestrial Intermediate Origin (TIO). Valid 2003 and 2010
// Ref. IERS Tech Note 32 Chap 5 Eqn 12 and IERS Tech Note 36 Chap 5 Eqn 5.13
// param T Coordinate transformation time T.
// return angle 's prime' in radians
double EarthOrientation::Sprime(double T)
throw()
{
double sp = -47.0e-6 * T * ARCSEC_TO_RAD;
return sp;
}
//------------------------------------------------------------------------------
// Compute the coordinates X,Y of the Celestial Intermediate Origin (CIO) using
// a series based on IAU 2006 precession and IAU 2000A nutation (IERS 2010).
// The coordinates form a unit vector that points towards the CIO; they include
// the effects of frame bias, precession and nutation. cf. sofa xy06
// Reference IERS(2010) Section 5.5.4
// param T, the coordinate transformation time at the time of interest
// param X, x coordinate of CIO
// param Y, y coordinate of CIO
void EarthOrientation::XYCIO(double& T, double& X, double& Y)
throw()
{
// include data arrays : defines MAXPT
#include "IERS2010CIOSeriesData.hpp"
int i,j;
double t;
// compute and store powers of T
double powsT[MAXPT+1];
t = 1.0;
for(i=0; i<=MAXPT; i++) {
powsT[i] = t;
t *= T;
}
// fundamental arguments
double fa[14];
fa[0] = L(T); // mean anomaly of the moon
fa[1] = Lp(T); // mean anomaly of the sun
fa[2] = F(T); // mean longitude of the moon - Omega
fa[3] = D(T); // mean elongation of the moon from the sun
fa[4] = Omega2003(T); // mean longitude of lunar ascending node
fa[5] = LMe(T); // mean longitude Mercury
fa[6] = LV(T); // mean longitude of Venus
fa[7] = LE(T); // mean longitude of Earth
fa[8] = LMa(T); // mean longitude Mars
fa[9] = LJ(T); // mean longitude Jupiter
fa[10] = LS(T); // mean longitude Saturn
fa[11] = LU(T); // mean longitude Uranus
fa[12] = LN(T); // mean longitude Neptune
fa[13] = Pa(T); // general precession in longitude
// intermediate totals
double xypoly[2]={0.0,0.0},xylunarsolar[2]={0.0,0.0},xyplanet[2]={0.0,0.0};
// polynomial
for(i=0; i<2; i++) {
for(j=MAXPT; j>=0; j--)
xypoly[i] += XYcoeff[i][j] * powsT[j];
}
// nutation planetary terms
int ilast(NAmp),jlast;
double sc[2];
for(int ifreq=NFAP-1; ifreq >= 0; ifreq--) {
// build the argument
double arg(0.0);
for(i=0; i<14; i++)
if(nFAplanetary[ifreq][i]) // don't add zero
arg += double(nFAplanetary[ifreq][i]) * fa[i];
// store sin and cos
sc[0] = ::sin(arg);
sc[1] = ::cos(arg);
// amplitudes
jlast = iamp[ifreq+NFALS];
for(i=ilast; i >= jlast; i--) {
j = i - jlast; // coeff number
xyplanet[jaxy[j]] += amp[i-1] * sc[jasc[j]] * powsT[japt[j]];
}
ilast = jlast - 1;
}
// NB ilast is maintained through this point
// nutation lunar solar terms
for(int ifreq=NFALS-1; ifreq >= 0; ifreq--) {
// build the argument
double arg(0.0);
for(i=0; i<5; i++)
if(nFAlunarsolar[ifreq][i]) // don't add zero
arg += double(nFAlunarsolar[ifreq][i]) * fa[i];
// store sin and cos
sc[0] = ::sin(arg);
sc[1] = ::cos(arg);
// amplitudes
jlast = iamp[ifreq];
for(i=ilast; i >= jlast; i--) {
j = i - jlast; // coeff number
xylunarsolar[jaxy[j]] += amp[i-1] * sc[jasc[j]] * powsT[japt[j]];
}
ilast = jlast - 1;
}
X = xypoly[0] + (xylunarsolar[0]+xyplanet[0])*1.e-6;
X *= ARCSEC_TO_RAD;
Y = xypoly[1] + (xylunarsolar[1]+xyplanet[1])*1.e-6;
Y *= ARCSEC_TO_RAD;
}
//---------------------------------------------------------------------------------
// Starting with 2003 (and valid for 2010) conventions a new method for computing
// the transformation fron ITRS to GCRS is provided by the Celestial Ephemeris
// Origin (CEO) which is based on the Earth Rotation Angle. cf. sofa ERA00.c
// param t EphTime time of interest
// param UT1mUTC offset UT1-UTC
// return Earth rotation angle in radians
// throw if the TimeSystem conversion fails (if t.system==TimeSystem::Unknown)
double EarthOrientation::EarthRotationAngle(const EphTime& t,
const double& UT1mUTC)
throw(Exception)
{
try {
EphTime tUT1(t);
tUT1.convertSystemTo(TimeSystem::UTC);
tUT1 += UT1mUTC;
// TN36 eqn 5.15
//double days = tUT1.dMJD() - JulianEpoch; // days since JE
int idays(int(tUT1.dMJD()-0.5)-intJulianEpoch); // days = idays+frac
double frac(0.5+tUT1.secOfDay()/86400.0); // fractional part of days
if(frac > 1.0) frac -= 1.0;
// mod the terms with 1 individually to avoid numerical error
double term1 = frac + 0.7790572732640 + 0.00273781191135448*frac;
if(term1 > 1.0) term1 -= 1.0;
double term2 = ::fmod(0.00273781191135448*double(idays), 1.0);
double term = ::fmod(term1+term2, 1.0);
double era = TWOPI * term;
if(era > TWOPI) era -= TWOPI;
return era;
}
catch(Exception& e) { GPSTK_RETHROW(e); }
}
//------------------------------------------------------------------------------
// Equation of the equinoxes complementary terms, IAU 2000 (IERS 2003)
// Note that GAST = GMST + EquationOfEquinoxes2003
// param t EphTime epoch of interest
// return the ee in radians
// throw if the TimeSystem conversion fails (if t.system==TimeSystem::Unknown)
// Based on IERS function EECT2000.f; all planets but Venus dropped b/c their
// contribution is zero.
double EarthOrientation::EquationOfEquinoxes2003(EphTime t)
throw(Exception)
{
// first define the coefficients
// number of integer coefficients and fundamental arguments
const int N(8);
// NB drop the lma,lju,lsa,lur,lne terms - all zero!
typedef struct {
// coefficients of l,lp,f,d,o,lme,lv,le,lma,lju,lsa,lur,lne,pa in arg
// *these were dropped: * * * * * *
int coeff[N];
// coefficients of sin(arg) and cos(arg) in the series
double sincoeff,coscoeff;
} Coeffs;
// T^0 ...not very efficient
static const Coeffs Czero[] = {
// l lp f d o lv le pa c(sin) c(cos)
// 1-10
{{ 0, 0, 0, 0, 1, 0, 0, 0}, 2640.96e-6, -0.39e-6 },
{{ 0, 0, 0, 0, 2, 0, 0, 0}, 63.52e-6, -0.02e-6 },
{{ 0, 0, 2, -2, 3, 0, 0, 0}, 11.75e-6, 0.01e-6 },
{{ 0, 0, 2, -2, 1, 0, 0, 0}, 11.21e-6, 0.01e-6 },
{{ 0, 0, 2, -2, 2, 0, 0, 0}, -4.55e-6, 0.00e-6 },
{{ 0, 0, 2, 0, 3, 0, 0, 0}, 2.02e-6, 0.00e-6 },
{{ 0, 0, 2, 0, 1, 0, 0, 0}, 1.98e-6, 0.00e-6 },
{{ 0, 0, 0, 0, 3, 0, 0, 0}, -1.72e-6, 0.00e-6 },
{{ 0, 1, 0, 0, 1, 0, 0, 0}, -1.41e-6, -0.01e-6 },
{{ 0, 1, 0, 0, -1, 0, 0, 0}, -1.26e-6, -0.01e-6 },
// 11-20
{{ 1, 0, 0, 0, -1, 0, 0, 0}, -0.63e-6, 0.00e-6 },
{{ 1, 0, 0, 0, 1, 0, 0, 0}, -0.63e-6, 0.00e-6 },
{{ 0, 1, 2, -2, 3, 0, 0, 0}, 0.46e-6, 0.00e-6 },
{{ 0, 1, 2, -2, 1, 0, 0, 0}, 0.45e-6, 0.00e-6 },
{{ 0, 0, 4, -4, 4, 0, 0, 0}, 0.36e-6, 0.00e-6 },
{{ 0, 0, 1, -1, 1, -8, 12, 0}, -0.24e-6, -0.12e-6 },
{{ 0, 0, 2, 0, 0, 0, 0, 0}, 0.32e-6, 0.00e-6 },
{{ 0, 0, 2, 0, 2, 0, 0, 0}, 0.28e-6, 0.00e-6 },
{{ 1, 0, 2, 0, 3, 0, 0, 0}, 0.27e-6, 0.00e-6 },
{{ 1, 0, 2, 0, 1, 0, 0, 0}, 0.26e-6, 0.00e-6 },
// 21-30
{{ 0, 0, 2, -2, 0, 0, 0, 0}, -0.21e-6, 0.00e-6 },
{{ 0, 1, -2, 2, -3, 0, 0, 0}, 0.19e-6, 0.00e-6 },
{{ 0, 1, -2, 2, -1, 0, 0, 0}, 0.18e-6, 0.00e-6 },
{{ 0, 0, 0, 0, 0, 8,-13, -1}, -0.10e-6, 0.05e-6 },
{{ 0, 0, 0, 2, 0, 0, 0, 0}, 0.15e-6, 0.00e-6 },
{{ 2, 0, -2, 0, -1, 0, 0, 0}, -0.14e-6, 0.00e-6 },
{{ 1, 0, 0, -2, 1, 0, 0, 0}, 0.14e-6, 0.00e-6 },
{{ 0, 1, 2, -2, 2, 0, 0, 0}, -0.14e-6, 0.00e-6 },
{{ 1, 0, 0, -2, -1, 0, 0, 0}, 0.14e-6, 0.00e-6 },
{{ 0, 0, 4, -2, 4, 0, 0, 0}, 0.13e-6, 0.00e-6 },
// 31-33
{{ 0, 0, 2, -2, 4, 0, 0, 0}, -0.11e-6, 0.00e-6 },
{{ 1, 0, -2, 0, -3, 0, 0, 0}, 0.11e-6, 0.00e-6 },
{{ 1, 0, -2, 0, -1, 0, 0, 0}, 0.11e-6, 0.00e-6 }
};
// T^1 - do this manually
//static const Coeffs C1[] = {
// {{ 0, 0, 0, 0, 1, 0, 0, 0, 0 }, -0.87e-6, +0.00e-6 }
//};
// number of terms in each order
const int n0 = int(sizeof Czero / sizeof(Coeffs));
//const int n1 = int(sizeof C1 / sizeof(Coeffs));
try {
// coordinate transformation time
double T(CoordTransTime(t));
// fundamental arguments l lp f d o lme lv le pa
double farg[N];
LOG(DEBUG7) << "\nT = " << fixed << setprecision(15) << T;
farg[0] = L(T); // mean anomaly of the moon
LOG(DEBUG7) << "L(T) = " << fixed << setprecision(15) << farg[0];
farg[1] = Lp(T); // mean anomaly of the sun
LOG(DEBUG7) << "Lp(T) = " << fixed << setprecision(15) << farg[1];
farg[2] = F(T); // mean longitude of the moon - Omega
LOG(DEBUG7) << "F(T) = " << fixed << setprecision(15) << farg[2];
farg[3] = D(T); // mean elongation of the moon from the sun
LOG(DEBUG7) << "D(T) = " << fixed << setprecision(15) << farg[3];
farg[4] = Omega2003(T); // mean longitude of lunar ascending node
LOG(DEBUG7) << "Omega2003(T) = " << fixed << setprecision(15) << farg[4];
farg[5] = LV(T); // mean longitude of Venus
LOG(DEBUG7) << "LV(T) = " << fixed << setprecision(15) << farg[5];
farg[6] = LE(T); // mean longitude of Earth
LOG(DEBUG7) << "LE(T) = " << fixed << setprecision(15) << farg[6];
farg[7] = Pa(T); // general precession in longitude
LOG(DEBUG7) << "Pa(T) = " << fixed << setprecision(15) << farg[7];
// do the sums
double ee(0.0);
for(int i=n0-1; i>=0; --i) { // order 0
double arg(0.0);
for(int j=0; j<N; ++j)
if(Czero[i].coeff[j])
arg += Czero[i].coeff[j] * farg[j];
ee += Czero[i].sincoeff * ::sin(arg);
if(Czero[i].coscoeff) ee += Czero[i].coscoeff * ::cos(arg);
}
// the T^1 term
ee += -0.87e-6 * ::sin(farg[4]) * T;
// convert to radians
ee *= ARCSEC_TO_RAD;
return ee;
}
catch(Exception& e) { GPSTK_RETHROW(e); }
}
//------------------------------------------------------------------------------
// Zonal tide terms for corrections of UT1mUTC when that quantity does not
// include tides (e.g. NGA EOP), ref. IERS 1996 Ch. 8, table 8.1 pg 74.
// param T, the coordinate transformation time at the time of interest
// param UT1mUT1R, the correction to UT1mUTC (seconds)
// param dlodR, the correction to the length of day (seconds)
// param domegaR, the correction to the Earth rotation rate (radians/second)
void EarthOrientation::UT1mUTCTidalCorrections(double T,
double& UT1mUT1R,
double& dlodR,
double& domegaR)
throw()
{
// Define (all doubles) and all in radians
double o(Omega(T)); // mean longitude of lunar ascending node
double f(F(T)); // mean longitude of the moon - Omega
double d(D(T)); // mean elongation of the moon from the sun
double l(L(T)); // mean anomaly of the moon
double lp(Lp(T)); // mean anomaly of the sun
//-----------------------------------------------------------------------
// include code that forms UT1mUT1R dlodR domegaR
#include "IERS1996UT1mUTCData.hpp"
}
//---------------------------------------------------------------------------------
// Compute eps, the obliquity of the ecliptic, in radians,
// given T, the CoordTransTime at the time of interest. IAU76 IAU80 for IERS1996,03
double EarthOrientation::Obliquity1996(double T)
throw()
{
//double eps;
//// seconds of arc
//eps = T*(-46.8150 + T*(-0.00059 + T*0.001813));
//eps /= 3600.0; // convert to degrees
//// degrees
//eps += 23.4392911111111111; // = 84381.448/3600.0
//eps *= DEG_TO_RAD;
//return eps;
return ( 84381.448
+ T*( -46.8150
+ T*( -0.00059
+ T*( 0.001813)))) * ARCSEC_TO_RAD;
}
//---------------------------------------------------------------------------------
// Compute eps, the obliquity of the ecliptic, in radians,
// given T, the CoordTransTime at the time of interest.
double EarthOrientation::Obliquity2010(double T)
throw()
{
//double eps;
//// mean obliquity cf. sofa obl06.c
//eps = (84381.406 + (-46.836769 + (-0.0001831 + (0.00200340 +
// (-0.000000576 - 0.0000000434*T)*T)*T)*T)*T)*ARCSEC_TO_RAD;
//return eps;
return ( 84381.406
+ T*(-46.836769
+ T*( -0.0001831
+ T*( 0.00200340
+ T*( -0.000000576
+ T*( -0.0000000434)))))) * ARCSEC_TO_RAD;
}
//------------------------------------------------------------------------------
// Compute Greenwich Mean Sidereal Time, or the Greenwich hour angle of
// the mean vernal equinox (radians), given the UT1 time of interest,
// and UT1-UTC (sec), from the IERS bulletin. For IERS1996. cf sofa gmst82.c
// param t EphTime epoch of the rotation.
// param UT1mUTC, UT1-UTC in seconds, as found in the IERS bulletin.
// return GMST in radians
double EarthOrientation::GMST1996(EphTime t, double UT1mUTC, bool reduced)
throw(Exception)
{
try {
// convert to UTC first
t.convertSystemTo(TimeSystem::UTC);
// if reduced, compute tidal terms
if(reduced) {
double dlodR,domegaR,UT1mUT1R;
UT1mUTCTidalCorrections(CoordTransTime(t), UT1mUT1R, dlodR, domegaR);
UT1mUTC = UT1mUT1R-UT1mUTC;
}
// convert to UT1
t += UT1mUTC;
// dont use CoordTransTime() b/c UT1 is needed here, not TT
double T((t.dMJD()-JulianEpoch)/36525.0);
// Compute GMST in radians
double G = -19089.45159 // first term is 24110.54841-43200. seconds
+ T*(8640184.812866 + T*(0.093104 - T * 6.2e-6));
// convert seconds to days
G /= 86400.0;
// this should be the same ... seconds (24060s = 6h 41min)
//G = 24110.54841 + (8640184.812866 + (0.093104 - 6.2e-6*T)*T)*T; sec
//G /= 86400.0; // instead, divide the numbers above manually
//G = 0.279057273264 + 100.0021390378009*T // seconds/86400 = days
// + (0.093104 - 6.2e-6*T)*T*T/86400.0;
//G += (UT1mUTC + t.secOfDay())/86400.0; // days
// add fraction of day
double frac(0.5+t.secOfDay()/86400); // fraction of day
if(frac > 1.0) frac -= 1.0;
G += frac;
// convert to radians
G *= TWOPI; // radians
G = ::fmod(G,TWOPI);
if(G < 0.0) G += TWOPI;
return G;
}
catch(Exception& e) { GPSTK_RETHROW(e); }
}
//------------------------------------------------------------------------------
// Compute Greenwich Mean Sidereal Time, or the Greenwich hour angle of
// the mean vernal equinox (radians), given the coordinate time of interest,
// and UT1-UTC (sec), which comes from the IERS bulletin. For IERS2003
// param t EphTime epoch of the rotation.
// param UT1mUTC, UT1-UTC in seconds, as found in the IERS bulletin.
double EarthOrientation::GMST2003(EphTime t, double UT1mUTC)
throw(Exception)
{
try {
// TT days since epoch
double T(CoordTransTime(t)), G;
double era = EarthRotationAngle(t,UT1mUTC);
G = ::fmod(era + (0.014506 + (4612.15739966 + (1.39667721 + (-0.00009344
+ 0.00001882*T)*T)*T)*T)*ARCSEC_TO_RAD, TWOPI);
return G;
}
catch(Exception& e) { GPSTK_RETHROW(e); }
}
//------------------------------------------------------------------------------
// Compute Greenwich Mean Sidereal Time, or the Greenwich hour angle of
// the mean vernal equinox (radians), given the coordinate time of interest,
// and UT1-UTC (sec), which comes from the IERS bulletin. For IERS2010
// param t EphTime epoch of the rotation.
// param UT1mUTC, UT1-UTC in seconds, as found in the IERS bulletin.
double EarthOrientation::GMST2010(EphTime t, double UT1mUTC)
throw(Exception)
{
try {
double era = EarthRotationAngle(t,UT1mUTC); // radians
// IERS2010 - cf sofa gmst06.c and TN36 eqn 5.32
double T = CoordTransTime(t);
//double G = ::fmod(era+(0.014506 + (4612.156534 + (1.3915817 + (-0.00000044
// + (-0.000029956 + (-0.0000000368)*T)*T)*T)*T)*T)*ARCSEC_TO_RAD, TWOPI);
//return G;
return (era + (0.014506 + T*(4612.156534 // NB era in radians already
+ T*(1.3915817
+ T*(-0.00000044
+ T*(-0.000029956
+ T*(-0.0000000368)))))) * ARCSEC_TO_RAD);
}
catch(Exception& e) { GPSTK_RETHROW(e); }
}
//---------------------------------------------------------------------------------
// Helper to compute the Greenwich hour angle of the true vernal equinox, or
// Greenwich Apparent Sidereal Time (GAST) in radians, for IERS1996,
// given the (UT) time of interest t, and, where T = CoordTransTime(t),
// o = Omega(T) = mean longitude of lunar ascending node, in radians,
// eps = the obliquity of the ecliptic, in radians,
// dpsi = nutation in longitude (counted in the ecliptic),
// in seconds of arc.
double EarthOrientation::gast1996(EphTime t,
double om, double eps, double dpsi, double UT1mUTC)
throw(Exception)
{
try {
double G = GMST1996(t,UT1mUTC,false);
// add equation of equinoxes: dpsi, eps and Omega terms
double ee = dpsi * ::cos(eps)
+ (0.00264 * ::sin(om) + 0.000063 * ::sin(2.0*om)) * ARCSEC_TO_RAD;
LOG(DEBUG7) << "\nequequinox = " << fixed << setprecision(15)
<< showpos << 1.e3*ee*RAD_TO_DEG << " / 1.e3";
LOG(DEBUG7) << "\nGMST = " << fixed << setprecision(15)
<< showpos << G*RAD_TO_DEG;
return (G+ee);
}
catch(Exception& e) { GPSTK_RETHROW(e); }
}
//------------------------------------------------------------------------------
// Compute Greenwich Apparent Sidereal Time, or the Greenwich hour angle of
// the true vernal equinox (radians), given the coordinate time of interest,
// and UT1-UTC (sec), which comes from the IERS bulletin.
// param t EphTime epoch of the rotation.
// param UT1mUTC, UT1-UTC in seconds, as found in the IERS bulletin.
//
// GAST = Greenwich hour angle of the true vernal equinox
// GAST = GMST + dpsi*cos(eps) + 0.00264" * sin(Omega) +0.000063" * sin(2*Omega)
// (these terms account for the accumulated precession and nutation in
// right ascension and minimize any discontinuity in UT1)
//
// GMST = Greenwich hour angle of the mean vernal equinox
// = Greenwich Mean Sideral Time
// = GMST0 + r*[UTC + (UT1-UTC)]
// r = is the ratio of universal to sidereal time
// = 1.002737909350795 + 5.9006E-11*T' - 5.9e-15*T'^2
// T' = days'/36525
// days'= number of days elapsed since the Julian Epoch t0 (J2000)
// = +/-(integer+0.5)
// and
// (UT1-UTC) (seconds) is taken from the IERS bulletin
//
// GMST0 = GMST at 0h UT1
// = 6h 41min (50.54841+8640184.812866*T'+0.093104*T'^2-6.2E-6*T'^3)sec
//
// see pg 21 of the Reference (IERS 1996).
double EarthOrientation::GAST1996(EphTime t, double UT1mUTC, bool reduced)
throw(Exception)
{
try {
double T(CoordTransTime(t));
double omega,deps,dpsi,G;
double eps(Obliquity1996(T)),epsa;
NutationAngles1996(T,deps,dpsi,omega); // deps is not used...
// if reduced (NGA), correct for tides
double UT1mUT1R,dlodR,domegaR;
if(reduced) {
UT1mUTCTidalCorrections(T, UT1mUT1R, dlodR, domegaR);
G = gast1996(t, omega, eps, dpsi, UT1mUT1R-UT1mUTC);
}
else
G = gast1996(t, omega, eps, dpsi, UT1mUTC);
return G;
}
catch(Exception& e) { GPSTK_RETHROW(e); }
}
//------------------------------------------------------------------------------
// Compute Greenwich Apparent Sidereal Time, or the Greenwich hour angle of
// the true vernal equinox (radians), given the coordinate time of interest,
// and UT1-UTC (sec), which comes from the IERS bulletin.
// param t EphTime epoch of the rotation.
// param UT1mUTC, UT1-UTC in seconds, as found in the IERS bulletin.
double EarthOrientation::GAST2003(EphTime t, double UT1mUTC)
throw(Exception)
{
try {
double omega,deps,dpsi,G;
double T(CoordTransTime(t));
// precession and obliquity corrections (rad/century)
double dpsipr,depspr;
PrecessionRateCorrections2003(T, dpsipr, depspr); // dpsipr not used
// compute mean obliquity from IERS Tech Note 32 Chapter 5, eqn 32.
double eps(Obliquity1996(T));
// mean obliquity consistent with IAU 2000 P-N models
double epsa(eps + depspr);
NutationAngles2003(T,deps,dpsi);
// Equation of the equinoxes.
double ee = EquationOfEquinoxes2003(t);
LOG(DEBUG7) << "\nee = " << fixed << setprecision(15) << showpos
<< 1.e6*ee*RAD_TO_DEG << " / 1.e6";
ee = dpsi * ::cos(epsa) + ee;
G = GMST2003(t, UT1mUTC) + ee;
return G;
}
catch(Exception& e) { GPSTK_RETHROW(e); }
}
//------------------------------------------------------------------------------
// Compute Greenwich Apparent Sidereal Time, or the Greenwich hour angle of
// the true vernal equinox (radians), given the coordinate time of interest,
// and UT1-UTC (sec), which comes from the IERS bulletin.
// param t EphTime epoch of the rotation.
// param UT1mUTC, UT1-UTC in seconds, as found in the IERS bulletin.
double EarthOrientation::GAST2010(EphTime t, double UT1mUTC)
throw(Exception)
{
try {
Matrix<double> NutPreBias = PreciseEarthRotation2010(CoordTransTime(t));
// extract X and Y coords of the CIP from the matrix
// cf. sofa bpn2xy.c
double X(NutPreBias(2,0)), Y(NutPreBias(2,1));
// get T and the CIO locator s
double T(CoordTransTime(t));
double s(S(T,X,Y,IERSConvention::IERS2010));
// get ERA(UT1)
double era = EarthRotationAngle(t,UT1mUTC);
// equation of the origins. cf. sofa eors.c
double eo,ax,xs,ys,zs,p,q;
ax = X / (1.0 + NutPreBias(2,2));
xs = 1.0 - ax * X;
ys = -ax * Y;
zs = -X;
p = NutPreBias(0,0)*xs + NutPreBias(0,1)*ys + NutPreBias(0,2)*zs;
q = NutPreBias(1,0)*xs + NutPreBias(1,1)*ys + NutPreBias(1,2)*zs;
eo = ((p != 0) || (q != 0)) ? s - ::atan2(q,p) : s;
//double G(era-eo);
//G = ::fmod(G, TWOPI);
//return G;
return ::fmod(era-eo, TWOPI);
}
catch(Exception& e) { GPSTK_RETHROW(e); }
}
//---------------------------------------------------------------------------------
// Generate transformation matrix (3X3 rotation) due to the polar motion
// angles xp and yp (arcseconds), as found in the IERS bulletin;
// see class EarthOrientation.
// param xp, Earth wobble in arcseconds, as found in the IERS bulletin.
// param yp, Earth wobble in arcseconds, as found in the IERS bulletin.
// return Matrix<double>(3,3) rotation matrix
Matrix<double> EarthOrientation::PolarMotionMatrix1996(double xp, double yp)
throw()
{
xp *= ARCSEC_TO_RAD;
yp *= ARCSEC_TO_RAD;
Matrix<double> R1,R2;
R1 = rotation(-yp,1);
R2 = rotation(-xp,2);
return (R2*R1);
}
//---------------------------------------------------------------------------------
// Generate transformation matrix (3X3 rotation) due to the polar motion
// angles xp and yp (arcseconds), as found in the IERS bulletin;
// The returned matrix R transforms the CIP into TRS: V(TRS) = R * V(CIP).
// Also see class EarthOrientation, sofa pom00. Also valid for IERS2010.
// param t EphTime epoch of the rotation.
// param xp, Earth wobble in arcseconds, as found in the IERS bulletin.
// param yp, Earth wobble in arcseconds, as found in the IERS bulletin.
// return Matrix<double>(3,3) rotation matrix CIP -> TRS
Matrix<double> EarthOrientation::PolarMotionMatrix2003(EphTime t,
double xp, double yp)
throw()
{
double sp(Sprime(t)); // parameter s' provides position of TEO on CIP
LOG(DEBUG7) << "\nsp = " << fixed << setprecision(15) << setw(18) << sp
<< " with T = " << CoordTransTime(t);
xp *= ARCSEC_TO_RAD;
yp *= ARCSEC_TO_RAD;
Matrix<double> R1,R2,R3;
R3 = rotation(sp, 3);
R2 = rotation(-xp, 2);
R1 = rotation(-yp, 1);
return (R1*R2*R3);
}
//------------------------------------------------------------------------------
// Compute Fukushima-Williams angles for computing nutation, frame bias and
// precession matrices in IERS2010; cf. FukushimaWilliams().
// NB. fourth angle is Obliquity.
void EarthOrientation::FukushimaWilliams(double T, double& gamb, double& phib,
double& psib, double& eps)
throw()
{
// P03 bias+precession angles cf. sofa pfw06.c
gamb = (-0.052928 + (10.556378 + (0.4932044 + (-0.00031238 +
(-0.000002788 + 0.0000000260*T)*T)*T)*T)*T)*ARCSEC_TO_RAD;
phib = (84381.412819 + (-46.811016 + (0.0511268 + (0.00053289 +
(-0.000000440 - 0.0000000176*T)*T)*T)*T)*T)*ARCSEC_TO_RAD;
psib = (-0.041775 + (5038.481484 + (1.5584175 + (-0.00018522 +
(-0.000026452 - 0.0000000148*T)*T)*T)*T)*T)*ARCSEC_TO_RAD;
// obliquity
eps = Obliquity2010(T);
}
//---------------------------------------------------------------------------------
// Generate any of B = frame bias matrix
// PB = Precession*Bias matrix
// NPB = Nutation*Precession*Bias matrix
// for IERS 2010, given the four F-W angles with caviats, as follows.
// Get B by passing the full F-W angles at J2000 (T=0).
// Get PB by passing the full F-W angles at time time of interest.
// Get NPB by passing the full F-W angles at time time of interest with
// nutation angle corrections (NutationAngles2010()). Specifically,
// FukushimaWilliams(T, gamb, phib, psib, eps);
// NutationAngles2010(T, deps, dpsi);
// NPB = FukushimaWilliams(gamb, phib, psib+dpsi, eps+deps);
// Thus the precession matrix is computed as PB * transpose(B), and
// the nutation matrix is computes as N = NPB * transpose(PB).
// param gamb F-W angle
// param phib F-W angle
// param psib F-W angle
// param epsa F-W angle, the obliquity
// return 3x3 rotation matrix
Matrix<double> EarthOrientation::FukushimaWilliams(double gamb, double phib,
double psib, double epsa)
throw()
{
Matrix<double> R;
R = rotation(-epsa,1) *
rotation(-psib,3) *
rotation(phib,1) *
rotation(gamb,3);
return R;
}
//---------------------------------------------------------------------------------
// Nutation of the obliquity (deps) and of the longitude (dpsi), IERS 1996
// model (ref SOFA nut80.c - not found in Tech Note 21!).
// param T, the coordinate transformation time at the time of interest
// param deps, nutation of the obliquity, in radians (output)
// param dpsi, nutation of the longitude, in radians (output)
// param om, longitude mean ascending node of lunar orbit, from mean equinox
void EarthOrientation::NutationAngles1996(double T,
double& deps, double& dpsi, double& om)
throw()
{
// include coefficients array; defines coeff[Ncoeff]
#include "IERS1996NutationData.hpp"
// Define fundamental arguments in radians - these do not appear elsewhere (!?)
// Mean longitude of Moon minus mean longitude of Moon's perigee
double el = ::fmod((485866.733 + (715922.633 + (31.310 + 0.064 * T) * T) * T)
* ARCSEC_TO_RAD + ::fmod(1325.0 * T, 1.0)*TWOPI, TWOPI);
// Mean longitude of Sun minus mean longitude of Sun's perigee
double elp = ::fmod((1287099.804 + (1292581.224 + (-0.577 - 0.012 * T) * T) * T)
* ARCSEC_TO_RAD + ::fmod(99.0 * T, 1.0)*TWOPI, TWOPI);
// Mean longitude of Moon minus mean longitude of Moon's node
double f = ::fmod((335778.877 + (295263.137 + (-13.257 + 0.011 * T) * T) * T)
* ARCSEC_TO_RAD + ::fmod(1342.0 * T, 1.0)*TWOPI, TWOPI);
// Mean elongation of Moon from Sun
double d = ::fmod((1072261.307 + (1105601.328 + (-6.891 + 0.019 * T) * T) * T)
* ARCSEC_TO_RAD + ::fmod(1236.0 * T, 1.0)*TWOPI, TWOPI);
// Longitude of the mean ascending node of the lunar orbit on the
// ecliptic, measured from the mean equinox of date
om = ::fmod((450160.280 + (-482890.539 + (7.455 + 0.008 * T) * T) * T)
* ARCSEC_TO_RAD + ::fmod(-5.0 * T, 1.0)*TWOPI, TWOPI);
// sum the series
double arg,scoeff,ccoeff;
deps = dpsi = 0.0;
for(int i=Ncoeff-1; i>=0; i--) {
// form argument
double arg = coeff[i].nl * el
+ coeff[i].nlp * elp
+ coeff[i].nf * f
+ coeff[i].nd * d
+ coeff[i].nom * om;
// sine and cosine terms
scoeff = coeff[i].sp + coeff[i].spt*T;
ccoeff = coeff[i].ce + coeff[i].cet*T;
if(scoeff != 0.0) dpsi += scoeff * ::sin(arg);
if(ccoeff != 0.0) deps += ccoeff * ::cos(arg);
}
// convert from 0.1 milliarcseconds to radians
deps *= ARCSEC_TO_RAD * 1.e-4;
dpsi *= ARCSEC_TO_RAD * 1.e-4;
}
//---------------------------------------------------------------------------------
// Nutation of the obliquity (deps) and of the longitude (dpsi), IERS 2003 or
// IAU 2000A model (MHB2000 luni-solar and planetary nutation without free core n).
// param T, the coordinate transformation time at the time of interest
// param deps, nutation of the obliquity, in radians (output)
// param dpsi, nutation of the longitude, in radians (output)
void EarthOrientation::NutationAngles2003(double T, double& deps, double& dpsi)
throw()
{
// sin and cos coefficients have units 0.1 microarcsec = 1e-7as
const double COEFF_TO_RAD(ARCSEC_TO_RAD*1.0e-7);
// -----------------------------------------
// include huge static arrays of coefficients
#include "IERS2003NutationData.hpp"
// -----------------------------------------
// Lunar-Solar nutation
// fundamental arguments, in radians
double l(L(T)); // mean anomaly of the moon
double lp(::fmod( 1287104.79305 // mean anomaly of the sun MHB2000 value
+ T*(129596581.0481
+ T*( -0.5532
+ T*( 0.000136
+ T*( -0.00001149)))), ARCSEC_PER_CIRCLE) * ARCSEC_TO_RAD);
double f(::fmod( 335779.526232 // mean longitude of moon minus Omega MHB2000
+ T*(1739527262.8478
+ T*( -12.7512
+ T*( -0.001037
+ T*( 0.00000417)))), ARCSEC_PER_CIRCLE) * ARCSEC_TO_RAD);
double d(::fmod( 1072260.70369 // mean elongation moon from sun MHB2000
+ T*(1602961601.2090
+ T*( -6.3706
+ T*( 0.006593
+ T*( -0.00003169)))), ARCSEC_PER_CIRCLE) * ARCSEC_TO_RAD);
double Om(Omega2003(T)); // mean longitude of lunar ascending node
// initialize
deps = dpsi = 0.0;
int i;
double arg,sina,cosa;
// form the LS series
for(i=NLS-1; i>=0; --i) {
// argument
arg = ::fmod(LSCoeff[i].nl * l +
LSCoeff[i].nlp * lp +
LSCoeff[i].nf * f +
LSCoeff[i].nd * d +
LSCoeff[i].nom * Om, TWOPI);
sina = ::sin(arg);
cosa = ::cos(arg);
// term
deps += (LSCoeff[i].ce + LSCoeff[i].cet * T) * cosa + LSCoeff[i].se * sina;
dpsi += (LSCoeff[i].sp + LSCoeff[i].spt * T) * sina + LSCoeff[i].cp * cosa;
}
// -----------------------------------------
// Planetary nutation
// fundamental arguments, in radians.
// NB MHB2000 values are very close to IERS2003; follow SOFA here TD ??
// mean anomaly of the moon MHB2000 value
l = ::fmod(2.35555598 + 8328.6914269554 * T, TWOPI);
// mean longitude of the moon minus Omega MHB2000 value
f = ::fmod(1.627905234 + 8433.466158131 * T, TWOPI);
// mean elongation of the Moon from the Sun MHB2000 value
d = ::fmod(5.198466741 + 7771.3771468121 * T, TWOPI);
// mean longitude of lunar ascending node MHB2000 value
Om = ::fmod(2.18243920 - 33.757045 * T, TWOPI);
// mean longitude Mercury
double lme(LMe(T));
// mean longitude of Venus
double lve(LV(T));
// mean longitude of Earth
double lea(LE(T));
// mean longitude Mars
double lma(LMa(T));
// mean longitude Jupiter
double lju(LJ(T));
// mean longitude Saturn
double lsa(LS(T));
// mean longitude Uranus
double lur(LU(T));
// mean longitude Neptune
double lne(::fmod(5.321159000 + 3.8127774000 * T, TWOPI));
// general precession in longitude
double pa(Pa(T));
// form the planetary series
for(i=NP-1; i>=0; --i) {
// argument
arg = ::fmod(PCoeff[i].nl * l +
PCoeff[i].nf * f +
PCoeff[i].nd * d +
PCoeff[i].nom * Om +
PCoeff[i].nme * lme +
PCoeff[i].nve * lve +
PCoeff[i].nea * lea +
PCoeff[i].nma * lma +
PCoeff[i].nju * lju +
PCoeff[i].nsa * lsa +
PCoeff[i].nur * lur +
PCoeff[i].nne * lne +
PCoeff[i].npa * pa, TWOPI);
sina = ::sin(arg);
cosa = ::cos(arg);
// term
deps += PCoeff[i].ce * cosa + PCoeff[i].se * sina;
dpsi += PCoeff[i].sp * sina + PCoeff[i].cp * cosa;
}
// convert 0.1microarcsec to radians
deps *= COEFF_TO_RAD;
dpsi *= COEFF_TO_RAD;
return;
}
//---------------------------------------------------------------------------------
// Nutation of the obliquity (deps) and of the longitude (dpsi), IERS 2010 or
// IAU 2000A model (MHB2000 luni-solar and planetary nutation without free core n)
// with P03 adjustments. cf. sofa nut06a.c
// param T, the coordinate transformation time at the time of interest
// param deps, nutation of the obliquity, in radians (output)
// param dpsi, nutation of the longitude, in radians (output)
void EarthOrientation::NutationAngles2010(double T, double& deps, double& dpsi)
throw()
{
NutationAngles2003(T,deps,dpsi);
double fj2(-2.7774e-6 * T);
dpsi *= (1.0+0.4697e-6 + fj2);
deps *= (1.0+fj2);
}
//---------------------------------------------------------------------------------
// Compute the nutation matrix, given
// eps, the obliquity of the ecliptic, in radians,
// dpsi, the nutation in longitude (counted in the ecliptic), in radians
// deps, the nutation in obliquity, in radians.
Matrix<double> EarthOrientation::NutationMatrix(double eps,
double dpsi, double deps)
throw()
{
Matrix<double> R1 = rotation(eps, 1);
Matrix<double> R2 = rotation(-dpsi, 3);
Matrix<double> R3 = rotation(-(eps+deps), 1);
return (R3*R2*R1);
}
//------------------------------------------------------------------------------
// IERS1996 nutation matrix, a 3x3 rotation matrix, given
// param T, the coordinate transformation time at the time of interest
// return nutation matrix Matrix<double>(3,3)
Matrix<double> EarthOrientation::NutationMatrix1996(double T)
throw()
{
double eps(Obliquity1996(T)), deps, dpsi, om;
NutationAngles1996(T,deps,dpsi,om);
return NutationMatrix(eps,dpsi,deps);
}
//------------------------------------------------------------------------------
// IERS2003 nutation matrix, a 3x3 rotation matrix
// (including the frame bias matrix), given
// param T, the coordinate transformation time at the time of interest
// return nutation matrix Matrix<double>(3,3)
Matrix<double> EarthOrientation::NutationMatrix2003(double T)
throw()
{
double eps(Obliquity1996(T)), deps, dpsi; // same as Obliquity2003
NutationAngles2003(T,deps,dpsi);
// Precession rate contributions with respect to IAU 2000
// Precession and obliquity corrections (radians)
double depspr = -0.02524 * ARCSEC_TO_RAD * T;
eps += depspr;
return NutationMatrix(eps,dpsi,deps);
}
//------------------------------------------------------------------------------
// IERS2010 nutation matrix, a 3x3 rotation matrix, given
// param T, the coordinate transformation time at the time of interest;
// cf. FukushimaWilliams().
// return nutation matrix Matrix<double>(3,3)
Matrix<double> EarthOrientation::NutationMatrix2010(double T)
throw()
{
double deps,dpsi,eps;
//// get the F-W angles at epoch
//double gamb,phib,psib;
//FukushimaWilliams(T, gamb, phib, psib, eps);
//
//// get nutation angles
//NutationAngles2010(T,deps,dpsi);
//
//// construct nutation x precession x frame bias matrix
//// NB this is the same as PreciseEarthRotation2010(T)
//Matrix<double> NPB = FukushimaWilliams(gamb,phib,psib+dpsi,eps+deps);
//
//// now get PB alone - see FukushimaWilliams()
//Matrix<double> PB = FukushimaWilliams(gamb,phib,psib,eps);
//
//return (NPB * transpose(PB));
// same result
NutationAngles2010(T,deps,dpsi);
return NutationMatrix(Obliquity2010(T),dpsi,deps);
}
//------------------------------------------------------------------------------
// Compute the IERS1996 precession matrix, a 3x3 rotation matrix, given
// param T, the coordinate transformation time at the time of interest
// return precession matrix Matrix<double>(3,3)
Matrix<double> EarthOrientation::PrecessionMatrix1996(double T)
throw()
{
// IAU76 - ref McCarthy - seconds of arc
// NB t0==0 in sofa prec76.c - TD why do they do these things?
double TAR(T*ARCSEC_TO_RAD); // convert to radians
double zeta = TAR*(2306.2181 + T*(0.30188 + T*0.017998));
double theta = TAR*(2004.3109 - T*(0.42665 + T*0.041833));
double z = TAR*(2306.2181 + T*(1.09468 + T*0.018203));
Matrix<double> R1 = rotation(-zeta, 3);
Matrix<double> R2 = rotation(theta, 2);
Matrix<double> R3 = rotation(-z, 3);
Matrix<double> P = R3*R2*R1;
return P;
}
//------------------------------------------------------------------------------
// Compute the IERS2003 precession matrix, a 3x3 rotation matrix, given
// param T, the coordinate transformation time at the time of interest
// Includes the frame bias matrix. cf sofa bp00.c
// return precession matrix Matrix<double>(3,3)
Matrix<double> EarthOrientation::PrecessionMatrix2003(double T)
throw()
{
// obliquity at the J2000.0 epoch
static const double eps0(84381.448 * ARCSEC_TO_RAD);
LOG(DEBUG7) << "\nobliquity at J2000 eps0 = " << fixed << setprecision(15)
<< showpos << eps0;
// frame bias corrections in longitude and obliquity
static const double psibias = -0.041775 * ARCSEC_TO_RAD;
static const double epsbias = -0.0068192 * ARCSEC_TO_RAD;
// ICRS right ascension of the J2000.0 equinox
static const double raeps0 = -0.0146 * ARCSEC_TO_RAD;
LOG(DEBUG7) << "frame bias psi = " << fixed << setprecision(15)
<< showpos << psibias;
LOG(DEBUG7) << "frame bias eps = " << fixed << setprecision(15)
<< showpos << epsbias;
LOG(DEBUG7) << "frame bias dra = " << fixed << setprecision(15)
<< showpos << raeps0;
// precession angles
double psia((5038.7784 + (-1.07259 + (-0.001147)*T)*T)*T*ARCSEC_TO_RAD);
double epsa( eps0 + ((0.05127 + (-0.007726)*T)*T)*T*ARCSEC_TO_RAD);
double chia(( 10.5526 + (-2.38064 + (-0.001125)*T)*T)*T*ARCSEC_TO_RAD);
LOG(DEBUG7) << "\nprecession angle psi = " << fixed << setprecision(15)
<< showpos << psia;
LOG(DEBUG7) << "precession angle eps = " << fixed << setprecision(15)
<< showpos << epsa;
LOG(DEBUG7) << "precession angle chi = " << fixed << setprecision(15)
<< showpos << chia;
// Precession rate contributions with respect to IAU 2000 p-n models
// Precession and obliquity corrections (radians) cf sofa pr00.c
double dpsipr, depspr;
PrecessionRateCorrections2003(T, dpsipr, depspr);
// Apply precession corrections
LOG(DEBUG7) << "precession rate = " << fixed << setprecision(15) << showpos
<< dpsipr << " " << depspr;
psia += dpsipr;
epsa += depspr;
// Frame bias matrix
Matrix<double> R1 = rotation(raeps0, 3);
Matrix<double> R2 = rotation(psibias * ::sin(eps0), 2);
Matrix<double> R3 = rotation(-epsbias, 1);
Matrix<double> FrameBias(R3*R2*R1);
LOG(DEBUG7) << "\nframe bias matrix:\n" << fixed << setprecision(15) << showpos
<< FrameBias;
// Precession matrix
R1 = rotation(eps0, 1);
R2 = rotation(-psia, 3);
R3 = rotation(-epsa, 1);
Matrix<double> R4 = rotation(chia, 3);
Matrix<double> Precess(R4*R3*R2*R1);
LOG(DEBUG7) << "\nprecession matrix:\n" << fixed << setprecision(15) << showpos
<< Precess;
LOG(DEBUG7) << "\nprecession*framebias matrix:\n" << fixed << setprecision(15)
<< showpos << (Precess*FrameBias);
return (Precess*FrameBias);
}
//------------------------------------------------------------------------------
// Compute the IERS2003 precession and obliquity rate corrections, IAU 2000
// param T, the coordinate transformation time at the time of interest
// return precession, obliquity corrections in radians
void EarthOrientation::PrecessionRateCorrections2003(double T,
double& dpsi, double& deps)
throw()
{
// Precession rate contributions with respect to IAU 2000
// Precession and obliquity corrections (radians)
dpsi = -0.29965 * ARCSEC_TO_RAD * T;
deps = -0.02524 * ARCSEC_TO_RAD * T;
}
//------------------------------------------------------------------------------
// IERS2010 frame bias matrix, a 3x3 rotation matrix; cf. FukushimaWilliams().
// return frame bias matrix Matrix<double>(3,3)
Matrix<double> EarthOrientation::BiasMatrix2010(void)
throw()
{
// get F-W angles at J2000
double gamb,phib,psib,epsa;
FukushimaWilliams(0.0, gamb, phib, psib, epsa);
// frame bias matrix
return FukushimaWilliams(gamb, phib, psib, epsa);
}
//---------------------------------------------------------------------------------
// Compute the IERS2010 precession matrix, a 3x3 rotation matrix, given
// param T, the coordinate transformation time at the time of interest
// Does not include the frame bias matrix. Cf. FukushimaWilliams().
// return precession matrix Matrix<double>(3,3)
Matrix<double> EarthOrientation::PrecessionMatrix2010(double T)
throw()
{
// the F-W angles
double gamb,phib,psib,epsa;
// get frame bias matrix
Matrix<double> B = BiasMatrix2010();
// get F-W angles at epoch
FukushimaWilliams(T, gamb, phib, psib, epsa);
// precession x frame bias matrix
Matrix<double> PB = FukushimaWilliams(gamb, phib, psib, epsa);
return (PB * transpose(B));
}
//------------------------------------------------------------------------------
// Generate precise transformation matrix (3X3 rotation) for Earth motion due to
// precession, nutation and frame bias (NPB matrix), at the given time of interest,
// for IERS 2003.
// param T CoordTransTime of interest
// return 3x3 rotation matrix
Matrix<double> EarthOrientation::PreciseEarthRotation2003(double T)
throw(Exception)
{
try {
Matrix<double> N = NutationMatrix2003(T);
Matrix<double> P = PrecessionMatrix2003(T); // includes bias
//Matrix<double> NPB(N*P);
//LOG(DEBUG7) << "\nNPB matrix:\n" << fixed << setprecision(15) << setw(18)
// << showpos << NPB;
return (N*P);
}
catch(Exception& e) { GPSTK_RETHROW(e); }
}
//------------------------------------------------------------------------------
// Generate precise transformation matrix (3X3 rotation) for Earth motion due to
// precession, nutation and frame bias (NPB matrix), at the given time of interest,
// for IERS 2010.
// param T CoordTransTime of interest
// return 3x3 rotation matrix
Matrix<double> EarthOrientation::PreciseEarthRotation2010(double T)
throw(Exception)
{
try {
double deps,dpsi,epsa;
// get the F-W angles
double gamb,phib,psib;
FukushimaWilliams(T, gamb, phib, psib, epsa);
// get nutation angles
NutationAngles2010(T,deps,dpsi);
// construct nutation x precession x frame bias matrix
return FukushimaWilliams(gamb,phib,psib+dpsi,epsa+deps);
}
catch(Exception& e) { GPSTK_RETHROW(e); }
}
//---------------------------------------------------------------------------------
// Generate the full transformation matrix (3x3 rotation) relating the ECEF
// frame to the conventional inertial frame, using IERS 1996 conventions.
// Input is the time of interest, the polar motion angles xp and yp (arcsecs),
// and UT1-UTC (sec) (xp,yp and UT1-UTC are just as found in the IERS bulletin;
// see class EarthOrientation).
Matrix<double> EarthOrientation::ECEFtoInertial1996(EphTime t,
double xp, double yp, double UT1mUTC, bool reduced)
throw(Exception)
{
try {
Matrix<double> P,N,W,S;
double T=CoordTransTime(t);
// precession
P = PrecessionMatrix1996(T);
LOG(DEBUG7) << "\nprecession matrix:\n" << fixed << setprecision(15)
<< setw(18) << showpos << P;
// nutation
double eps,deps,dpsi,om;
// mean obliquity radians
eps = Obliquity1996(T);
LOG(DEBUG7) << "\nmean obliquity " << fixed << setprecision(15)
<< showpos << eps;
// nutation angles - om is used in gast
NutationAngles1996(T,deps,dpsi,om);
LOG(DEBUG7) << "\nnutation angles psi eps " << fixed << setprecision(15)
<< showpos << dpsi << " " << deps;
// nutation matrix
N = NutationMatrix(eps,dpsi,deps);
LOG(DEBUG7) << "\nnutation matrix:\n" << fixed << setprecision(15)
<< setw(18) << showpos << N;
LOG(DEBUG7) << "\nNPB matrix:\n" << fixed << setprecision(15)
<< setw(18) << showpos << N*P;
// if reduced (NGA), correct UT1mUTC for tides
double UT1mUT1R,dlodR,domegaR;
if(reduced) {
UT1mUTCTidalCorrections(T, UT1mUT1R, dlodR, domegaR);
UT1mUTC = UT1mUT1R - UT1mUTC;
}
double g = gast1996(t, om, eps, dpsi, UT1mUTC);
LOG(DEBUG7) << "\nGAST = " << fixed << setprecision(15)
<< showpos << g*RAD_TO_DEG;
S = rotation(g,3);
LOG(DEBUG7) << "\ncelestial-to-terrestrial matrix (no polar motion):\n"
<< fixed << setprecision(15) << setw(18) << showpos << S*N*P;
// Polar Motion
W = PolarMotionMatrix1996(xp, yp);
LOG(DEBUG7) << "\npolar motion matrix:\n" << fixed << setprecision(15)
<< setw(18) << showpos << W;
return transpose(W*S*N*P);
}
catch(Exception& e) { GPSTK_RETHROW(e); }
}
//---------------------------------------------------------------------------------
// Generate the full transformation matrix (3x3 rotation) relating the ECEF
// frame to the conventional inertial frame, using IERS 2003 conventions.
// Input is the time of interest, the polar motion angles xp and yp (arcsecs),
// and UT1-UTC (sec) (xp,yp and UT1-UTC are just as found in the IERS bulletin;
// see class EarthOrientation).
Matrix<double> EarthOrientation::ECEFtoInertial2003(EphTime t,
double xp, double yp, double UT1mUTC)
throw(Exception)
{
try {
Matrix<double> P,N,R,W;
double T(CoordTransTime(t));
if(LOGlevel >= DEBUG7) {
double gmst = GMST2003(t, UT1mUTC);
LOG(DEBUG7) << "\nGMST = " << fixed << setprecision(15)
<< showpos << gmst*RAD_TO_DEG;
double gast = GAST2003(t, UT1mUTC);
LOG(DEBUG7) << "\nGAST = " << fixed << setprecision(15)
<< showpos << gast*RAD_TO_DEG;
}
// nutation
double deps, dpsi, dpsipr, depspr;
NutationAngles2003(T,deps,dpsi);
LOG(DEBUG7) << "\nnutation angles psi eps " << fixed << setprecision(15)
<< showpos << dpsi << " " << deps;
// Precession rate contributions with respect to IAU 2000
// Precession and obliquity corrections (radians)
PrecessionRateCorrections2003(T, dpsipr, depspr);
LOG(DEBUG7) << "\nprecession-rate " << fixed << setprecision(15)
<< showpos << dpsipr << " " << depspr;
double eps(Obliquity1996(T)); // same as 2003
LOG(DEBUG7) << "\nmean obliquity " << fixed << setprecision(15)
<< showpos << eps;
eps += depspr;
N = NutationMatrix(eps,dpsi,deps);
LOG(DEBUG7) << "\nnutation matrix:\n" << fixed << setprecision(15)
<< setw(18) << showpos << N;
// precession
P = PrecessionMatrix2003(T);
Matrix<double> NPB(N*P);
LOG(DEBUG7) << "\nNPB matrix:\n" << fixed << setprecision(15) << setw(18)
<< showpos << NPB;
// ERA replaces GAST in the Earth rotation matrix
double era(EarthRotationAngle(t,UT1mUTC));
LOG(DEBUG7) << "\nERA = " << fixed << setprecision(15) << showpos
<< era*RAD_TO_DEG;
R = rotation(era,3);
//double gast = GAST2003(t, UT1mUTC);
//R = rotation(gast,3);
// polar motion
W = PolarMotionMatrix2003(t, xp, yp);
LOG(DEBUG7) << "\npolar motion matrix:\n" << fixed << setprecision(15)
<< setw(18) << showpos << W;
return transpose(W*R*N*P);
}
catch(Exception& e) { GPSTK_RETHROW(e); }
}
//---------------------------------------------------------------------------------
// Generate the full transformation matrix (3x3 rotation) relating the ECEF
// frame to the conventional inertial frame, using IERS 2010 conventions.
// Input is the time of interest, the polar motion angles xp and yp (arcsecs),
// and UT1-UTC (sec) (xp,yp and UT1-UTC are just as found in the IERS bulletin;
// see class EarthOrientation).
Matrix<double> EarthOrientation::ECEFtoInertial2010(EphTime t,
double xp, double yp, double UT1mUTC)
throw(Exception)
{
try {
double T(CoordTransTime(t));
// get the CIO coordinates and s
// note that X,Y could also be obtained as (2,0),(2,1) components
// of FukushimaWilliams()
double X,Y,s;
XYCIO(T, X, Y);
s = S(T,X,Y,IERSConvention::IERS2010);
LOG(DEBUG7) << "X = " << fixed << setprecision(15) << showpos << X;
LOG(DEBUG7) << "Y = " << fixed << setprecision(15) << showpos << Y;
LOG(DEBUG7) << "s\" = " << fixed << setprecision(15) << s/ARCSEC_TO_RAD;
// compute transformation GCRS-to-CIRS or inertial-to-intermediate-celestial
// cf. sofa c2ixys
double r2(X*X+Y*Y); // squared radius
double e(r2 != 0.0 ? ::atan2(Y, X) : 0.0); // spherical angles
double d(::atan(::sqrt(r2/(1.0-r2)))); //
Matrix<double> GCRStoCIRS;
GCRStoCIRS = rotation(-(e+s),3) * rotation(d, 2) * rotation(e, 3);
LOG(DEBUG7) << "\nNPB matrix:\n" << fixed << setprecision(15) << setw(18)
<< showpos << GCRStoCIRS;
// note that we could have called PreciseEarthRotation2010() instead
// get ERA at UT1
double era = EarthRotationAngle(t,UT1mUTC);
LOG(DEBUG7) << "\nERA = " << fixed << setprecision(15)
<< showpos << era*RAD_TO_DEG;
// compute transf. CIRS-to-TIRS or intermediate-celestial-to-terrestrial
Matrix<double> CIRStoTIRS;
CIRStoTIRS = rotation(era, 3);
LOG(DEBUG7) << "\ncelestial-to-terrestrial matrix (no polar motion):\n"
<< fixed << setprecision(15) << setw(18) << showpos
<< CIRStoTIRS * GCRStoCIRS;
// compute the polar motion matrix, TIRS-to-ITRS
//double sprime(Sprime(T));
Matrix<double> PolarMotion(PolarMotionMatrix2003(t, xp, yp)); // 2010 == 2003
LOG(DEBUG7) << "\npolar motion matrix:\n" << fixed << setprecision(15)
<< setw(18) << showpos << PolarMotion;
// combine to get GCRS-to-ITRS
Matrix<double> GCRStoITRS;
GCRStoITRS = PolarMotion * CIRStoTIRS * GCRStoCIRS;
// invert to get ITRS-to-GCRS or ECEFtoInertial
return (transpose(GCRStoITRS));
}
catch(Exception& e) { GPSTK_RETHROW(e); }
}
} // end namespace gpstk
/*=============================================================================
** SOME of these routines, as noted, are based on, but not simply copied from, SOFA;
** SOFA has the following license.
**
** Copyright (C) 2012
** Standards Of Fundamental Astronomy Board
** of the International Astronomical Union.
**
** =====================
** SOFA Software License
** =====================
**
** NOTICE TO USER:
**
** BY USING THIS SOFTWARE YOU ACCEPT THE FOLLOWING SIX TERMS AND
** CONDITIONS WHICH APPLY TO ITS USE.
**
** 1. The Software is owned by the IAU SOFA Board ("SOFA").
**
** 2. Permission is granted to anyone to use the SOFA software for any
** purpose, including commercial applications, free of charge and
** without payment of royalties, subject to the conditions and
** restrictions listed below.
**
** 3. You (the user) may copy and distribute SOFA source code to others,
** and use and adapt its code and algorithms in your own software,
** on a world-wide, royalty-free basis. That portion of your
** distribution that does not consist of intact and unchanged copies
** of SOFA source code files is a "derived work" that must comply
** with the following requirements:
**
** a) Your work shall be marked or carry a statement that it
** (i) uses routines and computations derived by you from
** software provided by SOFA under license to you; and
** (ii) does not itself constitute software provided by and/or
** endorsed by SOFA.
**
** b) The source code of your derived work must contain descriptions
** of how the derived work is based upon, contains and/or differs
** from the original SOFA software.
**
** c) The names of all routines in your derived work shall not
** include the prefix "iau" or "sofa" or trivial modifications
** thereof such as changes of case.
**
** d) The origin of the SOFA components of your derived work must
** not be misrepresented; you must not claim that you wrote the
** original software, nor file a patent application for SOFA
** software or algorithms embedded in the SOFA software.
**
** e) These requirements must be reproduced intact in any source
** distribution and shall apply to anyone to whom you have
** granted a further right to modify the source code of your
** derived work.
**
** Note that, as originally distributed, the SOFA software is
** intended to be a definitive implementation of the IAU standards,
** and consequently third-party modifications are discouraged. All
** variations, no matter how minor, must be explicitly marked as
** such, as explained above.
**
** 4. You shall not cause the SOFA software to be brought into
** disrepute, either by misuse, or use for inappropriate tasks, or
** by inappropriate modification.
**
** 5. The SOFA software is provided "as is" and SOFA makes no warranty
** as to its use or performance. SOFA does not and cannot warrant
** the performance or results which the user may obtain by using the
** SOFA software. SOFA makes no warranties, express or implied, as
** to non-infringement of third party rights, merchantability, or
** fitness for any particular purpose. In no event will SOFA be
** liable to the user for any consequential, incidental, or special
** damages, including any lost profits or lost savings, even if a
** SOFA representative has been advised of such damages, or for any
** claim by any third party.
**
** 6. The provision of any version of the SOFA software under the terms
** and conditions specified herein does not imply that future
** versions will also be made available under the same terms and
** conditions.
*
** In any published work or commercial product which uses the SOFA
** software directly, acknowledgement (see www.iausofa.org) is
** appreciated.
**
** Correspondence concerning SOFA software should be addressed as
** follows:
**
** By email: sofa@ukho.gov.uk
** By post: IAU SOFA Center
** HM Nautical Almanac Office
** UK Hydrographic Office
** Admiralty Way, Taunton
** Somerset, TA1 2DN
** United Kingdom
**
**=============================================================================*/
| 44.221763 | 86 | 0.507616 | [
"object",
"vector",
"model"
] |
03cc8de682582be0c07edeb397b0b0e453b1366b | 61,133 | cpp | C++ | pwiz_tools/Bumbershoot/myrimatch/myrimatch.cpp | austinkeller/pwiz | aa8e575cb40fd5e97cc7d922e4d8da44c9277cca | [
"Apache-2.0"
] | null | null | null | pwiz_tools/Bumbershoot/myrimatch/myrimatch.cpp | austinkeller/pwiz | aa8e575cb40fd5e97cc7d922e4d8da44c9277cca | [
"Apache-2.0"
] | null | null | null | pwiz_tools/Bumbershoot/myrimatch/myrimatch.cpp | austinkeller/pwiz | aa8e575cb40fd5e97cc7d922e4d8da44c9277cca | [
"Apache-2.0"
] | null | null | null | //
// $Id$
//
// 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.
//
// The Original Code is the MyriMatch search engine.
//
// The Initial Developer of the Original Code is Matt Chambers.
//
// Copyright 2009 Vanderbilt University
//
// Contributor(s): Surendra Dasari
//
#include "stdafx.h"
#include "myrimatch.h"
#include "boost/lockfree/queue.hpp"
#include "pwiz/data/msdata/Version.hpp"
#include "pwiz/data/proteome/Version.hpp"
#include "pwiz/utility/misc/DateTime.hpp"
#include "PTMVariantList.h"
#include "myrimatchVersion.hpp"
namespace freicore
{
namespace myrimatch
{
proteinStore proteins;
boost::lockfree::queue<size_t> proteinTasks;
SearchStatistics searchStatistics;
SpectraList spectra;
SpectraMassMapList avgSpectraByChargeState;
SpectraMassMapList monoSpectraByChargeState;
RunTimeConfig* g_rtConfig;
int InitProcess( argList_t& args )
{
//cout << g_hostString << " is initializing." << endl;
if( g_pid == 0 )
{
cout << "MyriMatch " << Version::str() << " (" << Version::LastModified() << ")\n" <<
MYRIMATCH_LICENSE << endl;
}
string usage = "Usage: " + lexical_cast<string>(bfs::path(args[0]).filename()) + " [optional arguments] <input spectra filemask 1> [input spectra filemask 2] ...\n"
"Optional arguments:\n"
"-cfg <config filepath> : specify a configuration file other than the default\n"
"-workdir <working directory> : change working directory (where output files are written)\n"
"-cpus <value> : force use of <value> worker threads\n"
"-ignoreConfigErrors : ignore errors in configuration file or the command-line\n"
"-AnyParameterName <value> : override the value of the given parameter to <value>\n"
"-dump : show runtime configuration settings before starting the run\n";
bool ignoreConfigErrors = false;
g_endianType = GetHostEndianType();
g_numWorkers = GetNumProcessors();
// First set the working directory, if provided
for( size_t i=1; i < args.size(); ++i )
{
if( args[i] == "-workdir" && i+1 <= args.size() )
{
chdir( args[i+1].c_str() );
args.erase( args.begin() + i );
} else if( args[i] == "-cpus" && i+1 <= args.size() )
{
g_numWorkers = atoi( args[i+1].c_str() );
args.erase( args.begin() + i );
} else if( args[i] == "-ignoreConfigErrors" )
{
ignoreConfigErrors = true;
} else
continue;
args.erase( args.begin() + i );
--i;
}
g_rtConfig = new RunTimeConfig(!ignoreConfigErrors);
g_rtSharedConfig = (BaseRunTimeConfig*) g_rtConfig;
if( g_pid == 0 )
{
for( size_t i=1; i < args.size(); ++i )
{
if( args[i] == "-cfg" && i+1 <= args.size() )
{
if( g_rtConfig->initializeFromFile( args[i+1] ) )
{
cerr << "Unable to find runtime configuration at \"" << args[i+1] << "\"." << endl;
return 1;
}
args.erase( args.begin() + i );
} else
continue;
args.erase( args.begin() + i );
--i;
}
if( args.size() < 2 )
{
cerr << "Not enough arguments.\n\n" << usage << endl;
return 1;
}
if( !g_rtConfig->initialized() )
{
if( g_rtConfig->initializeFromFile() )
{
cerr << "Could not find the default configuration file (hard-coded defaults in use)." << endl;
}
}
#ifdef USE_MPI
if( g_numChildren > 0 )
TransmitConfigsToChildProcesses();
#endif
} else // child process
{
#ifdef USE_MPI
ReceiveConfigsFromRootProcess();
#endif
}
// Command line overrides happen after config file has been distributed but before PTM parsing
RunTimeVariableMap vars = g_rtConfig->getVariables();
for( RunTimeVariableMap::iterator itr = vars.begin(); itr != vars.end(); ++itr )
{
string varName;
varName += "-" + itr->first;
for( size_t i=1; i < args.size(); ++i )
{
if( args[i].find( varName ) == 0 && i+1 <= args.size() )
{
//cout << varName << " " << itr->second << " " << args[i+1] << endl;
itr->second = args[i+1];
args.erase( args.begin() + i );
args.erase( args.begin() + i );
--i;
}
}
}
g_rtConfig->setVariables( vars );
if( g_pid == 0 )
{
for( size_t i=1; i < args.size(); ++i )
{
if( args[i] == "-dump" || args[i] == "-help" || args[i] == "--help" )
{
g_rtConfig->dump();
if (args[i] == "-help" || args[i] == "--help")
throw pwiz::util::usage_exception(usage);
args.erase( args.begin() + i );
--i;
}
}
for( size_t i=1; i < args.size(); ++i )
{
if( args[i][0] == '-' )
{
if (!ignoreConfigErrors)
{
cerr << "Error: unrecognized parameter \"" << args[i] << "\"" << endl;
return 1;
}
cerr << "Warning: ignoring unrecognized parameter \"" << args[i] << "\"" << endl;
args.erase( args.begin() + i );
--i;
}
}
}
if( g_rtConfig->ProteinDatabase.empty() )
{
if( g_pid == 0 ) cerr << "No FASTA protein database specified on command-line or in configuration file.\n\n" << usage << endl;
return 1;
}
if (args.size() == 1)
{
if( g_pid == 0 ) cerr << "No data sources specified.\n\n" << usage << endl;
return 1;
}
return 0;
}
int InitWorkerGlobals()
{
spectra.sort( spectraSortByID() );
if( spectra.empty() )
return 0;
// Determine the maximum seen charge state
BOOST_FOREACH(Spectrum* s, spectra)
g_rtConfig->maxChargeStateFromSpectra = max(s->possibleChargeStates.back(), g_rtConfig->maxChargeStateFromSpectra);
g_rtConfig->maxFragmentChargeState = ( g_rtConfig->MaxFragmentChargeState > 0 ? g_rtConfig->MaxFragmentChargeState+1 : g_rtConfig->maxChargeStateFromSpectra );
g_rtConfig->monoPrecursorMassTolerance.clear();
g_rtConfig->avgPrecursorMassTolerance.clear();
for( int z=1; z <= g_rtConfig->maxChargeStateFromSpectra; ++z )
{
g_rtConfig->monoPrecursorMassTolerance.push_back( MZTolerance(g_rtConfig->MonoPrecursorMzTolerance.value * z,
g_rtConfig->MonoPrecursorMzTolerance.units) );
g_rtConfig->avgPrecursorMassTolerance.push_back( MZTolerance(g_rtConfig->AvgPrecursorMzTolerance.value * z,
g_rtConfig->AvgPrecursorMzTolerance.units) );
}
size_t monoPrecursorHypotheses = 0, avgPrecursorHypotheses = 0;
// Create a map of precursor masses to the spectrum indices
monoSpectraByChargeState.resize( g_rtConfig->maxChargeStateFromSpectra );
avgSpectraByChargeState.resize( g_rtConfig->maxChargeStateFromSpectra );
for( int z=0; z < g_rtConfig->maxChargeStateFromSpectra; ++z )
{
BOOST_FOREACH(Spectrum* s, spectra)
BOOST_FOREACH(const PrecursorMassHypothesis& p, s->precursorMassHypotheses)
if (p.charge != z+1) continue;
else if (g_rtConfig->precursorMzToleranceRule == MzToleranceRule_Mono ||
p.massType == MassType_Monoisotopic && g_rtConfig->precursorMzToleranceRule != MzToleranceRule_Avg)
monoSpectraByChargeState[z].insert(make_pair(p.mass, make_pair(s, p)));
else
avgSpectraByChargeState[z].insert(make_pair(p.mass, make_pair(s, p)));
monoPrecursorHypotheses += monoSpectraByChargeState[z].size();
avgPrecursorHypotheses += avgSpectraByChargeState[z].size();
}
if( g_numChildren == 0 || g_pid == 0 )
cout << "Monoisotopic mass precursor hypotheses: " << monoPrecursorHypotheses << endl
<< "Average mass precursor hypotheses: " << avgPrecursorHypotheses << endl;
g_rtConfig->curMinPeptideMass = spectra.front()->precursorMassHypotheses.front().mass;
g_rtConfig->curMaxPeptideMass = 0;
// find the smallest and largest precursor masses
size_t maxPeakBins = (size_t) spectra.front()->totalPeakSpace;
BOOST_FOREACH(Spectrum* s, spectra)
{
g_rtConfig->curMinPeptideMass = min(g_rtConfig->curMinPeptideMass, s->precursorMassHypotheses.front().mass);
g_rtConfig->curMaxPeptideMass = max(g_rtConfig->curMaxPeptideMass, s->precursorMassHypotheses.back().mass);
double fragMassError = g_rtConfig->FragmentMzTolerance.units == MZTolerance::PPM ? (s->totalPeakSpace/2.0 * g_rtConfig->FragmentMzTolerance.value * 1e-6) : g_rtConfig->FragmentMzTolerance.value;
size_t totalPeakBins = (size_t) round( s->totalPeakSpace / ( fragMassError * 2.0 ) );
if( totalPeakBins > maxPeakBins )
maxPeakBins = totalPeakBins;
}
// adjust for precursor tolerance
g_rtConfig->curMinPeptideMass -= g_rtConfig->AvgPrecursorMzTolerance;
g_rtConfig->curMaxPeptideMass += g_rtConfig->AvgPrecursorMzTolerance;
// adjust for DynamicMods
g_rtConfig->curMinPeptideMass = min( g_rtConfig->curMinPeptideMass, g_rtConfig->curMinPeptideMass - g_rtConfig->largestPositiveDynamicModMass );
g_rtConfig->curMaxPeptideMass = max( g_rtConfig->curMaxPeptideMass, g_rtConfig->curMaxPeptideMass - g_rtConfig->largestNegativeDynamicModMass );
// adjust for user settings
g_rtConfig->curMinPeptideMass = max( g_rtConfig->curMinPeptideMass, g_rtConfig->MinPeptideMass );
g_rtConfig->curMaxPeptideMass = min( g_rtConfig->curMaxPeptideMass, g_rtConfig->MaxPeptideMass );
double minResidueMass = AminoAcid::Info::record('G').residueFormula.monoisotopicMass();
double maxResidueMass = AminoAcid::Info::record('W').residueFormula.monoisotopicMass();
// calculate minimum length of a peptide made entirely of tryptophan over the minimum mass
int curMinPeptideLength = max( g_rtConfig->MinPeptideLength,
(int) floor( g_rtConfig->curMinPeptideMass /
maxResidueMass ) );
// calculate maximum length of a peptide made entirely of glycine under the maximum mass
int curMaxPeptideLength = min((int) ceil( g_rtConfig->curMaxPeptideMass / minResidueMass ),
g_rtConfig->MaxPeptideLength);
// set digestion parameters
Digestion::Specificity specificity = (Digestion::Specificity) g_rtConfig->MinTerminiCleavages;
g_rtConfig->digestionConfig = Digestion::Config( g_rtConfig->MaxMissedCleavages,
curMinPeptideLength,
curMaxPeptideLength,
specificity );
//cout << g_hostString << " is precaching factorials up to " << (int) maxPeakSpace << "." << endl;
g_lnFactorialTable.resize( maxPeakBins );
//cout << g_hostString << " finished precaching factorials." << endl;
if( g_numChildren == 0 || g_pid == 0 )
{
//cout << "Smallest observed precursor is " << g_rtConfig->curMinPeptideMass << " Da." << endl;
//cout << "Largest observed precursor is " << g_rtConfig->curMaxPeptideMass << " Da." << endl;
cout << "Min. effective peptide mass is " << g_rtConfig->curMinPeptideMass << endl;
cout << "Max. effective peptide mass is " << g_rtConfig->curMaxPeptideMass << endl;
cout << "Min. effective peptide length is " << curMinPeptideLength << endl;
cout << "Max. effective peptide length is " << curMaxPeptideLength << endl;
}
return 0;
}
void DestroyWorkerGlobals()
{
}
void ComputeXCorrs()
{
Timer timer;
timer.Begin();
if( g_numChildren == 0 )
cout << "Computing cross-correlations." << endl;
// For each spectrum, iterate through its result set and compute the XCorr.
BOOST_FOREACH(Spectrum* s, spectra)
s->ComputeXCorrs();
if( g_numChildren == 0 )
cout << "Finished computing cross-correlations; " << timer.End() << " seconds elapsed." << endl;
}
void WriteOutputToFile( const string& dataFilename,
string startTime,
string startDate,
float totalSearchTime,
vector< size_t > opcs,
vector< size_t > fpcs,
SearchStatistics& overallStats )
{
int numSpectra = 0;
int numMatches = 0;
int numLoci = 0;
string filenameAsScanName = path(dataFilename).filename().string();
BOOST_FOREACH(Spectrum* s, spectra)
{
++ numSpectra;
spectra.setId( s->id, SpectrumId( filenameAsScanName, s->id.nativeID, s->id.charge ) );
s->computeSecondaryScores();
}
RunTimeVariableMap vars = g_rtConfig->getVariables();
RunTimeVariableMap fileParams;
for( RunTimeVariableMap::iterator itr = vars.begin(); itr != vars.end(); ++itr )
fileParams[ string("Config: ") + itr->first ] = itr->second;
fileParams["SearchEngine: Name"] = "MyriMatch";
fileParams["SearchEngine: Version"] = Version::str();
fileParams["SearchTime: Started"] = startTime + " on " + startDate;
fileParams["SearchTime: Stopped"] = GetTimeString() + " on " + GetDateString();
fileParams["SearchTime: Duration"] = lexical_cast<string>( totalSearchTime ) + " seconds";
fileParams["SearchStats: Nodes"] = lexical_cast<string>( g_numProcesses );
fileParams["SearchStats: Overall"] = (string) overallStats;
fileParams["PeakCounts: Mean: Original"] = lexical_cast<string>( opcs[5] );
fileParams["PeakCounts: Mean: Filtered"] = lexical_cast<string>( fpcs[5] );
fileParams["PeakCounts: Min/Max: Original"] = lexical_cast<string>( opcs[0] ) + " / " + lexical_cast<string>( opcs[1] );
fileParams["PeakCounts: Min/Max: Filtered"] = lexical_cast<string>( fpcs[0] ) + " / " + lexical_cast<string>( fpcs[1] );
fileParams["PeakCounts: 1stQuartile: Original"] = lexical_cast<string>( opcs[2] );
fileParams["PeakCounts: 1stQuartile: Filtered"] = lexical_cast<string>( fpcs[2] );
fileParams["PeakCounts: 2ndQuartile: Original"] = lexical_cast<string>( opcs[3] );
fileParams["PeakCounts: 2ndQuartile: Filtered"] = lexical_cast<string>( fpcs[3] );
fileParams["PeakCounts: 3rdQuartile: Original"] = lexical_cast<string>( opcs[4] );
fileParams["PeakCounts: 3rdQuartile: Filtered"] = lexical_cast<string>( fpcs[4] );
string extension = g_rtConfig->outputFormat == pwiz::identdata::IdentDataFile::Format_pepXML ? ".pepXML" : ".mzid";
string outputFilename = filenameAsScanName + g_rtConfig->OutputSuffix + extension;
cout << "Writing search results to file \"" << outputFilename << "\"." << endl;
spectra.write(dataFilename,
g_rtConfig->outputFormat,
g_rtConfig->OutputSuffix,
"MyriMatch",
Version::str(),
"http://forge.fenchurch.mc.vanderbilt.edu/projects/myrimatch/",
g_dbPath + g_dbFilename,
g_rtConfig->cleavageAgent,
g_rtConfig->cleavageAgentRegex,
g_rtConfig->decoyPrefix,
fileParams);
}
void PrepareSpectra()
{
int numSpectra = (int) spectra.size();
Timer timer;
if( g_numChildren == 0 )
{
cout << "Trimming spectra with less than " << g_rtConfig->minIntensityClassCount << " peaks." << endl;
}
int preTrimCount = spectra.filterByPeakCount ( g_rtConfig->minIntensityClassCount );
//int preTrimCount = spectra.filterByPeakCount( 10 );
numSpectra = (int) spectra.size();
if( g_numChildren == 0 )
{
cout << "Trimmed " << preTrimCount << " spectra for being too sparse." << endl;
cout << "Preprocessing " << numSpectra << " spectra." << endl;
}
timer.Begin();
BOOST_FOREACH(Spectrum* s, spectra)
{
try
{
s->Preprocess();
} catch( std::exception& e )
{
stringstream msg;
msg << "preprocessing spectrum " << s->id << ": " << e.what();
throw runtime_error( msg.str() );
} catch( ... )
{
stringstream msg;
msg << "preprocessing spectrum " << s->id;
throw runtime_error( msg.str() );
}
}
// Trim spectra that have observed precursor masses outside the user-configured range
// (erase the peak list and the trim 0 peaks out)
BOOST_FOREACH(Spectrum* s, spectra)
{
if( s->precursorMassHypotheses.back().mass < g_rtConfig->MinPeptideMass ||
s->precursorMassHypotheses.front().mass > g_rtConfig->MaxPeptideMass )
{
s->peakPreData.clear();
s->peakData.clear();
}
}
if( g_numChildren == 0 )
{
cout << "Finished preprocessing its spectra; " << timer.End() << " seconds elapsed." << endl;
cout << "Trimming spectra with less than " << g_rtConfig->minIntensityClassCount << " peaks." << endl;
cout << "Trimming spectra with precursors too small or large: " <<
g_rtConfig->MinPeptideMass << " - " << g_rtConfig->MaxPeptideMass << endl;
}
int postTrimCount = spectra.filterByPeakCount( g_rtConfig->minIntensityClassCount );
if( g_numChildren == 0 )
{
cout << "Trimmed " << postTrimCount << " spectra." << endl;
}
}
boost::int64_t QuerySequence( const DigestedPeptide& candidate, const string& protein, bool isDecoy, bool estimateComparisonsOnly = false )
{
boost::int64_t numComparisonsDone = 0;
string sequence = PEPTIDE_N_TERMINUS_STRING + candidate.sequence() + PEPTIDE_C_TERMINUS_STRING;
double monoCalculatedMass = candidate.monoisotopicMass();
double avgCalculatedMass = candidate.molecularWeight();
for( int z = 0; z < g_rtConfig->maxChargeStateFromSpectra; ++z )
{
int fragmentChargeState = min( z, g_rtConfig->maxFragmentChargeState-1 );
vector< double > sequenceIons;
// Look up the spectra that have precursor mass hypotheses between mass + massError and mass - massError
vector<SpectraMassMap::iterator> candidateHypotheses;
SpectraMassMap::iterator cur, end;
end = monoSpectraByChargeState[z].upper_bound( monoCalculatedMass + g_rtConfig->monoPrecursorMassTolerance[z] );
for( cur = monoSpectraByChargeState[z].lower_bound( monoCalculatedMass - g_rtConfig->monoPrecursorMassTolerance[z] ); cur != end; ++cur )
candidateHypotheses.push_back(cur);
end = avgSpectraByChargeState[z].upper_bound( avgCalculatedMass + g_rtConfig->avgPrecursorMassTolerance[z] );
for( cur = avgSpectraByChargeState[z].lower_bound( avgCalculatedMass - g_rtConfig->avgPrecursorMassTolerance[z] ); cur != end; ++cur )
candidateHypotheses.push_back(cur);
BOOST_FOREACH(SpectraMassMap::iterator spectrumHypothesisPair, candidateHypotheses)
{
Spectrum* spectrum = spectrumHypothesisPair->second.first;
PrecursorMassHypothesis& p = spectrumHypothesisPair->second.second;
boost::shared_ptr<SearchResult> resultPtr(new SearchResult(candidate));
SearchResult& result = *resultPtr;
if( !estimateComparisonsOnly )
{
START_PROFILER(2);
if( sequenceIons.empty() )
{
CalculateSequenceIons( candidate,
fragmentChargeState+1,
&sequenceIons,
spectrum->fragmentTypes,
g_rtConfig->UseSmartPlusThreeModel,
0,
0 );
}
STOP_PROFILER(2);
START_PROFILER(3);
spectrum->ScoreSequenceVsSpectrum( result, sequence, sequenceIons );
STOP_PROFILER(3);
if( result.mvh >= g_rtConfig->MinResultScore )
{
START_PROFILER(5);
result.proteins.insert(protein);
result._isDecoy = isDecoy;
STOP_PROFILER(5);
}
}
++ numComparisonsDone;
if( estimateComparisonsOnly )
continue;
START_PROFILER(4);
{
boost::mutex::scoped_lock guard(spectrum->mutex);
if( isDecoy )
++ spectrum->numDecoyComparisons;
else
++ spectrum->numTargetComparisons;
if( result.mvh >= g_rtConfig->MinResultScore )
{
if( g_rtConfig->KeepUnadjustedPrecursorMz )
{
PrecursorMassHypothesis unadjustedHypothesis(p);
unadjustedHypothesis.mass = Ion::neutralMass(spectrum->mzOfPrecursor, p.charge);
result.precursorMassHypothesis = unadjustedHypothesis;
}
else
result.precursorMassHypothesis = p;
//result.massError = p.massType == MassType_Monoisotopic ? monoCalculatedMass - p.mass
// : avgCalculatedMass - p.mass;
// Accumulate score distributions for the spectrum
//++ spectrum->mvhScoreDistribution[ (int) (result.mvh+0.5) ];
//++ spectrum->mzFidelityDistribution[ (int) (result.mzFidelity+0.5)];
spectrum->resultsByCharge[z].add( resultPtr );
}
}
STOP_PROFILER(4);
}
}
return numComparisonsDone;
}
int ExecuteSearchThread()
{
try
{
size_t proteinTask;
while( true )
{
if (!proteinTasks.pop(proteinTask))
break;
++ searchStatistics.numProteinsDigested;
proteinData p = proteins[proteinTask];
if (!g_rtConfig->ProteinListFilters.empty() &&
g_rtConfig->ProteinListFilters.find(p.getName()) == string::npos)
{
continue;
}
Peptide protein(p.getSequence());
bool isDecoy = p.isDecoy();
// BXZ are allowed to be in the prefix/suffix but not in the peptide sequence
string validSequenceResidues("ACDEFGHIKLMNPQRSTUVWY");
string validResidues = validSequenceResidues + "BXZ";
scoped_ptr<Digestion> digestionPtr;
if (g_rtConfig->cleavageAgent != CVID_Unknown)
digestionPtr.reset(new Digestion(protein, g_rtConfig->cleavageAgent, g_rtConfig->digestionConfig));
else
digestionPtr.reset(new Digestion(protein, g_rtConfig->cleavageAgentRegex, g_rtConfig->digestionConfig));
const Digestion& digestion = *digestionPtr;
for( Digestion::const_iterator itr = digestion.begin(); itr != digestion.end(); )
{
++searchStatistics.numPeptidesGenerated;
if (itr->sequence().find_first_not_of(validSequenceResidues) != string::npos ||
itr->NTerminusPrefix().find_first_not_of(validResidues) != string::npos ||
itr->CTerminusSuffix().find_first_not_of(validResidues) != string::npos)
{
++itr;
continue;
}
// a selenopeptide's molecular weight can be lower than its monoisotopic mass!
double minMass = min(itr->monoisotopicMass(), itr->molecularWeight());
double maxMass = max(itr->monoisotopicMass(), itr->molecularWeight());
if( minMass > g_rtConfig->curMaxPeptideMass ||
maxMass < g_rtConfig->curMinPeptideMass )
{
++itr;
continue;
}
PTMVariantList variantIterator( (*itr), g_rtConfig->MaxDynamicMods, g_rtConfig->dynamicMods, g_rtConfig->staticMods, g_rtConfig->MaxPeptideVariants);
if(variantIterator.isSkipped)
{
++ searchStatistics.numPeptidesSkipped;
++ itr;
continue;
}
searchStatistics.numVariantsGenerated += variantIterator.numVariants;
// query each variant
do
{
boost::int64_t queryComparisonCount = QuerySequence( variantIterator.ptmVariant, p.getName(), isDecoy, g_rtConfig->EstimateSearchTimeOnly );
if( queryComparisonCount > 0 )
searchStatistics.numComparisonsDone += queryComparisonCount;
}
while (variantIterator.next());
++itr;
}
}
} catch( std::exception& e )
{
cerr << " terminated with an error: " << e.what() << endl;
} catch(...)
{
cerr << " terminated with an unknown error." << endl;
}
return 0;
}
void ExecuteSearch()
{
size_t numProcessors = (size_t) g_numWorkers;
boost::uint32_t numProteins = (boost::uint32_t) proteins.size();
for (size_t i=0; i < numProteins; ++i)
proteinTasks.push(i);
bpt::ptime start = bpt::microsec_clock::local_time();
boost::thread_group workerThreadGroup;
vector<boost::thread*> workerThreads;
for (size_t i = 0; i < numProcessors; ++i)
workerThreads.push_back(workerThreadGroup.create_thread(&ExecuteSearchThread));
if (g_numChildren > 0)
{
// MPI jobs do a simple join_all
workerThreadGroup.join_all();
// xcorrs are calculated just before sending back results
}
else
{
bpt::ptime lastUpdate = start;
for (size_t i=0; i < numProcessors; ++i)
{
// returns true if the thread finished before the timeout;
// (each thread index is joined until it finishes)
if (!workerThreads[i]->timed_join(bpt::seconds(round(g_rtConfig->StatusUpdateFrequency))))
--i;
bpt::ptime current = bpt::microsec_clock::local_time();
// only make one update per StatusUpdateFrequency seconds
if ((current - lastUpdate).total_microseconds() / 1e6 < g_rtConfig->StatusUpdateFrequency)
continue;
lastUpdate = current;
bpt::time_duration elapsed = current - start;
float proteinsPerSec = static_cast<float>(searchStatistics.numProteinsDigested) / elapsed.total_microseconds() * 1e6;
bpt::time_duration estimatedTimeRemaining(0, 0, round((numProteins - searchStatistics.numProteinsDigested) / proteinsPerSec));
cout << "Searched " << searchStatistics.numProteinsDigested << " of " << numProteins << " proteins; ";
//cout << searchStatistics.numPeptidesGenerated << " peptides; "
// << searchStatistics.numVariantsGenerated << " variants; ";
//if (searchStatistics.numPeptidesSkipped > 0)
// cout << searchStatistics.numPeptidesSkipped << " skipped; ";
//cout << searchStatistics.numComparisonsDone << " comparisons; ";
cout << round(proteinsPerSec) << " per second, "
<< format_date_time("%H:%M:%S", bpt::time_duration(0, 0, elapsed.total_seconds())) << " elapsed, "
<< format_date_time("%H:%M:%S", estimatedTimeRemaining) << " remaining." << endl;
//float candidatesPerSec = threadInfo->stats.numComparisonsDone / totalSearchTime;
//float estimatedTimeRemaining = float( numCandidates - threadInfo->stats.numComparisonsDone ) / candidatesPerSec / numThreads;
//cout << threadInfo->workerHostString << " has made " << threadInfo->stats.numComparisonsDone << " of about " << numCandidates << " comparisons; " <<
// candidatesPerSec << " per second, " << estimatedTimeRemaining << " seconds remaining." << endl;
}
// compute xcorr for top ranked results
if( g_rtConfig->ComputeXCorr )
ComputeXCorrs();
}
}
// Shared pointer to SpectraList.
typedef boost::shared_ptr<SpectraList> SpectraListPtr;
/**
This function takes a spectra list and splits them into small batches as dictated by
ResultsPerBatch variable. This function also checks to make sure that the last batch
is not smaller than 1000 spectra.
*/
vector<SpectraListPtr> estimateSpectralBatches()
{
int estimatedResultsSize = 0;
// Shuffle the spectra so that there is a
// proper load balancing between batches.
spectra.random_shuffle();
vector<SpectraListPtr> batches;
SpectraListPtr current(new SpectraList());
// For each spectrum
for( SpectraList::const_iterator sItr = spectra.begin(); sItr != spectra.end(); ++sItr )
{
// Check the result size, if it exceeds the limit, then push back the
// current list into the vector and get a fresh list
estimatedResultsSize += g_rtConfig->MaxResultRank;
if(estimatedResultsSize>g_rtConfig->ResultsPerBatch)
{
batches.push_back(current);
current.reset(new SpectraList());
estimatedResultsSize = g_rtConfig->MaxResultRank * 2;
}
current->push_back((*sItr));
}
// Make sure you push back the last batch
if(current->size()>0)
batches.push_back(current);
// Check to see if the last batch is not a tiny batch
if(batches.back()->size()<1000 && batches.size()>1)
{
SpectraListPtr last = batches.back(); batches.pop_back();
SpectraListPtr penultimate = batches.back(); batches.pop_back();
penultimate->insert(last->begin(),last->end(),penultimate->end());
batches.push_back(penultimate);
last->clear( false );
}
//for(vector<SpectraListPtr>::const_iterator bItr = batches.begin(); bItr != batches.end(); ++bItr)
// cout << (*bItr)->size() << endl;
return batches;
}
/**
This function is the entry point into the MyriMatch search engine. This
function process the command line arguments, sets up the search, triggers
the threads that perform the search, and writes out the result file.
*/
int ProcessHandler( int argc, char* argv[] )
{
// Get the command line arguments and process them
vector< string > args;
for( int i=0; i < argc; ++i )
args.push_back( argv[i] );
if( InitProcess( args ) )
return 1;
// Get the database name
g_dbFilename = g_rtConfig->ProteinDatabase;
int numSpectra = 0;
INIT_PROFILERS(14)
#ifdef USE_MPI
// Collect the number of cpus available for the job.
int worldRank;
int totalNumCPUs = 0;
MPI_Allreduce(&g_numWorkers, &totalNumCPUs, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
// Adjust for the cpus on the head node
MPI_Comm_rank(MPI_COMM_WORLD, &worldRank);
if(worldRank == 0)
totalNumCPUs -= g_numWorkers;
#endif
// If this is a parent process then read the input spectral data and
// protein database files
if( g_pid == 0 )
{
for( size_t i=1; i < args.size(); ++i )
{
//cout << g_hostString << " is reading spectra from files matching mask \"" << args[i] << "\"" << endl;
FindFilesByMask( args[i], g_inputFilenames );
}
if( g_inputFilenames.empty() )
{
cerr << "No data sources found with the given filemasks." << endl;
return 1;
}
if( !TestFileType( g_dbFilename, "fasta" ) )
return 1;
// Read the protein database
cout << "Reading \"" << g_dbFilename << "\"" << endl;
Timer readTime(true);
try
{
proteins = proteinStore( g_rtConfig->decoyPrefix );
proteins.readFASTA( g_dbFilename, " ", g_rtConfig->automaticDecoys );
} catch( std::exception& e )
{
cout << g_hostString << " had an error: " << e.what() << endl;
return 1;
}
cout << "Read " << proteins.size() << " proteins; " << readTime.End() << " seconds elapsed." << endl;
// randomize order of the proteins to optimize work distribution
// in the MPI and multi-threading mode.
proteins.random_shuffle();
// If we are running in clster mode and this is a master process then
// compute the protein batch size using numer of child processes. Each
// child process is sent all spectra to be searched against a batch of
// protein sequences.
#ifdef USE_MPI
if( g_numChildren > 0 )
{
g_rtConfig->ProteinBatchSize = (int) ceil( (float) proteins.size() / (float) totalNumCPUs / (float) g_rtConfig->NumBatches );
//g_rtConfig->ProteinBatchSize = (int) ceil( (float) proteins.size() / (float) g_numChildren / (float) g_rtConfig->NumBatches );
cout << "Dynamic protein batch size is " << g_rtConfig->ProteinBatchSize << endl;
}
#endif
fileList_t finishedFiles;
fileList_t::iterator fItr;
// For each input spectra file
for( fItr = g_inputFilenames.begin(); fItr != g_inputFilenames.end(); ++fItr )
{
Timer fileTime(true);
spectra.clear();
avgSpectraByChargeState.clear();
monoSpectraByChargeState.clear();
searchStatistics = SearchStatistics();
cout << "Reading spectra from file \"" << *fItr << "\"" << endl;
finishedFiles.insert( *fItr );
Timer readTime(true);
// Read the spectra
try
{
spectra.readPeaks( *fItr,
0, -1,
2, // minMsLevel
g_rtConfig->SpectrumListFilters,
g_rtConfig->NumChargeStates);
} catch( std::exception& e )
{
cerr << g_hostString << " had an error: " << e.what() << endl;
return 1;
}
// Compute the peak counts
int totalPeakCount = 0;
numSpectra = (int) spectra.size();
for( SpectraList::iterator sItr = spectra.begin(); sItr != spectra.end(); ++sItr )
totalPeakCount += (*sItr)->peakPreCount;
cout << "Read " << numSpectra << " spectra with " << totalPeakCount << " peaks; " << readTime.End() << " seconds elapsed." << endl;
int skip = 0;
if( numSpectra == 0 )
{
cout << "Skipping a file with no spectra." << endl;
skip = 1;
}
// If the file has no spectra, then tell the child processes to skip
#ifdef USE_MPI
if( g_numChildren > 0 && !g_rtConfig->EstimateSearchTimeOnly )
{
g_rtConfig->SpectraBatchSize = (int) ceil( (float) numSpectra / (float) g_numChildren / (float) g_rtConfig->NumBatches );
cout << "Dynamic spectra batch size is " << g_rtConfig->SpectraBatchSize << endl;
}
for( int p=0; p < g_numChildren; ++p )
MPI_Ssend( &skip, 1, MPI_INT, p+1, 0x00, MPI_COMM_WORLD );
#endif
Timer searchTime;
string startTime;
string startDate;
vector< size_t > opcs; // original peak count statistics
vector< size_t > fpcs; // filtered peak count statistics
// If the file has spectra
if( !skip )
{
// If this is a master process and we are in MPI mode.
if( g_numProcesses > 1 && !g_rtConfig->EstimateSearchTimeOnly )
{
#ifdef USE_MPI
// Send some spectra away to the child nodes for processing
cout << "Sending spectra to worker nodes to prepare them for search." << endl;
Timer prepareTime(true);
TransmitUnpreparedSpectraToChildProcesses();
spectra.clear();
ReceivePreparedSpectraFromChildProcesses();
numSpectra = (int) spectra.size();
skip = 0;
if( numSpectra == 0 )
{
cout << "Skipping a file with no suitable spectra." << endl;
skip = 1;
}
// If all processed spectra gets dropped out then
// there is no need to proceed.
for( int p=0; p < g_numChildren; ++p )
MPI_Ssend( &skip, 1, MPI_INT, p+1, 0x00, MPI_COMM_WORLD );
if( !skip )
{
// Get peak count stats
opcs = spectra.getOriginalPeakCountStatistics();
fpcs = spectra.getFilteredPeakCountStatistics();
cout << "Mean original (filtered) peak count: " << opcs[5] << " (" << fpcs[5] << ")" << endl;
cout << "Min/max original (filtered) peak count: " << opcs[0] << " (" << fpcs[0] << ") / " << opcs[1] << " (" << fpcs[1] << ")" << endl;
cout << "Original (filtered) peak count at 1st/2nd/3rd quartiles: " <<
opcs[2] << " (" << fpcs[2] << "), " <<
opcs[3] << " (" << fpcs[3] << "), " <<
opcs[4] << " (" << fpcs[4] << ")" << endl;
float filter = 1.0f - ( (float) fpcs[5] / (float) opcs[5] );
cout << "Filtered out " << filter * 100.0f << "% of peaks." << endl;
cout << "Prepared " << numSpectra << " spectra; " << prepareTime.End() << " seconds elapsed." << endl;
// Init the globals
InitWorkerGlobals();
// List to store finished spectra
SpectraList finishedSpectra;
// Split the spectra into batches if needed
vector<SpectraListPtr> batches = estimateSpectralBatches();
if(batches.size()>1)
cout << "Splitting spectra into " << batches.size() << " batches for search." << endl;
startTime = GetTimeString(); startDate = GetDateString(); searchTime.Begin();
// For each spectral batch
size_t batchIndex = 0;
for(vector<SpectraListPtr>::iterator bItr = batches.begin(); bItr != batches.end(); ++bItr)
{
// Variables to report batch progess to the user
++batchIndex;
stringstream batchString;
batchString << "";
if(batches.size()>1)
batchString << " (" << batchIndex << " of " << batches.size() << " batches)";
// Clear the master list and populate it with a small batch
spectra.clear( false );
spectra.insert((*bItr)->begin(), (*bItr)->end(), spectra.end());
// Check to see if we are processing the last batch.
int lastBatch = 0;
if((*bItr) == batches.back())
lastBatch = 1;
// Transmit spectra to all children. Also tell them if this is
// the last batch of the spectra they would be getting from the parent.
cout << "Sending some prepared spectra to all worker nodes from a pool of " << spectra.size() << " spectra" << batchString.str() << "." << endl;
try
{
Timer sendTime(true);
numSpectra = TransmitSpectraToChildProcesses(lastBatch);
cout << "Finished sending " << numSpectra << " prepared spectra to all worker nodes; " <<
sendTime.End() << " seconds elapsed." << endl;
} catch( std::exception& e )
{
cout << g_hostString << " had an error transmitting prepared spectra: " << e.what() << endl;
MPI_Abort( MPI_COMM_WORLD, 1 );
}
// Transmit the proteins and start the search.
cout << "Commencing database search on " << numSpectra << " spectra" << batchString.str() << "." << endl;
try
{
Timer batchTimer(true); batchTimer.Begin();
TransmitProteinsToChildProcesses();
cout << "Finished database search; " << batchTimer.End() << " seconds elapsed" << batchString.str() << "." << endl;
} catch( std::exception& e )
{
cout << g_hostString << " had an error transmitting protein batches: " << e.what() << endl;
MPI_Abort( MPI_COMM_WORLD, 1 );
}
// Get the results
cout << "Receiving search results for " << numSpectra << " spectra" << batchString.str() << "." << endl;
try
{
Timer receiveTime(true);
ReceiveResultsFromChildProcesses(((*bItr) == batches.front()));
cout << "Finished receiving search results; " << receiveTime.End() << " seconds elapsed." << endl;
} catch( std::exception& e )
{
cout << g_hostString << " had an error receiving results: " << e.what() << endl;
MPI_Abort( MPI_COMM_WORLD, 1 );
}
cout << "Overall stats: " << (string) searchStatistics << endl;
// Store the searched spectra in a list and clear the
// master list for next batch
finishedSpectra.insert( spectra.begin(), spectra.end(), finishedSpectra.end() );
spectra.clear( false );
(*bItr)->clear( false );
}
searchTime.End();
// Move the searched spectra from temporary list to the master list
spectra.clear( false );
spectra.insert(finishedSpectra.begin(), finishedSpectra.end(), spectra.end() );
finishedSpectra.clear(false);
// Spectra are randomly shuffled for load distribution during batching process
// Sort them back by ID.
spectra.sort( spectraSortByID() );
DestroyWorkerGlobals();
}
#endif
} else
{
// If we are not in the MPI mode then prepare the spectra
// ourselves
cout << "Preparing " << numSpectra << " spectra." << endl;
Timer prepareTime(true);
PrepareSpectra();
cout << "Finished preparing spectra; " << prepareTime.End() << " seconds elapsed." << endl;
numSpectra = (int) spectra.size();
skip = 0;
if( numSpectra == 0 )
{
cout << "Skipping a file with no suitable spectra." << endl;
skip = 1;
}
// If the file has spectra to search
if( !skip )
{
opcs = spectra.getOriginalPeakCountStatistics();
fpcs = spectra.getFilteredPeakCountStatistics();
cout << "Mean original (filtered) peak count: " << opcs[5] << " (" << fpcs[5] << ")" << endl;
cout << "Min/max original (filtered) peak count: " << opcs[0] << " (" << fpcs[0] << ") / " << opcs[1] << " (" << fpcs[1] << ")" << endl;
cout << "Original (filtered) peak count at 1st/2nd/3rd quartiles: " <<
opcs[2] << " (" << fpcs[2] << "), " <<
opcs[3] << " (" << fpcs[3] << "), " <<
opcs[4] << " (" << fpcs[4] << ")" << endl;
float filter = 1.0f - ( (float) fpcs[5] / (float) opcs[5] );
cout << "Filtered out " << filter * 100.0f << "% of peaks." << endl;
InitWorkerGlobals();
// Start the search
if( !g_rtConfig->EstimateSearchTimeOnly )
{
cout << "Commencing database search on " << numSpectra << " spectra." << endl;
startTime = GetTimeString(); startDate = GetDateString(); searchTime.Begin();
ExecuteSearch();
cout << "Finished database search; " << searchTime.End() << " seconds elapsed." << endl;
cout << "Overall stats: " << (string) searchStatistics << endl;
} else
{
cout << "Estimating the count of sequence comparisons to be done." << endl;
ExecuteSearch();
double estimatedComparisonsPerProtein = searchStatistics.numComparisonsDone / (double) searchStatistics.numProteinsDigested;
boost::int64_t estimatedTotalComparisons = (boost::int64_t) (estimatedComparisonsPerProtein * proteins.size());
cout << "Will make an estimated total of " << estimatedTotalComparisons << " sequence comparisons." << endl;
//cout << g_hostString << " will make an estimated " << estimatedComparisonsPerProtein << " sequence comparisons per protein." << endl;
skip = 1;
}
}
DestroyWorkerGlobals();
}
// Write the output
if( !skip )
{
WriteOutputToFile( *fItr, startTime, startDate, searchTime.End(), opcs, fpcs, searchStatistics );
cout << "Finished file \"" << *fItr << "\"; " << fileTime.End() << " seconds elapsed." << endl;
//PRINT_PROFILERS(cout,"old");
}
searchStatistics.reset();
}
// Tell the child nodes that we are all done if there are
// no other spectral data files to process
#ifdef USE_MPI
int done = ( ( g_inputFilenames.size() - finishedFiles.size() ) == 0 ? 1 : 0 );
for( int p=0; p < g_numChildren; ++p )
MPI_Ssend( &done, 1, MPI_INT, p+1, 0x00, MPI_COMM_WORLD );
#endif
}
}
#ifdef USE_MPI
else
{
if( g_rtConfig->EstimateSearchTimeOnly )
return 0; // nothing to do
int allDone = 0;
while( !allDone )
{
int skip;
MPI_Recv( &skip, 1, MPI_INT, 0, 0x00, MPI_COMM_WORLD, &st );
if( !skip )
{
SpectraList preparedSpectra;
while( ReceiveUnpreparedSpectraBatchFromRootProcess() )
{
PrepareSpectra();
preparedSpectra.insert( spectra.begin(), spectra.end(), preparedSpectra.end() );
spectra.clear( false );
}
//for( int i=0; i < (int) preparedSpectra.size(); ++i )
// cout << preparedSpectra[i]->id.nativeID << " " << preparedSpectra[i]->peakData.size() << endl;
TransmitPreparedSpectraToRootProcess( preparedSpectra );
preparedSpectra.clear();
MPI_Recv( &skip, 1, MPI_INT, 0, 0x00, MPI_COMM_WORLD, &st );
if( !skip )
{
int done = 0;
do
{
try
{
done = ReceiveSpectraFromRootProcess();
} catch( std::exception& e )
{
cout << g_hostString << " had an error receiving prepared spectra: " << e.what() << endl;
MPI_Abort( MPI_COMM_WORLD, 1 );
}
InitWorkerGlobals();
int numBatches = 0;
try
{
while( ReceiveProteinBatchFromRootProcess() )
{
++ numBatches;
ExecuteSearch();
}
} catch( std::exception& e )
{
cout << g_hostString << " had an error receiving protein batch: " << e.what() << endl;
MPI_Abort( MPI_COMM_WORLD, 1 );
}
cout << g_hostString << " stats: " << numBatches << " batches; " << (string) searchStatistics << endl;
try
{
// compute xcorr for top ranked results
if( g_rtConfig->ComputeXCorr )
ComputeXCorrs();
TransmitResultsToRootProcess();
} catch( std::exception& e )
{
cout << g_hostString << " had an error transmitting results: " << e.what() << endl;
MPI_Abort( MPI_COMM_WORLD, 1 );
}
DestroyWorkerGlobals();
spectra.clear();
avgSpectraByChargeState.clear();
monoSpectraByChargeState.clear();
} while( !done );
}
}
MPI_Recv( &allDone, 1, MPI_INT, 0, 0x00, MPI_COMM_WORLD, &st );
} // end of while
} // end of if
#endif
return 0;
}
}
}
int main( int argc, char* argv[] )
{
char buf[256];
GetHostname( buf, sizeof(buf) );
// Initialize the message passing interface for the parallel processing system
#ifdef MPI_DEBUG
cout << buf << " is initializing MPI... " << endl;
#endif
#ifdef USE_MPI
int threadLevel;
MPI_Init_thread( &argc, &argv, MPI_THREAD_MULTIPLE, &threadLevel );
if( threadLevel < MPI_THREAD_SINGLE )
{
cerr << "MPI library is not thread compliant: " << threadLevel << " should be " << MPI_THREAD_MULTIPLE << endl;
return 1;
}
MPI_Buffer_attach( malloc( MPI_BUFFER_SIZE ), MPI_BUFFER_SIZE );
//CommitCommonDatatypes();
#endif
#ifdef MPI_DEBUG
cout << buf << " has initialized MPI... " << endl;
#endif
// Get information on the MPI environment
#ifdef MPI_DEBUG
cout << buf << " is gathering MPI information... " << endl;
#endif
#ifdef USE_MPI
MPI_Comm_size( MPI_COMM_WORLD, &g_numProcesses );
MPI_Comm_rank( MPI_COMM_WORLD, &g_pid );
#else
g_numProcesses = 1;
g_pid = 0;
#endif
g_numChildren = g_numProcesses - 1;
ostringstream str;
str << "Process #" << g_pid << " (" << buf << ")";
g_hostString = str.str();
#ifdef MPI_DEBUG
cout << g_hostString << " has gathered its MPI information." << endl;
#endif
// Process the data
#ifndef MPI_DEBUG
cout << g_hostString << " is starting." << endl;
#endif
int result = 0;
try
{
result = myrimatch::ProcessHandler( argc, argv );
} catch (pwiz::util::usage_exception& e)
{
cerr << e.what() << endl;
result = 0;
} catch (std::exception& e)
{
cerr << e.what() << endl;
result = 1;
} catch( ... )
{
cerr << "Caught unspecified fatal exception." << endl;
result = 1;
}
#ifdef USE_MPI
if( g_pid == 0 && g_numChildren > 0 && result > 0 )
MPI_Abort( MPI_COMM_WORLD, 1 );
#endif
#ifdef MPI_DEBUG
cout << g_hostString << " has finished." << endl;
#endif
// Destroy the message passing interface
#ifdef MPI_DEBUG
cout << g_hostString << " is finalizing MPI... " << endl;
#endif
#ifdef USE_MPI
int size;
MPI_Buffer_detach( &g_mpiBuffer, &size );
free( g_mpiBuffer );
MPI_Finalize();
#endif
#ifdef MPI_DEBUG
cout << g_hostString << " is terminating." << endl;
#endif
// HACK: avoid crashing at exit on Windows (probably a conflict between Boost and the .NET vendor DLLs)
#ifdef WIN32
TerminateProcess(GetCurrentProcess(), result);
#else
return result;
#endif
}
| 45.861215 | 207 | 0.484419 | [
"vector"
] |
03cdc95e2ba6813da83b3d346f17fcc4dde0c0db | 470 | cpp | C++ | Algorithms/Graph-Theory/journey-to-the-moon.cpp | RitvijSrivastava/Hackerrank-1 | 781e60ff18b581bda88be63bd095118778bc2d56 | [
"MIT"
] | 29 | 2018-10-08T18:14:09.000Z | 2021-10-10T08:37:06.000Z | Algorithms/Graph-Theory/journey-to-the-moon.cpp | RitvijSrivastava/Hackerrank-1 | 781e60ff18b581bda88be63bd095118778bc2d56 | [
"MIT"
] | 36 | 2018-10-03T18:39:26.000Z | 2021-10-08T21:21:40.000Z | Algorithms/Graph-Theory/journey-to-the-moon.cpp | RitvijSrivastava/Hackerrank-1 | 781e60ff18b581bda88be63bd095118778bc2d56 | [
"MIT"
] | 86 | 2018-10-03T19:19:40.000Z | 2021-12-23T11:59:22.000Z | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
vector<vector<int>> g;
int n, m, x, y, c=0, i, j;
cin>>n>>m;
g.resize(n, vector<int>(n, 0));
for(i=0; i<n; i++) g[i][i] = 1;
while(m--) {
cin>>x>>y;
g[x][y] = 1;
}
for(i=0; i<n; i++) {
for(j=i+1; j<n; j++) {
if(g[i][j]==0) c++;
}
}
cout<<c;
return 0;
}
| 18.076923 | 35 | 0.440426 | [
"vector"
] |
03d0311bf3ab02e110dd3db87b86307e70a36655 | 15,987 | cpp | C++ | demo/wiced-43xxx/rama_mqtt/rama_mqtt.cpp | OlafFilies/holonomic | 99858d87032082a48c452ef37ac33d26a9cc752c | [
"MIT"
] | 1 | 2021-07-27T16:19:56.000Z | 2021-07-27T16:19:56.000Z | demo/wiced-43xxx/rama_mqtt/rama_mqtt.cpp | OlafFilies/holonomic | 99858d87032082a48c452ef37ac33d26a9cc752c | [
"MIT"
] | null | null | null | demo/wiced-43xxx/rama_mqtt/rama_mqtt.cpp | OlafFilies/holonomic | 99858d87032082a48c452ef37ac33d26a9cc752c | [
"MIT"
] | null | null | null | /**
* ============================================================================
* \name : Rama Killough a holonomic driving platform
* \author : Dr. Olaf Filies, Marcus Gordon Filies
* \version : 0.0.1
* \copyright : Infineon Technologies AG
* \brief Controlling 3 wheel holonomic platform
* \details : Controlling 3 wheel holonomic platform with
* one Infineon TLE94112EL microcontroller shield
* one Infineon XMC1100 or XMC4x00 microcontroller
* used : Infineon Arduino port for using XMC arm based microcontroller
* Infineon tle94112 base library
* 1x Infineon XMC1100 microcontroller
* 1x Infineon TLE94112 DC motor controller shield
*
* ============================================================================
* Rama holonomic driving platform is on and waiting for input
* ============================================================================
* We need three values
* the angular alpha for the direction between 0deg-360deg
* the speed in alpha direction between 0%-100%
* the speed the rotation -100%-100% speed
* with negative values as anti clockwise
* and positive numbers for clockwise
* either alpha and alpha speed are set or rotation speed are set but
* yet not both
* ============================================================================
*
* SPDX-License-Identifier: MIT
*/
#include <rama_mqtt.hpp>
#if (HOLONOMIC_FRAMEWORK == HOLONOMIC_FRMWK_WICED)
/******************************************************
* Pointer to motor controller
******************************************************/
Holonomic3 RamaDrive = Holonomic3();
Holonomic3::velInput_t driveParam = { 0, 0, 0 };
/**
* @brief main loop function
*
*/
void application_start()
{
static wiced_mqtt_object_t mqtt_object;
wiced_mqtt_security_t security;
wiced_result_t ret = WICED_SUCCESS;
enAppState_t enAppState = APP_STATE_AFTER_RESET;
uint8_t channel = 0;
uint8_t value = 0;
/* Main Loop */
while (ret == WICED_SUCCESS) {
switch (enAppState) {
case APP_STATE_AFTER_RESET:
wiced_init();
/* Memory allocated for mqtt object*/
mqtt_object = (wiced_mqtt_object_t) malloc(WICED_MQTT_OBJECT_MEMORY_SIZE_REQUIREMENT);
if (mqtt_object == NULL) {
WPRINT_APP_ERROR(("Dont have memory to allocate for mqtt object...\n"));
return;
}
ret = mqtt_start_wifi();
security = mqtt_start_mqtt(mqtt_object);
WPRINT_APP_INFO(("[TLE94112] : setup begin -> %u\n", 0));
RamaDrive.begin();
RamaDrive.coastRama();
WPRINT_APP_INFO(("[Holonomic drive] : startup begin -> %u\n", 0));
enAppState = APP_STATE_MQTT_CONNECT;
break;
case APP_STATE_CONNECT_TO_WIFI:
break;
case APP_STATE_MQTT_FIND_BROKER:
break;
case APP_STATE_MQTT_CONNECT:
WPRINT_APP_INFO(("[MQTT] Opening connection..."));
RUN_COMMAND_PRINT_STATUS_AND_BREAK_ON_ERROR(
mqtt_conn_open( mqtt_object,&broker_address, WICED_STA_INTERFACE, callbacks, &security ), NULL, "Did you configure you broker IP address?\n" );
enAppState = APP_STATE_MQTT_SUBSCRIBE;
break;
case APP_STATE_MQTT_CLOSECONNECT:
WPRINT_APP_INFO(("[MQTT] Closing connection..."));
RUN_COMMAND_PRINT_STATUS_AND_BREAK_ON_ERROR(
mqtt_conn_close(mqtt_object), NULL, NULL);
enAppState = APP_STATE_END;
break;
case APP_STATE_MQTT_SUBSCRIBE:
WPRINT_APP_INFO(("[MQTT] Subscribing..."));
RUN_COMMAND_PRINT_STATUS_AND_BREAK_ON_ERROR(
mqtt_app_subscribe( mqtt_object, WICED_TOPIC , WICED_MQTT_QOS_DELIVER_AT_MOST_ONCE ),NULL, NULL);
enAppState = APP_STATE_MQTT_WAIT_FOR_ACTION;
break;
case APP_STATE_MQTT_UNSUBSCRIBE:
WPRINT_APP_INFO(("[MQTT] Unsubscribing..."));
RUN_COMMAND_PRINT_STATUS_AND_BREAK_ON_ERROR(
mqtt_app_unsubscribe( mqtt_object, WICED_TOPIC ), NULL,NULL);
enAppState = APP_STATE_MQTT_WAIT_FOR_ACTION;
break;
case APP_STATE_MQTT_PUBLISH: {
WPRINT_APP_INFO(("[MQTT] Publishing..."));
//RUN_COMMAND_PRINT_STATUS_AND_BREAK_ON_ERROR(
// mqtt_app_publish( mqtt_object, WICED_MQTT_QOS_DELIVER_AT_LEAST_ONCE, topic, (uint8_t*)valbuf ,sizeof(valbuf) ), NULL, NULL );
channel++;
enAppState = APP_STATE_MQTT_WAIT_FOR_ACTION;
break;
}
case APP_STATE_MQTT_PUBLISH_RESPOND:
WPRINT_APP_INFO(("[MQTT] Publish respond..."));
enAppState = APP_STATE_MQTT_WAIT_FOR_ACTION;
break;
case APP_STATE_MQTT_WAIT_FOR_ACTION:
WPRINT_APP_INFO( ("[MQTT] Waiting some time for ping exchange...\n\n"));
wiced_rtos_delay_milliseconds(WICED_MQTT_DELAY_IN_MILLISECONDS * 1);
value += WICED_MQTT_DELAY_IN_MILLISECONDS;
channel = channel % 4;
value = value % 255;
enAppState = APP_STATE_MQTT_PUBLISH;
break;
case APP_STATE_END:
break;
default:
while (1)
;
break;
} //switch (enAppState)
}
/* Stop Mqtt */
mqtt_stop_mqtt(mqtt_object, security);
}
/******************************************************
* Static Function Definitions
******************************************************/
/**
* @brief Wifi startup function
*
* @return wiced_result_t
*/
static wiced_result_t mqtt_start_wifi()
{
WPRINT_APP_INFO(( "Starting Network...\n" ));
wiced_network_up(WICED_STA_INTERFACE, WICED_USE_EXTERNAL_DHCP_SERVER, NULL);
WPRINT_APP_INFO(( "Resolving IP address of MQTT broker...\n" ));
wiced_result_t ret = wiced_hostname_lookup( MQTT_BROKER_ADDRESS, &broker_address, 10000, WICED_STA_INTERFACE);
WPRINT_APP_INFO(
("Resolved Broker IP: %u.%u.%u.%u\n\n",
(uint8_t)(GET_IPV4_ADDRESS(broker_address) >> 24),
(uint8_t)(GET_IPV4_ADDRESS(broker_address) >> 16),
(uint8_t)(GET_IPV4_ADDRESS(broker_address) >> 8),
(uint8_t)(GET_IPV4_ADDRESS(broker_address) >> 0))
);
if (ret == WICED_ERROR || broker_address.ip.v4 == 0) {
WPRINT_APP_INFO(("Error in resolving DNS\n"));
}
return ret;
}
/**
* @brief MQTT startup function
*
* @param mqtt_object
* @return wiced_mqtt_security_t
*/
static wiced_mqtt_security_t mqtt_start_mqtt(wiced_mqtt_object_t mqtt_object)
{
uint32_t size_out;
wiced_mqtt_security_t security;
/* Read root CA certificate (self certified) from resources*/
//resource_get_readonly_buffer(&resources_apps_DIR_secure_mqtt_DIR_ca_crt, 0, MQTT_MAX_RESOURCE_SIZE, &size_out,(const void **) &security.ca_cert);
//security.ca_cert_len = size_out;
//resource_get_readonly_buffer(&resources_apps_DIR_secure_mqtt_DIR_client_crt, 0, MQTT_MAX_RESOURCE_SIZE, &size_out,(const void **) &security.cert);
//security.cert_len = size_out;
resource_get_readonly_buffer(&resources_apps_DIR_secure_mqtt_DIR_client_key, 0, MQTT_MAX_RESOURCE_SIZE, &size_out,(const void **) &security.key);
security.key_len = size_out;
wiced_mqtt_init(mqtt_object);
wiced_rtos_init_semaphore(&semaphore);
return security;
}
/**
* @brief MQTT stop function
*
* @param mqtt_object
* @param security
*/
static void mqtt_stop_mqtt(wiced_mqtt_object_t mqtt_object, wiced_mqtt_security_t security)
{
/* Stop Mqtt */
wiced_rtos_deinit_semaphore(&semaphore);
WPRINT_APP_INFO(("[MQTT] Deinit connection..."));
wiced_result_t ret = wiced_mqtt_deinit(mqtt_object);
mqtt_print_status(ret, NULL, NULL);
free(mqtt_object);
mqtt_object = NULL;
/* Free security resources, only needed at initialization */
//resource_free_readonly_buffer(&resources_apps_DIR_secure_mqtt_DIR_ca_crt, security.ca_cert);
//resource_free_readonly_buffer(&resources_apps_DIR_secure_mqtt_DIR_client_crt, security.cert);
resource_free_readonly_buffer(&resources_apps_DIR_secure_mqtt_DIR_client_key, security.key);
}
/**
* @brief A simple result log function
*
* @param result
* @param ok_message
* @param error_message
*/
static void mqtt_print_status(wiced_result_t result, const char * ok_message, const char * error_message)
{
if (result == WICED_SUCCESS) {
if (ok_message != NULL) {
WPRINT_APP_INFO(( "OK (%s)\n\n", (ok_message)));
} else {
WPRINT_APP_INFO(( "OK.\n\n" ));
}
} else {
if (error_message != NULL) {
WPRINT_APP_INFO(( "ERROR (%s)\n\n", (error_message)));
} else {
WPRINT_APP_INFO(( "ERROR.\n\n" ));
}
}
}
/**
* @brief Call back function to handle connection events.
*
* @param mqtt_object
* @param event
* @return wiced_result_t
*/
static wiced_result_t mqtt_connection_event_cb(wiced_mqtt_object_t mqtt_object, wiced_mqtt_event_info_t *event)
{
switch (event->type) {
case WICED_MQTT_EVENT_TYPE_CONNECT_REQ_STATUS:
case WICED_MQTT_EVENT_TYPE_DISCONNECTED:
case WICED_MQTT_EVENT_TYPE_PUBLISHED:
case WICED_MQTT_EVENT_TYPE_SUBSCRIBED:
case WICED_MQTT_EVENT_TYPE_UNSUBSCRIBED: {
expected_event = event->type;
wiced_rtos_set_semaphore(&semaphore);
}
break;
case WICED_MQTT_EVENT_TYPE_PUBLISH_MSG_RECEIVED: {
wiced_mqtt_topic_msg_t msg = event->data.pub_recvd;
int value = 0;
for (int i = 0; i < (int) msg.data_len; i++){
value = 10 * value + (msg.data[i] - '0');
}
switch (msg.topic[6]){
case alpha:{
driveParam.alpha = value;
break;
}
case speed:{
driveParam.speed = value;
break;
}
case rotation:{
driveParam.rotation = value;
break;
}
}
if (driveParam.speed != 0) {
RamaDrive.driveXY(driveParam);
} else {
if (driveParam.rotation == 0) {
RamaDrive.coastRama();
} else {
RamaDrive.driveRot(driveParam);
}
}
WPRINT_APP_INFO( ( "[MQTT] TOPIC : %.*s\n", (int) msg.topic_len, msg.topic));
WPRINT_APP_INFO( ( "[MQTT] DATA : %.*s,%u\n", (int) msg.data_len, msg.data,(int) msg.data_len ));
WPRINT_APP_INFO( ("OK -> <%u,%u,%u>\n", driveParam.alpha,driveParam.speed,driveParam.rotation));
}
break;
default:
break;
}
return WICED_SUCCESS;
}
/**
* Call back function to handle channel events.
*
* For each event:
* - The call back will set the expected_event global to the received event.
* - The call back will set the event semaphore to run any blocking thread functions waiting on this event
* - Some events will also log other global variables required for extra processing.
*
* A thread function will probably be waiting for the received event. Once the event is received and the
* semaphore is set, the thread function will check for the received event and make sure it matches what
* it is expecting.
*
* Note: This mechanism is not thread safe as we are using a non protected global variable for read/write.
* However as this snip is a single controlled thread, there is no risc of racing conditions. It is
* however not recommended for multi-threaded applications.
*/
/**
* @brief A blocking call to an expected event.
*
* @param event
* @param timeout
* @return wiced_result_t
*/
static wiced_result_t mqtt_wait_for(wiced_mqtt_event_type_t event, uint32_t timeout)
{
if (wiced_rtos_get_semaphore(&semaphore, timeout) != WICED_SUCCESS) {
return WICED_ERROR;
} else {
if (event != expected_event) {
return WICED_ERROR;
}
}
return WICED_SUCCESS;
}
/**
* @brief Open a connection and wait for WICED_MQTT_TIMEOUT period to receive a connection open OK event
*
* @param mqtt_obj
* @param address
* @param interface
* @param callback
* @param security
* @return wiced_result_t
*/
static wiced_result_t mqtt_conn_open(wiced_mqtt_object_t mqtt_obj, wiced_ip_address_t *address, wiced_interface_t interface, wiced_mqtt_callback_t callback, wiced_mqtt_security_t *security)
{
wiced_mqtt_pkt_connect_t conninfo;
wiced_result_t ret = WICED_SUCCESS;
memset(&conninfo, 0, sizeof(conninfo));
conninfo.port_number = 0; /* set to 0 indicates library to use default settings */
conninfo.mqtt_version = WICED_MQTT_PROTOCOL_VER3;
conninfo.clean_session = 1;
conninfo.client_id = (uint8_t*) MQTT_BROKER_CLIENT_ID;
conninfo.keep_alive = 5;
conninfo.password = (uint8_t*) MQTT_BROKER_USER_NAME;
conninfo.username = (uint8_t*) MQTT_BROKER_USER_PASSWORD;
conninfo.peer_cn = NULL;
ret = wiced_mqtt_connect(mqtt_obj, address, interface, callback, security,
&conninfo);
if (ret != WICED_SUCCESS) {
return WICED_ERROR;
}
if (mqtt_wait_for(WICED_MQTT_EVENT_TYPE_CONNECT_REQ_STATUS,WICED_MQTT_TIMEOUT) != WICED_SUCCESS) {
return WICED_ERROR;
}
return WICED_SUCCESS;
}
/**
* @brief Close a connection and wait for 5 seconds to receive a connection close OK event
*
* @param mqtt_obj
* @return wiced_result_t
*/
static wiced_result_t mqtt_conn_close(wiced_mqtt_object_t mqtt_obj)
{
if (wiced_mqtt_disconnect(mqtt_obj) != WICED_SUCCESS) {
return WICED_ERROR;
}
if (mqtt_wait_for(WICED_MQTT_EVENT_TYPE_DISCONNECTED, WICED_MQTT_TIMEOUT) != WICED_SUCCESS) {
return WICED_ERROR;
}
return WICED_SUCCESS;
}
/**
* @brief Subscribe to WICED_TOPIC and wait for 5 seconds to receive an ACM.
*
* @param mqtt_obj
* @param topic
* @param qos
* @return wiced_result_t
*/
static wiced_result_t mqtt_app_subscribe(wiced_mqtt_object_t mqtt_obj,char *topic, uint8_t qos)
{
wiced_mqtt_msgid_t pktid;
pktid = wiced_mqtt_subscribe(mqtt_obj, topic, qos);
if (pktid == 0) {
return WICED_ERROR;
}
if (mqtt_wait_for(WICED_MQTT_EVENT_TYPE_SUBSCRIBED, WICED_MQTT_TIMEOUT) != WICED_SUCCESS) {
return WICED_ERROR;
}
return WICED_SUCCESS;
}
/**
* @brief Unsubscribe from WICED_TOPIC and wait for 10 seconds to receive an ACM.
*
* @param mqtt_obj
* @param topic
* @return wiced_result_t
*/
static wiced_result_t mqtt_app_unsubscribe(wiced_mqtt_object_t mqtt_obj,char *topic)
{
wiced_mqtt_msgid_t pktid;
pktid = wiced_mqtt_unsubscribe(mqtt_obj, topic);
if (pktid == 0) {
return WICED_ERROR;
}
if (mqtt_wait_for(WICED_MQTT_EVENT_TYPE_UNSUBSCRIBED, WICED_MQTT_TIMEOUT * 2) != WICED_SUCCESS) {
return WICED_ERROR;
}
return WICED_SUCCESS;
}
/**
* @brief Publish (send) WICED_MESSAGE_STR to WICED_TOPIC and wait for 5 seconds to receive a PUBCOMP (as it is QoS=2).
*
* @param mqtt_obj
* @param qos
* @param topic
* @param data
* @param data_len
* @return wiced_result_t
*/
static wiced_result_t mqtt_app_publish(wiced_mqtt_object_t mqtt_obj,uint8_t qos, char *topic, uint8_t *data, uint32_t data_len)
{
wiced_mqtt_msgid_t pktid;
pktid = wiced_mqtt_publish(mqtt_obj, topic, data, data_len, qos);
if (pktid == 0) {
return WICED_ERROR;
}
if (mqtt_wait_for(WICED_MQTT_EVENT_TYPE_PUBLISHED, WICED_MQTT_TIMEOUT) != WICED_SUCCESS) {
return WICED_ERROR;
}
return WICED_SUCCESS;
}
#endif
| 33.099379 | 189 | 0.632889 | [
"object"
] |
03d201fdf723cd7898c8e1a712c5b979b3305354 | 1,524 | cpp | C++ | codeforces/1511/b/b.cpp | Shahraaz/CP_S5 | 2cfb5467841d660c1e47cb8338ea692f10ca6e60 | [
"MIT"
] | 3 | 2020-02-08T10:34:16.000Z | 2020-02-09T10:23:19.000Z | codeforces/1511/b/b.cpp | Shahraaz/CP_S5 | 2cfb5467841d660c1e47cb8338ea692f10ca6e60 | [
"MIT"
] | null | null | null | codeforces/1511/b/b.cpp | Shahraaz/CP_S5 | 2cfb5467841d660c1e47cb8338ea692f10ca6e60 | [
"MIT"
] | 2 | 2020-10-02T19:05:32.000Z | 2021-09-08T07:01:49.000Z | #include <bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#include "/debug.h"
#else
#define db(...)
#endif
#define all(v) v.begin(), v.end()
#define pb push_back
using ll = long long;
const int NAX = 2e5 + 5, MOD = 1000000007;
const int NAX_PRIME = 2e5 + 5;
bool is_composite[NAX_PRIME];
vector<int> primes;
vector<vector<int>> primes_list(11);
bool is_prime(int x)
{
for (long long i = 2; i * i <= x; i++)
{
if (x % i == 0)
return false;
}
return true;
}
void seive(int n = NAX_PRIME)
{
primes_list[0] = {1, 1};
for (int i = 1; i < 10; i++)
{
int c = i - 1, x = 1;
while (c--)
x = x * 10;
while (primes_list[i].size() < 2)
{
if (is_prime(x))
primes_list[i].pb(x);
++x;
}
db(i, primes_list[i]);
}
}
void solveCase()
{
int a, b, c;
cin >> a >> b >> c;
int base = 1, l = c - 1;
db(a, b, c);
while (l--)
base = base * 10;
db(base);
db(a - c, b - c);
if (a == b)
{
cout << primes_list[a - c + 1][0] * base << ' ';
cout << primes_list[b - c + 1][1] * base << '\n';
}
else
{
cout << primes_list[a - c + 1][0] * base << ' ';
cout << primes_list[b - c + 1][1] * base << '\n';
}
}
int32_t main()
{
seive();
#ifndef LOCAL
ios_base::sync_with_stdio(0);
cin.tie(0);
#endif
int t = 1;
cin >> t;
for (int i = 1; i <= t; ++i)
solveCase();
return 0;
} | 18.361446 | 57 | 0.459974 | [
"vector"
] |
03d7775a277eca22e5bc8ab88aa2b74eb7cfb15c | 3,741 | cpp | C++ | src/SpectralClustering/Kmeans.cpp | gbull122/SpectralClustering | 76c1ab9e06a88a40807b5dad6f15bac9efb2da52 | [
"MIT"
] | 2 | 2020-01-03T03:25:11.000Z | 2020-04-20T15:50:32.000Z | src/SpectralClustering/Kmeans.cpp | gbull122/SpectralClustering | 76c1ab9e06a88a40807b5dad6f15bac9efb2da52 | [
"MIT"
] | null | null | null | src/SpectralClustering/Kmeans.cpp | gbull122/SpectralClustering | 76c1ab9e06a88a40807b5dad6f15bac9efb2da52 | [
"MIT"
] | null | null | null | /*
* Kmeans.cpp
*
* Created on: 04-Mar-2009
* Author: sbutler
*/
#define EIGEN2_SUPPORT
#include "Kmeans.h"
#include <map>
#include <iostream>
Kmeans::Kmeans() {
}
Kmeans::~Kmeans() {
}
/**
* kmeans clustering
* based on kmeans matlab script by Ian T Nabney (1996-2001)
*
* @param data affinity matrix
* @oaram ncentres number of clusters
* @return ordered set of data row indices (the path id) for each cluster
* (order is based on distance to cluster centre)
*/
std::vector<std::vector<int> > Kmeans::cluster(Eigen::MatrixXd& data, int ncentres)
{
int ndims = data.cols();
int ndata = data.rows();
//int ncentres = 2;
Eigen::MatrixXd centres = Eigen::MatrixXd::Zero(ncentres, ndims);
Eigen::MatrixXd old_centres;
std::vector<int> rands;
for (int i = 0; i < ncentres; i++)
{
//randomly initialise centers
bool flag;
do
{
flag = false;
int randIndex = Eigen::ei_random(0, ndata - 1);
//make sure same row not chosen twice
for (unsigned int j = 0; j < rands.size(); ++j)
{
if (randIndex == rands[j])
{
flag = true;
break;
}
}
if (!flag)
{
centres.row(i) = data.row(randIndex);
rands.push_back(randIndex);
}
}
while (flag);
}
Eigen::MatrixXd id = Eigen::MatrixXd::Identity(ncentres, ncentres);
//maps vectors to centres.
Eigen::MatrixXd post(ndata, ncentres);
Eigen::VectorXd minvals(ndata);
double old_e = 0;
int niters = 100;
for (int n = 0; n < niters; n++)
{
//Save old centres to check for termination
old_centres = centres;
// Calculate posteriors based on existing centres
Eigen::MatrixXd d2(ndata, ncentres);
for (int j = 0; j < ncentres; j++)
{
for (int k = 0; k < ndata; k++)
{
d2(k, j) = (data.row(k) - centres.row(j)).squaredNorm();
}
}
int r, c;
// Assign each point to nearest centre
for (int k = 0; k < ndata; k++)
{
//get centre index (c)
minvals[k] = d2.row(k).minCoeff(&r, &c);
//set centre
post.row(k) = id.row(c);
}
Eigen::VectorXd num_points = post.colwise().sum();
// Adjust the centres based on new posteriors
for (int j = 0; j < ncentres; j++)
{
if (num_points[j] > 0)
{
Eigen::MatrixXd s = Eigen::MatrixXd::Zero(1, ndims);
for (int k = 0; k < ndata; k++)
{
if (post(k, j) == 1)
{
s += data.row(k);
}
}
centres.row(j) = s / num_points[j];
}
}
// Error value is total squared distance from cluster centres
double e = minvals.sum();
double ediff = fabs(old_e - e);
double cdiff = (centres - old_centres).cwise().abs().maxCoeff();
std::cout << "Cycle " << n << " Error " << e << " Movement " << cdiff << ", " << ediff << std::endl;
if (n > 1)
{
//Test for termination
if (cdiff < 0.0000000001 && ediff < 0.0000000001)
{
break;
}
}
old_e = e;
}
//------- finished kmeans ---------
//find the item closest to the centre for each cluster
std::vector<std::vector<int> > clustered_items;
for (int j = 0; j < ncentres; j++)
{
//put data into map (multimap because minvals[k] could be the same for multiple units)
std::multimap<double, int> cluster;
for (int k = 0; k < ndata; k++)
{
if (post(k, j) == 1)
{
cluster.insert(std::make_pair(minvals[k], k));
}
}
//extract data from map
std::vector<int> units;
//the map will be sorted based on the key (the minval) so just loop through it
//to get set of data indices sorted on the minval
for (std::multimap<double, int>::iterator it = cluster.begin(); it != cluster.end(); it++)
{
units.push_back(it->second);
}
clustered_items.push_back(units);
}
//return the ordered set of item indices for each cluster centre
return clustered_items;
}
| 23.092593 | 102 | 0.603849 | [
"vector"
] |
03d79832aaeeadaae7c5387b0589446f4b21beb3 | 21,430 | cpp | C++ | Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp | azhirnov/DiligentCore | 28ad08478938d8c910195eff169513cd4eef9e3e | [
"Apache-2.0"
] | null | null | null | Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp | azhirnov/DiligentCore | 28ad08478938d8c910195eff169513cd4eef9e3e | [
"Apache-2.0"
] | null | null | null | Graphics/GraphicsEngineD3D11/src/PipelineStateD3D11Impl.cpp | azhirnov/DiligentCore | 28ad08478938d8c910195eff169513cd4eef9e3e | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019-2021 Diligent Graphics LLC
* Copyright 2015-2019 Egor Yusov
*
* 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.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include "pch.h"
#include <array>
#include "PipelineStateD3D11Impl.hpp"
#include "RenderDeviceD3D11Impl.hpp"
#include "ShaderResourceBindingD3D11Impl.hpp"
#include "EngineMemory.h"
namespace Diligent
{
template <typename PSOCreateInfoType>
void PipelineStateD3D11Impl::InitInternalObjects(const PSOCreateInfoType& CreateInfo)
{
m_ResourceLayoutIndex.fill(-1);
std::vector<ShaderD3D11Impl*> Shaders;
ExtractShaders<ShaderD3D11Impl>(CreateInfo, Shaders);
const auto NumShaderStages = GetNumShaderStages();
VERIFY_EXPR(NumShaderStages > 0 && NumShaderStages == Shaders.size());
FixedLinearAllocator MemPool{GetRawAllocator()};
MemPool.AddSpace<ShaderResourceCacheD3D11>(NumShaderStages);
MemPool.AddSpace<ShaderResourceLayoutD3D11>(NumShaderStages);
ReserveSpaceForPipelineDesc(CreateInfo, MemPool);
MemPool.Reserve();
m_pStaticResourceCaches = MemPool.ConstructArray<ShaderResourceCacheD3D11>(NumShaderStages);
// The memory is now owned by PipelineStateD3D11Impl and will be freed by Destruct().
auto* Ptr = MemPool.ReleaseOwnership();
VERIFY_EXPR(Ptr == m_pStaticResourceCaches);
(void)Ptr;
m_pStaticResourceLayouts = MemPool.Allocate<ShaderResourceLayoutD3D11>(NumShaderStages);
for (Uint32 i = 0; i < NumShaderStages; ++i)
new (m_pStaticResourceLayouts + i) ShaderResourceLayoutD3D11{*this, m_pStaticResourceCaches[i]}; // noexcept
InitializePipelineDesc(CreateInfo, MemPool);
// It is important to construct all objects before initializing them because if an exception is thrown,
// destructors will be called for all objects
InitResourceLayouts(CreateInfo, Shaders);
}
PipelineStateD3D11Impl::PipelineStateD3D11Impl(IReferenceCounters* pRefCounters,
RenderDeviceD3D11Impl* pRenderDeviceD3D11,
const GraphicsPipelineStateCreateInfo& CreateInfo) :
// clang-format off
TPipelineStateBase
{
pRefCounters,
pRenderDeviceD3D11,
CreateInfo
},
m_SRBMemAllocator{GetRawAllocator()},
m_ImmutableSamplers (STD_ALLOCATOR_RAW_MEM(ImmutableSamplerInfo, GetRawAllocator(), "Allocator for vector<ImmutableSamplerInfo>"))
// clang-format on
{
try
{
InitInternalObjects(CreateInfo);
auto& GraphicsPipeline = GetGraphicsPipelineDesc();
#define INIT_SHADER(ShortName, ExpectedType) \
do \
{ \
auto* pShader = ValidatedCast<ShaderD3D11Impl>(CreateInfo.p##ShortName); \
m_p##ShortName = pShader; \
if (m_p##ShortName && m_p##ShortName->GetDesc().ShaderType != ExpectedType) \
{ \
LOG_ERROR_AND_THROW(GetShaderTypeLiteralName(ExpectedType), " shader is expeceted while ", GetShaderTypeLiteralName(m_p##ShortName->GetDesc().ShaderType), " provided"); \
} \
if (pShader != nullptr) \
HashCombine(m_ShaderResourceLayoutHash, pShader->GetD3D11Resources()->GetHash()); \
} while (false)
INIT_SHADER(VS, SHADER_TYPE_VERTEX);
INIT_SHADER(PS, SHADER_TYPE_PIXEL);
INIT_SHADER(GS, SHADER_TYPE_GEOMETRY);
INIT_SHADER(DS, SHADER_TYPE_DOMAIN);
INIT_SHADER(HS, SHADER_TYPE_HULL);
#undef INIT_SHADER
if (m_pVS == nullptr)
{
LOG_ERROR_AND_THROW("Vertex shader is null");
}
auto* pDeviceD3D11 = pRenderDeviceD3D11->GetD3D11Device();
D3D11_BLEND_DESC D3D11BSDesc = {};
BlendStateDesc_To_D3D11_BLEND_DESC(GraphicsPipeline.BlendDesc, D3D11BSDesc);
CHECK_D3D_RESULT_THROW(pDeviceD3D11->CreateBlendState(&D3D11BSDesc, &m_pd3d11BlendState),
"Failed to create D3D11 blend state object");
D3D11_RASTERIZER_DESC D3D11RSDesc = {};
RasterizerStateDesc_To_D3D11_RASTERIZER_DESC(GraphicsPipeline.RasterizerDesc, D3D11RSDesc);
CHECK_D3D_RESULT_THROW(pDeviceD3D11->CreateRasterizerState(&D3D11RSDesc, &m_pd3d11RasterizerState),
"Failed to create D3D11 rasterizer state");
D3D11_DEPTH_STENCIL_DESC D3D11DSSDesc = {};
DepthStencilStateDesc_To_D3D11_DEPTH_STENCIL_DESC(GraphicsPipeline.DepthStencilDesc, D3D11DSSDesc);
CHECK_D3D_RESULT_THROW(pDeviceD3D11->CreateDepthStencilState(&D3D11DSSDesc, &m_pd3d11DepthStencilState),
"Failed to create D3D11 depth stencil state");
// Create input layout
const auto& InputLayout = GraphicsPipeline.InputLayout;
if (InputLayout.NumElements > 0)
{
std::vector<D3D11_INPUT_ELEMENT_DESC, STDAllocatorRawMem<D3D11_INPUT_ELEMENT_DESC>> d311InputElements(STD_ALLOCATOR_RAW_MEM(D3D11_INPUT_ELEMENT_DESC, GetRawAllocator(), "Allocator for vector<D3D11_INPUT_ELEMENT_DESC>"));
LayoutElements_To_D3D11_INPUT_ELEMENT_DESCs(InputLayout, d311InputElements);
ID3DBlob* pVSByteCode = m_pVS.RawPtr<ShaderD3D11Impl>()->GetBytecode();
if (!pVSByteCode)
LOG_ERROR_AND_THROW("Vertex Shader byte code does not exist");
CHECK_D3D_RESULT_THROW(pDeviceD3D11->CreateInputLayout(d311InputElements.data(), static_cast<UINT>(d311InputElements.size()), pVSByteCode->GetBufferPointer(), pVSByteCode->GetBufferSize(), &m_pd3d11InputLayout),
"Failed to create the Direct3D11 input layout");
}
}
catch (...)
{
Destruct();
throw;
}
}
PipelineStateD3D11Impl::PipelineStateD3D11Impl(IReferenceCounters* pRefCounters,
RenderDeviceD3D11Impl* pRenderDeviceD3D11,
const ComputePipelineStateCreateInfo& CreateInfo) :
// clang-format off
TPipelineStateBase
{
pRefCounters,
pRenderDeviceD3D11,
CreateInfo
},
m_SRBMemAllocator{GetRawAllocator()},
m_ImmutableSamplers(STD_ALLOCATOR_RAW_MEM(ImmutableSamplerInfo, GetRawAllocator(), "Allocator for vector<ImmutableSamplerInfo>"))
// clang-format on
{
try
{
InitInternalObjects(CreateInfo);
m_pCS = ValidatedCast<ShaderD3D11Impl>(CreateInfo.pCS);
if (m_pCS == nullptr)
{
LOG_ERROR_AND_THROW("Compute shader is null");
}
if (m_pCS->GetDesc().ShaderType != SHADER_TYPE_COMPUTE)
{
LOG_ERROR_AND_THROW(GetShaderTypeLiteralName(SHADER_TYPE_COMPUTE), " shader is expeceted while ", GetShaderTypeLiteralName(m_pCS->GetDesc().ShaderType), " provided");
}
m_ShaderResourceLayoutHash = m_pCS->GetD3D11Resources()->GetHash();
}
catch (...)
{
Destruct();
throw;
}
}
PipelineStateD3D11Impl::~PipelineStateD3D11Impl()
{
Destruct();
}
void PipelineStateD3D11Impl::Destruct()
{
TPipelineStateBase::Destruct();
if (m_pStaticResourceLayouts != nullptr)
{
for (Uint32 l = 0; l < GetNumShaderStages(); ++l)
{
m_pStaticResourceLayouts[l].~ShaderResourceLayoutD3D11();
}
}
if (m_pStaticResourceCaches != nullptr)
{
for (Uint32 s = 0; s < GetNumShaderStages(); ++s)
{
m_pStaticResourceCaches[s].Destroy(GetRawAllocator());
m_pStaticResourceCaches[s].~ShaderResourceCacheD3D11();
}
}
// All subobjects are allocated in contiguous chunks of memory.
if (auto* pRawMem = m_pStaticResourceCaches)
GetRawAllocator().Free(pRawMem);
}
IMPLEMENT_QUERY_INTERFACE(PipelineStateD3D11Impl, IID_PipelineStateD3D11, TPipelineStateBase)
void PipelineStateD3D11Impl::InitResourceLayouts(const PipelineStateCreateInfo& CreateInfo,
const std::vector<ShaderD3D11Impl*>& Shaders)
{
const auto& ResourceLayout = m_Desc.ResourceLayout;
#ifdef DILIGENT_DEVELOPMENT
{
const ShaderResources* pResources[MAX_SHADERS_IN_PIPELINE] = {};
for (Uint32 s = 0; s < Shaders.size(); ++s)
{
pResources[s] = Shaders[s]->GetD3D11Resources().get();
}
ShaderResources::DvpVerifyResourceLayout(ResourceLayout, pResources, GetNumShaderStages(),
(CreateInfo.Flags & PSO_CREATE_FLAG_IGNORE_MISSING_VARIABLES) == 0,
(CreateInfo.Flags & PSO_CREATE_FLAG_IGNORE_MISSING_IMMUTABLE_SAMPLERS) == 0);
}
#endif
decltype(m_ImmutableSamplers) ImmutableSamplers{STD_ALLOCATOR_RAW_MEM(ImmutableSamplerInfo, GetRawAllocator(), "Allocator for vector<ImmutableSamplerInfo>")};
std::array<size_t, MAX_SHADERS_IN_PIPELINE> ShaderResLayoutDataSizes = {};
std::array<size_t, MAX_SHADERS_IN_PIPELINE> ShaderResCacheDataSizes = {};
for (Uint32 s = 0; s < Shaders.size(); ++s)
{
const auto* pShader = Shaders[s];
const auto& ShaderDesc = pShader->GetDesc();
const auto& Resources = *pShader->GetD3D11Resources();
VERIFY_EXPR(ShaderDesc.ShaderType == Resources.GetShaderType());
// The cache will be initialized by the resource layout
// Shader resource layout will only contain dynamic and mutable variables
const SHADER_RESOURCE_VARIABLE_TYPE StaticVarTypes[] = {SHADER_RESOURCE_VARIABLE_TYPE_STATIC};
m_pStaticResourceLayouts[s].Initialize(
pShader->GetD3D11Resources(),
m_Desc.ResourceLayout,
StaticVarTypes,
_countof(StaticVarTypes),
GetRawAllocator(),
GetRawAllocator() //
);
// Initialize immutable samplers
for (Uint32 sam = 0; sam < Resources.GetNumSamplers(); ++sam)
{
const auto& SamplerAttribs = Resources.GetSampler(sam);
constexpr bool LogImtblSamplerArrayError = true;
auto SrcImtblSamplerInd = Resources.FindImmutableSampler(SamplerAttribs, ResourceLayout, LogImtblSamplerArrayError);
if (SrcImtblSamplerInd >= 0)
{
const auto& SrcImtblSamplerInfo = ResourceLayout.ImmutableSamplers[SrcImtblSamplerInd];
RefCntAutoPtr<ISampler> pImbtlSampler;
GetDevice()->CreateSampler(SrcImtblSamplerInfo.Desc, &pImbtlSampler);
ImmutableSamplers.emplace_back(SamplerAttribs, std::move(pImbtlSampler));
}
}
m_ImmutableSamplerOffsets[s + 1] = static_cast<Uint16>(ImmutableSamplers.size());
if (m_Desc.SRBAllocationGranularity > 1)
{
const SHADER_RESOURCE_VARIABLE_TYPE SRBVarTypes[] = //
{
SHADER_RESOURCE_VARIABLE_TYPE_MUTABLE,
SHADER_RESOURCE_VARIABLE_TYPE_DYNAMIC //
};
ShaderResLayoutDataSizes[s] = ShaderResourceLayoutD3D11::GetRequiredMemorySize(Resources, ResourceLayout, SRBVarTypes, _countof(SRBVarTypes));
ShaderResCacheDataSizes[s] = ShaderResourceCacheD3D11::GetRequriedMemorySize(Resources);
}
auto ShaderInd = GetShaderTypePipelineIndex(ShaderDesc.ShaderType, m_Desc.PipelineType);
m_ResourceLayoutIndex[ShaderInd] = static_cast<Int8>(s);
}
if (m_Desc.SRBAllocationGranularity > 1)
{
m_SRBMemAllocator.Initialize(m_Desc.SRBAllocationGranularity, GetNumShaderStages(), ShaderResLayoutDataSizes.data(), GetNumShaderStages(), ShaderResCacheDataSizes.data());
}
m_ImmutableSamplers.reserve(ImmutableSamplers.size());
for (auto& ImtblSam : ImmutableSamplers)
m_ImmutableSamplers.emplace_back(std::move(ImtblSam));
for (Uint32 s = 0; s < GetNumShaderStages(); ++s)
{
// Initialize immutable samplers in the static resource cache to avoid warning messages
SetImmutableSamplers(m_pStaticResourceCaches[s], s);
}
}
ID3D11BlendState* PipelineStateD3D11Impl::GetD3D11BlendState()
{
return m_pd3d11BlendState;
}
ID3D11RasterizerState* PipelineStateD3D11Impl::GetD3D11RasterizerState()
{
return m_pd3d11RasterizerState;
}
ID3D11DepthStencilState* PipelineStateD3D11Impl::GetD3D11DepthStencilState()
{
return m_pd3d11DepthStencilState;
}
ID3D11InputLayout* PipelineStateD3D11Impl::GetD3D11InputLayout()
{
return m_pd3d11InputLayout;
}
void PipelineStateD3D11Impl::CreateShaderResourceBinding(IShaderResourceBinding** ppShaderResourceBinding, bool InitStaticResources)
{
auto& SRBAllocator = GetDevice()->GetSRBAllocator();
auto pShaderResBinding = NEW_RC_OBJ(SRBAllocator, "ShaderResourceBindingD3D11Impl instance", ShaderResourceBindingD3D11Impl)(this, false);
if (InitStaticResources)
pShaderResBinding->InitializeStaticResources(nullptr);
pShaderResBinding->QueryInterface(IID_ShaderResourceBinding, reinterpret_cast<IObject**>(static_cast<IShaderResourceBinding**>(ppShaderResourceBinding)));
}
bool PipelineStateD3D11Impl::IsCompatibleWith(const IPipelineState* pPSO) const
{
VERIFY_EXPR(pPSO != nullptr);
if (pPSO == this)
return true;
const PipelineStateD3D11Impl* pPSOD3D11 = ValidatedCast<const PipelineStateD3D11Impl>(pPSO);
if (m_ShaderResourceLayoutHash != pPSOD3D11->m_ShaderResourceLayoutHash)
return false;
if (GetNumShaderStages() != pPSOD3D11->GetNumShaderStages())
return false;
for (Uint32 s = 0; s < GetNumShaderStages(); ++s)
{
auto* pShader0 = GetShader(s);
auto* pShader1 = pPSOD3D11->GetShader(s);
if (pShader0->GetDesc().ShaderType != pShader1->GetDesc().ShaderType)
return false;
const auto& Res0 = *pShader0->GetD3D11Resources();
const auto& Res1 = *pShader1->GetD3D11Resources();
if (!Res0.IsCompatibleWith(Res1))
return false;
}
return true;
}
ID3D11VertexShader* PipelineStateD3D11Impl::GetD3D11VertexShader()
{
if (!m_pVS) return nullptr;
auto* pVSD3D11 = m_pVS.RawPtr<ShaderD3D11Impl>();
return static_cast<ID3D11VertexShader*>(pVSD3D11->GetD3D11Shader());
}
ID3D11PixelShader* PipelineStateD3D11Impl::GetD3D11PixelShader()
{
if (!m_pPS) return nullptr;
auto* pPSD3D11 = m_pPS.RawPtr<ShaderD3D11Impl>();
return static_cast<ID3D11PixelShader*>(pPSD3D11->GetD3D11Shader());
}
ID3D11GeometryShader* PipelineStateD3D11Impl::GetD3D11GeometryShader()
{
if (!m_pGS) return nullptr;
auto* pGSD3D11 = m_pGS.RawPtr<ShaderD3D11Impl>();
return static_cast<ID3D11GeometryShader*>(pGSD3D11->GetD3D11Shader());
}
ID3D11DomainShader* PipelineStateD3D11Impl::GetD3D11DomainShader()
{
if (!m_pDS) return nullptr;
auto* pDSD3D11 = m_pDS.RawPtr<ShaderD3D11Impl>();
return static_cast<ID3D11DomainShader*>(pDSD3D11->GetD3D11Shader());
}
ID3D11HullShader* PipelineStateD3D11Impl::GetD3D11HullShader()
{
if (!m_pHS) return nullptr;
auto* pHSD3D11 = m_pHS.RawPtr<ShaderD3D11Impl>();
return static_cast<ID3D11HullShader*>(pHSD3D11->GetD3D11Shader());
}
ID3D11ComputeShader* PipelineStateD3D11Impl::GetD3D11ComputeShader()
{
if (!m_pCS) return nullptr;
auto* pCSD3D11 = m_pCS.RawPtr<ShaderD3D11Impl>();
return static_cast<ID3D11ComputeShader*>(pCSD3D11->GetD3D11Shader());
}
void PipelineStateD3D11Impl::BindStaticResources(Uint32 ShaderFlags, IResourceMapping* pResourceMapping, Uint32 Flags)
{
for (Uint32 s = 0; s < GetNumShaderStages(); ++s)
{
auto& StaticResLayout = m_pStaticResourceLayouts[s];
if ((ShaderFlags & StaticResLayout.GetShaderType()) != 0)
StaticResLayout.BindResources(pResourceMapping, Flags, m_pStaticResourceCaches[s]);
}
}
Uint32 PipelineStateD3D11Impl::GetStaticVariableCount(SHADER_TYPE ShaderType) const
{
const auto LayoutInd = GetStaticVariableCountHelper(ShaderType, m_ResourceLayoutIndex);
if (LayoutInd < 0)
return 0;
VERIFY_EXPR(static_cast<Uint32>(LayoutInd) <= GetNumShaderStages());
return m_pStaticResourceLayouts[LayoutInd].GetTotalResourceCount();
}
IShaderResourceVariable* PipelineStateD3D11Impl::GetStaticVariableByName(SHADER_TYPE ShaderType, const Char* Name)
{
const auto LayoutInd = GetStaticVariableByNameHelper(ShaderType, Name, m_ResourceLayoutIndex);
if (LayoutInd < 0)
return nullptr;
VERIFY_EXPR(static_cast<Uint32>(LayoutInd) <= GetNumShaderStages());
return m_pStaticResourceLayouts[LayoutInd].GetShaderVariable(Name);
}
IShaderResourceVariable* PipelineStateD3D11Impl::GetStaticVariableByIndex(SHADER_TYPE ShaderType, Uint32 Index)
{
const auto LayoutInd = GetStaticVariableByIndexHelper(ShaderType, Index, m_ResourceLayoutIndex);
if (LayoutInd < 0)
return nullptr;
VERIFY_EXPR(static_cast<Uint32>(LayoutInd) <= GetNumShaderStages());
return m_pStaticResourceLayouts[LayoutInd].GetShaderVariable(Index);
}
void PipelineStateD3D11Impl::SetImmutableSamplers(ShaderResourceCacheD3D11& ResourceCache, Uint32 ShaderInd) const
{
auto NumCachedSamplers = ResourceCache.GetSamplerCount();
for (Uint32 s = m_ImmutableSamplerOffsets[ShaderInd]; s < m_ImmutableSamplerOffsets[ShaderInd + 1]; ++s)
{
auto& SamplerInfo = m_ImmutableSamplers[s];
const auto& SamAttribs = SamplerInfo.Attribs;
auto* pSamplerD3D11Impl = SamplerInfo.pSampler.RawPtr<SamplerD3D11Impl>();
// Limiting EndBindPoint is required when initializing immutable samplers in a Shader's static cache
auto EndBindPoint = std::min(static_cast<Uint32>(SamAttribs.BindPoint) + SamAttribs.BindCount, NumCachedSamplers);
for (Uint32 BindPoint = SamAttribs.BindPoint; BindPoint < EndBindPoint; ++BindPoint)
ResourceCache.SetSampler(BindPoint, pSamplerD3D11Impl);
}
}
const ShaderD3D11Impl* PipelineStateD3D11Impl::GetShaderByType(SHADER_TYPE ShaderType) const
{
switch (ShaderType)
{
// clang-format off
case SHADER_TYPE_VERTEX: return m_pVS;
case SHADER_TYPE_PIXEL: return m_pPS;
case SHADER_TYPE_GEOMETRY: return m_pGS;
case SHADER_TYPE_HULL: return m_pHS;
case SHADER_TYPE_DOMAIN: return m_pDS;
case SHADER_TYPE_COMPUTE: return m_pCS;
default: UNEXPECTED("unsupported shader type"); return nullptr;
// clang-format on
}
}
const ShaderD3D11Impl* PipelineStateD3D11Impl::GetShader(Uint32 Index) const
{
if (Index < GetNumShaderStages())
return GetShaderByType(GetShaderStageType(Index));
UNEXPECTED("Shader index is out of range");
return nullptr;
}
} // namespace Diligent
| 42.435644 | 232 | 0.652217 | [
"object",
"vector"
] |
03dca44ccf5356346812f0411ba979e38d9f61d0 | 7,652 | cpp | C++ | src/Backend/Window/Backend.cpp | texus/TGUI | 87042f5dfafe9421d8a916b23ce7575d16f06d4c | [
"Zlib"
] | 543 | 2015-01-03T22:53:59.000Z | 2022-03-25T08:55:45.000Z | src/Backend/Window/Backend.cpp | texus/TGUI | 87042f5dfafe9421d8a916b23ce7575d16f06d4c | [
"Zlib"
] | 118 | 2015-01-21T12:22:58.000Z | 2022-03-31T17:05:33.000Z | src/Backend/Window/Backend.cpp | texus/TGUI | 87042f5dfafe9421d8a916b23ce7575d16f06d4c | [
"Zlib"
] | 111 | 2015-02-02T13:22:13.000Z | 2022-03-31T08:09:40.000Z | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// TGUI - Texus' Graphical User Interface
// Copyright (C) 2012-2021 Bruno Van de Velde (vdv_b@tgui.eu)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <TGUI/Backend/Window/Backend.hpp>
#include <TGUI/Loading/Theme.hpp>
#include <TGUI/Timer.hpp>
#include <TGUI/Font.hpp>
#include <TGUI/DefaultFont.hpp>
#include <TGUI/Backend/Font/BackendFontFactory.hpp>
#include <TGUI/Backend/Renderer/BackendRenderer.hpp>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace tgui
{
namespace
{
std::shared_ptr<Backend> globalBackend = nullptr;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool isBackendSet()
{
return (globalBackend != nullptr);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void setBackend(std::shared_ptr<Backend> backend)
{
TGUI_ASSERT(!backend || !globalBackend, "setBackend() was called with a backend while there already was a backend");
globalBackend = backend;
// Do some cleanup when we destroy the backend
if (!backend)
{
// Stop all timers (as they could contain resources that have to be destroyed before the main function exits)
Timer::clearTimers();
// Destroy the global font
Font::setGlobalFont(nullptr);
// Destroy the global theme
Theme::setDefault(nullptr);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::shared_ptr<Backend> getBackend()
{
TGUI_ASSERT(globalBackend != nullptr, "getBackend() was called while there is no backend");
return globalBackend;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Backend::setDestroyOnLastGuiDetatch(bool destroyOnDetatch)
{
m_destroyOnLastGuiDetatch = destroyOnDetatch;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Font Backend::createDefaultFont()
{
if (m_fontBackend)
return {defaultFontBytes, sizeof(defaultFontBytes)};
else
return {};
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Backend::openVirtualKeyboard(const FloatRect&)
{
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Backend::closeVirtualKeyboard()
{
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Backend::setClipboard(const String& contents)
{
m_clipboardContents = contents;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
String Backend::getClipboard() const
{
return m_clipboardContents;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::unique_ptr<std::uint8_t[]> Backend::readFileFromAndroidAssets(const String&, std::size_t&) const
{
return nullptr;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::shared_ptr<BackendFont> Backend::createFont()
{
return getFontBackend()->createFont();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::shared_ptr<BackendText> Backend::createText()
{
return getRenderer()->createText();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::shared_ptr<BackendTexture> Backend::createTexture()
{
return getRenderer()->createTexture();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Backend::hasRenderer() const
{
return (m_renderer != nullptr);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::shared_ptr<BackendRenderer> Backend::getRenderer() const
{
TGUI_ASSERT(m_renderer != nullptr, "getRenderer() called on backend while no BackendRenderer was created yet. Has a window been attached to a gui object yet?");
return m_renderer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Backend::setRenderer(std::shared_ptr<BackendRenderer> renderer)
{
m_renderer = renderer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool Backend::hasFontBackend() const
{
return (m_fontBackend != nullptr);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
std::shared_ptr<BackendFontFactory> Backend::getFontBackend() const
{
TGUI_ASSERT(m_fontBackend != nullptr, "getFontBackend() called on backend while no BackendFont was created yet. Has a window been attached to a gui object yet?");
return m_fontBackend;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Backend::setFontBackend(std::shared_ptr<BackendFontFactory> fontBackend)
{
m_fontBackend = fontBackend;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 38.26 | 170 | 0.381469 | [
"object"
] |
03de80207f1aaebd780ecca1ccc0d5b0a6ff69eb | 11,251 | cpp | C++ | ullr/src/ullr/graphics/loader/assimpModelLoader.cpp | jonestristand/UllrEngine | cb7e7e2e07afd9e8926d0b05fcba3c7201ec0355 | [
"Apache-2.0"
] | null | null | null | ullr/src/ullr/graphics/loader/assimpModelLoader.cpp | jonestristand/UllrEngine | cb7e7e2e07afd9e8926d0b05fcba3c7201ec0355 | [
"Apache-2.0"
] | null | null | null | ullr/src/ullr/graphics/loader/assimpModelLoader.cpp | jonestristand/UllrEngine | cb7e7e2e07afd9e8926d0b05fcba3c7201ec0355 | [
"Apache-2.0"
] | null | null | null | #include "ullrpch.h"
#include "assimpModelLoader.h"
#include "assimp/Importer.hpp"
#include "assimp/scene.h"
#include "assimp/postprocess.h"
#include "stb_image.h"
#include <iostream>
#include "ullr/graphics/animation/animatedModel.h"
#include "ullr/graphics/animation/jointTransform.h"
namespace Ullr::Graphics::Loader
{
AssimpModelLoader::AssimpModelLoader()
: ModelLoader(), currDirectory(), loadedTextures(), boneNameIndices(), boneMatrices()
{}
Model* AssimpModelLoader::LoadFromFile(const std::string& path)
{
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_CalcTangentSpace | aiProcess_LimitBoneWeights);
// Ensure scene loaded succesfully
if ((!scene) || (scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE) || (!scene->mRootNode)) {
UL_CORE_ERROR("[ASSIMP] Unable to load model '{0}'.", path);
return new Model(MeshPtrList()); // Return an empty model
}
// Store the directory of the model root for finding textures later
this->currDirectory = path.substr(0, path.find_last_of('/') + 1);
MeshPtrList meshList; // stores the list of meshes
meshList.reserve(scene->mNumMeshes);
this->boneNameIndices.clear();
if (!scene->HasAnimations()) {
this->processMeshNodes(scene->mRootNode, scene, meshList);
return new Model(meshList); // Create and return the new model
}
else { // build and return an AnimatedModel instead
this->processMeshNodes(scene->mRootNode, scene, meshList);
auto skeleton = this->buildBoneHierarchy(scene->mRootNode, scene);
auto animator = this->loadAnimations(scene);
return new Animation::AnimatedModel(meshList, skeleton, this->boneNameIndices.size(), animator); // Create and return the new model
}
}
Model* AssimpModelLoader::LoadFromMemory(const byte* modelBuffer)
{
UL_CORE_ASSERT(false, "Loading model from memory buffer not yet supported");
return nullptr;
}
void AssimpModelLoader::processMeshNodes(aiNode* node, const aiScene* scene, MeshPtrList& meshList)
{
// Process any meshes in this node
for (uint32 i = 0; i < node->mNumMeshes; i++) {
aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
meshList.emplace_back(this->processMesh(mesh, scene));
}
// Process any child nodes of this node
for (uint32 i = 0; i < node->mNumChildren; i++) {
this->processMeshNodes(node->mChildren[i], scene, meshList);
}
}
Animation::Joint* AssimpModelLoader::buildBoneHierarchy(aiNode* node, const aiScene* scene)
{
auto boneEntry = this->boneNameIndices.find(node->mName.C_Str());
Animation::Joint* joint = nullptr;
if (boneEntry != this->boneNameIndices.end()) {
// Is a bone
joint = new Animation::Joint(boneEntry->second, boneEntry->first, this->boneMatrices[boneEntry->second]);
}
// Loop through children
for (uint32 i = 0; i < node->mNumChildren; i++) {
auto child = this->buildBoneHierarchy(node->mChildren[i], scene);
if (child != nullptr) {
if (joint != nullptr) // This is a joint/bone node - add any children
joint->AddChild(child); // Add if any child found further down hierarchy
else // This is not a bone node, return the first child
return child; // TODO: fix this to be more flexible than just returning first child
}
}
return joint;
}
MeshPtr AssimpModelLoader::processMesh(aiMesh* mesh, const aiScene* scene)
{
std::vector<Mesh::Vertex> vertices;
std::vector<uint32> vertexBoneWeightCount;
std::vector<uint32> indices;
TexturePtrList textures;
// Keep track of how many bone weights each vertex has been assigned so far
vertexBoneWeightCount.resize(mesh->mNumVertices, 0);
// Pre-size the vertex buffer to hold all of the vertices
vertices.reserve(mesh->mNumVertices);
// == Process vertices
for (uint32 i = 0; i < mesh->mNumVertices; i++) {
Mesh::Vertex vert;
// Position
glm::vec3 pos(mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z);
vert.Position = pos;
// Normal
glm::vec3 norm(mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z);
vert.Normal = norm;
// TexCoords
if (mesh->mTextureCoords[0]) {// Does it have any texture coordinates?
vert.TexCoords = glm::vec2(mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y);
}
else {
vert.TexCoords = glm::vec2(0.0f, 0.0f);
}
// Tangent
if (mesh->HasTangentsAndBitangents()) { // Does it have a calculated tangent?
vert.Tangent = glm::vec3(mesh->mTangents[i].x, mesh->mTangents[i].y, mesh->mTangents[i].z);
}
else {
vert.Tangent = glm::vec3(0.0f, 0.0f, 0.0f);
}
// Clear the boneids and bone weights vector
vert.BoneIds = glm::ivec4(0, 0, 0, 0);
vert.BoneWeights = glm::vec4(0.0f, 0.0f, 0.0f, 0.0f);
// Push into vertex array
vertices.push_back(vert);
}
// == Process indices
for (uint32 i = 0; i < mesh->mNumFaces; i++) {
aiFace face = mesh->mFaces[i];
for (uint32 j = 0; j < face.mNumIndices; j++)
indices.push_back(face.mIndices[j]);
}
// == Process materials
if (mesh->mMaterialIndex >= 0)
{
aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
TexturePtrList diffuseMaps = this->loadTextures(material, aiTextureType_DIFFUSE, "diffuse", scene);
textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
TexturePtrList specularMaps = this->loadTextures(material, aiTextureType_SPECULAR, "specular", scene);
textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
// TODO: Hack to support different model formats
TexturePtrList normalMaps1 = this->loadTextures(material, aiTextureType_NORMALS, "normal", scene);
textures.insert(textures.end(), normalMaps1.begin(), normalMaps1.end());
TexturePtrList normalMaps2 = this->loadTextures(material, aiTextureType_HEIGHT, "normal", scene);
textures.insert(textures.end(), normalMaps2.begin(), normalMaps2.end());
}
// == Process bones
if (mesh->HasBones()) {
// If the mesh has bones, iterate through them and record the name of each bone in this->boneNames
this->boneNameIndices.reserve(mesh->mNumBones);
this->boneMatrices.resize(mesh->mNumBones);
for (uint32 i = 0; i < mesh->mNumBones; i++) {
auto bone = mesh->mBones[i];
this->boneNameIndices.emplace(bone->mName.C_Str(), i);
this->boneMatrices[i] = this->convertAssimpMat4(bone->mOffsetMatrix);
// Now iterate all weights for this bone
for (uint32 j = 0; j < bone->mNumWeights; j++) {
// Find an empty slot in the vector and record the bone index and weight
auto vertexId = bone->mWeights[j].mVertexId;
// TODO: move max bones to a constant somewhere
if (vertexBoneWeightCount[vertexId] < 4) {
vertices[vertexId].BoneIds[vertexBoneWeightCount[vertexId]] = i;
vertices[vertexId].BoneWeights[vertexBoneWeightCount[vertexId]] = bone->mWeights[j].mWeight;
vertexBoneWeightCount[vertexId]++;
}
}
}
}
// TODO: probably have model with function to load all meshes in to GPU at once
auto newMesh = Mesh::CreateMesh(vertices, indices, textures);
newMesh->UploadMesh();
return newMesh;
}
std::unique_ptr<Animation::Animator> AssimpModelLoader::loadAnimations(const aiScene * scene)
{
// TODO: Rewrite all this to load multiple animations
auto animation = scene->mAnimations[0];
std::vector<Animation::KeyFrameList> keyFrames;
keyFrames.resize(this->boneNameIndices.size());
// Loop through all channels in the animation
for (int j = 0; j < animation->mNumChannels; j++) {
auto jointIndexIterator = this->boneNameIndices.find(animation->mChannels[j]->mNodeName.C_Str());
if (jointIndexIterator != this->boneNameIndices.end())
{
auto jointIndex = jointIndexIterator->second;
for (int i = 0; i < animation->mChannels[j]->mNumPositionKeys; i++) {
auto translation = animation->mChannels[j]->mPositionKeys[i].mValue;
auto rotation = animation->mChannels[j]->mRotationKeys[i].mValue;
auto keyFrameTime = animation->mChannels[j]->mPositionKeys[i].mTime;
Animation::JointTransform transform;
transform.Translation = glm::vec3(translation.x, translation.y, translation.z);
transform.Rotation = glm::quat(rotation.w, rotation.x, rotation.y, rotation.z);
keyFrames[jointIndex].AddKeyframe(keyFrameTime / animation->mTicksPerSecond, transform);
}
}
}
auto animator = std::make_unique<Animation::Animator>(animation->mDuration / animation->mTicksPerSecond, keyFrames);
return std::move(animator);
}
TexturePtrList AssimpModelLoader::loadTextures(aiMaterial* mat, aiTextureType type, std::string typeName, const aiScene* scene)
{
TexturePtrList textures;
for (uint32 i = 0; i < mat->GetTextureCount(type); i++) {
aiString filename;
mat->GetTexture(type, i, &filename);
TexturePtr texture;
// First check if it exists already in our list of textures (339.8MB)
auto cachedTexture = this->loadedTextures.find(filename.C_Str());
if (cachedTexture == this->loadedTextures.end()) {
if (auto tex = scene->GetEmbeddedTexture(filename.C_Str()))
{
auto hint = tex->achFormatHint; // TODO: need to check if compressed or uncompressed and address that apropriately with stbi or direct load
int32 w, h, c;
byte* buffer = stbi_load_from_memory((byte*)tex->pcData, tex->mWidth, &w, &h, &c, 4); // this->filePath.c_str(), & this->width, & this->height, & this->numChannels, 4)
texture = std::shared_ptr<Texture>(Texture::CreateTexture(buffer, w, h, typeName));
}
else {
std::string fullpath = this->currDirectory + std::string(filename.C_Str());
// TODO: stbi loading should be done in the model loader, not the texture class
texture = std::shared_ptr<Texture>(Texture::CreateTexture(fullpath, typeName));
texture->ReadFile();
}
// Send command the renderer to load texture data to the GPU
texture->LoadTexture();
this->loadedTextures.emplace(filename.C_Str(), texture);
}
else { // Texture is in repository
texture = cachedTexture->second;
}
textures.push_back(texture);
}
return textures;
}
glm::mat4 AssimpModelLoader::convertAssimpMat4(const aiMatrix4x4& mat)
{
glm::mat4 result;
result[0].x = mat.a1; result[0].y = mat.b1; result[0].z = mat.c1; result[0].w = mat.d1;
result[1].x = mat.a2; result[1].y = mat.b2; result[1].z = mat.c2; result[1].w = mat.d2;
result[2].x = mat.a3; result[2].y = mat.b3; result[2].z = mat.c3; result[2].w = mat.d3;
result[3].x = mat.a4; result[3].y = mat.b4; result[3].z = mat.c4; result[3].w = mat.d4;
return result;
}
}
| 37.755034 | 177 | 0.656119 | [
"mesh",
"vector",
"model",
"transform"
] |
03e0c008215be77e888d5ee6f71bb79b5eef03bd | 8,718 | cpp | C++ | frontend/parser/Variable.cpp | patrickf2000/tiny-lang | 0339bf046be53e31130c47a9eae4c0a62fe5a1a6 | [
"BSD-3-Clause"
] | null | null | null | frontend/parser/Variable.cpp | patrickf2000/tiny-lang | 0339bf046be53e31130c47a9eae4c0a62fe5a1a6 | [
"BSD-3-Clause"
] | null | null | null | frontend/parser/Variable.cpp | patrickf2000/tiny-lang | 0339bf046be53e31130c47a9eae4c0a62fe5a1a6 | [
"BSD-3-Clause"
] | null | null | null | //
// Copyright 2021-2022 Patrick Flynn
// This file is part of the Tiny Lang compiler.
// Tiny Lang is licensed under the BSD-3 license. See the COPYING file for more information.
//
#include <iostream>
#include <string>
#include <vector>
#include <parser/Parser.hpp>
#include <ast.hpp>
// Builds a variable declaration
// A variable declaration is composed of an Alloca and optionally, an assignment
bool Parser::buildVariableDec(AstBlock *block) {
Token token = scanner->getNext();
std::vector<std::string> toDeclare;
toDeclare.push_back(token.id_val);
if (token.type != Id) {
syntax->addError(scanner->getLine(), "Expected variable name.");
return false;
}
token = scanner->getNext();
while (token.type != Colon) {
if (token.type == Comma) {
token = scanner->getNext();
if (token.type != Id) {
syntax->addError(scanner->getLine(), "Expected variable name.");
return false;
}
toDeclare.push_back(token.id_val);
} else if (token.type != Colon) {
syntax->addError(scanner->getLine(), "Invalid token in variable declaration.");
return false;
}
token = scanner->getNext();
}
token = scanner->getNext();
DataType dataType = DataType::Void;
bool isString = false;
switch (token.type) {
case Bool: dataType = DataType::Bool; break;
case Char: dataType = DataType::Char; break;
case I8: dataType = DataType::I8; break;
case U8: dataType = DataType::U8; break;
case I16: dataType = DataType::I16; break;
case U16: dataType = DataType::U16; break;
case I32: dataType = DataType::I32; break;
case U32: dataType = DataType::U32; break;
case I64: dataType = DataType::I64; break;
case U64: dataType = DataType::U64; break;
case Str: dataType = DataType::String; break;
default: {
syntax->addError(scanner->getLine(), "Invalid data type.");
return false;
}
}
token = scanner->getNext();
// We have an array
if (token.type == LBracket) {
AstVarDec *empty = new AstVarDec("", DataType::Ptr);
AstExpression *arg = buildExpression(DataType::I32, RBracket);
if (!arg) return false;
empty->setExpression(arg);
token = scanner->getNext();
if (token.type != SemiColon) {
syntax->addError(scanner->getLine(), "Error: Expected \';\'.");
return false;
}
for (std::string name : toDeclare) {
vars.push_back(name);
AstVarDec *vd = new AstVarDec(name, DataType::Ptr);
block->addStatement(vd);
vd->setExpression(empty->getExpression());
vd->setPtrType(dataType);
// Create an assignment to a malloc call
AstVarAssign *va = new AstVarAssign(name);
va->setDataType(DataType::Ptr);
va->setPtrType(dataType);
block->addStatement(va);
AstFuncCallExpr *callMalloc = new AstFuncCallExpr("malloc");
//callMalloc->setArguments(vd->getExpressions());
va->setExpression(callMalloc);
// In order to get a proper malloc, we need to multiply the argument by
// the size of the type. Get the arguments, and do that
///AstExpression *arg = callMalloc->getArguments().at(0);
///callMalloc->clearArguments();
AstExprList *list = new AstExprList;
callMalloc->setArgExpression(list);
AstI32 *size;
if (dataType == DataType::I32 | dataType == DataType::U32) size = new AstI32(4);
else if (dataType == DataType::I64 || dataType == DataType::U64) size = new AstI32(8);
else if (dataType == DataType::String) size = new AstI32(8);
else size = new AstI32(1);
AstMulOp *op = new AstMulOp;
op->setLVal(size);
op->setRVal(vd->getExpression());
//callMalloc->addArgument(op);
list->addExpression(op);
// Finally, set the size of the declaration
vd->setPtrSize(vd->getExpression());
typeMap[name] = std::pair<DataType, DataType>(DataType::Ptr, dataType);
}
// We're at the end of the declaration
} else if (token.type == SemiColon) {
syntax->addError(scanner->getLine(), "Expected init expression.");
return false;
// Otherwise, we have a regular variable
} else {
AstExpression *arg = buildExpression(dataType);
if (!arg) return false;
for (std::string name : toDeclare) {
vars.push_back(name);
AstVarDec *vd = new AstVarDec(name, dataType);
block->addStatement(vd);
auto typePair = std::pair<DataType, DataType>(dataType, DataType::Void);
typeMap[name] = typePair;
AstVarAssign *va = new AstVarAssign(name);
va->setDataType(dataType);
va->setExpression(arg);
block->addStatement(va);
}
}
return true;
}
// Builds a variable assignment
bool Parser::buildVariableAssign(AstBlock *block, Token idToken) {
DataType dataType = typeMap[idToken.id_val].first;
AstVarAssign *va = new AstVarAssign(idToken.id_val);
va->setDataType(dataType);
block->addStatement(va);
AstExpression *arg = buildExpression(dataType);
if (!arg) return false;
va->setExpression(arg);
if (!va->hasExpression()) {
syntax->addError(scanner->getLine(), "Invalid variable assignment.");
return false;
}
return true;
}
// Builds an array assignment
bool Parser::buildArrayAssign(AstBlock *block, Token idToken) {
DataType dataType = typeMap[idToken.id_val].second;
AstArrayAssign *pa = new AstArrayAssign(idToken.id_val);
pa->setDataType(typeMap[idToken.id_val].first);
pa->setPtrType(dataType);
block->addStatement(pa);
AstExpression *arg = buildExpression(DataType::I32, RBracket);
if (!arg) return false;
pa->setIndex(arg);
Token token = scanner->getNext();
if (token.type != Assign) {
syntax->addError(scanner->getLine(), "Expected \'=\' after array assignment.");
return false;
}
arg = buildExpression(dataType);
if (!arg) return false;
pa->setExpression(arg);
return true;
}
// Builds a constant variable
bool Parser::buildConst(bool isGlobal) {
Token token = scanner->getNext();
std::string name = token.id_val;
// Make sure we have a name for our constant
if (token.type != Id) {
syntax->addError(scanner->getLine(), "Expected constant name.");
return false;
}
// Syntax check
token = scanner->getNext();
if (token.type != Colon) {
syntax->addError(scanner->getLine(), "Expected \':\' in constant expression.");
return false;
}
// Get the data type
token = scanner->getNext();
DataType dataType = DataType::Void;
switch (token.type) {
case Bool: dataType = DataType::Bool; break;
case Char: dataType = DataType::Char; break;
case I8: dataType = DataType::I8; break;
case U8: dataType = DataType::U8; break;
case I16: dataType = DataType::I16; break;
case U16: dataType = DataType::U16; break;
case I32: dataType = DataType::I32; break;
case U32: dataType = DataType::U32; break;
case I64: dataType = DataType::I64; break;
case U64: dataType = DataType::U64; break;
case Str: dataType = DataType::String; break;
default: {
syntax->addError(scanner->getLine(), "Unknown data type.");
return false;
}
}
// Final syntax check
token = scanner->getNext();
if (token.type != Assign) {
syntax->addError(scanner->getLine(), "Expected \'=\' after const assignment.");
return false;
}
// Build the expression. We create a dummy statement for this
AstExpression *expr = buildExpression(dataType, SemiColon, true);
if (!expr) return false;
// Put it all together
if (isGlobal) {
globalConsts[name] = std::pair<DataType, AstExpression*>(dataType, expr);
} else {
localConsts[name] = std::pair<DataType, AstExpression*>(dataType, expr);
}
return true;
}
| 33.660232 | 98 | 0.580294 | [
"vector"
] |
03e3b18407a366794d23a8cea3890b6a7b6997f9 | 3,083 | hpp | C++ | src/framework/results/result.hpp | garrison/qiskit-aer | 24c51a675b8653c8ad2af587d40b795ac94c07c7 | [
"Apache-2.0"
] | 313 | 2018-12-19T09:19:12.000Z | 2022-03-21T18:15:41.000Z | src/framework/results/result.hpp | garrison/qiskit-aer | 24c51a675b8653c8ad2af587d40b795ac94c07c7 | [
"Apache-2.0"
] | 933 | 2018-12-21T02:56:49.000Z | 2022-03-30T01:19:54.000Z | src/framework/results/result.hpp | chriseclectic/qiskit-aer | 61b028b7ccd1d6e96c8de48a10648c0bc3c07ff9 | [
"Apache-2.0"
] | 313 | 2018-12-19T14:52:55.000Z | 2022-02-28T20:20:14.000Z | /**
* This code is part of Qiskit.
*
* (C) Copyright IBM 2018, 2019.
*
* This code is licensed under the Apache License, Version 2.0. You may
* obtain a copy of this license in the LICENSE.txt file in the root directory
* of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
*
* Any modifications or derivative works of this code must retain this
* copyright notice, and modified files need to carry a notice indicating
* that they have been altered from the originals.
*/
#ifndef _aer_framework_results_result_hpp_
#define _aer_framework_results_result_hpp_
#include "framework/results/data/metadata.hpp"
#include "framework/results/experiment_result.hpp"
namespace AER {
//============================================================================
// Result container for Qiskit-Aer
//============================================================================
struct Result {
public:
// Result status:
// completed: all experiments were executed successfully
// partial: only some experiments were executed succesfully
enum class Status {empty, completed, partial_completed, error};
// Constructor
Result(size_t num_exp = 0) {results.resize(num_exp);}
// Experiment results
std::vector<ExperimentResult> results;
// Job metadata
std::string backend_name;
std::string backend_version;
std::string qobj_id;
std::string job_id;
std::string date;
// Success and status
Status status = Status::empty; // Result status
std::string message; // error message
// Metadata
json_t header;
Metadata metadata;
// Size and resize
auto size() {return results.size();}
void resize(size_t size) {results.resize(size);}
// Serialize engine data to JSON
json_t to_json();
};
//------------------------------------------------------------------------------
// JSON serialization
//------------------------------------------------------------------------------
json_t Result::to_json() {
// Initialize output as additional data JSON
json_t js;
js["qobj_id"] = qobj_id;
js["backend_name"] = backend_name;
js["backend_version"] = backend_version;
js["date"] = date;
js["job_id"] = job_id;
if (results.empty()) {
js["results"] = json_t::array({});
} else {
for (auto& res : results) {
js["results"].push_back(res.to_json());
}
}
if (header.empty() == false)
js["header"] = header;
js["metadata"] = metadata.to_json();
js["success"] = (status == Status::completed);
switch (status) {
case Status::completed:
js["status"] = std::string("COMPLETED");
break;
case Status:: partial_completed:
js["status"] = std::string("PARTIAL COMPLETED");
break;
case Status::error:
js["status"] = std::string("ERROR: ") + message;
break;
case Status::empty:
js["status"] = std::string("EMPTY");
}
return js;
}
//------------------------------------------------------------------------------
} // end namespace AER
//------------------------------------------------------------------------------
#endif
| 28.813084 | 80 | 0.570873 | [
"vector"
] |
03e957a239a8bf81a58de9bf8d141b017fd2c272 | 5,836 | cc | C++ | src/core/http_module_static.cc | archilleu/muinx | 5b9cae589a0b3b1ca126912ca7bbda6c9f8d8e35 | [
"Unlicense"
] | null | null | null | src/core/http_module_static.cc | archilleu/muinx | 5b9cae589a0b3b1ca126912ca7bbda6c9f8d8e35 | [
"Unlicense"
] | null | null | null | src/core/http_module_static.cc | archilleu/muinx | 5b9cae589a0b3b1ca126912ca7bbda6c9f8d8e35 | [
"Unlicense"
] | null | null | null | //---------------------------------------------------------------------------
#include <memory>
#include <sys/types.h>
#include <sys/stat.h>
#include "defines.h"
#include "base/include/function.h"
#include "../tools/muinx_logger.h"
#include "http_module_core.h"
#include "http_module_static.h"
#include "http_module_filter_header.h"
//---------------------------------------------------------------------------
namespace core
{
//---------------------------------------------------------------------------
using namespace std::placeholders;
//---------------------------------------------------------------------------
HttpModuleStatic g_http_module_static;
//---------------------------------------------------------------------------
HttpModuleStatic::HttpModuleStatic()
{
HttpModuleCtx* ctx = new HttpModuleCtx();
ctx->postconfiguration = std::bind(&HttpModuleStatic::Initialize, this);
ctx->create_loc_config = std::bind(&HttpModuleStatic::CreateStaticConfig, this);
this->ctx_.reset(ctx);
this->commands_ =
{
{
"directio",
HTTP_MAIN_CONF|HTTP_SRV_CONF|HTTP_LOC_CONF|CONF_FLAG,
std::bind(&HttpModuleStatic::ConfigSetCallbackDirectio, this, _1, _2, _3),
HTTP_LOC_CONF_OFFSET
}
};
}
//---------------------------------------------------------------------------
HttpModuleStatic::~HttpModuleStatic()
{
}
//---------------------------------------------------------------------------
int HttpModuleStatic::StaticHandler(HttpRequest& http_request)
{
if(!(http_request.method()&(HttpRequest::GET|HttpRequest::POST|HttpRequest::HEAD)))
{
return HttpRequest::NOT_ALLOWED;
}
/*
* 其次是检查请求的 url 的结尾字符是不是斜杠/,如果是说明请求的不是一个文件,给后续的
* handler 去处理,比如后续的 ngx_http_autoindex_handler(如果是请求的是一个目录下面,
* 可以列出这个目录的文件),或者是 ngx_http_index_handler(如果请求的路径下面有个默认
* 的 index 文件,直接返回 index 文件的内容)
*/
if('/' == http_request.url().back())
{
return MUINX_DECLINED;
}
//获取该模块需要的配置项目
//TODO:处理目录的符号链接
//TODO:缓存文件
auto static_config = reinterpret_cast<HttpStaticConfig*>
(http_request.loc_conf()[g_http_module_static.module_index()]);
if(true == static_config->cache)
{
}
//判断路径是文件还是目录等,不跟随符号链接
struct stat sb;
HttpRequest::StatusCode status_code;
if (-1 == lstat(http_request.path().c_str(), &sb))
{
switch(errno)
{
case EACCES:
status_code = HttpRequest::StatusCode::FORBIDDEN;
break;
case ENAMETOOLONG:
status_code = HttpRequest::StatusCode::REQUEST_URI_TOO_LARGE;
break;
case ENOENT:
status_code = HttpRequest::StatusCode::NOT_FOUND;
break;
default:
status_code = HttpRequest::StatusCode::INTERNAL_SERVER_ERROR;
}
http_request.set_status_code(status_code);
return MUINX_ERROR;
}
switch (sb.st_mode & S_IFMT)
{
case S_IFREG:
break;
case S_IFDIR: //目录
//TODO:加上'/'重定向
break;
//不是文件或者目录
case S_IFBLK:
case S_IFCHR:
case S_IFIFO:
case S_IFLNK:
case S_IFSOCK:
http_request.set_status_code(HttpRequest::StatusCode::FORBIDDEN);
return MUINX_ERROR;
}
//获取文件数据
std::vector<char> data;
if(false == base::LoadFile(http_request.path(), &data))
{
http_request.set_status_code(HttpRequest::StatusCode::INTERNAL_SERVER_ERROR);
return MUINX_DECLINED;
}
http_request.headers_out().set_content_length(data.size());
http_request.set_response_body(std::move(data));
//设置响应头
http_request.headers_out().set_connection(http_request.headers_in().connection());
http_request.headers_out().set_last_modified(sb.st_mtim.tv_sec);
//TODO:设置响应头map
//根据后缀设置响应内容格式
auto loc_conf = reinterpret_cast<HttpModuleCore::HttpLocConf*>
(http_request.loc_conf()[g_http_module_core.module_index()]);
if(http_request.exten().empty())
{
http_request.headers_out().set_content_type(loc_conf->default_type);
}
else
{
auto main_conf = reinterpret_cast<HttpModuleCore::HttpMainConf*>
(http_request.main_conf()[g_http_module_core.module_index()]);
auto iter = main_conf->types.find(http_request.exten());
if(iter == main_conf->types.end())
{
http_request.headers_out().set_content_type(loc_conf->default_type);
}
else
{
http_request.headers_out().set_content_type(iter->second);
}
}
return MUINX_OK;
}
//---------------------------------------------------------------------------
bool HttpModuleStatic::ConfigSetCallbackDirectio(const CommandConfig& command_config, const CommandModule& module, void* config)
{
(void)module;
auto http_static_config = reinterpret_cast<HttpStaticConfig*>(config);
http_static_config->cache = (command_config.args[1] == "on");
return true;
}
//---------------------------------------------------------------------------
bool HttpModuleStatic::Initialize()
{
Logger_debug("index:%d, PostConfiguration", this->index());
g_http_module_core.core_main_conf()->phases[HttpModuleCore::HTTP_CONTENT_PHASE]
.handlers.push_back(std::bind(StaticHandler, _1));
return true;
}
//---------------------------------------------------------------------------
void* HttpModuleStatic::CreateStaticConfig()
{
auto config = new HttpStaticConfig();
config->cache = false;
return config;
}
//---------------------------------------------------------------------------
}//namespace core
//---------------------------------------------------------------------------
| 31.545946 | 128 | 0.546436 | [
"vector"
] |
03f081849a2bcbe24f6bf8059affe56970764b59 | 7,223 | cpp | C++ | machine-learning/small-tasks/support-vector-machine.cpp | nothingelsematters/university | 5561969b1b11678228aaf7e6660e8b1a93d10294 | [
"WTFPL"
] | 1 | 2018-06-03T17:48:50.000Z | 2018-06-03T17:48:50.000Z | machine-learning/small-tasks/support-vector-machine.cpp | nothingelsematters/University | b1e188cb59e5a436731b92c914494626a99e1ae0 | [
"WTFPL"
] | null | null | null | machine-learning/small-tasks/support-vector-machine.cpp | nothingelsematters/University | b1e188cb59e5a436731b92c914494626a99e1ae0 | [
"WTFPL"
] | 14 | 2019-04-07T21:27:09.000Z | 2021-12-05T13:37:25.000Z | #include <iostream>
#include <iomanip>
#include <limits>
#include <algorithm>
#include <vector>
#include <set>
#include <random>
using std::pair;
using std::vector;
using std::set;
using std::mt19937;
class SupportVectorMachine {
public:
SupportVectorMachine(
vector<vector<double>> objects,
vector<double> results,
double c,
double tolerance = 1e-3) :
tolerance(tolerance),
c(c),
objects_amount(objects.size()),
objects(objects),
results(results) {
alphas.resize(objects_amount, 0.0);
errors.resize(objects_amount, 0.0);
for (bool examine_all = true, changed = false; changed || examine_all; examine_all = !examine_all && !changed) {
changed = false;
if (examine_all) {
for (size_t i = 0; i < objects_amount; ++i) {
changed |= examine_example(i);
}
} else {
for (size_t i : vector<size_t>(non_bound.begin(), non_bound.end())) {
changed |= examine_example(i);
}
}
}
}
pair<vector<double>, double> coefficients() {
return {alphas, b};
}
private:
bool equals(double a, double b = 0, double e = epsilon) {
return std::abs(a - b) < e;
}
double f(size_t x) {
double result = -b;
for (size_t i = 0; i < objects_amount; ++i) {
result += alphas[i] * results[i] * objects[x][i];
}
return result;
}
bool on_bounds(double alpha) {
return equals(alpha) || equals(alpha, c);
}
double svm_output(double alpha, size_t i, double y) {
return !equals(alpha) && equals(alpha, 0, c - epsilon) ? errors[i] : (f(i) - y);
}
bool take_step(size_t i1, size_t i2, double E2) {
if (i1 == i2) {
return false;
}
double y1 = results[i1];
double y2 = results[i2];
double alpha1 = alphas[i1];
double alpha2 = alphas[i2];
double E1 = svm_output(alpha1, i1, y1);
double s = y1 * y2;
double L = std::max(0.0, equals(y1, y2) ? alpha1 + alpha2 - c : alpha2 - alpha1);
double H = std::min(static_cast<double>(c), equals(y1, y2) ? alpha1 + alpha2 : c + alpha2 - alpha1);
if (equals(L, H)) {
return false;
}
double k11 = objects[i1][i1];
double k12 = objects[i1][i2];
double k22 = objects[i2][i2];
double eta = k11 + k22 - 2 * k12;
double a2;
if (!equals(eta)) {
a2 = alpha2 + y2 * (E1 - E2) / eta;
if (a2 < L) {
a2 = L;
} else if (a2 > H) {
a2 = H;
}
} else {
double f1 = y1 * (E1 + b) - alpha1 * k11 - s * alpha2 * k12;
double f2 = y2 * (E2 + b) - s * alpha1 * k12 - alpha2 * k22;
double L1 = alpha1 + s * (alpha2 - L);
double H1 = alpha1 + s * (alpha2 - H);
double objL = L1 * f1 + L * f2 + 0.5 * L1 * L1 * k11 + 0.5 * L * L * k22 + s * L * L1 * k12;
double objH = H1 * f1 + H * f2 + 0.5 * H1 * H1 * k11 + 0.5 * H * H * k22 + s * H * H1 * k12;
if (objL < objH - epsilon) {
a2 = L;
} else if (objL > objH + epsilon) {
a2 = H;
} else {
a2 = alpha2;
}
}
if (equals(a2, alpha2, epsilon * (a2 + alpha2 + epsilon))) {
return false;
}
double a1 = alpha1 + s * (alpha2 - a2);
if (a1 < 0) {
a2 += s * a1;
a1 = 0;
} else if (a1 > c) {
a2 += s * (a1 - c);
a1 = c;
}
double b1 = E1 + y1 * (a1 - alpha1) * k11 + y2 * (a2 - alpha2) * k12 + b;
double b2 = E2 + y1 * (a1 - alpha1) * k12 + y2 * (a2 - alpha2) * k22 + b;
double b_new;
if (0 < a1 && a1 < c) {
b_new = b1;
} else if (0 < a2 && a2 < c) {
b_new = b2;
} else {
b_new = (b1 + b2) / 2.0;
}
double deltaB = b_new - b;
b = b_new;
double deltaA1 = a1 - alpha1;
double deltaA2 = a2 - alpha2;
for (size_t i : non_bound) {
errors[i] += deltaA1 * y1 * objects[i1][i] + deltaA2 * y2 * objects[i2][i] - deltaB;
}
errors[i2] = 0.0;
if (!on_bounds(a1)) {
non_bound.insert(i1);
} else {
non_bound.erase(i1);
}
if (!on_bounds(a2)) {
non_bound.insert(i2);
} else {
non_bound.erase(i2);
}
alphas[i1] = a1;
alphas[i2] = a2;
return true;
}
bool examine_example(size_t i2) {
int y2 = results[i2];
double alpha2 = alphas[i2];
double E2 = svm_output(alpha2, i2, y2);
double r2 = E2 * y2;
if ((r2 < -tolerance && alpha2 < c - epsilon) || (r2 > tolerance && alpha2 > epsilon)) {
if (non_bound.size() > 1) {
size_t i1 = 0;
for (size_t i : non_bound) {
if (fabs(E2 - errors[i]) > fabs(E2 - errors[i1])) {
i1 = i;
}
}
if (take_step(i1, i2, E2)) {
return true;
}
}
vector<size_t> non_bound_ids(non_bound.begin(), non_bound.end());
std::shuffle(non_bound_ids.begin(), non_bound_ids.end(), random_generator);
for (size_t i1 : non_bound_ids) {
if (take_step(i1, i2, E2)) {
return true;
}
}
size_t random_start = random_generator() % objects_amount;
for (size_t i = random_start; i < random_start + objects_amount; ++i) {
size_t i1 = i % objects_amount;
if (take_step(i1, i2, E2)) {
return true;
}
}
}
return false;
}
static constexpr double epsilon = std::numeric_limits<double>::epsilon();
mt19937 random_generator = mt19937(std::random_device()());
double b = 0.0;
double tolerance;
double c;
size_t objects_amount;
vector<vector<double>> objects;
vector<double> results;
vector<double> alphas;
vector<double> errors;
set<double> non_bound;
};
int main() {
std::ios_base::sync_with_stdio(false);
size_t objects_amount;
std::cin >> objects_amount;
vector<vector<double>> objects(objects_amount, vector<double>(objects_amount));
vector<double> results(objects_amount);
double c;
for (size_t i = 0; i < objects_amount; ++i) {
for (size_t j = 0; j < objects_amount; ++j) {
std::cin >> objects[i][j];
}
std::cin >> results[i];
}
std::cin >> c;
auto [alphas, b] = SupportVectorMachine(objects, results, c).coefficients();
for (size_t i = 0; i < objects_amount; ++i) {
std::cout << std::setprecision(10) << alphas[i] << '\n';
}
std::cout << std::setprecision(10) << -b << '\n';
return 0;
}
| 27.154135 | 120 | 0.473903 | [
"vector"
] |
03f5e8bf7cf3db8d96793f09ce004c2ca670ca88 | 7,488 | cc | C++ | mysql-dst/mysql-cluster/unittest/gunit/byteorder-t.cc | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 9 | 2020-12-17T01:59:13.000Z | 2022-03-30T16:25:08.000Z | mysql-dst/mysql-cluster/unittest/gunit/byteorder-t.cc | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 1 | 2021-07-30T12:06:33.000Z | 2021-07-31T10:16:09.000Z | mysql-dst/mysql-cluster/unittest/gunit/byteorder-t.cc | SJTU-IPADS/dst | 897b929a692642cbf295c105d9d6e64090abb673 | [
"Apache-2.0"
] | 1 | 2021-08-01T13:47:07.000Z | 2021-08-01T13:47:07.000Z | /* Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
#include "my_config.h"
#include <gtest/gtest.h>
#include <limits>
#include "my_global.h"
namespace byteorder_unittest {
using std::numeric_limits;
#if defined(GTEST_HAS_PARAM_TEST)
/*
This class is used to instantiate parameterized tests for float and double.
*/
template<typename T>
class FloatingTest
{
protected:
T input;
T output;
uchar buf[sizeof(T)];
};
class Float4Test : public FloatingTest<float>,
public ::testing::TestWithParam<float>
{
virtual void SetUp()
{
input= GetParam();
output= numeric_limits<float>::quiet_NaN();
}
};
INSTANTIATE_TEST_CASE_P(Foo, Float4Test,
::testing::Values(numeric_limits<float>::min(),
numeric_limits<float>::max(),
numeric_limits<float>::epsilon(),
-numeric_limits<float>::min(),
-numeric_limits<float>::max(),
-numeric_limits<float>::epsilon(),
-1.0f, 0.0f, 1.0f));
/*
The actual test case for float: store and get some values.
*/
TEST_P(Float4Test, PutAndGet)
{
float4store(buf, input);
float4get(&output, buf);
EXPECT_EQ(input, output);
floatstore(buf, input);
floatget(&output, buf);
EXPECT_EQ(input, output);
}
class Float8Test : public FloatingTest<double>,
public ::testing::TestWithParam<double>
{
virtual void SetUp()
{
input= GetParam();
output= numeric_limits<double>::quiet_NaN();
}
};
INSTANTIATE_TEST_CASE_P(Foo, Float8Test,
::testing::Values(numeric_limits<double>::min(),
numeric_limits<double>::max(),
numeric_limits<double>::epsilon(),
-numeric_limits<double>::min(),
-numeric_limits<double>::max(),
-numeric_limits<double>::epsilon(),
-1.0, 0.0, 1.0));
/*
The actual test case for double: store and get some values.
*/
TEST_P(Float8Test, PutAndGet)
{
float8store(buf, input);
float8get(&output, buf);
EXPECT_EQ(input, output);
doublestore(buf, input);
doubleget(&output, buf);
EXPECT_EQ(input, output);
}
#endif // GTEST_HAS_PARAM_TEST
#if defined(GTEST_HAS_TYPED_TEST)
/*
A test fixture class, parameterized on type.
Will be instantiated for all IntegralTypes below.
*/
template<typename T>
class IntegralTest : public ::testing::Test
{
protected:
typedef std::numeric_limits<T> Limit;
T input;
T output;
uchar buf[sizeof(T)];
typename std::vector<T> values;
IntegralTest() : input(0), output(0) {}
virtual void SetUp()
{
values.push_back(Limit::min());
values.push_back(Limit::min() / T(2));
values.push_back(T(0));
values.push_back(T(42));
values.push_back(Limit::max() / T(2));
values.push_back(Limit::max());
}
};
/*
A class to make our 3, 5 and 6 digit integers look like builtins.
*/
template<int ndigits>
struct sizeNint
{
// For numeric_limits.
typedef ulonglong value_type;
sizeNint() : value(0) {}
explicit sizeNint(ulonglong v)
{
switch(ndigits)
{
case 3: value= v & 0xFFFFFFULL; break;
case 5: value= v & 0xFFFFFFFFFFULL; break;
case 6: value= v & 0xFFFFFFFFFFFFULL; break;
default: ADD_FAILURE() << "unxpected number of digits";
}
}
sizeNint operator/(const sizeNint &that) const
{ return sizeNint(this->value / that.value); }
bool operator==(const sizeNint &that) const
{ return this->value == that.value; }
ulonglong value;
};
// googletest needs to be able to print arguments to EXPECT_EQ.
template<int ndigits>
std::ostream &operator<<(std::ostream &s, const sizeNint<ndigits> &v)
{ return s << v.value; }
// Instantiate the PutAndGet test for all these types:
typedef ::testing::Types<short, ushort,
sizeNint<3>, sizeNint<5>, sizeNint<6>,
int, unsigned,
longlong, ulonglong> IntegralTypes;
TYPED_TEST_CASE(IntegralTest, IntegralTypes);
/*
Wrap all the __get, __store, __korr macros in functions.
*/
template<typename T> void put_integral(uchar *buf, T val)
{ ADD_FAILURE() << "unknown type in put_integral"; }
template<typename T> void get_integral(T &val, uchar *buf)
{ ADD_FAILURE() << "unknown type in get_integral"; }
template<> void put_integral(uchar *buf, short val) { shortstore(buf, val); }
template<> void get_integral(short &val, uchar *buf) { shortget(&val, buf); }
// Hmm, there's no ushortstore...
template<> void put_integral(uchar *buf, ushort val) { shortstore(buf, val); }
template<> void get_integral(ushort &val, uchar *buf) { ushortget(&val, buf); }
template<> void put_integral(uchar *buf, int val) { longstore(buf, val); }
template<> void get_integral(int &val, uchar *buf) { longget(&val, buf); }
// Hmm, there's no ulongstore...
template<> void put_integral(uchar *buf, unsigned val) { longstore(buf, val); }
template<> void get_integral(unsigned &val, uchar *buf) { ulongget(&val, buf); }
template<> void put_integral(uchar *buf, longlong val)
{ longlongstore(buf, val); }
template<> void get_integral(longlong &val, uchar *buf)
{ longlongget(&val, buf); }
// Reading ulonglong is different from all the above ....
template<> void put_integral(uchar *buf, ulonglong val)
{ int8store(buf, val); }
template<> void get_integral(ulonglong &val, uchar *buf)
{ val= uint8korr(buf); }
template<> void put_integral(uchar *buf, sizeNint<3> val)
{ int3store(buf, static_cast<uint>(val.value)); }
template<> void get_integral(sizeNint<3> &val, uchar *buf)
{ val.value= uint3korr(buf); }
template<> void put_integral(uchar *buf, sizeNint<5> val)
{ int5store(buf, val.value); }
template<> void get_integral(sizeNint<5> &val, uchar *buf)
{ val.value= uint5korr(buf); }
template<> void put_integral(uchar *buf, sizeNint<6> val)
{ int6store(buf, val.value); }
template<> void get_integral(sizeNint<6> &val, uchar *buf)
{ val.value= uint6korr(buf); }
/*
This is the actual test which will be instantiated for all IntegralTypes.
*/
TYPED_TEST(IntegralTest, PutAndGet)
{
for (size_t ix= 0; ix < this->values.size(); ++ix)
{
this->input= this->values[ix];
put_integral(this->buf, this->input);
get_integral(this->output, this->buf);
// Visual studio rejects: EXPECT_EQ(this->input, this->output);
TypeParam myinput= this->input;
TypeParam myoutput= this->output;
EXPECT_EQ(myinput, myoutput);
}
}
#endif // GTEST_HAS_TYPED_TEST
}
| 30.315789 | 80 | 0.641827 | [
"vector"
] |
03fb15f6a23abe1fb57ded9db144e021bbdafe9b | 33,486 | cxx | C++ | PWGCF/Correlations/JCORRAN/Pro/AliBSDiJetTask.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 114 | 2017-03-03T09:12:23.000Z | 2022-03-03T20:29:42.000Z | PWGCF/Correlations/JCORRAN/Pro/AliBSDiJetTask.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 19,637 | 2017-01-16T12:34:41.000Z | 2022-03-31T22:02:40.000Z | PWGCF/Correlations/JCORRAN/Pro/AliBSDiJetTask.cxx | maroozm/AliPhysics | 22ec256928cfdf8f800e05bfc1a6e124d90b6eaf | [
"BSD-3-Clause"
] | 1,021 | 2016-07-14T22:41:16.000Z | 2022-03-31T05:15:51.000Z | /*************************************************************************
*
* Copyright(c) 1998-2018, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// Comment describing what this class does needed!
//==================================================================
// Class for di-charged and full jet analyses.
// by Beomkyu KIM
//==================================================================
#include <TClonesArray.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TH3F.h>
#include <TF1.h>
#include <TList.h>
#include <TProfile.h>
#include <TLorentzVector.h>
#include <TVector.h>
#include <TSystem.h>
#include <TFile.h>
#include <TKey.h>
#include <THnSparse.h>
#include <TRandom.h>
#include "THistManager.h"
#include "AliVCluster.h"
#include "AliAODCaloCluster.h"
#include "AliVTrack.h"
#include "AliEmcalJet.h"
#include "AliLog.h"
#include "AliJetContainer.h"
#include "AliParticleContainer.h"
#include "AliClusterContainer.h"
#include "AliPicoTrack.h"
#include "AliCentrality.h"
#include "AliBSDiJetTask.h"
#include <TRandom3.h>
#include "AliAnalysisManager.h"
#include "AliAODMCHeader.h"
#include "AliGenEventHeader.h"
#include "AliGenPythiaEventHeader.h"
#include "AliEmcalPythiaInfo.h"
#include "AliMCEvent.h"
#include "AliStack.h"
#include "AliEmcalTrackSelection.h"
#include "AliEmcalTrackSelectionAOD.h"
#include "AliAnalysisUtils.h"
//#include "AliAnalysisTaskCounter.h"
#include "AliESDEvent.h"
#include "AliAODEvent.h"
#include "AliCalorimeterUtils.h"
#include "AliEMCALGeometry.h"
#include "AliMultSelection.h"
#include "AliAnalysisTaskEmcalEmbeddingHelper.h"
const Double_t pionmass = AliPID::ParticleMass(AliPID::kPion);
const Double_t pi = TMath::Pi();
AliBSDiJetTask::AliBSDiJetTask()
: AliAnalysisTaskEmcalJet("AliBSDiJetTask",kTRUE)
, fOutput(0)
{
DefineOutput (1, TList::Class());
}
AliBSDiJetTask::AliBSDiJetTask(const char *name)
: AliAnalysisTaskEmcalJet(name,kTRUE)
, fOutput(0)
{
DefineOutput (1, TList::Class());
}
AliBSDiJetTask::AliBSDiJetTask(const char *name, const char *option)
: AliAnalysisTaskEmcalJet(name,kTRUE)
, fOutput(0)
, fOption(option)
{
DefineOutput (1, TList::Class());
}
AliBSDiJetTask::AliBSDiJetTask(const AliBSDiJetTask& ap)
: AliAnalysisTaskEmcalJet(ap.fName,kTRUE)
, fOutput(ap.fOutput)
{
}
AliBSDiJetTask& AliBSDiJetTask::operator = (const AliBSDiJetTask& ap)
{
this->~AliBSDiJetTask();
new(this) AliBSDiJetTask(ap);
return *this;
}
AliBSDiJetTask::~AliBSDiJetTask()
{
delete fOutput;
delete fBSRandom;
}
void AliBSDiJetTask::UserCreateOutputObjects(){
fBSRandom = new TRandom3;
fBSRandom->SetSeed();
//===============================
// BINS
//===============================
auto binJetMass = AxisFix( "JetMass", 50, 0, 100 );
auto binInvM = AxisVar( "InvM", {0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100,105,110,115,120,125,130,135,140,145,150,160,170,180,190,200,220,240,270,300,500,1000,5000});
auto binCent = AxisFix( "Cent", 1, 0, 100 );
auto binDiJetSel = AxisStr( "DiJetSel", { "NoCut"
,"B1","B2","B3","C1","C2","C3","D1","D2","D3"
,"M1","M2","M3","M4","M5","M6","M7" } );
fNDiJetSelection = binDiJetSel.GetNbins();
if( fIsAA ){
binCent = AxisFix( "Cent", 20, 0, 100 );
}
if (fOption.Contains("LHC16l")){
binCent = AxisVar("Cent",{0,0.001,0.01,0.1,0.5,1,5,10,15,20,30,40,50,70,100});
}
auto binLog1k = AxisLog("Log1k",500,0.1,1000,0);
//auto binLog3c = AxisVar("Log3c",{0,5,7,9,12,16,21,28,36,45,57,70,85,99,115,132,150,169,190,212,235,500});
auto binLog3c = AxisVar("Log3c",{0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100,105,110,115,120,125,130,135,140,145,150,160,170,180,190,200,220,240,270 ,300,500,1000,5000});
auto bintpt = AxisVar("JetTPt",{0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100,105,110,115,120,125,130,135,140,145,150,160,170,180,190,200,220,240,270 ,300,500,1000,5000});
auto bin1c = AxisFix("Fix1c",100,0,100);
auto binAsim = AxisFix("Asim", 100 ,0,1);
auto binM = AxisFix("BinM",600,-300,300);
auto binpthardbin = AxisFix("pthardbin",20,0,20);
//auto binjetpt = AxisVar("binjetpt",{0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,35,40,45,50,55,60,65,70,80,90,100,120,140,160,180,200,250,300,350,400,450,500,600,700,800,900,1000});
//auto binjetpt = AxisVar("binjetpt",{0,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,500,1000});
auto binjetpt = AxisLog("binjetpt",100,1,1000,1);
//===============================
// HISTOGRAMS
//===============================
fHistos = new THistManager("jethists");
const int nbins=100;
Double_t logbins[nbins+1];
Double_t low= 0.1;
Double_t high=300;
Double_t logbw= (log(high)-log(low))/nbins;
for(int ij=0;ij<=nbins;ij++) logbins[ij]=low*exp(ij*logbw);
fHistos -> CreateTH1("zvtx","zvtx",60,-30,30,"s");
fHistos -> CreateTH1("mczvtx","mczvtx",60,-30,30,"s");
fHistos -> CreateTH1("hPtHardBin","pthardbin",20,0,20,"s");
fHistos -> CreateTH1("nCentrality","nCentrality", 10,0,100,"s");
fHistos -> CreateTH2("trketaphi","trketaphi",20,-1,1,90,0,TMath::TwoPi(),"s");
fHistos -> CreateTH2("jetetaphi","jetetaphi",20,-1,1,90,0,TMath::TwoPi(),"s");
vector<TString> ent ={"All","PassPileUp","PassPileUpGoodz","GoodzNTrials","GoodzNX","NXoNTrials"};
auto h = fHistos->CreateTH1("hEventNumbers","",ent.size(), 0, ent.size());
for(auto i=0u;i<ent.size();i++) h->GetXaxis()->SetBinLabel(i+1,ent.at(i).Data());
CreateTHnSparse( "hJetPtLeading","",4,{
binDiJetSel,binCent,bintpt,binpthardbin}, "s" );
CreateTHnSparse( "hRho","Rho dist",3,{binCent,bin1c,binpthardbin},"s");
CreateTHnSparse( "hDiJetDPhi_0_2pi", "DiJet #Delta#Phi", 6, {
binDiJetSel, binCent, bintpt,binInvM, AxisFix( "",100, 0, 2*pi ), binpthardbin },"s");
CreateTHnSparse( "hDiJetDPhi_0_2piTruth", "DiJet #Delta#Phi", 6, {
binDiJetSel, binCent, bintpt,binInvM, AxisFix( "",100, 0, 2*pi ), binpthardbin },"s");
CreateTHnSparse( "hDiJetInvMPtPair", "DiJet PtPair", 6, {
binDiJetSel, binCent, bintpt, binInvM, binLog3c, binpthardbin },"s");
CreateTHnSparse( "hDiJetInvMPtPairTruth", "DiJet PtPair Truth", 6, {
binDiJetSel, binCent, bintpt, binInvM, binLog3c, binpthardbin },"s");
CreateTHnSparse( "hDiJetInvMPtPairRes", "DiJet InvM PtPair Res Matrix", 8, {
binDiJetSel, binCent, bintpt,binInvM,binInvM,binLog3c,binLog3c, binpthardbin},"s");
CreateTHnSparse( "hDiJetInvMPtPairMiss", "DiJet InvM PtPair missing tracks", 6, {
binDiJetSel, binCent, bintpt,binInvM, binLog3c, binpthardbin},"s");
CreateTHnSparse( "hDiJetInvMPtPairFake", "DiJet InvM PtPair fake tracks", 6, {
binDiJetSel, binCent, bintpt,binInvM, binLog3c, binpthardbin},"s");
CreateTHnSparse( "hJetPt", "Inclusive jet pt", 3, {binCent, binjetpt, binpthardbin },"s");
CreateTHnSparse( "hJetPtMatched", "Inclusive matched jet pt", 3, {binCent, binjetpt, binpthardbin },"s");
CreateTHnSparse( "hJetPtTruth", "Inclusive Gen jet pt", 3, {binCent, binjetpt, binpthardbin },"s");
CreateTHnSparse( "hJetPtRes", "Inclusive jet pt Res Matrix", 4, {
binCent, binjetpt, binjetpt, binpthardbin },"s");
CreateTHnSparse( "hJetPtFake", "Inclusive jet pt fake tracks", 3, {
binCent, binjetpt, binpthardbin},"s");
CreateTHnSparse( "hJetPtMiss", "Inclusive jet pt missing tracks", 3, {
binCent, binjetpt, binpthardbin},"s");
PostData(1, fHistos->GetListOfHistograms());
//===============================
// For Sure
//===============================
//std::cout<< "DEBUG4 IsAA?"<< (fIsAA?"AA":"pp")<<std::endl;
//std::cout<<"NBins of Cent : "<<binCent.GetNbins()<<"\t"<<binCent.GetXmin()<<"\t"<<binCent.GetXmax()<<endl;
if( fNDiJetSelection != kBDiJetSelEnd-1 ){
cout<<"fNDiJetSelection("<<fNDiJetSelection
<<") is not match with kBDiJetSelEnd("<<kBDiJetSelEnd<<")"<<endl;
gSystem->Exit(1);
}
for (auto i=0u; i<kBDiJetSelEnd; i++) {
fDijetSelectionCut.push_back(false);
fDijetPtPair.push_back(0.);
fDijetInvM.push_back(0.);
}
fUtils = new AliAnalysisUtils();
fUtils -> SetMaxVtxZ(10);
}
//________________________________________________________________________
Bool_t AliBSDiJetTask::Run(){
using TMath::Abs;
fCent = -1;
//Cent = InputEvent()->GetCentrality();
sel = (AliMultSelection*) InputEvent() -> FindListObject("MultSelection");
if (sel) {
if (fOption.Contains("13f")) fCent = sel -> GetMultiplicityPercentile("V0C");
else if (
fOption.Contains("13b") ||
fOption.Contains("13c") ||
fOption.Contains("13d") ||
fOption.Contains("13e")
) fCent = sel -> GetMultiplicityPercentile("V0A");
else fCent = sel -> GetMultiplicityPercentile("V0M");
}
//pt hard bin scaling-----------------------------------------------------------
//https://twiki.cern.ch/twiki/bin/viewauth/ALICE/JetMCProductionsCrossSections
sf = 1.;
if (fIsMC) this->MeasurePtHardBinScalingFactor();
//cout<<"Scaling factor = "<<sf<<endl;
fHistos->FillTH1("hEventNumbers","All",1);
AliVEvent *event = InputEvent();
event->IsA()==AliESDEvent::Class()
? fEvt = dynamic_cast<AliESDEvent*>(event)
: fEvt = dynamic_cast<AliAODEvent*>(event);
if (!fEvt) return false;
if (!fIsMC && fUtils->IsPileUpSPD(InputEvent())) {
PostData(1, fHistos->GetListOfHistograms());
return false;
}
fHistos->FillTH1("hEventNumbers","PassPileUp",1);
// Fill z_vertex and cut z_vertex range
IsGoodVertex = false;
IsGenGoodVtx = false;
if (fOption.Contains("Emb") || fOption.Contains("MC")){
fHistos -> FillTH1 ("zvtx",genzvtx);
//cout<<"bkkim genzvtx : "<<genzvtx<<endl;
if (abs(genzvtx)<=10) {
IsGenGoodVtx = true;
}
}
const AliVVertex* vtx = InputEvent()->GetPrimaryVertex();
if (fUtils->IsVertexSelected2013pA(InputEvent())){
//if (vtx-> GetNContributors()>1){
double zvtx = vtx->GetZ();
vtx ->GetXYZ(vertex);
fHistos -> FillTH1 ("zvtx",zvtx);
if (abs(zvtx)<=10) IsGoodVertex = true;
//if (IsGoodVertex) cout<<"bkkim zvtx : "<<zvtx<<endl;
}
if (IsGoodVertex) {
fHistos->FillTH1("hEventNumbers","PassPileUpGoodz",1);
fHistos->FillTH1("hEventNumbers","GoodzNTrials",NTrials);
fHistos->FillTH1("hEventNumbers","GoodzNX",XSection);
fHistos->FillTH1("hEventNumbers","NXoNTrials",XSection/NTrials);
fHistos -> FillTH1 ("nCentrality",fCent);
fHistos -> FillTH1("hPtHardBin",pthardbin);
}
AliAnalysisManager *man = AliAnalysisManager::GetAnalysisManager();
//===============================
// RESUM JETS
//===============================
auto jetContainer = GetJetContainer(0);
//cout<<"First jet Container name : "<<jetContainer -> GetName()<<endl;
auto trkContainer = GetParticleContainer(0); //trk container recall for QA purpose
//cout<<"trkContainer name "<<trkContainer->GetName()<<endl;
AliClusterContainer* cluContainer = nullptr;
if (fName.Contains("FullJet")) cluContainer = GetClusterContainer(0);
auto ktContainer = GetJetContainer(1);
//cout<<"Second jet Container name : "<<ktContainer -> GetName()<<endl;
AliJetContainer *mcContainer = nullptr;
if (fOption.Contains("Emb") || fOption.Contains("MC")){
mcContainer = GetJetContainer(2);
//cout<<"MC jet Container name : "<<mcContainer -> GetName()<<endl;
}
// =============================
// QA plots
// ============================
for (auto trk : trkContainer->all()){
fHistos->FillTH2("trketaphi",trk->Eta(),trk->Phi());
//cout<<"trk -> Eta : "<<trk->Eta()<<endl;
//cout<<"trk -> Label : "<<trk->GetLabel()<<endl;
}
//cout<<((AliAODEvent*)AliAnalysisTaskEmcalEmbeddingHelper::GetInstance()->GetExternalEvent())->GetCentrality()->GetCentralityPercentile("V0M")<<endl;
//for(int i=0; i<10; i++) cout<<"pt hard bin : "<<AliAnalysisTaskEmcalEmbeddingHelper::GetInstance()->GetInputFilename()<<endl;
//for(int i=0; i<10; i++) cout<<"pt hard bin : "<<AliAnalysisTaskEmcalEmbeddingHelper::GetInstance()-> GetStartingFileIndex()<<endl;
//for(int i=0; i<10; i++) cout<<"pt hard bin : "<<((AliAODEvent*)AliAnalysisTaskEmcalEmbeddingHelper::GetInstance()->GetExternalEvent()) -> GetTree() -> GetCurrentFile() <<endl;
// Underlying background calculation
// this will be done by four-momentum sum of constituents
this -> MeasureBgDensity(ktContainer);
TLorentzVector1D RecJets;
Bool_t gooddijet = this -> MeasureJets(jetContainer, RecJets, false);
std::sort(RecJets.begin(), RecJets.end(), [&](const TLorentzVector& x, const TLorentzVector& y) { return x.Pt() > y.Pt() ;});
if (!gooddijet) return false;
TLorentzVector1D TrueJets;
Bool_t gooddijetkine = false;
if (fOption.Contains("Emb") || fOption.Contains("MC")){
gooddijetkine = this -> MeasureJets(mcContainer, TrueJets, true);
for (auto j : TrueJets){
}
if (!gooddijetkine) return false;
std::sort(TrueJets.begin(), TrueJets.end(), [&](const TLorentzVector& x, const TLorentzVector& y) { return x.Pt() > y.Pt(); });
}
TLorentzVector1D matchedjets;
if ((fOption.Contains("Emb") || fOption.Contains("MC")) && IsGenGoodVtx){ // Inclusive jet pt response matrix
TLorentzVector1D pjets = TrueJets;
TLorentzVector1D rjets = RecJets;
for(auto pj : pjets){
FillTHnSparse("hJetPtTruth",{fCent,pj.Pt(),pthardbin},sf);
}
if (IsGoodVertex){
for(auto rj : rjets){
FillTHnSparse("hJetPt",{fCent,rj.Pt(),pthardbin},sf);
}
for (auto pj : pjets){
double maxjpt = 0;
TLorentzVector maxjet(0,0,0,0);
for (auto rj : rjets){
if (rj.Pt()>pj.Pt()*0.3 && rj.DeltaR(pj)<0.4 && maxjet.Pt()<rj.Pt()) {
maxjet = rj;
}
}
if (maxjet.Pt()>0) {
matchedjets.push_back(maxjet);
rjets.erase(std::remove_if(rjets.begin(), rjets.end(),
[&](const TLorentzVector& x) { return x.Pt() == maxjet.Pt() ; }), rjets.end());
FillTHnSparse("hJetPtRes",{fCent,maxjet.Pt(),pj.Pt(),pthardbin},sf);
}
if (maxjet.Pt()==0) FillTHnSparse("hJetPtMiss",{fCent,pj.Pt(),pthardbin},sf);
}
for (auto rj : rjets){
FillTHnSparse("hJetPtFake",{fCent,rj.Pt(),pthardbin},sf);
}
RecJets = matchedjets;
//cout<<"matchedjets"<<endl;
for (auto mj : RecJets){
FillTHnSparse("hJetPtMatched",{fCent,mj.Pt(),pthardbin},sf);
}
}
} else if (IsGoodVertex) {
TLorentzVector1D rjets = RecJets;
for(auto rj : rjets){
FillTHnSparse("hJetPt",{fCent,rj.Pt(),pthardbin},sf);
}
}
TLorentzVector2D sj( fNDiJetSelection+1, TLorentzVector1D(2));
Bool1D recdisel(fNDiJetSelection +1, false);
this->CheckDijetSelections(RecJets,sj, recdisel);
TLorentzVector2D sjkine( fNDiJetSelection+1, TLorentzVector1D(2));
Bool1D truedisel(fNDiJetSelection +1, false);
if (fOption.Contains("Emb") || fOption.Contains("MC")) {
this->CheckDijetSelections(TrueJets,sjkine, truedisel);
}
//cout <<"sj size : "<<sj.size()<<endl;
//===============================
// ptPair : leading - subleading
//===============================
for( int ids=kBDiJetSelBegin;ids<kBDiJetSelEnd;ids++ ){ // NOTE : begin with 1
auto j = sj[ids];
//=== SKIP Empty DiJet
if( j[0].E() < 1e-4 || j[1].E() < 1e-4 ) {
//fDijetSelectionCut[ids] = false;
if (fOption.Contains("Emb") || fOption.Contains("MC")){
auto truej = sjkine[ids];
auto dijet = truej[0] + truej[1];
auto invM = dijet.M();
auto ptpair = dijet.Pt();
Bool_t truthdijetcut = truedisel.at(ids);
if (IsGenGoodVtx && truthdijetcut ) {
FillTHnSparse( "hDiJetInvMPtPairMiss", {(double)ids,fCent,truej[0].Pt(),invM,ptpair,pthardbin},sf);
}
}
}
if (!recdisel[ids]) continue;
Double_t nphi=0;
auto diJetSel = Double_t( ids );
auto dijet = j[0] + j[1];
auto invM = dijet.M();
auto dPhi = j[0].DeltaPhi(j[1]);
auto dPhiA = Abs(dPhi);
auto dPhi_0_2pi = TVector2::Phi_0_2pi(dPhi);
auto tpt = j[0].Pt();
auto apt = j[1].Pt();
auto ptpair = dijet.Pt();
auto testdphi = nphi-j[0].Phi();
auto ptAsim = (tpt-apt)/(tpt+apt);
auto eAsim = (j[0].E()-j[1].E())/(j[0].E()+j[1].E());
auto kty = j[0].Pt() * TMath::Sin(dPhi_0_2pi);
if (ids>=kM1) ptpair = kty;
double tratio = 1.;
double tratioh = 1.;
double tratiol = 1.;
if (fOption.Contains("Emb") || fOption.Contains("MC")){
auto truej = sjkine[ids];
auto truedijet = truej[0] + truej[1];
Double_t truthptpair = truedijet.Pt();
Double_t truthinvM = truedijet.M();
Bool_t truthdijetcut = truedisel.at(ids);
auto dPhi_0_2piTruth = TVector2::Phi_0_2pi(truej[0].DeltaPhi(truej[1]));
if ( IsGenGoodVtx) {
if (IsGoodVertex){
if (truthdijetcut){
FillTHnSparse( "hDiJetInvMPtPairRes", { diJetSel,fCent,tpt,invM,truthinvM,ptpair,truthptpair, pthardbin},sf);
} else {
FillTHnSparse( "hDiJetInvMPtPairFake", {diJetSel,fCent,tpt,invM,ptpair, pthardbin},sf);
FillTHnSparse( "hDiJetInvMPtPairMiss", {diJetSel,fCent,tpt,truthinvM,truthptpair, pthardbin},sf);
}
} else FillTHnSparse( "hDiJetInvMPtPairMiss", {diJetSel,fCent,tpt,truthinvM,truthptpair,pthardbin},sf);
}
if (truthdijetcut) {
FillTHnSparse( "hDiJetInvMPtPairTruth", { diJetSel, fCent, tpt, truthinvM, truthptpair,pthardbin },sf);
FillTHnSparse( "hDiJetDPhi_0_2piTruth", { diJetSel, fCent, tpt, truthinvM, dPhi_0_2piTruth, pthardbin },sf);
}
}
if (IsGoodVertex){
FillTHnSparse( "hJetPtLeading", { diJetSel, fCent, tpt, pthardbin},sf*tratio );
FillTHnSparse( "hDiJetDPhi_0_2pi", { diJetSel, fCent, tpt, invM, dPhi_0_2pi, pthardbin },sf);
FillTHnSparse( "hDiJetInvMPtPair", { diJetSel, fCent, tpt, invM, ptpair, pthardbin },sf);
}
}
PostData(1, fHistos->GetListOfHistograms());;
//PostData(1, fOutput);
//cout<<"\n\n\n"<<endl;
return kTRUE;
}
void AliBSDiJetTask::FinishTaskOutput()
{
}
//___________________________________________________________________
void AliBSDiJetTask::MeasureBgDensity(AliJetContainer* ktContainer){
using TMath::Abs;
RHO=0;
RHOM=0;
int n = 0;
TLorentzVector1D rhoarray;
Double1D Sumpt;
Double1D Summ;
TLorentzVector leadingkt;
Bool_t isfirstdijet = true;
for( auto j : ktContainer->accepted() ){
if (Abs(j->Eta())>0.7) continue;
double lpt = 0;
double sumpt = 0;
double summ = 0;
TLorentzVector sumkt (0,0,0,0);
for( int it=0; it<j->GetNumberOfTracks(); it++ ) {
auto trk = j->Track(it);
if( ! ((AliAODTrack*) trk)->TestFilterBit(768)) continue;
TLorentzVector temp;
temp.SetXYZM(trk->Px(),trk->Py(),trk->Pz(),pionmass);
if( lpt < temp.Pt() ) lpt = temp.Pt();
sumkt += temp;
sumpt += temp.Pt();
summ += (sqrt(pionmass*pionmass+temp.Pt()*temp.Pt())-temp.Pt());
}
sumpt /= j->Area();
summ /= j->Area();
if (n==0) { //remove leading kt jet
leadingkt = sumkt;
n++;
continue;
}
//remove back-subleading kt jet
else if (Abs(sumkt.DeltaPhi(leadingkt))>pi/2. && isfirstdijet){
n++;
isfirstdijet = false;
continue;
}
Sumpt.push_back(sumpt);
Summ.push_back(summ);
n++;
}
Double_t rhopt[Sumpt.size()];
Double_t rhom[Summ.size()];
int i=0;
for (auto k : Sumpt){
rhopt[i] = k;
i++;
}
i=0;
for (auto k : Summ){
rhom[i] = k;
i++;
}
RHO = TMath::Median(Sumpt.size(),rhopt);
RHOM = TMath::Median(Summ.size(),rhom);
FillTHnSparse("hRho",{fCent,RHO, pthardbin},sf);
}
void AliBSDiJetTask::MeasurePtHardBinScalingFactor(){
NTrials = -1;
XSection =-1;
genzvtx = -30;
auto bin16j5 = AxisVar( "bin16j5", {5,7,9,12,16,21,28,36,45,57,70,85,99,115,132,150,169,190,212,235,10000});
if(fIsMC){
if (fOption.Contains("AOD")){
AliVEvent *event = InputEvent();
if (fOption.Contains("Emb")) event = AliAnalysisTaskEmcalEmbeddingHelper::GetInstance()->GetExternalEvent();
if (!event) {
Printf("ERROR: Could not retrieve event");
sf = 0;
}
AliAODMCHeader *cHeaderAOD = dynamic_cast<AliAODMCHeader*>
(event->FindListObject(AliAODMCHeader::StdBranchName()));
genzvtx = cHeaderAOD -> GetVtxZ();
fHistos->FillTH1("mczvtx",genzvtx);
TList *genHeaders = cHeaderAOD->GetCocktailHeaders();
NTrials = -1;
XSection =-1;
AliGenEventHeader* gh = 0;
for(Int_t i = 0; i<genHeaders->GetEntries();i++){
gh = (AliGenEventHeader*)genHeaders->At(i);
TString GeneratorName = gh->GetName();
if (GeneratorName.CompareTo("Pythia") == 0){
AliGenPythiaEventHeader* gPythia = dynamic_cast<AliGenPythiaEventHeader*>(gh);
NTrials = gPythia->Trials();
XSection = gPythia->GetXsection();
pthardbin = double(bin16j5.FindBin(gPythia->GetPtHard())) -0.5;
}
}
sf = XSection/NTrials;
cout<<"XSection : "<<XSection<<endl;
cout<<"NTrials : "<<NTrials<<endl;
fMCArray = (TClonesArray*) event->FindListObject("mcparticles");
const Int_t nTracksMC = fMCArray->GetEntriesFast();
for (Int_t iTracks = 0; iTracks < nTracksMC; iTracks++) {
AliAODMCParticle* trackMC = dynamic_cast<AliAODMCParticle*>(fMCArray->At(iTracks));
Int_t pdgCode = trackMC->PdgCode();
if (iTracks == 4) p6.SetXYZT(trackMC->Px(), trackMC->Py(), trackMC->Pz(), trackMC->E());
if (iTracks == 5) p7.SetXYZT(trackMC->Px(), trackMC->Py(), trackMC->Pz(), trackMC->E());
}
}
else {
AliMCEvent *mcEvent = MCEvent();
AliStack *stack = mcEvent->Stack();
AliGenPythiaEventHeader* gPythia =
dynamic_cast<AliGenPythiaEventHeader*>(mcEvent->GenEventHeader());
NTrials = gPythia->Trials();
XSection = gPythia->GetXsection();
sf = XSection/NTrials;
Int_t nPrim = stack->GetNprimary();
for (Int_t i = 0; i < nPrim; i++){
TParticle* p = stack->Particle(i);
if (!p) continue;
}
}
}
//The method above doesn't work for MC 13b4_fix and plus AOD files
//For these MC productions, the method below is used..
if ( fOption.Contains("13plus")
|| fOption.Contains("12a15e")
|| fOption.Contains("12a15f")
|| fOption.Contains("13e4")
|| fOption.Contains("13fix") ){
TTree *tree = AliAnalysisManager::GetAnalysisManager()->GetTree();
if(!tree) sf = 0;;
TFile *curfile = tree->GetCurrentFile();
if(!curfile) sf = 0;
TString fCurrFileName = TString(curfile->GetName());
if (!filename.EqualTo(fCurrFileName)) {
filename = fCurrFileName.Data();
fCurrFileName.ReplaceAll(gSystem->BaseName(fCurrFileName.Data()),"");
TFile *fxsec = TFile::Open(Form("%s%s",fCurrFileName.Data()
,"pyxsec_hists.root"));
TKey* key = (TKey*)fxsec->GetListOfKeys()->At(0);
TList *list = dynamic_cast<TList*>(key->ReadObj());
XSection = ((TProfile*)list->FindObject("h1Xsec"))->GetBinContent(1);
NTrials = ((TH1F * ) list->FindObject("h1Trials"))->GetBinContent(1);
Int_t entries = ((TH1F * ) list->FindObject("h1Trials"))->GetEntries();
NTrials /= entries;
pyxsechistsf = XSection/NTrials;
fxsec->Close();
}
sf = pyxsechistsf;
}
}
Bool_t AliBSDiJetTask::MeasureJets(AliJetContainer *jetContainer, TLorentzVector1D &Jets, Bool_t istruth){
using TMath::Abs;
//=== NOTE : We will not use sj[0] because bin in THnSparse is always begin with 1.
int ij=0;
for( auto j : jetContainer->accepted() ){
fHistos->FillTH2("jetetaphi",j->Eta(),j->Phi(),sf);
TLorentzVector sum (0,0,0,0);
double sumpt=0;
double lpt = 0;
for( int it=0; it<j->GetNumberOfTracks(); it++ ) {
auto trk = j->Track(it);
if( ! ((AliAODTrack*) trk)->TestFilterBit(768)) continue;
if (!istruth && fOption.Contains("MBTR")){
if (fBSRandom->Uniform(0,100)<5.) continue;
}
TLorentzVector temp;
temp.SetXYZM(trk->Px(),trk->Py(),trk->Pz(),pionmass);
sum+=temp;
sumpt+=trk->Pt();
if( lpt < temp.Pt() ) lpt = temp.Pt();
}
if (fOption.Contains("FullJet")){
for( int it=0; it<j->GetNumberOfClusters(); it++ ) {
auto clu = j->Cluster(it);
TLorentzVector temp;
clu->GetMomentum(temp,vertex);
sum+=temp;
sumpt+=temp.Pt();
if( lpt < temp.Pt() ) lpt = temp.Pt();
}
}
TLorentzVector avec(0,0,0,0);
avec.SetPtEtaPhiE(j->AreaPt(),j->AreaEta(),j->AreaPhi(),j->AreaE());
TLorentzVector sumcorr(
sum.Px()-RHO*avec.Px()
, sum.Py()-RHO*avec.Py()
, sum.Pz()-(RHO+RHOM)*avec.Pz()
, sum.E() -(RHO+RHOM)*avec.E()
);
//MC Pythia jet / pT-hard > 4 cut
if( lpt < fLeadingParticlePtMin ) continue;
if (istruth){
if (abs(sum.Eta())<0.5) Jets.push_back(sum);
} else {
if (abs(sumcorr.Eta())<0.5) Jets.push_back(sumcorr);
}
ij++;
}
return true;
}
void AliBSDiJetTask::CheckDijetSelections(TLorentzVector1D Jets, TLorentzVector2D& sj, Bool1D &disel){
using TMath::Abs;
//=== DiJetSelection 1 : LS = Leading-SubLeading
TLorentzVector1D zsj(2,TLorentzVector(0,0,0,0));
sj[0] = zsj;
for (auto j : Jets){
if (sj[0][0].Pt() < j.Pt()) {
sj[0][0]=j;
}
else if( sj[0][1].Pt() < j.Pt()){
sj[0][1]=j;
}
}
//0 lorentz vector
disel[kNoCut] = true;
sj[kNoCut] = sj[0];
Double_t kinecut = 20;
//DiJetSelection 1 : TpTJET>20, ApTJET>20, pT_pair
if (sj[0][0].Pt()>kinecut && sj[0][1].Pt()>kinecut) {
sj[kB1] =sj[0];
disel[kB1] = true;
}
//DiJetSelection 2 : TpTJET>20, ApTJET>20, pT_pair
//Leading-Subreading & dPhi>pi/2
if(sj[0][0].Pt()>kinecut && sj[0][1].Pt()>kinecut &&
Abs(sj[0][0].DeltaPhi(sj[0][1])) > pi/2. ){
sj[kB2] = sj[0]; disel[kB2] = true;
}
//DiJetSelection 3 : TpTJET>20, ApTJET>20, pT_pair
//Leading - Subleading in opposite hemisphere
if(sj[0][0].Pt()>kinecut ){
auto tj = sj[kB3][0] = sj[0][0]; // Leading is same as 1:LS
sj[kB3][1] = TLorentzVector(0,0,0,0);
for( auto jet: Jets ){
if( Abs(tj.DeltaPhi( jet )) < pi/2. ) continue;
if( sj[kB3][1].Pt() < jet.Pt() ) sj[kB3][1] = jet;
}
if (sj[kB3][1].Pt() >kinecut) disel[kB3] = true;
}
if (sj[0][0].Pt()>30 && sj[0][1].Pt()>30) {
sj[kC1] =sj[0];
disel[kC1] = true;
}
//DiJetSelection 2 : TpTJET>20, ApTJET>20, pT_pair
//Leading-Subreading & dPhi>pi/2
if(sj[0][0].Pt()>30 && sj[0][1].Pt()>30 &&
Abs(sj[0][0].DeltaPhi(sj[0][1])) > pi/2. ){
sj[kC2] = sj[0]; disel[kC2] = true;
}
//DiJetSelection 3 : TpTJET>20, ApTJET>20, pT_pair
//Leading - Subleading in opposite hemisphere
if(sj[0][0].Pt()>30 ){
auto tj = sj[kC3][0] = sj[0][0]; // Leading is same as 1:LS
sj[kC3][1] = TLorentzVector(0,0,0,0);
for( auto jet: Jets ){
if( Abs(tj.DeltaPhi( jet )) < pi/2. ) continue;
if( sj[kC3][1].Pt() < jet.Pt() ) sj[kC3][1] = jet;
}
if (sj[kC3][1].Pt() >30) disel[kC3] = true;
}
if (sj[0][0].Pt()>40 && sj[0][1].Pt()>40) {
sj[kD1] =sj[0];
disel[kD1] = true;
}
//DiJetSelection 2 : TpTJET>20, ApTJET>20, pT_pair
//Leading-Subreading & dPhi>pi/2
if(sj[0][0].Pt()>40 && sj[0][1].Pt()>40 &&
Abs(sj[0][0].DeltaPhi(sj[0][1])) > pi/2. ){
sj[kD2] = sj[0]; disel[kD2] = true;
}
//DiJetSelection 3 : TpTJET>20, ApTJET>20, pT_pair
//Leading - Subleading in opposite hemisphere
if(sj[0][0].Pt()>30 ){
auto tj = sj[kD3][0] = sj[0][0]; // Leading is same as 1:LS
sj[kD3][1] = TLorentzVector(0,0,0,0);
for( auto jet: Jets ){
if( Abs(tj.DeltaPhi( jet )) < pi/2. ) continue;
if( sj[kD3][1].Pt() < jet.Pt() ) sj[kD3][1] = jet;
}
if (sj[kD3][1].Pt() >30) disel[kD3] = true;
}
//DiJetSelection 4 : 20<TpTJET<40, 20<ApTJET, kTy
if (sj[0][0].Pt()>20 && sj[0][0].Pt()<40){
auto tj = sj[kM1][0] = sj[0][0]; // Leading is same as 1:LS
sj[kM1][1] = TLorentzVector(0,0,0,0);
for( auto jet: Jets ){
if( Abs(TVector2::Phi_0_2pi(tj.DeltaPhi(jet))-pi) > pi/3.) continue;
if( sj[kM1][1].Pt() < jet.Pt() ) sj[kM1][1] = jet;
}
if (sj[kM1][1].Pt() >20) disel[kM1] = true;
} else sj[kM1] = zsj;
//DiJetSelection 5 : 40<TpTJET<60, 20<ApTJET, kTy
if (sj[0][0].Pt()>40 && sj[0][0].Pt()<60){
auto tj = sj[kM2][0] = sj[0][0]; // Leading is same as 1:LS
sj[kM2][1] = TLorentzVector(0,0,0,0);
for( auto jet: Jets ){
if( Abs(TVector2::Phi_0_2pi(tj.DeltaPhi(jet))-pi) > pi/3.) continue;
if( sj[kM2][1].Pt() < jet.Pt() ) sj[kM2][1] = jet;
}
if (sj[kM2][1].Pt() >20) disel[kM2] = true;
} else sj[kM2] = zsj;
//DiJetSelection 6 : 60<TpTJET<80, 20<ApTJET, kTy
if (sj[0][0].Pt()>60 && sj[0][0].Pt()<80){
auto tj = sj[kM3][0] = sj[0][0]; // Leading is same as 1:LS
sj[kM3][1] = TLorentzVector(0,0,0,0);
for( auto jet: Jets ){
if( Abs(TVector2::Phi_0_2pi(tj.DeltaPhi(jet))-pi) > pi/3.) continue;
if( sj[kM3][1].Pt() < jet.Pt() ) sj[kM3][1] = jet;
}
if (sj[kM3][1].Pt() >20) disel[kM3] = true;
} else sj[kM3] = zsj;
//DiJetSelection 7 : 80<TpTJET<110, 20<ApTJET, kTy
if (sj[0][0].Pt()>80 && sj[0][0].Pt()<110){
auto tj = sj[kM4][0] = sj[0][0]; // Leading is same as 1:LS
sj[kM4][1] = TLorentzVector(0,0,0,0);
for( auto jet: Jets ){
if( Abs(TVector2::Phi_0_2pi(tj.DeltaPhi(jet))-pi) > pi/3.) continue;
if( sj[kM4][1].Pt() < jet.Pt() ) sj[kM4][1] = jet;
}
if (sj[kM4][1].Pt() >20) disel[kM4] = true;
} else sj[kM4] = zsj;
//DiJetSelection 8 : 70<TpTJET<110, 20<ApTJET<30, kTy
if (sj[0][0].Pt()>70 && sj[0][0].Pt()<110){
auto tj = sj[kM5][0] = sj[0][0]; // Leading is same as 1:LS
sj[kM5][1] = TLorentzVector(0,0,0,0);
for( auto jet: Jets ){
if( Abs(TVector2::Phi_0_2pi(tj.DeltaPhi(jet))-pi) > pi/3.) continue;
if( sj[kM5][1].Pt() < jet.Pt() ) sj[kM5][1] = jet;
}
if (sj[kM5][1].Pt() >20 && sj[kM5][1].Pt() < 30) disel[kM5] = true;
} else sj[kM5] = zsj;
//DiJetSelection 9 : 70<TpTJET<110, 30<ApTJET<40, kTy
if (sj[0][0].Pt()>70 && sj[0][0].Pt()<110){
auto tj = sj[kM6][0] = sj[0][0]; // Leading is same as 1:LS
sj[kM6][1] = TLorentzVector(0,0,0,0);
for( auto jet: Jets ){
if( Abs(TVector2::Phi_0_2pi(tj.DeltaPhi(jet))-pi) > pi/3.) continue;
if( sj[kM6][1].Pt() < jet.Pt() ) sj[kM6][1] = jet;
}
if (sj[kM6][1].Pt() >30 && sj[kM6][1].Pt() < 40) disel[kM6] = true;
} else sj[kM6] = zsj;
//DiJetSelection 10 : 70<TpTJET<110, 40<ApTJET, kTy
if (sj[0][0].Pt()>70 && sj[0][0].Pt()<110){
auto tj = sj[kM7][0] = sj[0][0]; // Leading is same as 1:LS
sj[kM7][1] = TLorentzVector(0,0,0,0);
for( auto jet: Jets ){
if( Abs(TVector2::Phi_0_2pi(tj.DeltaPhi(jet))-pi) > pi/3.) continue;
if( sj[kM7][1].Pt() < jet.Pt() ) sj[kM7][1] = jet;
}
if (sj[kM7][1].Pt() >40) disel[kM7] = true;
} else sj[kM7] = zsj;
}
THnSparse * AliBSDiJetTask::CreateTHnSparse(TString name, TString title, Int_t ndim, std::vector<TAxis> bins, Option_t * opt){
const TAxis * axises[bins.size()];
for( UInt_t i=0;i<bins.size();i++ ) axises[i]= &bins[i];
THnSparse * h= fHistos->CreateTHnSparse(name, title, ndim, axises,opt );
return h;
}
THnSparse * AliBSDiJetTask::CreateTHnSparse(TString name, TString title, TString templ, Option_t * opt){
auto o = fHistos->FindObject(templ);
if( !o ) {
cout<<"ERROR: no "<<templ<<endl;
gSystem->Exit(1);
}
auto ht = dynamic_cast<THnSparse*>( o );
const TAxis * axises[ht->GetNdimensions()];
for( int i=0;i<ht->GetNdimensions();i++ ) axises[i]= ht->GetAxis(i);
auto h= fHistos->CreateTHnSparse(name, title, ht->GetNdimensions(), axises,opt );
return h;
}
Long64_t AliBSDiJetTask::FillTHnSparse( TString name, std::vector<Double_t> x, Double_t w ){
auto hsparse = dynamic_cast<THnSparse*>( fHistos->FindObject(name) );
if(! hsparse ){
cout<<"ERROR : no "<<name<<endl;
exit(1);
}
return FillTHnSparse( hsparse, x, w );
}
/*
Long64_t AliBSDiJetTask::Fill( TString name, std::vector<Double_t> x, Double_t w ){
return FillTHnSparse( name, x, w );
}
*/
Long64_t AliBSDiJetTask::FillTHnSparse( THnSparse *h, std::vector<Double_t> x, Double_t w ){
if( int(x.size()) != h->GetNdimensions() ){
cout<<"ERROR : wrong sized of array while Fill "<<h->GetName()<<endl;
exit(1);
}
return h->Fill( &x.front(), w );
}
TAxis AliBSDiJetTask::AxisFix( TString name, int nbin, Double_t xmin, Double_t xmax ){
TAxis axis(nbin, xmin, xmax);axis.SetName(name);
return axis;
}
TAxis AliBSDiJetTask::AxisStr( TString name, std::vector<TString> bin ){
TAxis ax = AxisFix( name, bin.size(), 0.5, bin.size()+0.5);
UInt_t i=1;
for( auto blabel : bin )
ax.SetBinLabel( i++, blabel );
return ax;
}
TAxis AliBSDiJetTask::AxisVar( TString name, std::vector<Double_t> bin ){
TAxis axis( bin.size()-1, &bin.front() ) ;axis.SetName(name);
return axis;
}
TAxis AliBSDiJetTask::AxisLog( TString name, int nbin, Double_t xmin, Double_t xmax, Double_t xmin0){
int binoffset = ( xmin0<0 || (xmin-xmin0)<1e-9) ? 0 : 1;
std::vector<Double_t> bin(nbin+1+binoffset,0);
double logBW3 = (log(xmax)-log(xmin))/nbin;
for(int ij=0;ij<=nbin;ij++) bin[ij+binoffset]=xmin*exp(ij*logBW3);
TAxis axis( nbin, &bin.front() ) ;
axis.SetName(name);
return axis;
}
| 35.137461 | 195 | 0.626142 | [
"vector"
] |
03fbda6e266e0acb9e3760ab22d993ad03fc42eb | 2,742 | cpp | C++ | 072.cpp | zawa-tin/practice90 | cbd3378920958727df6ccbf4f1b5f116f0e2ad24 | [
"MIT"
] | null | null | null | 072.cpp | zawa-tin/practice90 | cbd3378920958727df6ccbf4f1b5f116f0e2ad24 | [
"MIT"
] | null | null | null | 072.cpp | zawa-tin/practice90 | cbd3378920958727df6ccbf4f1b5f116f0e2ad24 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
// clang-format off
using namespace std;
#define all(a) a.begin(), a.end()
#define over_load_(_1, _2, _3, _4, NAME, ...) NAME
#define rep(...) over_load_(__VA_ARGS__, rep4, rep3, rep2)(__VA_ARGS__)
#define rep2(i, r) for (int i = 0; i < static_cast<int>(r); (i) += 1)
#define rep3(i, l, r) for (int i = static_cast<int>(l); i < static_cast<int>(r); (i) += 1)
#define rep4(i, l, r, stride) for (int i = static_cast<int>(l); i < static_cast<int>(r); (i) += (stride))
#define rrep(...) over_load_(__VA_ARGS__, rrep4, rrep3, rrep2)(__VA_ARGS__)
#define rrep2(i, r) for (int i = static_cast<int>(r) - 1; i >= 0; (i) -= 1)
#define rrep3(i, l, r) for (int i = static_cast<int>(r) - 1; i >= static_cast<int>(l); (i) -= 1)
#define rrep4(i, l, r, stride) for (int i = static_cast<int>(r) - 1; i >= static_cast<int>(l); (i) -= (stride))
#define fore(i, a) for (auto &i : a)
template <typename T1, typename T2>
inline bool chmax(T1 &a, T2 b)
{
return a < b && (a = b, true);
}
template <typename T1, typename T2>
inline bool chmin(T1 &a, T2 b)
{
return a > b and (a = b, true);
}
constexpr char newl = '\n';
long long pow2(int x) {return x * x;}
bool isupper(char c) {return ('A' <= c and c <= 'Z');}
bool islower(char c) {return ('a' <= c and c <= 'z');}
bool isnumber(char c) {return ('0' <= c and c <= '9');}
// O(logX)
int getdigit(long long x) {
int res = 0;
while(x > 0) {
res++;
x /= 10;
}
return res;
}
using ll = long long;
using vi = vector<int>;
using vll = vector<ll>;
using vvi = vector<vi>;
using vvll = vector<vll>;
using vp = vector<pair<int, int>>;
using vs = vector<string>;
const ll sup = LONG_LONG_MAX / 2 - 1;
const double pi = 3.141592653589793;
int h, w;
vs grid;
vvi G;
vvi dp;
int f(int y, int x) {
return y * w + x;
}
void make() {
vi d = {-1, 1};
rep(y, h) rep(x, w) {
if (grid[y][x] == '#') continue;
fore(dx, d) if (0 <= x + dx and x + dx < w) if (grid[y][x + dx] == '.') G[f(y, x)].push_back(f(y, x + dx));
fore(dy, d) if (0 <= y + dy and y + dy < h) if (grid[y + dy][x] == '.') G[f(y, x)].push_back(f(y + dy, x));
}
}
void rec(int now, int start, int st) {
if (st != 0 and now == start) return;
fore(x, G[now]) {
if ((st >> x) & 1) continue;
chmax(dp[start][st | (1 << x)], dp[start][st] + 1);
rec(x, start, st | (1 << x));
}
}
void solve() {
G = vvi(h*w);
make();
dp = vvi(h*w, vi(1 << (h*w), 0));
rep(i, h * w) rec(i, i, 0);
int ans = -1;
rep(i, h*w) rep(j, 1 << (h*w)) if ((j >> i) & 1) chmax(ans, dp[i][j]);
cout << (ans < 3 ? -1 : ans) << newl;
}
int main() {
cin >> h >> w;
grid = vs(h); fore(x, grid) cin >> x;
solve();
}
| 28.268041 | 115 | 0.530999 | [
"vector"
] |
03fe6490a5a2eb500a27848beefb4479231d8b61 | 4,645 | cc | C++ | src/default_lemma_job_generator.cc | benjaminkiesl/ut_tamarin | fc58f5e721b9c9577c475ba4768fdb13c81206d1 | [
"MIT"
] | 3 | 2020-09-04T14:02:52.000Z | 2021-08-28T16:44:09.000Z | src/default_lemma_job_generator.cc | benjaminkiesl/ut_tamarin | fc58f5e721b9c9577c475ba4768fdb13c81206d1 | [
"MIT"
] | 2 | 2021-08-25T10:38:58.000Z | 2021-10-07T10:18:02.000Z | src/default_lemma_job_generator.cc | benjaminkiesl/ut_tamarin | fc58f5e721b9c9577c475ba4768fdb13c81206d1 | [
"MIT"
] | null | null | null | // MIT License
//
// Copyright (c) 2020 Benjamin Kiesl
//
// 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 "default_lemma_job_generator.h"
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include "lemma_name_reader.h"
#include "utility.h"
using std::shared_ptr;
using std::string;
using std::vector;
namespace uttamarin {
DefaultLemmaJobGenerator::DefaultLemmaJobGenerator(
const string& spthy_file_path,
const string& starting_lemma,
shared_ptr<UtTamarinConfig> config) :
spthy_file_path_(spthy_file_path),
config_(config) {
}
vector<LemmaJob> DefaultLemmaJobGenerator::DoGenerateLemmaJobs() {
vector<LemmaJob> lemma_jobs;
for(auto lemma_name : GetNamesOfLemmasToVerify()) {
lemma_jobs.emplace_back(LemmaJob(spthy_file_path_, lemma_name));
}
return lemma_jobs;
}
vector<string> DefaultLemmaJobGenerator::GetNamesOfLemmasToVerify() {
auto lemmas = ReadLemmaNamesFromSpthyFile(spthy_file_path_);
if(!config_->GetLemmaAllowList().empty()) {
lemmas = GetLemmasInAllowList(lemmas, config_->GetLemmaAllowList());
}
if(!config_->GetLemmaDenyList().empty()) {
lemmas = RemoveLemmasInDenyList(lemmas, config_->GetLemmaDenyList());
}
if(starting_lemma_ != "") {
lemmas = RemoveLemmasBeforeStart(lemmas, starting_lemma_);
}
return lemmas;
}
vector<string> DefaultLemmaJobGenerator::GetLemmasInAllowList(
const vector<string>& all_lemmas,
const vector<string>& allow_list) {
for(auto lemma_name : allow_list) {
if(std::find(all_lemmas.begin(), all_lemmas.end(), lemma_name)
== all_lemmas.end()) {
std::cerr << "Warning: lemma '" << lemma_name << "' is not declared in "
<< "the Tamarin theory." << std::endl;
}
}
auto filtered_lemmas = all_lemmas;
filtered_lemmas.erase(
std::remove_if(filtered_lemmas.begin(), filtered_lemmas.end(),
[&allow_list](const string& lemma_name) {
return std::find(allow_list.begin(),
allow_list.end(), lemma_name)
== allow_list.end();
}), filtered_lemmas.end());
return filtered_lemmas;
}
vector<string> DefaultLemmaJobGenerator::RemoveLemmasInDenyList(
const vector<string>& all_lemmas,
const vector<string>& deny_list) {
auto filtered_lemmas = all_lemmas;
filtered_lemmas.erase(
std::remove_if(filtered_lemmas.begin(), filtered_lemmas.end(),
[&](const string& lemma_name) {
return std::find(deny_list.begin(),
deny_list.end(),
lemma_name) != deny_list.end();
}),
filtered_lemmas.end());
return filtered_lemmas;
}
vector<string> DefaultLemmaJobGenerator::RemoveLemmasBeforeStart(
const vector<string>& all_lemmas,
const string& starting_lemma) {
auto it_start = std::find(all_lemmas.begin(), all_lemmas.end(),
GetStringWithShortestEditDistance(all_lemmas,
starting_lemma));
vector<string> filtered_lemmas;
for(auto it = it_start;it != all_lemmas.end();++it) {
filtered_lemmas.emplace_back(*it);
}
return filtered_lemmas;
}
} // namespace uttamarin
| 38.38843 | 79 | 0.637675 | [
"vector"
] |
ff01449a5ec55672d519dfcf0d79d8e5ffe0b635 | 4,462 | cc | C++ | libs/quadwild/libs/CoMISo/NSolver/COMISOSolver.cc | Pentacode-IAFA/Quad-Remeshing | f8fd4c10abf1c54656b38a00b8a698b952a85fe2 | [
"Apache-2.0"
] | 29 | 2019-11-27T00:43:07.000Z | 2020-02-25T14:35:54.000Z | libs/quadwild/libs/CoMISo/NSolver/COMISOSolver.cc | Pentacode-IAFA/Quad-Remeshing | f8fd4c10abf1c54656b38a00b8a698b952a85fe2 | [
"Apache-2.0"
] | 1 | 2018-11-14T23:14:58.000Z | 2018-11-14T23:14:58.000Z | libs/quadwild/libs/CoMISo/NSolver/COMISOSolver.cc | Pentacode-IAFA/Quad-Remeshing | f8fd4c10abf1c54656b38a00b8a698b952a85fe2 | [
"Apache-2.0"
] | 4 | 2019-11-27T05:19:03.000Z | 2020-03-23T22:49:53.000Z | //=============================================================================
//
// CLASS COMISOSolver - IMPLEMENTATION
//
//=============================================================================
//== INCLUDES =================================================================
//== COMPILE-TIME PACKAGE REQUIREMENTS ========================================
#include <CoMISo/Config/config.hh>
//=============================================================================
#include <vector>
#include "COMISOSolver.hh"
//== NAMESPACES ===============================================================
namespace COMISO {
//== IMPLEMENTATION ==========================================================
// ********** SOLVE **************** //
void
COMISOSolver::
solve(NProblemInterface* _problem,
std::vector<NConstraintInterface*>& _constraints,
std::vector<PairUiV>& _discrete_constraints,
double _reg_factor,
bool _show_miso_settings,
bool _show_timings )
{
//----------------------------------------------
// 1. identify integer variables
//----------------------------------------------
// identify integer variables
std::vector<int> round_idxs;
for(unsigned int i=0; i<_discrete_constraints.size(); ++i)
switch(_discrete_constraints[i].second)
{
case Binary :
case Integer:
round_idxs.push_back(_discrete_constraints[i].first); break;
default : break;
}
//----------------------------------------------
// 2. setup constraints
//----------------------------------------------
int n = _problem->n_unknowns();
gmm::row_matrix< gmm::wsvector< double > > C(_constraints.size(), n+1);
int n_constraints = 0;
// get zero vector
std::vector<double> x(n, 0.0);
for(unsigned int i=0; i<_constraints.size(); ++i)
if(_constraints[i]->constraint_type() == NConstraintInterface::NC_EQUAL)
{
if(!_constraints[i]->is_linear())
std::cerr << "Warning: COMISOSolver received a problem with non-linear constraints!!!" << std::endl;
// get linear part
NConstraintInterface::SVectorNC gc;
_constraints[i]->eval_gradient(P(x), gc);
NConstraintInterface::SVectorNC::InnerIterator v_it(gc);
for(; v_it; ++v_it)
C(n_constraints, v_it.index()) = v_it.value();
// get constant part
C(n_constraints, n) = _constraints[i]->eval_constraint(P(x));
// move to next constraint
++n_constraints;
}
// resize matrix to final number of constraints
gmm::resize(C,n_constraints, n+1);
//----------------------------------------------
// 3. setup energy
//----------------------------------------------
if(!_problem->constant_hessian())
std::cerr << "Warning: COMISOSolver received a problem with non-constant hessian!!!" << std::endl;
// get hessian matrix
gmm::col_matrix< gmm::wsvector< double > > A(n,n);
NProblemInterface::SMatrixNP H;
_problem->eval_hessian(P(x), H);
for( int i=0; i<H.outerSize(); ++i)
for (NProblemInterface::SMatrixNP::InnerIterator it(H,i); it; ++it)
A(it.row(),it.col()) = it.value();
// get negative gradient
std::vector<double> rhs(_problem->n_unknowns());
_problem->eval_gradient(P(x), P(rhs));
for(unsigned int i=0; i<rhs.size(); ++i)
rhs[i] = -rhs[i];
// // add constant part
// objective += _problem->eval_f(P(x));
//----------------------------------------------
// 4. solve problem
//----------------------------------------------
cs_.solve(C,A,x,rhs,round_idxs,
_reg_factor, _show_miso_settings, _show_timings);
// void solve(
// RMatrixT& _constraints,
// CMatrixT& _A,
// VectorT& _x,
// VectorT& _rhs,
// VectorIT& _idx_to_round,
// double _reg_factor = 0.0,
// bool _show_miso_settings = true,
// bool _show_timings = true );
//----------------------------------------------
// 5. store result
//----------------------------------------------
_problem->store_result(P(x));
// std::cout << "COMISO Objective: " << model.get(GRB_DoubleAttr_ObjVal) << std::endl;
}
//=============================================================================
} // namespace COMISO
//=============================================================================
| 31.64539 | 108 | 0.452488 | [
"vector",
"model"
] |
ff0157b19b0ce5daa66f1d73b16b2e0950b44a9f | 1,618 | cpp | C++ | tooltip.cpp | darkoppressor/huberts-island-adventure-mouse-o-war | 9ff8d9e2c2b388bf762a0e463238794fb0233df8 | [
"MIT"
] | null | null | null | tooltip.cpp | darkoppressor/huberts-island-adventure-mouse-o-war | 9ff8d9e2c2b388bf762a0e463238794fb0233df8 | [
"MIT"
] | null | null | null | tooltip.cpp | darkoppressor/huberts-island-adventure-mouse-o-war | 9ff8d9e2c2b388bf762a0e463238794fb0233df8 | [
"MIT"
] | null | null | null | /* Copyright (c) 2012-2013 Cheese and Bacon Games, LLC */
/* See the file docs/COPYING.txt for copying permission. */
#include "tooltip.h"
#include "world.h"
#include "render.h"
#include "holidays.h"
using namespace std;
Tooltip::Tooltip(){
on=false;
message="";
//Starting coordinates.
x=0;
y=0;
//Dimensions.
w=0;
h=0;
}
void Tooltip::setup(string get_message,int mouse_x,int mouse_y){
message=get_message;
on=true;
x=mouse_x;
y=mouse_y+24;
set_dimensions();
//If the tooltip would be displayed off the screen, move it.
if(x+w>main_window.SCREEN_WIDTH){
x=mouse_x-w;
}
if(y+h>main_window.SCREEN_HEIGHT){
y=mouse_y-24-h;
}
}
void Tooltip::set_dimensions(){
short current_width=11;
w=11;
h=24;
for(short i=0;i<message.length();i++){
if(message[i]!='\xA'){
current_width+=11;
}
//If we hit a new line.
else{
h+=24;
if(current_width>w){
w=current_width;
}
current_width=11;
}
if(i==message.length()-1){
if(current_width>w){
w=current_width;
}
}
}
}
void Tooltip::render(){
//As long as the tooltip is on and has content.
if(on && message.length()>0){
render_rectangle(x-4,y-4,w,h,1.0,return_gui_color(holiday,0));
render_rectangle(x-4+2,y-4+2,w-4,h-4,1.0,return_gui_color(holiday,1));
font.show(x+2,y+2,message,COLOR_BLACK);
font.show(x,y,message,return_gui_color(holiday,3));
}
}
| 20.481013 | 78 | 0.563659 | [
"render"
] |
ff0198156a0b632b6887fd70429ba00c81a5dad2 | 829 | hpp | C++ | flare_skia/include/flare_skia/skr_actor_base_path.hpp | taehyub/flare_cpp | 7731bc0bcf2ce721f103586a48f74aa5c12504e8 | [
"MIT"
] | null | null | null | flare_skia/include/flare_skia/skr_actor_base_path.hpp | taehyub/flare_cpp | 7731bc0bcf2ce721f103586a48f74aa5c12504e8 | [
"MIT"
] | null | null | null | flare_skia/include/flare_skia/skr_actor_base_path.hpp | taehyub/flare_cpp | 7731bc0bcf2ce721f103586a48f74aa5c12504e8 | [
"MIT"
] | null | null | null | #ifndef _SKR_ACTOR_BASE_PATH_HPP_
#define _SKR_ACTOR_BASE_PATH_HPP_
#include "SkPath.h"
#include <thorvg.h>
class SkPath;
namespace flare
{
class ActorBasePath;
class SkrActorBasePath
{
SkPath m_Path;
ActorBasePath* m_BasePath;
protected:
bool m_IsPathValid;
private:
void updatePath();
protected:
SkrActorBasePath(ActorBasePath* path);
public:
const SkPath& path();
ActorBasePath* basePath() const { return m_BasePath; }
};
class TvgActorBasePath
{
ActorBasePath* m_BasePath;
protected:
bool m_IsPathValid;
private:
void updatePath(tvg::Canvas *canvas, tvg::Shape *tvgPath);
protected:
TvgActorBasePath(ActorBasePath* path);
public:
void path(tvg::Canvas *canvas, tvg::Shape *tvgPath);
ActorBasePath* basePath() const { return m_BasePath; }
};
} // namespace flare
#endif
| 15.641509 | 60 | 0.73462 | [
"shape"
] |
ff0cb3705cb8aa6a4ff82762e31599be36d5bce0 | 3,686 | cpp | C++ | libs/hwui/tests/common/scenes/SimpleColorMatrixAnimation.cpp | rio-31/android_frameworks_base-1 | 091a068a3288d27d77636708679dde58b7b7fd25 | [
"Apache-2.0"
] | 164 | 2015-01-05T16:49:11.000Z | 2022-03-29T20:40:27.000Z | libs/hwui/tests/common/scenes/SimpleColorMatrixAnimation.cpp | rio-31/android_frameworks_base-1 | 091a068a3288d27d77636708679dde58b7b7fd25 | [
"Apache-2.0"
] | 127 | 2015-01-12T12:02:32.000Z | 2021-11-28T08:46:25.000Z | libs/hwui/tests/common/scenes/SimpleColorMatrixAnimation.cpp | rio-31/android_frameworks_base-1 | 091a068a3288d27d77636708679dde58b7b7fd25 | [
"Apache-2.0"
] | 1,141 | 2015-01-01T22:54:40.000Z | 2022-02-09T22:08:26.000Z | /*
* Copyright (C) 2017 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 "TestSceneBase.h"
#include <SkColorMatrixFilter.h>
#include <SkGradientShader.h>
class SimpleColorMatrixAnimation;
static TestScene::Registrar _SimpleColorMatrix(TestScene::Info{
"simpleColorMatrix",
"A color matrix shader benchmark for the simple scale/translate case, which has R, G, and "
"B "
"all scaled and translated the same amount.",
TestScene::simpleCreateScene<SimpleColorMatrixAnimation>});
class SimpleColorMatrixAnimation : public TestScene {
public:
std::vector<sp<RenderNode> > cards;
void createContent(int width, int height, Canvas& canvas) override {
canvas.drawColor(Color::White, SkBlendMode::kSrcOver);
sp<RenderNode> card = createCard(0, 0, width, height);
canvas.drawRenderNode(card.get());
cards.push_back(card);
}
void doFrame(int frameNr) override {
int curFrame = frameNr % 20;
for (size_t ci = 0; ci < cards.size(); ci++) {
cards[ci]->mutateStagingProperties().setTranslationX(curFrame);
cards[ci]->mutateStagingProperties().setTranslationY(curFrame);
cards[ci]->setPropertyFieldsDirty(RenderNode::X | RenderNode::Y);
}
}
private:
sp<RenderNode> createCard(int x, int y, int width, int height) {
return TestUtils::createNode(
x, y, x + width, y + height,
[width, height](RenderProperties& props, Canvas& canvas) {
SkPaint paint;
float matrix[20] = {0};
// Simple scale/translate case where R, G, and B are all treated equivalently
matrix[SkColorMatrix::kR_Scale] = 1.1f;
matrix[SkColorMatrix::kG_Scale] = 1.1f;
matrix[SkColorMatrix::kB_Scale] = 1.1f;
matrix[SkColorMatrix::kA_Scale] = 0.5f;
matrix[SkColorMatrix::kR_Trans] = 5.0f;
matrix[SkColorMatrix::kG_Trans] = 5.0f;
matrix[SkColorMatrix::kB_Trans] = 5.0f;
matrix[SkColorMatrix::kA_Trans] = 10.0f;
paint.setColorFilter(SkColorFilter::MakeMatrixFilterRowMajor255(matrix));
// set a shader so it's not likely for the matrix to be optimized away (since a
// clever
// enough renderer might apply it directly to the paint color)
float pos[] = {0, 1};
SkPoint pts[] = {SkPoint::Make(0, 0), SkPoint::Make(width, height)};
SkColor colors[2] = {Color::DeepPurple_500, Color::DeepOrange_500};
paint.setShader(SkGradientShader::MakeLinear(pts, colors, pos, 2,
SkShader::kClamp_TileMode));
// overdraw several times to emphasize shader cost
for (int i = 0; i < 10; i++) {
canvas.drawRect(i, i, width, height, paint);
}
});
}
};
| 42.367816 | 99 | 0.594954 | [
"vector"
] |
d42e7d773f5e8b68e59ef7a309ccf2499715f6ef | 6,193 | cc | C++ | content/browser/cache_storage/cross_sequence/cross_sequence_cache_storage_manager.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/cache_storage/cross_sequence/cross_sequence_cache_storage_manager.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/cache_storage/cross_sequence/cross_sequence_cache_storage_manager.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/cache_storage/cross_sequence/cross_sequence_cache_storage_manager.h"
#include "base/bind_helpers.h"
#include "content/browser/cache_storage/cache_storage.h"
#include "content/browser/cache_storage/cache_storage_context_impl.h"
#include "content/browser/cache_storage/cross_sequence/cross_sequence_cache_storage.h"
#include "content/browser/cache_storage/cross_sequence/cross_sequence_utils.h"
#include "third_party/blink/public/mojom/quota/quota_types.mojom.h"
namespace content {
// The Inner class is SequenceBound<> to the real target manager sequence by
// the outer CrossSequenceCacheStorageManager. All CacheStorageManager
// operations are proxied to the Inner on the correct sequence via the Post()
// method. The outer manager is responsible for wrapping any callbacks in
// order to post on the outer's original sequence.
class CrossSequenceCacheStorageManager::Inner {
public:
explicit Inner(scoped_refptr<CacheStorageContextWithManager> context)
: target_manager_(context->CacheManager()) {
DCHECK(target_manager_);
}
void GetAllOriginsUsage(CacheStorageOwner owner,
CacheStorageContext::GetUsageInfoCallback callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
target_manager_->GetAllOriginsUsage(owner, std::move(callback));
}
void GetOriginUsage(const url::Origin& origin_url,
CacheStorageOwner owner,
storage::QuotaClient::GetUsageCallback callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
target_manager_->GetOriginUsage(origin_url, owner, std::move(callback));
}
void GetOrigins(CacheStorageOwner owner,
storage::QuotaClient::GetOriginsCallback callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
target_manager_->GetOrigins(owner, std::move(callback));
}
void GetOriginsForHost(const std::string& host,
CacheStorageOwner owner,
storage::QuotaClient::GetOriginsCallback callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
target_manager_->GetOriginsForHost(host, owner, std::move(callback));
}
void DeleteOriginData(const url::Origin& origin,
CacheStorageOwner owner,
storage::QuotaClient::DeletionCallback callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
target_manager_->DeleteOriginData(origin, owner, std::move(callback));
}
private:
const scoped_refptr<CacheStorageManager> target_manager_;
SEQUENCE_CHECKER(sequence_checker_);
};
CrossSequenceCacheStorageManager::CrossSequenceCacheStorageManager(
scoped_refptr<base::SequencedTaskRunner> target_task_runner,
scoped_refptr<CacheStorageContextWithManager> context)
: target_task_runner_(std::move(target_task_runner)),
context_(context),
inner_(target_task_runner_, std::move(context)) {}
CacheStorageHandle CrossSequenceCacheStorageManager::OpenCacheStorage(
const url::Origin& origin,
CacheStorageOwner owner) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// Construct the CrossSequenceCacheStorage object immediately on our current
// sequence. This is necessary in order to return a Handle synchronously.
// The CrossSequenceCacheStorage object will asynchronously open the real
// CacheStorage on the correct sequence.
auto storage = base::MakeRefCounted<CrossSequenceCacheStorage>(
origin, owner, target_task_runner_, context_);
return storage->CreateHandle();
}
void CrossSequenceCacheStorageManager::GetAllOriginsUsage(
CacheStorageOwner owner,
CacheStorageContext::GetUsageInfoCallback callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
inner_.Post(FROM_HERE, &Inner::GetAllOriginsUsage, owner,
WrapCallbackForCurrentSequence(std::move(callback)));
}
void CrossSequenceCacheStorageManager::GetOriginUsage(
const url::Origin& origin_url,
CacheStorageOwner owner,
storage::QuotaClient::GetUsageCallback callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
inner_.Post(FROM_HERE, &Inner::GetOriginUsage, origin_url, owner,
WrapCallbackForCurrentSequence(std::move(callback)));
}
void CrossSequenceCacheStorageManager::GetOrigins(
CacheStorageOwner owner,
storage::QuotaClient::GetOriginsCallback callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
inner_.Post(FROM_HERE, &Inner::GetOrigins, owner,
WrapCallbackForCurrentSequence(std::move(callback)));
}
void CrossSequenceCacheStorageManager::GetOriginsForHost(
const std::string& host,
CacheStorageOwner owner,
storage::QuotaClient::GetOriginsCallback callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
inner_.Post(FROM_HERE, &Inner::GetOriginsForHost, host, owner,
WrapCallbackForCurrentSequence(std::move(callback)));
}
void CrossSequenceCacheStorageManager::DeleteOriginData(
const url::Origin& origin,
CacheStorageOwner owner,
storage::QuotaClient::DeletionCallback callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
inner_.Post(FROM_HERE, &Inner::DeleteOriginData, origin, owner,
WrapCallbackForCurrentSequence(std::move(callback)));
}
void CrossSequenceCacheStorageManager::DeleteOriginData(
const url::Origin& origin,
CacheStorageOwner owner) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DeleteOriginData(origin, owner, base::DoNothing());
}
void CrossSequenceCacheStorageManager::SetBlobParametersForCache(
scoped_refptr<BlobStorageContextWrapper> blob_storage_context) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// This method is used for initialization of a real manager and should not
// be invoked for the cross-sequence wrapper.
NOTREACHED();
}
CrossSequenceCacheStorageManager::~CrossSequenceCacheStorageManager() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}
} // namespace content
| 41.563758 | 94 | 0.772485 | [
"object"
] |
d42feaf001fc2432f733381ac5085b1489588c97 | 19,423 | cc | C++ | test/gtest/ucp/test_ucp_peer_failure.cc | lemonrock/ucx-patches | e20898d1c139225068d7354dbdf094444d642de4 | [
"BSD-3-Clause"
] | 1 | 2021-04-12T09:07:21.000Z | 2021-04-12T09:07:21.000Z | test/gtest/ucp/test_ucp_peer_failure.cc | lemonrock/ucx-patches | e20898d1c139225068d7354dbdf094444d642de4 | [
"BSD-3-Clause"
] | null | null | null | test/gtest/ucp/test_ucp_peer_failure.cc | lemonrock/ucx-patches | e20898d1c139225068d7354dbdf094444d642de4 | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright (C) Mellanox Technologies Ltd. 2001-2017. ALL RIGHTS RESERVED.
*
* See file LICENSE for terms.
*/
#include "test_ucp_tag.h"
#include "ucp_datatype.h"
extern "C" {
#include <malloc.h>
}
class test_ucp_peer_failure_base {
protected:
enum {
FAIL_AFTER_WIREUP = ucp_test::DEFAULT_PARAM_VARIANT,
FAIL_IMMEDIATELY
};
test_ucp_peer_failure_base() {
/* Set small TL timeouts to reduce testing time */
m_env.push_back(new ucs::scoped_setenv("UCX_RC_TIMEOUT", "10us"));
m_env.push_back(new ucs::scoped_setenv("UCX_RC_RETRY_COUNT", "2"));
std::string ud_timeout = ucs::to_string<int>(1 * ucs::test_time_multiplier()) + "s";
m_env.push_back(new ucs::scoped_setenv("UCX_UD_TIMEOUT", ud_timeout.c_str()));
}
virtual ucp_ep_params_t get_ep_params() {
ucp_ep_params_t params;
memset(¶ms, 0, sizeof(params));
params.field_mask = UCP_EP_PARAM_FIELD_ERR_HANDLING_MODE |
UCP_EP_PARAM_FIELD_ERR_HANDLER;
params.err_mode = UCP_ERR_HANDLING_MODE_PEER;
params.err_handler.cb = err_cb;
params.err_handler.arg = NULL;
return params;
}
void init() {
m_err_cntr = 0;
m_err_status = UCS_OK;
}
static void err_cb(void *arg, ucp_ep_h ep, ucs_status_t status) {
EXPECT_EQ(UCS_ERR_ENDPOINT_TIMEOUT, status);
m_err_status = status;
++m_err_cntr;
}
protected:
static size_t m_err_cntr;
static ucs_status_t m_err_status;
ucs::ptr_vector<ucs::scoped_setenv> m_env;
};
size_t test_ucp_peer_failure_base::m_err_cntr = 0;
ucs_status_t test_ucp_peer_failure_base::m_err_status = UCS_OK;
class test_ucp_peer_failure :
public test_ucp_tag,
protected test_ucp_peer_failure_base {
public:
test_ucp_peer_failure() : m_msg_size(1024) {
}
static std::vector<ucp_test_param>
enum_test_params(const ucp_params_t& ctx_params,
const std::string& name,
const std::string& test_case_name,
const std::string& tls)
{
std::vector<ucp_test_param> result =
test_ucp_tag::enum_test_params(ctx_params, name, test_case_name, tls);
generate_test_params_variant(ctx_params, name, test_case_name, tls,
FAIL_AFTER_WIREUP, result);
generate_test_params_variant(ctx_params, name, test_case_name, tls,
FAIL_IMMEDIATELY, result);
return result;
}
virtual void init();
virtual void cleanup();
void test_status_after(bool request_must_fail);
void test_force_close();
protected:
virtual ucp_ep_params_t get_ep_params() {
return test_ucp_peer_failure_base::get_ep_params();
}
void fail_receiver() {
/* TODO: need to handle non-empty TX window in UD EP destructor",
* see debug message (ud_ep.c:220)
* ucs_debug("ep=%p id=%d conn_id=%d has %d unacked packets",
* self, self->ep_id, self->conn_id,
* (int)ucs_queue_length(&self->tx.window));
*/
flush_worker(receiver());
m_entities.remove(&receiver());
}
void smoke_test() {
long buf = 0;
request *req = recv_nb(&buf, sizeof(buf), DATATYPE, 0, 0);
send_b(&buf, sizeof(buf), DATATYPE, 0, 0);
wait_and_validate(req);
}
void wait_err() {
while (!m_err_cntr) {
progress();
}
}
static void err_cb_mod(void *arg, ucp_ep_h ep, ucs_status_t status) {
EXPECT_EQ(uintptr_t(ucp::MAGIC), uintptr_t(arg));
err_cb(arg, ep, status);
m_err_cb_mod = true;
}
protected:
const size_t m_msg_size;
static bool m_err_cb_mod;
};
bool test_ucp_peer_failure::m_err_cb_mod = false;
void test_ucp_peer_failure::init() {
m_err_cb_mod = false;
test_ucp_peer_failure_base::init();
test_ucp_tag::init();
if (GetParam().variant != FAIL_IMMEDIATELY) {
smoke_test();
}
/* Make second pair */
create_entity(true);
create_entity(false);
sender().connect(&receiver(), get_ep_params());
if (GetParam().variant != FAIL_IMMEDIATELY) {
smoke_test();
}
wrap_errors();
ucp_ep_params_t ep_params_mod = {0};
ep_params_mod.field_mask = UCP_EP_PARAM_FIELD_ERR_HANDLER;
ep_params_mod.err_handler.cb = err_cb_mod;
/* NOTE: using of ucp_ep_params_t::user_data field is more preferable but
* need to test err_handler.arg as well */
ep_params_mod.err_handler.arg = reinterpret_cast<void *>(uintptr_t(ucp::MAGIC));
for (size_t i = 0; i < m_entities.size(); ++i) {
for (int widx = 0; widx < e(i).get_num_workers(); ++widx) {
for (int epidx = 0; epidx < e(i).get_num_eps(widx); ++epidx) {
void *req = e(i).modify_ep(ep_params_mod, widx, epidx);
ucp_test::wait(req, widx);
}
}
}
}
void test_ucp_peer_failure::cleanup() {
restore_errors();
test_ucp_tag::cleanup();
}
void test_ucp_peer_failure::test_status_after(bool request_must_fail)
{
fail_receiver();
std::vector<uint8_t> buf(m_msg_size, 0);
request *req = send_nb(buf.data(), buf.size(), DATATYPE,
0x111337);
wait_err();
EXPECT_NE(UCS_OK, m_err_status);
EXPECT_TRUE(m_err_cb_mod);
if (UCS_PTR_IS_PTR(req)) {
/* The request may either succeed or fail, even though the data is not
* delivered - depends on when the error is detected on sender side and
* if zcopy/bcopy protocol is used. In any case, the request must
* complete, and all resources have to be released.
*/
EXPECT_TRUE(req->completed);
if (request_must_fail) {
EXPECT_EQ(m_err_status, req->status);
} else {
EXPECT_TRUE((m_err_status == req->status) || (UCS_OK == req->status));
}
request_release(req);
}
ucs_status_ptr_t status_ptr = ucp_tag_send_nb(sender().ep(), NULL, 0, DATATYPE,
0x111337, NULL);
EXPECT_FALSE(UCS_PTR_IS_PTR(status_ptr));
EXPECT_EQ(m_err_status, UCS_PTR_STATUS(status_ptr));
/* Destroy failed sender */
sender().destroy_worker();
m_entities.remove(&sender());
/* Check workability of second pair */
smoke_test();
}
void test_ucp_peer_failure::test_force_close()
{
const size_t msg_size = 16000;
const size_t iter = 1000;
uint8_t *buf = (uint8_t *)calloc(msg_size, iter);
struct mallinfo mem_before, mem_after;
std::vector<request *> reqs;
reqs.reserve(iter);
for (size_t i = 0; i < iter; ++i) {
request *sreq = send_nb(&buf[i * msg_size], msg_size, DATATYPE, 17);
if (UCS_PTR_IS_PTR(sreq)) {
reqs.push_back(sreq);
} else if (UCS_PTR_IS_ERR(sreq)) {
EXPECT_EQ(UCS_ERR_NO_RESOURCE, UCS_PTR_STATUS(sreq));
break;
}
}
fail_receiver();
mem_before = mallinfo();
request *close_req = (request *)ucp_ep_close_nb(sender().ep(),
UCP_EP_CLOSE_MODE_FORCE);
if (UCS_PTR_IS_PTR(close_req)) {
wait(close_req);
ucp_request_release(close_req);
} else {
EXPECT_FALSE(UCS_PTR_IS_ERR(close_req));
}
mem_after = mallinfo();
/* Too low chance to predict memory consumption on wire up for all TLS */
if (GetParam().variant != FAIL_IMMEDIATELY) {
EXPECT_GT(mem_before.uordblks, mem_after.uordblks);
}
/* The EP can't be used now */
sender().revoke_ep();
while (!reqs.empty()) {
EXPECT_NE(UCS_INPROGRESS, ucp_request_test(reqs.back(), NULL));
ucp_request_release(reqs.back());
reqs.pop_back();
}
/* Check that TX polling is working well */
while (sender().progress());
/* When all requests on sender are done we need to prevent LOCAL_FLUSH
* in test teardown. Receiver is killed and doesn't respond on FC requests
*/
sender().destroy_worker();
free(buf);
}
UCS_TEST_P(test_ucp_peer_failure, disable_sync_send) {
/* 1GB memory markup takes too long time with valgrind, reduce to 1MB */
const size_t max_size = RUNNING_ON_VALGRIND ? (1024 * 1024) :
(1024 * 1024 * 1024);
std::vector<char> buf(max_size, 0);
request *req;
/* Make sure API is disabled for any size and data type */
for (size_t size = 1; size <= max_size; size *= 2) {
req = send_sync_nb(buf.data(), size, DATATYPE, 0x111337);
EXPECT_FALSE(UCS_PTR_IS_PTR(req));
EXPECT_EQ(UCS_ERR_UNSUPPORTED, UCS_PTR_STATUS(req));
ucp::data_type_desc_t dt_desc(DATATYPE_IOV, buf.data(), size);
req = send_sync_nb(dt_desc.buf(), dt_desc.count(), dt_desc.dt(), 0x111337);
EXPECT_FALSE(UCS_PTR_IS_PTR(req));
EXPECT_EQ(UCS_ERR_UNSUPPORTED, UCS_PTR_STATUS(req));
}
}
UCS_TEST_P(test_ucp_peer_failure, status_after_error) {
test_status_after(false);
}
UCP_INSTANTIATE_TEST_CASE(test_ucp_peer_failure)
class test_ucp_peer_failure_zcopy : public test_ucp_peer_failure
{
public:
virtual void init() {
modify_config("ZCOPY_THRESH", ucs::to_string(m_msg_size - 1));
test_ucp_peer_failure::init();
}
};
UCS_TEST_P(test_ucp_peer_failure_zcopy, status_after_error) {
test_status_after(true);
}
UCP_INSTANTIATE_TEST_CASE(test_ucp_peer_failure_zcopy)
class test_ucp_peer_failure_zcopy_multi : public test_ucp_peer_failure_zcopy
{
public:
virtual void init() {
/* MAX BCOPY is internally used as fragment size */
m_env.push_back(new ucs::scoped_setenv("UCX_MAX_BCOPY",
(ucs::to_string(m_msg_size/2) + "b").c_str()));
/* HW TM does not support multiprotocols and eager protocol for messages
* bigger than UCT segment size */
m_env.push_back(new ucs::scoped_setenv("UCX_RC_TM_ENABLE", "n"));
test_ucp_peer_failure_zcopy::init();
}
};
UCS_TEST_P(test_ucp_peer_failure_zcopy_multi, status_after_error) {
test_status_after(true);
}
UCP_INSTANTIATE_TEST_CASE(test_ucp_peer_failure_zcopy_multi)
class test_ucp_peer_failure_with_rma : public test_ucp_peer_failure {
public:
enum {
FAIL_ON_RMA = FAIL_IMMEDIATELY + 1
};
static std::vector<ucp_test_param>
enum_test_params(const ucp_params_t& ctx_params,
const std::string& name,
const std::string& test_case_name,
const std::string& tls)
{
std::vector<ucp_test_param> result =
test_ucp_peer_failure::enum_test_params(ctx_params, name,
test_case_name, tls);
generate_test_params_variant(ctx_params, name, test_case_name, tls,
FAIL_ON_RMA, result);
return result;
}
static ucp_params_t get_ctx_params() {
ucp_params_t params = test_ucp_tag::get_ctx_params();
params.features |= UCP_FEATURE_RMA;
return params;
}
};
UCS_TEST_P(test_ucp_peer_failure_with_rma, status_after_error) {
unsigned buf = 0;
ucp_mem_map_params_t params;
memset(¶ms, 0, sizeof(params));
params.field_mask = UCP_MEM_MAP_PARAM_FIELD_ADDRESS |
UCP_MEM_MAP_PARAM_FIELD_LENGTH;
params.address = &buf;
params.length = sizeof(buf);
ucp_mem_h memh;
ucs_status_t status = ucp_mem_map(receiver().ucph(), ¶ms, &memh);
ASSERT_UCS_OK(status);
ucp_mem_attr_t mem_attr;
mem_attr.field_mask = UCP_MEM_ATTR_FIELD_ADDRESS;
status = ucp_mem_query(memh, &mem_attr);
ASSERT_UCS_OK(status);
void *rkey_buffer;
size_t rkey_buffer_size;
status = ucp_rkey_pack(receiver().ucph(), memh, &rkey_buffer, &rkey_buffer_size);
ASSERT_UCS_OK(status);
ucp_rkey_h rkey;
status = ucp_ep_rkey_unpack(sender().ep(), rkey_buffer, &rkey);
ASSERT_UCS_OK(status);
ucp_rkey_buffer_release(rkey_buffer);
ucp_mem_unmap(receiver().ucph(), memh);
fail_receiver();
if (GetParam().variant == FAIL_ON_RMA) {
ucp_get_nbi(sender().ep(), mem_attr.address, 1, (uintptr_t)&buf, rkey);
} else {
request *req = send_nb(NULL, 0, DATATYPE, 0x111337);
if (UCS_PTR_IS_PTR(req)) {
request_release(req);
}
}
ucp_ep_flush(sender().ep());
wait_err();
EXPECT_NE(UCS_OK, m_err_status);
ucs_status_ptr_t status_ptr = ucp_tag_send_nb(sender().ep(), NULL, 0, DATATYPE,
0x111337, NULL);
EXPECT_FALSE(UCS_PTR_IS_PTR(status_ptr));
EXPECT_EQ(m_err_status, UCS_PTR_STATUS(status_ptr));
status = ucp_put(sender().ep(), mem_attr.address, 1, (uintptr_t)&buf, rkey);
EXPECT_FALSE(UCS_PTR_IS_PTR(status));
EXPECT_EQ(m_err_status, status);
ucp_rkey_destroy(rkey);
/* Destroy failed sender */
sender().destroy_worker();
m_entities.remove(&sender());
/* Check workability of second pair */
smoke_test();
}
UCP_INSTANTIATE_TEST_CASE(test_ucp_peer_failure_with_rma)
class test_ucp_peer_failure_2pairs :
public ucp_test,
protected test_ucp_peer_failure_base
{
public:
static ucp_params_t get_ctx_params() {
ucp_params_t params = ucp_test::get_ctx_params();
params.features = UCP_FEATURE_TAG;
return params;
}
protected:
virtual void init();
virtual void cleanup();
static void err_cb(void *arg, ucp_ep_h ep, ucs_status_t);
ucp_worker_h rworker(int i);
ucp_worker_h sworker();
void progress();
void wait_err();
ucs_status_t wait_req(void *req);
static void rcomplete_cb(void *req, ucs_status_t status,
ucp_tag_recv_info_t *info);
static void scomplete_cb(void *req, ucs_status_t status);
void smoke_test(size_t idx);
static void ep_destructor(ucp_ep_h ep, test_ucp_peer_failure_2pairs* test) {
test->wait_req(ucp_disconnect_nb(ep));
}
virtual ucp_ep_params_t get_ep_params() {
return test_ucp_peer_failure_base::get_ep_params();
}
ucs::handle<ucp_context_h> m_ucph;
std::vector<ucs::handle<ucp_worker_h> > m_workers;
std::vector<ucs::handle<ucp_ep_h, test_ucp_peer_failure_2pairs*> > m_eps;
ucs::ptr_vector<ucs::scoped_setenv> m_env;
};
void test_ucp_peer_failure_2pairs::init()
{
test_base::init(); /* skip entities creation */
test_ucp_peer_failure_base::init();
set_ucp_config(m_ucp_config);
ucp_params_t cparams = get_ctx_params();
UCS_TEST_CREATE_HANDLE(ucp_context_h, m_ucph, ucp_cleanup,
ucp_init, &cparams, m_ucp_config);
m_workers.resize(3);
for (int i = 0; i < 3; ++i) {
ucp_worker_params_t wparams = get_worker_params();
UCS_TEST_CREATE_HANDLE(ucp_worker_h, m_workers[i], ucp_worker_destroy,
ucp_worker_create, m_ucph, &wparams);
}
m_eps.resize(2);
for (int i = 0; i < 2; ++i) {
ucp_address_t *address;
size_t address_length;
ucs_status_t status;
ucp_ep_h ep;
status = ucp_worker_get_address(rworker(i), &address, &address_length);
ASSERT_UCS_OK(status);
ucp_ep_params ep_params = get_ep_params();
ep_params.field_mask |= UCP_EP_PARAM_FIELD_REMOTE_ADDRESS;
ep_params.address = address;
hide_errors();
status = ucp_ep_create(sworker(), &ep_params, &ep);
restore_errors();
ucp_worker_release_address(rworker(i), address);
if (status == UCS_ERR_UNREACHABLE) {
UCS_TEST_SKIP_R(m_errors.empty() ? "" : m_errors.back());
}
m_eps[i].reset(ep, ep_destructor, this);
}
/* Make sure wire up is done*/
smoke_test(0);
smoke_test(1);
wrap_errors();
}
void test_ucp_peer_failure_2pairs::cleanup()
{
restore_errors();
m_eps.clear();
m_workers.clear();
test_base::cleanup();
}
void test_ucp_peer_failure_2pairs::err_cb(void *arg, ucp_ep_h ep, ucs_status_t) {
test_ucp_peer_failure_2pairs *self;
self = *reinterpret_cast<test_ucp_peer_failure_2pairs**>(arg);
self->m_err_cntr++;
}
ucp_worker_h test_ucp_peer_failure_2pairs::rworker(int i)
{
return m_workers[i];
}
ucp_worker_h test_ucp_peer_failure_2pairs::sworker()
{
return m_workers[2];
}
void test_ucp_peer_failure_2pairs::progress()
{
for (std::vector<ucs::handle<ucp_worker_h> >::iterator iter = m_workers.begin();
iter != m_workers.end(); ++iter)
{
if (*iter) {
ucp_worker_progress(*iter);
}
}
}
void test_ucp_peer_failure_2pairs::wait_err()
{
while (!m_err_cntr) {
progress();
}
}
ucs_status_t test_ucp_peer_failure_2pairs::wait_req(void *req)
{
if (req == NULL) {
return UCS_OK;
}
ucs_assert(!!req);
if (UCS_PTR_IS_ERR(req)) {
return UCS_PTR_STATUS(req);
}
ucs_status_t status;
do {
progress();
status = ucp_request_check_status(req);
} while (status == UCS_INPROGRESS);
ucp_request_release(req);
return status;
}
void test_ucp_peer_failure_2pairs::rcomplete_cb(void *req, ucs_status_t status,
ucp_tag_recv_info_t *info)
{
}
void test_ucp_peer_failure_2pairs::scomplete_cb(void *req, ucs_status_t status)
{
}
void test_ucp_peer_failure_2pairs::smoke_test(size_t idx)
{
long buf = 0;
void *rreq = ucp_tag_recv_nb(rworker(idx), &buf, 1,
ucp_dt_make_contig(1), 0, 0,
rcomplete_cb);
void *sreq = ucp_tag_send_nb(m_eps[idx], &buf, 1,
ucp_dt_make_contig(1), 0,
scomplete_cb);
wait_req(sreq);
wait_req(rreq);
}
UCS_TEST_P(test_ucp_peer_failure_2pairs, status_after_error) {
m_workers[0].reset();
ucs_status_t status;
void *sreq;
unsigned buf = 0;
do {
sreq = ucp_tag_send_nb(m_eps[0], &buf, 1, ucp_dt_make_contig(1),
0x111337, scomplete_cb);
status = wait_req(sreq);
} while ((status == UCS_OK) || !m_err_cntr);
wait_err();
EXPECT_NE(UCS_OK, m_err_status);
sreq = ucp_tag_send_nb(m_eps[0], NULL, 0, ucp_dt_make_contig(1), 0x111337,
scomplete_cb);
EXPECT_FALSE(UCS_PTR_IS_PTR(sreq));
EXPECT_EQ(m_err_status, UCS_PTR_STATUS(sreq));
/* Destroy failed sender */
m_eps[0].reset();
/* Check workability of second pair */
smoke_test(1);
}
UCP_INSTANTIATE_TEST_CASE(test_ucp_peer_failure_2pairs)
class test_ucp_ep_force_disconnect : public test_ucp_peer_failure
{
public:
virtual void init() {
m_env.clear(); /* restore default timeouts. */
test_ucp_peer_failure::init();
}
};
UCS_TEST_P(test_ucp_ep_force_disconnect, test) {
test_force_close();
}
UCP_INSTANTIATE_TEST_CASE(test_ucp_ep_force_disconnect)
| 30.113178 | 94 | 0.629666 | [
"vector"
] |
d4356c0f4918ab30aa78d716270b36d54039c1fe | 29,750 | cc | C++ | shill/vpn/l2tp_ipsec_driver_test.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | shill/vpn/l2tp_ipsec_driver_test.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | shill/vpn/l2tp_ipsec_driver_test.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "shill/vpn/l2tp_ipsec_driver.h"
#include <utility>
#include <base/containers/contains.h>
#include <base/files/file_util.h>
#include <base/files/scoped_temp_dir.h>
#include <base/memory/ptr_util.h>
#include <base/memory/weak_ptr.h>
#include <base/strings/string_util.h>
#include <base/strings/stringprintf.h>
#include <gtest/gtest.h>
#include <libpasswordprovider/fake_password_provider.h>
#include <libpasswordprovider/password.h>
#include <libpasswordprovider/password_provider.h>
#include <vpn-manager/service_error.h>
#include "shill/ipconfig.h"
#include "shill/mock_adaptors.h"
#include "shill/mock_certificate_file.h"
#include "shill/mock_control.h"
#include "shill/mock_device_info.h"
#include "shill/mock_external_task.h"
#include "shill/mock_manager.h"
#include "shill/mock_metrics.h"
#include "shill/mock_process_manager.h"
#include "shill/ppp_device.h"
#include "shill/test_event_dispatcher.h"
#include "shill/vpn/fake_vpn_util.h"
#include "shill/vpn/mock_vpn_driver.h"
#include "shill/vpn/mock_vpn_provider.h"
using testing::_;
using testing::Mock;
using testing::NiceMock;
using testing::Return;
using testing::ReturnRef;
using testing::WithArg;
namespace shill {
namespace {
// Output of `stroke statusall` used in
// L2TPIPsecDriverTest::ExpectCipherMetricsReported().
constexpr char kStrokeStatusAllOutput[] =
R"(Status of IKE charon daemon (strongSwan 5.7.2, Linux 4.4.289-21012-gca997499d4ea, x86_64):
uptime: 3 minutes, since Oct 28 12:34:20 2021
malloc: sbrk 1622016, mmap 1196032, used 613040, free 1008976
worker threads: 10 of 16 idle, 6/0/0/0 working, job queue: 0/0/0/0, scheduled: 3
loaded plugins: charon pkcs11 aes des rc2 sha2 sha1 md5 mgf1 random nonce x509 revocation constraints pubkey pkcs1 pkcs7 pkcs8 pkcs12 pgp dnskey sshkey pem openssl fips-prf gmp curve25519 xcbc cmac hmac attr kernel-netlink resolve socket-default socket-dynamic stroke vici updown xauth-generic lookip led counters
Listening IP addresses:
1.2.3.4
1.2.3.5
192.168.0.1
192.168.1.2
Connections:
managed: %any...10.0.0.1 IKEv1
managed: local: [100.86.195.191] uses pre-shared key authentication
managed: remote: uses pre-shared key authentication
managed: child: dynamic[udp/l2tp] === dynamic[udp/l2tp] TRANSPORT
Security Associations (1 up, 0 connecting):
managed[1]: ESTABLISHED 3 minutes ago, 1.2.3.4[1.2.3.4]...10.0.0.1[10.0.0.1]
managed[1]: IKEv1 SPIs: a8936495c1cbbca4_i* f8b549a4234245e7_r, pre-shared key reauthentication in 2 hours
managed[1]: IKE proposal: AES_CBC_128/HMAC_SHA2_256_128/PRF_HMAC_SHA2_256/MODP_3072
managed{1}: INSTALLED, TRANSPORT, reqid 1, ESP in UDP SPIs: c422affe_i c5ff79b3_o
managed{1}: AES_CBC_128/HMAC_SHA2_256_128, 4034 bytes_i (57 pkts, 19s ago), 42409 bytes_o (569 pkts, 1s ago), rekeying in 41 minutes
managed{1}: 1.2.3.4/32[udp/l2tp] === 10.0.0.1/32[udp/l2tp])";
} // namespace
class L2TPIPsecDriverTest : public testing::Test, public RpcTaskDelegate {
public:
L2TPIPsecDriverTest()
: manager_(&control_, &dispatcher_, &metrics_),
device_info_(&manager_),
driver_(new L2TPIPsecDriver(&manager_, &process_manager_)),
certificate_file_(new MockCertificateFile()),
weak_factory_(this) {
manager_.set_mock_device_info(&device_info_);
driver_->certificate_file_.reset(certificate_file_); // Passes ownership.
driver_->vpn_util_ = std::make_unique<FakeVPNUtil>();
}
~L2TPIPsecDriverTest() override = default;
void SetUp() override {
manager_.vpn_provider_ = std::make_unique<MockVPNProvider>();
manager_.vpn_provider_->manager_ = &manager_;
manager_.user_traffic_uids_.push_back(1000);
manager_.UpdateProviderMapping();
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
}
void TearDown() override {
SetEventHandler(nullptr);
ASSERT_TRUE(temp_dir_.Delete());
// The ExternalTask instance initially held by |driver_->external_task_|
// could be scheduled to be destroyed after |driver_| is destroyed. To avoid
// leaking any ExternalTask instance when the test finishes, we explicitly
// destroy |driver_| here and in turn schedules the destruction of
// |driver_->external_task_| in the message loop. Then we run until the
// message loop becomes idle to exercise the destruction task of
// ExternalTask.
driver_ = nullptr;
dispatcher_.PostTask(
FROM_HERE,
base::BindOnce(&EventDispatcherForTest::QuitDispatchForever,
// dispatcher_ will not be deleted before RunLoop quits.
base::Unretained(&dispatcher_)));
dispatcher_.DispatchForever();
}
protected:
static const char kInterfaceName[];
static const int kInterfaceIndex;
void SetArg(const std::string& arg, const std::string& value) {
driver_->args()->Set<std::string>(arg, value);
}
void SetArgArray(const std::string& arg,
const std::vector<std::string>& value) {
driver_->args()->Set<Strings>(arg, value);
}
KeyValueStore* GetArgs() { return driver_->args(); }
std::string GetProviderType() { return driver_->GetProviderType(); }
void SetEventHandler(VPNDriver::EventHandler* handler) {
driver_->event_handler_ = handler;
}
bool IsPSKFileCleared(const base::FilePath& psk_file_path) const {
return !base::PathExists(psk_file_path) && GetPSKFile().empty();
}
bool IsXauthCredentialsFileCleared(
const base::FilePath& xauth_credentials_file_path) const {
return !base::PathExists(xauth_credentials_file_path) &&
GetXauthCredentialsFile().empty();
}
// Used to assert that a flag appears in the options.
void ExpectInFlags(const std::vector<std::string>& options,
const std::string& flag,
const std::string& value);
base::FilePath SetupPSKFile();
base::FilePath SetupXauthCredentialsFile();
base::FilePath GetPSKFile() const { return driver_->psk_file_; }
base::FilePath GetXauthCredentialsFile() const {
return driver_->xauth_credentials_file_;
}
void InvokeNotify(const std::string& reason,
const std::map<std::string, std::string>& dict) {
driver_->Notify(reason, dict);
}
void FakeUpConnect(base::FilePath* psk_file,
base::FilePath* xauth_credentials_file) {
*psk_file = SetupPSKFile();
*xauth_credentials_file = SetupXauthCredentialsFile();
SetEventHandler(&event_handler_);
}
void ExpectMetricsReported() {
Error unused_error;
PropertyStore store;
driver_->InitPropertyStore(&store);
store.SetStringProperty(kL2TPIPsecPskProperty, "x", &unused_error);
store.SetStringProperty(kL2TPIPsecPasswordProperty, "y", &unused_error);
store.SetStringProperty(kL2TPIPsecTunnelGroupProperty, "z", &unused_error);
EXPECT_CALL(metrics_, SendEnumToUMA(Metrics::kMetricVpnDriver,
Metrics::kVpnDriverL2tpIpsec,
Metrics::kMetricVpnDriverMax));
EXPECT_CALL(metrics_,
SendEnumToUMA(Metrics::kMetricVpnRemoteAuthenticationType,
Metrics::kVpnRemoteAuthenticationTypeL2tpIpsecPsk,
Metrics::kVpnRemoteAuthenticationTypeMax));
EXPECT_CALL(
metrics_,
SendEnumToUMA(
Metrics::kMetricVpnUserAuthenticationType,
Metrics::kVpnUserAuthenticationTypeL2tpIpsecUsernamePassword,
Metrics::kVpnUserAuthenticationTypeMax));
EXPECT_CALL(metrics_,
SendEnumToUMA(Metrics::kMetricVpnL2tpIpsecTunnelGroupUsage,
Metrics::kVpnL2tpIpsecTunnelGroupUsageYes,
Metrics::kVpnL2tpIpsecTunnelGroupUsageMax));
ExpectCipherMetricsReported();
}
void ExpectCipherMetricsReported() {
EXPECT_CALL(process_manager_,
StartProcessInMinijailWithStdout(_, _, _, _, _, _))
.WillOnce(WithArg<5>([](ProcessManager::ExitWithStdoutCallback cb) {
// Invokes the callback directly.
std::move(cb).Run(0, kStrokeStatusAllOutput);
return 123;
}));
// Expects metrics for IKE.
EXPECT_CALL(
metrics_,
SendEnumToUMA(Metrics::kMetricVpnL2tpIpsecIkeEncryptionAlgorithm,
Metrics::kVpnIpsecEncryptionAlgorithm_AES_CBC_128,
Metrics::kMetricVpnL2tpIpsecIkeEncryptionAlgorithmMax));
EXPECT_CALL(
metrics_,
SendEnumToUMA(Metrics::kMetricVpnL2tpIpsecIkeIntegrityAlgorithm,
Metrics::kVpnIpsecIntegrityAlgorithm_HMAC_SHA2_256_128,
Metrics::kMetricVpnL2tpIpsecIkeIntegrityAlgorithmMax));
EXPECT_CALL(metrics_,
SendEnumToUMA(Metrics::kMetricVpnL2tpIpsecIkeDHGroup,
Metrics::kVpnIpsecDHGroup_MODP_3072,
Metrics::kMetricVpnL2tpIpsecIkeDHGroupMax));
// Expect metrics for ESP.
EXPECT_CALL(
metrics_,
SendEnumToUMA(Metrics::kMetricVpnL2tpIpsecEspEncryptionAlgorithm,
Metrics::kVpnIpsecEncryptionAlgorithm_AES_CBC_128,
Metrics::kMetricVpnL2tpIpsecEspEncryptionAlgorithmMax));
EXPECT_CALL(
metrics_,
SendEnumToUMA(Metrics::kMetricVpnL2tpIpsecEspIntegrityAlgorithm,
Metrics::kVpnIpsecIntegrityAlgorithm_HMAC_SHA2_256_128,
Metrics::kMetricVpnL2tpIpsecEspIntegrityAlgorithmMax));
}
void ExpectEndReasonMetricsReported(Service::ConnectFailure failure) {
EXPECT_CALL(
metrics_,
SendEnumToUMA(Metrics::kMetricVpnL2tpIpsecStrokeEndReason,
Metrics::ConnectFailureToServiceErrorEnum(failure),
Metrics::kMetricVpnL2tpIpsecStrokeEndReasonMax));
}
void SaveLoginPassword(const std::string& password_str) {
driver_->password_provider_ =
std::make_unique<password_provider::FakePasswordProvider>();
int fds[2];
base::CreateLocalNonBlockingPipe(fds);
base::ScopedFD read_dbus_fd(fds[0]);
base::ScopedFD write_scoped_fd(fds[1]);
size_t data_size = password_str.length();
base::WriteFileDescriptor(write_scoped_fd.get(), password_str);
auto password = password_provider::Password::CreateFromFileDescriptor(
read_dbus_fd.get(), data_size);
ASSERT_TRUE(password);
driver_->password_provider_->SavePassword(*password);
}
// Inherited from RpcTaskDelegate.
void GetLogin(std::string* user, std::string* password) override;
void Notify(const std::string& reason,
const std::map<std::string, std::string>& dict) override;
base::ScopedTempDir temp_dir_;
MockControl control_;
EventDispatcherForTest dispatcher_;
MockMetrics metrics_;
MockProcessManager process_manager_;
MockManager manager_;
NiceMock<MockDeviceInfo> device_info_;
MockVPNDriverEventHandler event_handler_;
std::unique_ptr<L2TPIPsecDriver> driver_;
MockCertificateFile* certificate_file_; // Owned by |driver_|.
base::WeakPtrFactory<L2TPIPsecDriverTest> weak_factory_;
};
const char L2TPIPsecDriverTest::kInterfaceName[] = "ppp0";
const int L2TPIPsecDriverTest::kInterfaceIndex = 123;
void L2TPIPsecDriverTest::GetLogin(std::string* /*user*/,
std::string* /*password*/) {}
void L2TPIPsecDriverTest::Notify(
const std::string& /*reason*/,
const std::map<std::string, std::string>& /*dict*/) {}
void L2TPIPsecDriverTest::ExpectInFlags(const std::vector<std::string>& options,
const std::string& flag,
const std::string& value) {
const auto flag_value =
base::StringPrintf("%s=%s", flag.c_str(), value.c_str());
EXPECT_TRUE(base::Contains(options, flag_value));
}
base::FilePath L2TPIPsecDriverTest::SetupPSKFile() {
base::FilePath psk_file;
EXPECT_TRUE(base::CreateTemporaryFileInDir(temp_dir_.GetPath(), &psk_file));
EXPECT_FALSE(psk_file.empty());
EXPECT_TRUE(base::PathExists(psk_file));
driver_->psk_file_ = psk_file;
return psk_file;
}
base::FilePath L2TPIPsecDriverTest::SetupXauthCredentialsFile() {
base::FilePath xauth_credentials_file;
EXPECT_TRUE(base::CreateTemporaryFileInDir(temp_dir_.GetPath(),
&xauth_credentials_file));
EXPECT_FALSE(xauth_credentials_file.empty());
EXPECT_TRUE(base::PathExists(xauth_credentials_file));
driver_->xauth_credentials_file_ = xauth_credentials_file;
return xauth_credentials_file;
}
TEST_F(L2TPIPsecDriverTest, GetProviderType) {
EXPECT_EQ(kProviderL2tpIpsec, GetProviderType());
}
TEST_F(L2TPIPsecDriverTest, Cleanup) {
driver_->Cleanup(); // Ensure no crash.
base::FilePath psk_file;
base::FilePath xauth_credentials_file;
FakeUpConnect(&psk_file, &xauth_credentials_file);
driver_->external_task_.reset(new MockExternalTask(
&control_, &process_manager_, weak_factory_.GetWeakPtr(),
base::Callback<void(pid_t, int)>()));
SetEventHandler(&event_handler_);
EXPECT_CALL(event_handler_,
OnDriverFailure(Service::kFailureBadPassphrase, _));
ExpectEndReasonMetricsReported(Service::kFailureBadPassphrase);
driver_->FailService(Service::kFailureBadPassphrase); // Trigger Cleanup.
EXPECT_TRUE(IsPSKFileCleared(psk_file));
EXPECT_TRUE(IsXauthCredentialsFileCleared(xauth_credentials_file));
EXPECT_FALSE(driver_->event_handler_);
EXPECT_FALSE(driver_->external_task_);
SetEventHandler(&event_handler_);
ExpectEndReasonMetricsReported(Service::kFailureDisconnect);
driver_->Disconnect();
EXPECT_FALSE(driver_->event_handler_);
}
TEST_F(L2TPIPsecDriverTest, DeleteTemporaryFiles) {
base::FilePath psk_file = SetupPSKFile();
base::FilePath xauth_credentials_file = SetupXauthCredentialsFile();
driver_->DeleteTemporaryFiles();
EXPECT_TRUE(IsPSKFileCleared(psk_file));
EXPECT_TRUE(IsXauthCredentialsFileCleared(xauth_credentials_file));
}
TEST_F(L2TPIPsecDriverTest, InitOptionsNoHost) {
Error error;
std::vector<std::string> options;
EXPECT_FALSE(driver_->InitOptions(&options, &error));
EXPECT_EQ(Error::kInvalidArguments, error.type());
EXPECT_TRUE(options.empty());
}
TEST_F(L2TPIPsecDriverTest, InitOptions) {
static const char kHost[] = "192.168.2.254";
static const char kPSK[] = "foobar";
static const char kXauthUser[] = "silly";
static const char kXauthPassword[] = "rabbit";
const std::vector<std::string> kCaCertPEM{"Insert PEM encoded data here"};
static const char kPEMCertfile[] = "/tmp/der-file-from-pem-cert";
base::FilePath pem_cert(kPEMCertfile);
SetArg(kProviderHostProperty, kHost);
SetArg(kL2TPIPsecPskProperty, kPSK);
SetArg(kL2TPIPsecXauthUserProperty, kXauthUser);
SetArg(kL2TPIPsecXauthPasswordProperty, kXauthPassword);
SetArgArray(kL2TPIPsecCaCertPemProperty, kCaCertPEM);
EXPECT_CALL(*certificate_file_, CreatePEMFromStrings(kCaCertPEM))
.WillOnce(Return(pem_cert));
const base::FilePath temp_dir(temp_dir_.GetPath());
// Once each for PSK and Xauth options.
EXPECT_CALL(manager_, run_path())
.WillOnce(ReturnRef(temp_dir))
.WillOnce(ReturnRef(temp_dir));
Error error;
std::vector<std::string> options;
EXPECT_TRUE(driver_->InitOptions(&options, &error));
EXPECT_TRUE(error.IsSuccess());
ExpectInFlags(options, "--remote_host", kHost);
ASSERT_FALSE(driver_->psk_file_.empty());
ExpectInFlags(options, "--psk_file", driver_->psk_file_.value());
ASSERT_FALSE(driver_->xauth_credentials_file_.empty());
ExpectInFlags(options, "--xauth_credentials_file",
driver_->xauth_credentials_file_.value());
ExpectInFlags(options, "--server_ca_file", kPEMCertfile);
}
TEST_F(L2TPIPsecDriverTest, InitPSKOptions) {
Error error;
std::vector<std::string> options;
static const char kPSK[] = "foobar";
const base::FilePath bad_dir("/non/existent/directory");
const base::FilePath temp_dir(temp_dir_.GetPath());
EXPECT_CALL(manager_, run_path())
.WillOnce(ReturnRef(bad_dir))
.WillOnce(ReturnRef(temp_dir));
EXPECT_TRUE(driver_->InitPSKOptions(&options, &error));
EXPECT_TRUE(options.empty());
EXPECT_TRUE(error.IsSuccess());
SetArg(kL2TPIPsecPskProperty, kPSK);
EXPECT_FALSE(driver_->InitPSKOptions(&options, &error));
EXPECT_TRUE(options.empty());
EXPECT_EQ(Error::kInternalError, error.type());
error.Reset();
EXPECT_TRUE(driver_->InitPSKOptions(&options, &error));
ASSERT_FALSE(driver_->psk_file_.empty());
ExpectInFlags(options, "--psk_file", driver_->psk_file_.value());
EXPECT_TRUE(error.IsSuccess());
std::string contents;
EXPECT_TRUE(base::ReadFileToString(driver_->psk_file_, &contents));
EXPECT_EQ(kPSK, contents);
struct stat buf;
ASSERT_EQ(0, stat(driver_->psk_file_.value().c_str(), &buf));
EXPECT_EQ(S_IFREG | S_IRUSR | S_IRGRP, buf.st_mode);
}
TEST_F(L2TPIPsecDriverTest, InitPEMOptions) {
const std::vector<std::string> kCaCertPEM{"Insert PEM encoded data here"};
static const char kPEMCertfile[] = "/tmp/der-file-from-pem-cert";
base::FilePath empty_cert;
base::FilePath pem_cert(kPEMCertfile);
SetArgArray(kL2TPIPsecCaCertPemProperty, kCaCertPEM);
EXPECT_CALL(*certificate_file_, CreatePEMFromStrings(kCaCertPEM))
.WillOnce(Return(empty_cert))
.WillOnce(Return(pem_cert));
std::vector<std::string> options;
driver_->InitPEMOptions(&options);
EXPECT_TRUE(options.empty());
driver_->InitPEMOptions(&options);
ExpectInFlags(options, "--server_ca_file", kPEMCertfile);
}
TEST_F(L2TPIPsecDriverTest, InitXauthOptions) {
std::vector<std::string> options;
EXPECT_CALL(manager_, run_path()).Times(0);
{
Error error;
EXPECT_TRUE(driver_->InitXauthOptions(&options, &error));
EXPECT_TRUE(error.IsSuccess());
}
EXPECT_TRUE(options.empty());
static const char kUser[] = "foobar";
SetArg(kL2TPIPsecXauthUserProperty, kUser);
{
Error error;
EXPECT_FALSE(driver_->InitXauthOptions(&options, &error));
EXPECT_EQ(Error::kInvalidArguments, error.type());
}
EXPECT_TRUE(options.empty());
static const char kPassword[] = "foobar";
SetArg(kL2TPIPsecXauthUserProperty, "");
SetArg(kL2TPIPsecXauthPasswordProperty, kPassword);
{
Error error;
EXPECT_FALSE(driver_->InitXauthOptions(&options, &error));
EXPECT_EQ(Error::kInvalidArguments, error.type());
}
EXPECT_TRUE(options.empty());
Mock::VerifyAndClearExpectations(&manager_);
SetArg(kL2TPIPsecXauthUserProperty, kUser);
const base::FilePath bad_dir("/non/existent/directory");
const base::FilePath temp_dir(temp_dir_.GetPath());
EXPECT_CALL(manager_, run_path())
.WillOnce(ReturnRef(bad_dir))
.WillOnce(ReturnRef(temp_dir));
{
Error error;
EXPECT_FALSE(driver_->InitXauthOptions(&options, &error));
EXPECT_EQ(Error::kInternalError, error.type());
}
EXPECT_TRUE(options.empty());
{
Error error;
EXPECT_TRUE(driver_->InitXauthOptions(&options, &error));
EXPECT_TRUE(error.IsSuccess());
}
ASSERT_FALSE(driver_->xauth_credentials_file_.empty());
ExpectInFlags(options, "--xauth_credentials_file",
driver_->xauth_credentials_file_.value());
std::string contents;
EXPECT_TRUE(
base::ReadFileToString(driver_->xauth_credentials_file_, &contents));
std::string expected_contents(std::string(kUser) + "\n" + kPassword + "\n");
EXPECT_EQ(expected_contents, contents);
struct stat buf;
ASSERT_EQ(0, stat(driver_->xauth_credentials_file_.value().c_str(), &buf));
EXPECT_EQ(S_IFREG | S_IRUSR | S_IRGRP, buf.st_mode);
}
TEST_F(L2TPIPsecDriverTest, AppendValueOption) {
static const char kOption[] = "--l2tpipsec-option";
static const char kProperty[] = "L2TPIPsec.SomeProperty";
static const char kValue[] = "some-property-value";
static const char kOption2[] = "--l2tpipsec-option2";
static const char kProperty2[] = "L2TPIPsec.SomeProperty2";
static const char kValue2[] = "some-property-value2";
std::vector<std::string> options;
EXPECT_FALSE(driver_->AppendValueOption("L2TPIPsec.UnknownProperty", kOption,
&options));
EXPECT_TRUE(options.empty());
SetArg(kProperty, "");
EXPECT_FALSE(driver_->AppendValueOption(kProperty, kOption, &options));
EXPECT_TRUE(options.empty());
SetArg(kProperty, kValue);
SetArg(kProperty2, kValue2);
EXPECT_TRUE(driver_->AppendValueOption(kProperty, kOption, &options));
EXPECT_TRUE(driver_->AppendValueOption(kProperty2, kOption2, &options));
EXPECT_EQ(2, options.size());
EXPECT_EQ(base::StringPrintf("%s=%s", kOption, kValue), options[0]);
EXPECT_EQ(base::StringPrintf("%s=%s", kOption2, kValue2), options[1]);
}
TEST_F(L2TPIPsecDriverTest, AppendFlag) {
static const char kTrueOption[] = "--l2tpipsec-option";
static const char kFalseOption[] = "--nol2tpipsec-option";
static const char kProperty[] = "L2TPIPsec.SomeProperty";
static const char kTrueOption2[] = "--l2tpipsec-option2";
static const char kFalseOption2[] = "--nol2tpipsec-option2";
static const char kProperty2[] = "L2TPIPsec.SomeProperty2";
std::vector<std::string> options;
EXPECT_FALSE(driver_->AppendFlag("L2TPIPsec.UnknownProperty", kTrueOption,
kFalseOption, &options));
EXPECT_TRUE(options.empty());
SetArg(kProperty, "");
EXPECT_FALSE(
driver_->AppendFlag(kProperty, kTrueOption, kFalseOption, &options));
EXPECT_TRUE(options.empty());
SetArg(kProperty, "true");
SetArg(kProperty2, "false");
EXPECT_TRUE(
driver_->AppendFlag(kProperty, kTrueOption, kFalseOption, &options));
EXPECT_TRUE(
driver_->AppendFlag(kProperty2, kTrueOption2, kFalseOption2, &options));
EXPECT_EQ(2, options.size());
EXPECT_EQ(kTrueOption, options[0]);
EXPECT_EQ(kFalseOption2, options[1]);
}
TEST_F(L2TPIPsecDriverTest, GetLogin) {
static const char kUser[] = "joesmith";
static const char kPassword[] = "random-password";
std::string user, password;
SetArg(kL2TPIPsecUserProperty, kUser);
SetArg(kL2TPIPsecUseLoginPasswordProperty, "false");
driver_->GetLogin(&user, &password);
EXPECT_TRUE(user.empty());
EXPECT_TRUE(password.empty());
SetArg(kL2TPIPsecUserProperty, "");
SetArg(kL2TPIPsecPasswordProperty, kPassword);
driver_->GetLogin(&user, &password);
EXPECT_TRUE(user.empty());
EXPECT_TRUE(password.empty());
SetArg(kL2TPIPsecUserProperty, kUser);
driver_->GetLogin(&user, &password);
EXPECT_EQ(kUser, user);
EXPECT_EQ(kPassword, password);
}
TEST_F(L2TPIPsecDriverTest, UseLoginPassword) {
static const char kUser[] = "joesmith";
static const char kPassword[] = "random-password";
std::string user, password;
SetArg(kL2TPIPsecUserProperty, kUser);
SetArg(kL2TPIPsecUseLoginPasswordProperty, "true");
driver_->GetLogin(&user, &password);
EXPECT_TRUE(user.empty());
EXPECT_TRUE(password.empty());
SaveLoginPassword(kPassword);
driver_->GetLogin(&user, &password);
EXPECT_EQ(kUser, user);
EXPECT_EQ(kPassword, password);
}
TEST_F(L2TPIPsecDriverTest, OnL2TPIPsecVPNDied) {
const int kPID = 123456;
SetEventHandler(&event_handler_);
EXPECT_CALL(event_handler_, OnDriverFailure(Service::kFailureDNSLookup, _));
ExpectEndReasonMetricsReported(Service::kFailureDNSLookup);
driver_->OnL2TPIPsecVPNDied(kPID,
vpn_manager::kServiceErrorResolveHostnameFailed);
EXPECT_FALSE(driver_->event_handler_);
}
TEST_F(L2TPIPsecDriverTest, SpawnL2TPIPsecVPN) {
Error error;
// Fail without sufficient arguments.
EXPECT_FALSE(driver_->SpawnL2TPIPsecVPN(&error));
EXPECT_TRUE(error.IsFailure());
// Provide the required arguments.
static const char kHost[] = "192.168.2.254";
SetArg(kProviderHostProperty, kHost);
EXPECT_CALL(process_manager_,
StartProcessInMinijail(
_, _, _, _, MinijailOptionsMatchCloseNonstdFDs(true), _))
.WillOnce(Return(-1))
.WillOnce(Return(1));
EXPECT_FALSE(driver_->SpawnL2TPIPsecVPN(&error));
EXPECT_FALSE(driver_->external_task_);
EXPECT_TRUE(driver_->SpawnL2TPIPsecVPN(&error));
EXPECT_NE(nullptr, driver_->external_task_);
}
TEST_F(L2TPIPsecDriverTest, Connect) {
static const char kHost[] = "192.168.2.254";
SetArg(kProviderHostProperty, kHost);
EXPECT_CALL(process_manager_,
StartProcessInMinijail(
_, _, _, _, MinijailOptionsMatchCloseNonstdFDs(true), _))
.WillOnce(Return(1));
base::TimeDelta timeout = driver_->ConnectAsync(&event_handler_);
EXPECT_NE(timeout, VPNDriver::kTimeoutNone);
}
TEST_F(L2TPIPsecDriverTest, Disconnect) {
SetEventHandler(&event_handler_);
ExpectEndReasonMetricsReported(Service::kFailureDisconnect);
driver_->Disconnect();
EXPECT_FALSE(driver_->event_handler_);
}
TEST_F(L2TPIPsecDriverTest, OnConnectTimeout) {
SetEventHandler(&event_handler_);
EXPECT_CALL(event_handler_, OnDriverFailure(Service::kFailureConnect, _));
ExpectEndReasonMetricsReported(Service::kFailureConnect);
driver_->OnConnectTimeout();
EXPECT_FALSE(driver_->event_handler_);
}
TEST_F(L2TPIPsecDriverTest, InitPropertyStore) {
// Quick test property store initialization.
PropertyStore store;
driver_->InitPropertyStore(&store);
const std::string kUser = "joe";
Error error;
store.SetStringProperty(kL2TPIPsecUserProperty, kUser, &error);
EXPECT_TRUE(error.IsSuccess());
EXPECT_EQ(kUser, GetArgs()->Lookup<std::string>(kL2TPIPsecUserProperty, ""));
}
TEST_F(L2TPIPsecDriverTest, GetProvider) {
PropertyStore store;
driver_->InitPropertyStore(&store);
{
KeyValueStore props;
Error error;
SetArg(kL2TPIPsecClientCertIdProperty, "");
EXPECT_TRUE(
store.GetKeyValueStoreProperty(kProviderProperty, &props, &error));
EXPECT_TRUE(props.Lookup<bool>(kPassphraseRequiredProperty, false));
EXPECT_TRUE(props.Lookup<bool>(kL2TPIPsecPskRequiredProperty, false));
}
{
KeyValueStore props;
Error error;
SetArg(kL2TPIPsecClientCertIdProperty, "some-cert-id");
EXPECT_TRUE(
store.GetKeyValueStoreProperty(kProviderProperty, &props, &error));
EXPECT_TRUE(props.Lookup<bool>(kPassphraseRequiredProperty, false));
EXPECT_FALSE(props.Lookup<bool>(kL2TPIPsecPskRequiredProperty, true));
SetArg(kL2TPIPsecClientCertIdProperty, "");
}
{
KeyValueStore props;
SetArg(kL2TPIPsecPasswordProperty, "random-password");
SetArg(kL2TPIPsecPskProperty, "random-psk");
Error error;
EXPECT_TRUE(
store.GetKeyValueStoreProperty(kProviderProperty, &props, &error));
EXPECT_FALSE(props.Lookup<bool>(kPassphraseRequiredProperty, true));
EXPECT_FALSE(props.Lookup<bool>(kL2TPIPsecPskRequiredProperty, true));
EXPECT_FALSE(props.Contains<std::string>(kL2TPIPsecPasswordProperty));
}
}
TEST_F(L2TPIPsecDriverTest, Notify) {
std::map<std::string, std::string> config{
{kPPPInterfaceName, kInterfaceName}};
base::FilePath psk_file;
base::FilePath xauth_credentials_file;
FakeUpConnect(&psk_file, &xauth_credentials_file);
// Make sure that a notification of an intermediate state doesn't cause
// the driver to fail the connection.
EXPECT_CALL(event_handler_, OnDriverConnected(_, _)).Times(0);
EXPECT_CALL(event_handler_, OnDriverFailure(_, _)).Times(0);
EXPECT_TRUE(driver_->event_handler_);
InvokeNotify(kPPPReasonAuthenticating, config);
EXPECT_TRUE(driver_->event_handler_);
InvokeNotify(kPPPReasonAuthenticated, config);
EXPECT_TRUE(driver_->event_handler_);
ExpectMetricsReported();
EXPECT_CALL(event_handler_,
OnDriverConnected(kInterfaceName, kInterfaceIndex));
EXPECT_CALL(device_info_, GetIndex(kInterfaceName))
.WillOnce(Return(kInterfaceIndex));
InvokeNotify(kPPPReasonConnect, config);
EXPECT_TRUE(IsPSKFileCleared(psk_file));
EXPECT_TRUE(IsXauthCredentialsFileCleared(xauth_credentials_file));
}
TEST_F(L2TPIPsecDriverTest, NotifyWithoutDeviceInfoReady) {
std::map<std::string, std::string> config{
{kPPPInterfaceName, kInterfaceName}};
base::FilePath psk_file;
base::FilePath xauth_credentials_file;
FakeUpConnect(&psk_file, &xauth_credentials_file);
DeviceInfo::LinkReadyCallback link_ready_callback;
EXPECT_CALL(event_handler_, OnDriverConnected(_, _)).Times(0);
EXPECT_CALL(device_info_, GetIndex(kInterfaceName)).WillOnce(Return(-1));
EXPECT_CALL(device_info_, AddVirtualInterfaceReadyCallback(kInterfaceName, _))
.WillOnce([&link_ready_callback](const std::string&,
DeviceInfo::LinkReadyCallback callback) {
link_ready_callback = std::move(callback);
});
InvokeNotify(kPPPReasonConnect, config);
EXPECT_CALL(event_handler_,
OnDriverConnected(kInterfaceName, kInterfaceIndex));
std::move(link_ready_callback).Run(kInterfaceName, kInterfaceIndex);
}
TEST_F(L2TPIPsecDriverTest, NotifyDisconnected) {
std::map<std::string, std::string> dict;
SetEventHandler(&event_handler_);
base::Callback<void(pid_t, int)> death_callback;
MockExternalTask* local_external_task = new MockExternalTask(
&control_, &process_manager_, weak_factory_.GetWeakPtr(), death_callback);
driver_->external_task_.reset(local_external_task); // passes ownership
EXPECT_CALL(event_handler_, OnDriverFailure(_, _));
ExpectEndReasonMetricsReported(Service::kFailureUnknown);
EXPECT_CALL(*local_external_task, OnDelete());
driver_->Notify(kPPPReasonDisconnect, dict);
EXPECT_EQ(nullptr, driver_->external_task_);
}
} // namespace shill
| 38.387097 | 315 | 0.724739 | [
"vector"
] |
d43f5973c672f50740ed609dbe5489115fc54a86 | 7,171 | cpp | C++ | src/CwshInPlaceCommand.cpp | colinw7/Cwsh | f39e93ca48e92b14a55c1dce8c85b37843cff81e | [
"MIT"
] | 1 | 2021-12-23T02:22:56.000Z | 2021-12-23T02:22:56.000Z | src/CwshInPlaceCommand.cpp | colinw7/Cwsh | f39e93ca48e92b14a55c1dce8c85b37843cff81e | [
"MIT"
] | null | null | null | src/CwshInPlaceCommand.cpp | colinw7/Cwsh | f39e93ca48e92b14a55c1dce8c85b37843cff81e | [
"MIT"
] | null | null | null | #include <CwshI.h>
CwshInPlaceCommand::
CwshInPlaceCommand(Cwsh *cwsh, const CwshWord &word) :
cwsh_(cwsh), word_(word)
{
}
bool
CwshInPlaceCommand::
expand(CwshWordArray &words)
{
bool flag = false;
const CwshSubWordArray &sub_words = word_.getSubWords();
std::string str1;
int num_sub_words = sub_words.size();
for (int i = 0; i < num_sub_words; i++) {
CwshSubWordType type = sub_words[i].getType();
std::string sub_str;
if (type == CwshSubWordType::BACK_QUOTED) {
sub_str = expandCommand(sub_words[i].getWord());
flag = true;
}
else if (type == CwshSubWordType::DOUBLE_QUOTED) {
std::string sub_str1;
if (expandQuotedWord(CwshWord(sub_words[i].getWord()), sub_str1)) {
sub_str = '"' + sub_str1 + '"';
flag = true;
}
else
sub_str = sub_words[i].getString();
}
else
sub_str = sub_words[i].getString();
str1 += sub_str;
}
if (flag) {
CwshWord::toWords(str1, words);
if (cwsh_->getDebug()) {
std::cerr << "Expand In Place String to Words" << std::endl;
CwshWord::printWords(words);
}
}
return flag;
}
bool
CwshInPlaceCommand::
expandQuotedWord(const CwshWord &word, std::string &word1)
{
bool flag = false;
const CwshSubWordArray &sub_words = word.getSubWords();
int num_sub_words = sub_words.size();
for (int i = 0; i < num_sub_words; i++) {
CwshSubWordType type = sub_words[i].getType();
std::string sub_word;
if (type == CwshSubWordType::BACK_QUOTED) {
sub_word = expandCommand(sub_words[i].getWord());
flag = true;
}
else
sub_word = sub_words[i].getString();
word1 += sub_word;
}
return flag;
}
std::string
CwshInPlaceCommand::
expandCommand(const std::string &str)
{
// Convert Line to Command Groups
CwshCmdGroupArray groups;
CwshCommandUtil::parseCommandGroups(cwsh_, str, groups);
//------
std::string output;
int num_groups = groups.size();
for (int i = 0; i < num_groups; i++) {
CwshCmdArray cmds = CwshCommandUtil::parseCommandGroup(cwsh_, groups[i]);
//------
// Execute Commands
output = executeCommands(cmds);
}
//------
for (auto &group : groups)
delete group;
//------
if (cwsh_->getDebug()) {
std::cerr << "Expand Command '" << str << "' to '" << output << "'" << std::endl;
}
return output;
}
std::string
CwshInPlaceCommand::
executeCommands(const CwshCmdArray &cmds)
{
std::string output;
//------
// Execute Commands
std::vector<CwshCommandData *> pcommands;
int num_cmds = cmds.size();
for (int i = 0; i < num_cmds; i++) {
if (cwsh_->getDebug()) {
std::cerr << "Execute Command: ";
cmds[i]->display();
}
CwshCmdSeparatorType separator = cmds[i]->getSeparator().getType();
// Get Command
std::vector<std::string> words;
int num_words = cmds[i]->getNumWords();
for (int j = 0; j < num_words; j++)
words.push_back(cmds[i]->getWord(j).getWord());
CAutoPtr<CwshCommandData> command;
command = new CwshCommandData(cwsh_, words);
CwshCommand *command1 = command->getCommand();
if (! command1)
continue;
// Set Redirection
if (cmds[i]->hasStdInFile())
command1->addFileSrc(cmds[i]->getStdInFile());
if (cmds[i]->hasStdOutFile()) {
command1->addFileDest(cmds[i]->getStdOutFile(), 1);
CwshVariable *variable = cwsh_->lookupVariable("noclobber");
if (cmds[i]->getStdOutClobber() || ! variable)
command1->setFileDestOverwrite(true, 1);
else
command1->setFileDestOverwrite(false, 1);
if (cmds[i]->getStdOutAppend())
command1->setFileDestAppend(true, 1);
}
if (cmds[i]->hasStdErrFile()) {
if (! cmds[i]->hasStdOutFile()) {
command1->addFileDest(cmds[i]->getStdErrFile(), 1);
CwshVariable *variable = cwsh_->lookupVariable("noclobber");
if (cmds[i]->getStdErrClobber() || ! variable)
command1->setFileDestOverwrite(true, 1);
else
command1->setFileDestOverwrite(false, 1);
if (cmds[i]->getStdErrAppend())
command1->setFileDestAppend(true, 1);
}
command1->addFileDest(cmds[i]->getStdErrFile(), 2);
CwshVariable *variable = cwsh_->lookupVariable("noclobber");
if (cmds[i]->getStdErrClobber() || ! variable)
command1->setFileDestOverwrite(true, 2);
else
command1->setFileDestOverwrite(false, 2);
if (cmds[i]->getStdErrAppend())
command1->setFileDestAppend(true, 2);
}
// Run Command
if (separator != CwshCmdSeparatorType::PIPE &&
separator != CwshCmdSeparatorType::PIPE_ERR) {
int num_pcommands = pcommands.size();
if (num_pcommands > 0) {
command1->addPipeSrc();
for (int k = 0; k < num_pcommands - 1; k++)
pcommands[k]->getCommand()->start();
pcommands[num_pcommands - 1]->getCommand()->start();
int numPCmds = cmds.size();
if (i == numPCmds - 1) {
command1->addStringDest(output);
separator = CwshCmdSeparatorType::NORMAL;
}
command1->start();
for (int k = 0; k < num_pcommands; k++)
pcommands[k]->getCommand()->wait();
if (separator != CwshCmdSeparatorType::BACKGROUND) {
command1->wait();
int status = command1->getReturnCode();
cwsh_->defineVariable("status", status);
for (auto &pcommand : pcommands)
delete pcommand;
if (separator == CwshCmdSeparatorType::AND && status != 0)
break;
if (separator == CwshCmdSeparatorType::OR && status == 0)
break;
}
else {
CwshProcess *process = cwsh_->addProcess(command.release());
int pid = command1->getPid();
std::cout << "[" << process->getNum() << "] " << pid << std::endl;
}
pcommands.clear();
}
else {
int numPCmds = cmds.size();
if (i == numPCmds - 1) {
command1->addStringDest(output);
separator = CwshCmdSeparatorType::NORMAL;
}
command1->start();
if (separator != CwshCmdSeparatorType::BACKGROUND) {
command1->wait();
int status = command1->getReturnCode();
cwsh_->defineVariable("status", status);
if (separator == CwshCmdSeparatorType::AND && status != 0)
break;
if (separator == CwshCmdSeparatorType::OR && status == 0)
break;
}
else {
CwshProcess *process = cwsh_->addProcess(command.release());
int pid = command1->getPid();
std::cout << "[" << process->getNum() << "] " << pid << std::endl;
}
}
}
else {
if (pcommands.size() > 0)
command1->addPipeSrc();
if (separator == CwshCmdSeparatorType::PIPE)
command1->addPipeDest(1);
else {
command1->addPipeDest(1);
command1->addPipeDest(2);
}
pcommands.push_back(command.release());
}
}
return CStrUtil::compressSpaces(output);
}
| 22.339564 | 85 | 0.583601 | [
"vector"
] |
d442209f2c1156b20e22b75e445eee000a811ef3 | 9,857 | cpp | C++ | packages/CLPBN/clpbn/bp/CFactorGraph.cpp | miar/yap-6.3 | 6b2121d03942ba821da87a829b86ce40caf06585 | [
"Artistic-1.0-Perl",
"ClArtistic"
] | null | null | null | packages/CLPBN/clpbn/bp/CFactorGraph.cpp | miar/yap-6.3 | 6b2121d03942ba821da87a829b86ce40caf06585 | [
"Artistic-1.0-Perl",
"ClArtistic"
] | null | null | null | packages/CLPBN/clpbn/bp/CFactorGraph.cpp | miar/yap-6.3 | 6b2121d03942ba821da87a829b86ce40caf06585 | [
"Artistic-1.0-Perl",
"ClArtistic"
] | null | null | null |
#include "CFactorGraph.h"
#include "Factor.h"
bool CFactorGraph::checkForIdenticalFactors = true;
CFactorGraph::CFactorGraph (const FactorGraph& fg)
{
groundFg_ = &fg;
freeColor_ = 0;
const VarNodes& varNodes = fg.varNodes();
varSignatures_.reserve (varNodes.size());
for (unsigned i = 0; i < varNodes.size(); i++) {
unsigned c = (varNodes[i]->neighbors().size() * 2) + 1;
varSignatures_.push_back (Signature (c));
}
const FacNodes& facNodes = fg.facNodes();
facSignatures_.reserve (facNodes.size());
for (unsigned i = 0; i < facNodes.size(); i++) {
unsigned c = facNodes[i]->neighbors().size() + 1;
facSignatures_.push_back (Signature (c));
}
varColors_.resize (varNodes.size());
facColors_.resize (facNodes.size());
setInitialColors();
createGroups();
}
CFactorGraph::~CFactorGraph (void)
{
for (unsigned i = 0; i < varClusters_.size(); i++) {
delete varClusters_[i];
}
for (unsigned i = 0; i < facClusters_.size(); i++) {
delete facClusters_[i];
}
}
void
CFactorGraph::setInitialColors (void)
{
// create the initial variable colors
VarColorMap colorMap;
const VarNodes& varNodes = groundFg_->varNodes();
for (unsigned i = 0; i < varNodes.size(); i++) {
unsigned dsize = varNodes[i]->range();
VarColorMap::iterator it = colorMap.find (dsize);
if (it == colorMap.end()) {
it = colorMap.insert (make_pair (
dsize, vector<Color> (dsize+1,-1))).first;
}
unsigned idx;
if (varNodes[i]->hasEvidence()) {
idx = varNodes[i]->getEvidence();
} else {
idx = dsize;
}
vector<Color>& stateColors = it->second;
if (stateColors[idx] == -1) {
stateColors[idx] = getFreeColor();
}
setColor (varNodes[i], stateColors[idx]);
}
const FacNodes& facNodes = groundFg_->facNodes();
for (unsigned i = 0; i < facNodes.size(); i++) {
facNodes[i]->factor().setDistId (Util::maxUnsigned());
}
// FIXME FIXME FIXME : pfl should give correct dist ids.
if (checkForIdenticalFactors || true) {
unsigned groupCount = 1;
for (unsigned i = 0; i < facNodes.size(); i++) {
Factor& f1 = facNodes[i]->factor();
if (f1.distId() != Util::maxUnsigned()) {
continue;
}
f1.setDistId (groupCount);
for (unsigned j = i + 1; j < facNodes.size(); j++) {
Factor& f2 = facNodes[j]->factor();
if (f2.distId() != Util::maxUnsigned()) {
continue;
}
if (f1.size() == f2.size() &&
f1.ranges() == f2.ranges() &&
f1.params() == f2.params()) {
f2.setDistId (groupCount);
}
}
groupCount ++;
}
}
// create the initial factor colors
DistColorMap distColors;
for (unsigned i = 0; i < facNodes.size(); i++) {
unsigned distId = facNodes[i]->factor().distId();
DistColorMap::iterator it = distColors.find (distId);
if (it == distColors.end()) {
it = distColors.insert (make_pair (distId, getFreeColor())).first;
}
setColor (facNodes[i], it->second);
}
}
void
CFactorGraph::createGroups (void)
{
VarSignMap varGroups;
FacSignMap facGroups;
unsigned nIters = 0;
bool groupsHaveChanged = true;
const VarNodes& varNodes = groundFg_->varNodes();
const FacNodes& facNodes = groundFg_->facNodes();
while (groupsHaveChanged || nIters == 1) {
nIters ++;
unsigned prevFactorGroupsSize = facGroups.size();
facGroups.clear();
// set a new color to the factors with the same signature
for (unsigned i = 0; i < facNodes.size(); i++) {
const Signature& signature = getSignature (facNodes[i]);
FacSignMap::iterator it = facGroups.find (signature);
if (it == facGroups.end()) {
it = facGroups.insert (make_pair (signature, FacNodes())).first;
}
it->second.push_back (facNodes[i]);
}
for (FacSignMap::iterator it = facGroups.begin();
it != facGroups.end(); it++) {
Color newColor = getFreeColor();
FacNodes& groupMembers = it->second;
for (unsigned i = 0; i < groupMembers.size(); i++) {
setColor (groupMembers[i], newColor);
}
}
// set a new color to the variables with the same signature
unsigned prevVarGroupsSize = varGroups.size();
varGroups.clear();
for (unsigned i = 0; i < varNodes.size(); i++) {
const Signature& signature = getSignature (varNodes[i]);
VarSignMap::iterator it = varGroups.find (signature);
if (it == varGroups.end()) {
it = varGroups.insert (make_pair (signature, VarNodes())).first;
}
it->second.push_back (varNodes[i]);
}
for (VarSignMap::iterator it = varGroups.begin();
it != varGroups.end(); it++) {
Color newColor = getFreeColor();
VarNodes& groupMembers = it->second;
for (unsigned i = 0; i < groupMembers.size(); i++) {
setColor (groupMembers[i], newColor);
}
}
groupsHaveChanged = prevVarGroupsSize != varGroups.size()
|| prevFactorGroupsSize != facGroups.size();
}
printGroups (varGroups, facGroups);
createClusters (varGroups, facGroups);
}
void
CFactorGraph::createClusters (
const VarSignMap& varGroups,
const FacSignMap& facGroups)
{
varClusters_.reserve (varGroups.size());
for (VarSignMap::const_iterator it = varGroups.begin();
it != varGroups.end(); it++) {
const VarNodes& groupVars = it->second;
VarCluster* vc = new VarCluster (groupVars);
for (unsigned i = 0; i < groupVars.size(); i++) {
vid2VarCluster_.insert (make_pair (groupVars[i]->varId(), vc));
}
varClusters_.push_back (vc);
}
facClusters_.reserve (facGroups.size());
for (FacSignMap::const_iterator it = facGroups.begin();
it != facGroups.end(); it++) {
FacNode* groupFactor = it->second[0];
const VarNodes& neighs = groupFactor->neighbors();
VarClusters varClusters;
varClusters.reserve (neighs.size());
for (unsigned i = 0; i < neighs.size(); i++) {
VarId vid = neighs[i]->varId();
varClusters.push_back (vid2VarCluster_.find (vid)->second);
}
facClusters_.push_back (new FacCluster (it->second, varClusters));
}
}
const Signature&
CFactorGraph::getSignature (const VarNode* varNode)
{
Signature& sign = varSignatures_[varNode->getIndex()];
vector<Color>::iterator it = sign.colors.begin();
const FacNodes& neighs = varNode->neighbors();
for (unsigned i = 0; i < neighs.size(); i++) {
*it = getColor (neighs[i]);
it ++;
*it = neighs[i]->factor().indexOf (varNode->varId());
it ++;
}
*it = getColor (varNode);
return sign;
}
const Signature&
CFactorGraph::getSignature (const FacNode* facNode)
{
Signature& sign = facSignatures_[facNode->getIndex()];
vector<Color>::iterator it = sign.colors.begin();
const VarNodes& neighs = facNode->neighbors();
for (unsigned i = 0; i < neighs.size(); i++) {
*it = getColor (neighs[i]);
it ++;
}
*it = getColor (facNode);
return sign;
}
FactorGraph*
CFactorGraph::getGroundFactorGraph (void) const
{
FactorGraph* fg = new FactorGraph();
for (unsigned i = 0; i < varClusters_.size(); i++) {
VarNode* var = varClusters_[i]->getGroundVarNodes()[0];
VarNode* newVar = new VarNode (var);
varClusters_[i]->setRepresentativeVariable (newVar);
fg->addVarNode (newVar);
}
for (unsigned i = 0; i < facClusters_.size(); i++) {
const VarClusters& myVarClusters = facClusters_[i]->getVarClusters();
Vars myGroundVars;
myGroundVars.reserve (myVarClusters.size());
for (unsigned j = 0; j < myVarClusters.size(); j++) {
VarNode* v = myVarClusters[j]->getRepresentativeVariable();
myGroundVars.push_back (v);
}
FacNode* fn = new FacNode (Factor (myGroundVars,
facClusters_[i]->getGroundFactors()[0]->factor().params()));
facClusters_[i]->setRepresentativeFactor (fn);
fg->addFacNode (fn);
for (unsigned j = 0; j < myGroundVars.size(); j++) {
fg->addEdge (static_cast<VarNode*> (myGroundVars[j]), fn);
}
}
return fg;
}
unsigned
CFactorGraph::getEdgeCount (
const FacCluster* fc,
const VarCluster* vc) const
{
unsigned count = 0;
VarId vid = vc->getGroundVarNodes().front()->varId();
const FacNodes& clusterGroundFactors = fc->getGroundFactors();
for (unsigned i = 0; i < clusterGroundFactors.size(); i++) {
if (clusterGroundFactors[i]->factor().contains (vid)) {
count ++;
}
}
// CVarNodes vars = vc->getGroundVarNodes();
// for (unsigned i = 1; i < vars.size(); i++) {
// VarNode* var = vc->getGroundVarNodes()[i];
// unsigned count2 = 0;
// for (unsigned i = 0; i < clusterGroundFactors.size(); i++) {
// if (clusterGroundFactors[i]->getPosition (var) != -1) {
// count2 ++;
// }
// }
// if (count != count2) { cout << "oops!" << endl; abort(); }
// }
return count;
}
void
CFactorGraph::printGroups (
const VarSignMap& varGroups,
const FacSignMap& facGroups) const
{
unsigned count = 1;
cout << "variable groups:" << endl;
for (VarSignMap::const_iterator it = varGroups.begin();
it != varGroups.end(); it++) {
const VarNodes& groupMembers = it->second;
if (groupMembers.size() > 0) {
cout << count << ": " ;
for (unsigned i = 0; i < groupMembers.size(); i++) {
cout << groupMembers[i]->label() << " " ;
}
count ++;
cout << endl;
}
}
count = 1;
cout << endl << "factor groups:" << endl;
for (FacSignMap::const_iterator it = facGroups.begin();
it != facGroups.end(); it++) {
const FacNodes& groupMembers = it->second;
if (groupMembers.size() > 0) {
cout << ++count << ": " ;
for (unsigned i = 0; i < groupMembers.size(); i++) {
cout << groupMembers[i]->getLabel() << " " ;
}
count ++;
cout << endl;
}
}
}
| 28.991176 | 73 | 0.610733 | [
"vector"
] |
d447ae09a867b27f4ab8f0b3f7d3aed1bab25f45 | 2,080 | cpp | C++ | src/intheap.cpp | vnetserg/contraction | 9cbc47841359121a1cc7c632f3d2ee02ef6c05fb | [
"MIT"
] | 1 | 2021-03-18T03:13:49.000Z | 2021-03-18T03:13:49.000Z | src/intheap.cpp | vnetserg/contraction | 9cbc47841359121a1cc7c632f3d2ee02ef6c05fb | [
"MIT"
] | null | null | null | src/intheap.cpp | vnetserg/contraction | 9cbc47841359121a1cc7c632f3d2ee02ef6c05fb | [
"MIT"
] | 1 | 2019-10-14T14:35:56.000Z | 2019-10-14T14:35:56.000Z | #include <vector>
#include <math.h>
#include "../include/intheap.hpp"
// PUBLIC
IntHeap::IntHeap(int64_t max_size) : pos(max_size, -1)
{
heap.reserve(sqrt(max_size));
}
void IntHeap::push(int64_t el, int64_t prio)
{
pos[el] = heap.size();
heap.push_back(HeapItem(el, prio));
swim(heap.size()-1);
}
bool IntHeap::hasElement(int64_t el)
{
return pos[el] != -1;
}
int64_t IntHeap::priority(int64_t el)
{
return heap[pos[el]].prio;
}
void IntHeap::decreasePriority(int64_t el, int64_t prio)
{
int64_t p = pos[el];
heap[p].prio = prio;
swim(p);
}
void IntHeap::clear()
{
for (auto &e : heap)
pos[e.el] = -1;
heap.clear();
}
void IntHeap::pop()
{
pos[heap[0].el] = -1;
if (heap.size() > 1)
{
heap[0] = heap[heap.size()-1];
pos[heap[0].el] = 0;
}
heap.pop_back();
if (!heap.empty())
{
sink(0);
}
}
IntHeap::HeapItem IntHeap::top()
{
return heap[0];
}
std::vector<IntHeap::HeapItem>::const_iterator IntHeap::cbegin() const
{
return heap.cbegin();
}
std::vector<IntHeap::HeapItem>::const_iterator IntHeap::cend() const
{
return heap.cend();
}
bool IntHeap::empty()
{
return heap.empty();
}
// PRIVATE
void IntHeap::swim(int64_t i)
{
while (i > 0 && heap[parent(i)].prio > heap[i].prio)
{
swap(i, parent(i));
i = parent(i);
}
}
void IntHeap::sink(int64_t i)
{
while(true)
{
int64_t c1 = child(i), c2 = c1+1;
int64_t min = i;
if (c1 < heap.size() && heap[c1].prio < heap[min].prio)
min = c1;
if (c2 < heap.size() && heap[c2].prio < heap[min].prio)
min = c2;
if (min != i)
{
swap(i, min);
i = min;
}
else
return;
}
}
inline int64_t IntHeap::parent(int64_t i)
{
return (i-1)/2;
}
inline int64_t IntHeap::child(int64_t i)
{
return 2*i + 1;
}
inline void IntHeap::swap(int64_t i, int64_t j)
{
pos[heap[i].el] = j;
pos[heap[j].el] = i;
std::swap(heap[i], heap[j]);
}
| 16.25 | 70 | 0.543269 | [
"vector"
] |
d44d79563d7e523e9592ff106edf061aec3b69ba | 34,023 | cpp | C++ | src/ardrone_driver.cpp | Hurisa/ardrone_autonomy | 1f897b3ed8f74d4cc176cd5867e9152faee20f3b | [
"BSD-3-Clause"
] | null | null | null | src/ardrone_driver.cpp | Hurisa/ardrone_autonomy | 1f897b3ed8f74d4cc176cd5867e9152faee20f3b | [
"BSD-3-Clause"
] | null | null | null | src/ardrone_driver.cpp | Hurisa/ardrone_autonomy | 1f897b3ed8f74d4cc176cd5867e9152faee20f3b | [
"BSD-3-Clause"
] | null | null | null | /**
Software License Agreement (BSD)
\file ardrone_driver.cpp
\authors Mani Monajjemi <mmonajje@sfu.ca>
\copyright Copyright (c) 2012, Autonomy Lab (Simon Fraser University), All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Autonomy Lab nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WAR-
RANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, IN-
DIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <signal.h>
#include <string>
#include <algorithm>
#include <vector>
#include <ardrone_autonomy/ardrone_driver.h>
#include <ardrone_autonomy/teleop_twist.h>
#include <ardrone_autonomy/video.h>
////////////////////////////////////////////////////////////////////////////////
// class ARDroneDriver
////////////////////////////////////////////////////////////////////////////////
ARDroneDriver::ARDroneDriver()
: private_nh("~"),
image_transport(node_handle),
// Ugly: This has been defined in the template file. Cleaner way to guarantee initilaztion?
initialized_navdata_publishers(false),
last_frame_id(-1),
last_navdata_id(-1),
is_inited(false),
last_receive_time(0.0)
{
cmd_vel_sub = node_handle.subscribe("cmd_vel", 1, &CmdVelCallback);
takeoff_sub = node_handle.subscribe("ardrone/takeoff", 1, &TakeoffCallback);
reset_sub = node_handle.subscribe("ardrone/reset", 1, &ResetCallback);
land_sub = node_handle.subscribe("ardrone/land", 1, &LandCallback);
image_pub = image_transport.advertiseCamera("ardrone/image_raw", 10);
hori_pub = image_transport.advertiseCamera("ardrone/front/image_raw", 10);
vert_pub = image_transport.advertiseCamera("ardrone/bottom/image_raw", 10);
toggle_cam_srv = node_handle.advertiseService("ardrone/togglecam", ToggleCamCallback);
set_cam_channel_srv = node_handle.advertiseService("ardrone/setcamchannel", SetCamChannelCallback);
set_led_animation_srv = node_handle.advertiseService("ardrone/setledanimation", SetLedAnimationCallback);
flat_trim_srv = node_handle.advertiseService("ardrone/flattrim", FlatTrimCallback);
set_flight_anim_srv = node_handle.advertiseService("ardrone/setflightanimation", SetFlightAnimationCallback);
set_record_srv = node_handle.advertiseService("ardrone/setrecord", SetRecordCallback);
/* TF Frames */
std::string tf_prefix_key;
private_nh.searchParam("tf_prefix", tf_prefix_key);
private_nh.param(tf_prefix_key, tf_prefix, std::string(""));
private_nh.param<std::string>("drone_frame_id", drone_frame_id, "ardrone_base");
drone_frame_base = tf::resolve(tf_prefix, drone_frame_id + "_link");
drone_frame_imu = tf::resolve(tf_prefix, drone_frame_id + "_imu");
drone_frame_front_cam = tf::resolve(tf_prefix, drone_frame_id + "_frontcam");
drone_frame_bottom_cam = tf::resolve(tf_prefix, drone_frame_id + "_bottomcam");
tf_odom.frame_id_ = tf::resolve(tf_prefix, "odom");
if (private_nh.hasParam("root_frame"))
{
ROS_WARN("Changing `root_frame` has been deprecated since version 1.4. ");
}
// Fill constant parts of IMU Message
// If no rosparam is set then the default value of 0.0 will be assigned to all covariance values
for (int i = 0; i < 9; i++)
{
imu_msg.linear_acceleration_covariance[i] = 0.0;
imu_msg.angular_velocity_covariance[i] = 0.0;
imu_msg.orientation_covariance[i] = 0.0;
}
ReadCovParams("~cov/imu_la", imu_msg.linear_acceleration_covariance);
ReadCovParams("~cov/imu_av", imu_msg.angular_velocity_covariance);
ReadCovParams("~cov/imu_or", imu_msg.orientation_covariance);
if (private_nh.hasParam("do_imu_caliberation"))
{
ROS_WARN("IMU Caliberation has been deprecated since 1.4.");
}
// Camera Info Manager
//cinfo_hori = new camera_info_manager::CameraInfoManager(ros::NodeHandle("ardrone/front"), "ardrone_front");
//cinfo_vert = new camera_info_manager::CameraInfoManager(ros::NodeHandle("ardrone/bottom"), "ardrone_bottom");
std::string front_calib_url("");
private_nh.getParam("front_camera_info_url",front_calib_url);
cinfo_hori=new camera_info_manager::CameraInfoManager(ros::NodeHandle("ardrone/front"), "ardrone_front", front_calib_url);
std::string bottom_calib_url("");
private_nh.getParam("bottom_camera_info_url",bottom_calib_url);
cinfo_vert=new camera_info_manager::CameraInfoManager(ros::NodeHandle("ardrone/bottom/camera_info"), "ardrone_bottom", bottom_calib_url);
// TF Stuff
// Front Cam to Base
// TODO(mani-monaj): Precise values for Drone1 & Drone2
tf_base_front = tf::StampedTransform(
tf::Transform(
tf::createQuaternionFromRPY(-90.0 * _DEG2RAD, 0.0, -90.0 * _DEG2RAD),
tf::Vector3(0.21, 0.0, 0.0)),
ros::Time::now(), drone_frame_base, drone_frame_front_cam);
// Bottom Cam to Base (Bad Assumption: No translation from IMU and Base)
// TODO(mani-monaj): This should be different from Drone 1 & 2.
tf_base_bottom = tf::StampedTransform(
tf::Transform(
tf::createQuaternionFromRPY(180.0 * _DEG2RAD, 0.0, 90.0 * _DEG2RAD),
tf::Vector3(0.0, -0.02, 0.0)),
ros::Time::now(), drone_frame_base, drone_frame_bottom_cam);
// reset odometry
odometry[0] = odometry[1] = 0;
}
ARDroneDriver::~ARDroneDriver()
{
delete cinfo_hori;
delete cinfo_vert;
}
void ARDroneDriver::run()
{
ros::Rate loop_rate(looprate);
const ros::Time startTime = ros::Time::now();
static int freq_dev = 0;
while (node_handle.ok())
{
if (!is_inited) // Give the Drone 5s of free time to finish init phase
{
if (((ros::Time::now() - startTime).toSec()) > 5.0)
{
is_inited = true;
// Send the configuration to the drone
ConfigureDrone();
vp_os_mutex_lock(&navdata_lock);
ROS_INFO("Successfully connected to '%s' (AR-Drone %d.0 - Firmware: %s) - Battery(%%): %d",
ardrone_control_config.ardrone_name,
(IS_ARDRONE1) ? 1 : 2,
ardrone_control_config.num_version_soft,
shared_raw_navdata_ptr->navdata_demo.vbat_flying_percentage);
ROS_INFO("Navdata Publish Settings:");
ROS_INFO(" Legacy Navdata Mode: %s", enabled_legacy_navdata ? "On" : "Off");
ROS_INFO(" ROS Loop Rate: %d Hz", looprate);
ROS_INFO(" Realtime Navdata Publish: %s", realtime_navdata ? "On" : "Off");
ROS_INFO(" Realtime Video Publish: %s", realtime_video ? "On" : "Off");
ROS_INFO(" Drone Navdata Send Speed: %s",
ardrone_application_default_config.navdata_demo == 0 ?
"200Hz (navdata_demo=0)" : "15Hz (navdata_demo=1)");
// TODO(mani-monaj): Enabled Navdata Demo
vp_os_mutex_unlock(&navdata_lock);
if (ardrone_control_config.num_version_soft[0] == '0')
{
ROS_WARN("The AR-Drone has a suspicious Firmware number. It usually means the network link is unreliable.");
}
ROS_DEBUG_STREAM("Using " << tf_prefix << " to prefix TF frames.");
}
}
else
{
if (!realtime_video)
{
vp_os_mutex_lock(&video_lock);
copy_current_frame_id = current_frame_id;
vp_os_mutex_unlock(&video_lock);
if (copy_current_frame_id != last_frame_id)
{
last_frame_id = copy_current_frame_id;
PublishVideo();
}
}
if (!realtime_navdata)
{
vp_os_mutex_lock(&navdata_lock);
copy_current_navdata_id = current_navdata_id;
vp_os_mutex_unlock(&navdata_lock);
if (copy_current_navdata_id != last_navdata_id)
{
vp_os_mutex_lock(&navdata_lock);
last_navdata_id = copy_current_navdata_id;
// Thread safe copy of interesting Navdata data
// TODO(mani-monaj): This is a very expensive task, can we optimize here?
// maybe ignoring the copy when it is not needed.
const navdata_unpacked_t navdata_raw = *shared_raw_navdata_ptr;
const ros::Time navdata_receive_time = shared_navdata_receive_time;
vp_os_mutex_unlock(&navdata_lock);
// This function is defined in the template NavdataMessageDefinitions.h template file
PublishNavdataTypes(navdata_raw, navdata_receive_time);
PublishNavdata(navdata_raw, navdata_receive_time);
PublishOdometry(navdata_raw, navdata_receive_time);
}
}
if (freq_dev == 0) PublishTF();
// (looprate / 5)Hz TF publish
// TODO(mani-monaj): Make TF publish rate fixed
freq_dev = (freq_dev + 1) % 5;
}
ros::spinOnce();
loop_rate.sleep();
}
printf("ROS loop terminated ... \n");
}
void ARDroneDriver::ConfigureDrone()
{
#include "ardrone_autonomy/snippet_configure_drone.h"
}
double ARDroneDriver::CalcAverage(const std::vector<double> &vec)
{
double ret = 0.0;
for (unsigned int i = 0; i < vec.size(); i++)
{
ret += vec[i];
}
return (ret / vec.size());
}
bool ARDroneDriver::ReadCovParams(const std::string ¶m_name, boost::array<double, 9> &cov_array)
{
XmlRpc::XmlRpcValue cov_list;
std::stringstream str_stream;
if (ros::param::get(param_name, cov_list))
{
if (cov_list.getType() != XmlRpc::XmlRpcValue::TypeArray)
{
ROS_WARN("Covariance values for %s is not a list", param_name.c_str());
return false;
}
if (cov_list.size() != 9)
{
ROS_WARN("Covariance list size for %s is not of size 9 (Size: %d)", param_name.c_str(), cov_list.size());
return false;
}
str_stream << param_name << " set to [";
for (int32_t i = 0; i < cov_list.size(); i++)
{
ROS_ASSERT(cov_list[i].getType() == XmlRpc::XmlRpcValue::TypeDouble);
cov_array[i] = static_cast<double>(cov_list[i]);
str_stream << cov_array[i] << ((i < 8) ? ", " : "");
}
str_stream << "]";
ROS_INFO("%s", str_stream.str().c_str());
return true;
}
else
{
ROS_INFO("No values found for `%s` in parameters, set all to zero.", param_name.c_str());
return false;
}
}
void ARDroneDriver::PublishVideo()
{
if (
(image_pub.getNumSubscribers() == 0) &&
(hori_pub.getNumSubscribers() == 0) &&
(vert_pub.getNumSubscribers() == 0)
) return;
// Camera Info (NO PIP)
sensor_msgs::CameraInfo cinfo_msg_hori = cinfo_hori->getCameraInfo();
sensor_msgs::CameraInfo cinfo_msg_vert = cinfo_vert->getCameraInfo();
cinfo_msg_hori.header.frame_id = drone_frame_front_cam;
cinfo_msg_vert.header.frame_id = drone_frame_bottom_cam;
if (IS_ARDRONE1)
{
/*
* Information on buffer and image sizes.
* Buffer is always in QVGA size, however for different Camera Modes
* The picture and PIP sizes are different.
*
* image_raw and buffer are always 320x240. In order to preserve backward compatibilty image_raw remains
* always as before. Two new set of topics are added for two new cameras : /ardrone/front/xxx and /ardrone/bottom/xxx
*
* In Camera State 0 front image relays the buffer and image_raw and bottom image are not updated.
*
* In Camera State 1 bottom image is a 174x144 crop of the buffer. The front image is not updated
*
* In Camera State 2 bottom image is a PIP cut of size (87x72) from buffer.
* The bottom image is a (320-87)x(240) cut of the buffer.
*
* In Camera State 3 front image is a PIP cut of size (58x42) from buffer.
* The bottom image is a (174-58)x144 crop of the buffer.
*/
sensor_msgs::Image image_msg;
sensor_msgs::Image::_data_type::iterator _it;
if ((cam_state == ZAP_CHANNEL_HORI) || (cam_state == ZAP_CHANNEL_LARGE_HORI_SMALL_VERT))
{
image_msg.header.frame_id = drone_frame_front_cam;
}
else if ((cam_state == ZAP_CHANNEL_VERT) || (cam_state == ZAP_CHANNEL_LARGE_VERT_SMALL_HORI))
{
image_msg.header.frame_id = drone_frame_bottom_cam;
}
else
{
ROS_WARN_ONCE("Something is wrong with camera channel config.");
}
image_msg.width = D1_STREAM_WIDTH;
image_msg.height = D1_STREAM_HEIGHT;
image_msg.encoding = "rgb8";
image_msg.is_bigendian = false;
image_msg.step = D1_STREAM_WIDTH * 3;
image_msg.data.resize(D1_STREAM_WIDTH * D1_STREAM_HEIGHT * 3);
if (!realtime_video) vp_os_mutex_lock(&video_lock);
image_msg.header.stamp = shared_video_receive_time;
std::copy(buffer, buffer + (D1_STREAM_WIDTH * D1_STREAM_HEIGHT * 3), image_msg.data.begin());
if (!realtime_video) vp_os_mutex_unlock(&video_lock);
cinfo_msg_hori.header.stamp = image_msg.header.stamp;
cinfo_msg_vert.header.stamp = image_msg.header.stamp;
if (cam_state == ZAP_CHANNEL_HORI)
{
/*
* Horizontal camera is activated, only /ardrone/front/ is being updated
*/
cinfo_msg_hori.width = D1_STREAM_WIDTH;
cinfo_msg_hori.height = D1_STREAM_HEIGHT;
image_pub.publish(image_msg, cinfo_msg_hori);
hori_pub.publish(image_msg, cinfo_msg_hori);
}
else if (cam_state == ZAP_CHANNEL_VERT)
{
/*
* Vertical camera is activated, only /ardrone/bottom/ is being updated
*/
image_msg.width = D1_VERTSTREAM_WIDTH;
image_msg.height = D1_VERTSTREAM_HEIGHT;
image_msg.encoding = "rgb8";
image_msg.is_bigendian = false;
image_msg.step = D1_VERTSTREAM_WIDTH * 3;
image_msg.data.clear();
image_msg.data.resize(D1_VERTSTREAM_WIDTH * D1_VERTSTREAM_HEIGHT * 3);
_it = image_msg.data.begin();
if (!realtime_video) vp_os_mutex_lock(&video_lock);
for (int row = 0; row < D1_VERTSTREAM_HEIGHT ; row++)
{
int _b = row * D1_STREAM_WIDTH * 3;
int _e = _b + image_msg.step;
_it = std::copy(buffer + _b, buffer + _e, _it);
}
if (!realtime_video) vp_os_mutex_unlock(&video_lock);
cinfo_msg_vert.width = D1_VERTSTREAM_WIDTH;
cinfo_msg_vert.height = D1_VERTSTREAM_HEIGHT;
image_pub.publish(image_msg, cinfo_msg_vert);
vert_pub.publish(image_msg, cinfo_msg_vert);
}
else if (cam_state == ZAP_CHANNEL_LARGE_HORI_SMALL_VERT)
{
/*
* The Picture in Picture is activated with vertical camera inside the horizontal
* camera. Both /ardrone/front and /ardrone/bottom is being updated
*/
// Front (Cropping the first 88 columns)
image_msg.width = D1_STREAM_WIDTH - D1_MODE2_PIP_WIDTH;
image_msg.height = D1_STREAM_HEIGHT;
image_msg.encoding = "rgb8";
image_msg.is_bigendian = false;
image_msg.step = (D1_STREAM_WIDTH - D1_MODE2_PIP_WIDTH) * 3;
image_msg.data.clear();
image_msg.data.resize((D1_STREAM_WIDTH - D1_MODE2_PIP_WIDTH)*D1_STREAM_HEIGHT * 3);
_it = image_msg.data.begin();
if (!realtime_video) vp_os_mutex_lock(&video_lock);
for (int row = 0; row < D1_STREAM_HEIGHT; row++)
{
int _b = (row * D1_STREAM_WIDTH * 3) + (D1_MODE2_PIP_WIDTH * 3);
int _e = _b + image_msg.step;
_it = std::copy(buffer + _b, buffer + _e, _it);
}
if (!realtime_video) vp_os_mutex_unlock(&video_lock);
cinfo_msg_hori.width = D1_STREAM_WIDTH - D1_MODE2_PIP_WIDTH;
cinfo_msg_hori.height = D1_STREAM_HEIGHT;
hori_pub.publish(image_msg, cinfo_msg_hori);
// Bottom
image_msg.width = D1_MODE2_PIP_WIDTH;
image_msg.height = D1_MODE2_PIP_HEIGHT;
image_msg.encoding = "rgb8";
image_msg.is_bigendian = false;
image_msg.step = D1_MODE2_PIP_WIDTH * 3;
image_msg.data.clear();
image_msg.data.resize(D1_MODE2_PIP_WIDTH * D1_MODE2_PIP_HEIGHT * 3);
_it = image_msg.data.begin();
if (!realtime_video) vp_os_mutex_lock(&video_lock);
for (int row = 0; row < D1_MODE2_PIP_HEIGHT; row++)
{
int _b = row * D1_STREAM_WIDTH * 3;
int _e = _b + image_msg.step;
_it = std::copy(buffer + _b, buffer + _e, _it);
}
if (!realtime_video) vp_os_mutex_unlock(&video_lock);
cinfo_msg_vert.width = D1_MODE2_PIP_WIDTH;
cinfo_msg_vert.height = D1_MODE2_PIP_HEIGHT;
vert_pub.publish(image_msg, cinfo_msg_vert);
}
else if (cam_state == ZAP_CHANNEL_LARGE_VERT_SMALL_HORI)
{
/*
* The Picture in Picture is activated with horizontal camera inside the vertical
* camera. Both /ardrone/front and /ardrone/bottom is being updated
*/
// Bottom (Cropping the first 58 columns)
image_msg.width = D1_VERTSTREAM_WIDTH - D1_MODE3_PIP_WIDTH;
image_msg.height = D1_VERTSTREAM_HEIGHT;
image_msg.encoding = "rgb8";
image_msg.is_bigendian = false;
image_msg.step = (D1_VERTSTREAM_WIDTH - D1_MODE3_PIP_WIDTH) * 3;
image_msg.data.clear();
image_msg.data.resize((D1_VERTSTREAM_WIDTH - D1_MODE3_PIP_WIDTH)* D1_VERTSTREAM_HEIGHT * 3);
_it = image_msg.data.begin();
for (int row = 0; row < D1_VERTSTREAM_HEIGHT; row++)
{
int _b = (row * (D1_STREAM_WIDTH * 3)) + (D1_MODE3_PIP_WIDTH * 3);
int _e = _b + image_msg.step;
if (!realtime_video) vp_os_mutex_lock(&video_lock);
_it = std::copy(buffer + _b, buffer + _e, _it);
if (!realtime_video) vp_os_mutex_unlock(&video_lock);
}
cinfo_msg_vert.width = D1_VERTSTREAM_WIDTH - D1_MODE3_PIP_WIDTH;
cinfo_msg_vert.height = D1_VERTSTREAM_HEIGHT;
vert_pub.publish(image_msg, cinfo_msg_vert);
// Front
image_msg.width = D1_MODE3_PIP_WIDTH;
image_msg.height = D1_MODE3_PIP_HEIGHT;
image_msg.encoding = "rgb8";
image_msg.is_bigendian = false;
image_msg.step = D1_MODE3_PIP_WIDTH * 3;
image_msg.data.clear();
image_msg.data.resize(D1_MODE3_PIP_WIDTH * D1_MODE3_PIP_HEIGHT * 3);
_it = image_msg.data.begin();
if (!realtime_video) vp_os_mutex_lock(&video_lock);
for (int row = 0; row < D1_MODE3_PIP_HEIGHT; row++)
{
int _b = row * D1_STREAM_WIDTH * 3;
int _e = _b + image_msg.step;
_it = std::copy(buffer + _b, buffer + _e, _it);
}
if (!realtime_video) vp_os_mutex_unlock(&video_lock);
cinfo_msg_hori.width = D1_MODE3_PIP_WIDTH;
cinfo_msg_hori.height = D1_MODE3_PIP_HEIGHT;
hori_pub.publish(image_msg, cinfo_msg_hori);
}
}
/**
* For Drone 2 w/ SDK2. Both camera streams are 360p.
* No 720p support for now.
* SDK 2.0 Does not support PIP.
*/
if (IS_ARDRONE2)
{
sensor_msgs::Image image_msg;
sensor_msgs::Image::_data_type::iterator _it;
if (cam_state == ZAP_CHANNEL_HORI)
{
image_msg.header.frame_id = drone_frame_front_cam;
}
else if (cam_state == ZAP_CHANNEL_VERT)
{
image_msg.header.frame_id = drone_frame_bottom_cam;
}
else
{
ROS_WARN_ONCE("Something is wrong with camera channel config.");
}
image_msg.width = D2_STREAM_WIDTH;
image_msg.height = D2_STREAM_HEIGHT;
image_msg.encoding = "rgb8";
image_msg.is_bigendian = false;
image_msg.step = D2_STREAM_WIDTH * 3;
image_msg.data.resize(D2_STREAM_WIDTH * D2_STREAM_HEIGHT * 3);
if (!realtime_video) vp_os_mutex_lock(&video_lock);
image_msg.header.stamp = shared_video_receive_time;
std::copy(buffer, buffer + (D2_STREAM_WIDTH * D2_STREAM_HEIGHT * 3), image_msg.data.begin());
if (!realtime_video) vp_os_mutex_unlock(&video_lock);
// We only put the width and height in here.
cinfo_msg_hori.header.stamp = image_msg.header.stamp;
cinfo_msg_vert.header.stamp = image_msg.header.stamp;
if (cam_state == ZAP_CHANNEL_HORI)
{
/*
* Horizontal camera is activated, only /ardrone/front/ is being updated
*/
cinfo_msg_hori.width = D2_STREAM_WIDTH;
cinfo_msg_hori.height = D2_STREAM_HEIGHT;
image_pub.publish(image_msg, cinfo_msg_hori); // /ardrone
hori_pub.publish(image_msg, cinfo_msg_hori);
}
else if (cam_state == ZAP_CHANNEL_VERT)
{
/*
* Vertical camera is activated, only /ardrone/bottom/ is being updated
*/
cinfo_msg_vert.width = D2_STREAM_WIDTH;
cinfo_msg_vert.height = D2_STREAM_HEIGHT;
image_pub.publish(image_msg, cinfo_msg_vert); // /ardrone
vert_pub.publish(image_msg, cinfo_msg_vert);
}
}
}
void ARDroneDriver::PublishNavdata(const navdata_unpacked_t &navdata_raw, const ros::Time &navdata_receive_time)
{
if (!enabled_legacy_navdata ||
((navdata_pub.getNumSubscribers() == 0) &&
(imu_pub.getNumSubscribers() == 0) &&
(mag_pub.getNumSubscribers() == 0)))
return; // why bother, no one is listening.
legacynavdata_msg.header.stamp = navdata_receive_time;
legacynavdata_msg.header.frame_id = drone_frame_base;
legacynavdata_msg.batteryPercent = navdata_raw.navdata_demo.vbat_flying_percentage;
legacynavdata_msg.state = (navdata_raw.navdata_demo.ctrl_state >> 16);
// positive means counterclockwise rotation around axis
legacynavdata_msg.rotX = navdata_raw.navdata_demo.phi / 1000.0; // tilt left/right
legacynavdata_msg.rotY = -navdata_raw.navdata_demo.theta / 1000.0; // tilt forward/backward
legacynavdata_msg.rotZ = -navdata_raw.navdata_demo.psi / 1000.0; // orientation
legacynavdata_msg.altd = navdata_raw.navdata_demo.altitude; // cm
legacynavdata_msg.vx = navdata_raw.navdata_demo.vx; // mm/sec
legacynavdata_msg.vy = -navdata_raw.navdata_demo.vy; // mm/sec
legacynavdata_msg.vz = -navdata_raw.navdata_demo.vz; // mm/sec
// msg.tm = navdata_raw.navdata_time.time;
// First 21 bits (LSB) are usecs + 11 HSB are seconds
legacynavdata_msg.tm = (navdata_raw.navdata_time.time & 0x001FFFFF) + (navdata_raw.navdata_time.time >> 21) * 1000000;
legacynavdata_msg.ax = navdata_raw.navdata_phys_measures.phys_accs[ACC_X] / 1000.0; // g
legacynavdata_msg.ay = -navdata_raw.navdata_phys_measures.phys_accs[ACC_Y] / 1000.0; // g
legacynavdata_msg.az = -navdata_raw.navdata_phys_measures.phys_accs[ACC_Z] / 1000.0; // g
legacynavdata_msg.motor1 = navdata_raw.navdata_pwm.motor1;
legacynavdata_msg.motor2 = navdata_raw.navdata_pwm.motor2;
legacynavdata_msg.motor3 = navdata_raw.navdata_pwm.motor3;
legacynavdata_msg.motor4 = navdata_raw.navdata_pwm.motor4;
// New stuff
if (IS_ARDRONE2)
{
legacynavdata_msg.magX = (int32_t)navdata_raw.navdata_magneto.mx;
legacynavdata_msg.magY = (int32_t)navdata_raw.navdata_magneto.my;
legacynavdata_msg.magZ = (int32_t)navdata_raw.navdata_magneto.mz;
legacynavdata_msg.pressure = navdata_raw.navdata_pressure_raw.Pression_meas; // typo in the SDK!
legacynavdata_msg.temp = navdata_raw.navdata_pressure_raw.Temperature_meas;
legacynavdata_msg.wind_speed = navdata_raw.navdata_wind_speed.wind_speed;
legacynavdata_msg.wind_angle = navdata_raw.navdata_wind_speed.wind_angle;
legacynavdata_msg.wind_comp_angle = navdata_raw.navdata_wind_speed.wind_compensation_phi;
}
else
{
legacynavdata_msg.magX = legacynavdata_msg.magY = legacynavdata_msg.magZ = 0;
legacynavdata_msg.pressure = 0.0;
legacynavdata_msg.temp = 0.0;
legacynavdata_msg.wind_speed = 0.0;
legacynavdata_msg.wind_angle = 0.0;
legacynavdata_msg.wind_comp_angle = 0.0;
}
// Tag Detection, need to clear vectors first because it's a member variable now
legacynavdata_msg.tags_type.clear();
legacynavdata_msg.tags_xc.clear();
legacynavdata_msg.tags_yc.clear();
legacynavdata_msg.tags_width.clear();
legacynavdata_msg.tags_height.clear();
legacynavdata_msg.tags_orientation.clear();
legacynavdata_msg.tags_distance.clear();
legacynavdata_msg.tags_count = navdata_raw.navdata_vision_detect.nb_detected;
for (int i = 0; i < navdata_raw.navdata_vision_detect.nb_detected; i++)
{
/*
* The tags_type is in raw format. In order to extract the information
* macros from ardrone_api.h is needed.
*
* #define DETECTION_MAKE_TYPE(source,tag) ( ((source)<<16) | (tag) )
* #define DETECTION_EXTRACT_SOURCE(type) ( ((type)>>16) & 0x0FF )
* #define DETECTION_EXTRACT_TAG(type) ( (type) & 0x0FF )
*
* Please also note that the xc, yc, width and height are in [0,1000] range
* and must get converted back based on image resolution.
*/
legacynavdata_msg.tags_type.push_back(navdata_raw.navdata_vision_detect.type[i]);
legacynavdata_msg.tags_xc.push_back(navdata_raw.navdata_vision_detect.xc[i]);
legacynavdata_msg.tags_yc.push_back(navdata_raw.navdata_vision_detect.yc[i]);
legacynavdata_msg.tags_width.push_back(navdata_raw.navdata_vision_detect.width[i]);
legacynavdata_msg.tags_height.push_back(navdata_raw.navdata_vision_detect.height[i]);
legacynavdata_msg.tags_orientation.push_back(navdata_raw.navdata_vision_detect.orientation_angle[i]);
legacynavdata_msg.tags_distance.push_back(navdata_raw.navdata_vision_detect.dist[i]);
}
/* IMU */
imu_msg.header.frame_id = drone_frame_base;
imu_msg.header.stamp = navdata_receive_time;
// IMU - Linear Acc
imu_msg.linear_acceleration.x = legacynavdata_msg.ax * 9.8;
imu_msg.linear_acceleration.y = legacynavdata_msg.ay * 9.8;
imu_msg.linear_acceleration.z = legacynavdata_msg.az * 9.8;
// IMU - Rotation Matrix
tf::Quaternion q;
q.setRPY(legacynavdata_msg.rotX * _DEG2RAD, legacynavdata_msg.rotY * _DEG2RAD, legacynavdata_msg.rotZ * _DEG2RAD);
tf::quaternionTFToMsg(q, imu_msg.orientation);
// IMU - Gyro (Gyro is being sent in deg/sec)
// TODO(mani-monaj): Should Gyro be added to Navdata?
imu_msg.angular_velocity.x = navdata_raw.navdata_phys_measures.phys_gyros[GYRO_X] * DEG_TO_RAD;
imu_msg.angular_velocity.y = -navdata_raw.navdata_phys_measures.phys_gyros[GYRO_Y] * DEG_TO_RAD;
imu_msg.angular_velocity.z = -navdata_raw.navdata_phys_measures.phys_gyros[GYRO_Z] * DEG_TO_RAD;
mag_msg.header.frame_id = drone_frame_base;
mag_msg.header.stamp = navdata_receive_time;
const float mag_normalizer = sqrt(legacynavdata_msg.magX * legacynavdata_msg.magX +
legacynavdata_msg.magY * legacynavdata_msg.magY +
legacynavdata_msg.magZ * legacynavdata_msg.magZ);
// TODO(mani-monaj): Check if it is really needed that magnetometer message includes normalized value
if (fabs(mag_normalizer) > 1e-9f)
{
mag_msg.vector.x = legacynavdata_msg.magX / mag_normalizer;
mag_msg.vector.y = legacynavdata_msg.magY / mag_normalizer;
mag_msg.vector.z = legacynavdata_msg.magZ / mag_normalizer;
mag_pub.publish(mag_msg);
}
else
{
ROS_WARN_THROTTLE(30, "There is something wrong with the magnetometer readings (Magnitude is extremely small).");
}
navdata_pub.publish(legacynavdata_msg);
imu_pub.publish(imu_msg);
}
// Load actual auto-generated code to publish full navdata
#define NAVDATA_STRUCTS_SOURCE
#include <ardrone_autonomy/NavdataMessageDefinitions.h>
#undef NAVDATA_STRUCTS_SOURCE
void ARDroneDriver::PublishTF()
{
tf_base_front.stamp_ = ros::Time::now();
tf_base_bottom.stamp_ = ros::Time::now();
tf_broad.sendTransform(tf_base_front);
tf_broad.sendTransform(tf_base_bottom);
}
void ARDroneDriver::PublishOdometry(const navdata_unpacked_t &navdata_raw, const ros::Time &navdata_receive_time)
{
if (last_receive_time.isValid())
{
double delta_t = (navdata_receive_time - last_receive_time).toSec();
odometry[0] += ((cos((navdata_raw.navdata_demo.psi / 180000.0) * M_PI) *
navdata_raw.navdata_demo.vx - sin((navdata_raw.navdata_demo.psi / 180000.0) * M_PI) *
-navdata_raw.navdata_demo.vy) * delta_t) / 1000.0;
odometry[1] += ((sin((navdata_raw.navdata_demo.psi / 180000.0) * M_PI) *
navdata_raw.navdata_demo.vx + cos((navdata_raw.navdata_demo.psi / 180000.0) * M_PI) *
-navdata_raw.navdata_demo.vy) * delta_t) / 1000.0;
}
last_receive_time = navdata_receive_time;
nav_msgs::Odometry odo_msg;
odo_msg.header.stamp = navdata_receive_time;
odo_msg.header.frame_id = "odom";
odo_msg.child_frame_id = drone_frame_base;
odo_msg.pose.pose.position.x = odometry[0];
odo_msg.pose.pose.position.y = odometry[1];
odo_msg.pose.pose.position.z = navdata_raw.navdata_demo.altitude / 1000.0;
odo_msg.pose.pose.orientation = tf::createQuaternionMsgFromRollPitchYaw(
navdata_raw.navdata_demo.phi / 180000.0 * M_PI,
-navdata_raw.navdata_demo.theta / 180000.0 * M_PI,
-navdata_raw.navdata_demo.psi / 180000.0 * M_PI);
odo_msg.twist.twist.linear.x = navdata_raw.navdata_demo.vx / 1000.0;
odo_msg.twist.twist.linear.y = -navdata_raw.navdata_demo.vy / 1000.0;
odo_msg.twist.twist.linear.z = -navdata_raw.navdata_demo.vz / 1000.0;
if (odo_pub.getNumSubscribers() > 0)
{
odo_pub.publish(odo_msg);
}
tf::Vector3 t;
tf::pointMsgToTF(odo_msg.pose.pose.position, t);
tf::Quaternion q;
tf::quaternionMsgToTF(odo_msg.pose.pose.orientation, q);
tf_odom.stamp_ = navdata_receive_time;
tf_odom.child_frame_id_ = drone_frame_base;
tf_odom.setOrigin(t);
tf_odom.setRotation(q);
//tf_broad.sendTransform(tf_odom);
}
void ControlCHandler(int signal)
{
ros::shutdown();
should_exit = 1;
}
////////////////////////////////////////////////////////////////////////////////
// custom_main
////////////////////////////////////////////////////////////////////////////////
// extern "C" int custom_main(int argc, char** argv)
int main(int argc, char** argv)
{
C_RESULT res = C_FAIL;
char * drone_ip_address = NULL;
// We need to implement our own Signal handler instead of ROS to shutdown
// the SDK threads correctly.
ros::init(argc, argv, "ardrone_driver", ros::init_options::NoSigintHandler);
signal(SIGABRT, &ControlCHandler);
signal(SIGTERM, &ControlCHandler);
signal(SIGINT, &ControlCHandler);
// Now to setup the drone and communication channels
// We do this here because calling ardrone_tool_main uses an old
// function initialization and is no longer recommended by parrot
// I've based this section off the ControlEngine's initialization
// routine (distributed with ARDrone SDK 2.0 Examples) as well as
// the ardrone_tool_main function
// Parse command line for
// Backward compatibility with `-ip` command line argument
argc--;
argv++;
while (argc && *argv[0] == '-')
{
if (!strcmp(*argv, "-ip") && (argc > 1))
{
drone_ip_address = *(argv + 1);
printf("Using custom ip address %s\n", drone_ip_address);
argc--;
argv++;
}
argc--;
argv++;
}
// Configure wifi
vp_com_wifi_config_t *config = reinterpret_cast<vp_com_wifi_config_t*>(wifi_config());
if (config)
{
vp_os_memset(&wifi_ardrone_ip[0], 0, ARDRONE_IPADDRESS_SIZE);
// TODO(mani-monaj): Check if IP is valid
if (drone_ip_address)
{
printf("===================+> %s\n", drone_ip_address);
strncpy(&wifi_ardrone_ip[0], drone_ip_address, ARDRONE_IPADDRESS_SIZE - 1);
}
else
{
printf("===================+> %s\n", config->server);
strncpy(&wifi_ardrone_ip[0], config->server, ARDRONE_IPADDRESS_SIZE - 1);
}
}
while (-1 == getDroneVersion(".", wifi_ardrone_ip, &ardroneVersion))
{
printf("Getting AR.Drone version ...\n");
vp_os_delay(250);
}
// Setup communication channels
res = ardrone_tool_setup_com(NULL);
if (FAILED(res))
{
PRINT("Wifi initialization failed. It means either:\n");
PRINT("\t* you're not root (it's mandatory because you can set up wifi connection only as root)\n");
PRINT("\t* wifi device is not present (on your pc or on your card)\n");
PRINT("\t* you set the wrong name for wifi interface (for example rausb0 instead of wlan0) \n");
PRINT("\t* ap is not up (reboot card or remove wifi usb dongle)\n");
PRINT("\t* wifi device has no antenna\n");
}
else
{
// setup the application and user profiles for the driver
const char* appname = reinterpret_cast<const char*>(DRIVER_APPNAME);
const char* usrname = reinterpret_cast<const char*>(DRIVER_USERNAME);
ardrone_gen_appid(appname, "2.0", app_id, app_name, APPLI_NAME_SIZE);
ardrone_gen_usrid(usrname, usr_id, usr_name, USER_NAME_SIZE);
// and finally initialize everything!
// this will then call our sdk, which then starts the ::run() method of this file as an ardrone client thread
res = ardrone_tool_init(wifi_ardrone_ip,
strlen(wifi_ardrone_ip),
NULL,
app_name,
usr_name,
NULL,
NULL,
MAX_FLIGHT_STORING_SIZE,
NULL);
while (SUCCEED(res) && ardrone_tool_exit() == FALSE)
{
res = ardrone_tool_update();
}
res = ardrone_tool_shutdown();
}
return SUCCEED(res) ? 0 : -1;
}
| 39.561628 | 139 | 0.687182 | [
"vector",
"transform"
] |
d4505c15323216eebf000ee1493c8cd11acc7b59 | 2,871 | cpp | C++ | src/audiosystems/OpenSLES/OpenSLES_AudioManager.cpp | Tomcodon/libxal | a40100c5965e463c7596f0a16a1c32cbabdea754 | [
"BSD-3-Clause"
] | null | null | null | src/audiosystems/OpenSLES/OpenSLES_AudioManager.cpp | Tomcodon/libxal | a40100c5965e463c7596f0a16a1c32cbabdea754 | [
"BSD-3-Clause"
] | null | null | null | src/audiosystems/OpenSLES/OpenSLES_AudioManager.cpp | Tomcodon/libxal | a40100c5965e463c7596f0a16a1c32cbabdea754 | [
"BSD-3-Clause"
] | null | null | null | /// @file
/// @version 3.4
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause
///
/// @section DESCRIPTION
///
/// Represents an implementation of the AudioManager for OpenSLES.
#ifdef _OPENSLES
#include <string.h>
#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>
#include <hltypes/hdir.h>
#include <hltypes/hexception.h>
#include <hltypes/hlog.h>
#include <hltypes/hltypesUtil.h>
#include <hltypes/hmap.h>
#include <hltypes/hstring.h>
#include "Buffer.h"
#include "Category.h"
#include "OpenSLES_AudioManager.h"
#include "OpenSLES_Player.h"
#include "Sound.h"
#include "xal.h"
namespace xal
{
OpenSLES_AudioManager::OpenSLES_AudioManager(void* backendId, bool threaded, float updateTime, chstr deviceName) :
AudioManager(backendId, threaded, updateTime, deviceName), engineObject(NULL), engine(NULL), outputMixObject(NULL)
{
this->name = XAL_AS_OPENSLES;
hlog::write(xal::logTag, "Initializing OpenSLES.");
SLresult result;
// creating engine
result = slCreateEngine(&this->engineObject, 0, NULL, 0, NULL, NULL);
if (result != SL_RESULT_SUCCESS)
{
hlog::error(xal::logTag, "Could not create engine object!");
return;
}
result = __CPP_WRAP_ARGS(this->engineObject, Realize, SL_BOOLEAN_FALSE);
if (result != SL_RESULT_SUCCESS)
{
hlog::error(xal::logTag, "Could not realize engine object!");
__CPP_WRAP(this->engineObject, Destroy);
this->engineObject = NULL;
return;
}
result = __CPP_WRAP_ARGS(this->engineObject, GetInterface, SL_IID_ENGINE, &this->engine);
if (result != SL_RESULT_SUCCESS)
{
hlog::error(xal::logTag, "Could not get engine interface!");
__CPP_WRAP(this->engineObject, Destroy);
this->engineObject = NULL;
return;
}
// creating output mix
result = __CPP_WRAP_ARGS(this->engine, CreateOutputMix, &this->outputMixObject, 0, NULL, NULL);
if (result != SL_RESULT_SUCCESS)
{
hlog::error(xal::logTag, "Could not create output mix object!");
return;
}
result = __CPP_WRAP_ARGS(this->outputMixObject, Realize, SL_BOOLEAN_FALSE);
if (result != SL_RESULT_SUCCESS)
{
hlog::error(xal::logTag, "Could not realize output mix object!");
__CPP_WRAP(this->outputMixObject, Destroy);
return;
}
this->enabled = true;
}
OpenSLES_AudioManager::~OpenSLES_AudioManager()
{
hlog::write(xal::logTag, "Destroying OpenSLES.");
if (this->outputMixObject != NULL)
{
__CPP_WRAP(this->outputMixObject, Destroy);
this->outputMixObject = NULL;
}
this->engine = NULL;
if (this->engineObject != NULL)
{
__CPP_WRAP(this->engineObject, Destroy);
this->engineObject = NULL;
}
}
Player* OpenSLES_AudioManager::_createSystemPlayer(Sound* sound)
{
return new OpenSLES_Player(sound);
}
}
#endif
| 27.873786 | 116 | 0.710902 | [
"object"
] |
d452b996ba5f210086abbf2eb89b86098ca4d1ff | 1,358 | cpp | C++ | src/strategy/actions/HelpAction.cpp | htc16/mod-playerbots | 2307e3f980035a244bfb4fedefda5bc55903d470 | [
"MIT"
] | 12 | 2022-03-23T05:14:53.000Z | 2022-03-30T12:12:58.000Z | src/strategy/actions/HelpAction.cpp | htc16/mod-playerbots | 2307e3f980035a244bfb4fedefda5bc55903d470 | [
"MIT"
] | 24 | 2022-03-23T13:56:37.000Z | 2022-03-31T18:23:32.000Z | src/strategy/actions/HelpAction.cpp | htc16/mod-playerbots | 2307e3f980035a244bfb4fedefda5bc55903d470 | [
"MIT"
] | 3 | 2022-03-24T21:47:10.000Z | 2022-03-31T06:21:46.000Z | /*
* Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU GPL v2 license, you may redistribute it and/or modify it under version 2 of the License, or (at your option), any later version.
*/
#include "HelpAction.h"
#include "ChatActionContext.h"
#include "Event.h"
#include "Playerbots.h"
HelpAction::HelpAction(PlayerbotAI* botAI) : Action(botAI, "help")
{
chatContext = new ChatActionContext();
}
HelpAction::~HelpAction()
{
delete chatContext;
}
bool HelpAction::Execute(Event event)
{
TellChatCommands();
TellStrategies();
return true;
}
void HelpAction::TellChatCommands()
{
std::ostringstream out;
out << "Whisper any of: ";
out << CombineSupported(chatContext->supports());
out << ", [item], [quest] or [object] link";
botAI->TellError(out.str());
}
void HelpAction::TellStrategies()
{
std::ostringstream out;
out << "Possible strategies (co/nc/dead commands): ";
out << CombineSupported(botAI->GetAiObjectContext()->GetSupportedStrategies());
botAI->TellError(out.str());
}
std::string const HelpAction::CombineSupported(std::set<std::string> commands)
{
std::ostringstream out;
for (std::set<std::string>::iterator i = commands.begin(); i != commands.end(); )
{
out << *i;
if (++i != commands.end())
out << ", ";
}
return out.str();
}
| 23.824561 | 205 | 0.664212 | [
"object"
] |
d45347b17671e2bf7dcc47449a6b2bb400da48ff | 6,201 | hpp | C++ | include/bouge/IOModules/XMLParserCommon/XMLSerializer.hpp | lucasb-eyer/bouge | 0ac49789101a6c42c1ef404cc324d1f5ec05d1d8 | [
"Zlib"
] | 3 | 2015-10-10T21:27:00.000Z | 2016-05-29T05:48:23.000Z | include/bouge/IOModules/XMLParserCommon/XMLSerializer.hpp | lucasb-eyer/bouge | 0ac49789101a6c42c1ef404cc324d1f5ec05d1d8 | [
"Zlib"
] | null | null | null | include/bouge/IOModules/XMLParserCommon/XMLSerializer.hpp | lucasb-eyer/bouge | 0ac49789101a6c42c1ef404cc324d1f5ec05d1d8 | [
"Zlib"
] | 1 | 2019-03-18T05:23:45.000Z | 2019-03-18T05:23:45.000Z | ////////////////////////////////////////////////////////////
//
// Bouge - Modern and flexible skeletal animation library
// Copyright (C) 2010 Lucas Beyer (pompei2@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef BOUGE_XML_SERIALIZER_HPP
#define BOUGE_XML_SERIALIZER_HPP
// Note: This file is heavily inspired/copied from the CEGUI project.
#include <bouge/Config.hpp>
#include <string>
#include <vector>
#include <iterator>
#if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable : 4251)
#endif
namespace bouge
{
/// Class used to create XML Document.
///
/// This class hides the complexity of formatting valid XML files. The
/// class provides automatic substitution of entities, XML indenting
/// in respect of the spaces. The following
/// example show the code needed to exports parts of an XML document
/// similar to what can be found in a layout.
///
/// @code
/// #include <iostream>
/// #include <bouge/XMLSerializer.h>
///
/// int main()
/// {
/// // Create an encoder that outputs its result on standard output
/// XMLSerializer xml(std::cout, 4);
/// xml.openTag("Window")
/// .attribute("Type", "TaharezLook/StaticText")
/// .attribute("Name", "Test")
/// .openTag("Property")
/// .attribute("Name", "Text")
/// .text("This is the static text to be displayed")
/// .closeTag()
/// .openTag("Window")
/// .attribute("Name", "Button")
/// .attribute("Type", "Vanilla/Button")
/// .openTag("Property")
/// .attribute("Name", "Text")
/// .attribute("Value", "Push me")
/// .closeTag()
/// .closeTag()
/// .closeTag();
///
/// if (xml)
/// {
/// std::cout << "XML Exported successfully" << std::endl;
/// }
/// return 0;
/// }
/// @endcode
template<class OutStream>
class BOUGE_API XMLSerializer
{
public:
/// XMLSerializer constructor
/// \param out The stream to use to export the result
/// \param indentSpace The indentation level (0 to disable indentation)
XMLSerializer(OutStream& out, size_t indentSpace = 4);
/// XMLSerializer destructor
virtual ~XMLSerializer();
/// Start a new tag in the xml document.
/// \param name The name of the tag
/// \return A reference to the current object for chaining operation
XMLSerializer& openTag(const std::string& name);
/// brief Close the current tag.
/// \return A reference to the current object for chaining operation
XMLSerializer& closeTag(void);
/// After an opening tag you can populate attribute list with this function
/// \param name The name of the attribute
/// \param value The value of the attribute
/// \return A reference to the current object for chaining operation
XMLSerializer& attribute(const std::string& name, const std::string& value);
/// Create a text node
/// \param text the content of the node
/// \return A reference to the current object for chaining operation
XMLSerializer& text(const std::string& text);
/// report the nimber of tags created in the document
/// \return return the number of tag created in the document
unsigned int getTagCount() const;
/// Check wether the XML Serializer status is valid
/// \return True if all previous operations where successfull
operator bool () const
{
return false == m_error;
}
/// Check wether the XML Serializer status is invalid
/// \return True if one operations failed
bool operator!() const
{
return false != m_error;
}
protected:
private:
bool m_error; //!< Store the status of the serializer
unsigned int m_tagCount; //!<Return the number of tag in the document
size_t m_depth; //!< Store the current depth for indentation purpose
size_t m_indentSpace; //!< Store the number of space use for indenting
bool m_needClose; //!< Store whether the next operation need to close the tag or not
bool m_lastIsText; //!< Store whether the last operation was a text node or not
OutStream& m_stream; //!< A reference to the stream object use
std::vector<std::string> m_tagStack; //!< Store the tag stack for correct closing of the tags.
/// put padding in the stream before line data
void indentLine();
/// convert special char to there corresponding entity in text data.
static std::string convertEntityInText(const std::string& text);
/// convert special char into entities including line ending for use in attributes.
static std::string convertEntityInAttribute(const std::string& attributeValue);
// Disabled operation
XMLSerializer(const XMLSerializer& obj);
// Disabled operation
XMLSerializer& operator=(const XMLSerializer& obj);
};
#include "XMLSerializer.inl"
} // namespace bouge
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
#endif // BOUGE_XML_SERIALIZER_HPP
| 36.910714 | 102 | 0.627318 | [
"object",
"vector"
] |
d4549a1899e8c5a2357f345f3a88ee80d2b1583a | 1,268 | cc | C++ | leetcode/1-100/91-decode-ways/91.cc | punkieL/proCon | 7e994d67e5efdf7ac0b1bee5e0b19b317f07e8af | [
"MIT"
] | 1 | 2015-10-06T16:27:42.000Z | 2015-10-06T16:27:42.000Z | leetcode/1-100/91-decode-ways/91.cc | punkieL/proCon | 7e994d67e5efdf7ac0b1bee5e0b19b317f07e8af | [
"MIT"
] | 1 | 2015-10-06T16:24:16.000Z | 2015-10-06T16:24:16.000Z | leetcode/1-100/91-decode-ways/91.cc | punkieL/proCon | 7e994d67e5efdf7ac0b1bee5e0b19b317f07e8af | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
int numDecodings(string s) {
if(s.length() < 1) return 0;
vector<int> mem(s.length()+1, 1);
dp(s, mem, 1);
//show(mem);
return mem[s.length()];
}
void dp(string& a, vector<int>& mem, int j){
int i = j - 1;
if(j > a.length()) return;
if(check_posibility(i-1, j-1, a) && a[j-1] == '0') //10, 20 case
mem[j] = mem[j-2];
else if(check_posibility(i-1, j-1, a)) //two digits case
mem[j] = mem[j-1] + mem[j-2];
else if(a[j-1] == '0')//single 0 case
mem[j] = 0;
else //other single digit case
mem[j] = mem[j-1];
dp(a, mem, j+1);
}
bool check_posibility(int m, int n, string& a){
if(m < 0) return false;
char i = a[m];
char j = a[n];
if(i == '1' ) return true;
if(i == '2' && j < '7') return true;
return false;
}
template<typename T>
void show(T a){
for(auto i : a){
cout << i << " ";
}
cout << endl;
}
};
template<typename T>
void show(T a){
for(auto i : a){
}
cout << endl;
}
int main(int argc, char *argv[]){
Solution a;
//cout << argc << argv[0] << endl;
cout << a.numDecodings(argv[1]) << endl;
} | 20.126984 | 69 | 0.526814 | [
"vector"
] |
d46dc0497b58261bf3be4828ded0701c4355c630 | 8,052 | cc | C++ | chrome/browser/ui/signin/profile_colors_util.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | chrome/browser/ui/signin/profile_colors_util.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chrome/browser/ui/signin/profile_colors_util.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/signin/profile_colors_util.h"
#include "base/containers/contains.h"
#include "base/rand_util.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile_attributes_storage.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/themes/browser_theme_pack.h"
#include "chrome/browser/themes/custom_theme_supplier.h"
#include "chrome/browser/themes/theme_properties.h"
#include "chrome/common/search/generated_colors_info.h"
#include "ui/gfx/color_utils.h"
#include "ui/native_theme/native_theme.h"
namespace {
// Minimum saturation for a color to be autoselected (as picking 'colorful'
// colors is needed to distinguish colors from each other).
constexpr double kMinimumSaturation = 0.25;
// Maximum diff in lightness of an autoselected color to the color of the
// current profile (so that the interception UI does not look bad).
constexpr double kMaximumLightnessDiff = 0.35;
// This is the core definition of how ProfileThemeColors are obtained.
ProfileThemeColors GetProfileThemeColorsFromHighlightColor(
SkColor highlight_color) {
ProfileThemeColors colors;
colors.profile_highlight_color = highlight_color;
colors.default_avatar_fill_color = highlight_color;
colors.default_avatar_stroke_color =
GetAvatarStrokeColor(colors.default_avatar_fill_color);
return colors;
}
ProfileThemeColors GetProfileThemeColorsForAutogeneratedColor(
SkColor autogenerated_color) {
auto pack = base::MakeRefCounted<BrowserThemePack>(
CustomThemeSupplier::ThemeType::AUTOGENERATED);
BrowserThemePack::BuildFromColor(autogenerated_color, pack.get());
return GetProfileThemeColorsForThemeSupplier(pack.get());
}
size_t GenerateRandomIndex(size_t size) {
DCHECK_GT(size, 0u);
return static_cast<size_t>(base::RandInt(0, size - 1));
}
std::vector<int> GetAvailableColorIndices(
const std::set<ProfileThemeColors>& used_theme_colors,
base::Optional<double> current_color_lightness) {
std::vector<int> available_color_indices;
for (size_t i = 0; i < base::size(chrome_colors::kGeneratedColorsInfo); ++i) {
ProfileThemeColors theme_colors =
GetProfileThemeColorsForAutogeneratedColor(
chrome_colors::kGeneratedColorsInfo[i].color);
if (base::Contains(used_theme_colors, theme_colors))
continue;
const SkColor highlight = theme_colors.profile_highlight_color;
if (!IsSaturatedForAutoselection(highlight))
continue;
if (current_color_lightness &&
!IsLightForAutoselection(highlight, *current_color_lightness))
continue;
available_color_indices.push_back(i);
}
return available_color_indices;
}
double ExtractCurrentColorLightness(ProfileAttributesEntry* current_profile) {
ProfileThemeColors current_colors;
if (!current_profile) {
current_colors = GetDefaultProfileThemeColors(
ui::NativeTheme::GetInstanceForNativeUi()->ShouldUseDarkColors());
} else {
current_colors = current_profile->GetProfileThemeColors();
}
color_utils::HSL hsl;
color_utils::SkColorToHSL(current_colors.profile_highlight_color, &hsl);
return hsl.l;
}
} // namespace
bool ProfileThemeColors::operator<(const ProfileThemeColors& other) const {
return std::tie(this->profile_highlight_color,
this->default_avatar_fill_color,
this->default_avatar_stroke_color) <
std::tie(other.profile_highlight_color,
other.default_avatar_fill_color,
other.default_avatar_stroke_color);
}
bool ProfileThemeColors::operator==(const ProfileThemeColors& other) const {
return std::tie(this->profile_highlight_color,
this->default_avatar_fill_color,
this->default_avatar_stroke_color) ==
std::tie(other.profile_highlight_color,
other.default_avatar_fill_color,
other.default_avatar_stroke_color);
}
bool ProfileThemeColors::operator!=(const ProfileThemeColors& other) const {
return !(*this == other);
}
ProfileThemeColors GetProfileThemeColorsForThemeSupplier(
const CustomThemeSupplier* supplier) {
SkColor highlight_color;
bool is_defined =
supplier->GetColor(ThemeProperties::COLOR_FRAME_ACTIVE, &highlight_color);
DCHECK(is_defined);
return GetProfileThemeColorsFromHighlightColor(highlight_color);
}
ProfileThemeColors GetDefaultProfileThemeColors(bool dark_mode) {
return GetProfileThemeColorsFromHighlightColor(
ThemeProperties::GetDefaultColor(ThemeProperties::COLOR_FRAME_ACTIVE,
/*incognito=*/false, dark_mode));
}
SkColor GetProfileForegroundTextColor(SkColor profile_highlight_color) {
return color_utils::GetColorWithMaxContrast(profile_highlight_color);
}
SkColor GetProfileForegroundIconColor(SkColor profile_highlight_color) {
SkColor text_color = GetProfileForegroundTextColor(profile_highlight_color);
SkColor icon_color = color_utils::DeriveDefaultIconColor(text_color);
return color_utils::BlendForMinContrast(icon_color, profile_highlight_color,
text_color)
.color;
}
SkColor GetAvatarStrokeColor(SkColor avatar_fill_color) {
if (color_utils::IsDark(avatar_fill_color)) {
return SK_ColorWHITE;
}
color_utils::HSL color_hsl;
color_utils::SkColorToHSL(avatar_fill_color, &color_hsl);
color_hsl.l = std::max(0., color_hsl.l - 0.5);
return color_utils::HSLToSkColor(color_hsl, SkColorGetA(avatar_fill_color));
}
bool IsSaturatedForAutoselection(SkColor color) {
color_utils::HSL hsl;
color_utils::SkColorToHSL(color, &hsl);
return hsl.s >= kMinimumSaturation;
}
bool IsLightForAutoselection(SkColor color, double reference_lightness) {
color_utils::HSL hsl;
color_utils::SkColorToHSL(color, &hsl);
return std::abs(hsl.l - reference_lightness) <= kMaximumLightnessDiff;
}
chrome_colors::ColorInfo GenerateNewProfileColorWithGenerator(
ProfileAttributesStorage& storage,
base::OnceCallback<size_t(size_t count)> random_generator,
ProfileAttributesEntry* current_profile) {
// TODO(crbug.com/1108295): Return only a SkColor if the full ColorInfo is not
// needed.
std::set<ProfileThemeColors> used_theme_colors;
for (ProfileAttributesEntry* entry : storage.GetAllProfilesAttributes()) {
base::Optional<ProfileThemeColors> current_colors =
entry->GetProfileThemeColorsIfSet();
if (current_colors)
used_theme_colors.insert(*current_colors);
}
double current_color_lightness =
ExtractCurrentColorLightness(current_profile);
// Collect indices of profile colors that match all the filters.
std::vector<int> available_color_indices =
GetAvailableColorIndices(used_theme_colors, current_color_lightness);
// Relax the constraints until some colors become available.
if (available_color_indices.empty()) {
available_color_indices =
GetAvailableColorIndices(used_theme_colors, base::nullopt);
}
if (available_color_indices.empty()) {
// If needed, we could allow unsaturated colors (shades of grey) before
// allowing a duplicate color.
available_color_indices =
GetAvailableColorIndices(std::set<ProfileThemeColors>(), base::nullopt);
}
DCHECK(!available_color_indices.empty());
size_t size = available_color_indices.size();
size_t available_index = std::move(random_generator).Run(size);
DCHECK_LT(available_index, size);
size_t index = available_color_indices[available_index];
return chrome_colors::kGeneratedColorsInfo[index];
}
chrome_colors::ColorInfo GenerateNewProfileColor(
ProfileAttributesEntry* current_profile) {
return GenerateNewProfileColorWithGenerator(
g_browser_process->profile_manager()->GetProfileAttributesStorage(),
base::BindOnce(&GenerateRandomIndex), current_profile);
}
| 38.161137 | 80 | 0.764158 | [
"vector"
] |
d47367d6430d6b11134065ed0ef27e6c16728ee4 | 248 | hpp | C++ | examples/simple/src/for_codegen/3_typeclass_combinations/Spell_MagicItem_typeclass_combo.hpp | mohibqureshi/CXXCTP | db7c80da469fe3511f7d8ac7f7dee7391122dac6 | [
"MIT"
] | 63 | 2019-08-30T11:53:47.000Z | 2021-05-19T06:17:47.000Z | examples/simple/src/for_codegen/3_typeclass_combinations/Spell_MagicItem_typeclass_combo.hpp | mohibqureshi/CXXCTP | db7c80da469fe3511f7d8ac7f7dee7391122dac6 | [
"MIT"
] | 96 | 2019-09-16T05:03:31.000Z | 2020-10-14T14:33:50.000Z | examples/simple/src/for_codegen/3_typeclass_combinations/Spell_MagicItem_typeclass_combo.hpp | mohibqureshi/CXXCTP | db7c80da469fe3511f7d8ac7f7dee7391122dac6 | [
"MIT"
] | 27 | 2019-09-25T10:12:37.000Z | 2020-05-06T02:59:44.000Z | #pragma once
#include "cxxctp_macros.hpp"
#include <vector>
#include <string>
#include <iostream>
// just wraps multiple `traits`, forwards calls
/// \note example of combined typeclasses
$typeclass_combo(
typeclass_combo(Spell, MagicItem)
)
| 17.714286 | 47 | 0.75 | [
"vector"
] |
d47a69699a22af7b1e62e1454dc37e086363ac6d | 25,667 | cc | C++ | decoder/earley_composer.cc | kho/cdec | d88186af251ecae60974b20395ce75807bfdda35 | [
"BSD-3-Clause-LBNL",
"Apache-2.0"
] | 114 | 2015-01-11T05:41:03.000Z | 2021-08-31T03:47:12.000Z | decoder/earley_composer.cc | kho/cdec | d88186af251ecae60974b20395ce75807bfdda35 | [
"BSD-3-Clause-LBNL",
"Apache-2.0"
] | 29 | 2015-01-09T01:00:09.000Z | 2019-09-25T06:04:02.000Z | decoder/earley_composer.cc | kho/cdec | d88186af251ecae60974b20395ce75807bfdda35 | [
"BSD-3-Clause-LBNL",
"Apache-2.0"
] | 50 | 2015-02-13T13:48:39.000Z | 2019-08-07T09:45:11.000Z | #include "earley_composer.h"
#include <iostream>
#include <fstream>
#include <map>
#include <queue>
#ifndef HAVE_OLD_CPP
# include <unordered_map>
# include <unordered_set>
#else
# include <tr1/unordered_map>
# include <tr1/unordered_set>
namespace std { using std::tr1::unordered_map; using std::tr1::unordered_multiset; using std::tr1::unordered_set; }
#endif
#include <boost/shared_ptr.hpp>
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>
#include "fast_lexical_cast.hpp"
#include "phrasetable_fst.h"
#include "sparse_vector.h"
#include "tdict.h"
#include "hg.h"
#include "hg_remove_eps.h"
using namespace std;
// Define the following macro if you want to see lots of debugging output
// when you run the chart parser
#undef DEBUG_CHART_PARSER
// A few constants used by the chart parser ///////////////
static const int kMAX_NODES = 2000000;
static const string kPHRASE_STRING = "X";
static bool constants_need_init = true;
static WordID kUNIQUE_START;
static WordID kPHRASE;
static TRulePtr kX1X2;
static TRulePtr kX1;
static WordID kEPS;
static TRulePtr kEPSRule;
static void InitializeConstants() {
if (constants_need_init) {
kPHRASE = TD::Convert(kPHRASE_STRING) * -1;
kUNIQUE_START = TD::Convert("S") * -1;
kX1X2.reset(new TRule("[X] ||| [X,1] [X,2] ||| [X,1] [X,2]"));
kX1.reset(new TRule("[X] ||| [X,1] ||| [X,1]"));
kEPSRule.reset(new TRule("[X] ||| <eps> ||| <eps>"));
kEPS = TD::Convert("<eps>");
constants_need_init = false;
}
}
////////////////////////////////////////////////////////////
TRulePtr CreateBinaryRule(int lhs, int rhs1, int rhs2) {
TRule* r = new TRule(*kX1X2);
r->lhs_ = lhs;
r->f_[0] = rhs1;
r->f_[1] = rhs2;
return TRulePtr(r);
}
TRulePtr CreateUnaryRule(int lhs, int rhs1) {
TRule* r = new TRule(*kX1);
r->lhs_ = lhs;
r->f_[0] = rhs1;
return TRulePtr(r);
}
TRulePtr CreateEpsilonRule(int lhs) {
TRule* r = new TRule(*kEPSRule);
r->lhs_ = lhs;
return TRulePtr(r);
}
class EGrammarNode {
friend bool EarleyComposer::Compose(const Hypergraph& src_forest, Hypergraph* trg_forest);
friend void AddGrammarRule(const string& r, map<WordID, EGrammarNode>* g);
public:
#ifdef DEBUG_CHART_PARSER
string hint;
#endif
EGrammarNode() : is_some_rule_complete(false), is_root(false) {}
const map<WordID, EGrammarNode>& GetTerminals() const { return tptr; }
const map<WordID, EGrammarNode>& GetNonTerminals() const { return ntptr; }
bool HasNonTerminals() const { return (!ntptr.empty()); }
bool HasTerminals() const { return (!tptr.empty()); }
bool RuleCompletes() const {
return (is_some_rule_complete || (ntptr.empty() && tptr.empty()));
}
bool GrammarContinues() const {
return !(ntptr.empty() && tptr.empty());
}
bool IsRoot() const {
return is_root;
}
// these are the features associated with the rule from the start
// node up to this point. If you use these features, you must
// not Extend() this rule.
const SparseVector<double>& GetCFGProductionFeatures() const {
return input_features;
}
const EGrammarNode* Extend(const WordID& t) const {
if (t < 0) {
map<WordID, EGrammarNode>::const_iterator it = ntptr.find(t);
if (it == ntptr.end()) return NULL;
return &it->second;
} else {
map<WordID, EGrammarNode>::const_iterator it = tptr.find(t);
if (it == tptr.end()) return NULL;
return &it->second;
}
}
private:
map<WordID, EGrammarNode> tptr;
map<WordID, EGrammarNode> ntptr;
SparseVector<double> input_features;
bool is_some_rule_complete;
bool is_root;
};
typedef map<WordID, EGrammarNode> EGrammar; // indexed by the rule LHS
// edges are immutable once created
struct Edge {
#ifdef DEBUG_CHART_PARSER
static int id_count;
const int id;
#endif
const WordID cat; // lhs side of rule proved/being proved
const EGrammarNode* const dot; // dot position
const FSTNode* const q; // start of span
const FSTNode* const r; // end of span
const Edge* const active_parent; // back pointer, NULL for PREDICT items
const Edge* const passive_parent; // back pointer, NULL for SCAN and PREDICT items
const TargetPhraseSet* const tps; // translations
boost::shared_ptr<SparseVector<double> > features; // features from CFG rule
bool IsPassive() const {
// when a rule is completed, this value will be set
return static_cast<bool>(features);
}
bool IsActive() const { return !IsPassive(); }
bool IsInitial() const {
return !(active_parent || passive_parent);
}
bool IsCreatedByScan() const {
return active_parent && !passive_parent && !dot->IsRoot();
}
bool IsCreatedByPredict() const {
return dot->IsRoot();
}
bool IsCreatedByComplete() const {
return active_parent && passive_parent;
}
// constructor for PREDICT
Edge(WordID c, const EGrammarNode* d, const FSTNode* q_and_r) :
#ifdef DEBUG_CHART_PARSER
id(++id_count),
#endif
cat(c), dot(d), q(q_and_r), r(q_and_r), active_parent(NULL), passive_parent(NULL), tps(NULL) {}
Edge(WordID c, const EGrammarNode* d, const FSTNode* q_and_r, const Edge* act_parent) :
#ifdef DEBUG_CHART_PARSER
id(++id_count),
#endif
cat(c), dot(d), q(q_and_r), r(q_and_r), active_parent(act_parent), passive_parent(NULL), tps(NULL) {}
// constructors for SCAN
Edge(WordID c, const EGrammarNode* d, const FSTNode* i, const FSTNode* j,
const Edge* act_par, const TargetPhraseSet* translations) :
#ifdef DEBUG_CHART_PARSER
id(++id_count),
#endif
cat(c), dot(d), q(i), r(j), active_parent(act_par), passive_parent(NULL), tps(translations) {}
Edge(WordID c, const EGrammarNode* d, const FSTNode* i, const FSTNode* j,
const Edge* act_par, const TargetPhraseSet* translations,
const SparseVector<double>& feats) :
#ifdef DEBUG_CHART_PARSER
id(++id_count),
#endif
cat(c), dot(d), q(i), r(j), active_parent(act_par), passive_parent(NULL), tps(translations),
features(new SparseVector<double>(feats)) {}
// constructors for COMPLETE
Edge(WordID c, const EGrammarNode* d, const FSTNode* i, const FSTNode* j,
const Edge* act_par, const Edge *pas_par) :
#ifdef DEBUG_CHART_PARSER
id(++id_count),
#endif
cat(c), dot(d), q(i), r(j), active_parent(act_par), passive_parent(pas_par), tps(NULL) {
assert(pas_par->IsPassive());
assert(act_par->IsActive());
}
Edge(WordID c, const EGrammarNode* d, const FSTNode* i, const FSTNode* j,
const Edge* act_par, const Edge *pas_par, const SparseVector<double>& feats) :
#ifdef DEBUG_CHART_PARSER
id(++id_count),
#endif
cat(c), dot(d), q(i), r(j), active_parent(act_par), passive_parent(pas_par), tps(NULL),
features(new SparseVector<double>(feats)) {
assert(pas_par->IsPassive());
assert(act_par->IsActive());
}
// constructor for COMPLETE query
Edge(const FSTNode* _r) :
#ifdef DEBUG_CHART_PARSER
id(0),
#endif
cat(0), dot(NULL), q(NULL),
r(_r), active_parent(NULL), passive_parent(NULL), tps(NULL) {}
// constructor for MERGE quere
Edge(const FSTNode* _q, int) :
#ifdef DEBUG_CHART_PARSER
id(0),
#endif
cat(0), dot(NULL), q(_q),
r(NULL), active_parent(NULL), passive_parent(NULL), tps(NULL) {}
};
#ifdef DEBUG_CHART_PARSER
int Edge::id_count = 0;
#endif
ostream& operator<<(ostream& os, const Edge& e) {
string type = "PREDICT";
if (e.IsCreatedByScan())
type = "SCAN";
else if (e.IsCreatedByComplete())
type = "COMPLETE";
os << "["
#ifdef DEBUG_CHART_PARSER
<< '(' << e.id << ") "
#else
<< '(' << &e << ") "
#endif
<< "q=" << e.q << ", r=" << e.r
<< ", cat="<< TD::Convert(e.cat*-1) << ", dot="
<< e.dot
#ifdef DEBUG_CHART_PARSER
<< e.dot->hint
#endif
<< (e.IsActive() ? ", Active" : ", Passive")
<< ", " << type;
#ifdef DEBUG_CHART_PARSER
if (e.active_parent) { os << ", act.parent=(" << e.active_parent->id << ')'; }
if (e.passive_parent) { os << ", psv.parent=(" << e.passive_parent->id << ')'; }
#endif
if (e.tps) { os << ", tps=" << e.tps; }
return os << ']';
}
struct Traversal {
const Edge* const edge; // result from the active / passive combination
const Edge* const active;
const Edge* const passive;
Traversal(const Edge* me, const Edge* a, const Edge* p) : edge(me), active(a), passive(p) {}
};
struct UniqueTraversalHash {
size_t operator()(const Traversal* t) const {
size_t x = 5381;
x = ((x << 5) + x) ^ reinterpret_cast<size_t>(t->active);
x = ((x << 5) + x) ^ reinterpret_cast<size_t>(t->passive);
x = ((x << 5) + x) ^ t->edge->IsActive();
return x;
}
};
struct UniqueTraversalEquals {
size_t operator()(const Traversal* a, const Traversal* b) const {
return (a->passive == b->passive && a->active == b->active && a->edge->IsActive() == b->edge->IsActive());
}
};
struct UniqueEdgeHash {
size_t operator()(const Edge* e) const {
size_t x = 5381;
if (e->IsActive()) {
x = ((x << 5) + x) ^ reinterpret_cast<size_t>(e->dot);
x = ((x << 5) + x) ^ reinterpret_cast<size_t>(e->q);
x = ((x << 5) + x) ^ reinterpret_cast<size_t>(e->r);
x = ((x << 5) + x) ^ static_cast<size_t>(e->cat);
x += 13;
} else { // with passive edges, we don't care about the dot
x = ((x << 5) + x) ^ reinterpret_cast<size_t>(e->q);
x = ((x << 5) + x) ^ reinterpret_cast<size_t>(e->r);
x = ((x << 5) + x) ^ static_cast<size_t>(e->cat);
}
return x;
}
};
struct UniqueEdgeEquals {
bool operator()(const Edge* a, const Edge* b) const {
if (a->IsActive() != b->IsActive()) return false;
if (a->IsActive()) {
return (a->cat == b->cat) && (a->dot == b->dot) && (a->q == b->q) && (a->r == b->r);
} else {
return (a->cat == b->cat) && (a->q == b->q) && (a->r == b->r);
}
}
};
struct REdgeHash {
size_t operator()(const Edge* e) const {
size_t x = 5381;
x = ((x << 5) + x) ^ reinterpret_cast<size_t>(e->r);
return x;
}
};
struct REdgeEquals {
bool operator()(const Edge* a, const Edge* b) const {
return (a->r == b->r);
}
};
struct QEdgeHash {
size_t operator()(const Edge* e) const {
size_t x = 5381;
x = ((x << 5) + x) ^ reinterpret_cast<size_t>(e->q);
return x;
}
};
struct QEdgeEquals {
bool operator()(const Edge* a, const Edge* b) const {
return (a->q == b->q);
}
};
struct EdgeQueue {
queue<const Edge*> q;
EdgeQueue() {}
void clear() { while(!q.empty()) q.pop(); }
bool HasWork() const { return !q.empty(); }
const Edge* Next() { const Edge* res = q.front(); q.pop(); return res; }
void AddEdge(const Edge* s) { q.push(s); }
};
class EarleyComposerImpl {
public:
EarleyComposerImpl(WordID start_cat, const FSTNode& q_0) : start_cat_(start_cat), q_0_(&q_0) {}
// returns false if the intersection is empty
bool Compose(const EGrammar& g, Hypergraph* forest) {
goal_node = NULL;
EGrammar::const_iterator sit = g.find(start_cat_);
forest->ReserveNodes(kMAX_NODES);
assert(sit != g.end());
Edge* init = new Edge(start_cat_, &sit->second, q_0_);
if (!IncorporateNewEdge(init)) {
cerr << "Failed to create initial edge!\n";
abort();
}
while (exp_agenda.HasWork() || agenda.HasWork()) {
while(exp_agenda.HasWork()) {
const Edge* edge = exp_agenda.Next();
FinishEdge(edge, forest);
}
if (agenda.HasWork()) {
const Edge* edge = agenda.Next();
#ifdef DEBUG_CHART_PARSER
cerr << "processing (" << edge->id << ')' << endl;
#endif
if (edge->IsActive()) {
if (edge->dot->HasTerminals())
DoScan(edge);
if (edge->dot->HasNonTerminals()) {
DoMergeWithPassives(edge);
DoPredict(edge, g);
}
} else {
DoComplete(edge);
}
}
}
if (goal_node) {
forest->PruneUnreachable(goal_node->id_);
RemoveEpsilons(forest, kEPS);
}
FreeAll();
return goal_node;
}
void FreeAll() {
for (int i = 0; i < free_list_.size(); ++i)
delete free_list_[i];
free_list_.clear();
for (int i = 0; i < traversal_free_list_.size(); ++i)
delete traversal_free_list_[i];
traversal_free_list_.clear();
all_traversals.clear();
exp_agenda.clear();
agenda.clear();
tps2node.clear();
edge2node.clear();
all_edges.clear();
passive_edges.clear();
active_edges.clear();
}
~EarleyComposerImpl() {
FreeAll();
}
// returns the total number of edges created during composition
int EdgesCreated() const {
return free_list_.size();
}
private:
void DoScan(const Edge* edge) {
// here, we assume that the FST will potentially have many more outgoing
// edges than the grammar, which will be just a couple. If you want to
// efficiently handle the case where both are relatively large, this code
// will need to change how the intersection is done. The best general
// solution would probably be the Baeza-Yates double binary search.
const EGrammarNode* dot = edge->dot;
const FSTNode* r = edge->r;
const map<WordID, EGrammarNode>& terms = dot->GetTerminals();
for (map<WordID, EGrammarNode>::const_iterator git = terms.begin();
git != terms.end(); ++git) {
const FSTNode* next_r = r->Extend(git->first);
if (!next_r) continue;
const EGrammarNode* next_dot = &git->second;
const bool grammar_continues = next_dot->GrammarContinues();
const bool rule_completes = next_dot->RuleCompletes();
assert(grammar_continues || rule_completes);
const SparseVector<double>& input_features = next_dot->GetCFGProductionFeatures();
// create up to 4 new edges!
if (next_r->HasOutgoingNonEpsilonEdges()) { // are there further symbols in the FST?
const TargetPhraseSet* translations = NULL;
if (rule_completes)
IncorporateNewEdge(new Edge(edge->cat, next_dot, edge->q, next_r, edge, translations, input_features));
if (grammar_continues)
IncorporateNewEdge(new Edge(edge->cat, next_dot, edge->q, next_r, edge, translations));
}
if (next_r->HasData()) { // indicates a loop back to q_0 in the FST
const TargetPhraseSet* translations = next_r->GetTranslations();
if (rule_completes)
IncorporateNewEdge(new Edge(edge->cat, next_dot, edge->q, q_0_, edge, translations, input_features));
if (grammar_continues)
IncorporateNewEdge(new Edge(edge->cat, next_dot, edge->q, q_0_, edge, translations));
}
}
}
void DoPredict(const Edge* edge, const EGrammar& g) {
const EGrammarNode* dot = edge->dot;
const map<WordID, EGrammarNode>& non_terms = dot->GetNonTerminals();
for (map<WordID, EGrammarNode>::const_iterator git = non_terms.begin();
git != non_terms.end(); ++git) {
const WordID nt_to_predict = git->first;
//cerr << edge->id << " -- " << TD::Convert(nt_to_predict*-1) << endl;
EGrammar::const_iterator egi = g.find(nt_to_predict);
if (egi == g.end()) {
cerr << "[ERROR] Can't find any grammar rules with a LHS of type "
<< TD::Convert(-1*nt_to_predict) << '!' << endl;
continue;
}
assert(edge->IsActive());
const EGrammarNode* new_dot = &egi->second;
Edge* new_edge = new Edge(nt_to_predict, new_dot, edge->r, edge);
IncorporateNewEdge(new_edge);
}
}
void DoComplete(const Edge* passive) {
#ifdef DEBUG_CHART_PARSER
cerr << " complete: " << *passive << endl;
#endif
const WordID completed_nt = passive->cat;
const FSTNode* q = passive->q;
const FSTNode* next_r = passive->r;
const Edge query(q);
const pair<unordered_multiset<const Edge*, REdgeHash, REdgeEquals>::iterator,
unordered_multiset<const Edge*, REdgeHash, REdgeEquals>::iterator > p =
active_edges.equal_range(&query);
for (unordered_multiset<const Edge*, REdgeHash, REdgeEquals>::iterator it = p.first;
it != p.second; ++it) {
const Edge* active = *it;
#ifdef DEBUG_CHART_PARSER
cerr << " pos: " << *active << endl;
#endif
const EGrammarNode* next_dot = active->dot->Extend(completed_nt);
if (!next_dot) continue;
const SparseVector<double>& input_features = next_dot->GetCFGProductionFeatures();
// add up to 2 rules
if (next_dot->RuleCompletes())
IncorporateNewEdge(new Edge(active->cat, next_dot, active->q, next_r, active, passive, input_features));
if (next_dot->GrammarContinues())
IncorporateNewEdge(new Edge(active->cat, next_dot, active->q, next_r, active, passive));
}
}
void DoMergeWithPassives(const Edge* active) {
// edge is active, has non-terminals, we need to find the passives that can extend it
assert(active->IsActive());
assert(active->dot->HasNonTerminals());
#ifdef DEBUG_CHART_PARSER
cerr << " merge active with passives: ACT=" << *active << endl;
#endif
const Edge query(active->r, 1);
const pair<unordered_multiset<const Edge*, QEdgeHash, QEdgeEquals>::iterator,
unordered_multiset<const Edge*, QEdgeHash, QEdgeEquals>::iterator > p =
passive_edges.equal_range(&query);
for (unordered_multiset<const Edge*, QEdgeHash, QEdgeEquals>::iterator it = p.first;
it != p.second; ++it) {
const Edge* passive = *it;
const EGrammarNode* next_dot = active->dot->Extend(passive->cat);
if (!next_dot) continue;
const FSTNode* next_r = passive->r;
const SparseVector<double>& input_features = next_dot->GetCFGProductionFeatures();
if (next_dot->RuleCompletes())
IncorporateNewEdge(new Edge(active->cat, next_dot, active->q, next_r, active, passive, input_features));
if (next_dot->GrammarContinues())
IncorporateNewEdge(new Edge(active->cat, next_dot, active->q, next_r, active, passive));
}
}
// take ownership of edge memory, add to various indexes, etc
// returns true if this edge is new
bool IncorporateNewEdge(Edge* edge) {
free_list_.push_back(edge);
if (edge->passive_parent && edge->active_parent) {
Traversal* t = new Traversal(edge, edge->active_parent, edge->passive_parent);
traversal_free_list_.push_back(t);
if (all_traversals.find(t) != all_traversals.end()) {
return false;
} else {
all_traversals.insert(t);
}
}
exp_agenda.AddEdge(edge);
return true;
}
bool FinishEdge(const Edge* edge, Hypergraph* hg) {
bool is_new = false;
if (all_edges.find(edge) == all_edges.end()) {
#ifdef DEBUG_CHART_PARSER
cerr << *edge << " is NEW\n";
#endif
all_edges.insert(edge);
is_new = true;
if (edge->IsPassive()) passive_edges.insert(edge);
if (edge->IsActive()) active_edges.insert(edge);
agenda.AddEdge(edge);
} else {
#ifdef DEBUG_CHART_PARSER
cerr << *edge << " is NOT NEW.\n";
#endif
}
AddEdgeToTranslationForest(edge, hg);
return is_new;
}
// build the translation forest
void AddEdgeToTranslationForest(const Edge* edge, Hypergraph* hg) {
assert(hg->nodes_.size() < kMAX_NODES);
Hypergraph::Node* tps = NULL;
// first add any target language rules
if (edge->tps) {
Hypergraph::Node*& node = tps2node[(size_t)edge->tps];
if (!node) {
// cerr << "Creating phrases for " << edge->tps << endl;
const vector<TRulePtr>& rules = edge->tps->GetRules();
node = hg->AddNode(kPHRASE);
for (int i = 0; i < rules.size(); ++i) {
Hypergraph::Edge* hg_edge = hg->AddEdge(rules[i], Hypergraph::TailNodeVector());
hg_edge->feature_values_ += rules[i]->GetFeatureValues();
hg->ConnectEdgeToHeadNode(hg_edge, node);
}
}
tps = node;
}
Hypergraph::Node*& head_node = edge2node[edge];
if (!head_node)
head_node = hg->AddNode(edge->cat);
if (edge->cat == start_cat_ && edge->q == q_0_ && edge->r == q_0_ && edge->IsPassive()) {
assert(goal_node == NULL || goal_node == head_node);
goal_node = head_node;
}
int rhs1 = 0;
int rhs2 = 0;
Hypergraph::TailNodeVector tail;
SparseVector<double> extra;
if (edge->IsCreatedByPredict()) {
// extra.set_value(FD::Convert("predict"), 1);
} else if (edge->IsCreatedByScan()) {
tail.push_back(edge2node[edge->active_parent]->id_);
rhs1 = edge->active_parent->cat;
if (tps) {
tail.push_back(tps->id_);
rhs2 = kPHRASE;
}
//extra.set_value(FD::Convert("scan"), 1);
} else if (edge->IsCreatedByComplete()) {
tail.push_back(edge2node[edge->active_parent]->id_);
rhs1 = edge->active_parent->cat;
tail.push_back(edge2node[edge->passive_parent]->id_);
rhs2 = edge->passive_parent->cat;
//extra.set_value(FD::Convert("complete"), 1);
} else {
assert(!"unexpected edge type!");
}
//cerr << head_node->id_ << "<--" << *edge << endl;
#ifdef DEBUG_CHART_PARSER
for (int i = 0; i < tail.size(); ++i)
if (tail[i] == head_node->id_) {
cerr << "ERROR: " << *edge << "\n i=" << i << endl;
if (i == 1) { cerr << "\tP: " << *edge->passive_parent << endl; }
if (i == 0) { cerr << "\tA: " << *edge->active_parent << endl; }
assert(!"self-loop found!");
}
#endif
Hypergraph::Edge* hg_edge = NULL;
if (tail.size() == 0) {
hg_edge = hg->AddEdge(CreateEpsilonRule(edge->cat), tail);
} else if (tail.size() == 1) {
hg_edge = hg->AddEdge(CreateUnaryRule(edge->cat, rhs1), tail);
} else if (tail.size() == 2) {
hg_edge = hg->AddEdge(CreateBinaryRule(edge->cat, rhs1, rhs2), tail);
}
if (edge->features)
hg_edge->feature_values_ += *edge->features;
hg_edge->feature_values_ += extra;
hg->ConnectEdgeToHeadNode(hg_edge, head_node);
}
Hypergraph::Node* goal_node;
EdgeQueue exp_agenda;
EdgeQueue agenda;
unordered_map<size_t, Hypergraph::Node*> tps2node;
unordered_map<const Edge*, Hypergraph::Node*, UniqueEdgeHash, UniqueEdgeEquals> edge2node;
unordered_set<const Traversal*, UniqueTraversalHash, UniqueTraversalEquals> all_traversals;
unordered_set<const Edge*, UniqueEdgeHash, UniqueEdgeEquals> all_edges;
unordered_multiset<const Edge*, QEdgeHash, QEdgeEquals> passive_edges;
unordered_multiset<const Edge*, REdgeHash, REdgeEquals> active_edges;
vector<Edge*> free_list_;
vector<Traversal*> traversal_free_list_;
const WordID start_cat_;
const FSTNode* const q_0_;
};
#ifdef DEBUG_CHART_PARSER
static string TrimRule(const string& r) {
size_t start = r.find(" |||") + 5;
size_t end = r.rfind(" |||");
return r.substr(start, end - start);
}
#endif
void AddGrammarRule(const string& r, EGrammar* g) {
const size_t pos = r.find(" ||| ");
if (pos == string::npos || r[0] != '[') {
cerr << "Bad rule: " << r << endl;
return;
}
const size_t rpos = r.rfind(" ||| ");
string feats;
string rs = r;
if (rpos != pos) {
feats = r.substr(rpos + 5);
rs = r.substr(0, rpos);
}
string rhs = rs.substr(pos + 5);
string trule = rs + " ||| " + rhs + " ||| " + feats;
TRule tr(trule);
#ifdef DEBUG_CHART_PARSER
string hint_last_rule;
#endif
EGrammarNode* cur = &(*g)[tr.GetLHS()];
cur->is_root = true;
for (int i = 0; i < tr.FLength(); ++i) {
WordID sym = tr.f()[i];
#ifdef DEBUG_CHART_PARSER
hint_last_rule = TD::Convert(sym < 0 ? -sym : sym);
cur->hint += " <@@> (*" + hint_last_rule + ") " + TrimRule(tr.AsString());
#endif
if (sym < 0)
cur = &cur->ntptr[sym];
else
cur = &cur->tptr[sym];
}
#ifdef DEBUG_CHART_PARSER
cur->hint += " <@@> (" + hint_last_rule + "*) " + TrimRule(tr.AsString());
#endif
cur->is_some_rule_complete = true;
cur->input_features = tr.GetFeatureValues();
}
EarleyComposer::~EarleyComposer() {
delete pimpl_;
}
EarleyComposer::EarleyComposer(const FSTNode* fst) {
InitializeConstants();
pimpl_ = new EarleyComposerImpl(kUNIQUE_START, *fst);
}
bool EarleyComposer::Compose(const Hypergraph& src_forest, Hypergraph* trg_forest) {
// first, convert the src forest into an EGrammar
EGrammar g;
const int nedges = src_forest.edges_.size();
const int nnodes = src_forest.nodes_.size();
vector<int> cats(nnodes);
bool assign_cats = false;
for (int i = 0; i < nnodes; ++i)
if (assign_cats) {
cats[i] = TD::Convert("CAT_" + boost::lexical_cast<string>(i)) * -1;
} else {
cats[i] = src_forest.nodes_[i].cat_;
}
// construct the grammar
for (int i = 0; i < nedges; ++i) {
const Hypergraph::Edge& edge = src_forest.edges_[i];
const vector<WordID>& src = edge.rule_->f();
EGrammarNode* cur = &g[cats[edge.head_node_]];
cur->is_root = true;
int ntc = 0;
for (int j = 0; j < src.size(); ++j) {
WordID sym = src[j];
if (sym <= 0) {
sym = cats[edge.tail_nodes_[ntc]];
++ntc;
cur = &cur->ntptr[sym];
} else {
cur = &cur->tptr[sym];
}
}
cur->is_some_rule_complete = true;
cur->input_features = edge.feature_values_;
}
EGrammarNode& goal_rule = g[kUNIQUE_START];
assert((goal_rule.ntptr.size() == 1 && goal_rule.tptr.size() == 0) ||
(goal_rule.ntptr.size() == 0 && goal_rule.tptr.size() == 1));
return pimpl_->Compose(g, trg_forest);
}
bool EarleyComposer::Compose(istream* in, Hypergraph* trg_forest) {
EGrammar g;
while(*in) {
string line;
getline(*in, line);
if (line.empty()) continue;
AddGrammarRule(line, &g);
}
return pimpl_->Compose(g, trg_forest);
}
| 33.683727 | 115 | 0.630381 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.