text
stringlengths 8
6.88M
|
|---|
/*
* Copyright (c) 2009-2012 André Tupinambá (andrelrt@gmail.com)
*
* 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.
*/
//-----------------------------------------------------------------------------
#ifndef _DCL_INFO_SAMPLER_H_
#define _DCL_INFO_SAMPLER_H_
#if (defined _MSC_VER) && (_MSC_VER >= 1200)
#pragma once
#endif
#include <string.h>
#include "distributedcl_internal.h"
#include "library_exception.h"
#include "dcl_objects.h"
#include "icd_object.h"
//-----------------------------------------------------------------------------
namespace dcl {
namespace info {
//-----------------------------------------------------------------------------
struct sampler_info
{
public:
cl_bool normalized_coords_;
cl_addressing_mode addressing_mode_;
cl_filter_mode filter_mode_;
sampler_info()
{
memset( this, 0, sizeof(sampler_info) );
}
inline size_t get_info_size( cl_device_info info ) const
{
switch( info )
{
case CL_SAMPLER_NORMALIZED_COORDS: return sizeof(cl_bool);
case CL_SAMPLER_ADDRESSING_MODE: return sizeof(cl_addressing_mode);
case CL_SAMPLER_FILTER_MODE: return sizeof(cl_filter_mode);
default:
throw library_exception( CL_INVALID_VALUE );
}
}
inline const void* get_info_pointer( cl_device_info info ) const
{
switch( info )
{
case CL_SAMPLER_NORMALIZED_COORDS: return &normalized_coords_;
case CL_SAMPLER_ADDRESSING_MODE: return &addressing_mode_;
case CL_SAMPLER_FILTER_MODE: return &filter_mode_;
default:
throw library_exception( CL_INVALID_VALUE );
}
}
};
//-----------------------------------------------------------------------------
class generic_sampler :
public cl_object< cl_sampler, cl_sampler_info, CL_INVALID_SAMPLER >,
public icd_object< cl_sampler, dcl_sampler_id >,
public dcl_object< sampler_info >
{
public:
virtual ~generic_sampler(){}
generic_sampler( cl_bool normalized_coords, cl_addressing_mode addressing_mode,
cl_filter_mode filter_mode )
{
local_info_.normalized_coords_ = normalized_coords;
local_info_.addressing_mode_ = addressing_mode;
local_info_.filter_mode_ = filter_mode;
}
inline const sampler_info& get_info() const
{
return local_info_;
}
protected:
sampler_info local_info_;
};
//-----------------------------------------------------------------------------
}} // namespace dcl::info
//-----------------------------------------------------------------------------
#endif // _DCL_INFO_KERNEL_H_
|
#include "GroupInfoStruct.h"
#include "GroupMemberInfoStruct.h"
GroupInfoStruct::GroupInfoStruct()
{
}
|
class Solution {
public:
int consecutiveNumbersSum(int n) {
int res = 1; // the array of [n]
for (int i = 2; i < sqrt(2 * n); i++) {
if ((n - i * (i - 1) / 2) % i == 0) res++;
}
return res;
}
};
|
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <fstream>
#include "story.h"
using namespace std;
int main(int argc, char ** argv){
string in_story;
string in_cat;
ifstream load_story;
ifstream load_cat;
Story story;
CategoryArr & arr = story.getCategoryArr();
if (argc == 3){
load_story.open(argv[2]);
load_cat.open(argv[1]);
if(load_story.fail()|load_cat.fail()){
cerr << "cannot open file" << endl;
return EXIT_FAILURE;
}
while (!load_story.eof()){
getline(load_story,in_story);
story.addintoRawData(in_story);
}
load_story.close();
while (!load_cat.eof()){
getline(load_cat,in_cat);
arr.addIntoCategory(in_cat);
}
load_cat.close();
story.printStory();
exit(EXIT_SUCCESS);
}
else{
cerr << "wrong format of input" << endl;
exit(EXIT_FAILURE);
}
}
|
#include "piece.h"
#include <iostream>
using namespace std;
Piece::Piece(const int (&board)[25][10], int type, int orientation, pair<int, int> coordinate, bool alive):
board(board),
type(type),
orientation(orientation),
coordinate(coordinate),
alive(alive)
{
};
int Piece::get_type() const{
return this->type;
}
int Piece::get_orientation() const{
return this->orientation;
}
bool Piece::get_alive() const{
return this->alive;
}
pair<int, int> Piece::get_coordinate() const{
return this->coordinate;
}
void Piece::move_left(){
// 1. Moving doesn't make it out of boundary
// 2. Moving doesn't make cover occupied squares
pair<int, int> occupied[4];
get_occupied_coordinates(occupied);
// Left <==> .second-1
bool invalid=false;
for(int j=0; j<4 && !invalid; ++j){
int new_y = occupied[j].first,
new_x = occupied[j].second-1;
if(new_x<0 || board[new_y][new_x]>0) invalid=true;
}
if(!invalid) --coordinate.second;
}
void Piece::move_right(){
pair<int, int> occupied[4];
get_occupied_coordinates(occupied);
// Right <==> .second+1
bool invalid=false;
for(int j=0; j<4 && !invalid; ++j){
int new_y = occupied[j].first,
new_x = occupied[j].second+1;
if(new_x>=10 || board[new_y][new_x]>0) invalid=true;
}
if(!invalid) ++coordinate.second;
}
void Piece:: move_down(){ // 判斷電死
pair<int, int> occupied[4];
get_occupied_coordinates(occupied);
// Down <==> .first-1
for(int j=0; j<4 && alive; ++j){
int new_y = occupied[j].first-1,
new_x = occupied[j].second;
if(new_y<0 || board[new_y][new_x]>0) alive=false;
}
if(alive) --coordinate.first;
}
void Piece::drop(){ // 直接電死
while(alive)
{
move_down();
}
}
void Piece::rotate(){
{
orientation = (orientation+1)%4; // Do
pair<int, int> new_occupied[4];
get_occupied_coordinates(new_occupied);
bool invalid = false;
for(int j=0; j<4 && !invalid; ++j){
int new_y = new_occupied[j].first,
new_x = new_occupied[j].second;
if(new_x<0 || new_x>=10 || new_y<0 || new_y>=25 || board[new_y][new_x]>0) invalid=true;
}
if(!invalid) return;
else orientation = (orientation+4-1)%4; // Undo
}
// Invalid. Try moving left or right by 1
int try_this_order[4] = {-1, 1, -2, 2};
int num_of_try = 2;
if(type == 1) num_of_try = 4;
for(int j=0; j< num_of_try; ++j){
int dx = try_this_order[j];
coordinate.second += dx; // Do
orientation = (orientation+1)%4; // Do
pair<int, int> new_occupied[4];
get_occupied_coordinates(new_occupied);
bool invalid = false;
for(int j=0; j<4 && !invalid; ++j){
int new_y = new_occupied[j].first,
new_x = new_occupied[j].second;
if(new_x<0 || new_x>=10 || new_y<0 || new_y>=25 || board[new_y][new_x]>0) invalid=true;
}
if(!invalid) return;
else{
orientation = (orientation+4-1)%4; // Undo
coordinate.second -= dx; // Undo
}
}
}
|
#include <bson/Value.h>
#include <iostream>
int main(){
BSON::Value doc = BSON::Object{
{"undefined",BSON::Value{}},
{"int32",(BSON::int32)1},
{"int64",(BSON::int64)1},
{"double",3.14},
{"true",true},
{"false",false},
{"string","foobar"},
{"datetime",std::chrono::milliseconds{123}},
{"object",BSON::Object{{"foo","bar"}}},
{"array",BSON::Array{1,2,3}}
};
std::string test = doc.toBSON();
BSON::Value reDoc = BSON::Value::fromBSON(test);
std::string & foo = reDoc["string"];
std::cout<<foo<<std::endl;
std::cout<<doc.toJSON()<<std::endl;
std::cout<<reDoc.toJSON()<<std::endl;
return 0;
}
|
// learning c++
#include<iostream>
using namespace std;
int main()
{
int ary;
cout<< "welcome to c++ tutorial"<<endl;
cout << "value of ary is" << ary << endl;
return 0;
}
|
#include<iostream>
#include<algorithm>
#include<vector>
#include<set>
#include<queue>
using namespace std;
set<long long>PrimeSet;
long long GetNextPrime()
{
long long k;
for(k=;;k++)
{
bool Flag=false;
for(int j=0;j<PrimeSet.size();j++)
{
if(k%PrimeSet[j]==0)
{
Flag=true;
break;
}
}
if(!Flag)
{
break;
}
}
PrimeSet.push(k);
for(priority_queue<long long>::iterator iter=PrimeSet.begin();iter!=PrimeSet.end();iter++)
{
long long current=iter;
if(current%k!=0)
{
PrimeSet.push(current*k);
}
}
return k;
}
int main()
{
long long k=0;
PrimeSet.clear();PrimeSet.push(2);PrimeSet.push(3);GetNextPrime();
priority_queue<long long>::iterator iter=PrimeSet.begin();iter++;iter++;
cin >>k;
for(int i=4;;i++)
{
cout <<i<<endl;
if(i>=iter)
{
iter++;
i++;
}
k--;
}
return 0;
}
|
//
// Copyright Jason Rice 2017
// Distributed under 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)
//
#ifndef NBDL_SQL_DB_INSERT_HPP
#define NBDL_SQL_DB_INSERT_HPP
#include <nbdl/concept/Entity.hpp>
#include <nbdl/concept/EntityContainer.hpp>
#include <nbdl/fwd/sql_db/insert.hpp>
#include <nbdl/sql_db/traits.hpp>
#include <boost/hana/concat.hpp>
#include <boost/hana/core/default.hpp>
#include <boost/hana/core/when.hpp>
#include <boost/hana/pair.hpp>
#include <boost/hana/tuple.hpp>
#include <utility>
namespace nbdl::sql_db
{
namespace hana = boost::hana;
template <typename DbInsert, typename Entity>
auto insert_fn::operator()(DbInsert db_insert, Entity&& e) const
{
return this->operator()(db_insert, std::forward<Entity>(e), hana::tuple<>{});
};
template <typename DbInsert, typename Entity, typename ForeignKeys>
auto insert_fn::operator()(DbInsert db_insert, Entity&& e, ForeignKeys&& keys) const
{
using Tag = std::decay_t<Entity>;
using Impl = insert_impl<Tag>;
return Impl::apply(db_insert, std::forward<Entity>(e), std::forward<ForeignKeys>(keys));
};
// one-to-one:
// child => parent w/child_id
// one-to-many:
// parent => child w/parent_id
template<typename Tag, bool condition>
struct insert_impl<Tag, hana::when<condition>>
: hana::default_
{
static auto apply(...) = delete;
};
template <Entity T>
struct insert_impl<T>
{
// ForeignKeys would be an owner_id or
// the keys in a path from a nbdl::Message
template <typename DbInsert, typename Entity, typename ForeignKeys>
static auto apply(DbInsert db_insert, Entity&& e, ForeignKeys&& keys)
-> primary_key<T>
{
using ChildMembers = members_child<T>;
using MultiMembers = members_multirow<T>;
using ValueMembers = members_value<T>;
// insert children (one-to-one)
auto child_ids = hana::unpack(ChildMembers{}, [&](auto ...member)
{
return hana::make_tuple(
hana::make_pair(
member_key_name<decltype(member)>{}
, insert(db_insert, nbdl::get_member<decltype(member)>(std::forward<Entity>(e)))
)...
);
});
// get "values" map
auto values = hana::unpack(ValueMembers{}, [&](auto ...member)
{
return hana::make_tuple(
hana::make_pair(
nbdl::member_name<decltype(member)>{}
, nbdl::get_member<decltype(member)>(std::forward<Entity>(e))
)...
);
});
// insert self
primary_key<T> insert_id{db_insert(
table_name<T>{}
, hana::concat(
hana::concat(
std::forward<ForeignKeys>(keys)
, std::move(child_ids)
)
, std::move(values)
)
)};
// insert children in containers (one-to-many)
hana::for_each(MultiMembers{}, [&](auto member)
{
insert(
db_insert
, nbdl::get_member<decltype(member)>(std::forward<Entity>(e))
, hana::make_tuple(
hana::make_pair(
table_key_name<T>{}
, insert_id
)
)
);
});
return insert_id;
}
};
template <EntityContainer T>
struct insert_impl<T>
{
template <typename DbInsert, typename Container, typename ForeignKeys>
static void apply(DbInsert db_insert, Container&& c, ForeignKeys&& keys)
{
for (auto&& x : std::forward<Container>(c))
{
insert(
db_insert
, std::forward<decltype(x)>(x)
, std::forward<ForeignKeys>(keys)
);
}
};
};
}
#endif
|
#pragma once
#include "Core.h"
template <class T>
class ObjPool final{
public:
ObjPool<T>();
~ObjPool<T>();
const std::vector<std::pair<bool, T*>>& GetObjPool();
T* const& RetrieveInactiveObj();
void CreateObjs(int amt);
private:
std::vector<std::pair<bool, T*>> im_ObjPool;
};
#include "ObjPool.inl"
|
/****************************************
*
* INSERT-PROJECT-NAME-HERE - INSERT-GENERIC-NAME-HERE
* Copyright (C) 2019 Victor Tran
*
* 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, either version 3 of the License, or
* (at your option) any later version.
*
* 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, see <http://www.gnu.org/licenses/>.
*
* *************************************/
#include "friendsdialog.h"
#include "ui_friendsdialog.h"
#include <the-libs_global.h>
#include "private/friendsmodel.h"
#include "pauseoverlay.h"
#include "textinputoverlay.h"
#include "questionoverlay.h"
#include "onlineapi.h"
#include <QKeyEvent>
#include <QShortcut>
struct FriendsDialogPrivate {
FriendsModel* model;
};
FriendsDialog::FriendsDialog(QWidget *parent) :
QWidget(parent),
ui(new Ui::FriendsDialog)
{
ui->setupUi(this);
d = new FriendsDialogPrivate();
d->model = new FriendsModel();
ui->leftWidget->setFixedWidth(SC_DPI(300));
ui->friendsList->setModel(d->model);
ui->friendsList->setItemDelegate(new FriendsDelegate);
ui->friendsList->installEventFilter(this);
ui->addFriendPage->setFocusProxy(ui->addFriendByUsernameButton);
this->setFocusProxy(ui->friendsList);
connect(ui->friendsList->selectionModel(), &QItemSelectionModel::selectionChanged, this, [=](QItemSelection current, QItemSelection previous) {
QModelIndex index = current.indexes().first();
QString pane = index.data(Qt::UserRole).toString();
if (pane == "friend-add") {
ui->stackedWidget->setCurrentWidget(ui->addFriendPage);
} else if (pane == "friend") {
ui->friendPage->setActiveUser(index.data(Qt::DisplayRole).toString(), index.data(Qt::UserRole + 2).toString());
ui->stackedWidget->setCurrentWidget(ui->friendPage);
}
});
connect(ui->friendPage, &FriendPage::blockUi, this, [=](bool block) {
if (block) {
ui->mainStack->setCurrentWidget(ui->loaderPage);
} else {
ui->mainStack->setCurrentWidget(ui->mainPage);
}
});
connect(ui->friendPage, &FriendPage::reloadFriendsModel, this, [=] {
d->model->update();
});
ui->gamepadHud->setButtonText(QGamepadManager::ButtonA, tr("Select"));
ui->gamepadHud->setButtonText(QGamepadManager::ButtonB, tr("Back"));
ui->gamepadHud->setButtonAction(QGamepadManager::ButtonA, GamepadHud::standardAction(GamepadHud::SelectAction));
ui->gamepadHud->setButtonAction(QGamepadManager::ButtonB, [=] {
if (ui->friendsList->hasFocus()) {
ui->backButton->click();
} else {
ui->friendsList->setFocus();
}
});
QShortcut* backShortcut = new QShortcut(QKeySequence(Qt::Key_Escape), this);
connect(backShortcut, &QShortcut::activated, this, [=] {
if (ui->friendsList->hasFocus()) {
ui->backButton->click();
} else {
ui->friendsList->setFocus();
}
});
ui->focusBarrier->setBounceWidget(ui->addFriendByUsernameButton);
ui->focusBarrier_2->setBounceWidget(ui->addFriendByUsernameButton);
PauseOverlay::overlayForWindow(parent)->pushOverlayWidget(this);
}
FriendsDialog::~FriendsDialog()
{
delete ui;
// delete d;
}
void FriendsDialog::on_backButton_clicked()
{
PauseOverlay::overlayForWindow(this)->popOverlayWidget([=] {
emit done();
});
}
void FriendsDialog::on_addFriendByUsernameButton_clicked()
{
bool canceled;
QString username = TextInputOverlay::getText(this, tr("What's your friend's username?"), &canceled);
if (!canceled) {
//Send the friend request
ui->mainStack->setCurrentWidget(ui->loaderPage);
OnlineApi::instance()->post("/friends/requestByUsername", {
{"username", username}
})->then([=](QJsonDocument doc) {
QuestionOverlay* question = new QuestionOverlay(this);
if (doc.object().contains("error")) {
question->setIcon(QMessageBox::Critical);
QString error = doc.object().value("error").toString();
if (error == "user.unknownTarget") {
question->setTitle(tr("Unknown User"));
question->setText(tr("That user doesn't exist."));
} else if (error == "friends.alreadyFriends") {
question->setTitle(tr("Already Friends"));
question->setText(tr("You're already friends with that user."));
} else {
question->setTitle(tr("Friend Request Failed"));
question->setText(error);
}
} else {
question->setIcon(QMessageBox::Information);
question->setTitle(tr("Friend Request Sent"));
question->setText(tr("Your friend request to %1 has been sent.").arg(username));
}
question->setButtons(QMessageBox::Ok);
connect(question, &QuestionOverlay::accepted, question, &QuestionOverlay::deleteLater);
connect(question, &QuestionOverlay::rejected, question, &QuestionOverlay::deleteLater);
d->model->update();
ui->mainStack->setCurrentWidget(ui->mainPage);
})->error([=](QString error) {
QuestionOverlay* question = new QuestionOverlay(this);
question->setIcon(QMessageBox::Critical);
question->setTitle(tr("Friend Request Failed"));
question->setText(OnlineApi::errorFromPromiseRejection(error));
question->setButtons(QMessageBox::Ok);
connect(question, &QuestionOverlay::accepted, question, &QuestionOverlay::deleteLater);
connect(question, &QuestionOverlay::rejected, question, &QuestionOverlay::deleteLater);
ui->mainStack->setCurrentWidget(ui->mainPage);
});
}
}
bool FriendsDialog::eventFilter(QObject*watched, QEvent*event)
{
if (watched == ui->friendsList && event->type() == QEvent::KeyPress) {
QKeyEvent* e = static_cast<QKeyEvent*>(event);
if (e->key() == Qt::Key_Right || e->key() == Qt::Key_Enter || e->key() == Qt::Key_Space) {
ui->stackedWidget->currentWidget()->setFocus();
} else if (e->key() == Qt::Key_Up) {
if (ui->friendsList->model()->index(ui->friendsList->currentIndex().row() - 1, 0).data(Qt::UserRole).toString() == "sep") {
ui->friendsList->setCurrentIndex(ui->friendsList->model()->index(ui->friendsList->currentIndex().row() - 2, 0));
return true;
}
} else if (e->key() == Qt::Key_Down) {
if (ui->friendsList->model()->index(ui->friendsList->currentIndex().row() + 1, 0).data(Qt::UserRole).toString() == "sep") {
ui->friendsList->setCurrentIndex(ui->friendsList->model()->index(ui->friendsList->currentIndex().row() + 2, 0));
return true;
}
}
}
return false;
}
|
/**
* author : Wang Shaotong
* email : wangshaotongsydemon@gmail.com
* date : 2020-04-08
*
* id : hdu 1692
* name : Destroy the Well of Life
* url : http://acm.hdu.edu.cn/showproblem.php?pid=1692
* level : 1
* tag : 枚举
*/
#include <iostream>
using namespace std;
const int MAXN = 100100;
const int INF = 0x3f3f3f;
int w[MAXN], l[MAXN], p[MAXN];
int main()
{
int t;
cin >> t;
int tmp = t;
while (t--) {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> w[i] >> l[i] >> p[i];
}
int minPoint = INF;
for (int i = 0; i < n; i++) {
int weight = 0, point = 0;
for (int j = i; j < n; j++) {
if (j >= n) {
j -= n;
}
if (w[j] + weight <= l[j]) {
point += p[j];
weight += w[j];
} else {
weight += w[j];
}
if (point > minPoint) { // 终止不符和条件的循环以减少时间
break;
}
}
minPoint = point < minPoint ? point : minPoint;
}
cout << "Case " << tmp - t << ": Need to use " << minPoint << " mana points." << endl;
}
return 0;
}
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "base.h"
WINRT_WARNING_PUSH
#include "internal/Windows.Foundation.3.h"
#include "internal/Windows.UI.Xaml.Interop.3.h"
#include "internal/Windows.Foundation.Collections.3.h"
#include "internal/Windows.UI.Xaml.3.h"
#include "internal/Windows.UI.Xaml.Markup.3.h"
#include "Windows.UI.Xaml.h"
WINRT_EXPORT namespace winrt {
namespace impl {
template <typename D>
struct produce<D, Windows::UI::Xaml::Markup::IComponentConnector> : produce_base<D, Windows::UI::Xaml::Markup::IComponentConnector>
{
HRESULT __stdcall abi_Connect(int32_t connectionId, impl::abi_arg_in<Windows::Foundation::IInspectable> target) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Connect(connectionId, *reinterpret_cast<const Windows::Foundation::IInspectable *>(&target));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::UI::Xaml::Markup::IComponentConnector2> : produce_base<D, Windows::UI::Xaml::Markup::IComponentConnector2>
{
HRESULT __stdcall abi_GetBindingConnector(int32_t connectionId, impl::abi_arg_in<Windows::Foundation::IInspectable> target, impl::abi_arg_out<Windows::UI::Xaml::Markup::IComponentConnector> returnValue) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*returnValue = detach_abi(this->shim().GetBindingConnector(connectionId, *reinterpret_cast<const Windows::Foundation::IInspectable *>(&target)));
return S_OK;
}
catch (...)
{
*returnValue = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::UI::Xaml::Markup::IDataTemplateComponent> : produce_base<D, Windows::UI::Xaml::Markup::IDataTemplateComponent>
{
HRESULT __stdcall abi_Recycle() noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Recycle();
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_ProcessBindings(impl::abi_arg_in<Windows::Foundation::IInspectable> item, int32_t itemIndex, int32_t phase, int32_t * nextPhase) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().ProcessBindings(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&item), itemIndex, phase, *nextPhase);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::UI::Xaml::Markup::IXamlBinaryWriter> : produce_base<D, Windows::UI::Xaml::Markup::IXamlBinaryWriter>
{};
template <typename D>
struct produce<D, Windows::UI::Xaml::Markup::IXamlBinaryWriterStatics> : produce_base<D, Windows::UI::Xaml::Markup::IXamlBinaryWriterStatics>
{
HRESULT __stdcall abi_Write(impl::abi_arg_in<Windows::Foundation::Collections::IVector<Windows::Storage::Streams::IRandomAccessStream>> inputStreams, impl::abi_arg_in<Windows::Foundation::Collections::IVector<Windows::Storage::Streams::IRandomAccessStream>> outputStreams, impl::abi_arg_in<Windows::UI::Xaml::Markup::IXamlMetadataProvider> xamlMetadataProvider, impl::abi_arg_out<Windows::UI::Xaml::Markup::XamlBinaryWriterErrorInformation> returnValue) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*returnValue = detach_abi(this->shim().Write(*reinterpret_cast<const Windows::Foundation::Collections::IVector<Windows::Storage::Streams::IRandomAccessStream> *>(&inputStreams), *reinterpret_cast<const Windows::Foundation::Collections::IVector<Windows::Storage::Streams::IRandomAccessStream> *>(&outputStreams), *reinterpret_cast<const Windows::UI::Xaml::Markup::IXamlMetadataProvider *>(&xamlMetadataProvider)));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::UI::Xaml::Markup::IXamlBindingHelper> : produce_base<D, Windows::UI::Xaml::Markup::IXamlBindingHelper>
{};
template <typename D>
struct produce<D, Windows::UI::Xaml::Markup::IXamlBindingHelperStatics> : produce_base<D, Windows::UI::Xaml::Markup::IXamlBindingHelperStatics>
{
HRESULT __stdcall get_DataTemplateComponentProperty(impl::abi_arg_out<Windows::UI::Xaml::IDependencyProperty> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().DataTemplateComponentProperty());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_GetDataTemplateComponent(impl::abi_arg_in<Windows::UI::Xaml::IDependencyObject> element, impl::abi_arg_out<Windows::UI::Xaml::Markup::IDataTemplateComponent> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().GetDataTemplateComponent(*reinterpret_cast<const Windows::UI::Xaml::DependencyObject *>(&element)));
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_SetDataTemplateComponent(impl::abi_arg_in<Windows::UI::Xaml::IDependencyObject> element, impl::abi_arg_in<Windows::UI::Xaml::Markup::IDataTemplateComponent> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetDataTemplateComponent(*reinterpret_cast<const Windows::UI::Xaml::DependencyObject *>(&element), *reinterpret_cast<const Windows::UI::Xaml::Markup::IDataTemplateComponent *>(&value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_SuspendRendering(impl::abi_arg_in<Windows::UI::Xaml::IUIElement> target) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SuspendRendering(*reinterpret_cast<const Windows::UI::Xaml::UIElement *>(&target));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_ResumeRendering(impl::abi_arg_in<Windows::UI::Xaml::IUIElement> target) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().ResumeRendering(*reinterpret_cast<const Windows::UI::Xaml::UIElement *>(&target));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_ConvertValue(impl::abi_arg_in<Windows::UI::Xaml::Interop::TypeName> type, impl::abi_arg_in<Windows::Foundation::IInspectable> value, impl::abi_arg_out<Windows::Foundation::IInspectable> returnValue) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*returnValue = detach_abi(this->shim().ConvertValue(*reinterpret_cast<const Windows::UI::Xaml::Interop::TypeName *>(&type), *reinterpret_cast<const Windows::Foundation::IInspectable *>(&value)));
return S_OK;
}
catch (...)
{
*returnValue = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_SetPropertyFromString(impl::abi_arg_in<Windows::Foundation::IInspectable> dependencyObject, impl::abi_arg_in<Windows::UI::Xaml::IDependencyProperty> propertyToSet, impl::abi_arg_in<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetPropertyFromString(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&dependencyObject), *reinterpret_cast<const Windows::UI::Xaml::DependencyProperty *>(&propertyToSet), *reinterpret_cast<const hstring *>(&value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_SetPropertyFromBoolean(impl::abi_arg_in<Windows::Foundation::IInspectable> dependencyObject, impl::abi_arg_in<Windows::UI::Xaml::IDependencyProperty> propertyToSet, bool value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetPropertyFromBoolean(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&dependencyObject), *reinterpret_cast<const Windows::UI::Xaml::DependencyProperty *>(&propertyToSet), value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_SetPropertyFromChar16(impl::abi_arg_in<Windows::Foundation::IInspectable> dependencyObject, impl::abi_arg_in<Windows::UI::Xaml::IDependencyProperty> propertyToSet, wchar_t value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetPropertyFromChar16(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&dependencyObject), *reinterpret_cast<const Windows::UI::Xaml::DependencyProperty *>(&propertyToSet), value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_SetPropertyFromDateTime(impl::abi_arg_in<Windows::Foundation::IInspectable> dependencyObject, impl::abi_arg_in<Windows::UI::Xaml::IDependencyProperty> propertyToSet, impl::abi_arg_in<Windows::Foundation::DateTime> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetPropertyFromDateTime(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&dependencyObject), *reinterpret_cast<const Windows::UI::Xaml::DependencyProperty *>(&propertyToSet), *reinterpret_cast<const Windows::Foundation::DateTime *>(&value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_SetPropertyFromDouble(impl::abi_arg_in<Windows::Foundation::IInspectable> dependencyObject, impl::abi_arg_in<Windows::UI::Xaml::IDependencyProperty> propertyToSet, double value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetPropertyFromDouble(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&dependencyObject), *reinterpret_cast<const Windows::UI::Xaml::DependencyProperty *>(&propertyToSet), value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_SetPropertyFromInt32(impl::abi_arg_in<Windows::Foundation::IInspectable> dependencyObject, impl::abi_arg_in<Windows::UI::Xaml::IDependencyProperty> propertyToSet, int32_t value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetPropertyFromInt32(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&dependencyObject), *reinterpret_cast<const Windows::UI::Xaml::DependencyProperty *>(&propertyToSet), value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_SetPropertyFromUInt32(impl::abi_arg_in<Windows::Foundation::IInspectable> dependencyObject, impl::abi_arg_in<Windows::UI::Xaml::IDependencyProperty> propertyToSet, uint32_t value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetPropertyFromUInt32(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&dependencyObject), *reinterpret_cast<const Windows::UI::Xaml::DependencyProperty *>(&propertyToSet), value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_SetPropertyFromInt64(impl::abi_arg_in<Windows::Foundation::IInspectable> dependencyObject, impl::abi_arg_in<Windows::UI::Xaml::IDependencyProperty> propertyToSet, int64_t value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetPropertyFromInt64(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&dependencyObject), *reinterpret_cast<const Windows::UI::Xaml::DependencyProperty *>(&propertyToSet), value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_SetPropertyFromUInt64(impl::abi_arg_in<Windows::Foundation::IInspectable> dependencyObject, impl::abi_arg_in<Windows::UI::Xaml::IDependencyProperty> propertyToSet, uint64_t value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetPropertyFromUInt64(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&dependencyObject), *reinterpret_cast<const Windows::UI::Xaml::DependencyProperty *>(&propertyToSet), value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_SetPropertyFromSingle(impl::abi_arg_in<Windows::Foundation::IInspectable> dependencyObject, impl::abi_arg_in<Windows::UI::Xaml::IDependencyProperty> propertyToSet, float value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetPropertyFromSingle(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&dependencyObject), *reinterpret_cast<const Windows::UI::Xaml::DependencyProperty *>(&propertyToSet), value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_SetPropertyFromPoint(impl::abi_arg_in<Windows::Foundation::IInspectable> dependencyObject, impl::abi_arg_in<Windows::UI::Xaml::IDependencyProperty> propertyToSet, impl::abi_arg_in<Windows::Foundation::Point> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetPropertyFromPoint(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&dependencyObject), *reinterpret_cast<const Windows::UI::Xaml::DependencyProperty *>(&propertyToSet), *reinterpret_cast<const Windows::Foundation::Point *>(&value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_SetPropertyFromRect(impl::abi_arg_in<Windows::Foundation::IInspectable> dependencyObject, impl::abi_arg_in<Windows::UI::Xaml::IDependencyProperty> propertyToSet, impl::abi_arg_in<Windows::Foundation::Rect> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetPropertyFromRect(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&dependencyObject), *reinterpret_cast<const Windows::UI::Xaml::DependencyProperty *>(&propertyToSet), *reinterpret_cast<const Windows::Foundation::Rect *>(&value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_SetPropertyFromSize(impl::abi_arg_in<Windows::Foundation::IInspectable> dependencyObject, impl::abi_arg_in<Windows::UI::Xaml::IDependencyProperty> propertyToSet, impl::abi_arg_in<Windows::Foundation::Size> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetPropertyFromSize(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&dependencyObject), *reinterpret_cast<const Windows::UI::Xaml::DependencyProperty *>(&propertyToSet), *reinterpret_cast<const Windows::Foundation::Size *>(&value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_SetPropertyFromTimeSpan(impl::abi_arg_in<Windows::Foundation::IInspectable> dependencyObject, impl::abi_arg_in<Windows::UI::Xaml::IDependencyProperty> propertyToSet, impl::abi_arg_in<Windows::Foundation::TimeSpan> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetPropertyFromTimeSpan(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&dependencyObject), *reinterpret_cast<const Windows::UI::Xaml::DependencyProperty *>(&propertyToSet), *reinterpret_cast<const Windows::Foundation::TimeSpan *>(&value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_SetPropertyFromByte(impl::abi_arg_in<Windows::Foundation::IInspectable> dependencyObject, impl::abi_arg_in<Windows::UI::Xaml::IDependencyProperty> propertyToSet, uint8_t value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetPropertyFromByte(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&dependencyObject), *reinterpret_cast<const Windows::UI::Xaml::DependencyProperty *>(&propertyToSet), value);
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_SetPropertyFromUri(impl::abi_arg_in<Windows::Foundation::IInspectable> dependencyObject, impl::abi_arg_in<Windows::UI::Xaml::IDependencyProperty> propertyToSet, impl::abi_arg_in<Windows::Foundation::IUriRuntimeClass> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetPropertyFromUri(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&dependencyObject), *reinterpret_cast<const Windows::UI::Xaml::DependencyProperty *>(&propertyToSet), *reinterpret_cast<const Windows::Foundation::Uri *>(&value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_SetPropertyFromObject(impl::abi_arg_in<Windows::Foundation::IInspectable> dependencyObject, impl::abi_arg_in<Windows::UI::Xaml::IDependencyProperty> propertyToSet, impl::abi_arg_in<Windows::Foundation::IInspectable> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetPropertyFromObject(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&dependencyObject), *reinterpret_cast<const Windows::UI::Xaml::DependencyProperty *>(&propertyToSet), *reinterpret_cast<const Windows::Foundation::IInspectable *>(&value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::UI::Xaml::Markup::IXamlMarkupHelper> : produce_base<D, Windows::UI::Xaml::Markup::IXamlMarkupHelper>
{};
template <typename D>
struct produce<D, Windows::UI::Xaml::Markup::IXamlMarkupHelperStatics> : produce_base<D, Windows::UI::Xaml::Markup::IXamlMarkupHelperStatics>
{
HRESULT __stdcall abi_UnloadObject(impl::abi_arg_in<Windows::UI::Xaml::IDependencyObject> element) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().UnloadObject(*reinterpret_cast<const Windows::UI::Xaml::DependencyObject *>(&element));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::UI::Xaml::Markup::IXamlMember> : produce_base<D, Windows::UI::Xaml::Markup::IXamlMember>
{
HRESULT __stdcall get_IsAttachable(bool * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().IsAttachable());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_IsDependencyProperty(bool * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().IsDependencyProperty());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_IsReadOnly(bool * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().IsReadOnly());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_Name(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Name());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_TargetType(impl::abi_arg_out<Windows::UI::Xaml::Markup::IXamlType> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().TargetType());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_Type(impl::abi_arg_out<Windows::UI::Xaml::Markup::IXamlType> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Type());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_GetValue(impl::abi_arg_in<Windows::Foundation::IInspectable> instance, impl::abi_arg_out<Windows::Foundation::IInspectable> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().GetValue(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&instance)));
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_SetValue(impl::abi_arg_in<Windows::Foundation::IInspectable> instance, impl::abi_arg_in<Windows::Foundation::IInspectable> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetValue(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&instance), *reinterpret_cast<const Windows::Foundation::IInspectable *>(&value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::UI::Xaml::Markup::IXamlMetadataProvider> : produce_base<D, Windows::UI::Xaml::Markup::IXamlMetadataProvider>
{
HRESULT __stdcall abi_GetXamlType(impl::abi_arg_in<Windows::UI::Xaml::Interop::TypeName> type, impl::abi_arg_out<Windows::UI::Xaml::Markup::IXamlType> xamlType) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*xamlType = detach_abi(this->shim().GetXamlType(*reinterpret_cast<const Windows::UI::Xaml::Interop::TypeName *>(&type)));
return S_OK;
}
catch (...)
{
*xamlType = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_GetXamlTypeByFullName(impl::abi_arg_in<hstring> fullName, impl::abi_arg_out<Windows::UI::Xaml::Markup::IXamlType> xamlType) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*xamlType = detach_abi(this->shim().GetXamlType(*reinterpret_cast<const hstring *>(&fullName)));
return S_OK;
}
catch (...)
{
*xamlType = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_GetXmlnsDefinitions(uint32_t * __definitionsSize, impl::abi_arg_out<Windows::UI::Xaml::Markup::XmlnsDefinition> * definitions) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
std::tie(*__definitionsSize, *definitions) = detach_abi(this->shim().GetXmlnsDefinitions());
return S_OK;
}
catch (...)
{
*__definitionsSize = 0;
*definitions = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::UI::Xaml::Markup::IXamlReader> : produce_base<D, Windows::UI::Xaml::Markup::IXamlReader>
{};
template <typename D>
struct produce<D, Windows::UI::Xaml::Markup::IXamlReaderStatics> : produce_base<D, Windows::UI::Xaml::Markup::IXamlReaderStatics>
{
HRESULT __stdcall abi_Load(impl::abi_arg_in<hstring> xaml, impl::abi_arg_out<Windows::Foundation::IInspectable> returnValue) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*returnValue = detach_abi(this->shim().Load(*reinterpret_cast<const hstring *>(&xaml)));
return S_OK;
}
catch (...)
{
*returnValue = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_LoadWithInitialTemplateValidation(impl::abi_arg_in<hstring> xaml, impl::abi_arg_out<Windows::Foundation::IInspectable> returnValue) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*returnValue = detach_abi(this->shim().LoadWithInitialTemplateValidation(*reinterpret_cast<const hstring *>(&xaml)));
return S_OK;
}
catch (...)
{
*returnValue = nullptr;
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::UI::Xaml::Markup::IXamlType> : produce_base<D, Windows::UI::Xaml::Markup::IXamlType>
{
HRESULT __stdcall get_BaseType(impl::abi_arg_out<Windows::UI::Xaml::Markup::IXamlType> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().BaseType());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_ContentProperty(impl::abi_arg_out<Windows::UI::Xaml::Markup::IXamlMember> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().ContentProperty());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_FullName(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().FullName());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_IsArray(bool * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().IsArray());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_IsCollection(bool * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().IsCollection());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_IsConstructible(bool * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().IsConstructible());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_IsDictionary(bool * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().IsDictionary());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_IsMarkupExtension(bool * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().IsMarkupExtension());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_IsBindable(bool * value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().IsBindable());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall get_ItemType(impl::abi_arg_out<Windows::UI::Xaml::Markup::IXamlType> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().ItemType());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_KeyType(impl::abi_arg_out<Windows::UI::Xaml::Markup::IXamlType> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().KeyType());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_UnderlyingType(impl::abi_arg_out<Windows::UI::Xaml::Interop::TypeName> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().UnderlyingType());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_ActivateInstance(impl::abi_arg_out<Windows::Foundation::IInspectable> instance) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*instance = detach_abi(this->shim().ActivateInstance());
return S_OK;
}
catch (...)
{
*instance = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_CreateFromString(impl::abi_arg_in<hstring> value, impl::abi_arg_out<Windows::Foundation::IInspectable> instance) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*instance = detach_abi(this->shim().CreateFromString(*reinterpret_cast<const hstring *>(&value)));
return S_OK;
}
catch (...)
{
*instance = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_GetMember(impl::abi_arg_in<hstring> name, impl::abi_arg_out<Windows::UI::Xaml::Markup::IXamlMember> xamlMember) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*xamlMember = detach_abi(this->shim().GetMember(*reinterpret_cast<const hstring *>(&name)));
return S_OK;
}
catch (...)
{
*xamlMember = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall abi_AddToVector(impl::abi_arg_in<Windows::Foundation::IInspectable> instance, impl::abi_arg_in<Windows::Foundation::IInspectable> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().AddToVector(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&instance), *reinterpret_cast<const Windows::Foundation::IInspectable *>(&value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_AddToMap(impl::abi_arg_in<Windows::Foundation::IInspectable> instance, impl::abi_arg_in<Windows::Foundation::IInspectable> key, impl::abi_arg_in<Windows::Foundation::IInspectable> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().AddToMap(*reinterpret_cast<const Windows::Foundation::IInspectable *>(&instance), *reinterpret_cast<const Windows::Foundation::IInspectable *>(&key), *reinterpret_cast<const Windows::Foundation::IInspectable *>(&value));
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
HRESULT __stdcall abi_RunInitializer() noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().RunInitializer();
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
}
namespace Windows::UI::Xaml::Markup {
template <typename D> void impl_IComponentConnector<D>::Connect(int32_t connectionId, const Windows::Foundation::IInspectable & target) const
{
check_hresult(WINRT_SHIM(IComponentConnector)->abi_Connect(connectionId, get_abi(target)));
}
template <typename D> Windows::UI::Xaml::Markup::IComponentConnector impl_IComponentConnector2<D>::GetBindingConnector(int32_t connectionId, const Windows::Foundation::IInspectable & target) const
{
Windows::UI::Xaml::Markup::IComponentConnector returnValue;
check_hresult(WINRT_SHIM(IComponentConnector2)->abi_GetBindingConnector(connectionId, get_abi(target), put_abi(returnValue)));
return returnValue;
}
template <typename D> bool impl_IXamlMember<D>::IsAttachable() const
{
bool value {};
check_hresult(WINRT_SHIM(IXamlMember)->get_IsAttachable(&value));
return value;
}
template <typename D> bool impl_IXamlMember<D>::IsDependencyProperty() const
{
bool value {};
check_hresult(WINRT_SHIM(IXamlMember)->get_IsDependencyProperty(&value));
return value;
}
template <typename D> bool impl_IXamlMember<D>::IsReadOnly() const
{
bool value {};
check_hresult(WINRT_SHIM(IXamlMember)->get_IsReadOnly(&value));
return value;
}
template <typename D> hstring impl_IXamlMember<D>::Name() const
{
hstring value;
check_hresult(WINRT_SHIM(IXamlMember)->get_Name(put_abi(value)));
return value;
}
template <typename D> Windows::UI::Xaml::Markup::IXamlType impl_IXamlMember<D>::TargetType() const
{
Windows::UI::Xaml::Markup::IXamlType value;
check_hresult(WINRT_SHIM(IXamlMember)->get_TargetType(put_abi(value)));
return value;
}
template <typename D> Windows::UI::Xaml::Markup::IXamlType impl_IXamlMember<D>::Type() const
{
Windows::UI::Xaml::Markup::IXamlType value;
check_hresult(WINRT_SHIM(IXamlMember)->get_Type(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::IInspectable impl_IXamlMember<D>::GetValue(const Windows::Foundation::IInspectable & instance) const
{
Windows::Foundation::IInspectable value;
check_hresult(WINRT_SHIM(IXamlMember)->abi_GetValue(get_abi(instance), put_abi(value)));
return value;
}
template <typename D> void impl_IXamlMember<D>::SetValue(const Windows::Foundation::IInspectable & instance, const Windows::Foundation::IInspectable & value) const
{
check_hresult(WINRT_SHIM(IXamlMember)->abi_SetValue(get_abi(instance), get_abi(value)));
}
template <typename D> Windows::UI::Xaml::Markup::IXamlType impl_IXamlType<D>::BaseType() const
{
Windows::UI::Xaml::Markup::IXamlType value;
check_hresult(WINRT_SHIM(IXamlType)->get_BaseType(put_abi(value)));
return value;
}
template <typename D> Windows::UI::Xaml::Markup::IXamlMember impl_IXamlType<D>::ContentProperty() const
{
Windows::UI::Xaml::Markup::IXamlMember value;
check_hresult(WINRT_SHIM(IXamlType)->get_ContentProperty(put_abi(value)));
return value;
}
template <typename D> hstring impl_IXamlType<D>::FullName() const
{
hstring value;
check_hresult(WINRT_SHIM(IXamlType)->get_FullName(put_abi(value)));
return value;
}
template <typename D> bool impl_IXamlType<D>::IsArray() const
{
bool value {};
check_hresult(WINRT_SHIM(IXamlType)->get_IsArray(&value));
return value;
}
template <typename D> bool impl_IXamlType<D>::IsCollection() const
{
bool value {};
check_hresult(WINRT_SHIM(IXamlType)->get_IsCollection(&value));
return value;
}
template <typename D> bool impl_IXamlType<D>::IsConstructible() const
{
bool value {};
check_hresult(WINRT_SHIM(IXamlType)->get_IsConstructible(&value));
return value;
}
template <typename D> bool impl_IXamlType<D>::IsDictionary() const
{
bool value {};
check_hresult(WINRT_SHIM(IXamlType)->get_IsDictionary(&value));
return value;
}
template <typename D> bool impl_IXamlType<D>::IsMarkupExtension() const
{
bool value {};
check_hresult(WINRT_SHIM(IXamlType)->get_IsMarkupExtension(&value));
return value;
}
template <typename D> bool impl_IXamlType<D>::IsBindable() const
{
bool value {};
check_hresult(WINRT_SHIM(IXamlType)->get_IsBindable(&value));
return value;
}
template <typename D> Windows::UI::Xaml::Markup::IXamlType impl_IXamlType<D>::ItemType() const
{
Windows::UI::Xaml::Markup::IXamlType value;
check_hresult(WINRT_SHIM(IXamlType)->get_ItemType(put_abi(value)));
return value;
}
template <typename D> Windows::UI::Xaml::Markup::IXamlType impl_IXamlType<D>::KeyType() const
{
Windows::UI::Xaml::Markup::IXamlType value;
check_hresult(WINRT_SHIM(IXamlType)->get_KeyType(put_abi(value)));
return value;
}
template <typename D> Windows::UI::Xaml::Interop::TypeName impl_IXamlType<D>::UnderlyingType() const
{
Windows::UI::Xaml::Interop::TypeName value {};
check_hresult(WINRT_SHIM(IXamlType)->get_UnderlyingType(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::IInspectable impl_IXamlType<D>::ActivateInstance() const
{
Windows::Foundation::IInspectable instance;
check_hresult(WINRT_SHIM(IXamlType)->abi_ActivateInstance(put_abi(instance)));
return instance;
}
template <typename D> Windows::Foundation::IInspectable impl_IXamlType<D>::CreateFromString(hstring_view value) const
{
Windows::Foundation::IInspectable instance;
check_hresult(WINRT_SHIM(IXamlType)->abi_CreateFromString(get_abi(value), put_abi(instance)));
return instance;
}
template <typename D> Windows::UI::Xaml::Markup::IXamlMember impl_IXamlType<D>::GetMember(hstring_view name) const
{
Windows::UI::Xaml::Markup::IXamlMember xamlMember;
check_hresult(WINRT_SHIM(IXamlType)->abi_GetMember(get_abi(name), put_abi(xamlMember)));
return xamlMember;
}
template <typename D> void impl_IXamlType<D>::AddToVector(const Windows::Foundation::IInspectable & instance, const Windows::Foundation::IInspectable & value) const
{
check_hresult(WINRT_SHIM(IXamlType)->abi_AddToVector(get_abi(instance), get_abi(value)));
}
template <typename D> void impl_IXamlType<D>::AddToMap(const Windows::Foundation::IInspectable & instance, const Windows::Foundation::IInspectable & key, const Windows::Foundation::IInspectable & value) const
{
check_hresult(WINRT_SHIM(IXamlType)->abi_AddToMap(get_abi(instance), get_abi(key), get_abi(value)));
}
template <typename D> void impl_IXamlType<D>::RunInitializer() const
{
check_hresult(WINRT_SHIM(IXamlType)->abi_RunInitializer());
}
template <typename D> Windows::UI::Xaml::Markup::IXamlType impl_IXamlMetadataProvider<D>::GetXamlType(const Windows::UI::Xaml::Interop::TypeName & type) const
{
Windows::UI::Xaml::Markup::IXamlType xamlType;
check_hresult(WINRT_SHIM(IXamlMetadataProvider)->abi_GetXamlType(get_abi(type), put_abi(xamlType)));
return xamlType;
}
template <typename D> Windows::UI::Xaml::Markup::IXamlType impl_IXamlMetadataProvider<D>::GetXamlType(hstring_view fullName) const
{
Windows::UI::Xaml::Markup::IXamlType xamlType;
check_hresult(WINRT_SHIM(IXamlMetadataProvider)->abi_GetXamlTypeByFullName(get_abi(fullName), put_abi(xamlType)));
return xamlType;
}
template <typename D> com_array<Windows::UI::Xaml::Markup::XmlnsDefinition> impl_IXamlMetadataProvider<D>::GetXmlnsDefinitions() const
{
com_array<Windows::UI::Xaml::Markup::XmlnsDefinition> definitions {};
check_hresult(WINRT_SHIM(IXamlMetadataProvider)->abi_GetXmlnsDefinitions(impl::put_size_abi(definitions), put_abi(definitions)));
return definitions;
}
template <typename D> Windows::UI::Xaml::Markup::XamlBinaryWriterErrorInformation impl_IXamlBinaryWriterStatics<D>::Write(const Windows::Foundation::Collections::IVector<Windows::Storage::Streams::IRandomAccessStream> & inputStreams, const Windows::Foundation::Collections::IVector<Windows::Storage::Streams::IRandomAccessStream> & outputStreams, const Windows::UI::Xaml::Markup::IXamlMetadataProvider & xamlMetadataProvider) const
{
Windows::UI::Xaml::Markup::XamlBinaryWriterErrorInformation returnValue {};
check_hresult(WINRT_SHIM(IXamlBinaryWriterStatics)->abi_Write(get_abi(inputStreams), get_abi(outputStreams), get_abi(xamlMetadataProvider), put_abi(returnValue)));
return returnValue;
}
template <typename D> Windows::Foundation::IInspectable impl_IXamlReaderStatics<D>::Load(hstring_view xaml) const
{
Windows::Foundation::IInspectable returnValue;
check_hresult(WINRT_SHIM(IXamlReaderStatics)->abi_Load(get_abi(xaml), put_abi(returnValue)));
return returnValue;
}
template <typename D> Windows::Foundation::IInspectable impl_IXamlReaderStatics<D>::LoadWithInitialTemplateValidation(hstring_view xaml) const
{
Windows::Foundation::IInspectable returnValue;
check_hresult(WINRT_SHIM(IXamlReaderStatics)->abi_LoadWithInitialTemplateValidation(get_abi(xaml), put_abi(returnValue)));
return returnValue;
}
template <typename D> void impl_IDataTemplateComponent<D>::Recycle() const
{
check_hresult(WINRT_SHIM(IDataTemplateComponent)->abi_Recycle());
}
template <typename D> void impl_IDataTemplateComponent<D>::ProcessBindings(const Windows::Foundation::IInspectable & item, int32_t itemIndex, int32_t phase, int32_t & nextPhase) const
{
check_hresult(WINRT_SHIM(IDataTemplateComponent)->abi_ProcessBindings(get_abi(item), itemIndex, phase, &nextPhase));
}
template <typename D> Windows::UI::Xaml::DependencyProperty impl_IXamlBindingHelperStatics<D>::DataTemplateComponentProperty() const
{
Windows::UI::Xaml::DependencyProperty value { nullptr };
check_hresult(WINRT_SHIM(IXamlBindingHelperStatics)->get_DataTemplateComponentProperty(put_abi(value)));
return value;
}
template <typename D> Windows::UI::Xaml::Markup::IDataTemplateComponent impl_IXamlBindingHelperStatics<D>::GetDataTemplateComponent(const Windows::UI::Xaml::DependencyObject & element) const
{
Windows::UI::Xaml::Markup::IDataTemplateComponent value;
check_hresult(WINRT_SHIM(IXamlBindingHelperStatics)->abi_GetDataTemplateComponent(get_abi(element), put_abi(value)));
return value;
}
template <typename D> void impl_IXamlBindingHelperStatics<D>::SetDataTemplateComponent(const Windows::UI::Xaml::DependencyObject & element, const Windows::UI::Xaml::Markup::IDataTemplateComponent & value) const
{
check_hresult(WINRT_SHIM(IXamlBindingHelperStatics)->abi_SetDataTemplateComponent(get_abi(element), get_abi(value)));
}
template <typename D> void impl_IXamlBindingHelperStatics<D>::SuspendRendering(const Windows::UI::Xaml::UIElement & target) const
{
check_hresult(WINRT_SHIM(IXamlBindingHelperStatics)->abi_SuspendRendering(get_abi(target)));
}
template <typename D> void impl_IXamlBindingHelperStatics<D>::ResumeRendering(const Windows::UI::Xaml::UIElement & target) const
{
check_hresult(WINRT_SHIM(IXamlBindingHelperStatics)->abi_ResumeRendering(get_abi(target)));
}
template <typename D> Windows::Foundation::IInspectable impl_IXamlBindingHelperStatics<D>::ConvertValue(const Windows::UI::Xaml::Interop::TypeName & type, const Windows::Foundation::IInspectable & value) const
{
Windows::Foundation::IInspectable returnValue;
check_hresult(WINRT_SHIM(IXamlBindingHelperStatics)->abi_ConvertValue(get_abi(type), get_abi(value), put_abi(returnValue)));
return returnValue;
}
template <typename D> void impl_IXamlBindingHelperStatics<D>::SetPropertyFromString(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, hstring_view value) const
{
check_hresult(WINRT_SHIM(IXamlBindingHelperStatics)->abi_SetPropertyFromString(get_abi(dependencyObject), get_abi(propertyToSet), get_abi(value)));
}
template <typename D> void impl_IXamlBindingHelperStatics<D>::SetPropertyFromBoolean(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, bool value) const
{
check_hresult(WINRT_SHIM(IXamlBindingHelperStatics)->abi_SetPropertyFromBoolean(get_abi(dependencyObject), get_abi(propertyToSet), value));
}
template <typename D> void impl_IXamlBindingHelperStatics<D>::SetPropertyFromChar16(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, wchar_t value) const
{
check_hresult(WINRT_SHIM(IXamlBindingHelperStatics)->abi_SetPropertyFromChar16(get_abi(dependencyObject), get_abi(propertyToSet), value));
}
template <typename D> void impl_IXamlBindingHelperStatics<D>::SetPropertyFromDateTime(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, const Windows::Foundation::DateTime & value) const
{
check_hresult(WINRT_SHIM(IXamlBindingHelperStatics)->abi_SetPropertyFromDateTime(get_abi(dependencyObject), get_abi(propertyToSet), get_abi(value)));
}
template <typename D> void impl_IXamlBindingHelperStatics<D>::SetPropertyFromDouble(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, double value) const
{
check_hresult(WINRT_SHIM(IXamlBindingHelperStatics)->abi_SetPropertyFromDouble(get_abi(dependencyObject), get_abi(propertyToSet), value));
}
template <typename D> void impl_IXamlBindingHelperStatics<D>::SetPropertyFromInt32(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, int32_t value) const
{
check_hresult(WINRT_SHIM(IXamlBindingHelperStatics)->abi_SetPropertyFromInt32(get_abi(dependencyObject), get_abi(propertyToSet), value));
}
template <typename D> void impl_IXamlBindingHelperStatics<D>::SetPropertyFromUInt32(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, uint32_t value) const
{
check_hresult(WINRT_SHIM(IXamlBindingHelperStatics)->abi_SetPropertyFromUInt32(get_abi(dependencyObject), get_abi(propertyToSet), value));
}
template <typename D> void impl_IXamlBindingHelperStatics<D>::SetPropertyFromInt64(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, int64_t value) const
{
check_hresult(WINRT_SHIM(IXamlBindingHelperStatics)->abi_SetPropertyFromInt64(get_abi(dependencyObject), get_abi(propertyToSet), value));
}
template <typename D> void impl_IXamlBindingHelperStatics<D>::SetPropertyFromUInt64(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, uint64_t value) const
{
check_hresult(WINRT_SHIM(IXamlBindingHelperStatics)->abi_SetPropertyFromUInt64(get_abi(dependencyObject), get_abi(propertyToSet), value));
}
template <typename D> void impl_IXamlBindingHelperStatics<D>::SetPropertyFromSingle(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, float value) const
{
check_hresult(WINRT_SHIM(IXamlBindingHelperStatics)->abi_SetPropertyFromSingle(get_abi(dependencyObject), get_abi(propertyToSet), value));
}
template <typename D> void impl_IXamlBindingHelperStatics<D>::SetPropertyFromPoint(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, const Windows::Foundation::Point & value) const
{
check_hresult(WINRT_SHIM(IXamlBindingHelperStatics)->abi_SetPropertyFromPoint(get_abi(dependencyObject), get_abi(propertyToSet), get_abi(value)));
}
template <typename D> void impl_IXamlBindingHelperStatics<D>::SetPropertyFromRect(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, const Windows::Foundation::Rect & value) const
{
check_hresult(WINRT_SHIM(IXamlBindingHelperStatics)->abi_SetPropertyFromRect(get_abi(dependencyObject), get_abi(propertyToSet), get_abi(value)));
}
template <typename D> void impl_IXamlBindingHelperStatics<D>::SetPropertyFromSize(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, const Windows::Foundation::Size & value) const
{
check_hresult(WINRT_SHIM(IXamlBindingHelperStatics)->abi_SetPropertyFromSize(get_abi(dependencyObject), get_abi(propertyToSet), get_abi(value)));
}
template <typename D> void impl_IXamlBindingHelperStatics<D>::SetPropertyFromTimeSpan(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, const Windows::Foundation::TimeSpan & value) const
{
check_hresult(WINRT_SHIM(IXamlBindingHelperStatics)->abi_SetPropertyFromTimeSpan(get_abi(dependencyObject), get_abi(propertyToSet), get_abi(value)));
}
template <typename D> void impl_IXamlBindingHelperStatics<D>::SetPropertyFromByte(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, uint8_t value) const
{
check_hresult(WINRT_SHIM(IXamlBindingHelperStatics)->abi_SetPropertyFromByte(get_abi(dependencyObject), get_abi(propertyToSet), value));
}
template <typename D> void impl_IXamlBindingHelperStatics<D>::SetPropertyFromUri(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, const Windows::Foundation::Uri & value) const
{
check_hresult(WINRT_SHIM(IXamlBindingHelperStatics)->abi_SetPropertyFromUri(get_abi(dependencyObject), get_abi(propertyToSet), get_abi(value)));
}
template <typename D> void impl_IXamlBindingHelperStatics<D>::SetPropertyFromObject(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, const Windows::Foundation::IInspectable & value) const
{
check_hresult(WINRT_SHIM(IXamlBindingHelperStatics)->abi_SetPropertyFromObject(get_abi(dependencyObject), get_abi(propertyToSet), get_abi(value)));
}
template <typename D> void impl_IXamlMarkupHelperStatics<D>::UnloadObject(const Windows::UI::Xaml::DependencyObject & element) const
{
check_hresult(WINRT_SHIM(IXamlMarkupHelperStatics)->abi_UnloadObject(get_abi(element)));
}
inline Windows::UI::Xaml::Markup::XamlBinaryWriterErrorInformation XamlBinaryWriter::Write(const Windows::Foundation::Collections::IVector<Windows::Storage::Streams::IRandomAccessStream> & inputStreams, const Windows::Foundation::Collections::IVector<Windows::Storage::Streams::IRandomAccessStream> & outputStreams, const Windows::UI::Xaml::Markup::IXamlMetadataProvider & xamlMetadataProvider)
{
return get_activation_factory<XamlBinaryWriter, IXamlBinaryWriterStatics>().Write(inputStreams, outputStreams, xamlMetadataProvider);
}
inline Windows::UI::Xaml::DependencyProperty XamlBindingHelper::DataTemplateComponentProperty()
{
return get_activation_factory<XamlBindingHelper, IXamlBindingHelperStatics>().DataTemplateComponentProperty();
}
inline Windows::UI::Xaml::Markup::IDataTemplateComponent XamlBindingHelper::GetDataTemplateComponent(const Windows::UI::Xaml::DependencyObject & element)
{
return get_activation_factory<XamlBindingHelper, IXamlBindingHelperStatics>().GetDataTemplateComponent(element);
}
inline void XamlBindingHelper::SetDataTemplateComponent(const Windows::UI::Xaml::DependencyObject & element, const Windows::UI::Xaml::Markup::IDataTemplateComponent & value)
{
get_activation_factory<XamlBindingHelper, IXamlBindingHelperStatics>().SetDataTemplateComponent(element, value);
}
inline void XamlBindingHelper::SuspendRendering(const Windows::UI::Xaml::UIElement & target)
{
get_activation_factory<XamlBindingHelper, IXamlBindingHelperStatics>().SuspendRendering(target);
}
inline void XamlBindingHelper::ResumeRendering(const Windows::UI::Xaml::UIElement & target)
{
get_activation_factory<XamlBindingHelper, IXamlBindingHelperStatics>().ResumeRendering(target);
}
inline Windows::Foundation::IInspectable XamlBindingHelper::ConvertValue(const Windows::UI::Xaml::Interop::TypeName & type, const Windows::Foundation::IInspectable & value)
{
return get_activation_factory<XamlBindingHelper, IXamlBindingHelperStatics>().ConvertValue(type, value);
}
inline void XamlBindingHelper::SetPropertyFromString(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, hstring_view value)
{
get_activation_factory<XamlBindingHelper, IXamlBindingHelperStatics>().SetPropertyFromString(dependencyObject, propertyToSet, value);
}
inline void XamlBindingHelper::SetPropertyFromBoolean(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, bool value)
{
get_activation_factory<XamlBindingHelper, IXamlBindingHelperStatics>().SetPropertyFromBoolean(dependencyObject, propertyToSet, value);
}
inline void XamlBindingHelper::SetPropertyFromChar16(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, wchar_t value)
{
get_activation_factory<XamlBindingHelper, IXamlBindingHelperStatics>().SetPropertyFromChar16(dependencyObject, propertyToSet, value);
}
inline void XamlBindingHelper::SetPropertyFromDateTime(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, const Windows::Foundation::DateTime & value)
{
get_activation_factory<XamlBindingHelper, IXamlBindingHelperStatics>().SetPropertyFromDateTime(dependencyObject, propertyToSet, value);
}
inline void XamlBindingHelper::SetPropertyFromDouble(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, double value)
{
get_activation_factory<XamlBindingHelper, IXamlBindingHelperStatics>().SetPropertyFromDouble(dependencyObject, propertyToSet, value);
}
inline void XamlBindingHelper::SetPropertyFromInt32(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, int32_t value)
{
get_activation_factory<XamlBindingHelper, IXamlBindingHelperStatics>().SetPropertyFromInt32(dependencyObject, propertyToSet, value);
}
inline void XamlBindingHelper::SetPropertyFromUInt32(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, uint32_t value)
{
get_activation_factory<XamlBindingHelper, IXamlBindingHelperStatics>().SetPropertyFromUInt32(dependencyObject, propertyToSet, value);
}
inline void XamlBindingHelper::SetPropertyFromInt64(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, int64_t value)
{
get_activation_factory<XamlBindingHelper, IXamlBindingHelperStatics>().SetPropertyFromInt64(dependencyObject, propertyToSet, value);
}
inline void XamlBindingHelper::SetPropertyFromUInt64(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, uint64_t value)
{
get_activation_factory<XamlBindingHelper, IXamlBindingHelperStatics>().SetPropertyFromUInt64(dependencyObject, propertyToSet, value);
}
inline void XamlBindingHelper::SetPropertyFromSingle(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, float value)
{
get_activation_factory<XamlBindingHelper, IXamlBindingHelperStatics>().SetPropertyFromSingle(dependencyObject, propertyToSet, value);
}
inline void XamlBindingHelper::SetPropertyFromPoint(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, const Windows::Foundation::Point & value)
{
get_activation_factory<XamlBindingHelper, IXamlBindingHelperStatics>().SetPropertyFromPoint(dependencyObject, propertyToSet, value);
}
inline void XamlBindingHelper::SetPropertyFromRect(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, const Windows::Foundation::Rect & value)
{
get_activation_factory<XamlBindingHelper, IXamlBindingHelperStatics>().SetPropertyFromRect(dependencyObject, propertyToSet, value);
}
inline void XamlBindingHelper::SetPropertyFromSize(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, const Windows::Foundation::Size & value)
{
get_activation_factory<XamlBindingHelper, IXamlBindingHelperStatics>().SetPropertyFromSize(dependencyObject, propertyToSet, value);
}
inline void XamlBindingHelper::SetPropertyFromTimeSpan(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, const Windows::Foundation::TimeSpan & value)
{
get_activation_factory<XamlBindingHelper, IXamlBindingHelperStatics>().SetPropertyFromTimeSpan(dependencyObject, propertyToSet, value);
}
inline void XamlBindingHelper::SetPropertyFromByte(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, uint8_t value)
{
get_activation_factory<XamlBindingHelper, IXamlBindingHelperStatics>().SetPropertyFromByte(dependencyObject, propertyToSet, value);
}
inline void XamlBindingHelper::SetPropertyFromUri(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, const Windows::Foundation::Uri & value)
{
get_activation_factory<XamlBindingHelper, IXamlBindingHelperStatics>().SetPropertyFromUri(dependencyObject, propertyToSet, value);
}
inline void XamlBindingHelper::SetPropertyFromObject(const Windows::Foundation::IInspectable & dependencyObject, const Windows::UI::Xaml::DependencyProperty & propertyToSet, const Windows::Foundation::IInspectable & value)
{
get_activation_factory<XamlBindingHelper, IXamlBindingHelperStatics>().SetPropertyFromObject(dependencyObject, propertyToSet, value);
}
inline void XamlMarkupHelper::UnloadObject(const Windows::UI::Xaml::DependencyObject & element)
{
get_activation_factory<XamlMarkupHelper, IXamlMarkupHelperStatics>().UnloadObject(element);
}
inline Windows::Foundation::IInspectable XamlReader::Load(hstring_view xaml)
{
return get_activation_factory<XamlReader, IXamlReaderStatics>().Load(xaml);
}
inline Windows::Foundation::IInspectable XamlReader::LoadWithInitialTemplateValidation(hstring_view xaml)
{
return get_activation_factory<XamlReader, IXamlReaderStatics>().LoadWithInitialTemplateValidation(xaml);
}
}
}
template<>
struct std::hash<winrt::Windows::UI::Xaml::Markup::IComponentConnector>
{
size_t operator()(const winrt::Windows::UI::Xaml::Markup::IComponentConnector & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Markup::IComponentConnector2>
{
size_t operator()(const winrt::Windows::UI::Xaml::Markup::IComponentConnector2 & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Markup::IDataTemplateComponent>
{
size_t operator()(const winrt::Windows::UI::Xaml::Markup::IDataTemplateComponent & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Markup::IXamlBinaryWriter>
{
size_t operator()(const winrt::Windows::UI::Xaml::Markup::IXamlBinaryWriter & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Markup::IXamlBinaryWriterStatics>
{
size_t operator()(const winrt::Windows::UI::Xaml::Markup::IXamlBinaryWriterStatics & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Markup::IXamlBindingHelper>
{
size_t operator()(const winrt::Windows::UI::Xaml::Markup::IXamlBindingHelper & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Markup::IXamlBindingHelperStatics>
{
size_t operator()(const winrt::Windows::UI::Xaml::Markup::IXamlBindingHelperStatics & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Markup::IXamlMarkupHelper>
{
size_t operator()(const winrt::Windows::UI::Xaml::Markup::IXamlMarkupHelper & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Markup::IXamlMarkupHelperStatics>
{
size_t operator()(const winrt::Windows::UI::Xaml::Markup::IXamlMarkupHelperStatics & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Markup::IXamlMember>
{
size_t operator()(const winrt::Windows::UI::Xaml::Markup::IXamlMember & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Markup::IXamlMetadataProvider>
{
size_t operator()(const winrt::Windows::UI::Xaml::Markup::IXamlMetadataProvider & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Markup::IXamlReader>
{
size_t operator()(const winrt::Windows::UI::Xaml::Markup::IXamlReader & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Markup::IXamlReaderStatics>
{
size_t operator()(const winrt::Windows::UI::Xaml::Markup::IXamlReaderStatics & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Markup::IXamlType>
{
size_t operator()(const winrt::Windows::UI::Xaml::Markup::IXamlType & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Markup::XamlBinaryWriter>
{
size_t operator()(const winrt::Windows::UI::Xaml::Markup::XamlBinaryWriter & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Markup::XamlBindingHelper>
{
size_t operator()(const winrt::Windows::UI::Xaml::Markup::XamlBindingHelper & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Markup::XamlMarkupHelper>
{
size_t operator()(const winrt::Windows::UI::Xaml::Markup::XamlMarkupHelper & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::UI::Xaml::Markup::XamlReader>
{
size_t operator()(const winrt::Windows::UI::Xaml::Markup::XamlReader & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
WINRT_WARNING_POP
|
#include "SoXipNeheBoxGenerator.h"
#include "SoXipNeheBox.h"
// array for box colors
const float boxCol[5][3]=
{
// Bright: Red, Orange, Yellow, Green, Blue
{1.0f,0.0f,0.0f},{1.0f,0.5f,0.0f},{1.0f,1.0f,0.0f},{0.0f,1.0f,0.0f},{0.0f,1.0f,1.0f}
};
// array for top colors
const float topCol[5][3]=
{
// Dark: Red, Orange, Yellow, Green, Blue
{.5f,0.0f,0.0f},{0.5f,0.25f,0.0f},{0.5f,0.5f,0.0f},{0.0f,0.5f,0.0f},{0.0f,0.5f,0.5f}
};
SO_NODE_SOURCE(SoXipNeheBoxGenerator)
void
SoXipNeheBoxGenerator::initClass()
{
SO_NODE_INIT_CLASS(SoXipNeheBoxGenerator, SoXipKit, "Node")
}
SoXipNeheBoxGenerator::SoXipNeheBoxGenerator()
{
SO_NODE_CONSTRUCTOR(SoXipNeheBoxGenerator);
SbRotation pitch(SbVec3f(1, 0, 0), 0); // rotation around X
SbMatrix pitchM;
SbRotation yaw(SbVec3f(0, 1, 0), 0); // rotation around Y
SbMatrix yawM;
SbMatrix transM = SbMatrix::identity(); // translation
SbMatrix compM = SbMatrix::identity();
float xrot = 0;
float yrot = 0;
for (int yloop = 1; yloop < 6 /* number of rows */ ; yloop++)
{
for (int xloop = 0; xloop < yloop; xloop++)
{
// another magic formula from Nehe for the translation...
transM.setTranslate(SbVec3f(1.4f+(float(xloop)*2.8f)-(float(yloop)*1.4f),((6.0f-float(yloop))*2.4f)-7.0f,-20.0f));
pitch.setValue(SbVec3f(1, 0, 0), (M_PI/180) * (45.0f-(2.0f*yloop)+ xrot));
pitch.getValue(pitchM);
yaw.setValue(SbVec3f(0,1,0), (M_PI/180) * (45.0f + yrot));
yaw.getValue(yawM);
compM = yawM * pitchM * transM;
SoXipNeheBox* neheBox = new SoXipNeheBox();
neheBox->transform.setValue(compM);
neheBox->topColor.setValue(topCol[yloop - 1]);
neheBox->boxColor.setValue(boxCol[yloop - 1]);
this->addChild(neheBox);
}
}
}
|
#include <SPI.h>
#include "RF24.h"
//RF
RF24 radio(10, 9);
byte direccion[][6] = {"0", "1"};
typedef struct {
byte id;
byte typeOfData;
float data;
int8_t foo;
}
inputData;
inputData datos;
void setup() {
Serial.begin(9600);
Serial.println("Iniciado");
setUpRF();
datos.id=2;
datos.typeOfData=5;
datos.data=1.0;
datos.foo=1;
Serial.print("Tamaño");
Serial.println(sizeof(datos));
}
void loop() {
Serial.print("Enviando: ");
bool ok = radio.write( &datos, sizeof(datos) );
Serial.println(datos.data);
datos.data++;
datos.foo++;
delay(2000);
}
|
// @copyright 2017 - 2018 Shaun Ostoic
// Distributed under the MIT License.
// (See accompanying file LICENSE.md or copy at https://opensource.org/licenses/MIT)
#pragma once
#include <distant/agents/process.hpp>
#include <distant/memory/virtual_ptr.hpp>
#include <distant/memory/calling_conventions.hpp>
#include <distant/memory/type_traits.hpp>
// Other declarations: ./fwd.hpp
namespace distant::memory
{
// Todo: Figure out order for template parameters so that default template parameters makes sense.
template <class Signature, class CallingConv = cdeclcall, class AddressT = dword, process_rights AccessRights = process_rights::all_access>
class function;
template <class R, class... Args, class CallingConv, class AddressT, process_rights AccessRights>
class function<R(Args...), CallingConv, AddressT, AccessRights>
{
public:
static constexpr auto required_process_rights = process_rights::all_access;
public:
function() noexcept = default;
function(nullptr_t)
: fn_ptr_{nullptr}
{}
// Function in this process should just act like std::function.
template <class Fn, class = std::enable_if_t<std::is_function<Fn>::value>>
function(Fn&& fn)
: fn_ptr_{
current_process(),
std::addressof(std::forward<Fn>(fn)
)}
{}
function(virtual_ptr<R(*)(Args...), AddressT, AccessRights> fn_ptr)
: fn_ptr_{fn_ptr}
{}
const agents::process<AccessRights>& process() const noexcept { return fn_ptr_.process(); }
agents::process<AccessRights>& process() noexcept { return fn_ptr_.process(); }
//void set_process(agents::process<AccessRights>& process) noexcept;
private:
virtual_ptr<R(*)(Args...), AddressT, AccessRights> fn_ptr_;
};
} // namespace distant::memory
namespace distant
{
using memory::function;
template <class R, class... Args, class CallingConv, class AddressT, process_rights AccessRights>
struct function_traits<function<R(Args...), CallingConv, AddressT, AccessRights>>
{
using return_type = R;
static constexpr std::size_t arity = sizeof...(Args);
template <std::size_t N>
struct argument
{
static_assert(N < arity, "Argument index out of range");
using type = std::tuple_element_t<N, std::tuple<Args...>>;
};
template <unsigned int N>
using argument_t = typename argument<N>::type;
};
} // namespace distant
#include "impl/function.hxx"
|
#include "stdafx.h"
#include "LongNumber.h"
namespace
{
const int RADIX = 10;
}
CLongNumber::CLongNumber(const long& number)
{
LongNumber tmp;
long shortNumber = number;
while (shortNumber > 0)
{
tmp.push_back(shortNumber % RADIX);
shortNumber /= RADIX;
}
m_longNumber = tmp;
}
CLongNumber::CLongNumber(const std::string & number)
{
LongNumber tmp;
for (const auto& digit : number)
{
tmp.push_back(digit - '0');
}
std::reverse(tmp.begin(), tmp.end());
m_longNumber = tmp;
}
CLongNumber::CLongNumber(const LongNumber & number)
: m_longNumber(number)
{
}
CLongNumber::CLongNumber(const CLongNumber & number)
: m_longNumber(number.GetLongNumber())
{
}
LongNumber CLongNumber::GetLongNumber() const
{
return m_longNumber;
}
size_t CLongNumber::GetSize() const
{
return m_longNumber.size();
}
CLongNumber const operator-(const CLongNumber & left, const CLongNumber & right)
{
LongNumber result = left.GetLongNumber();
LongNumber second = right.GetLongNumber();
for (size_t i = 0; i < second.size(); ++i)
{
result[i] -= second[i];
}
for (size_t i = 0; i < result.size(); ++i)
{
if (result[i] < 0)
{
result[i] += RADIX;
--result[i + 1];
}
}
return CLongNumber(result);
}
std::ostream & operator<<(std::ostream & output, const CLongNumber & number)
{
LongNumber longNumber = number.GetLongNumber();
std::reverse(longNumber.begin(), longNumber.end());
while (!longNumber.empty())
{
if (0 == *longNumber.begin())
{
longNumber.erase(longNumber.begin());
}
else
{
break;
}
}
for (auto digit : longNumber)
{
output << digit;
}
return output;
}
|
#include <bits/stdc++.h>
using namespace std;
#define MAXSIZE 10000000
long long int segtree[10000000];
long A[MAXSIZE];
void build(int t,int i,int j){
if(i==j){
segtree[t] = A[i];
return;
}
int left = t<<1,right=left|1,mid=(i+j)>>1;
build(left,i,mid);
build(right,mid+1,j);
segtree[t] = segtree[left] + segtree[right];
}
void update(int t,int i,int j,int k,int x){
if(i==j){
if(i==k)
segtree[t] = segtree[t] - x;
return;
}
int left = t<<1,right=left|1,mid=(i+j)>>1;
if(k<=mid)
update(left,i,mid,k,x);
else
update(right,mid+1,j,k,x);
segtree[t]= segtree[left] + segtree[right];
}
int query(int t,int i,int j,int ri,int rj){
if(j<ri || i>rj)
return 0;
if(ri<=i && rj>=j)
return segtree[t];
int left = t<<1,right=left|1,mid=(i+j)>>1;
return query(left,i,mid,ri,rj) + query(right,mid+1,j,ri,rj);
}
int main() {
int N,Q,L,R,l,t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&N,&Q);
for(int i=1;i<=N;i++)
scanf("%ld",&A[i]);
build(1,1,N);
while(Q--){
scanf("%d",&L);
if(L == 0)
{
scanf("%d%d",&l,&R);
printf("%d\n",query(1,1,N,l,R));
}
else
{
scanf("%d%d",&l,&R);
update(1,1,N,l,R);
}
}
}
return 0;
}
|
#include "../../includes/graphic/sender.hpp"
#ifdef _WIN32
int graphic::Sender::instance_number = 0;
#endif
graphic::Sender::Sender(int port) : connection{nullptr}, messageHistory{}
{
if (port <= 0)
{
throw std::invalid_argument("The port specified is "
+ std::to_string(port)
+ " which is <= 0!");
}
#ifdef _WIN32
if (instance_number == 0)
{
ix::initNetSystem();
}
instance_number++;
#endif
startServer(port);
}
graphic::Sender::~Sender()
{
stopServer();
#ifdef _WIN32
instance_number--;
if (instance_number == 0)
{
ix::uninitNetSystem();
}
#endif
}
void graphic::Sender::stopServer()
{
if (connection != nullptr)
{
closeConnection();
}
server->stop();
}
void graphic::Sender::closeConnection()
{
connection->close();
connection = nullptr;
}
void graphic::Sender::setCallback()
{
SharedQueue<std::string>* messageHistoryRef = &(this->messageHistory);
// Set the actions to perform when the server receive a message
server->setOnClientMessageCallback([this, messageHistoryRef](std::shared_ptr<ix::ConnectionState> connectionState,
ix::WebSocket &webSocket, const ix::WebSocketMessagePtr &msg)
{
// If the message is about opening a new connection..
if (msg->type == ix::WebSocketMessageType::Open)
{
if (!this->isConnected())
{
connection = &webSocket;
}
int messagesToSend = messageHistoryRef->size();
if (messagesToSend > 0)
{
for (int i = 0; i < messagesToSend; i++)
{
webSocket.send(messageHistoryRef->front());
messageHistoryRef->pop();
}
}
}
// If the message is about closing the connection..
else if (msg->type == ix::WebSocketMessageType::Close)
{
connection = nullptr;
}
});
}
void graphic::Sender::initializeServer(int port)
{
server = std::make_unique<ix::WebSocketServer>(port, ix::SocketServer::kDefaultHost,
ix::SocketServer::kDefaultTcpBacklog, 1);
setCallback();
}
void graphic::Sender::startServer(int port)
{
initializeServer(port);
// Start the server in background
server->listenAndStart();
}
void graphic::Sender::send(std::string data)
{
if (connection != nullptr && messageHistory.empty())
{
connection->send(data);
}
else
{
messageHistory.push(data);
}
}
bool graphic::Sender::isConnected()
{
return connection != nullptr;
}
|
//**************************************************************************
//**
//** See jlquake.txt for copyright info.
//**
//** 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; either version 3
//** of the License, or (at your option) any later version.
//**
//** 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
//** included (gnu.txt) GNU General Public License for more details.
//**
//**************************************************************************
#include "local.h"
#include "../../common/Common.h"
#include "../../common/message_utils.h"
#include "../../common/endian.h"
static byte svq2_fatpvs[ 65536 / 8 ]; // 32767 is MAX_MAP_LEAFS
// Writes a delta update of an q2entity_state_t list to the message.
static void SVQ2_EmitPacketEntities( const q2client_frame_t* from, const q2client_frame_t* to, QMsg* msg ) {
msg->WriteByte( q2svc_packetentities );
int from_num_entities;
if ( !from ) {
from_num_entities = 0;
} else {
from_num_entities = from->num_entities;
}
int newindex = 0;
int oldindex = 0;
while ( newindex < to->num_entities || oldindex < from_num_entities ) {
q2entity_state_t* newent;
int newnum;
if ( newindex >= to->num_entities ) {
newnum = 9999;
} else {
newent = &svs.q2_client_entities[ ( to->first_entity + newindex ) % svs.q2_num_client_entities ];
newnum = newent->number;
}
q2entity_state_t* oldent;
int oldnum;
if ( oldindex >= from_num_entities ) {
oldnum = 9999;
} else {
oldent = &svs.q2_client_entities[ ( from->first_entity + oldindex ) % svs.q2_num_client_entities ];
oldnum = oldent->number;
}
if ( newnum == oldnum ) { // delta update from old position
// because the force parm is false, this will not result
// in any bytes being emited if the entity has not changed at all
// note that players are always 'newentities', this updates their oldorigin always
// and prevents warping
MSGQ2_WriteDeltaEntity( oldent, newent, msg, false, newent->number <= sv_maxclients->value );
oldindex++;
newindex++;
continue;
}
if ( newnum < oldnum ) {
// this is a new entity, send it from the baseline
MSGQ2_WriteDeltaEntity( &sv.q2_baselines[ newnum ], newent, msg, true, true );
newindex++;
continue;
}
if ( newnum > oldnum ) {
// the old entity isn't present in the new message
int bits = Q2U_REMOVE;
if ( oldnum >= 256 ) {
bits |= Q2U_NUMBER16 | Q2U_MOREBITS1;
}
msg->WriteByte( bits & 255 );
if ( bits & 0x0000ff00 ) {
msg->WriteByte( ( bits >> 8 ) & 255 );
}
if ( bits & Q2U_NUMBER16 ) {
msg->WriteShort( oldnum );
} else {
msg->WriteByte( oldnum );
}
oldindex++;
continue;
}
}
msg->WriteShort( 0 ); // end of packetentities
}
static void SVQ2_WritePlayerstateToClient( const q2client_frame_t* from, const q2client_frame_t* to, QMsg* msg ) {
const q2player_state_t* ps = &to->ps;
const q2player_state_t* ops;
q2player_state_t dummy;
if ( !from ) {
Com_Memset( &dummy, 0, sizeof ( dummy ) );
ops = &dummy;
} else {
ops = &from->ps;
}
//
// determine what needs to be sent
//
int pflags = 0;
if ( ps->pmove.pm_type != ops->pmove.pm_type ) {
pflags |= Q2PS_M_TYPE;
}
if ( ps->pmove.origin[ 0 ] != ops->pmove.origin[ 0 ] ||
ps->pmove.origin[ 1 ] != ops->pmove.origin[ 1 ] ||
ps->pmove.origin[ 2 ] != ops->pmove.origin[ 2 ] ) {
pflags |= Q2PS_M_ORIGIN;
}
if ( ps->pmove.velocity[ 0 ] != ops->pmove.velocity[ 0 ] ||
ps->pmove.velocity[ 1 ] != ops->pmove.velocity[ 1 ] ||
ps->pmove.velocity[ 2 ] != ops->pmove.velocity[ 2 ] ) {
pflags |= Q2PS_M_VELOCITY;
}
if ( ps->pmove.pm_time != ops->pmove.pm_time ) {
pflags |= Q2PS_M_TIME;
}
if ( ps->pmove.pm_flags != ops->pmove.pm_flags ) {
pflags |= Q2PS_M_FLAGS;
}
if ( ps->pmove.gravity != ops->pmove.gravity ) {
pflags |= Q2PS_M_GRAVITY;
}
if ( ps->pmove.delta_angles[ 0 ] != ops->pmove.delta_angles[ 0 ] ||
ps->pmove.delta_angles[ 1 ] != ops->pmove.delta_angles[ 1 ] ||
ps->pmove.delta_angles[ 2 ] != ops->pmove.delta_angles[ 2 ] ) {
pflags |= Q2PS_M_DELTA_ANGLES;
}
if ( ps->viewoffset[ 0 ] != ops->viewoffset[ 0 ] ||
ps->viewoffset[ 1 ] != ops->viewoffset[ 1 ] ||
ps->viewoffset[ 2 ] != ops->viewoffset[ 2 ] ) {
pflags |= Q2PS_VIEWOFFSET;
}
if ( ps->viewangles[ 0 ] != ops->viewangles[ 0 ] ||
ps->viewangles[ 1 ] != ops->viewangles[ 1 ] ||
ps->viewangles[ 2 ] != ops->viewangles[ 2 ] ) {
pflags |= Q2PS_VIEWANGLES;
}
if ( ps->kick_angles[ 0 ] != ops->kick_angles[ 0 ] ||
ps->kick_angles[ 1 ] != ops->kick_angles[ 1 ] ||
ps->kick_angles[ 2 ] != ops->kick_angles[ 2 ] ) {
pflags |= Q2PS_KICKANGLES;
}
if ( ps->blend[ 0 ] != ops->blend[ 0 ] ||
ps->blend[ 1 ] != ops->blend[ 1 ] ||
ps->blend[ 2 ] != ops->blend[ 2 ] ||
ps->blend[ 3 ] != ops->blend[ 3 ] ) {
pflags |= Q2PS_BLEND;
}
if ( ps->fov != ops->fov ) {
pflags |= Q2PS_FOV;
}
if ( ps->rdflags != ops->rdflags ) {
pflags |= Q2PS_RDFLAGS;
}
if ( ps->gunframe != ops->gunframe ) {
pflags |= Q2PS_WEAPONFRAME;
}
pflags |= Q2PS_WEAPONINDEX;
//
// write it
//
msg->WriteByte( q2svc_playerinfo );
msg->WriteShort( pflags );
//
// write the q2pmove_state_t
//
if ( pflags & Q2PS_M_TYPE ) {
msg->WriteByte( ps->pmove.pm_type );
}
if ( pflags & Q2PS_M_ORIGIN ) {
msg->WriteShort( ps->pmove.origin[ 0 ] );
msg->WriteShort( ps->pmove.origin[ 1 ] );
msg->WriteShort( ps->pmove.origin[ 2 ] );
}
if ( pflags & Q2PS_M_VELOCITY ) {
msg->WriteShort( ps->pmove.velocity[ 0 ] );
msg->WriteShort( ps->pmove.velocity[ 1 ] );
msg->WriteShort( ps->pmove.velocity[ 2 ] );
}
if ( pflags & Q2PS_M_TIME ) {
msg->WriteByte( ps->pmove.pm_time );
}
if ( pflags & Q2PS_M_FLAGS ) {
msg->WriteByte( ps->pmove.pm_flags );
}
if ( pflags & Q2PS_M_GRAVITY ) {
msg->WriteShort( ps->pmove.gravity );
}
if ( pflags & Q2PS_M_DELTA_ANGLES ) {
msg->WriteShort( ps->pmove.delta_angles[ 0 ] );
msg->WriteShort( ps->pmove.delta_angles[ 1 ] );
msg->WriteShort( ps->pmove.delta_angles[ 2 ] );
}
//
// write the rest of the q2player_state_t
//
if ( pflags & Q2PS_VIEWOFFSET ) {
msg->WriteChar( ps->viewoffset[ 0 ] * 4 );
msg->WriteChar( ps->viewoffset[ 1 ] * 4 );
msg->WriteChar( ps->viewoffset[ 2 ] * 4 );
}
if ( pflags & Q2PS_VIEWANGLES ) {
msg->WriteAngle16( ps->viewangles[ 0 ] );
msg->WriteAngle16( ps->viewangles[ 1 ] );
msg->WriteAngle16( ps->viewangles[ 2 ] );
}
if ( pflags & Q2PS_KICKANGLES ) {
msg->WriteChar( ps->kick_angles[ 0 ] * 4 );
msg->WriteChar( ps->kick_angles[ 1 ] * 4 );
msg->WriteChar( ps->kick_angles[ 2 ] * 4 );
}
if ( pflags & Q2PS_WEAPONINDEX ) {
msg->WriteByte( ps->gunindex );
}
if ( pflags & Q2PS_WEAPONFRAME ) {
msg->WriteByte( ps->gunframe );
msg->WriteChar( ps->gunoffset[ 0 ] * 4 );
msg->WriteChar( ps->gunoffset[ 1 ] * 4 );
msg->WriteChar( ps->gunoffset[ 2 ] * 4 );
msg->WriteChar( ps->gunangles[ 0 ] * 4 );
msg->WriteChar( ps->gunangles[ 1 ] * 4 );
msg->WriteChar( ps->gunangles[ 2 ] * 4 );
}
if ( pflags & Q2PS_BLEND ) {
msg->WriteByte( ps->blend[ 0 ] * 255 );
msg->WriteByte( ps->blend[ 1 ] * 255 );
msg->WriteByte( ps->blend[ 2 ] * 255 );
msg->WriteByte( ps->blend[ 3 ] * 255 );
}
if ( pflags & Q2PS_FOV ) {
msg->WriteByte( ps->fov );
}
if ( pflags & Q2PS_RDFLAGS ) {
msg->WriteByte( ps->rdflags );
}
// send stats
int statbits = 0;
for ( int i = 0; i < MAX_STATS_Q2; i++ ) {
if ( ps->stats[ i ] != ops->stats[ i ] ) {
statbits |= 1 << i;
}
}
msg->WriteLong( statbits );
for ( int i = 0; i < MAX_STATS_Q2; i++ ) {
if ( statbits & ( 1 << i ) ) {
msg->WriteShort( ps->stats[ i ] );
}
}
}
void SVQ2_WriteFrameToClient( client_t* client, QMsg* msg ) {
// this is the frame we are creating
const q2client_frame_t* frame = &client->q2_frames[ sv.q2_framenum & UPDATE_MASK_Q2 ];
const q2client_frame_t* oldframe;
int lastframe;
if ( client->q2_lastframe <= 0 ) {
// client is asking for a retransmit
oldframe = NULL;
lastframe = -1;
} else if ( sv.q2_framenum - client->q2_lastframe >= ( UPDATE_BACKUP_Q2 - 3 ) ) {
// client hasn't gotten a good message through in a long time
oldframe = NULL;
lastframe = -1;
} else {
// we have a valid message to delta from
oldframe = &client->q2_frames[ client->q2_lastframe & UPDATE_MASK_Q2 ];
lastframe = client->q2_lastframe;
}
msg->WriteByte( q2svc_frame );
msg->WriteLong( sv.q2_framenum );
msg->WriteLong( lastframe ); // what we are delta'ing from
msg->WriteByte( client->q2_surpressCount ); // rate dropped packets
client->q2_surpressCount = 0;
// send over the areabits
msg->WriteByte( frame->areabytes );
msg->WriteData( frame->areabits, frame->areabytes );
// delta encode the playerstate
SVQ2_WritePlayerstateToClient( oldframe, frame, msg );
// delta encode the entities
SVQ2_EmitPacketEntities( oldframe, frame, msg );
}
// The client will interpolate the view position,
// so we can't use a single PVS point
static void SVQ2_FatPVS( const vec3_t org ) {
vec3_t mins, maxs;
for ( int i = 0; i < 3; i++ ) {
mins[ i ] = org[ i ] - 8;
maxs[ i ] = org[ i ] + 8;
}
int leafs[ 64 ];
int count = CM_BoxLeafnums( mins, maxs, leafs, 64 );
if ( count < 1 ) {
common->FatalError( "SV_FatPVS: count < 1" );
}
int longs = ( CM_NumClusters() + 31 ) >> 5;
// convert leafs to clusters
for ( int i = 0; i < count; i++ ) {
leafs[ i ] = CM_LeafCluster( leafs[ i ] );
}
Com_Memcpy( svq2_fatpvs, CM_ClusterPVS( leafs[ 0 ] ), longs << 2 );
// or in all the other leaf bits
for ( int i = 1; i < count; i++ ) {
int j;
for ( j = 0; j < i; j++ ) {
if ( leafs[ i ] == leafs[ j ] ) {
break;
}
}
if ( j != i ) {
continue; // already have the cluster we want
}
byte* src = CM_ClusterPVS( leafs[ i ] );
for ( j = 0; j < longs; j++ ) {
( ( long* )svq2_fatpvs )[ j ] |= ( ( long* )src )[ j ];
}
}
}
// Decides which entities are going to be visible to the client, and
// copies off the playerstat and areabits.
void SVQ2_BuildClientFrame( client_t* client ) {
q2edict_t* clent = client->q2_edict;
if ( !clent->client ) {
return; // not in game yet
}
// this is the frame we are creating
q2client_frame_t* frame = &client->q2_frames[ sv.q2_framenum & UPDATE_MASK_Q2 ];
frame->senttime = svs.realtime; // save it for ping calc later
// find the client's PVS
vec3_t org;
for ( int i = 0; i < 3; i++ ) {
org[ i ] = clent->client->ps.pmove.origin[ i ] * 0.125 + clent->client->ps.viewoffset[ i ];
}
int leafnum = CM_PointLeafnum( org );
int clientarea = CM_LeafArea( leafnum );
int clientcluster = CM_LeafCluster( leafnum );
// calculate the visible areas
frame->areabytes = CM_WriteAreaBits( frame->areabits, clientarea );
// grab the current q2player_state_t
frame->ps = clent->client->ps;
SVQ2_FatPVS( org );
byte* clientphs = CM_ClusterPHS( clientcluster );
// build up the list of visible entities
frame->num_entities = 0;
frame->first_entity = svs.q2_next_client_entities;
int c_fullsend = 0;
for ( int e = 1; e < ge->num_edicts; e++ ) {
q2edict_t* ent = Q2_EDICT_NUM( e );
// ignore ents without visible models
if ( ent->svflags & Q2SVF_NOCLIENT ) {
continue;
}
// ignore ents without visible models unless they have an effect
if ( !ent->s.modelindex && !ent->s.effects && !ent->s.sound &&
!ent->s.event ) {
continue;
}
// ignore if not touching a PV leaf
if ( ent != clent ) {
// check area
if ( !CM_AreasConnected( clientarea, ent->areanum ) ) { // doors can legally straddle two areas, so
// we may need to check another one
if ( !ent->areanum2 ||
!CM_AreasConnected( clientarea, ent->areanum2 ) ) {
continue; // blocked by a door
}
}
// beams just check one point for PHS
if ( ent->s.renderfx & Q2RF_BEAM ) {
int l = ent->clusternums[ 0 ];
if ( !( clientphs[ l >> 3 ] & ( 1 << ( l & 7 ) ) ) ) {
continue;
}
} else {
// FIXME: if an ent has a model and a sound, but isn't
// in the PVS, only the PHS, clear the model
byte* bitvector = svq2_fatpvs;
if ( ent->num_clusters == -1 ) {
// too many leafs for individual check, go by headnode
if ( !CM_HeadnodeVisible( ent->headnode, bitvector ) ) {
continue;
}
c_fullsend++;
} else {
// check individual leafs
int i;
for ( i = 0; i < ent->num_clusters; i++ ) {
int l = ent->clusternums[ i ];
if ( bitvector[ l >> 3 ] & ( 1 << ( l & 7 ) ) ) {
break;
}
}
if ( i == ent->num_clusters ) {
continue; // not visible
}
}
if ( !ent->s.modelindex ) { // don't send sounds if they will be attenuated away
vec3_t delta;
float len;
VectorSubtract( org, ent->s.origin, delta );
len = VectorLength( delta );
if ( len > 400 ) {
continue;
}
}
}
}
// add it to the circular client_entities array
q2entity_state_t* state = &svs.q2_client_entities[ svs.q2_next_client_entities % svs.q2_num_client_entities ];
if ( ent->s.number != e ) {
common->DPrintf( "FIXING ENT->S.NUMBER!!!\n" );
ent->s.number = e;
}
*state = ent->s;
// don't mark players missiles as solid
if ( ent->owner == client->q2_edict ) {
state->solid = 0;
}
svs.q2_next_client_entities++;
frame->num_entities++;
}
}
// Save everything in the world out without deltas.
// Used for recording footage for merged or assembled demos
void SVQ2_RecordDemoMessage() {
if ( !svs.q2_demofile ) {
return;
}
q2entity_state_t nostate;
Com_Memset( &nostate, 0, sizeof ( nostate ) );
QMsg buf;
byte buf_data[ 32768 ];
buf.InitOOB( buf_data, sizeof ( buf_data ) );
// write a frame message that doesn't contain a q2player_state_t
buf.WriteByte( q2svc_frame );
buf.WriteLong( sv.q2_framenum );
buf.WriteByte( q2svc_packetentities );
for ( int e = 1; e < ge->num_edicts; e++ ) {
q2edict_t* ent = Q2_EDICT_NUM( e );
// ignore ents without visible models unless they have an effect
if ( ent->inuse &&
ent->s.number &&
( ent->s.modelindex || ent->s.effects || ent->s.sound || ent->s.event ) &&
!( ent->svflags & Q2SVF_NOCLIENT ) ) {
MSGQ2_WriteDeltaEntity( &nostate, &ent->s, &buf, false, true );
}
}
buf.WriteShort( 0 ); // end of packetentities
// now add the accumulated multicast information
buf.WriteData( svs.q2_demo_multicast._data, svs.q2_demo_multicast.cursize );
svs.q2_demo_multicast.Clear();
// now write the entire message to the file, prefixed by the length
int len = LittleLong( buf.cursize );
FS_Write( &len, 4, svs.q2_demofile );
FS_Write( buf._data, buf.cursize, svs.q2_demofile );
}
|
#ifndef PIPELINE_VISUALIZATION_TEST_H
#define PIPELINE_VISUALIZATION_TEST_H
#include <Presenter/PipelinePresenter.h>
#include <Presenter/Elements/Nodes/TurtleNodePresenter.h>
#include <Presenter/Elements/Nodes/HypergraphNodePresenter.h>
#include <Presenter/Elements/Nodes/MeshNodePresenter.h>
#include <Presenter/Elements/EdgePresenter.h>
#include <QtWidgets/QMainWindow>
#include <View/PipelineEditor/FuGenPipelineEditor.h>
#include <View/EdgeVisualizer/FuGenGLView.h>
class PipelineVisualizationTest : public QMainWindow
{
Q_OBJECT
private:
FuGenPipelineEditor *PipelineEditor;
FuGenGLView *EdgeVisualizer;
//
class GLViewListener : public IGLViewListener
{
private:
PipelineVisualizationTest &Test;
public:
virtual void OnInitialization() override
{
Test.InitTest();
}
//
virtual void OnDraw() override
{}
//
GLViewListener(PipelineVisualizationTest &test)
:Test(test)
{}
//
virtual ~GLViewListener()
{}
/*
* End of class
*/
};
//
GLViewListener ViewListener;
//
PipelinePresenter *TestPipelinePresenter;
TurtleNodePresenter *TestNodePresenter1;
HypergraphNodePresenter *TestNodePresenter2;
MeshNodePresenter *TestNodePresenter3;
/*EdgePresenter *TestEdgePresenter1;
EdgePresenter *TestEdgePresenter2;
EdgePresenter *TestEdgePresenter3;*/
//
void InitTest()
{
EdgeVisualizer->GetEdgeVisualizer().SetShowSplines(true);
EdgeVisualizer->GetEdgeVisualizer().SetShowCylinders(true);
//
TestPipelinePresenter = new PipelinePresenter(EdgeVisualizer);
//
TestNodePresenter1 = new TurtleNodePresenter(
EdgeVisualizer
);
//
TestNodePresenter1->SetAxiom("A");
//
constexpr double PI = 3.14159265359;
TestNodePresenter1->SetDeltaAngle(PI/2.0*0.25);
TestNodePresenter1->SetDeltaDistance(1.0);
//
TestNodePresenter1->AddProduction('A',"[&FL!A]/////’[&FL!A]///////’[&FL!A]");
TestNodePresenter1->AddProduction('F',"S ///// F");
TestNodePresenter1->AddProduction('S',"F L");
TestNodePresenter1->AddProduction('L',"[’’’^^{.-f.+f.+f.-|-f.+f.+f.}]");
//
TestNodePresenter1->SetRecursionDepth(5);
//
TestNodePresenter2 = new HypergraphNodePresenter(
EdgeVisualizer
);
//
TestNodePresenter2->SetRadius(0.125);
TestNodePresenter2->SetRadiusDecay(0.75);
TestNodePresenter2->SetParentWeight(0.0);
TestNodePresenter2->SetInitSpeed(0.0);
TestNodePresenter2->SetEndSpeed(0.0);
//
TestNodePresenter3 = new MeshNodePresenter(
EdgeVisualizer
);
//
TestNodePresenter3->SetSegmentWidth(4);
TestNodePresenter3->SetSegmentHeight(10);
//
/*TestEdgePresenter1 = new EdgePresenter(
*TestPipelinePresenter,
TestNodePresenter1->GetDataPresenter()
);
//
TestEdgePresenter2 = new EdgePresenter(
*TestPipelinePresenter,
TestNodePresenter2->GetDataPresenter()
);
//
TestEdgePresenter3 = new EdgePresenter(
*TestPipelinePresenter,
TestNodePresenter3->GetDataPresenter()
);*/
//
std::cout << "N1 to N2 " << TestNodePresenter2->IsConnectable(TestNodePresenter1) << std::endl;
std::cout << "N2 to N1 " << TestNodePresenter1->IsConnectable(TestNodePresenter2) << std::endl;
std::cout << "N2 to N3 " << TestNodePresenter3->IsConnectable(TestNodePresenter2) << std::endl;
std::cout << "N3 to N2 " << TestNodePresenter2->IsConnectable(TestNodePresenter3) << std::endl;
std::cout << "N1 to N3 " << TestNodePresenter3->IsConnectable(TestNodePresenter1) << std::endl;
std::cout << "N3 to N1 " << TestNodePresenter1->IsConnectable(TestNodePresenter3) << std::endl;
//
TestNodePresenter2->ConnectInput(TestNodePresenter1->GetDataPresenter());
TestNodePresenter3->ConnectInput(TestNodePresenter2->GetDataPresenter());
//
FuGenPipelineNode *First = PipelineEditor->AddNode(10,10);
First->SetModel(TestNodePresenter1);
FuGenPipelineNode *Second = PipelineEditor->AddNode(40,80);
Second->SetModel(TestNodePresenter2);
FuGenPipelineNode *Third = PipelineEditor->AddNode(50,140);
Third->SetModel(TestNodePresenter3);
FuGenPipelineNode *Last = PipelineEditor->AddNode(60,200);
Last->SetModel(TestPipelinePresenter->AddAppNode());
//
/*FuGenPipelineEdge *FirstToSecond = PipelineEditor->AddEdge(First,Second);
FirstToSecond->SetModel(TestEdgePresenter1);
//
FuGenPipelineEdge *SecondToThird = PipelineEditor->AddEdge(Second,Third);
SecondToThird->SetModel(TestEdgePresenter2);
//
FuGenPipelineEdge *ThirdToApp = PipelineEditor->AddEdge(Third,Last);
ThirdToApp->SetModel(TestEdgePresenter3);*/
//
PipelineEditor->SetModel(TestPipelinePresenter);
}
//
public:
//
PipelineVisualizationTest();
virtual ~PipelineVisualizationTest() override;
/*
* End of class
*/
};
#endif // PIPELINE_VISUALIZATION_TEST_H
|
#ifndef ARVOREB_H
#define ARVOREB_H
#include "../lib/No.h"
#include "../lib/utils.h"
#include <map>
#include <string>
#include <iostream>
class ArvoreB {
private:
int height;
std::map<int, No*> noMap;
public:
ArvoreB();
~ArvoreB();
bool insert(std::string, int);
void print();
int seek(std::string);
void setHeight(int);
int getHeight();
int getPos();
private:
No* buscaPosInsercao(No*, std::string);
bool inserirNo(No*, std::string, int, No*, No* );
};
#endif
|
#include <gtest/gtest.h>
// #include <whiskey/Whiskey.hpp>
#include <whiskey/Core/PrintLiterals.hpp>
#include <whiskey/Parsing/EvalLiterals.hpp>
using namespace whiskey;
TEST(Feature_Unicode, PrintLiteralChar) {
std::stringstream ss;
printLiteralChar(ss, 0x7f);
ASSERT_STREQ(ss.str().c_str(), "'\\x7f'");
ss.str("");
printLiteralChar(ss, 0x80);
ASSERT_STREQ(ss.str().c_str(), "'\\x80'");
ss.str("");
printLiteralChar(ss, 0xff);
ASSERT_STREQ(ss.str().c_str(), "'\\xff'");
ss.str("");
printLiteralChar(ss, 0x100);
ASSERT_STREQ(ss.str().c_str(), "'\\u0100'");
ss.str("");
printLiteralChar(ss, 0xffff);
ASSERT_STREQ(ss.str().c_str(), "'\\uffff'");
ss.str("");
printLiteralChar(ss, 0x10000);
ASSERT_STREQ(ss.str().c_str(), "'\\U00010000'");
ss.str("");
printLiteralChar(ss, 0xffffffff);
ASSERT_STREQ(ss.str().c_str(), "'\\Uffffffff'");
}
TEST(Feature_Unicode, PrintLiteralString8) {
std::stringstream ss;
printLiteralString(ss, "a\xff");
ASSERT_STREQ(ss.str().c_str(), "\"a\\xff\"");
}
TEST(Feature_Unicode, PrintLiteralString16) {
std::stringstream ss;
printLiteralString(ss, u"a\xff\uffff");
ASSERT_STREQ(ss.str().c_str(), "\"a\\xff\\uffff\"");
}
TEST(Feature_Unicode, PrintLiteralString32) {
std::stringstream ss;
printLiteralString(ss, U"a\xff\uffff\U0002070e");
ASSERT_STREQ(ss.str().c_str(), "\"a\\xff\\uffff\\U0002070e\"");
}
TEST(Feature_Unicode, AppendChar32ToString8) {
std::string s;
appendChar32ToString8(s, U'a');
ASSERT_STREQ(s.c_str(), "a");
s = "";
appendChar32ToString8(s, U'\xff');
ASSERT_STREQ(s.c_str(), "\xff");
s = "";
appendChar32ToString8(s, u'\u7702');
ASSERT_STREQ(s.c_str(), "\xc9\xb7");
}
|
#include "zeta.h"
#ifdef HAS_MPI
#include <mpi.h>
int myid;
#endif
void Zeta::print_matrix(const gsl_matrix *m)
{
for (size_t i = 0; i < m->size1; i++) {
for (size_t j = 0; j < m->size2; j++) {
cout << gsl_matrix_get(m, i, j) << " ";
}
cout << endl;
}
}
Zeta::Zeta()
{
_kZeta = 3;
_target = NULL;
_output = NULL;
_reference = NULL;
_mask = NULL;
_patchRadius = -1;
_nbhdRadius = -1;
_initialised = false;
_refCount = 0;
_chanOffset = 0;
_nPatchCentres = 0;
_patchOffsets = NULL;
_patchCentresI = NULL;
_patchCentresJ = NULL;
_patchCentresK = NULL;
_nbhdOffsets = NULL;
_nbhdVol = 0;
_patchVol = 0;
_patchCentreIndices = NULL;
_use_mahalanobis = true;
#ifdef HAS_MPI
MPI_Comm_rank(MPI_COMM_WORLD,&myid);
#endif
}
Zeta::~Zeta()
{
delete [] _reference;
delete [] _patchCentreIndices;
delete [] _patchCentresI;
delete [] _patchCentresJ;
delete [] _patchCentresK;
delete [] _patchOffsets;
delete [] _nbhdOffsets;
}
void Zeta::SetTarget(irtkRealImage* tgt)
{
_target = tgt;
}
void Zeta::SetMask(irtkGreyImage* mask)
{
_mask = mask;
}
void Zeta::SetReferences(int count, irtkRealImage** refImg)
{
_refCount = count;
_reference = new irtkRealImage *[_refCount];
for (int i = 0; i < _refCount; i++){
_reference[i] = refImg[i];
}
}
void Zeta::SetPatchRadius(int p)
{
_patchRadius = p;
#ifdef HAS_MPI
if (myid == 0)
#endif
{
cout << "Zeta::SetPatchRadius: Set patch radius to " << _patchRadius << endl;
}
}
void Zeta::SetNeighbourhoodRadius(int n)
{
_nbhdRadius = n;
#ifdef HAS_MPI
if (myid == 0)
#endif
{
cout << "Zeta::SetNeighbourhoodRadius: Set neighbourhood radius to " << _nbhdRadius << endl;
}
}
void Zeta::UseMahalanobis(bool val){
_use_mahalanobis = val;
#ifdef HAS_MPI
if (myid == 0)
#endif
{
if (_use_mahalanobis)
cout << "Zeta::UseMahalanobis: True" << endl;
else
cout << "Zeta::UseMahalanobis: False" << endl;
}
}
irtkRealImage *Zeta::GetOutput()
{
return _output;
}
void Zeta::GetCovariance(gsl_matrix *C, gsl_matrix *X)
{
// X: nObservations x nDims data matrix
// C: Covariance matrix for X, nDims x nDims
// BOTH MUST BE PRE-ALLOCATED.
int dim = X->size2;
int nDataPts = X->size1;
gsl_vector_view colI;
gsl_vector_view colJ;
double val;
for (unsigned int j = 0; j < dim; j++){
colJ = gsl_matrix_column(X, j);
val = gsl_stats_mean(colJ.vector.data,
colJ.vector.stride,
nDataPts);
gsl_vector_add_constant(&colJ.vector, -1*val);
}
for (int i = 0; i < dim; i++){
for (int j = i; j < dim; j++){
colI = gsl_matrix_column(X, i);
colJ = gsl_matrix_column(X, j);
val = gsl_stats_covariance(colI.vector.data,
colI.vector.stride,
colJ.vector.data,
colJ.vector.stride,
colI.vector.size);
gsl_matrix_set(C, i, j, val);
gsl_matrix_set(C, j, i, val);
}
}
}
void Zeta::GetPrecision(gsl_matrix *C, gsl_matrix *P)
{
// C: Input covariance matrix nDims x nDims
// P: Precision matrix, inverse of C, nDims x nDims
// BOTH MUST BE SQUARE, EQUAL SIZE AND PRE-ALLOCATED.
int dim = C->size1;
gsl_permutation * perm = gsl_permutation_alloc (dim);
int signum;
gsl_linalg_LU_decomp(C, perm, &signum);
double det = gsl_linalg_LU_det(C, signum);
if (det > 0.0001)
gsl_linalg_LU_invert(C, perm, P);
else
gsl_matrix_set_identity(P);
gsl_permutation_free(perm);
}
void Zeta::Initialise()
{
int xdim, ydim, zdim, nChannels;
// #ifdef HAS_MPI
// int myid;
// MPI_Comm_rank(MPI_COMM_WORLD,&myid);
// #endif
if (_target == NULL){
#ifdef HAS_MPI
if (myid == 0)
#endif
{
cerr << "Zeta::Initialise: Target not set. Exiting." << endl;
}
exit(1);
}
if (_refCount == 0){
#ifdef HAS_MPI
if (myid == 0)
#endif
{
cerr << "Zeta::Initialise: No reference images. Nothing to do." << endl;
cerr << "Exiting" << endl;
}
exit(1);
}
if (_patchRadius < 0){
#ifdef HAS_MPI
if (myid == 0)
#endif
{
cout << "Zeta::Initialise: Setting patch size to 3" << endl;
}
_patchRadius = 3;
}
if (_nbhdRadius < 0){
#ifdef HAS_MPI
if (myid == 0)
#endif
{
cout << "Zeta::Initialise: Setting neighbourhood size to 4" << endl;
}
_nbhdRadius = 4;
}
if (_kZeta < 2){
#ifdef HAS_MPI
if (myid == 0)
#endif
{
cerr << "Zeta::Initialise: Number of nearest neighbours is less than 2. Exiting" << endl;
}
exit(1);
}
xdim = _target->GetX();
ydim = _target->GetY();
zdim = _target->GetZ();
nChannels = _target->GetT();
irtkImageAttributes attr = _target->GetImageAttributes();
if (_mask == NULL){
#ifdef HAS_MPI
if (myid == 0)
#endif
{
cout << "Zeta::Initialise: Create default mask" << endl;
}
_mask = new irtkGreyImage(attr);
(*_mask) *= 0;
(*_mask) += 1;
}
if ((xdim != _mask->GetX()) ||
(ydim != _mask->GetY()) ||
(zdim != _mask->GetZ()) ){
#ifdef HAS_MPI
if (myid == 0)
#endif
{
cerr << "Zeta::Initialise: Mask dimensions don't match target. Exiting." << endl;
}
exit(1);
}
// Set the output image! it only needs to be a 3D volume.
attr._t = 1;
_output = new irtkRealImage;
_output->Initialize(attr);
for (int n = 0; n < _refCount; n++){
irtkRealImage *im = _reference[n];
if ((xdim != im->GetX()) ||
(ydim != im->GetY()) ||
(zdim != im->GetZ()) ||
(nChannels != im->GetT()) ){
#ifdef HAS_MPI
if (myid == 0)
#endif
{
cerr << "Zeta::Initialise: Reference image dimensions don't match target. Exiting." << endl;
}
exit(1);
}
}
// The limits on where a patch centre can be.
// Allowable indices between the low (inclusive) and the high (exclusive).
int fovI_lo = _patchRadius + _nbhdRadius;
int fovJ_lo = _patchRadius + _nbhdRadius;
int fovK_lo = _patchRadius + _nbhdRadius;
int fovI_hi = xdim - _patchRadius - _nbhdRadius;
int fovJ_hi = ydim - _patchRadius - _nbhdRadius;
int fovK_hi = zdim - _patchRadius - _nbhdRadius;
if ((fovI_lo < 0) ||
(fovI_hi > xdim) ||
(fovJ_lo < 0) ||
(fovJ_hi > ydim) ||
(fovK_lo < 0) ||
(fovK_hi > zdim) ||
(fovI_lo >= fovI_hi) ||
(fovJ_lo >= fovJ_hi) ||
(fovK_lo >= fovK_hi) )
{
#ifdef HAS_MPI
if (myid == 0)
#endif
{
cout << "Image to small for required neighbourhood and patch radii" << endl;
}
exit(1);
}
// Where can we place patches?
int n = 0;
for (int k = fovK_lo; k < fovK_hi; k++){
for (int j = fovJ_lo; j < fovJ_hi; j++){
for (int i = fovI_lo; i < fovI_hi; i++){
if ((*_mask)(i,j,k) > 0)
n++;
}
}
}
_nPatchCentres = n;
#ifdef HAS_MPI
if (myid == 0)
#endif
{
cout << "No of patch centres: " << _nPatchCentres << endl;
}
_patchCentreIndices = new unsigned long[_nPatchCentres];
_patchCentresI = new unsigned int[_nPatchCentres];
_patchCentresJ = new unsigned int[_nPatchCentres];
_patchCentresK = new unsigned int[_nPatchCentres];
n = 0;
for (int k = fovK_lo; k < fovK_hi; k++){
for (int j = fovJ_lo; j < fovJ_hi; j++){
for (int i = fovI_lo; i < fovI_hi; i++){
if ((*_mask)(i,j,k) > 0){
_patchCentreIndices[n] = _target->VoxelToIndex(i, j, k);
_patchCentresI[n] = i;
_patchCentresJ[n] = j;
_patchCentresK[n] = k;
n++;
}
}
}
}
// Offsets for a patch.
#ifdef HAS_MPI
if (myid == 0)
#endif
{
cout << "Zeta::Initialise: Patch radius = " << _patchRadius << endl;
}
int patchDiam = 1 + 2 * _patchRadius;
_patchVol = patchDiam * patchDiam * patchDiam;
_patchOffsets = new unsigned long[_patchVol];
// Arbitrary. Choose a centre point against which to find offsets.
long centreIndex = _target->VoxelToIndex(fovI_lo, fovJ_lo, fovK_lo);
n = 0;
for (int k = -_patchRadius; k < 1 + _patchRadius; k++){
for (int j = -_patchRadius; j < 1 + _patchRadius; j++){
for (int i = -_patchRadius; i < 1 + _patchRadius; i++){
long patchVoxelIndex = _target->VoxelToIndex(fovI_lo + i, fovJ_lo + j, fovK_lo + k);
_patchOffsets[n] = patchVoxelIndex - centreIndex;
n++;
}
}
}
// Offsets for a neighbourhood
#ifdef HAS_MPI
if (myid == 0)
#endif
{
cout << "Zeta::Initialise: Neighbourhood radius = " << _nbhdRadius << endl;
}
int nbhdDiam = 1 + 2 * _nbhdRadius;
_nbhdVol = nbhdDiam * nbhdDiam * nbhdDiam;
_nbhdOffsets = new unsigned long[_nbhdVol];
n = 0;
for (int k = -_nbhdRadius; k < 1 + _nbhdRadius; k++){
for (int j = -_nbhdRadius; j < 1 + _nbhdRadius; j++){
for (int i = -_nbhdRadius; i < 1 + _nbhdRadius; i++){
long nbhdVoxelIndex = _target->VoxelToIndex(fovI_lo + i, fovJ_lo + j, fovK_lo + k);
_nbhdOffsets[n] = nbhdVoxelIndex - centreIndex;
n++;
}
}
}
#ifdef HAS_MPI
if (myid == 0)
#endif
{
cout << "done. " << endl;
}
// Offset for moving from a voxel in one 3D volume to
// the corresponding voxel in the next volume (assuming a 4D image)
_chanOffset = xdim * ydim * zdim;
_initialised = true;
#ifdef HAS_MPI
if (myid == 0)
#endif
{
cout << "Done initialising" << endl;
}
}
void Zeta::Run(){
if (! _initialised){
this->Initialise();
}
// Loop over ROI voxels
irtkRealPixel *tgtStartPtr, *tgtPatchCentre, *refNbhdCentre, *refPatchCentre, *pTemp;
irtkRealPixel **refStartPtr;
refStartPtr = new irtkRealPixel*[_refCount];
for (int r = 0; r < _refCount; r++){
refStartPtr[r] = _reference[r]->GetPointerToVoxels();
}
tgtStartPtr = _target->GetPointerToVoxels();
int nChannels = _target->GetT();
gsl_matrix_view tgt_patch_vals;
gsl_matrix *diff, *diffPrec, *dist2;
diffPrec = gsl_matrix_alloc(1, _patchVol * nChannels);
dist2 = gsl_matrix_alloc(1, 1);
// Store the target patches.
// Each row is of length nChannels x patch volume. A row
// contains the values for a patch in the first channel
// followed by the patch values for the second channel and so on.
gsl_matrix *T = gsl_matrix_alloc(_nPatchCentres, _patchVol*nChannels);
for (int n = 0; n < _nPatchCentres; n++){
tgtPatchCentre = tgtStartPtr + _patchCentreIndices[n];
for (int k = 0; k < _patchVol; k++){
int offset = 0;
pTemp = tgtPatchCentre + _patchOffsets[k];
for (int chan = 0; chan < nChannels; chan++, offset += _chanOffset){
double val = *(pTemp + offset ) ;
gsl_matrix_set(T, n, k + chan*_patchVol, val);
}
}
}
// TODO: Transport to MPI section
// Find per-voxel precision matrix from Reference images.
// Only need to store upper triangle of precision matrix.
// There will be _refCount*_patchVol samples used to estimate a
// square covariance and precision matrix of size nChannels. Need to
// Check we have enough samples otherwise the covariance will be singular.
if (_refCount * _patchVol < nChannels){
cerr << "Insufficient samples to estimate covariance. " << endl;
cerr << "Consider increasing patch radius or number of reference images." << endl;
exit(1);
}
unsigned long nPrecMatEntries = nChannels * (nChannels + 1) / 2;
gsl_matrix* precMatData = gsl_matrix_alloc(_nPatchCentres, nPrecMatEntries);
// TODO: Make conditional if using mahalanobis
// Voxel data from all reference images at a patch location.
gsl_matrix* voxData = gsl_matrix_alloc(_refCount*_patchVol, nChannels);
gsl_vector *refVoxel = gsl_vector_alloc(nChannels);
// Covariance:
gsl_matrix *C = gsl_matrix_alloc(nChannels, nChannels);
// Precision:
gsl_matrix *P = gsl_matrix_alloc(nChannels, nChannels);
// Loop over patch centres.
for (int n = 0; n < _nPatchCentres; n++){
// Get all reference patches for current patch centre.
for (int r = 0; r < _refCount; r++){
refPatchCentre = refStartPtr[r] + _patchCentreIndices[n];
// Data for current reference.
for (int k = 0; k < _patchVol; k++){
// Particular voxel within the patch.
pTemp = refPatchCentre + _patchOffsets[k];
// Loop over channels
int offset = 0;
for (int chan = 0; chan < nChannels; chan++, offset += _chanOffset){
gsl_vector_set(refVoxel,
chan,
*(pTemp + offset));
}
// Store voxel info.
gsl_matrix_set_row(voxData,
r * _patchVol + k,
refVoxel);
}
} // References
// Get precision for current voxel.
GetCovariance(C, voxData);
GetPrecision(C, P);
int k = 0;
for (int i=0; i < nChannels; i++){
for (int j = i; j < nChannels; j++){
double val = gsl_matrix_get(P, i, j);
gsl_matrix_set(precMatData, n, k, val);
k++;
}
}
} // Patch centres
// Variables for distance calculation
gsl_vector *refPatch = gsl_vector_alloc(_patchVol*nChannels);
gsl_matrix *RefData = gsl_matrix_alloc(_refCount, _patchVol*nChannels);
diff = gsl_matrix_alloc(1, _patchVol*nChannels);
gsl_matrix_view refPatchA;
gsl_matrix_view refPatchB;
double val, minVal;
double *refDistsToTgt = new double[_refCount];
unsigned long int *sortInds = new unsigned long int[_refCount];
double meanPairwise, meanTgtToRef;
double normFactor = _kZeta * (_kZeta - 1) / 2.0;
// Progress markers
for (int i = 0; i <= 100; i++){
printf("|");
}
printf("\n");
fflush(stdout);
int nChunk = _nPatchCentres / 100;
gsl_matrix *prec = gsl_matrix_alloc(_patchVol * nChannels, _patchVol * nChannels);
// Loop over target patch centres.
for (int n = 0; n < _nPatchCentres; n++){
tgt_patch_vals = gsl_matrix_submatrix(T, n, 0, 1, T->size2);
// Get precision matrix for current patch.
// TODO: Make conditional if using mahalanobis
int k = 0;
for (int i=0; i < nChannels; i++){
for (int j = i; j < nChannels; j++){
double val = gsl_matrix_get(precMatData, n, k);
gsl_matrix_set(P, i, j, val);
gsl_matrix_set(P, j, i, val);
k++;
}
}
// Replicate the precision matrix along the diagonal of block matrix for the entire patch.
gsl_matrix_set_zero(prec);
for (int k = 0; k < _patchVol; k++){
gsl_matrix_view submat;
submat = gsl_matrix_submatrix(prec, k*nChannels, k*nChannels, nChannels, nChannels);
gsl_matrix_memcpy(&(submat.matrix), P);
}
// Find closest patch to the target for each reference, store it and record distance
// For each reference
for (int r = 0; r < _refCount; r++){
minVal = 100000000.0;
refNbhdCentre = refStartPtr[r] + _patchCentreIndices[n];
// Current voxel is centre of the neighbourhood, loop
// over reference patches in the neighbourhood.
for (int m = 0; m < _nbhdVol; m++){
refPatchCentre = refNbhdCentre + _nbhdOffsets[m];
// Data for current reference patch.
for (int k = 0; k < _patchVol; k++){
int offset = 0;
// Particular spatial location within the patch.
pTemp = refPatchCentre + _patchOffsets[k];
for (int chan = 0; chan < nChannels; chan++, offset += _chanOffset){
double val = *(pTemp + offset);
gsl_vector_set(refPatch, k+chan*_patchVol, val);
}
}
gsl_matrix_set_row(diff, 0, refPatch);
gsl_matrix_sub(diff, &(tgt_patch_vals.matrix));
if (_use_mahalanobis)
{
gsl_matrix_set_zero(diffPrec);
// diff is a row vector, 1 x (patch vol * channels)
// diffPrec = diff * _Prec
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, diff,
prec, 0.0, diffPrec);
gsl_matrix_set_zero(dist2);
// dist2 = diffPrec * diff^T
gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, diffPrec,
diff, 0.0, dist2);
}
else
{
// dist2 = diff * diff^T
gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, diff,
diff, 0.0, dist2);
}
val = sqrt( gsl_matrix_get(dist2, 0, 0) );
if (minVal > val){
// Pick the current patch as the best one from this reference.
minVal = val;
gsl_matrix_set_row(RefData, r, refPatch);
}
} // Loop over patches in neighbourhood for current reference image.
// Set the minimum value for the current reference.
refDistsToTgt[r] = minVal;
} // Loop over references
// Gamma: Mean 'distance' to k-nearest refs.
// Sort and take mean of first k
gsl_sort_smallest_index(sortInds, _kZeta, refDistsToTgt, 1, _refCount);
meanTgtToRef = 0.0;
for (int r = 0; r < _kZeta; r++){
meanTgtToRef += refDistsToTgt[sortInds[r]];
}
meanTgtToRef /= _kZeta;
// Get pairwise distances in the k-nearest clique of references and find their mean.
meanPairwise = 0.0;
for (int rA = 0; rA < _kZeta-1; rA++){
refPatchA = gsl_matrix_submatrix(RefData,
sortInds[rA], 0, 1, RefData->size2);
for (int rB = rA+1; rB < _kZeta; rB++){
refPatchB = gsl_matrix_submatrix(RefData,
sortInds[rB], 0, 1, RefData->size2);
gsl_matrix_memcpy(diff, &(refPatchB.matrix));
gsl_matrix_sub(diff, &(refPatchA.matrix));
if (_use_mahalanobis)
{
// dist2 = diff * diffPrec * diff^T
gsl_matrix_set_zero(diffPrec);
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, diff,
prec, 0.0, diffPrec);
gsl_matrix_set_zero(dist2);
gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, diffPrec,
diff, 0.0, dist2);
}
else
{
// dist2 = diff * diff^T
gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, diff,
diff, 0.0, dist2);
}
meanPairwise += sqrt( gsl_matrix_get(dist2, 0, 0) );
}
}
meanPairwise /= normFactor;
// Zeta is difference between Gamma and mean intra-clique distance.
_output->PutAsDouble(_patchCentresI[n], _patchCentresJ[n], _patchCentresK[n], meanTgtToRef - meanPairwise);
if (n % nChunk == 0){
printf(".");
fflush(stdout);
}
} // Loop over patch centres, index: n
cout << endl << endl;
gsl_matrix_free(diffPrec);
gsl_matrix_free(dist2);
gsl_matrix_free(T);
gsl_matrix_free(diff);
gsl_vector_free(refPatch);
gsl_matrix_free(RefData);
gsl_matrix_free(precMatData);
gsl_matrix_free(voxData);
gsl_vector_free(refVoxel);
gsl_matrix_free(C);
gsl_matrix_free(P);
delete [] refStartPtr;
delete [] refDistsToTgt;
delete [] sortInds;
}
#ifdef HAS_MPI
void Zeta::RunParallel()
{
if (! _initialised){
this->Initialise();
}
irtkRealPixel *tgtStartPtr, *tgtPatchCentre, *refNbhdCentre, *refPatchCentre, *pTemp;
irtkRealPixel **refStartPtr;
refStartPtr = new irtkRealPixel*[_refCount];
for (int r = 0; r < _refCount; r++){
refStartPtr[r] = _reference[r]->GetPointerToVoxels();
}
/* get myid and # of processors */
int myid,numproc;
MPI_Comm_size(MPI_COMM_WORLD,&numproc);
MPI_Comm_rank(MPI_COMM_WORLD,&myid);
if (myid == 0)
cout << "Zeta: Running parallel version." << endl;
tgtStartPtr = _target->GetPointerToVoxels();
int nChannels = _target->GetT();
gsl_matrix_view tgt_patch_vals;
gsl_matrix *diff, *diffPrec, *dist2;
diffPrec = gsl_matrix_alloc(1, _patchVol * nChannels);
dist2 = gsl_matrix_alloc(1, 1);
diff = gsl_matrix_alloc(1, _patchVol*nChannels);
gsl_vector *refPatch = gsl_vector_alloc(_patchVol*nChannels);
// gsl_vector *refPatchA = gsl_vector_alloc(_patchVol*tdim);
// gsl_vector *refPatchB = gsl_vector_alloc(_patchVol*tdim);
gsl_matrix_view refPatchA;
gsl_matrix_view refPatchB;
gsl_matrix *RefData = gsl_matrix_alloc(_refCount, _patchVol*nChannels);
double val, minVal;
double *refDistsToTgt = new double[_refCount];
unsigned long int *sortInds = new unsigned long int[_refCount];
double meanPairwise, meanTgtToRef;
double normFactor = _kZeta * (_kZeta - 1) / 2.0;
// Array to populate data from all processes.
double *outputValues;
if (myid == 0)
outputValues = new double[_nPatchCentres];
/* divide loop */
int *displs = new int[numproc];
int *scounts = new int[numproc];
int currDisp = 0;
int chunkSizeA = _nPatchCentres / numproc;
int chunkSizeB = 1 + chunkSizeA;
for (int i = 0; i < numproc; i++){
displs[i] = currDisp;
if ( i < _nPatchCentres % numproc ){
currDisp += chunkSizeB;
scounts[i] = chunkSizeB;
} else {
currDisp += chunkSizeA;
scounts[i] = chunkSizeA;
}
}
if (myid == 0){
for (int i = 0; i < numproc; i++){
printf(" i: %02d displ: %d scount: %d\n",i, displs[i], scounts[i]);
}
}
double *rbuf = new double[scounts[myid]];
MPI_Scatterv(outputValues, scounts, displs, MPI_DOUBLE, rbuf, scounts[myid], MPI_DOUBLE, 0, MPI_COMM_WORLD);
/* Compute for the following index limits */
int mystart = displs[myid];
int mycount = scounts[myid];
int myend = displs[myid] + mycount;
// Store the target patches.
// Each row is of length nChannels x patch volume. A row
// contains the values for a patch in the first channel
// followed by the patch values for the second channel and so on.
gsl_matrix *T = gsl_matrix_alloc(mycount, _patchVol*nChannels);
// TODO: Make the range of index values restricted to those for the current process.
for (int n = mystart; n < myend; n++){
tgtPatchCentre = tgtStartPtr + _patchCentreIndices[n];
for (int k = 0; k < _patchVol; k++){
int offset = 0;
pTemp = tgtPatchCentre + _patchOffsets[k];
for (int chan = 0; chan < nChannels; chan++, offset += _chanOffset){
double val = *(pTemp + offset ) ;
gsl_matrix_set(T, n - mystart, k + chan*_patchVol, val);
}
}
}
// Find per-voxel precision matrix from Reference images.
// Only need to store upper triangle of precision matrix.
// There will be _refCount*_patchVol samples used to estimate a
// square covariance and precision matrix of size nChannels. Need to
// Check we have enough samples otherwise the covariance will be singular.
if ((myid == 0) && (_refCount * _patchVol < nChannels)){
cerr << "Insufficient samples to estimate covariance. " << endl;
cerr << "Consider increasing patch radius or number of reference images." << endl;
exit(1);
}
unsigned long nPrecMatEntries = nChannels * (nChannels + 1) / 2;
gsl_matrix* precMatData = gsl_matrix_alloc(mycount, nPrecMatEntries);
// TODO: Make conditional if using mahalanobis
// Voxel data from all reference images at a patch location.
gsl_matrix* voxData = gsl_matrix_alloc(_refCount*_patchVol, nChannels);
gsl_vector *refVoxel = gsl_vector_alloc(nChannels);
// Covariance:
gsl_matrix *C = gsl_matrix_alloc(nChannels, nChannels);
// Precision:
gsl_matrix *P = gsl_matrix_alloc(nChannels, nChannels);
// Loop over patch centres.
for (int n = mystart; n < myend; n++){
// Get all reference patches for current patch centre.
for (int r = 0; r < _refCount; r++){
refPatchCentre = refStartPtr[r] + _patchCentreIndices[n];
// Data for current reference.
for (int k = 0; k < _patchVol; k++){
// Particular voxel within the patch.
pTemp = refPatchCentre + _patchOffsets[k];
// Loop over channels
int offset = 0;
for (int chan = 0; chan < nChannels; chan++, offset += _chanOffset){
gsl_vector_set(refVoxel,
chan,
*(pTemp + offset));
}
// Store voxel info.
gsl_matrix_set_row(voxData,
r * _patchVol + k,
refVoxel);
}
} // References
// Get precision for current voxel.
GetCovariance(C, voxData);
GetPrecision(C, P);
int k = 0;
for (int i=0; i < nChannels; i++){
for (int j = i; j < nChannels; j++){
double val = gsl_matrix_get(P, i, j);
gsl_matrix_set(precMatData, n - mystart, k, val);
k++;
}
}
} // Patch centres
gsl_matrix *prec = gsl_matrix_alloc(_patchVol * nChannels, _patchVol * nChannels);
// Now do the actual work. Loop over target patch centres.
for (int n = mystart; n < myend; n++){
tgt_patch_vals = gsl_matrix_submatrix(T, n - mystart, 0, 1, T->size2);
// Find closest patch to the target for each reference, store it and record distance
// For each reference
for (int r = 0; r < _refCount; r++){
minVal = 100000000.0;
refNbhdCentre = refStartPtr[r] + _patchCentreIndices[n];
// Current voxel is centre of the neighbourhood, loop
// over reference patches in the neighbourhood.
for (int m = 0; m < _nbhdVol; m++){
refPatchCentre = refNbhdCentre + _nbhdOffsets[m];
// Data for current reference patch.
for (int k = 0; k < _patchVol; k++){
int offset = 0;
// Particular spatial location within the patch.
pTemp = refPatchCentre + _patchOffsets[k];
for (int chan = 0; chan < nChannels; chan++, offset += _chanOffset){
double val = *(pTemp + offset);
gsl_vector_set(refPatch, k+chan*_patchVol, val);
}
}
gsl_matrix_set_row(diff, 0, refPatch);
gsl_matrix_sub(diff, &(tgt_patch_vals.matrix));
if (_use_mahalanobis)
{
// Get precision matrix for current patch.
int k = 0;
for (int i=0; i < nChannels; i++){
for (int j = i; j < nChannels; j++){
double val = gsl_matrix_get(precMatData, n - mystart, k);
gsl_matrix_set(P, i, j, val);
gsl_matrix_set(P, j, i, val);
k++;
}
}
// Replicate the precision matrix along the diagonal of block matrix for the entire patch.
gsl_matrix_set_zero(prec);
for (int k = 0; k < _patchVol; k++){
gsl_matrix_view submat;
submat = gsl_matrix_submatrix(prec, k*nChannels, k*nChannels, nChannels, nChannels);
gsl_matrix_memcpy(&(submat.matrix), P);
}
gsl_matrix_set_zero(diffPrec);
// diff is a row vector, 1 x (patch vol * channels)
// diffPrec = diff * _Prec
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, diff,
prec, 0.0, diffPrec);
gsl_matrix_set_zero(dist2);
// dist2 = diffPrec * diff^T
gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, diffPrec,
diff, 0.0, dist2);
}
else
{
// dist2 = diff * diff^T
gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, diff,
diff, 0.0, dist2);
}
val = sqrt( gsl_matrix_get(dist2, 0, 0) );
if (minVal > val){
// Pick the current patch as the best one from this reference.
minVal = val;
gsl_matrix_set_row(RefData, r, refPatch);
}
} // Loop over patches in neighbourhood for current reference image.
// Set the minimum value for the current reference.
refDistsToTgt[r] = minVal;
} // Loop over references
// Gamma: Mean 'distance' to k-nearest refs.
// Sort and take mean of first k
gsl_sort_smallest_index(sortInds, _kZeta, refDistsToTgt, 1, _refCount);
meanTgtToRef = 0.0;
for (int r = 0; r < _kZeta; r++){
meanTgtToRef += refDistsToTgt[sortInds[r]];
}
meanTgtToRef /= _kZeta;
// Get pairwise distances in the k-nearest clique of references and find their mean.
meanPairwise = 0.0;
for (int rA = 0; rA < _kZeta-1; rA++){
refPatchA = gsl_matrix_submatrix(RefData,
sortInds[rA], 0, 1, RefData->size2);
for (int rB = rA+1; rB < _kZeta; rB++){
refPatchB = gsl_matrix_submatrix(RefData,
sortInds[rB], 0, 1, RefData->size2);
gsl_matrix_memcpy(diff, &(refPatchB.matrix));
gsl_matrix_sub(diff, &(refPatchA.matrix));
if (_use_mahalanobis)
{
// dist2 = diff * diffPrec * diff^T
gsl_matrix_set_zero(diffPrec);
gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, diff,
prec, 0.0, diffPrec);
gsl_matrix_set_zero(dist2);
gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, diffPrec,
diff, 0.0, dist2);
}
else
{
// dist2 = diff * diff^T
gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1.0, diff,
diff, 0.0, dist2);
}
meanPairwise += sqrt( gsl_matrix_get(dist2, 0, 0) );
}
}
meanPairwise /= normFactor;
// Zeta is difference between Gamma and mean intra-clique distance.
rbuf[n - mystart] = meanTgtToRef - meanPairwise;
} // Loop over patch centres, index: n
MPI_Gatherv(rbuf, scounts[myid],
MPI_DOUBLE, outputValues, scounts, displs, MPI_DOUBLE, 0, MPI_COMM_WORLD);
// Loop over target patch centres.
if (myid == 0){
for (int n = 0; n < _nPatchCentres; n++){
_output->PutAsDouble(_patchCentresI[n], _patchCentresJ[n], _patchCentresK[n], outputValues[n]);
}
}
gsl_matrix_free(diffPrec);
gsl_matrix_free(dist2);
gsl_matrix_free(T);
gsl_matrix_free(diff);
gsl_vector_free(refPatch);
gsl_matrix_free(RefData);
delete [] refStartPtr;
delete [] refDistsToTgt;
delete [] sortInds;
if (myid == 0)
delete [] outputValues;
}
#endif
void Zeta::Print(){
cout << "Patch radius: " << _patchRadius << endl;
cout << "Neighbourhood radius: " << _nbhdRadius << endl;
cout << "Number of voxels in ROI " << _nPatchCentres << endl;
cout << "Number of reference images: " << _refCount << endl;
cout << "Number of neighbours (k): " << _kZeta << endl;
int nChannels = _target->GetT();
cout << "Channels: " << nChannels << endl;
}
|
#pragma once
#include "afxcmn.h"
#include "Tap_Proxy.h"
#include "Tap_ARP.h"
#include "Tap_Others.h"
// Option_main 대화 상자입니다.
class Option_main : public CDialogEx
{
DECLARE_DYNAMIC(Option_main)
public:
Option_main(CWnd* pParent = NULL); // 표준 생성자입니다.
virtual ~Option_main();
// 대화 상자 데이터입니다.
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_Option_main };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다.
DECLARE_MESSAGE_MAP()
public:
CTabCtrl m_ctlTab;
Tap_Proxy *m_pTap_Proxy;
Tap_ARP *m_pTap_ARP;
Tap_Others *m_pTap_Others;
CWnd *c_pWnd;
afx_msg void OnTcnSelchangeTab1(NMHDR *pNMHDR, LRESULT *pResult);
};
|
/*
* Copyright (c) 1998-2004 Apple Computer, Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* The contents of this file constitute Original Code as defined in and
* are subject to the Apple Public Source License Version 1.1 (the
* "License"). You may not use this file except in compliance with the
* License. Please obtain a copy of the License at
* http://www.apple.com/publicsource and read it before using this file.
*
* This Original Code and all software distributed under the License are
* distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
* License for the specific language governing rights and limitations
* under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
/*
* Copyright (c) 1996 NeXT Software, Inc. All rights reserved.
*
* i82557.cpp
*
* HISTORY
*
* 22-Jan-96 Dieter Siegmund (dieter) at NeXT
* Created.
*
* 03-May-96 Dieter Siegmund (dieter) at NeXT
* Added a real ISR to improve performance.
*
* 10-June-96 Dieter Siegmund (dieter) at NeXT
* Added support for Splash 3 (10 Base-T only card).
*
* 18-June-96 Dieter Siegmund (dieter) at NeXT
* Keep the transmit queue draining by interrupting every
* N / 2 transmits (where N is the size of the hardware queue).
*
* 15-Dec-97 Joe Liu (jliu) at Apple
* Updated PHY programming to be 82558 aware.
* Misc changes to conform to new 82558 register flags.
* Changed RNR interrupt handler to restart RU instead of a reset.
* Interrupt handler now does a thread_call_func() to do most of its work.
* Interrupts are disabled until the thread callout finishes its work.
* Increased the size of TX/RX rings.
* buffer object removed, we use cluster mbufs to back up the receive ring.
*
* 29-May-98 Joe Liu (jliu) at Apple
* Updated _setupPhy method to take advantage of parallel detection whenever
* possible in order to detect the proper link speed.
*
* 17-Aug-98 Joe Liu (jliu) at Apple
* Re-enabled the setting of txready_sel PHY (PCS) bit for DP83840.
* Simplified interrupt handling, resulting in RCV performance improvements.
* Receive packets are sent upstream via a cached function pointer.
*/
#include "i82557.h"
#define ONE_SECOND_TICKS 1000
#define LOAD_STATISTICS_INTERVAL (4 * ONE_SECOND_TICKS)
#define super IOEthernetController
OSDefineMetaClassAndStructors( Intel82557, IOEthernetController )
//---------------------------------------------------------------------------
// Function: pciConfigInit
//
// Update PCI command register to enable the memory-mapped range,
// and bus-master interface.
bool Intel82557::pciConfigInit(IOPCIDevice * provider)
{
UInt16 reg16;
reg16 = provider->configRead16( kIOPCIConfigCommand );
reg16 |= ( kIOPCICommandBusMaster |
kIOPCICommandMemorySpace |
kIOPCICommandMemWrInvalidate );
reg16 &= ~kIOPCICommandIOSpace; // disable I/O space
provider->configWrite16( kIOPCIConfigCommand, reg16 );
// To allow the device to use the PCI Memory Write and Invalidate
// command, it must know the correct cache line size. The only
// supported cache line sizes are 8 and 16 Dwords.
//
// Do not modify the cache line size register. Leave this up
// to the platform's firmware.
// provider->configWrite8( kIOPCIConfigCacheLineSize, 8 );
// Locate the PM register block of this device in its PCI config space.
provider->findPCICapability( kIOPCIPowerManagementCapability,
&pmPCICapPtr );
if ( pmPCICapPtr )
{
UInt16 pciPMCReg = provider->configRead32( pmPCICapPtr ) >> 16;
// Only devices that support PME# assertion from D3-cold are
// considered valid for supporting Magic Packet wakeup.
if ( pciPMCReg & kPCIPMCPMESupportFromD3Cold )
{
magicPacketSupported = true;
}
// Clear PME# and set power state to D0.
provider->configWrite16( kPCIPMCSR, 0x8000 );
IOSleep( 10 );
}
return true;
}
//---------------------------------------------------------------------------
// Function: initDriver
//
// Create and initialize driver objects before the hardware is
// enabled.
//
// Returns true on sucess, and false if initialization failed.
bool Intel82557::initDriver(IOService * provider)
{
currentMediumType = MEDIUM_TYPE_INVALID;
// This driver will allocate and use an IOGatedOutputQueue.
//
transmitQueue = getOutputQueue();
if ( transmitQueue == 0 ) return false;
// Allocate two IOMbufLittleMemoryCursor instances. One for transmit and
// the other for receive.
//
rxMbufCursor = IOMbufLittleMemoryCursor::withSpecification(MAX_BUF_SIZE,1);
txMbufCursor = IOMbufLittleMemoryCursor::withSpecification(MAX_BUF_SIZE,
TBDS_PER_TCB);
if (!rxMbufCursor || !txMbufCursor)
return false;
// Get a handle to our superclass' workloop.
//
IOWorkLoop * myWorkLoop = (IOWorkLoop *) getWorkLoop();
if (!myWorkLoop)
return false;
// Create and register an interrupt event source. The provider will
// take care of the low-level interrupt registration stuff.
//
interruptSrc = IOFilterInterruptEventSource::filterInterruptEventSource(
this,
&Intel82557::interruptHandler,
&Intel82557::interruptFilter,
provider);
if (!interruptSrc ||
(myWorkLoop->addEventSource(interruptSrc) != kIOReturnSuccess))
return false;
// This is important. If the interrupt line is shared with other devices,
// then the interrupt vector will be enabled only if all corresponding
// interrupt event sources are enabled. To avoid masking interrupts for
// other devices that are sharing the interrupt line, the event source
// is enabled immediately.
interruptSrc->enable();
// Register a timer event source. This is used as a watchdog timer.
//
timerSrc = IOTimerEventSource::timerEventSource( this,
&Intel82557::timeoutHandler );
if (!timerSrc ||
(myWorkLoop->addEventSource(timerSrc) != kIOReturnSuccess))
return false;
// Create a dictionary to hold IONetworkMedium objects.
//
mediumDict = OSDictionary::withCapacity(5);
if (!mediumDict)
return false;
return true;
}
//---------------------------------------------------------------------------
// Function: getDefaultSettings
//
// Get the default driver settings chosen by the user. The properties
// are all stored in our property table (an OSDictionary).
bool Intel82557::getDefaultSettings()
{
OSNumber * numObj;
// Check for PHY address override.
//
phyAddr = PHY_ADDRESS_DEFAULT;
numObj = OSDynamicCast( OSNumber, getProperty("PHY Address") );
if ( numObj )
{
phyAddr = numObj->unsigned32BitValue();
}
// Check for Verbose flag.
//
verbose = false;
if ( getProperty("Verbose") == kOSBooleanTrue )
{
IOLog("%s: verbose mode enabled\n", getName());
verbose = true;
}
// Check for Flow-Control enable flag.
//
flowControl = false;
if ( getProperty("Flow Control") == kOSBooleanTrue )
{
VPRINT("%s: 802.3x flow control enabled\n", getName());
flowControl = true;
}
// The number of bytes that must be present in the FIFO before the
// transmission on the wire begins. The value read from the table
// is divided by 8 to yield the value programmed to the TxCB.
// The range is from 1 to 0xE0.
txThreshold8 = TCB_TX_THRESHOLD;
numObj = OSDynamicCast( OSNumber, getProperty("Transmit Threshold") );
if ( numObj && numObj->unsigned32BitValue() >= 8 )
{
txThreshold8 = min( 0xE0, numObj->unsigned32BitValue() / 8 );
VPRINT("%s: transmit threshold 0x%x\n", getName(), txThreshold8);
}
return true;
}
//---------------------------------------------------------------------------
// Function: start <IOService>
//
// Hardware was detected and initialized, start the driver.
bool Intel82557::start( IOService * provider )
{
bool ret = false;
bool started = false;
do {
// Start our superclass first.
if ( super::start(provider) == false )
break;
started = true;
// Cache our provider to an instance variable.
pciNub = OSDynamicCast(IOPCIDevice, provider);
if ( pciNub == 0 ) break;
// Retain provider, released in free().
pciNub->retain();
// Open our provider.
if ( pciNub->open(this) == false ) break;
// Request domain power.
// Without this, the PCIDevice may be in state 0, and the
// PCI config space may be invalid if the machine has been
// sleeping.
if ( pciNub->requestPowerDomainState(
/* power flags */ kIOPMPowerOn,
/* connection */ (IOPowerConnection *) getParentEntry(gIOPowerPlane),
/* spec */ IOPMLowestState ) != IOPMNoErr )
{
break;
}
// Initialize the driver's event sources and other support objects.
if ( initDriver(provider) == false ) break;
// Get the virtual address mapping of CSR registers located at
// Base Address Range 0 (0x10). The size of this range is 4K.
// This was changed to 32 bytes in 82558 A-Step, though only
// the first 32 bytes should be accessed, and the other bytes
// are considered reserved.
csrMap = pciNub->mapDeviceMemoryWithRegister( kIOPCIConfigBaseAddress0 );
if ( csrMap == 0 ) break;
CSR_p = (CSR_t *) csrMap->getVirtualAddress();
// Setup our PCI config space.
if ( pciConfigInit(pciNub) == false ) break;
// Create the EEPROM object.
eeprom = i82557eeprom::withAddress(&CSR_p->eepromControl);
if ( eeprom == 0 )
{
IOLog("%s: couldn't allocate eeprom object", getName());
break;
}
// Get default driver settings (stored in property table).
if ( getDefaultSettings() == false ) break;
if ( verbose ) eeprom->dumpContents();
// Execute one-time initialization code.
if ( coldInit() == false )
{
VPRINT("%s: coldInit failed\n", getName());
break;
}
if ( hwInit() == false )
{
VPRINT("%s: hwInit failed\n", getName());
break;
}
// Publish our media capabilities.
_phyPublishMedia();
if ( publishMediumDictionary(mediumDict) == false )
{
VPRINT("%s: publishMediumDictionary failed\n", getName());
break;
}
#if 0
// Announce the basic hardware configuration info.
IOLog("%s: Memory 0x%lx irq %d\n", getName(),
csrMap->getPhysicalAddress(), 0);
#endif
ret = true;
}
while ( false );
// Close our provider, it will be re-opened on demand when
// our enable() method is called.
if ( pciNub ) pciNub->close(this);
do {
if ( ret == false ) break;
ret = false;
// Allocate and attach an IOEthernetInterface instance to this driver
// object.
if ( attachInterface((IONetworkInterface **) &netif, false) == false )
break;
// Attach a kernel debugger client. This is not an essential service,
// and the return is not checked.
attachDebuggerClient(&debugger);
// Start matching for clients of IONetworkInterface.
netif->registerService();
ret = true;
}
while ( false );
// Issue a stop on failure.
if (started && !ret) super::stop(provider);
return ret;
}
//---------------------------------------------------------------------------
// Function: stop <IOService>
//
// Stop all activities and prepare for termination.
void Intel82557::stop(IOService * provider)
{
super::stop(provider);
}
//---------------------------------------------------------------------------
// Function: createWorkLoop <IONetworkController>
//
// Override IONetworkController::createWorkLoop() method to create and return
// a new work loop object.
bool Intel82557::createWorkLoop()
{
workLoop = IOWorkLoop::workLoop();
return ( workLoop != 0 );
}
//---------------------------------------------------------------------------
// Function: getWorkLoop <IOService>
//
// Override IOService::getWorkLoop() method and return a reference to our
// work loop.
IOWorkLoop * Intel82557::getWorkLoop() const
{
return workLoop;
}
//---------------------------------------------------------------------------
// Function: configureInterface <IONetworkController>
//
// Configure a newly instantiated IONetworkInterface object.
bool Intel82557::configureInterface(IONetworkInterface * netif)
{
IONetworkData * data;
if ( super::configureInterface(netif) == false )
return false;
// Get the generic network statistics structure.
data = netif->getParameter(kIONetworkStatsKey);
if (!data || !(netStats = (IONetworkStats *) data->getBuffer())) {
return false;
}
// Get the Ethernet statistics structure.
data = netif->getParameter(kIOEthernetStatsKey);
if (!data || !(etherStats = (IOEthernetStats *) data->getBuffer())) {
return false;
}
return true;
}
//---------------------------------------------------------------------------
// Function: free <IOService>
//
// Deallocate all resources and destroy the instance.
void Intel82557::free()
{
#define RELEASE(x) do { if(x) { (x)->release(); (x) = 0; } } while(0)
RELEASE( debugger );
RELEASE( netif );
if ( interruptSrc && workLoop )
{
workLoop->removeEventSource( interruptSrc );
}
RELEASE( interruptSrc );
RELEASE( timerSrc );
RELEASE( rxMbufCursor );
RELEASE( txMbufCursor );
RELEASE( csrMap );
RELEASE( eeprom );
RELEASE( mediumDict );
RELEASE( pciNub );
RELEASE( workLoop );
freePageBlock( &shared );
freePageBlock( &txRing );
freePageBlock( &rxRing );
if ( powerOffThreadCall )
{
thread_call_free( powerOffThreadCall );
powerOffThreadCall = 0;
}
if ( powerOnThreadCall )
{
thread_call_free( powerOnThreadCall );
powerOnThreadCall = 0;
}
super::free(); // pass it to our superclass
}
//---------------------------------------------------------------------------
// Function: enableAdapter
//
// Enables the adapter & driver to the given level of support.
bool Intel82557::enableAdapter(UInt32 level)
{
bool ret = false;
// IOLog("%s::%s enabling level %ld\n", getName(), __FUNCTION__, level);
switch (level) {
case kActivationLevel1:
// Open provider.
//
if ( ( pciNub == 0 ) || ( pciNub->open(this) == false ) )
{
break;
}
if ( hwInit() == false )
{
VPRINT("%s: hwInit failed\n", getName());
break;
}
if (!_initRingBuffers())
break;
if (!_startReceive()) {
_clearRingBuffers();
break;
}
// Set current medium.
//
if (selectMedium(getCurrentMedium()) != kIOReturnSuccess)
VPRINT("%s: selectMedium error\n", getName());
// Start the watchdog timer.
//
timerSrc->setTimeoutMS(LOAD_STATISTICS_INTERVAL);
// Enable hardware interrupt sources.
enableAdapterInterrupts();
// Force PHY to report link status.
//
_phyReportLinkStatus(true);
ret = true;
break;
case kActivationLevel2:
// Issue a dump statistics command.
//
_dumpStatistics();
// Start our IOOutputQueue object.
//
transmitQueue->setCapacity(TRANSMIT_QUEUE_SIZE);
transmitQueue->start();
ret = true;
break;
}
if (!ret)
VPRINT("%s::%s error in level %ld\n", getName(), __FUNCTION__, level);
return ret;
}
//---------------------------------------------------------------------------
// Function: disableAdapter
//
// Disables the adapter & driver to the given level of support.
bool Intel82557::disableAdapter(UInt32 level)
{
bool ret = false;
// IOLog("%s::%s disabling level %ld\n", getName(), __FUNCTION__, level);
switch (level) {
case kActivationLevel1:
// Disable hardware interrupt sources.
//
disableAdapterInterrupts();
// Stop the timer event source, and initialize the watchdog state.
//
timerSrc->cancelTimeout();
packetsReceived = true; // assume we're getting packets
packetsTransmitted = false;
txCount = 0;
txPendingInterruptCount = 0;
txWatchdogArmed = false;
// Reset the hardware engine.
//
ret = hwInit( true );
// Clear the descriptor rings after the hardware is idle.
//
_clearRingBuffers();
// Report link status: valid and down.
//
setLinkStatus( kIONetworkLinkValid );
// Flush all packets held in the queue and prevent it
// from accumulating any additional packets.
//
transmitQueue->setCapacity(0);
transmitQueue->flush();
// Close provider.
//
if ( pciNub )
{
pciNub->close(this);
}
break;
case kActivationLevel2:
// Stop the transmit queue. outputPacket() will not get called
// after this.
//
transmitQueue->stop();
ret = true;
break;
}
if (!ret)
VPRINT("%s::%s error in level %ld\n", getName(), __FUNCTION__, level);
return ret;
}
//---------------------------------------------------------------------------
bool Intel82557::resetAdapter( void )
{
bool success = false;
UInt32 oldLevel = currentLevel;
etherStats->dot3RxExtraEntry.resets++;
etherStats->dot3TxExtraEntry.resets++;
setActivationLevel(0);
if (setActivationLevel(oldLevel))
{
// promiscuous setting, MAC address override, and media
// type are automatically restored when chip is brought
// back up, but not so for the hardware multicast hash.
success = mcSetup(0, 0, true);
}
IOLog("%s: chip reset%s\n", getName(), success ? "" : " FAILED");
return success;
}
//---------------------------------------------------------------------------
// Function: setActivationLevel
//
// Sets the adapter's activation level.
//
// kActivationLevel0 - Adapter is disabled.
// kActivationLevel1 - Adapter is brought up just enough to support debugging.
// kActivationLevel2 - Adapter is completely up.
bool Intel82557::setActivationLevel(UInt32 level)
{
bool ret = false;
UInt32 nextLevel;
// IOLog("---> DESIRED LEVEL : %d\n", level);
if (currentLevel == level) return true;
for ( ; currentLevel > level; currentLevel--)
{
if ( (ret = disableAdapter(currentLevel)) == false )
break;
}
for ( nextLevel = currentLevel + 1;
currentLevel < level;
currentLevel++, nextLevel++ )
{
if ( (ret = enableAdapter(nextLevel)) == false )
break;
}
// IOLog("---> PRESENT LEVEL : %d\n\n", currentLevel);
return ret;
}
//---------------------------------------------------------------------------
// Function: enable <IONetworkController>
//
// A request from our interface client to enable the adapter.
IOReturn Intel82557::enable(IONetworkInterface * /*netif*/)
{
if ( enabledForNetif ) return kIOReturnSuccess;
enabledForNetif = setActivationLevel( kActivationLevel2 );
return ( enabledForNetif ? kIOReturnSuccess : kIOReturnIOError );
}
//---------------------------------------------------------------------------
// Function: disable <IONetworkController>
//
// A request from our interface client to disable the adapter.
IOReturn Intel82557::disable(IONetworkInterface * /*netif*/)
{
enabledForNetif = false;
setActivationLevel( enabledForDebugger ?
kActivationLevel1 : kActivationLevel0 );
return kIOReturnSuccess;
}
//---------------------------------------------------------------------------
// Function: enable <IONetworkController>
//
// A request from our debugger client to enable the adapter.
IOReturn Intel82557::enable(IOKernelDebugger * /*debugger*/)
{
if ( enabledForDebugger || enabledForNetif )
{
enabledForDebugger = true;
return kIOReturnSuccess;
}
enabledForDebugger = setActivationLevel( kActivationLevel1 );
return ( enabledForDebugger ? kIOReturnSuccess : kIOReturnIOError );
}
//---------------------------------------------------------------------------
// Function: disable <IONetworkController>
//
// A request from our debugger client to disable the adapter.
IOReturn Intel82557::disable(IOKernelDebugger * /*debugger*/)
{
enabledForDebugger = false;
if ( enabledForNetif == false )
setActivationLevel( kActivationLevel0 );
return kIOReturnSuccess;
}
//---------------------------------------------------------------------------
// Function: timeoutOccurred
//
// Periodic timer that monitors the receiver status, updates error
// and collision statistics, and update the current link status.
void Intel82557::timeoutOccurred( IOTimerEventSource * /*timer*/ )
{
if ( (packetsReceived == false) && (packetsTransmitted == true) )
{
/*
* The B-step of the i82557 requires that an mcsetup command be
* issued if the receiver stops receiving. This is a documented
* errata.
*/
mcSetup(0, 0, true);
}
packetsReceived = packetsTransmitted = false;
if (txWatchdogArmed &&
etherStats->dot3TxExtraEntry.interrupts == txLastInterruptCount)
{
reserveDebuggerLock();
resetAdapter();
releaseDebuggerLock();
}
txWatchdogArmed = (txPendingInterruptCount > 0);
if (txWatchdogArmed)
txLastInterruptCount = etherStats->dot3TxExtraEntry.interrupts;
_updateStatistics();
_phyReportLinkStatus();
timerSrc->setTimeoutMS(LOAD_STATISTICS_INTERVAL);
}
void Intel82557::timeoutHandler( OSObject * target, IOTimerEventSource * src )
{
// C++ glue to eliminate compiler warnings
((Intel82557 *) target)->timeoutOccurred( src );
}
//---------------------------------------------------------------------------
// Function: setPromiscuousMode <IOEthernetController>
IOReturn Intel82557::setPromiscuousMode( bool active )
{
bool rv;
promiscuousEnabled = active;
reserveDebuggerLock();
rv = config();
releaseDebuggerLock();
return (rv ? kIOReturnSuccess : kIOReturnIOError);
}
//---------------------------------------------------------------------------
// Function: setMulticastMode <IOEthernetController>
IOReturn Intel82557::setMulticastMode( bool active )
{
return kIOReturnSuccess;
}
//---------------------------------------------------------------------------
// Function: setMulticastList <IOEthernetController>
IOReturn Intel82557::setMulticastList(IOEthernetAddress * addrs, UInt32 count)
{
IOReturn ret = kIOReturnSuccess;
if ( mcSetup(addrs, count) == false )
{
VPRINT("%s: set multicast list failed\n", getName());
ret = kIOReturnIOError;
}
return ret;
}
//---------------------------------------------------------------------------
// Function: getPacketBufferConstraints <IONetworkController>
//
// Return our driver's packet alignment requirements.
void
Intel82557::getPacketBufferConstraints(IOPacketBufferConstraints * constraints) const
{
constraints->alignStart = kIOPacketBufferAlign2; // even word aligned.
constraints->alignLength = kIOPacketBufferAlign1; // no restriction.
}
//---------------------------------------------------------------------------
// Function: getHardwareAddress <IOEthernetController>
//
// Return the adapter's hardware/Ethernet address.
IOReturn Intel82557::getHardwareAddress(IOEthernetAddress * addrs)
{
bcopy(&myAddress, addrs, sizeof(*addrs));
return kIOReturnSuccess;
}
//---------------------------------------------------------------------------
// Function: setHardwareAddress <IOEthernetController>
//
// Change the address filtered by the unicast filter.
IOReturn Intel82557::setHardwareAddress( const IOEthernetAddress * addr )
{
IOReturn ior = kIOReturnSuccess;
memcpy( &myAddress, addr, sizeof(myAddress) );
if (currentLevel > kActivationLevel0)
{
// Adapter is up and running, setup the hardware IA filter.
if (iaSetup() == false)
ior = kIOReturnIOError;
}
return ior;
}
//---------------------------------------------------------------------------
// Function: createOutputQueue <IONetworkController>
//
// Allocate an IOGatedOutputQueue instance.
IOOutputQueue * Intel82557::createOutputQueue()
{
return IOGatedOutputQueue::withTarget(this, getWorkLoop());
}
//---------------------------------------------------------------------------
// Function: selectMedium <IONetworkController>
//
// Transition the controller/PHY to use a new medium. Note that
// this function can be called my the driver, or by our client.
IOReturn Intel82557::selectMedium(const IONetworkMedium * medium)
{
bool r;
if ( OSDynamicCast(IONetworkMedium, medium) == 0 )
{
// Defaults to Auto.
medium = _phyGetMediumWithType( MEDIUM_TYPE_AUTO );
if ( medium == 0 ) return kIOReturnError;
}
#if 0
IOLog("%s: selectMedium -> %s\n", getName(),
medium->getName()->getCStringNoCopy());
#endif
// Program PHY to select the desired medium.
//
r = _phySetMedium( (mediumType_t) medium->getIndex() );
// Update the current medium property.
//
if ( r && !setCurrentMedium(medium) )
VPRINT("%s: setCurrentMedium error\n", getName());
return ( r ? kIOReturnSuccess : kIOReturnIOError );
}
//---------------------------------------------------------------------------
// Function: newVendorString(), newModelString()
// <IONetworkController>
//
// Report human readable hardware information strings.
const OSString * Intel82557::newVendorString() const
{
return OSString::withCString("Intel");
}
const OSString * Intel82557::newModelString() const
{
const char * model = 0;
assert( eeprom && eeprom->getContents() );
switch ( eeprom->getContents()->controllerType )
{
case I82558_CONTROLLER_TYPE:
model = "82558";
break;
case I82557_CONTROLLER_TYPE:
default:
model = "82557";
break;
}
return OSString::withCString(model);
}
//---------------------------------------------------------------------------
// Kernel debugger entry points.
//
// KDP driven polling routines to send and transmit a frame.
// Remember, no memory allocation! Not even mbufs are safe.
void Intel82557::sendPacket(void * pkt, UInt32 pkt_len)
{
txWatchdogArmed = false;
_sendPacket(pkt, pkt_len);
}
void Intel82557::receivePacket(void * pkt, UInt32 * pkt_len, UInt32 timeout)
{
txWatchdogArmed = false;
_receivePacket(pkt, (UInt *) pkt_len, timeout);
}
|
/**
* @brief Work with shade files
* @file Shader.h
* @author matthewpoletin
*/
#pragma once
#include <iostream>
#include <string>
#include <fstream>
#include <GL/glew.h>
#include "Transform.h"
#include "Camera.h"
class Shader {
public:
/**
* Shader constructor
* @param fileName Shader file names
*/
explicit Shader(const std::string &fileName);
/**
* Bind shader
*/
void Bind();
/**
* Update shader
* @param transform Transform
* @param camera Camera
*/
void Update(const Transform &transform, const Camera &camera);
virtual ~Shader();
protected:
private:
// Number of shaders
static const unsigned int NUM_SHADERS = 2;
/**
* Copy constructor
* @param other Other shader
*/
Shader(const Shader &other);
enum {
TRANSFORM_U,
NUM_UNIFORMS
};
/**
* Check shader error
* @param shader Shader
* @param flag Flag
* @param isProgram Is program
* @param errorMessage Error message
*/
static void CheckShaderError(GLuint shader, GLuint flag, bool isProgram, const std::string &errorMessage);
/**
* Load shader
* @param fileName File name
* @return Shader
*/
static std::string LoadShader(const std::string &fileName);
/**
* Create shader
* @param text Shader
* @param shaderType Shader type
* @return Created shader
*/
static GLuint CreateShader(const std::string &text, GLenum shaderType);
GLuint m_program;
GLuint m_shaders[NUM_SHADERS];
GLuint m_uniforms[NUM_UNIFORMS];
};
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
#define pb push_back
#define rsz resize
#define all(x) begin(x), end(x)
#define sz(x) (int)(x).size()
using pi = pair<int, int>;
#define f first
#define s second
#define mp make_pair
int main()
{
setIO();
vector<pair<int, int>> cows;
vector<pair<int,int>> infected;
int n; cin >> n;
for (int i = 0; i < n; ++i) {
int loc, num; cin >> loc >> num;
cows.push_back({ loc, num });
if (num)
infected.push_back({ loc, num });
}
sort(all(cows));
sort(all(infected));
if (infected.size() < 2) {
cout << infected.size() << endl;
return 0;
}
int radius = 1e6;
for (int i = 1; i < n; ++i) {
if (cows[i].second != cows[i - 1].second)
radius = min(radius, abs(cows[i].first - cows[i - 1].first) - 1);
}
vector<int> codes;
int c = 0;
for (int i = 0; i < infected.size(); ++i) {
codes.push_back(-1);
}
for (int i = 0; i < infected.size(); ++i) {
if (codes[i] == -1) {
codes[i] = c;
int k = i;
while ((k + 1) < infected.size() && (infected[k + 1].first - infected[k].first) <= radius) {
codes[k + 1] = c;
++k;
}
c++;
}
}
cout << c;
}
|
#include <iostream>
#include <string>
#include "opencv/highgui.h"
#include "opencv/cv.h"
#include <math.h>
#include <opencv2/core/core.hpp>
#include <opencv2/ml/ml.hpp>
#define IMAGE_SIZE 250 // normalized W and H sizes of training data
// Color classifier parameters
#define N 1
#define CH 10
#define CS 10
#define CV 10
#define NUMBER_OF_COLOR_TRAINING_SAMPLES 4000
#define NUMBER_OF_COLOR_TESTING_SAMPLES 1000
#define NUMBER_OF_COLOR_FEATURES N * N * CH * CS * CV
// Texture classifier parameters
#define NUMBER_OF_TEXELS 1000
#define DELTA 40.0
#define NUMBER_OF_TEXTURE_TRAINING_SAMPLES 4000
#define NUMBER_OF_TEXTURE_TESTING_SAMPLES 1000
#define NUMBER_OF_TEXTURE_FEATURES NUMBER_OF_TEXELS
//#define AUTO_TRAIN_SVM
#define PREDICT
#define TRAINING_DIRECTORY "C:\\Users\\Allan\\Pictures\\train\\"
#define TEST_DIRECTORY "C:\\Users\\Allan\\Pictures\\test\\"
//#define PREDICTION_DIRECTORY "C:\\Users\\Allan\\Pictures\\predict\\"
#define PREDICTION_DIRECTORY "C:\\Users\\Allan\\Pictures\\predict2\\"
#define NUMBER_OF_IMAGES_TO_PREDICT 10
using namespace cv; // Namespace do OpenCV.
using namespace std;
// for texture features extraction
vector<Mat> texels;
int totalExtracted = 0;
cv::Mat createOne(std::vector<cv::Mat> & images, int cols, int min_gap_size)
{
// let's first find out the maximum dimensions
int max_width = 0;
int max_height = 0;
for ( int i = 0; i < images.size(); i++) {
// check if type is correct
// you could actually remove that check and convert the image
// in question to a specific type
if ( i > 0 && images[i].type() != images[i-1].type() ) {
std::cerr << "WARNING:createOne failed, different types of images";
return cv::Mat();
}
max_height = std::max(max_height, images[i].rows);
max_width = std::max(max_width, images[i].cols);
}
// number of images in y direction
int rows = std::ceil((float) images.size() / cols);
// create our result-matrix
cv::Mat result = cv::Mat::zeros(rows*max_height + (rows-1)*min_gap_size,
cols*max_width + (cols-1)*min_gap_size, images[0].type());
size_t i = 0;
int current_height = 0;
int current_width = 0;
for ( int y = 0; y < rows; y++ ) {
for ( int x = 0; x < cols; x++ ) {
if ( i >= images.size() ) // shouldn't happen, but let's be safe
return result;
// get the ROI in our result-image
cv::Mat to(result,
cv::Range(current_height, current_height + images[i].rows),
cv::Range(current_width, current_width + images[i].cols));
// copy the current image to the ROI
images[i++].copyTo(to);
current_width += max_width + min_gap_size;
}
// next line - reset width and update height
current_width = 0;
current_height += max_height + min_gap_size;
}
return result;
}
Mat resizeImage (Mat& src, int w, int h) {
Mat dst;
Size size(w, h);//the dst image size,e.g.100x100
resize(src, dst, size);//resize image
return dst;
}
// accuracy
void evaluateSVM(cv::Mat& testData, cv::Mat& testClasses, char* filename) {
CvSVM svm;
svm.load(filename);
cv::Mat predicted(testClasses.rows, 1, CV_32F);
for (int i = 0; i < testData.rows; i++) {
const cv::Mat sample = testData.row(i);
predicted.at<float> (i, 0) = svm.predict(sample);
}
assert(predicted.rows == testData.rows);
int t = 0;
int f = 0;
int tp = 0;
int fn = 0;
int tn = 0;
int fp = 0;
for(int i = 0; i < testData.rows; i++) {
float p = predicted.at<float>(i,0);
float a = testClasses.at<float>(i,0);
if((p >= 0.0 && a >= 0.0) || (p <= 0.0 && a <= 0.0)) {
t++;
} else {
f++;
}
if (p == 1.0 && a == 1.0)
tp++;
else if (p == 1.0 && a == -1.0)
fp++;
else if (p == -1.0 && a == -1.0)
tn++;
else if (p == -1.0 && a == 1.0)
fn++;
}
float accuracy = (t * 1.0) / (t + f);
float positivePrecision = (tp * 1.0) / (tp + fp);
float positiveRecall = (tp * 1.0) / (tp + fn);
float negativePrecision = (tn * 1.0) / (tn + fn);
float negativeRecall = (tn * 1.0) / (tn + fp);
float positiveFMeasure = 2 * ((positivePrecision * positiveRecall)/(positivePrecision + positiveRecall));
float negativeFMeasure = 2 * ((negativePrecision * negativeRecall)/(negativePrecision + negativeRecall));
printf ("{SVM accuracy} %f\n", accuracy);
printf ("{SVM positive class precision} %f\n", positivePrecision);
printf ("{SVM positive class recall} %f\n", positiveRecall);
printf ("{SVM negative class precision} %f\n", negativePrecision);
printf ("{SVM negative class recall} %f\n", negativeRecall);
printf ("{SVM positive class F measure} %f\n", positiveFMeasure);
printf ("{SVM negative class F measure} %f\n", negativeFMeasure);
}
void trainSVM(Mat& trainingData, Mat& labels, char* filename, float C, float gamma) {
cout << "Start SVM training, press any key to continue " << endl;
system("pause");
CvSVMParams params = CvSVMParams(
CvSVM::C_SVC, // Type of SVM; using N classes here
CvSVM::RBF, // Kernel type
0.0, // Param (degree) for poly kernel only
gamma, // Param (gamma) for poly/rbf kernel only
0.0, // Param (coef0) for poly/sigmoid kernel only
C, // SVM optimization param C
0, // SVM optimization param nu (not used for N class SVM)
0, // SVM optimization param p (not used for N class SVM)
NULL, // class weights (or priors)
/*
* Optional weights, assigned to particular classes.
* They are multiplied by C and thus affect the misclassification
* penalty for different classes. The larger the weight, the larger
* the penalty on misclassification of data from the corresponding
* class.
*/
cvTermCriteria(CV_TERMCRIT_ITER + CV_TERMCRIT_EPS, 1000, 0.000001)); // Termination criteria for the learning algorithm
CvSVM* svm = new CvSVM;
//printf("Starting SVM training...\n");
#ifdef AUTO_TRAIN_SVM
printf("Finding optimal parameters to use...\n");
// Use auto-training parameter grid search (ignore params manually
// specified above)
svm->train_auto(trainingData, labels, Mat(), Mat(), params, 5);
params = svm->get_params();
printf("The optimal parameters are: degree = %f, gamma = %f, coef0 = %f, C = %f, nu = %f, p = %f\n",
params.degree, params.gamma, params.coef0, params.C, params.nu, params.p);
#else
printf("Using default parameters...\n");
// Use regular training with parameters manually specified above
svm->train(trainingData, labels, Mat(), Mat(), params);
#endif
printf("Training complete.\n");
printf("Number of support vectors in the SVM: %i\n",
svm->get_support_vector_count());
svm -> save(filename);
}
/* returns True if there is one or more pixels in the block in the specified intervals*/
float isThereOneOrMorePixels(Mat block, vector<int> hueInterval, vector<int> saturationInterval,
vector<int> valueInterval) {
int rows = block.rows;
int cols = block.cols;
if (block.isContinuous())
{
cols = rows * cols; // Loop over all pixels as 1D array.
rows = 1;
}
for (int i = 0; i < rows; i++)
{
Vec3b *ptr = block.ptr<Vec3b>(i);
for (int j = 0; j < cols; j++)
{
Vec3b hsvPixel = ptr[j];
int H = hsvPixel.val[0];
int S = hsvPixel.val[1];
int V = hsvPixel.val[2];
int minHueValue = hueInterval.at(0);
int maxHueValue = hueInterval.at(1);
int minSaturationValue = saturationInterval.at(0);
int maxSaturationValue = saturationInterval.at(1);
int minValueValue = valueInterval.at(0);
int maxValueValue = valueInterval.at(1);
if ((H >= minHueValue && H <= maxHueValue) &&
(S >= minSaturationValue && S <= maxSaturationValue) &&
(V >= minValueValue && V <= maxValueValue)) {
return 1.0;
}
}
}
return 0.0;
}
double round(double d)
{
return floor(d + 0.5);
}
vector<vector<int>> splitColorSpace (int size, int p) {
vector<int> chanelValues;
vector<vector<int>> chanelIntervals;
for (int i = 0; i < size; ++i) {
chanelValues.push_back(i);
}
int right = round((double)size/(double)p);
int left = size % p;
for(int i = 0; i < size; i+= right)
{
if(i < size - right)
{
vector<int> v;
vector<int> vRange;
//MAJOR CORRECTION
for(int j = i; j < (i+right); j++)
{
v.push_back(chanelValues[j]);
}
vRange.push_back(v.front());
vRange.push_back(v.back());
chanelIntervals.push_back(vRange);
// cout << v.size() << endl;
}
else
{
right = size - i;
vector<int> v;
vector<int> vRange;
//Major Correction
for(int k =i; k < size; k++)
{
v.push_back(chanelValues[k]);
}
vRange.push_back(v.front());
vRange.push_back(v.back());
chanelIntervals.push_back(vRange);
// cout << v.size() << endl;
}
}
return chanelIntervals;
}
float calculateMaxEuclideanDistance(Mat block, Mat texel) {
int rows = block.rows;
int cols = block.cols;
if (rows != texel.rows || cols != texel.cols) {
cout << "(" << rows << ", " << cols << ")" << endl;
cout << "Diferent dimension images" << endl;
return 0.0;
}
vector<float> euclideanDistances;
for (int i = 0; i < rows; i++)
{
Vec3b *ptr1 = block.ptr<Vec3b>(i);
Vec3b *ptr2 = texel.ptr<Vec3b>(i);
for (int j = 0; j < cols; j++)
{
Vec3b bgrPixel1 = ptr1[j];
int B1 = bgrPixel1.val[0];
int G1 = bgrPixel1.val[1];
int R1 = bgrPixel1.val[2];
Vec3b bgrPixel2 = ptr2[j];
int B2 = bgrPixel2.val[0];
int G2 = bgrPixel2.val[1];
int R2 = bgrPixel2.val[2];
float euclideanDistance = sqrt(pow((B1 - B2), 2.0) + pow((G1 - G2), 2.0) + pow((R1 - R2), 2.0));
euclideanDistances.push_back(euclideanDistance);
}
}
float maxEuclideanDistance = *max_element(euclideanDistances.begin(), euclideanDistances.end());
return maxEuclideanDistance;
}
vector<float> normalizeEuclideanDistances(vector<float> euclideanDistances) {
vector<float> normalizedEuclideanDistances;
float minEuclideanDistance = *min_element(euclideanDistances.begin(), euclideanDistances.end());
float maxEuclideanDistance = *max_element(euclideanDistances.begin(), euclideanDistances.end());
for (int i = 0; i < euclideanDistances.size(); ++i) {
float normalizedEuclideanDistance = (euclideanDistances[i] - minEuclideanDistance) / (maxEuclideanDistance - minEuclideanDistance);
normalizedEuclideanDistances.push_back(normalizedEuclideanDistance);
}
return normalizedEuclideanDistances;
}
float calculateAverageEuclideanDistance(Mat texel1, Mat texel2) {
int rows = texel1.rows;
int cols = texel1.cols;
if (rows != texel2.rows || cols != texel2.cols) {
cout << "(" << rows << ", " << cols << ")" << endl;
cout << "Diferent dimension images" << endl;
return 0.0;
}
float acumulatedEuclideanDistances = 0;
for (int i = 0; i < rows; i++)
{
Vec3b *ptr1 = texel1.ptr<Vec3b>(i);
Vec3b *ptr2 = texel2.ptr<Vec3b>(i);
for (int j = 0; j < cols; j++)
{
Vec3b bgrPixel1 = ptr1[j];
int B1 = bgrPixel1.val[0];
int G1 = bgrPixel1.val[1];
int R1 = bgrPixel1.val[2];
Vec3b bgrPixel2 = ptr2[j];
int B2 = bgrPixel2.val[0];
int G2 = bgrPixel2.val[1];
int R2 = bgrPixel2.val[2];
float euclideanDistance = sqrt(pow((B1 - B2), 2.0) + pow((G1 - G2), 2.0) + pow((R1 - R2), 2.0));
acumulatedEuclideanDistances += euclideanDistance;
}
}
float averageEuclideanDistance = acumulatedEuclideanDistances/25;
return averageEuclideanDistance;
}
bool isAverageEuclideanDistanceAboveTresholdForAll (Mat candidateTexel, float delta) {
for (int i = 0; i < texels.size(); ++i) {
Mat texel = texels[i];
float averageEuclideanDistance = calculateAverageEuclideanDistance(candidateTexel, texel);
if (averageEuclideanDistance < delta)
return false;
}
return true;
}
int texelsCount = 0;
void generateSetOfTexels(int texelsSetSize, float delta) {
cout << "Start texels set generation, press any key to continue " << endl;
system("pause");
while (true) {
stringstream ss1;
int cat = 0 + (rand() % (int)(9999 - 0 + 1));
ss1 << TRAINING_DIRECTORY << "cat." << cat << ".jpg";
Mat bgrCatImg = imread (ss1.str());
bgrCatImg = resizeImage(bgrCatImg, IMAGE_SIZE, IMAGE_SIZE);
int blockSize = IMAGE_SIZE / 50;
for (int r = 0; r < bgrCatImg.rows; r += blockSize) {
for (int c = 0; c < bgrCatImg.cols; c += blockSize)
{
Mat block = bgrCatImg(Range(r, min(r + blockSize, bgrCatImg.rows)),
Range(c, min(c + blockSize, bgrCatImg.cols)));
if (isAverageEuclideanDistanceAboveTresholdForAll (block, delta)) {
texels.push_back(block);
texelsCount++;
cout << texelsCount << endl;
if (texelsSetSize == texels.size()) return;
}
}
}
stringstream ss2;
int dog = 0 + (rand() % (int)(9999 - 0 + 1));
ss2 << TRAINING_DIRECTORY << "dog." << dog << ".jpg";
Mat bgrDogImg = imread (ss2.str());
bgrDogImg = resizeImage(bgrDogImg, IMAGE_SIZE, IMAGE_SIZE);
for (int r = 0; r < bgrDogImg.rows; r += blockSize) {
for (int c = 0; c < bgrDogImg.cols; c += blockSize)
{
Mat block = bgrDogImg(Range(r, min(r + blockSize, bgrDogImg.rows)),
Range(c, min(c + blockSize, bgrDogImg.cols)));
if (isAverageEuclideanDistanceAboveTresholdForAll (block, delta)) {
texels.push_back(block);
texelsCount++;
cout << texelsCount << endl;
if (texelsSetSize == texels.size()) return;
}
}
}
}
}
vector<float> extractTextureFeatures(Mat& img) {
int textureFeaturesCount = 0;
int blockSize = IMAGE_SIZE / 50;
vector<float> euclideanDistancesFeatures;
Mat centralRoi = img(Range(100, 150),
Range(100, 150));
//cout << "(" << centralRoi.rows << ", " << centralRoi.cols << ")" << endl;
//system("pause");
for (int i = 0; i < texels.size(); ++i) {
Mat texel = texels[i];
vector<float> maxEuclideanDistances;
for (int r = 0; r < centralRoi.rows; r += blockSize) {
for (int c = 0; c < centralRoi.cols; c += blockSize)
{
Mat block = centralRoi(Range(r, min(r + blockSize, centralRoi.rows)),
Range(c, min(c + blockSize, centralRoi.cols)));
// calculate the max euclidean distance between the pixels of block and each texel
float maxEuclideanDistance = calculateMaxEuclideanDistance(block, texel);
maxEuclideanDistances.push_back(maxEuclideanDistance);
}
}
float minEuclideanDistance = *min_element(maxEuclideanDistances.begin(), maxEuclideanDistances.end());
euclideanDistancesFeatures.push_back(minEuclideanDistance);
textureFeaturesCount++;
//cout << textureFeaturesCount << endl;
}
vector<float> normalizedMinEuclideanDistances = normalizeEuclideanDistances(euclideanDistancesFeatures);
return normalizedMinEuclideanDistances;
}
void loadTextureTrainingData(Mat& dataMat, Mat& labelsMat, int dogNumber, int catNumber) {
cout << "Start loading texture training data, press any key to continue " << endl;
system("pause");
vector<vector<float>> allFeatures;
for (int i = 0; i < catNumber; ++i) {
labelsMat.at<float>(i, 0) = -1.0;
stringstream ss;
ss << TRAINING_DIRECTORY << "cat." << i << ".jpg";
Mat bgrImg = imread (ss.str());
bgrImg = resizeImage(bgrImg, IMAGE_SIZE, IMAGE_SIZE);
vector<float> features = extractTextureFeatures(bgrImg);
totalExtracted++;
cout << totalExtracted << endl;
allFeatures.push_back(features);
}
for (int i = catNumber; i < catNumber + dogNumber; ++i) {
labelsMat.at<float>(i, 0) = 1.0;
}
for (int i = 0; i < dogNumber; ++i) {
stringstream ss;
ss << TRAINING_DIRECTORY << "dog." << i << ".jpg";
Mat bgrImg = imread (ss.str());
bgrImg = resizeImage(bgrImg, IMAGE_SIZE, IMAGE_SIZE);
vector<float> features = extractTextureFeatures(bgrImg);
totalExtracted++;
cout << totalExtracted << endl;
allFeatures.push_back(features);
}
dataMat = (allFeatures.size(), allFeatures[0].size(), CV_32F);
for(int i = 0; i < allFeatures.size(); ++i)
dataMat.row(i) = Mat(allFeatures[i]).t();
cout << "Finish loading texture training data, press any key to continue " << endl;
system("pause");
}
void loadTextureTestData(Mat& dataMat, Mat& labelsMat, int dogNumber, int catNumber) {
cout << "Start loading texture test data, press any key to continue " << endl;
system("pause");
vector<vector<float>> allFeatures;
for (int i = 0; i < catNumber; ++i) {
labelsMat.at<float>(i, 0) = -1.0;
}
for (int i = 10000; i < 10000 + catNumber; ++i) {
stringstream ss;
ss << TEST_DIRECTORY << "cat." << i << ".jpg";
Mat bgrImg = imread (ss.str());
bgrImg = resizeImage(bgrImg, IMAGE_SIZE, IMAGE_SIZE);
vector<float> features = extractTextureFeatures(bgrImg);
totalExtracted++;
cout << totalExtracted << endl;
allFeatures.push_back(features);
}
for (int i = catNumber; i < catNumber + dogNumber; ++i) {
labelsMat.at<float>(i, 0) = 1.0;
}
for (int i = 10000; i < 10000 + dogNumber; ++i) {
stringstream ss;
ss << TEST_DIRECTORY << "dog." << i << ".jpg";
Mat bgrImg = imread (ss.str());
bgrImg = resizeImage(bgrImg, IMAGE_SIZE, IMAGE_SIZE);
vector<float> features = extractTextureFeatures(bgrImg);
totalExtracted++;
cout << totalExtracted << endl;
allFeatures.push_back(features);
}
dataMat = (allFeatures.size(), allFeatures[0].size(), CV_32F);
for(int i = 0; i < allFeatures.size(); ++i)
dataMat.row(i) = Mat(allFeatures[i]).t();
cout << "Finish loading texture test data, press any key to continue " << endl;
system("pause");
}
vector<float> extractColorFeatures(Mat& img, int n, int ch, int cs, int cv) {
// First thing: extract color features.
// Color features are represented in the form of a boolean vector,
// to compute this boolean vector first we slice the image in N^2
// blocks, each one of equal widith and heigth which size = ImageSize / N.
// We then partitionate the HSV color space in Ch, Cs and Cv
// bands of equal width.
// So, each element of the boolean vector is computed as 1
// if for each slice block combination with each band of the
// partitioned color space there is at least one pixel in the block
// that falls right into the range of this partitioned color space band, 0 otherwise.
// The size of each feature vector is equal to N^2 * Ch * Cs * Cv
vector<float> features;
vector<vector<int>> hueIntervals = splitColorSpace(180, ch);
vector<vector<int>> saturationIntervals = splitColorSpace(256, cs);
vector<vector<int>> valueIntervals = splitColorSpace(256, cv);
int blockSize = IMAGE_SIZE / n;
for (int r = 0; r < img.rows; r += blockSize) {
for (int c = 0; c < img.cols; c += blockSize)
{
Mat block = img(Range(r, min(r + blockSize, img.rows)),
Range(c, min(c + blockSize, img.cols)));
for (int x = 0; x < hueIntervals.size(); ++x) {
for (int y = 0; y < saturationIntervals.size(); ++y) {
for (int z = 0; z < valueIntervals.size(); ++z) {
vector<int> hueInterval = hueIntervals.at(x);
vector<int> saturationInterval = saturationIntervals.at(y);
vector<int> valueInterval = valueIntervals.at(z);
float feature = isThereOneOrMorePixels(block, hueInterval, saturationInterval, valueInterval);
//cout << feature << endl;
features.push_back(feature);
}
}
}
}
}
return features;
}
void loadColorTrainingData(Mat& dataMat, Mat& labelsMat, int dogNumber, int catNumber) {
cout << "Start loading color training data, press any key to continue " << endl;
system("pause");
vector<vector<float>> allFeatures;
for (int i = 0; i < catNumber; ++i) {
labelsMat.at<float>(i, 0) = -1.0;
Mat hsvImg;
stringstream ss;
ss << TRAINING_DIRECTORY << "cat." << i << ".jpg";
Mat bgrImg = imread (ss.str());
bgrImg = resizeImage(bgrImg, IMAGE_SIZE, IMAGE_SIZE);
cvtColor(bgrImg, hsvImg, CV_BGR2HSV);
vector<float> features = extractColorFeatures(hsvImg, N, CH, CS, CV);
/*
vector<float> features1 = extractColorFeatures(hsvImg, 1, 10, 10, 10);
vector<float> features2 = extractColorFeatures(hsvImg, 3, 10, 8, 8);
vector<float> features3 = extractColorFeatures(hsvImg, 5, 10, 6, 6);
vector<float> features;
features.reserve( features1.size() + features2.size() + features3.size());
features.insert( features.end(), features1.begin(), features1.end());
features.insert( features.end(), features2.begin(), features2.end());
features.insert( features.end(), features3.begin(), features3.end());*/
totalExtracted++;
cout << totalExtracted << endl;
allFeatures.push_back(features);
}
for (int i = catNumber; i < catNumber + dogNumber; ++i) {
labelsMat.at<float>(i, 0) = 1.0;
}
for (int i = 0; i < dogNumber; ++i) {
Mat hsvImg;
stringstream ss;
ss << TRAINING_DIRECTORY << "dog." << i << ".jpg";
Mat bgrImg = imread (ss.str());
bgrImg = resizeImage(bgrImg, IMAGE_SIZE, IMAGE_SIZE);
cvtColor(bgrImg, hsvImg, CV_BGR2HSV);
vector<float> features = extractColorFeatures(hsvImg, N, CH, CS, CV);
/*
vector<float> features1 = extractColorFeatures(hsvImg, 1, 10, 10, 10);
vector<float> features2 = extractColorFeatures(hsvImg, 3, 10, 8, 8);
vector<float> features3 = extractColorFeatures(hsvImg, 5, 10, 6, 6);
vector<float> features;
features.reserve( features1.size() + features2.size() + features3.size());
features.insert( features.end(), features1.begin(), features1.end());
features.insert( features.end(), features2.begin(), features2.end());
features.insert( features.end(), features3.begin(), features3.end());*/
totalExtracted++;
cout << totalExtracted << endl;
allFeatures.push_back(features);
}
dataMat = (allFeatures.size(), allFeatures[0].size(), CV_32F);
for(int i = 0; i < allFeatures.size(); ++i)
dataMat.row(i) = Mat(allFeatures[i]).t();
cout << "Finish loading color training data, press any key to continue " << endl;
system("pause");
}
void loadColorTestData(Mat& dataMat, Mat& labelsMat, int dogNumber, int catNumber) {
cout << "Start loading color test data, press any key to continue " << endl;
system("pause");
vector<vector<float>> allFeatures;
for (int i = 0; i < catNumber; ++i) {
labelsMat.at<float>(i, 0) = -1.0;
}
for (int i = 10000; i < 10000 + catNumber; ++i) {
Mat hsvImg;
stringstream ss;
ss << TEST_DIRECTORY << "cat." << i << ".jpg";
Mat bgrImg = imread (ss.str());
bgrImg = resizeImage(bgrImg, IMAGE_SIZE, IMAGE_SIZE);
cvtColor(bgrImg, hsvImg, CV_BGR2HSV);
vector<float> features = extractColorFeatures(hsvImg, N, CH, CS, CV);
/*
vector<float> features1 = extractColorFeatures(hsvImg, 1, 10, 10, 10);
vector<float> features2 = extractColorFeatures(hsvImg, 3, 10, 8, 8);
vector<float> features3 = extractColorFeatures(hsvImg, 5, 10, 6, 6);
vector<float> features;
features.reserve( features1.size() + features2.size() + features3.size());
features.insert( features.end(), features1.begin(), features1.end());
features.insert( features.end(), features2.begin(), features2.end());
features.insert( features.end(), features3.begin(), features3.end());*/
totalExtracted++;
cout << totalExtracted << endl;
allFeatures.push_back(features);
}
for (int i = catNumber; i < catNumber + dogNumber; ++i) {
labelsMat.at<float>(i, 0) = 1.0;
}
for (int i = 10000; i < 10000 + dogNumber; ++i) {
Mat hsvImg;
stringstream ss;
ss << TEST_DIRECTORY << "dog." << i << ".jpg";
Mat bgrImg = imread (ss.str());
bgrImg = resizeImage(bgrImg, IMAGE_SIZE, IMAGE_SIZE);
cvtColor(bgrImg, hsvImg, CV_BGR2HSV);
vector<float> features = extractColorFeatures(hsvImg, N, CH, CS, CV);
/*
vector<float> features1 = extractColorFeatures(hsvImg, 1, 10, 10, 10);
vector<float> features2 = extractColorFeatures(hsvImg, 3, 10, 8, 8);
vector<float> features3 = extractColorFeatures(hsvImg, 5, 10, 6, 6);
vector<float> features;
features.reserve( features1.size() + features2.size() + features3.size());
features.insert( features.end(), features1.begin(), features1.end());
features.insert( features.end(), features2.begin(), features2.end());
features.insert( features.end(), features3.begin(), features3.end());*/
totalExtracted++;
cout << totalExtracted << endl;
allFeatures.push_back(features);
}
dataMat = (allFeatures.size(), allFeatures[0].size(), CV_32F);
for(int i = 0; i < allFeatures.size(); ++i)
dataMat.row(i) = Mat(allFeatures[i]).t();
cout << "Finish loading color test data, press any key to continue " << endl;
system("pause");
}
void predictCategory() {
CvSVM colorSVM;
colorSVM.load("colorSVM.xml");
CvSVM colorSVM2;
colorSVM2.load("modelosvm3.xml");
CvSVM textureSVM;
textureSVM.load("textureSVM.xml");
//generateSetOfTexels(NUMBER_OF_TEXELS, DELTA);
cv::FileStorage storage("texels.yml", cv::FileStorage::READ);
storage["texels"] >> texels;
storage.release();
cout << "(colorSVM1, colorSVM2, textureSVM)" << endl;
for (int i = 1; i < NUMBER_OF_IMAGES_TO_PREDICT + 1; ++i) {
stringstream ss;
ss << PREDICTION_DIRECTORY << "img." << i << ".jpg";
Mat bgrImg = imread (ss.str());
bgrImg = resizeImage(bgrImg, IMAGE_SIZE, IMAGE_SIZE);
//namedWindow( "Display window", WINDOW_AUTOSIZE );// Create a window for display.
//imshow( "Display window", bgrImg ); // Show our image inside it.
// waitKey(0);
Mat hsvImg;
cvtColor(bgrImg, hsvImg, CV_BGR2HSV);
vector<float> colorFeatures = extractColorFeatures(hsvImg, N, CH, CS, CV);
vector<float> colorFeatures2 = extractColorFeatures(hsvImg, 5, 10, 6, 6);
vector<float> textureFeatures = extractTextureFeatures(bgrImg);
Mat colorFeaturesMat(1, NUMBER_OF_COLOR_FEATURES, CV_32F);
Mat colorFeaturesMat2(1, 9000, CV_32F);
Mat textureFeaturesMat(1, NUMBER_OF_TEXTURE_FEATURES, CV_32F);
colorFeaturesMat.row(0) = Mat(colorFeatures).t();
colorFeaturesMat2.row(0) = Mat(colorFeatures2).t();
textureFeaturesMat.row(0) = Mat(textureFeatures).t();
float colorSVMPrediction = colorSVM.predict(colorFeaturesMat);
float colorSVMPrediction2 = colorSVM2.predict(colorFeaturesMat2);
float textureSVMPrediction = textureSVM.predict(textureFeaturesMat);
string colorSVMPredictionResult;
string colorSVMPredictionResult2;
string textureSVMPredictionResult;
if (colorSVMPrediction == -1.0)
colorSVMPredictionResult = "Cat";
else
colorSVMPredictionResult = "Dog";
if (colorSVMPrediction2 == -1.0)
colorSVMPredictionResult2 = "Cat";
else
colorSVMPredictionResult2 = "Dog";
if (textureSVMPrediction == -1.0)
textureSVMPredictionResult = "Cat";
else
textureSVMPredictionResult = "Dog";
cout << i << "-" << "(" << colorSVMPredictionResult << ", " << colorSVMPredictionResult2 << ", " << textureSVMPredictionResult << ")" << endl;
/*
float combinedPrediction = (1.0/3) * colorSVMPrediction + (2.0/3) * textureSVMPrediction;
if (combinedPrediction == -1.0) {
cout << "Cat" << endl;
//namedWindow( "Cat", WINDOW_AUTOSIZE );// Create a window for display.
//imshow( "Cat", bgrImg);
} else if (combinedPrediction == 1.0) {
cout << "Dog" << endl;
//namedWindow( "Dog", WINDOW_AUTOSIZE );// Create a window for display.
//imshow( "Dog", bgrImg);
}*/
//system("pause");
}
vector<Mat> imgs;
for (int i = 1; i < NUMBER_OF_IMAGES_TO_PREDICT + 1; ++i) {
stringstream ss;
ss << PREDICTION_DIRECTORY << "img." << i << ".jpg";
Mat bgrImg = imread (ss.str());
bgrImg = resizeImage(bgrImg, 150, 150);
imgs.push_back(bgrImg);
}
Mat allInOne = createOne(imgs, 4, 3);
namedWindow( "Display window", WINDOW_AUTOSIZE );// Create a window for display.
imshow( "Display window", allInOne ); // Show our image inside it.
waitKey(0);
}
int main () {
#ifdef PREDICT
predictCategory();
Mat colorTestData (2000, 9000, CV_32F);
Mat colorTestLabels (2000, 1, CV_32FC1);
cv::FileStorage storage3("testData.yml", cv::FileStorage::READ);
storage3["testData"] >> colorTestData;
storage3.release();
cv::FileStorage storage4("testLabels.yml", cv::FileStorage::READ);
storage4["testLabels"] >> colorTestLabels;
storage4.release();
cout << "Evaluating color SVM f(5, 10, 6, 6)" << endl;
system("pause");
evaluateSVM(colorTestData, colorTestLabels, "colorSVM2.xml");
#else
// SVM Color classifier
Mat colorTrainingData(NUMBER_OF_COLOR_TRAINING_SAMPLES, NUMBER_OF_COLOR_FEATURES, CV_32F);
Mat colorTrainingLabels(NUMBER_OF_COLOR_TRAINING_SAMPLES, 1, CV_32FC1);
Mat colorTestData (NUMBER_OF_COLOR_TESTING_SAMPLES, NUMBER_OF_COLOR_FEATURES, CV_32F);
Mat colorTestLabels (NUMBER_OF_COLOR_TESTING_SAMPLES, 1, CV_32FC1);
// SVM Texture classifier
Mat textureTrainingData(NUMBER_OF_TEXTURE_TRAINING_SAMPLES, NUMBER_OF_TEXTURE_FEATURES, CV_32F);
Mat textureTrainingLabels(NUMBER_OF_TEXTURE_TRAINING_SAMPLES, 1, CV_32FC1);
Mat textureTestData (NUMBER_OF_TEXTURE_TESTING_SAMPLES, NUMBER_OF_TEXTURE_FEATURES, CV_32F);
Mat textureTestLabels (NUMBER_OF_TEXTURE_TESTING_SAMPLES, 1, CV_32FC1);
loadColorTrainingData(colorTrainingData, colorTrainingLabels, NUMBER_OF_COLOR_TRAINING_SAMPLES/2, NUMBER_OF_COLOR_TRAINING_SAMPLES/2);
loadColorTestData(colorTestData, colorTestLabels, NUMBER_OF_COLOR_TESTING_SAMPLES/2, NUMBER_OF_COLOR_TESTING_SAMPLES/2);
// number of texels, delta
generateSetOfTexels(NUMBER_OF_TEXELS, DELTA);
cv::FileStorage storage("texels.yml", cv::FileStorage::WRITE);
storage << "texels" << texels;
storage.release();
loadTextureTrainingData(textureTrainingData, textureTrainingLabels, NUMBER_OF_TEXTURE_TRAINING_SAMPLES/2, NUMBER_OF_TEXTURE_TRAINING_SAMPLES/2);
loadTextureTestData(textureTestData, textureTestLabels, NUMBER_OF_TEXTURE_TESTING_SAMPLES/2, NUMBER_OF_TEXTURE_TESTING_SAMPLES/2);
trainSVM(colorTrainingData, colorTrainingLabels, "colorSVM.xml", 10, pow(10.0, -3));
evaluateSVM(colorTestData, colorTestLabels, "colorSVM.xml");
trainSVM(textureTrainingData, textureTrainingLabels, "textureSVM.xml", 10, pow(10.0, -1));
evaluateSVM(textureTestData, textureTestLabels, "textureSVM.xml");
#endif
waitKey();
return 0;
}
|
#ifndef _INTERFAZ_H
#define _INTERFAZ_H
#include <cgicc/CgiDefs.h>
#include <cgicc/Cgicc.h>
#include <cgicc/HTTPHTMLHeader.h>
#include <cgicc/HTMLClasses.h>
#include "dominio.h"
class cInterfaz {
public:
//Constructor
cInterfaz();
//Obtiene una variable de un formulario
int obtenerVariable(std::string, std::string &, cDominio &);
//Redirige el navegador a una pagina
void redirigir(const std::string &);
//Redirige el navegador a una pagina del dominio
void redirigirDom(const std::string &, const cDominio &);
//Reporta un error de un comando
void reportarErrorComando(const std::string &, const std::string &, const cDominio &);
//Reporta un error fatal al navegador
void reportarErrorFatal();
//Reporta un mensaje al navegador
void reportarMensaje(const std::string &);
//Reporta un ok de un comando
void reportarOkComando(const std::string &, const std::string &, const cDominio &);
void reportarOkComandoBackup(const std::string &, const std::string &, const std::string &,
const std::string &, const cDominio &);
//Verifica que el cgi haya sido llamada por una pagina en especial
int verificarPagina(const std::string &);
private:
cgicc::Cgicc cgi; //Objeto referente al cgi
};
#endif // _INTERFAZ_H
|
#include "image_processing_form.h"
using namespace System;
using namespace System::Windows::Forms;
[STAThread]
int main(array<String^> ^args) {
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
BasicImageProcessing::ImageProccessingForm image_processing_form;
Application::Run(%image_processing_form);
return 0;
}
|
# include <iostream>
# include <vector>
typedef unsigned long long ul;
using namespace std;
ul max(ul a, ul b) { return a > b ? a : b; }
ul min(ul a, ul b) { return a < b ? a : b; }
class Node {
public:
ul maxPrice, minPrice, diff;
Node(ul value = 0) { maxPrice = minPrice = diff = value; }
Node operator - (const Node &rhs) {
Node node;
node.maxPrice = max(maxPrice, rhs.maxPrice);
node.minPrice = min(minPrice, rhs.minPrice);
node.diff = node.maxPrice - node.minPrice;
return node;
}
void operator = (const Node &rhs) {
maxPrice = rhs.maxPrice;
minPrice = rhs.minPrice;
diff = rhs.diff;
}
void operator -= (const Node &rhs) { *this = *this - rhs; }
};
class SegTree {
public:
vector<Node> tree;
int n;
SegTree(const ul *arr, const ul n) : n(n) {
tree = vector<Node>(n * 2, Node());
for (ul i = 0; i < n; ++i) tree[i + n] = Node(arr[i]);
for (ul i = n - 1; i > 0; --i) tree[i] = tree[i<<1] - tree[i<<1|1];
}
int query(ul l, ul r) {
Node node;
node.minPrice = 1e6;
for (l += n, r += n; l <= r; l >>= 1, r >>= 1) {
if (l & 1) node -= tree[l++];
if (!(r & 1)) node -= tree[r--];
}
return node.diff;
}
void modify(ul p, ul value) {
for (tree[p += n] = Node(value); p > 1; p >>= 1) tree[p>>1] = tree[p] - tree[p^1];
}
};
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
ul N, P[ul(1e6)], Q, op, l, r;
while(cin >> N) {
for (ul i = 0; i < N; ++i) cin >> P[i];
auto tree = SegTree(P, N);
cin >> Q;
while (Q--) {
cin >> op >> l >> r;
if (op == 1) tree.modify(--l, r);
if (op == 2) cout << tree.query(--l, --r) << '\n';
}
}
return 0;
}
|
// github.com/andy489
// https://www.hackerrank.com/contests/practice-9-sda/challenges/kruskalmstrsub
#include <iostream>
#include <algorithm>
using namespace std;
int p[3030];
pair<int, pair<int, int> > edge[5000000];
int find(int j) { return p[j] == j ? j : p[j] = find(p[j]); }
int main() {
int n, m, a, b, w, i(1);
cin >> n >> m;
for (; i <= n; ++i)
p[i] = i;
for (i = 0; i < m; ++i) {
cin >> a >> b >> w;
edge[i] = make_pair(w, make_pair(a, b));
}
sort(edge, edge + m);
int ans(0);
for (i = 0; i < m; ++i) {
int x = find(edge[i].second.first);
int y = find(edge[i].second.second);
if (x != y) {
p[x] = y;
ans += edge[i].first;
}
}
return cout << ans, 0;
}
|
// Section12.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "Prac7.h"
#include<iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
auto vec = func();
readFunc(vec);
printFunc(vec);
getchar();
getchar();
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
//Bottom up DP
std::vector<int> ways;
std::vector<int> coins;
std::vector<bool> filled;
int numberOfWaysBU(int n)
{
ways.at(0) = 1; //Number of ways of making 0 is 1, By not using any coins.
for(auto c : coins){
for(int i = c; i<ways.size(); ++i){
ways.at(i) += ways.at(i-c);
}
}
filled.at(n) = true;
return ways.at(n);
}
//Top Down DP
int numberOfWaysTD(int n)
{
if(n==0)
return 1;
//if(n<0)
// return 0;
if(filled.at(n)==true)
return ways.at(n);
for(auto c : coins){
if((n-c)>=0)
ways.at(n) += numberOfWaysTD(n-c);
else
continue;
}
filled.at(n) = true;
return ways.at(n);
}
int main()
{
int num;
cin>>num;
int denom;
cin>>denom;
ways.resize(num+1);
filled.resize(num+1);
fill(filled.begin(), filled.end(), false);
coins.resize(denom);
std::vector<int>::iterator itw;
std::vector<int>::iterator itc;
for(itc = coins.begin(); itc!=coins.end(); ++itc){
cin>>*itc;
}
//cout<<numberOfWaysTD(num);
//Debug:
numberOfWaysTD(num);
for(auto i: ways)
cout<<i<<' ';
return 0;
}
|
//
// ExifShellExt - Exif data shell extension
// Copyright (C) 2008 Michael Fink
//
/// \file ExifReader.hpp Exif data reader for JFIF files
//
#pragma once
// includes
#include "JFIFReader.hpp"
#include <vector>
class ExifReader: public JFIFReader
{
public:
ExifReader(Stream::IStream& streamIn)
:JFIFReader(streamIn)
{
}
const std::vector<BYTE>& GetData() const throw() { return m_vecExifData; }
private:
virtual void OnBlock(BYTE bStartByte, BYTE bMarker, WORD wLength) override
{
bStartByte;
if (bMarker == APP1)
{
m_vecExifData.resize(wLength-2);
DWORD dwLengthRead = 0;
m_streamIn.Read(&m_vecExifData[0], wLength-2, dwLengthRead);
// couldn't read all? clear exif data; isn't complete
if (dwLengthRead != static_cast<DWORD>(wLength-2))
m_vecExifData.clear();
}
}
private:
std::vector<BYTE> m_vecExifData;
};
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctime>
#include <math.h>
#define SIZE 120 //种群规模
#define MAXGEN 50 //最大迭代次数
#define P_CORSS 0.75 //交叉概率
#define P_MUTATION 0.05 //变异概率
#define LIN 3
#define RAN 10 //LIN,RAN是染色体数组的行和列
#define ORAN 8 // ORAN = pow(2.0,LIN) 可供输入的数据组数
#define NL 2
#define NR 3 //NCV门库数组(基因)
#define L NL-1
#define R NR-1 //L,R 是为了生成随机数而设定的
FILE *galog;
typedef struct node //种群结构体
{
char *gen[LIN][RAN]; //种群中的个体(以基因表示)
int output[LIN][RAN]; //输出数组
int mid[LIN]; //中间计算结果
//int input[LIN],
// med[NR];
//o_input[NR];
double fitness, //最大适应度(程序运行到目前为止函数的最大值)
fitsum; //当前种群适应度总和
}node;
node chr [SIZE], //当前种群数组
next [SIZE], //下一代种群数组
max, //适应度最大的个体
min; //适应度最小的个体
//生成并打印输入数组
void c_input()
{
fprintf(galog,"\n需要输入的数据\n");
//生成
int input[LIN][ORAN];
for (int i=0;i<ORAN;i++)
{
int temp = i;
for(int j=0;j<LIN;j++)
{
input[j][i] = temp%2;
temp=temp>>1;
}
}
//打印
for (int i=0;i<LIN;i++)
{
for(int j=0;j<ORAN;j++)
{
if (j%ORAN == 0)
fprintf(galog,"\n");
fprintf(galog,"%2d",input[i][j]);
}
}
fprintf(galog,"\n*******************************\n");
}
//产生0~1之间的随机小数
double randd()
{
return (double)rand()/RAND_MAX;
}
//产生0~k之间的随机整数
int randi(int k)
{
//+0.5是为了保证能取到上边界上的数
return (int)(randd()*k+0.5);
}
//打印
void print()
{
for(int i=0;i<SIZE;i++)
{
//控制换行
//if (i%10 == 0)
// fprintf(galog,"\n");
for(int k = 0; k < LIN;k++)
{if (k%LIN == 0)
fprintf(galog,"\n*******************************\n");
for(int j = 0; j < RAN;j++)
{
if (j%RAN == 0)
fprintf(galog,"\n");
fprintf(galog,"%4s",chr[i].gen[k][j]);
}
}
}
}
//生成初代染色体并编码
void init()
{
char *NCV[NL][NR] = {{"CTR","CTR","CTR"},{"CV+","CV","CN"}};
fprintf(galog,"初代种群\n");
int ran,lin;
for(int i=0;i<SIZE;i++)
{
for(int j = 0; j < RAN;j++)
{
lin = randi(L);//随机取NCV的行
ran = randi(R);//随机取NCV的列
int k = 0;
chr[i].gen[k][j] = NCV[lin][ran];
k = randi(L)+1;
chr[i].gen[k][j] = NCV[lin^1][ran];
if (k == 1)
chr[i].gen[k+1][j] = "ZE";
else
chr[i].gen[k-1][j] = "ZE";
}
//cal_fitness();
}
print();
}
int main()
{
srand((unsigned)time(NULL));
galog = fopen("galog.txt","w+");
c_input();
init();
//GA();
system("pause");
return 0;
}
|
std::vector<sf::IntRect> creerVect(int start, int ligne, int longueur, int hauteur, int ecart, int nbSprite){
int i;
std::vector<sf::IntRect> v;
for(i=0; i<nbSprite; ++i){
v.push_back(sf::IntRect(start+i*ecart, ligne, longueur, hauteur));
}
return v;
}
class Animation{
public:
Animation(std::vector<std::vector<sf::IntRect>> sens) :
actuelle_(0), sens_(sens) {
for(size_t i = 0; i<sens.size(); ++i){
actuSens_.push_back(0);
}
}
void setActuelle(int const& quelleSens){
actuSens_[actuelle_] = 0;
actuelle_ = quelleSens;
}
sf::IntRect& actuelSprite(){
return sens_[actuelle_][actuSens_[actuelle_]];
}
sf::IntRect& nextSprite(){
size_t& save = actuSens_[actuelle_];
if(++save == sens_[actuelle_].size()) save = 0;
return sens_[actuelle_][save];
}
int getActuelle(){
return actuelle_;
}
private:
//Rien, Bas, Haut, Cote, action
int actuelle_; //Position en cours
std::vector<size_t> actuSens_; //Numero du sprite
std::vector<std::vector<sf::IntRect>> sens_; //array contenant les vecteur de rectangle
};
|
/*
* Copyright (C) 2007-2015 Frank Mertens.
*
* Use of this source is governed by a BSD-style license that can be
* found in the LICENSE file.
*
*/
#ifndef FLUXMAKE_JOBSERVER_H
#define FLUXMAKE_JOBSERVER_H
#include <flux/Thread>
#include <flux/Channel>
#include "Job.h"
namespace fluxmake {
class JobServer: public Thread
{
public:
inline static Ref<JobServer> start(JobChannel *requestChannel, JobChannel *replyChannel) {
return new JobServer(requestChannel, replyChannel);
}
private:
JobServer(JobChannel *requestChannel, JobChannel *replyChannel);
~JobServer();
virtual void run();
Ref<JobChannel> requestChannel_;
Ref<JobChannel> replyChannel_;
};
} // namespace fluxmake
#endif // FLUXMAKE_JOBSERVER_H
|
#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
int a=5;
int b= 2;
while(a>b){
cout<<"Ingrese el valor de a: ";
cin>>a;
}
cout<<endl;
cout<<"Saliste del ciclo!";
return 0;
}
|
#ifndef NodeMessageStruct_h
#define NodeMessageStruct_h
#include <RFM69.h>
#include <NodeStruct.h>
class NodeMessageStruct: public RFM69 {
public:
NodeMessageStruct(uint8_t slaveSelectPin=RF69_SPI_CS, uint8_t interruptPin=RF69_IRQ_PIN, bool isRFM69HW=false, uint8_t interruptNum=RF69_IRQ_NUM) :
RFM69(slaveSelectPin, interruptPin, isRFM69HW, interruptNum) {
}
void SendMessage(uint8_t gateway, const __FlashStringHelper* message, uint8_t type, bool verbose, bool echo);
void SendMessage(uint8_t gateway, const __FlashStringHelper* message, uint8_t value, uint8_t type, bool verbose, bool echo);
void ClearBuffer (char *buffer);
void SerialStreamCapture(char *buffer, uint8_t &bufferLength);
void SerialSendwRadioEcho (Message myMessage, uint8_t gatewayID, bool verbose, bool echo);
};
extern NodeMessageStruct message;
#endif
|
//===--- Existential.h - Existential related Analyses. -------*- C++ //-*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_SILOPTIMIZER_UTILS_EXISTENTIAL_H
#define SWIFT_SILOPTIMIZER_UTILS_EXISTENTIAL_H
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SILOptimizer/Analysis/ClassHierarchyAnalysis.h"
#include "swift/SILOptimizer/Analysis/ProtocolConformanceAnalysis.h"
namespace swift {
/// Find InitExistential from global_addr and copy_addr.
SILValue findInitExistentialFromGlobalAddrAndCopyAddr(GlobalAddrInst *GAI,
CopyAddrInst *CAI);
/// Find InitExistential from global_addr and an apply argument.
SILValue findInitExistentialFromGlobalAddrAndApply(GlobalAddrInst *GAI,
ApplySite Apply, int ArgIdx);
/// Returns the address of an object with which the stack location \p ASI is
/// initialized. This is either a init_existential_addr or the destination of a
/// copy_addr. Returns a null value if the address does not dominate the
/// alloc_stack user \p ASIUser.
/// If the value is copied from another stack location, \p isCopied is set to
/// true.
SILValue getAddressOfStackInit(AllocStackInst *ASI, SILInstruction *ASIUser,
bool &isCopied);
/// Find the init_existential, which could be used to determine a concrete
/// type of the value used by \p openedUse.
/// If the value is copied from another stack location, \p isCopied is set to
/// true.
///
/// FIXME: replace all uses of this with ConcreteExistentialInfo.
SILInstruction *findInitExistential(Operand &openedUse,
ArchetypeType *&OpenedArchetype,
SILValue &OpenedArchetypeDef,
bool &isCopied);
/// Record conformance and concrete type info derived from an init_existential
/// value that is reopened before it's use. This is useful for finding the
/// concrete type of an apply's self argument. For example, an important pattern
/// for a class existential is:
///
/// %e = init_existential_ref %c : $C : $C, $P & Q
/// %o = open_existential_ref %e : $P & Q to $@opened("PQ") P & Q
/// %r = apply %f<@opened("PQ") P & Q>(%o)
/// : $@convention(method) <τ_0_0 where τ_0_0 : P, τ_0_0 : Q>
/// (@guaranteed τ_0_0) -> @owned τ_0_0
struct ConcreteExistentialInfo {
// The opened type passed as self. `$@opened("PQ")` above.
// This is also the replacement type of the method's Self type.
ArchetypeType *OpenedArchetype = nullptr;
// The definition of the OpenedArchetype.
SILValue OpenedArchetypeDef;
// True if the openedValue is copied from another stack location
bool isCopied;
// The init_existential instruction that produces the opened existential.
SILInstruction *InitExistential = nullptr;
// The existential type of the self argument before it is opened,
// produced by an init_existential.
CanType ExistentialType;
// The concrete type of self from the init_existential. `$C` above.
CanType ConcreteType;
// When ConcreteType is itself an opened existential, record the type
// definition. May be nullptr for a valid AppliedConcreteType.
SingleValueInstruction *ConcreteTypeDef = nullptr;
// The Substitution map derived from the init_existential.
// This maps a single generic parameter to the replacement ConcreteType
// and includes the full list of existential conformances.
// signature: <P & Q>, replacement: $C : conformances: [$P, $Q]
SubstitutionMap ExistentialSubs;
// The value of concrete type used to initialize the existential. `%c` above.
SILValue ConcreteValue;
// Search for a recognized pattern in which the given value is an opened
// existential that was previously initialized to a concrete type.
// Constructs a valid ConcreteExistentialInfo object if successfull.
ConcreteExistentialInfo(Operand &openedUse);
// This constructor initializes a ConcreteExistentialInfo based on already
// known ConcreteType and ProtocolDecl pair. It determines the
// OpenedArchetypeDef for the ArgOperand that will be used by unchecked_cast
// instructions to cast OpenedArchetypeDef to ConcreteType.
ConcreteExistentialInfo(Operand &ArgOperand, CanType ConcreteType,
ProtocolDecl *Protocol);
ConcreteExistentialInfo(ConcreteExistentialInfo &) = delete;
/// For scenerios where ConcreteExistentialInfo is created using a known
/// ConcreteType and ProtocolDecl, both of InitExistential
/// and ConcreteValue can be null. So there is no need for explicit check for
/// not null for them instead we assert on (!InitExistential ||
/// ConcreteValue).
bool isValid() const {
assert(!InitExistential || ConcreteValue);
return OpenedArchetype && OpenedArchetypeDef && ConcreteType &&
!ExistentialSubs.empty();
}
// Do a conformance lookup on ConcreteType with the given requirement, P. If P
// is satisfiable based on the existential's conformance, return the new
// conformance on P. Otherwise return None.
Optional<ProtocolConformanceRef>
lookupExistentialConformance(ProtocolDecl *P) const {
CanType selfTy = P->getSelfInterfaceType()->getCanonicalType();
return ExistentialSubs.lookupConformance(selfTy, P);
}
};
} // end namespace swift
#endif
|
// ===============================================
// @file pool.cpp
// @author kmurphy
// @brief Specification of memory pool collection class
// ===============================================
#include <iostream>
#include "Pool.h"
// this file is empty as class implementation was so small that
// i just put it in its header file.
|
#include <stdio.h>
#include <string.h>
int m,q;
char word[500][11];
double B[500];
double T[500][500];
double M[500][500];
int n;
char test[20][100][11];
int w2i(char *input)
{
for(int i=0;i<m;i++)
if(strcmp(input,word[i]) == 0)
return i;
return -1;
}
char *i2w(int input)
{
return word[input];
}
void func(int pos, int prev)
{
int input = w2i(word[pos]);
double max = 0;
int max_i = -1;
double ret = 0;
if(pos == 0)
{
for(int i=0;i<m;i++)
{
ret = B[i] * M[i][input];
if(ret > max)
{
max = ret;
max_i = i;
}
}
printf("%s ",i2w(max_i));
func(pos+1,max_i);
return;
}
if(pos == n)
return;
for(int i=0;i<m;i++)
{
ret = M[i][input] * T[prev][i];
if(ret > max)
{
max = ret;
max_i = i;
}
}
printf("%s ",i2w(max_i));
func(pos+1,max_i);
return;
}
int main()
{
scanf("%d %d",&m,&q);
for(int i=0;i<m;i++)
scanf("%s",word[i]);
for(int i=0;i<m;i++)
scanf("%lf",&B[i]);
for(int i=0;i<m;i++)
for(int j=0;j<m;j++)
scanf("%lf",&T[i][j]);
for(int i=0;i<m;i++)
for(int j=0;j<m;j++)
scanf("%lf",&M[i][j]);
for(int cnt=0;cnt<q;cnt++)
{
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%s",test[cnt][i]);
func(0,-1);
printf("\n");
}
}
|
#include "BangerFall.h"
#include "../../../../../GameDefines/GameDefine.h"
#include "../BangerStand/BangerStand.h"
BangerFall::BangerFall(Banger * e) :BangerState(e)
{
translateY = 25.0f;
e->setVy(0);
}
void BangerFall::onCollision(::SidesCollision side)
{
if (side == SidesCollision::Bottom)
banger->setState(new BangerStand(banger));
}
void BangerFall::update(float dt)
{
banger->addVy(translateY);
if (banger->getVy() > Define::ENEMY_MAX_JUMP_VELOCITY)
banger->setVy(Define::ENEMY_MAX_JUMP_VELOCITY);
}
::StateBanger BangerFall::getState()
{
return ::StateBanger::Fall;
}
|
#include <cstdio>
#include <iostream>
using namespace std;
typedef long long ll;
const int maxn = 35;
int n, d[maxn][maxn];
// #define DEBUG
int main() {
#ifdef DEBUG
freopen("d:\\.in", "r", stdin);
freopen("d:\\.out", "w", stdout);
#endif
while (cin >> n && n) {
for (int u = 1; u <= n; ++u)
for (int v = u + 1; v <= n; ++v) {
cin >> d[u][v];
d[v][u] = d[u][v];
}
int ans = d[1][2];
for (int i = 3; i <= n; ++i) {
int add = 0x3fffffff;
for (int u = 2; u < i; ++u)
add = min(add, (d[1][i] + d[u][i] - d[1][u]) >> 1);
ans += add;
}
cout << ans << endl;
}
return 0;
}
|
// dllmain.cpp : Defines the entry point for the DLL application.
// Including SDKDDKVer.h defines the highest available Windows platform.
// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and
// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h.
#include <SDKDDKVer.h>
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "TurretAimingComponent.h"
#include "BarrelMeshComponent.h"
#include "Projectile.h"
#include "TurretMeshComponent.h"
#include "Kismet/GameplayStatics.h"
// Sets default values for this component's properties
UTurretAimingComponent::UTurretAimingComponent()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
LastFireTime = FPlatformTime::Seconds();
// ...
}
void UTurretAimingComponent::Initialize(UBarrelMeshComponent* BarrelToSet, UTurretMeshComponent* TurretToSet)
{
Barrel = BarrelToSet;
Turret = TurretToSet;
}
// Called when the game starts
void UTurretAimingComponent::BeginPlay()
{
Super::BeginPlay();
// ...
}
// Called every frame
void UTurretAimingComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
bool isReloading = (FPlatformTime::Seconds() - LastFireTime) < ReloadTimeInSeconds;
if (RoundsLeft <= 0)
{
FiringState = EFiringState::OutOfAmmo;
}
else if (isReloading)
{
FiringState = EFiringState::Reloading;
}
else if (IsBarrelMoving())
{
FiringState = EFiringState::Aiming;
}
else
{
FiringState = EFiringState::Locked;
}
}
void UTurretAimingComponent::AimAt(const FVector& Location)
{
if (!ensure(Barrel && Turret)) return;
FVector OutLaunchVelocity;
FVector StartLocation = Barrel->GetSocketLocation(FName("Opening"));
// Calculate out launch velocity
bool bHaveAimSolution = UGameplayStatics::SuggestProjectileVelocity(
this,
OutLaunchVelocity,
StartLocation,
Location,
LaunchSpeed,
false,
0.0f,
0.0f,
ESuggestProjVelocityTraceOption::DoNotTrace
);
if (bHaveAimSolution)
{
AimDirection = OutLaunchVelocity.GetSafeNormal();
MoveTurretAndBarrel(AimDirection, true);
}
}
void UTurretAimingComponent::MoveTurretAndBarrel(const FVector &AimDirection, bool DoElevate /*= true*/)
{
if (!ensure(Barrel && Turret)) return;
FRotator BarrelRotator = Barrel->GetForwardVector().Rotation();
FRotator AimDirectionRotator = AimDirection.Rotation();
FRotator DeltaRotation = AimDirectionRotator - BarrelRotator;
if (DoElevate) Barrel->Elevate(DeltaRotation.Pitch);
// always yaw the shortest way...
if (FMath::Abs(DeltaRotation.Yaw) < 180)
{
Turret->Swivel(DeltaRotation.Yaw);
}
else
{
Turret->Swivel(-DeltaRotation.Yaw);
}
}
bool UTurretAimingComponent::IsBarrelMoving()
{
if (!ensure(Barrel)) { return false; }
FVector BarrelForward = Barrel->GetForwardVector();
return !BarrelForward.Equals(AimDirection, 0.01); // vectors are equal
}
void UTurretAimingComponent::Fire()
{
if (FiringState == EFiringState::Locked || FiringState == EFiringState::Aiming) // TODO Other States
{
if (!ensure(Barrel)) return;
if (!ensure(ProjectileBlueprint)) return;
//UE_LOG(LogTemp, Warning, TEXT("Tank %s Fired 3"), *GetName());
LastFireTime = FPlatformTime::Seconds();
AProjectile* Projectile = GetWorld()->SpawnActor<AProjectile>(
ProjectileBlueprint,
Barrel->GetSocketLocation(FName("Opening")),
Barrel->GetSocketRotation(FName("Opening")));
if (ensure(Projectile))
{
Projectile->LaunchProjectile(LaunchSpeed);
RoundsLeft = FMath::Max(0, RoundsLeft -1);
}
}
}
EFiringState UTurretAimingComponent::GetFiringState() const
{
return FiringState;
}
int32 UTurretAimingComponent::GetRoundsLeft() const
{
return RoundsLeft;
}
|
/*************************************************************************
> File Name: examples/testLongLifeFactory.cpp
> Author: Jason
> Mail: jie-email@jie-trancender.org
> Created Time: 2017年03月27日 星期一 22时23分28秒
************************************************************************/
#include "../stock-factory.hpp"
#include <cassert>
using namespace std;
void testLongLifeFactory()
{
shared_ptr<StockFactory> factory(new StockFactory);
{
shared_ptr<Stock> stock = factory->get("NYSE:IBM");
shared_ptr<Stock> stock2 = factory->get("NYSE:IBM");
assert(stock == stock2);
}
}
void testShortLifeFactory()
{
shared_ptr<Stock> stock;
{
shared_ptr<StockFactory> factory(new StockFactory);
stock = factory->get("NYSE:IBM");
shared_ptr<Stock> stock2 = factory->get("NYSE:IBM");
assert(stock == stock2);
}
}
int main(int argc, char* argv[])
{
testLongLifeFactory();
testShortLifeFactory();
}
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
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 University of Oxford 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.
*/
#ifndef _TESTXMLMESHWRITERS_HPP_
#define _TESTXMLMESHWRITERS_HPP_
#include <cxxtest/TestSuite.h>
#include "TrianglesMeshReader.hpp"
#include "TrianglesMeshWriter.hpp"
#include "OutputFileHandler.hpp"
#include "TetrahedralMesh.hpp"
#include "VtkMeshWriter.hpp"
#include "XdmfMeshWriter.hpp"
#include "DistributedTetrahedralMesh.hpp"
#include "MixedDimensionMesh.hpp"
#include "QuadraticMesh.hpp"
#include "PetscSetupAndFinalize.hpp"
#include "FileComparison.hpp"
#include <iostream>
#ifdef CHASTE_VTK
#define _BACKWARD_BACKWARD_WARNING_H 1 //Cut out the strstream deprecated warning for now (gcc4.3)
#include <vtkVersion.h>
#endif
class TestXmlMeshWriters : public CxxTest::TestSuite
{
public:
void TestBasicVtkMeshWriter()
{
#ifdef CHASTE_VTK
// Requires "sudo aptitude install libvtk5-dev" or similar
TrianglesMeshReader<3,3> reader("mesh/test/data/cube_2mm_12_elements");
TetrahedralMesh<3,3> mesh;
mesh.ConstructFromMeshReader(reader);
VtkMeshWriter<3,3> writer("TestVtkMeshWriter", "cube_2mm_12_elements");
TS_ASSERT_THROWS_NOTHING(writer.WriteFilesUsingMesh(mesh));
//1.6K uncompressed, 1.3K compressed
std::string results_dir = OutputFileHandler::GetChasteTestOutputDirectory() + "TestVtkMeshWriter/";
{
//Check that the reader can see it
VtkMeshReader<3,3> vtk_reader(results_dir+"cube_2mm_12_elements.vtu");
TS_ASSERT_EQUALS(vtk_reader.GetNumNodes(), mesh.GetNumNodes());
TS_ASSERT_EQUALS(vtk_reader.GetNumElements(), mesh.GetNumElements());
TS_ASSERT_EQUALS(vtk_reader.GetNumFaces(), mesh.GetNumBoundaryElements());
// Check we have the right number of nodes & elements when we re-construct it
TetrahedralMesh<3,3> vtk_mesh;
vtk_mesh.ConstructFromMeshReader(vtk_reader);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), vtk_mesh.GetNumNodes());
TS_ASSERT_EQUALS(mesh.GetNumElements(), vtk_mesh.GetNumElements());
TS_ASSERT_EQUALS(mesh.GetNumBoundaryElements(), vtk_mesh.GetNumBoundaryElements());
}
#else
std::cout << "This test was not run, as VTK is not enabled." << std::endl;
std::cout << "If required please install and alter your hostconfig settings to switch on chaste support." << std::endl;
#endif //CHASTE_VTK
}
void TestSequentialMeshCannotWriteParallelFiles()
{
#ifdef CHASTE_VTK
// Requires "sudo aptitude install libvtk5-dev" or similar
TrianglesMeshReader<3,3> reader("mesh/test/data/cube_2mm_12_elements");
TetrahedralMesh<3,3> mesh;
mesh.ConstructFromMeshReader(reader);
VtkMeshWriter<3,3> writer("TestVtkMeshWriter", "cube_2mm_12_elements");
TS_ASSERT_THROWS_THIS( writer.SetParallelFiles(mesh),
"Cannot write parallel files using a sequential mesh");
#else
std::cout << "This test was not run, as VTK is not enabled." << std::endl;
std::cout << "If required please install and alter your hostconfig settings to switch on chaste support." << std::endl;
#endif //CHASTE_VTK
}
void TestParallelVtkMeshWriter()
{
#ifdef CHASTE_VTK
// Requires "sudo aptitude install libvtk5-dev" or similar
TrianglesMeshReader<3,3> reader("mesh/test/data/cube_2mm_12_elements");
DistributedTetrahedralMesh<3,3> mesh(DistributedTetrahedralMeshPartitionType::DUMB);
mesh.ConstructFromMeshReader(reader);
VtkMeshWriter<3,3> writer("TestVtkMeshWriter", "cube_2mm_12_elements_with_data");
writer.SetParallelFiles(mesh);
// Add distance from origin into the node "point" data
std::vector<double> distance;
for (DistributedTetrahedralMesh<3,3>::NodeIterator node_iter = mesh.GetNodeIteratorBegin();
node_iter != mesh.GetNodeIteratorEnd();
++node_iter)
{
distance.push_back(norm_2(node_iter->rGetLocation()));
}
writer.AddPointData("Distance from origin", distance);
// Add location (vector) to "point" data
std::vector< c_vector<double, 3> > location;
for (DistributedTetrahedralMesh<3,3>::NodeIterator node_iter = mesh.GetNodeIteratorBegin();
node_iter != mesh.GetNodeIteratorEnd();
++node_iter)
{
location.push_back(node_iter->rGetLocation());
}
writer.AddPointData("Location", location);
// Add element quality into the element "cell" data
std::vector<double> quality;
for (DistributedTetrahedralMesh<3,3>::ElementIterator ele_iter = mesh.GetElementIteratorBegin();
ele_iter != mesh.GetElementIteratorEnd();
++ele_iter)
{
quality.push_back(ele_iter->CalculateQuality());
}
writer.AddCellData("Quality", quality);
// Add fibre type to "cell" data
std::vector< c_vector<double, 3> > centroid;
for (DistributedTetrahedralMesh<3,3>::ElementIterator ele_iter = mesh.GetElementIteratorBegin();
ele_iter != mesh.GetElementIteratorEnd();
++ele_iter)
{
centroid.push_back(ele_iter->CalculateCentroid());
}
writer.AddCellData("Centroid", centroid);
writer.WriteFilesUsingMesh(mesh);
PetscTools::Barrier("Wait for files to be written");
std::stringstream filepath;
filepath << OutputFileHandler::GetChasteTestOutputDirectory() << "TestVtkMeshWriter/cube_2mm_12_elements_with_data";
// Add suffix to VTK vtu file
if (PetscTools::IsSequential())
{
filepath << ".vtu";
}
else
{
/*
* Check that the pvtu file exists. Note that checking its content is hard
* because the number of processes (.vtu file references) will vary.
*/
FileFinder vtk_file(filepath.str() + ".pvtu", RelativeTo::Absolute);
TS_ASSERT(vtk_file.Exists());
// Add suffix to VTK vtu file
filepath << "_" << PetscTools::GetMyRank() << ".vtu";
}
{
// Check that the reader can see it
VtkMeshReader<3,3> vtk_reader(filepath.str());
TS_ASSERT_EQUALS(vtk_reader.GetNumNodes(), mesh.GetNumLocalNodes() + mesh.GetNumHaloNodes());
TS_ASSERT_EQUALS(vtk_reader.GetNumElements(), mesh.GetNumLocalElements());
// Check that it has the correct data
std::vector<double> distance_read;
vtk_reader.GetPointData("Distance from origin", distance_read);
TS_ASSERT_EQUALS(distance.size(), mesh.GetNumLocalNodes() );
TS_ASSERT_EQUALS(distance_read.size(), mesh.GetNumLocalNodes() + mesh.GetNumHaloNodes());
for (unsigned i=0; i<distance.size(); i++)
{
TS_ASSERT_EQUALS(distance[i], distance_read[i]);
}
std::vector<c_vector<double,3> > location_read;
vtk_reader.GetPointData("Location", location_read);
TS_ASSERT_EQUALS(location.size(), mesh.GetNumLocalNodes() );
TS_ASSERT_EQUALS(location_read.size(), mesh.GetNumLocalNodes() + mesh.GetNumHaloNodes());
for (unsigned i=0; i<location.size(); i++)
{
for (unsigned j=0; j<3; j++)
{
TS_ASSERT_EQUALS(location[i][j], location_read[i][j]);
}
}
std::vector<double> quality_read;
vtk_reader.GetCellData("Quality", quality_read);
TS_ASSERT_EQUALS(quality.size(), mesh.GetNumLocalElements() );
TS_ASSERT_EQUALS(quality_read.size(), mesh.GetNumLocalElements());
for (unsigned i=0; i<quality_read.size(); i++)
{
TS_ASSERT_EQUALS(quality[i], quality_read[i]);
}
std::vector<c_vector<double,3> > centroid_read;
vtk_reader.GetCellData("Centroid", centroid_read);
TS_ASSERT_EQUALS(centroid.size(), mesh.GetNumLocalElements() );
TS_ASSERT_EQUALS(centroid_read.size(), mesh.GetNumLocalElements());
for (unsigned i=0; i<centroid_read.size(); i++)
{
for (unsigned j=0; j<3; j++)
{
TS_ASSERT_EQUALS(centroid[i][j], centroid_read[i][j]);
}
}
}
#else
std::cout << "This test was not run, as VTK is not enabled." << std::endl;
std::cout << "If required please install and alter your hostconfig settings to switch on chaste support." << std::endl;
#endif //CHASTE_VTK
}
void TestParallelVtkMeshWriter2d()
{
#ifdef CHASTE_VTK
// Requires "sudo aptitude install libvtk5-dev" or similar
TrianglesMeshReader<2,2> reader("mesh/test/data/2D_0_to_1mm_200_elements");
DistributedTetrahedralMesh<2,2> mesh;
mesh.ConstructFromMeshReader(reader);
VtkMeshWriter<2,2> writer("TestVtkMeshWriter", "2D_0_to_1mm_200_elements_parallel_data", false);
writer.SetParallelFiles(mesh);
// Add distance from origin into the node "point" data
std::vector<double> rank;
// Real rank for the owned nodes
for (unsigned i=0; i<mesh.GetNumLocalNodes(); i++)
{
rank.push_back(PetscTools::GetMyRank());
}
writer.AddPointData("Process rank", rank);
writer.WriteFilesUsingMesh(mesh);
PetscTools::Barrier("Wait for files to be written");
std::stringstream filepath;
filepath << OutputFileHandler::GetChasteTestOutputDirectory() << "TestVtkMeshWriter/2D_0_to_1mm_200_elements_parallel_data";
// Add suffix to VTK vtu file.
if (PetscTools::IsSequential())
{
filepath << ".vtu";
}
else
{
/*
* Check that the pvtu file exists. Note that checking its content is hard
* because the number of processes (.vtu file references) will vary.
*/
FileFinder vtk_file(filepath.str() + ".pvtu", RelativeTo::Absolute);
TS_ASSERT(vtk_file.Exists());
// Add suffix to VTK vtu file
filepath << "_" << PetscTools::GetMyRank() << ".vtu";
}
{
// Check that the reader can see it
VtkMeshReader<2,2> vtk_reader(filepath.str());
TS_ASSERT_EQUALS(vtk_reader.GetNumNodes(), mesh.GetNumLocalNodes() + mesh.GetNumHaloNodes());
TS_ASSERT_EQUALS(vtk_reader.GetNumElements(), mesh.GetNumLocalElements());
// Check that it has the correct data
std::vector<double> rank_read;
vtk_reader.GetPointData("Process rank", rank_read);
TS_ASSERT_EQUALS(rank.size(), mesh.GetNumLocalNodes() );
TS_ASSERT_EQUALS(rank_read.size(), mesh.GetNumLocalNodes() + mesh.GetNumHaloNodes());
for (unsigned i=0; i<rank.size(); i++)
{
TS_ASSERT_EQUALS(rank[i], rank_read[i]);
TS_ASSERT_EQUALS(rank_read[i], PetscTools::GetMyRank());
}
}
#else
std::cout << "This test was not run, as VTK is not enabled." << std::endl;
std::cout << "If required please install and alter your hostconfig settings to switch on chaste support." << std::endl;
#endif //CHASTE_VTK
}
void TestVtkMeshWriter2D()
{
#ifdef CHASTE_VTK
// Requires "sudo aptitude install libvtk5-dev" or similar
TrianglesMeshReader<2,2> reader("mesh/test/data/2D_0_to_1mm_200_elements");
TetrahedralMesh<2,2> mesh;
mesh.ConstructFromMeshReader(reader);
VtkMeshWriter<2,2> writer("TestVtkMeshWriter", "2D_0_to_1mm_200_elements", false);
// Add distance from origin into the node "point" data
std::vector<double> distance;
for (unsigned i=0; i<mesh.GetNumNodes(); i++)
{
distance.push_back(norm_2(mesh.GetNode(i)->rGetLocation()));
}
writer.AddPointData("Distance from origin", distance);
// Add fibre type to "point" data
std::vector< c_vector<double, 2> > location;
for (unsigned i=0; i<mesh.GetNumNodes(); i++)
{
location.push_back(mesh.GetNode(i)->rGetLocation());
}
writer.AddPointData("Location", location);
// Add element quality into the element "cell" data
std::vector<double> quality;
for (unsigned i=0; i<mesh.GetNumElements(); i++)
{
quality.push_back(mesh.GetElement(i)->CalculateQuality());
}
writer.AddCellData("Quality", quality);
// Add fibre type to "cell" data
std::vector< c_vector<double, 2> > centroid;
for (unsigned i=0; i<mesh.GetNumElements(); i++)
{
centroid.push_back(mesh.GetElement(i)->CalculateCentroid());
}
writer.AddCellData("Centroid", centroid);
// Add Jacobian tensor cell data, covering both the symmetric and non-symmetric tensor methods
std::vector< c_matrix<double, 2, 2> > jacobian;
std::vector< c_vector<double, 3> > squared_jacobian;
for (unsigned i=0; i<mesh.GetNumElements(); i++)
{
c_matrix<double, 2, 2> element_jacobian;
double element_jacobian_determinant;
mesh.GetElement(i)->CalculateJacobian(element_jacobian, element_jacobian_determinant);
jacobian.push_back(element_jacobian);
c_matrix<double, 2, 2> squared_element_jacobian;
squared_element_jacobian = prod(element_jacobian, element_jacobian);
c_vector<double, 3> tri_squared_element_jacobian;
//We store [T00 T01 T02 T11 T12 T22]
tri_squared_element_jacobian(0) = squared_element_jacobian(0, 0);
tri_squared_element_jacobian(1) = squared_element_jacobian(0, 1);
tri_squared_element_jacobian(2) = squared_element_jacobian(1, 1);
squared_jacobian.push_back(tri_squared_element_jacobian);
}
writer.AddTensorCellData("Jacobian", jacobian);
writer.AddTensorCellData("SquaredJacobian", squared_jacobian);
//Add tensor point data, we use the outer product of the node's location
std::vector< c_matrix<double, 2, 2> > location_outer_product;
for (unsigned i=0; i<mesh.GetNumNodes(); i++)
{
c_matrix<double, 2, 2> element_location_outer_product;
element_location_outer_product = outer_prod(trans(mesh.GetNode(i)->rGetLocation()), mesh.GetNode(i)->rGetLocation());
location_outer_product.push_back(element_location_outer_product);
}
writer.AddTensorPointData("LocationProduct", location_outer_product);
writer.WriteFilesUsingMesh(mesh);
//13K uncompressed, 3.7K compressed
{
// Check that the reader can see it
VtkMeshReader<2,2> vtk_reader(OutputFileHandler::GetChasteTestOutputDirectory() + "TestVtkMeshWriter/2D_0_to_1mm_200_elements.vtu");
TS_ASSERT_EQUALS(vtk_reader.GetNumNodes(), mesh.GetNumNodes());
TS_ASSERT_EQUALS(vtk_reader.GetNumElements(), mesh.GetNumElements());
// Check that it has the correct data
std::vector<double> distance_read;
vtk_reader.GetPointData("Distance from origin", distance_read);
for (unsigned i=0; i<distance_read.size(); i++)
{
TS_ASSERT_EQUALS(distance[i], distance_read[i]);
}
std::vector<c_vector<double,2> > location_read;
vtk_reader.GetPointData("Location", location_read);
for (unsigned i=0; i<location_read.size(); i++)
{
for (unsigned j=0; j<2; j++)
{
TS_ASSERT_EQUALS(location[i][j], location_read[i][j]);
}
}
std::vector<double> quality_read;
vtk_reader.GetCellData("Quality", quality_read);
for (unsigned i=0; i<quality_read.size(); i++)
{
TS_ASSERT_EQUALS(quality[i], quality_read[i]);
}
std::vector<c_vector<double,2> > centroid_read;
vtk_reader.GetCellData("Centroid", centroid_read);
for (unsigned i=0; i<centroid_read.size(); i++)
{
for (unsigned j=0; j<2; j++)
{
TS_ASSERT_EQUALS(centroid[i][j], centroid_read[i][j]);
}
}
///\todo #2254 Implement reading of tensor data & test.
}
#else
std::cout << "This test was not run, as VTK is not enabled." << std::endl;
std::cout << "If required please install and alter your hostconfig settings to switch on chaste support." << std::endl;
#endif //CHASTE_VTK
}
void TestParallelVtkMeshWriter1d()
{
#ifdef CHASTE_VTK
// Requires "sudo aptitude install libvtk5-dev" or similar
TrianglesMeshReader<1,1> reader("mesh/test/data/1D_0_to_1_10_elements");
DistributedTetrahedralMesh<1,1> mesh;
mesh.ConstructFromMeshReader(reader);
VtkMeshWriter<1,1> writer("TestVtkMeshWriter", "1D_0_to_1_10_elements_parallel_data", false);
writer.SetParallelFiles(mesh);
// Add distance from origin into the node "point" data
std::vector<double> rank;
// Real rank for the owned nodes
for (unsigned i=0; i<mesh.GetNumLocalNodes(); i++)
{
rank.push_back(PetscTools::GetMyRank());
}
writer.AddPointData("Process rank", rank);
writer.WriteFilesUsingMesh(mesh);
PetscTools::Barrier("Wait for files to be written");
std::stringstream filepath;
filepath << OutputFileHandler::GetChasteTestOutputDirectory() << "TestVtkMeshWriter/1D_0_to_1_10_elements_parallel_data";
// Add suffix to VTK vtu file.
if (PetscTools::IsSequential())
{
filepath << ".vtu";
}
else
{
/*
* Check that the pvtu file exists. Note that checking its content is hard
* because the number of processes (.vtu file references) will vary.
*/
FileFinder vtk_file(filepath.str() + ".pvtu", RelativeTo::Absolute);
TS_ASSERT(vtk_file.Exists());
// Add suffix to VTK vtu file
filepath << "_" << PetscTools::GetMyRank() << ".vtu";
}
{
// Check that the reader can see it
VtkMeshReader<1,1> vtk_reader(filepath.str());
TS_ASSERT_EQUALS(vtk_reader.GetNumNodes(), mesh.GetNumLocalNodes() + mesh.GetNumHaloNodes());
TS_ASSERT_EQUALS(vtk_reader.GetNumElements(), mesh.GetNumLocalElements());
// Check that it has the correct data
std::vector<double> rank_read;
vtk_reader.GetPointData("Process rank", rank_read);
TS_ASSERT_EQUALS(rank.size(), mesh.GetNumLocalNodes() );
TS_ASSERT_EQUALS(rank_read.size(), mesh.GetNumLocalNodes() + mesh.GetNumHaloNodes());
for (unsigned i=0; i<rank.size(); i++)
{
TS_ASSERT_EQUALS(rank[i], rank_read[i]);
TS_ASSERT_EQUALS(rank_read[i], PetscTools::GetMyRank());
}
}
#else
std::cout << "This test was not run, as VTK is not enabled." << std::endl;
std::cout << "If required please install and alter your hostconfig settings to switch on chaste support." << std::endl;
#endif //CHASTE_VTK
}
void TestVtkMeshWriter1D()
{
#ifdef CHASTE_VTK
// Requires "sudo aptitude install libvtk5-dev" or similar
TrianglesMeshReader<1,1> reader("mesh/test/data/1D_0_to_1_10_elements");
DistributedTetrahedralMesh<1,1> mesh;
mesh.ConstructFromMeshReader(reader);
VtkMeshWriter<1,1> writer("TestVtkMeshWriter", "1D_0_to_1_10_elements", false);
writer.WriteFilesUsingMesh(mesh);
if (PetscTools::AmMaster())
{
// Check that the reader can see it
VtkMeshReader<1,1> vtk_reader(OutputFileHandler::GetChasteTestOutputDirectory() + "TestVtkMeshWriter/1D_0_to_1_10_elements.vtu");
TS_ASSERT_EQUALS(vtk_reader.GetNumNodes(), mesh.GetNumNodes());
TS_ASSERT_EQUALS(vtk_reader.GetNumElements(), mesh.GetNumElements());
//Construct a mesh
TetrahedralMesh<1,1> read_mesh;
read_mesh.ConstructFromMeshReader(vtk_reader);
TS_ASSERT_DELTA(read_mesh.GetNode(5)->rGetLocation()[0], 0.5, 1e-8);
}
#else
std::cout << "This test was not run, as VTK is not enabled." << std::endl;
std::cout << "If required please install and alter your hostconfig settings to switch on chaste support." << std::endl;
#endif //CHASTE_VTK
}
void TestVtkMeshWriterWithData()
{
#ifdef CHASTE_VTK
// Requires "sudo aptitude install libvtk5-dev" or similar
TrianglesMeshReader<3,3> reader("heart/test/data/UCSD_heart_decimated_173nodes");
TetrahedralMesh<3,3> mesh;
mesh.ConstructFromMeshReader(reader);
VtkMeshWriter<3,3> writer("TestVtkMeshWriter", "heart_decimation", false);
// Add element quality into the element "cell" data
std::vector<double> quality;
for (unsigned i=0; i<mesh.GetNumElements(); i++)
{
quality.push_back(mesh.GetElement(i)->CalculateQuality());
}
writer.AddCellData("Quality", quality);
// Add fibre type to "cell" data
std::vector< c_vector<double, 3> > centroid;
for (unsigned i=0; i<mesh.GetNumElements(); i++)
{
centroid.push_back(mesh.GetElement(i)->CalculateCentroid());
}
writer.AddCellData("Centroid", centroid);
// Add distance from origin into the node "point" data
std::vector<double> distance;
for (unsigned i=0; i<mesh.GetNumNodes(); i++)
{
distance.push_back(norm_2(mesh.GetNode(i)->rGetLocation()));
}
writer.AddPointData("Distance from origin", distance);
// Add fibre type to "point" data
std::vector< c_vector<double, 3> > location;
for (unsigned i=0; i<mesh.GetNumNodes(); i++)
{
location.push_back(mesh.GetNode(i)->rGetLocation());
}
writer.AddPointData("Location", location);
// Add Jacobian tensor cell data, covering both the symmetric and non-symmetric tensor methods
std::vector< c_matrix<double, 3, 3> > jacobian;
std::vector< c_vector<double, 6> > squared_jacobian;
for (unsigned i=0; i<mesh.GetNumElements(); i++)
{
c_matrix<double, 3, 3> element_jacobian;
double element_jacobian_determinant;
mesh.GetElement(i)->CalculateJacobian(element_jacobian, element_jacobian_determinant);
jacobian.push_back(element_jacobian);
c_matrix<double, 3, 3> squared_element_jacobian = prod(element_jacobian, element_jacobian);
c_vector<double, 6> tri_squared_element_jacobian;
//We store [T00 T01 T02 T11 T12 T22]
tri_squared_element_jacobian(0) = squared_element_jacobian(0, 0);
tri_squared_element_jacobian(1) = squared_element_jacobian(0, 1);
tri_squared_element_jacobian(2) = squared_element_jacobian(0, 2);
tri_squared_element_jacobian(3) = squared_element_jacobian(1, 1);
tri_squared_element_jacobian(4) = squared_element_jacobian(1, 2);
tri_squared_element_jacobian(5) = squared_element_jacobian(2, 2);
squared_jacobian.push_back(tri_squared_element_jacobian);
}
writer.AddTensorCellData("Jacobian", jacobian);
writer.AddTensorCellData("SquaredJacobian", squared_jacobian);
//Add tensor point data, we use the outer product of the node's location
std::vector< c_matrix<double, 3, 3> > location_outer_product;
for (unsigned i=0; i<mesh.GetNumNodes(); i++)
{
c_matrix<double, 3, 3> element_location_outer_product;
element_location_outer_product = outer_prod(trans(mesh.GetNode(i)->rGetLocation()), mesh.GetNode(i)->rGetLocation());
location_outer_product.push_back(element_location_outer_product);
}
writer.AddTensorPointData("LocationProduct", location_outer_product);
writer.WriteFilesUsingMesh(mesh);
//32K uncompressed, 19K compressed
{
// Check that the reader can see it
VtkMeshReader<3,3> vtk_reader(OutputFileHandler::GetChasteTestOutputDirectory() + "TestVtkMeshWriter/heart_decimation.vtu");
TS_ASSERT_EQUALS(vtk_reader.GetNumNodes(), mesh.GetNumNodes());
TS_ASSERT_EQUALS(vtk_reader.GetNumElements(), mesh.GetNumElements());
// Check that it has the correct data
std::vector<double> distance_read;
vtk_reader.GetPointData("Distance from origin", distance_read);
for (unsigned i=0; i<distance_read.size(); i++)
{
TS_ASSERT_EQUALS(distance[i], distance_read[i]);
}
std::vector<double> quality_read;
vtk_reader.GetCellData("Quality", quality_read);
for (unsigned i=0; i<quality_read.size(); i++)
{
TS_ASSERT_EQUALS(quality[i], quality_read[i]);
}
std::vector<c_vector<double,3> > centroid_read;
vtk_reader.GetCellData("Centroid", centroid_read);
TS_ASSERT_EQUALS(centroid_read.size(),centroid.size());
///\todo #1731 - need to read the tensors too.
}
#else
std::cout << "This test was not run, as VTK is not enabled." << std::endl;
std::cout << "If required please install and alter your hostconfig settings to switch on chaste support." << std::endl;
#endif //CHASTE_VTK
}
void TestVtkMeshWriterForCables()
{
#ifdef CHASTE_VTK
// Requires "sudo aptitude install libvtk5-dev" or similar
std::string mesh_base("mesh/test/data/mixed_dimension_meshes/cylinder");
TrianglesMeshReader<3,3> reader(mesh_base);
MixedDimensionMesh<3,3> mesh(DistributedTetrahedralMeshPartitionType::DUMB);
mesh.ConstructFromMeshReader(reader);
VtkMeshWriter<3,3> writer("TestVtkMeshWriter", "mixed_mesh_3d", false);
writer.SetParallelFiles(mesh);
// Add element quality into the element "cell" data
std::vector<double> quality;
for (DistributedTetrahedralMesh<3,3>::ElementIterator ele_iter = mesh.GetElementIteratorBegin();
ele_iter != mesh.GetElementIteratorEnd();
++ele_iter)
{
quality.push_back(ele_iter->CalculateQuality());
}
writer.AddCellData("Quality", quality);
// Add fibre type to "cell" data
std::vector< c_vector<double, 3> > centroid;
for (DistributedTetrahedralMesh<3,3>::ElementIterator ele_iter = mesh.GetElementIteratorBegin();
ele_iter != mesh.GetElementIteratorEnd();
++ele_iter)
{
centroid.push_back(ele_iter->CalculateCentroid());
}
writer.AddCellData("Centroid", centroid);
writer.WriteFilesUsingMesh(mesh);
///\todo #2052 We can't yet test if the cables are written correctly, because we don't have the reader part.
#else
std::cout << "This test was not run, as VTK is not enabled." << std::endl;
std::cout << "If required please install and alter your hostconfig settings to switch on chaste support." << std::endl;
#endif //CHASTE_VTK
}
void TestVtkMeshWriterForQuadraticMesh2D()
{
#ifdef CHASTE_VTK
// Requires "sudo aptitude install libvtk5-dev" or similar
TrianglesMeshReader<2,2> reader("mesh/test/data/2D_0_to_1mm_200_elements");
QuadraticMesh<2> mesh;
mesh.ConstructFromLinearMeshReader(reader);
VtkMeshWriter<2,2> writer("TestVtkMeshWriter", "2D_0_to_1mm_200_elements_quadratic", false);
// Add distance from origin into the node "point" data
std::vector<double> distance;
for (unsigned i=0; i<mesh.GetNumNodes(); i++)
{
distance.push_back(norm_2(mesh.GetNode(i)->rGetLocation()));
}
writer.AddPointData("Distance from origin", distance);
// Add fibre type to "point" data
std::vector< c_vector<double, 2> > location;
for (unsigned i=0; i<mesh.GetNumNodes(); i++)
{
location.push_back(mesh.GetNode(i)->rGetLocation());
}
writer.AddPointData("Location", location);
// Add element quality into the element "cell" data
std::vector<double> quality;
for (unsigned i=0; i<mesh.GetNumElements(); i++)
{
quality.push_back(mesh.GetElement(i)->CalculateQuality());
}
writer.AddCellData("Quality", quality);
// Add fibre type to "cell" data
std::vector< c_vector<double, 2> > centroid;
for (unsigned i=0; i<mesh.GetNumElements(); i++)
{
centroid.push_back(mesh.GetElement(i)->CalculateCentroid());
}
writer.AddCellData("Centroid", centroid);
writer.WriteFilesUsingMesh(mesh);
{
// Check that the reader can see it
VtkMeshReader<2,2> vtk_reader(OutputFileHandler::GetChasteTestOutputDirectory() + "TestVtkMeshWriter/2D_0_to_1mm_200_elements_quadratic.vtu");
TS_ASSERT_EQUALS(vtk_reader.GetNumNodes(), mesh.GetNumNodes());
TS_ASSERT_EQUALS(vtk_reader.GetNumElements(), mesh.GetNumElements());
// Check that it has the correct data
std::vector<double> distance_read;
vtk_reader.GetPointData("Distance from origin", distance_read);
for (unsigned i=0; i<distance_read.size(); i++)
{
TS_ASSERT_EQUALS(distance[i], distance_read[i]);
}
std::vector<c_vector<double,2> > location_read;
vtk_reader.GetPointData("Location", location_read);
for (unsigned i=0; i<location_read.size(); i++)
{
for (unsigned j=0; j<2; j++)
{
TS_ASSERT_EQUALS(location[i][j], location_read[i][j]);
}
}
std::vector<double> quality_read;
vtk_reader.GetCellData("Quality", quality_read);
for (unsigned i=0; i<quality_read.size(); i++)
{
TS_ASSERT_EQUALS(quality[i], quality_read[i]);
}
std::vector<c_vector<double,2> > centroid_read;
vtk_reader.GetCellData("Centroid", centroid_read);
for (unsigned i=0; i<centroid_read.size(); i++)
{
for (unsigned j=0; j<2; j++)
{
TS_ASSERT_EQUALS(centroid[i][j], centroid_read[i][j]);
}
}
}
#else
std::cout << "This test was not run, as VTK is not enabled." << std::endl;
std::cout << "If required please install and alter your hostconfig settings to switch on chaste support." << std::endl;
#endif //CHASTE_VTK
}
void TestBasicQuadraticVtkMeshWriter()
{
#ifdef CHASTE_VTK
// Requires "sudo aptitude install libvtk5-dev" or similar
TrianglesMeshReader<3,3> reader("mesh/test/data/cube_2mm_12_elements");
QuadraticMesh<3> mesh;
mesh.ConstructFromLinearMeshReader(reader);
VtkMeshWriter<3,3> writer("TestVtkMeshWriter", "cube_2mm_12_elements_quadratic", false);
TS_ASSERT_THROWS_NOTHING(writer.WriteFilesUsingMesh(mesh));
//1.6K uncompressed, 1.3K compressed
std::string results_dir = OutputFileHandler::GetChasteTestOutputDirectory() + "TestVtkMeshWriter/";
{
//Check that the reader can see it
VtkMeshReader<3,3> vtk_reader(results_dir+"cube_2mm_12_elements_quadratic.vtu");
TS_ASSERT_EQUALS(vtk_reader.GetNumNodes(), mesh.GetNumNodes());
TS_ASSERT_EQUALS(vtk_reader.GetNumElements(), mesh.GetNumElements());
///\todo: The reader can open a quadratic vtu file, but not construct a QuadraticMesh
//further tests of the written output should be made once this is supported.
}
#else
std::cout << "This test was not run, as VTK is not enabled." << std::endl;
std::cout << "If required please install and alter your hostconfig settings to switch on chaste VTK support." << std::endl;
#endif //CHASTE_VTK
}
//Test that the vtk mesh writer can output a 1D mesh embedded in 3D space
void TestVtkMeshWriter1Din3D()
{
#ifdef CHASTE_VTK
TrianglesMeshReader<1,3> reader("mesh/test/data/branched_1d_in_3d_mesh");
TetrahedralMesh<1,3> mesh;
mesh.ConstructFromMeshReader(reader);
VtkMeshWriter<1,3> writer("TestVtkMeshWriter", "branched_1d_in_3d_mesh", false);
TS_ASSERT_THROWS_NOTHING(writer.WriteFilesUsingMesh(mesh));
{
// Check that the reader can see it
VtkMeshReader<1,3> vtk_reader(OutputFileHandler::GetChasteTestOutputDirectory() + "TestVtkMeshWriter/branched_1d_in_3d_mesh.vtu");
TS_ASSERT_EQUALS(vtk_reader.GetNumNodes(), mesh.GetNumNodes());
TS_ASSERT_EQUALS(vtk_reader.GetNumElements(), mesh.GetNumElements());
//There should be 3 terminals (boundary nodes/elements)
TS_ASSERT_EQUALS(vtk_reader.GetNumEdges(), reader.GetNumEdges());
TS_ASSERT_EQUALS(vtk_reader.GetNumEdges(), mesh.GetNumBoundaryElements());
}
#else
std::cout << "This test was not run, as VTK is not enabled." << std::endl;
std::cout << "If required please install and alter your hostconfig settings to switch on chaste VTK support." << std::endl;
#endif //CHASTE_VTK
}
//Test that the vtk mesh writer can output a 2D mesh embedded in 3D space
void TestVtkMeshWriterWithSurfaceMesh()
{
#ifdef CHASTE_VTK
VtkMeshReader<2,3> mesh_reader("mesh/test/data/cylinder.vtu");
TetrahedralMesh<2,3> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
VtkMeshWriter<2,3> writer("TestVtkMeshWriter", "cylinder", false);
TS_ASSERT_THROWS_NOTHING(writer.WriteFilesUsingMesh(mesh));
{
// Check that the reader can see it
VtkMeshReader<2,3> vtk_reader(OutputFileHandler::GetChasteTestOutputDirectory() + "TestVtkMeshWriter/cylinder.vtu");
TS_ASSERT_EQUALS(vtk_reader.GetNumNodes(), mesh.GetNumNodes());
TS_ASSERT_EQUALS(vtk_reader.GetNumElements(), mesh.GetNumElements());
TS_ASSERT_EQUALS(mesh_reader.GetNumElements(), 1632u);
TS_ASSERT_EQUALS(mesh_reader.GetNumFaces(), 32u);
}
#else
std::cout << "This test was not run, as VTK is not enabled." << std::endl;
std::cout << "If required please install and alter your hostconfig settings to switch on chaste VTK support." << std::endl;
#endif //CHASTE_VTK
}
void TestXdmfWriter()
{
/*Read as ascii*/
TrianglesMeshReader<3,3> reader("mesh/test/data/simple_cube");
XdmfMeshWriter<3,3> writer_from_reader("TestXdmfMeshWriter", "simple_cube", false);
#ifdef _MSC_VER
if (PetscTools::AmMaster()) // Only the master does anything when using a mesh reader
{
TS_ASSERT_THROWS_THIS(writer_from_reader.WriteFilesUsingMeshReader(reader), "XDMF is not supported under Windows at present.");
}
#else
writer_from_reader.WriteFilesUsingMeshReader(reader);
//Check that the files are the same as previously
FileComparison(OutputFileHandler::GetChasteTestOutputDirectory() + "TestXdmfMeshWriter/simple_cube.xdmf",
"mesh/test/data/TestXdmfMeshWriter/simple_cube.xdmf").CompareFiles();
FileComparison(OutputFileHandler::GetChasteTestOutputDirectory() + "TestXdmfMeshWriter/simple_cube_geometry_0.xml",
"mesh/test/data/TestXdmfMeshWriter/simple_cube_geometry_0.xml").CompareFiles();
FileComparison(OutputFileHandler::GetChasteTestOutputDirectory() + "TestXdmfMeshWriter/simple_cube_topology_0.xml",
"mesh/test/data/TestXdmfMeshWriter/simple_cube_topology_0.xml").CompareFiles();
#endif // _MSC_VER
TetrahedralMesh<3,3> mesh;
mesh.ConstructFromMeshReader(reader);
XdmfMeshWriter<3,3> writer_from_mesh("TestXdmfMeshWriter", "simple_cube_from_mesh", false);
#ifdef _MSC_VER
TS_ASSERT_THROWS_THIS(writer_from_mesh.WriteFilesUsingMesh(mesh), "XDMF is not supported under Windows at present.");
#else
writer_from_mesh.WriteFilesUsingMesh(mesh);
//Just check that the files are there
FileComparison(OutputFileHandler::GetChasteTestOutputDirectory() + "TestXdmfMeshWriter/simple_cube_from_mesh.xdmf",
"mesh/test/data/TestXdmfMeshWriter/simple_cube_from_mesh.xdmf").CompareFiles();
FileComparison(OutputFileHandler::GetChasteTestOutputDirectory() + "TestXdmfMeshWriter/simple_cube_from_mesh_geometry_0.xml",
"mesh/test/data/TestXdmfMeshWriter/simple_cube_from_mesh_geometry_0.xml").CompareFiles();
FileComparison(OutputFileHandler::GetChasteTestOutputDirectory() + "TestXdmfMeshWriter/simple_cube_from_mesh_topology_0.xml",
"mesh/test/data/TestXdmfMeshWriter/simple_cube_from_mesh_topology_0.xml").CompareFiles();
#endif // _MSC_VER
}
void TestXdmfWriter2D()
{
#ifndef _MSC_VER
/*Read as ascii*/
TrianglesMeshReader<2,2> reader("mesh/test/data/disk_522_elements");
XdmfMeshWriter<2,2> writer_from_reader("TestXdmfMeshWriter", "disk", false);
writer_from_reader.WriteFilesUsingMeshReader(reader);
//Check that the files are the same as previously
FileComparison(OutputFileHandler::GetChasteTestOutputDirectory() + "TestXdmfMeshWriter/disk.xdmf",
"mesh/test/data/TestXdmfMeshWriter/disk.xdmf").CompareFiles();
FileComparison(OutputFileHandler::GetChasteTestOutputDirectory() + "TestXdmfMeshWriter/disk_geometry_0.xml",
"mesh/test/data/TestXdmfMeshWriter/disk_geometry_0.xml").CompareFiles();
FileComparison(OutputFileHandler::GetChasteTestOutputDirectory() + "TestXdmfMeshWriter/disk_topology_0.xml",
"mesh/test/data/TestXdmfMeshWriter/disk_topology_0.xml").CompareFiles();
TetrahedralMesh<2,2> mesh;
mesh.ConstructFromMeshReader(reader);
XdmfMeshWriter<2,2> writer_from_mesh("TestXdmfMeshWriter", "disk_from_mesh", false);
writer_from_mesh.WriteFilesUsingMesh(mesh);
//Just check that the files are there
FileComparison(OutputFileHandler::GetChasteTestOutputDirectory() + "TestXdmfMeshWriter/disk_from_mesh.xdmf",
"mesh/test/data/TestXdmfMeshWriter/disk_from_mesh.xdmf").CompareFiles();
FileComparison(OutputFileHandler::GetChasteTestOutputDirectory() + "TestXdmfMeshWriter/disk_from_mesh_geometry_0.xml",
"mesh/test/data/TestXdmfMeshWriter/disk_from_mesh_geometry_0.xml").CompareFiles();
FileComparison(OutputFileHandler::GetChasteTestOutputDirectory() + "TestXdmfMeshWriter/disk_from_mesh_topology_0.xml",
"mesh/test/data/TestXdmfMeshWriter/disk_from_mesh_topology_0.xml").CompareFiles();
#endif // _MSC_VER
}
void TestXdmfWriterDistributed()
{
#ifndef _MSC_VER
TrianglesMeshReader<3,3> reader("mesh/test/data/simple_cube");
DistributedTetrahedralMesh<3,3> mesh;
mesh.ConstructFromMeshReader(reader);
XdmfMeshWriter<3,3> writer_from_mesh("TestXdmfMeshWriter", "simple_cube_dist", false);
writer_from_mesh.WriteFilesUsingMesh(mesh);
if (PetscTools::AmMaster())
{
for (unsigned i=0; i<PetscTools::GetNumProcs(); i++)
{
std::stringstream chunk_name;
chunk_name << OutputFileHandler::GetChasteTestOutputDirectory();
chunk_name << "TestXdmfMeshWriter/simple_cube_dist_topology_" << i <<".xml";
TS_ASSERT( FileFinder(chunk_name.str(), RelativeTo::Absolute).Exists());
}
// If we are running with exactly 2 processes, then we can check for the exact output
if (PetscTools::GetNumProcs() == 2u)
{
FileComparison(OutputFileHandler::GetChasteTestOutputDirectory() + "TestXdmfMeshWriter/simple_cube_dist.xdmf",
"mesh/test/data/TestXdmfMeshWriter/simple_cube_dist.xdmf", false /*not collective*/).CompareFiles();
FileComparison(OutputFileHandler::GetChasteTestOutputDirectory() + "TestXdmfMeshWriter/simple_cube_dist_geometry_0.xml",
"mesh/test/data/TestXdmfMeshWriter/simple_cube_dist_geometry_0.xml", false /*not collective*/).CompareFiles();
FileComparison(OutputFileHandler::GetChasteTestOutputDirectory() + "TestXdmfMeshWriter/simple_cube_dist_topology_0.xml",
"mesh/test/data/TestXdmfMeshWriter/simple_cube_dist_topology_0.xml", false /*not collective*/).CompareFiles();
FileComparison(OutputFileHandler::GetChasteTestOutputDirectory() + "TestXdmfMeshWriter/simple_cube_dist_geometry_1.xml",
"mesh/test/data/TestXdmfMeshWriter/simple_cube_dist_geometry_1.xml", false /*not collective*/).CompareFiles();
FileComparison(OutputFileHandler::GetChasteTestOutputDirectory() + "TestXdmfMeshWriter/simple_cube_dist_topology_1.xml",
"mesh/test/data/TestXdmfMeshWriter/simple_cube_dist_topology_1.xml", false /*not collective*/).CompareFiles();
}
}
#endif // _MSC_VER
}
};
#endif //_TESTXMLMESHWRITERS_HPP_
|
#ifndef _LIBSVM_H
#define _LIBSVM_H
#define LIBSVM_VERSION 321
#include <iostream>
#include <fstream>
#include <cstdio>
#pragma warning(disable:4996)
using namespace std;
extern int libsvm_version;
struct svm_node
{
int index;
double value;
};
struct svm_problem
{
int l;
double *y;
struct svm_node **x;
};
enum { C_SVC, NU_SVC, ONE_CLASS, EPSILON_SVR, NU_SVR }; /* svm_type */
enum { LINEAR, POLY, RBF, SIGMOID, PRECOMPUTED }; /* kernel_type */
struct svm_parameter
{
int svm_type;
int kernel_type;
int degree; /* for poly */
double gamma; /* for poly/rbf/sigmoid */
double coef0; /* for poly/sigmoid */
/* these are for training only */
double cache_size; /* in MB */
double eps; /* stopping criteria */
double C; /* for C_SVC, EPSILON_SVR and NU_SVR */
int nr_weight; /* for C_SVC */
int *weight_label; /* for C_SVC */
double* weight; /* for C_SVC */
double nu; /* for NU_SVC, ONE_CLASS, and NU_SVR */
double p; /* for EPSILON_SVR */
int shrinking; /* use the shrinking heuristics */
int probability; /* do probability estimates */
};
//
// svm_model
//
struct svm_model
{
struct svm_parameter param; /* parameter */
int nr_class; /* number of classes, = 2 in regression/one class svm */
int l; /* total #SV */
struct svm_node **SV; /* SVs (SV[l]) */
double **sv_coef; /* coefficients for SVs in decision functions (sv_coef[k-1][l]) */
double *rho; /* constants in decision functions (rho[k*(k-1)/2]) */
double *probA; /* pariwise probability information */
double *probB;
int *sv_indices; /* sv_indices[0,...,nSV-1] are values in [1,...,num_traning_data] to indicate SVs in the training set */
/* for classification only */
int *label; /* label of each class (label[k]) */
int *nSV; /* number of SVs for each class (nSV[k]) */
/* nSV[0] + nSV[1] + ... + nSV[k-1] = l */
/* XXX */
int free_sv; /* 1 if svm_model is created by svm_load_model*/
/* 0 if svm_model is created by svm_train */
};
struct svm_model *svm_train(const struct svm_problem *prob, const struct svm_parameter *param);
void svm_cross_validation(const struct svm_problem *prob, const struct svm_parameter *param, int nr_fold, double *target);
int svm_save_model(const char *model_file_name, const struct svm_model *model);
struct svm_model *svm_load_model(const char *model_file_name);
int svm_get_svm_type(const struct svm_model *model);
int svm_get_nr_class(const struct svm_model *model);
void svm_get_labels(const struct svm_model *model, int *label);
void svm_get_sv_indices(const struct svm_model *model, int *sv_indices);
int svm_get_nr_sv(const struct svm_model *model);
double svm_get_svr_probability(const struct svm_model *model);
double svm_predict_values(const struct svm_model *model, const struct svm_node *x, double* dec_values);
double svm_predict(const struct svm_model *model, const struct svm_node *x);
double svm_predict_probability(const struct svm_model *model, const struct svm_node *x, double* prob_estimates);
void svm_free_model_content(struct svm_model *model_ptr);
void svm_free_and_destroy_model(struct svm_model **model_ptr_ptr);
void svm_destroy_param(struct svm_parameter *param);
const char *svm_check_parameter(const struct svm_problem *prob, const struct svm_parameter *param);
int svm_check_probability_model(const struct svm_model *model);
void svm_set_print_string_function(void (*print_func)(const char *));
#ifdef __cplusplus
class SVM {
public:
int n;
int dim, npos, nneg;
double **pos, **neg;
struct svm_parameter param;
struct svm_problem prob;
struct svm_model *model;
int TP, TN, FP, FN;
double acc, pre1, pre2, rec1, rec2, f11, f12;
void clear() {
int i;
for (i = 0; i < n; i++)
free(prob.x[i]);
free(prob.x);
free(prob.y);
free(model);
}
double getOutput(double *pat) {
int i;
struct svm_node *x = (struct svm_node*)malloc(sizeof(struct svm_node) * (dim + 1));
for (i = 0; i < dim; i++) {
x[i].index = i + 1;
x[i].value = pat[i];
}
x[i].index = -1;
double dec_values = 0.f;
double pred = svm_predict_values(model, x, &dec_values);
free(x);
return dec_values;
}
bool isPos(double *pat) {
int i;
bool result;
struct svm_node *x = (struct svm_node*)malloc(sizeof(struct svm_node) * (dim + 1));
for (i = 0; i < dim; i++) {
x[i].index = i + 1;
x[i].value = pat[i];
}
x[i].index = -1;
double dec_values = 0.f;
double pred = svm_predict_values(model, x, &dec_values);
result = (pred == 1 ? true : false);
free(x);
return result;
}
//Test
void test_counting(int test_npos, int test_nneg, double **test_pos, double **test_neg) {
int i;
for (i = 0; i < test_npos; i++) {
if (isPos(test_pos[i])) TP++;
else FP++;
}
for (i = 0; i < test_nneg; i++) {
if (isPos(test_neg[i])) FN++;
else TN++;
}
}
void test_measure(char *fname) {
char fch[100];
ofstream fout;
sprintf(fch, "%s_svm.csv", fname);
fout.open(fch);
acc = 1.f - ((double)(FP + FN)) / (TP + FP + TN + FN);
pre1 = (double)TP / (TP + FP);
rec1 = (double)TP / (TP + FN);
f11 = (2.f * pre1 * rec1) / (pre1 + rec1);
pre2 = (double)TN / (TN + FN);
rec2 = (double)TN / (TN + FP);
f12 = (2.f * pre2 * rec2) / (pre2 + rec2);
cout << "---------------SVM---------------" << endl;
cout << "Accuracy : " << acc << endl;
cout << "---------------NR----------------" << endl;
cout << "Precision (NR) : " << pre1 << endl;
cout << "Recall : " << rec1 << endl;
cout << "F1 : " << f11 << endl;
cout << "---------------AN----------------" << endl;
cout << "Precision (NR) : " << pre2 << endl;
cout << "Recall : " << rec2 << endl;
cout << "F1 : " << f12 << endl;
cout << endl;
fout << "Accuracy," << acc << endl;
fout << "Precision," << pre1 << endl;
fout << "Recall," << rec1 << endl;
fout << "F1," << f11 << endl;
fout << "Precision," << pre2 << endl;
fout << "Recall," << rec2 << endl;
fout << "F1," << f12 << endl;
fout.close();
}
//Training
void train(int dim, int npos, int nneg, double **pos, double **neg) {
int i, j;
this->dim = dim;
this->npos = npos;
this->nneg = nneg;
this->pos = pos;
this->neg = neg;
n = npos + nneg;
prob.l = n;
prob.y = (double*)malloc(sizeof(double) * n);
prob.x = (struct svm_node**)malloc(sizeof(struct svm_node*) * n);
for (i = 0; i < npos; i++) {
prob.x[i] = (struct svm_node*)malloc(sizeof(struct svm_node) * (dim + 1));
for (j = 0; j < dim; j++) {
prob.x[i][j].index = j + 1;
prob.x[i][j].value = pos[i][j];
}
prob.x[i][j].index = -1;
prob.y[i] = 1.f;
if (!prob.x)
i = i;
}
for (i = 0; i < nneg; i++) {
prob.x[i + npos] = (struct svm_node*)malloc(sizeof(struct svm_node) * (dim+1));
for (j = 0; j < dim; j++) {
prob.x[i + npos][j].index = j + 1;
prob.x[i + npos][j].value = neg[i][j];
}
prob.x[i+ npos][j].index = -1;
prob.y[i + npos] = -1.f;
}
model = svm_train(&prob, ¶m);
}
SVM() {
// default values
param.svm_type = C_SVC;
param.kernel_type = LINEAR;
param.degree = 3;
param.gamma = 0; // 1/num_features
param.coef0 = 0;
param.nu = 0.5;
param.cache_size = 100;
param.C = 1;
param.eps = 1e-3;
param.p = 0.1;
param.shrinking = 1;
param.probability = 0;
param.nr_weight = 0;
param.weight_label = NULL;
param.weight = NULL;
}
SVM(double gamma) {
// default values
param.svm_type = C_SVC;
param.kernel_type = RBF;
param.degree = 3;
param.gamma = gamma; // 1/num_features
param.coef0 = 0;
param.nu = 0.5;
param.cache_size = 100;
param.C = 1;
param.eps = 1e-3;
param.p = 0.1;
param.shrinking = 1;
param.probability = 0;
param.nr_weight = 0;
param.weight_label = NULL;
param.weight = NULL;
}
SVM(int svm_type, int kernel_type) {
// default values
param.svm_type = svm_type;
param.kernel_type = kernel_type;
param.degree = 3;
param.gamma = 0; // 1/num_features
param.coef0 = 0;
param.nu = 0.5;
param.cache_size = 100;
param.C = 1;
param.eps = 1e-3;
param.p = 0.1;
param.shrinking = 1;
param.probability = 0;
param.nr_weight = 0;
param.weight_label = NULL;
param.weight = NULL;
}
SVM(struct svm_parameter p) {
param.svm_type = p.svm_type;
param.kernel_type = p.kernel_type;
param.degree = p.degree;
param.gamma = p.gamma; // 1/num_features
param.coef0 = p.coef0;
param.nu = p.nu;
param.cache_size = p.cache_size;
param.C = p.C;
param.eps = p.eps;
param.p = p.p;
param.shrinking = p.shrinking;
param.probability = p.probability;
param.nr_weight = p.nr_weight;
param.weight_label = p.weight_label;
param.weight = p.weight;
}
};
#endif
#endif /* _LIBSVM_H */
|
#pragma once
#include <iostream>
/// \brief Geodetic position
struct GeodeticPosition
{
double latitude; /// Latitude in degrees.
double longitude; /// Longitude in degrees.
double altitude; /// Altitude in meters.
};
/// \brief Operator for reading data from stream.
std::istream& operator>>(std::istream& is, GeodeticPosition& pos);
/// \brief Operator for printing data to stream.
/// Meant for showing data, and is not compatible with the reader.
std::ostream& operator<<(std::ostream& os, const GeodeticPosition& pos);
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
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 University of Oxford 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.
*/
#ifndef ABSTRACTELEMENT_HPP_
#define ABSTRACTELEMENT_HPP_
#include <vector>
#include "UblasVectorInclude.hpp"
#include "Node.hpp"
#include "ElementAttributes.hpp"
/*
* When creating an element within a mesh one needs to specify its global index.
* If the element is not used within a mesh the following constant is used instead.
*/
const unsigned INDEX_IS_NOT_USED=0;
/**
* An abstract element class for use in finite element meshes.
*/
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM>
class AbstractElement
{
protected:
/** The nodes forming this element. */
std::vector<Node<SPACE_DIM>*> mNodes;
/** The index of this element within the mesh */
unsigned mIndex;
/**
* Whether this element has been deleted, and hence
* whether its location in the mesh can be re-used.
*/
bool mIsDeleted;
/** Whether the current process owns this element. */
bool mOwnership;
/** A pointer to an ElementAttributes object associated with this element. */
ElementAttributes<ELEMENT_DIM, SPACE_DIM>* mpElementAttributes;
/**
* Construct an empty ElementAttributes container.
*/
void ConstructElementAttributes();
public:
/**
* Constructor which takes in a vector of nodes.
*
* @param index the index of the element in the mesh
* @param rNodes the nodes owned by the element
*/
AbstractElement(unsigned index, const std::vector<Node<SPACE_DIM>*>& rNodes);
/**
* Default constructor, which doesn't add any nodes: they must be added later.
*
* @param index the index of the element in the mesh (defaults to INDEX_IS_NOT_USED)
*/
AbstractElement(unsigned index=INDEX_IS_NOT_USED);
/**
* Virtual destructor, since this class has virtual methods.
* Deletes added attributes (when they exist)
*/
virtual ~AbstractElement();
/**
* Update node at the given index.
*
* @param rIndex is an local index to which node to change
* @param pNode is a pointer to the replacement node
*/
virtual void UpdateNode(const unsigned& rIndex, Node<SPACE_DIM>* pNode)=0;
/**
* Replace one of the nodes in this element with another.
*
* @param pOldNode pointer to the current node
* @param pNewNode pointer to the replacement node
*/
void ReplaceNode(Node<SPACE_DIM>* pOldNode, Node<SPACE_DIM>* pNewNode);
/**
* Mark the element as having been removed from the mesh.
* Also notify nodes in the element that it has been removed.
*/
virtual void MarkAsDeleted()=0;
/**
* Inform all nodes forming this element that they are in this element.
*/
virtual void RegisterWithNodes()=0;
/**
* @return a single component of the location in space of one of the nodes
* in this element.
*
* @param localIndex the index of the node to query, in [0,N) where N
* is the number of nodes in this element.
* @param dimension the spatial dimension to query.
*/
double GetNodeLocation(unsigned localIndex, unsigned dimension) const;
/**
* @return the location in space of one of the nodes in this element.
*
* @param localIndex the index of the node to query, in [0,N) where N
* is the number of nodes in this element.
*/
c_vector<double, SPACE_DIM> GetNodeLocation(unsigned localIndex) const;
/**
* Given the local index of a node owned by this element, return the
* global index of the node in the mesh.
*
* @param localIndex the node's local index in this element
* @return the global index
*/
unsigned GetNodeGlobalIndex(unsigned localIndex) const;
/**
* Get the node with a given local index in this element.
*
* @param localIndex local index of the node in this element
* @return a pointer to the node.
*/
Node<SPACE_DIM>* GetNode(unsigned localIndex) const;
/**
* @return the number of nodes owned by this element.
*/
unsigned GetNumNodes() const;
/**
* Add a node to this element.
*
* @param pNode pointer to the new node
*/
void AddNode(Node<SPACE_DIM>* pNode);
/**
* Get whether the element is marked as deleted.
*
* @return mIsDeleted
*/
bool IsDeleted() const;
/**
* @return the index of this element
*/
unsigned GetIndex() const;
/**
* Set the index of this element in the mesh.
*
* @param index the new index
*/
void SetIndex(unsigned index);
/**
* @return whether the current process owns this element.
*/
bool GetOwnership() const;
/**
* Set whether the current process owns this element.
*
* @param ownership whether the current process now owns this element
*/
void SetOwnership(bool ownership);
/**
* Set an attribute (a value associated with the element)
*
* @param attribute the value of an attribute
*/
void SetAttribute(double attribute);
/**
* @return the element's attribute value
*/
double GetAttribute();
/**
* This method converts the attribute (stored as a double) to an
* unsigned, and throws an exception if this is not sensible.
*
* @return an unsigned attribute value.
*/
unsigned GetUnsignedAttribute();
/**
* Add an attribute to the list of element attributes.
*
* @param attribute the value of the attribute to be added
*/
void AddElementAttribute(double attribute);
/**
* @return reference to a vector containing the element attributes.
*/
std::vector<double>& rGetElementAttributes();
/**
* @return the number of node attributes associated with this node.
*/
unsigned GetNumElementAttributes();
};
#endif /*ABSTRACTELEMENT_HPP_*/
|
#ifndef __KMEANS_HH__
#define __KMEANS_HH__
#include "datatype.hh"
#include <string.h>
namespace KMeans {
void main(DataPoint* const centroids, DataPoint* const data);
static void initCentroids(DataPoint* const centroids, const DataPoint* const data) {
for(int kIdx=0; kIdx!=KSize; ++kIdx) {
centroids[kIdx].label = kIdx;
for(int featIdx=0; featIdx!=FeatSize; ++featIdx) {
centroids[kIdx].value[featIdx] = data[kIdx].value[featIdx];
}
}
}
void labeling(const DataPoint* const centroids, DataPoint* const data);
namespace Labeling {
Data_T euclideanDistSQR(const DataPoint* const lhs, const DataPoint* const rhs);
void setClosestCentroid(const DataPoint* centroids, DataPoint* const data);
};
void updateCentroid(DataPoint* const centroids, const DataPoint* const data);
namespace Update {
void addValuesLtoR(const Data_T* const lhs, Data_T* const rhs);
};
static bool isSame(DataPoint* const centroids, DataPoint* const newCentroids) {
DataPoint* prevCentroidPtr = centroids;
DataPoint* newCentroidPtr = newCentroids;
for(int kIdx=0; kIdx!=KSize; ++kIdx) {
Data_T* prevValuePtr = prevCentroidPtr->value;
Data_T* newValuePtr = newCentroidPtr->value;
for(int featIdx=0; featIdx!=FeatSize; ++featIdx) {
if(*prevValuePtr - *newValuePtr > 0.0001) {
return false;
}
prevValuePtr++;
newValuePtr++;
}
prevCentroidPtr++;
newCentroidPtr++;
}
return true;
}
};
static void resetNewCentroids(DataPoint* newCentroids) {
for(int i=0; i!=KSize; ++i) {
newCentroids[i].label = i;
Data_T* valuePtr = newCentroids[i].value;
for(int j=0; j!=FeatSize; ++j) {
*valuePtr = 0.0;
valuePtr++;
}
}
}
static inline void memcpyCentroid(DataPoint* const centroids, DataPoint* const newCentroids) {
memcpy((void*)centroids, (void*)newCentroids, KSize*sizeof(DataPoint));
}
#endif
|
#ifndef __SNESAPU_HELPERS_H__
#define __SNESAPU_HELPERS_H__
namespace SnesApu
{
class Helpers
{
public:
static short MultiplyVolume(short value, char volume);
static int Clamp(int value);
};
}
#endif
|
#include <iostream>
#include <stdlib.h>
#include "pila.h"
using namespace std;
/*
"Anthony Chaple did this(0_o)"
"|_|0|_|" << endl;
"|_|_|0|" << endl;
"|0|0|0|" << endl;
"---------------------------------"
"original code(had errors, at least when i compiled it on Qt)"
"in EDD book by:Salvador Pozo &Steven R. Davidson"
*/
int main()
{
cout << "Anthony Chaple did this(0_o)" << endl;
cout << "|_|0|_|" << endl;
cout << "|_|_|0|" << endl;
cout << "|0|0|0|" << endl;
cout << "---------------------------------" << endl;
pila<int> iPila;
pila<float> fPila;
pila<double> dPila;
pila<char> cPila;
pila<char *> sPila;
// Prueba con <int>
iPila.Push(20);
iPila.Push(10);
cout << iPila.Pop() << ",";
iPila.Push(40);
iPila.Push(30);
cout << iPila.Pop() << ",";
cout << iPila.Pop() << ",";
iPila.Push(90);
cout << iPila.Pop() << ",";
cout << iPila.Pop() << endl;
// Prueba con <float>
fPila.Push(20.01);
fPila.Push(10.02);
cout << fPila.Pop() << ",";
fPila.Push(40.03);
fPila.Push(30.04);
cout << fPila.Pop() << ",";
cout << fPila.Pop() << ",";
fPila.Push(90.05);
cout << fPila.Pop() << ",";
cout << fPila.Pop() << endl;
// Prueba con <double>
dPila.Push(0.0020);
dPila.Push(0.0010);
cout << dPila.Pop() << ",";
dPila.Push(0.0040);
dPila.Push(0.0030);
cout << dPila.Pop() << ",";
cout << dPila.Pop() << ",";
dPila.Push(0.0090);
cout << dPila.Pop() << ",";
cout << dPila.Pop() << endl;
// Prueba con <char>
cPila.Push('x');
cPila.Push('y');
cout << cPila.Pop() << ",";
cPila.Push('a');
cPila.Push('b');
cout << cPila.Pop() << ",";
cout << cPila.Pop() << ",";
cPila.Push('m');
cout << cPila.Pop() << ",";
cout << cPila.Pop() << endl;
// Prueba con <char *>
sPila.Push("Hola");
sPila.Push("somos");
cout << sPila.Pop() << ",";
sPila.Push("programadores");
sPila.Push("buenos");
cout << sPila.Pop() << ",";
cout << sPila.Pop() << ",";
sPila.Push("!!!!");
cout << sPila.Pop() << ",";
cout << sPila.Pop() << endl;
system("PAUSE");
return 0;
}
|
//C++ INCLUDES
#include <stdlib.h>
#include <algorithm>
#include <vector>
#include <fstream>
#include <iostream>
#include <math.h>
//ROOT INCLUDES
//#include <TSYSTEM.h>
#include <TSystem.h>
#include <TTree.h>
#include <TLatex.h>
#include <TString.h>
#include <TFile.h>
#include <TH1D.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TF1.h>
#include <TBox.h>
#include <TCanvas.h>
#include <TGraph.h>
#include <TColor.h>
#include <TGraphErrors.h>
#include <TRandom3.h>
#include <TLegend.h>
#include <TMath.h>
#include <TROOT.h>
#include <Math/GaussIntegrator.h>
#include <Math/IntegratorOptions.h>
#include <Math/DistFunc.h>
#include <TFractionFitter.h>
#include <TRandom3.h>
//LOCAL INCLUDES
#include "MakeFitMETTime.hh"
#include "Aux.hh"
//Axis
const float axisTitleSize = 0.06;
const float axisTitleOffset = .8;
const float axisTitleSizeRatioX = 0.18;
const float axisLabelSizeRatioX = 0.12;
const float axisTitleOffsetRatioX = 0.84;
const float axisTitleSizeRatioY = 0.15;
const float axisLabelSizeRatioY = 0.108;
const float axisTitleOffsetRatioY = 0.52;
//Margins
const float leftMargin = 0.13;
const float rightMargin = 0.05;
const float topMargin = 0.07;
const float bottomMargin = 0.12;
using namespace std;
RooWorkspace* FitDataBkgFraction( TH1F * h1_Data, TString varName, TString varTitle, TString varUnit, float lumi, float varLow, float varHigh, TH1F * h1_GJets, TH1F * h1_QCD, TString outPlotsDir)
{
RooWorkspace* ws = new RooWorkspace( "ws", "" );
// define variables
RooRealVar fitVar ( varName, varTitle, varLow, varHigh, varUnit);
//RooRealVar nGJets ("nGJets", "nGJets", 5835.0, 0.5*5835.0, 1.5*5835.0);
//RooRealVar nGJets ("nGJets", "nGJets", 5800.0, 0.0, tree->GetEntries());
//RooRealVar nGJets ("nGJets", "nGJets", 0.5, 0.0001, 10000.0);
RooRealVar nGJets ("nGJets", "nGJets", 0.5, 0.0001, 0.5*h1_Data->Integral());
//RooRealVar nQCD ("nQCD", "nQCD", 3500.0, 0.5*3500, 1.5*3500.0);
//RooRealVar nQCD ("nQCD", "nQCD", 3500.0, 0.0, tree->GetEntries());
//RooRealVar nQCD ("nQCD", "nQCD", 0.5, 0.0001, 10000.0);
RooRealVar nQCD ("nQCD", "nQCD", 0.5, 0.0001, 0.5*h1_Data->Integral());
// Import data
RooDataHist * data = new RooDataHist("data", "data", RooArgSet(fitVar), h1_Data);
// Import Background shapes
RooDataHist * rhGJets = new RooDataHist("rhGJets", "rhGJets", RooArgSet(fitVar), h1_GJets);
RooDataHist * rhQCD = new RooDataHist("rhQCD", "rhQCD", RooArgSet(fitVar), h1_QCD);
//to avoid zero likelihood, fill empty template bins with tiny values
for(int i=0;i<data->numEntries() ; i++)
{
data->get(i);
rhGJets->get(i);
rhQCD->get(i);
float weight_data = data->weight();
float weight_rhGJets = rhGJets->weight();
float weight_rhQCD = rhQCD->weight();
if((weight_rhGJets + weight_rhQCD < 1e-5) && (weight_data > 0))
{
rhGJets->set(1e-5);
rhQCD->set(1e-5);
}
}
// Define PDFs from Background shapes
RooHistPdf * rpGJets = new RooHistPdf("rpGJets", "rpGJets", RooArgSet(fitVar), *rhGJets);
RooHistPdf * rpQCD = new RooHistPdf("rpQCD", "rpQCD", RooArgSet(fitVar), *rhQCD);
// Add all PDFs to form fit model
RooAbsPdf * fitModel = new RooAddPdf("fitModel", "fitModel", RooArgSet(*rpGJets, *rpQCD), RooArgSet(nGJets, nQCD));
// do fit and save to workspace
RooFitResult * fres = fitModel->fitTo( *data, RooFit::Strategy(2), RooFit::Extended( kTRUE ), RooFit::Save( kTRUE ));
nGJets.Print();
nQCD.Print();
RooPlot * frame = fitVar.frame(varLow, varHigh, 100);
data->plotOn( frame, RooFit::Name("plot_data"));
fitModel->plotOn( frame, RooFit::Components("rpGJets"), RooFit::LineColor(kViolet + 10), RooFit::Name("plot_GJets") );
fitModel->plotOn( frame, RooFit::Components("rpQCD"), RooFit::LineColor(kOrange + 9), RooFit::Name("plot_QCD") );
fitModel->plotOn( frame, RooFit::Components("fitModel"), RooFit::LineColor(kGreen) , RooFit::Name("plot_all"));
frame->SetName(varName+"_frame");
//save the plot
TCanvas *myC = new TCanvas( "myC", "myC", 200, 10, 800, 800 );
myC->SetHighLightColor(2);
myC->SetFillColor(0);
myC->SetBorderMode(0);
myC->SetBorderSize(2);
myC->SetLeftMargin( leftMargin );
myC->SetRightMargin( rightMargin );
myC->SetTopMargin( topMargin );
myC->SetBottomMargin( bottomMargin );
myC->SetFrameBorderMode(0);
myC->SetFrameBorderMode(0);
myC->SetLogy(1);
frame->SetTitle("");
frame->SetMaximum(150.0*frame->GetMaximum());
frame->SetMinimum(0.1);
frame->Draw();
TLegend * leg = new TLegend(0.18, 0.7, 0.93, 0.89);
leg->SetNColumns(2);
leg->SetBorderSize(0);
leg->SetTextSize(0.03);
leg->SetLineColor(1);
leg->SetLineStyle(1);
leg->SetLineWidth(1);
leg->SetFillColor(0);
leg->SetFillStyle(1001);
leg->AddEntry("plot_data","data","lep");
leg->AddEntry("plot_GJets","#gamma + jets","l");
leg->AddEntry("plot_QCD","QCD","l");
leg->AddEntry("plot_all","combined fit","l");
leg->Draw();
DrawCMS(myC, 13, lumi);
myC->SetTitle("");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/bkg_yield_fit_"+varName+".pdf");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/bkg_yield_fit_"+varName+".png");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/bkg_yield_fit_"+varName+".C");
ws->import(*data);
ws->import(*fitModel);
ws->import(*frame);
ws->import(*fres);
return ws;
};
TFractionFitter* FitDataBkgFractionFilter(TH1F * h1_data, TH1F * h1_GJets, TH1F * h1_QCD)
{
TObjArray *temp = new TObjArray(2);
temp->Add(h1_GJets);
temp->Add(h1_QCD);
TFractionFitter* fit = new TFractionFitter(h1_data, temp);
fit->Constrain(0,0.0,1.0);
fit->Constrain(1,0.0,1.0);
Int_t status = fit->Fit();
cout << "fit status: " << status << endl;
Double_t par0, par0err, par1, par1err;
fit->GetResult(0, par0, par0err);
fit->GetResult(1, par1, par1err);
cout << "fraction GJets: " << par0 << " +/- " << par0err <<endl;
cout << "fraction QCD: " << par1 << " +/- " << par1err <<endl;
return fit;
};
RooWorkspace* Fit2DMETTimeDataBkg( TTree * treeData, TTree * treeGJets, TTree * treeQCD, float fracGJets, float fracGJetsErr, float fracQCD, float fracQCDErr)
{
RooWorkspace* ws = new RooWorkspace( "ws", "" );
// define variables
RooRealVar pho1ClusterTime_SmearToData("pho1ClusterTime_SmearToData","#gamma cluster time ",-15.0,15.0,"ns");
RooRealVar MET("MET","#slash{E}_{T} ",0,1000,"GeV");
RooRealVar nGJets ("nGJets", "nGJets", fracGJets, fracGJets-3.0*fracGJetsErr, fracGJets+3.0*fracGJetsErr);
RooRealVar nQCD ("nQCD", "nQCD", fracQCD, fracQCD-3.0*fracQCDErr, fracQCD+3.0*fracQCDErr);
//RooRealVar nGJets ("nGJets", "nGJets", 0.5,0.0,1.0);
//RooRealVar nQCD ("nQCD", "nQCD", 0.5,0.0,1.0);
RooRealVar weightGJets("weightGJets", "weightGJets", (treeData->GetEntries()*1.0)/(treeGJets->GetEntries()*1.0));
RooRealVar weightQCD("weightQCD", "weightQCD", (treeData->GetEntries()*1.0)/(treeQCD->GetEntries()*1.0));
//data sets
RooDataSet data( "data", "data", RooArgSet(pho1ClusterTime_SmearToData, MET), RooFit::Import(*treeData));
RooDataSet dataGJets( "dataGJets", "dataGJets", RooArgSet(pho1ClusterTime_SmearToData, MET), RooFit::Import(*treeGJets), RooFit::WeightVar("weightGJets"));
RooDataSet dataQCD( "dataQCD", "dataQCD", RooArgSet(pho1ClusterTime_SmearToData, MET), RooFit::Import(*treeQCD), RooFit::WeightVar("weightQCD"));
//RooDataSet -> RooDataHist
RooDataHist* rhGJets = new RooDataHist("rhGJets", "rhGJets", RooArgSet(pho1ClusterTime_SmearToData, MET), dataGJets);
RooDataHist* rhQCD = new RooDataHist("rhQCD", "rhQCD", RooArgSet(pho1ClusterTime_SmearToData, MET), dataQCD);
//RooDataHist -> RooHistPdf
RooHistPdf * rpGJets = new RooHistPdf("rpGJets", "rpGJets", RooArgSet(pho1ClusterTime_SmearToData, MET), *rhGJets);
RooHistPdf * rpQCD = new RooHistPdf("rpQCD", "rpQCD", RooArgSet(pho1ClusterTime_SmearToData, MET), *rhQCD);
//RooHistPdf -> RooAbsPdf
RooAbsPdf * fitModel = new RooAddPdf("fitModel", "fitModel", RooArgSet(*rpGJets, *rpQCD), RooArgSet(nGJets, nQCD));
//fit
RooAbsReal* nll = fitModel->createNLL(data, RooFit::NumCPU(8)) ;
RooMinimizer m(*nll);
m.migrad() ;
//RooFitResult * fres = fitModel->fitTo( data, RooFit::Strategy(2), RooFit::Extended( kTRUE ), RooFit::Save( kTRUE ));
//RooFitResult * fres = fitModel->fitTo( data, RooFit::Extended( kTRUE ), RooFit::Save( kTRUE ));
RooFitResult * fres1 = m.save();
int _status = -1;
_status = fres1->status();
if(_status!=0)
{
m.minimize("Minuit2", "Hesse");
}
RooFitResult * fres = m.save();
_status = fres->status();
nGJets.Print();
nQCD.Print();
RooPlot * frame_pho1ClusterTime_SmearToData = pho1ClusterTime_SmearToData.frame(-15.0, 15.0, 100);
data.plotOn( frame_pho1ClusterTime_SmearToData );
fitModel->plotOn( frame_pho1ClusterTime_SmearToData, RooFit::Components("rpGJets"), RooFit::LineColor(kViolet + 10) );
fitModel->plotOn( frame_pho1ClusterTime_SmearToData, RooFit::Components("rpQCD"), RooFit::LineColor(kOrange + 9) );
fitModel->plotOn( frame_pho1ClusterTime_SmearToData, RooFit::Components("fitModel"), RooFit::LineColor(kGreen) );
frame_pho1ClusterTime_SmearToData->SetName("pho1ClusterTime_SmearToData_frame");
RooPlot * frame_pho1ClusterTime_SmearToData_LL = pho1ClusterTime_SmearToData.frame(-15.0, 15.0, 100);
nll->plotOn(frame_pho1ClusterTime_SmearToData_LL, RooFit::ShiftToZero()) ;
frame_pho1ClusterTime_SmearToData_LL->SetName("pho1ClusterTime_SmearToData_frame_Likelihood");
RooPlot * frame_MET = MET.frame(0, 1000.0, 100);
data.plotOn( frame_MET );
fitModel->plotOn( frame_MET, RooFit::Components("rpGJets"), RooFit::LineColor(kViolet + 10) );
fitModel->plotOn( frame_MET, RooFit::Components("rpQCD"), RooFit::LineColor(kOrange + 9) );
fitModel->plotOn( frame_MET, RooFit::Components("fitModel"), RooFit::LineColor(kGreen) );
frame_MET->SetName("MET_frame");
RooPlot * frame_MET_LL = MET.frame(0, 1000.0, 100);
nll->plotOn(frame_MET_LL, RooFit::ShiftToZero()) ;
frame_MET_LL->SetName("MET_frame_Likelihood");
ws->import(data);
ws->import(dataGJets);
ws->import(dataQCD);
ws->import(*fitModel);
ws->import(*frame_pho1ClusterTime_SmearToData);
ws->import(*frame_pho1ClusterTime_SmearToData_LL);
ws->import(*frame_MET);
ws->import(*frame_MET_LL);
ws->import(*fres);
return ws;
};
RooWorkspace* Fit2DMETTimeDataBkg( TH2F * h2Data, TH2F * h2GJets, TH2F * h2QCD, float fracGJets, float fracGJetsErr, float fracQCD, float fracQCDErr, TString outPlotsDir)
{
RooWorkspace* ws = new RooWorkspace( "ws", "" );
// define variables
RooRealVar pho1ClusterTime_SmearToData("pho1ClusterTime_SmearToData","#gamma cluster time ",-15.0,15.0,"ns");
RooRealVar MET("MET","#slash{E}_{T} ",0,1000,"GeV");
RooRealVar nGJets ("nGJets", "nGJets", fracGJets, fracGJets-3.0*fracGJetsErr, fracGJets+3.0*fracGJetsErr);
RooRealVar nQCD ("nQCD", "nQCD", fracQCD, fracQCD-3.0*fracQCDErr, fracQCD+3.0*fracQCDErr);
//RooRealVar nGJets ("nGJets", "nGJets", 0.5,0.001,10000.0);
//RooRealVar nQCD ("nQCD", "nQCD", 0.5,0.001,10000.0);
//RooDataHist
RooDataHist* data = new RooDataHist("data", "data", RooArgSet(pho1ClusterTime_SmearToData, MET), h2Data);
RooDataHist* rhGJets = new RooDataHist("rhGJets", "rhGJets", RooArgSet(pho1ClusterTime_SmearToData, MET), h2GJets);
RooDataHist* rhQCD = new RooDataHist("rhQCD", "rhQCD", RooArgSet(pho1ClusterTime_SmearToData, MET), h2QCD);
//to avoid zero likelihood, fill empty template bins with tiny values
for(int i=0;i<data->numEntries() ; i++)
{
data->get(i);
rhGJets->get(i);
rhQCD->get(i);
float weight_data = data->weight();
float weight_rhGJets = rhGJets->weight();
float weight_rhQCD = rhQCD->weight();
if((weight_rhGJets + weight_rhQCD < 1e-5) && (weight_data > 0))
{
rhGJets->set(1e-5);
rhQCD->set(1e-5);
}
}
//RooDataHist -> RooHistPdf
RooHistPdf * rpGJets = new RooHistPdf("rpGJets", "rpGJets", RooArgSet(pho1ClusterTime_SmearToData, MET), *rhGJets, 0);
RooHistPdf * rpQCD = new RooHistPdf("rpQCD", "rpQCD", RooArgSet(pho1ClusterTime_SmearToData, MET), *rhQCD, 0);
//RooHistPdf -> RooAbsPdf
RooAbsPdf * fitModel = new RooAddPdf("fitModel", "fitModel", RooArgSet(*rpGJets, *rpQCD), RooArgSet(nGJets, nQCD));
//fit
RooAbsReal* nll = fitModel->createNLL(*data, RooFit::NumCPU(8)) ;
//RooFitResult * fres = fitModel->fitTo( *data, RooFit::Strategy(2), RooFit::Extended( kTRUE ), RooFit::Save( kTRUE ));
RooFitResult * fres = fitModel->fitTo( *data, RooFit::Extended( kTRUE ), RooFit::Save( kTRUE ));
nGJets.Print();
nQCD.Print();
//draw some fit_results/2016/plots
TCanvas *myC = new TCanvas( "myC", "myC", 200, 10, 800, 800 );
myC->SetHighLightColor(2);
myC->SetFillColor(0);
myC->SetBorderMode(0);
myC->SetBorderSize(2);
myC->SetLeftMargin( leftMargin );
myC->SetRightMargin( rightMargin );
myC->SetTopMargin( topMargin );
myC->SetBottomMargin( bottomMargin );
myC->SetFrameBorderMode(0);
myC->SetFrameBorderMode(0);
myC->SetLogy(1);
RooPlot * frame_pho1ClusterTime_SmearToData = pho1ClusterTime_SmearToData.frame(-15.0, 15.0, 100);
data->plotOn( frame_pho1ClusterTime_SmearToData, RooFit::Name("pho1ClusterTime_SmearToData_data") );
fitModel->plotOn( frame_pho1ClusterTime_SmearToData, RooFit::Name("pho1ClusterTime_SmearToData_GJets"), RooFit::Components("rpGJets"), RooFit::LineColor(kAzure + 7) );
fitModel->plotOn( frame_pho1ClusterTime_SmearToData, RooFit::Name("pho1ClusterTime_SmearToData_QCD"), RooFit::Components("rpQCD"), RooFit::LineColor(kOrange - 9) );
fitModel->plotOn( frame_pho1ClusterTime_SmearToData, RooFit::Name("pho1ClusterTime_SmearToData_all"), RooFit::Components("fitModel"), RooFit::LineColor(kRed) );
frame_pho1ClusterTime_SmearToData->SetName("pho1ClusterTime_SmearToData_frame");
frame_pho1ClusterTime_SmearToData->SetMaximum(150.0*frame_pho1ClusterTime_SmearToData->GetMaximum());
frame_pho1ClusterTime_SmearToData->SetMinimum(0.1);
frame_pho1ClusterTime_SmearToData->Draw();
TLegend * leg_pho1ClusterTime_SmearToData = new TLegend(0.18, 0.7, 0.93, 0.89);
leg_pho1ClusterTime_SmearToData->SetNColumns(3);
leg_pho1ClusterTime_SmearToData->SetBorderSize(0);
leg_pho1ClusterTime_SmearToData->SetTextSize(0.03);
leg_pho1ClusterTime_SmearToData->SetLineColor(1);
leg_pho1ClusterTime_SmearToData->SetLineStyle(1);
leg_pho1ClusterTime_SmearToData->SetLineWidth(1);
leg_pho1ClusterTime_SmearToData->SetFillColor(0);
leg_pho1ClusterTime_SmearToData->SetFillStyle(1001);
leg_pho1ClusterTime_SmearToData->AddEntry("pho1ClusterTime_SmearToData_data","data","lep");
leg_pho1ClusterTime_SmearToData->AddEntry("pho1ClusterTime_SmearToData_GJets","#gamma + jets","l");
leg_pho1ClusterTime_SmearToData->AddEntry("pho1ClusterTime_SmearToData_QCD","QCD","l");
leg_pho1ClusterTime_SmearToData->AddEntry("pho1ClusterTime_SmearToData_all","combined fit","l");
leg_pho1ClusterTime_SmearToData->Draw();
myC->SetTitle("");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/fit_bkgonly_pho1ClusterTime_SmearToData.pdf");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/fit_bkgonly_pho1ClusterTime_SmearToData.png");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/fit_bkgonly_pho1ClusterTime_SmearToData.C");
RooPlot * frame_MET = MET.frame(0, 1000.0, 100);
data->plotOn( frame_MET, RooFit::Name("MET_data") );
fitModel->plotOn( frame_MET, RooFit::Name("MET_GJets"), RooFit::Components("rpGJets"), RooFit::LineColor(kAzure + 7) );
fitModel->plotOn( frame_MET, RooFit::Name("MET_QCD"), RooFit::Components("rpQCD"), RooFit::LineColor(kOrange - 9) );
fitModel->plotOn( frame_MET, RooFit::Name("MET_all"), RooFit::Components("fitModel"), RooFit::LineColor(kRed) );
frame_MET->SetName("MET_frame");
frame_MET->SetMaximum(150.0*frame_MET->GetMaximum());
frame_MET->SetMinimum(0.1);
frame_MET->Draw();
TLegend * leg_MET = new TLegend(0.18, 0.7, 0.93, 0.89);
leg_MET->SetNColumns(3);
leg_MET->SetBorderSize(0);
leg_MET->SetTextSize(0.03);
leg_MET->SetLineColor(1);
leg_MET->SetLineStyle(1);
leg_MET->SetLineWidth(1);
leg_MET->SetFillColor(0);
leg_MET->SetFillStyle(1001);
leg_MET->AddEntry("MET_data","data","lep");
leg_MET->AddEntry("MET_GJets","#gamma + jets","l");
leg_MET->AddEntry("MET_QCD","QCD","l");
leg_MET->AddEntry("MET_all","combined fit","l");
leg_MET->Draw();
myC->SetTitle("");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/fit_bkgonly_MET.pdf");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/fit_bkgonly_MET.png");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/fit_bkgonly_MET.C");
RooPlot * frame_nGJets_LL = nGJets.frame(fracGJets-3.0*fracGJetsErr, fracGJets+3.0*fracGJetsErr, 100);
RooAbsReal* pll_nGJets = nll->createProfile(nGJets) ;
nll->plotOn(frame_nGJets_LL, RooFit::ShiftToZero()) ;
pll_nGJets->plotOn(frame_nGJets_LL, RooFit::LineColor(kRed)) ;
frame_nGJets_LL->SetName("nGJets_frame_Likelihood");
RooPlot * frame_nQCD_LL = nQCD.frame(fracQCD-3.0*fracQCDErr, fracQCD+3.0*fracQCDErr, 100);
RooAbsReal* pll_nQCD = nll->createProfile(nQCD) ;
nll->plotOn(frame_nQCD_LL, RooFit::ShiftToZero()) ;
pll_nQCD->plotOn(frame_nQCD_LL, RooFit::LineColor(kRed)) ;
frame_nQCD_LL->SetName("nQCD_frame_Likelihood");
myC->SetLogy(0);
myC->SetLogz(1);
myC->SetTheta(69.64934);
myC->SetPhi(-51.375);
TH2F * ph2 = new TH2F("fit2D","; #gamma cluster time (ns); #slash{E}_{T} (GeV); PDF",50,-5,5,50,0,500);
fitModel->fillHistogram(ph2, RooArgList(pho1ClusterTime_SmearToData, MET));
ph2->GetXaxis()->SetTitleOffset(2.0);
ph2->GetXaxis()->CenterTitle(kTRUE);
ph2->GetYaxis()->SetTitleOffset(2.0);
ph2->GetYaxis()->CenterTitle(kTRUE);
ph2->GetZaxis()->SetTitleOffset(1.8);
ph2->GetZaxis()->SetRangeUser(1e-8, 0.1);
ph2->Draw("SURF1");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/fit_bkgonly_2D_pdf.pdf");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/fit_bkgonly_2D_pdf.png");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/fit_bkgonly_2D_pdf.C");
ws->import(*data);
ws->import(*rhGJets);
ws->import(*rhQCD);
ws->import(*fitModel);
ws->import(*frame_pho1ClusterTime_SmearToData);
ws->import(*frame_MET);
// ws->import(*frame_2D);
ws->import(*frame_nGJets_LL);
ws->import(*frame_nQCD_LL);
ws->import(*fres);
return ws;
};
RooWorkspace* Fit2DMETTimeDataBkgSig( TH2F * h2Data, TH2F * h2GJets, TH2F * h2QCD, TH2F * h2Sig, float fracGJets, float fracQCD, TString modelName, TString modelTitle, bool useToy, TString outPlotsDir)
{
RooWorkspace* ws = new RooWorkspace( "ws", "" );
// define variables
RooRealVar pho1ClusterTime_SmearToData("pho1ClusterTime_SmearToData","#gamma cluster time ",-15.0,15.0,"ns");
RooRealVar MET("MET","#slash{E}_{T} ",0,1000,"GeV");
double npoints = 1.0*h2Data->Integral();
RooRealVar nGJets ("nGJets", "nGJets", fracGJets);
nGJets.setConstant(kTRUE);
RooRealVar nQCD ("nQCD", "nQCD", fracQCD);
nQCD.setConstant(kTRUE);
//RooDataHist
RooDataHist* data = new RooDataHist("data", "data", RooArgSet(pho1ClusterTime_SmearToData, MET), h2Data);
RooDataHist* rhGJets = new RooDataHist("rhGJets", "rhGJets", RooArgSet(pho1ClusterTime_SmearToData, MET), h2GJets);
RooDataHist* rhGJets_temp = new RooDataHist("rhGJets_temp", "rhGJets_temp", RooArgSet(pho1ClusterTime_SmearToData, MET), h2GJets);
RooDataHist* rhQCD = new RooDataHist("rhQCD", "rhQCD", RooArgSet(pho1ClusterTime_SmearToData, MET), h2QCD);
RooDataHist* rhQCD_temp = new RooDataHist("rhQCD_temp", "rhQCD_temp", RooArgSet(pho1ClusterTime_SmearToData, MET), h2QCD);
RooDataHist* rhSig = new RooDataHist("rhSig", "rhSig", RooArgSet(pho1ClusterTime_SmearToData, MET), h2Sig);
//fill iempty background Histgrams bins with tiny value to allow fluctuation in generated toy data
for(int i=0;i<data->numEntries() ; i++)
{
rhGJets_temp->get(i);
rhQCD_temp->get(i);
float weight_rhGJets = rhGJets_temp->weight();
float weight_rhQCD = rhQCD_temp->weight();
if(weight_rhGJets< 1e-5) rhGJets_temp->set(1e-3);
if(weight_rhQCD< 1e-5) rhQCD_temp->set(1e-3);
}
//RooDataHist -> RooHistPdf
RooHistPdf * rpGJets_temp = new RooHistPdf("rpGJets_temp", "rpGJets_temp", RooArgSet(pho1ClusterTime_SmearToData, MET), *rhGJets_temp, 0);
RooHistPdf * rpQCD_temp = new RooHistPdf("rpQCD_temp", "rpQCD_temp", RooArgSet(pho1ClusterTime_SmearToData, MET), *rhQCD_temp, 0);
//RooHistPdf -> RooAbsPdf
RooAbsPdf * fitModelBkg_temp = new RooAddPdf("fitModelBkg_temp", "fitModelBkg_temp", RooArgSet(*rpGJets_temp, *rpQCD_temp), RooArgSet(nGJets, nQCD));
//create toy data
//TRandom3* r3 = new TRandom3(0);
//double npoints = r3->PoissonD(h2Data->Integral());
//RooDataHist* data_toy = fitModelBkg->generateBinned(RooArgSet(pho1ClusterTime_SmearToData, MET), npoints, RooFit::ExpectedData());
RooDataHist* data_toy = fitModelBkg_temp->generateBinned(RooArgSet(pho1ClusterTime_SmearToData, MET), npoints);
data_toy->SetName("data_toy");
//to avoid zero likelihood, fill empty template bins with tiny values
for(int i=0;i<data->numEntries() ; i++)
{
data->get(i);
data_toy->get(i);
rhGJets->get(i);
rhQCD->get(i);
rhSig->get(i);
float weight_data = data->weight();
float weight_data_toy = data_toy->weight();
float weight_rhGJets = rhGJets->weight();
float weight_rhQCD = rhQCD->weight();
float weight_rhSig = rhSig->weight();
if((weight_rhSig < 1e-5) && ((useToy ? weight_data_toy : weight_data) > 0))
{
rhSig->set(1e-3);
}
if((weight_rhGJets + weight_rhQCD < 1e-5) && ((useToy ? weight_data_toy : weight_data) > 0))
{
rhGJets->set(1e-3);
rhQCD->set(1e-3);
}
}
//new pdf after fill empty bins
RooHistPdf * rpGJets = new RooHistPdf("rpGJets", "rpGJets", RooArgSet(pho1ClusterTime_SmearToData, MET), *rhGJets, 0);
RooHistPdf * rpQCD = new RooHistPdf("rpQCD", "rpQCD", RooArgSet(pho1ClusterTime_SmearToData, MET), *rhQCD, 0);
RooHistPdf * rpSig = new RooHistPdf("rpSig", "rpSig", RooArgSet(pho1ClusterTime_SmearToData, MET), *rhSig, 0);
RooAbsPdf * fitModelBkg = new RooAddPdf("fitModelBkg", "fitModelBkg", RooArgSet(*rpGJets, *rpQCD), RooArgSet(nGJets, nQCD));
RooRealVar nSig ("rpSig_yield", "rpSig_yield", 0.0, 0.0, 0.1*npoints);
nSig.setConstant(kFALSE);
RooRealVar nBkg ("fitModelBkg_yield", "fitModelBkg_yield", npoints, 0.0, 1.5*npoints);
nBkg.setConstant(kFALSE);
RooAbsPdf * fitModelBkgSig = new RooAddPdf("fitModelBkgSig", "fitModelBkgSig", RooArgSet(*fitModelBkg, *rpSig), RooArgSet(nBkg, nSig));
//RooAbsPdf * fitModelBkg = new RooAddPdf("fitModelBkg", "fitModelBkg", RooArgSet(*rpGJets, *rpQCD), RooArgSet(nGJets, nQCD));
//fit
RooAbsReal* nll = fitModelBkgSig->createNLL(*data, RooFit::NumCPU(8)) ;
RooFitResult * fres;
if(useToy) fres = fitModelBkgSig->fitTo( *data_toy, RooFit::Extended( kTRUE ), RooFit::Save( kTRUE ));
else fres = fitModelBkgSig->fitTo( *data, RooFit::Extended( kTRUE ), RooFit::Save( kTRUE ));
nGJets.Print();
nQCD.Print();
nBkg.Print();
nSig.Print();
//draw some plot-s
TCanvas *myC = new TCanvas( "myC", "myC", 200, 10, 800, 800 );
myC->SetHighLightColor(2);
myC->SetFillColor(0);
myC->SetBorderMode(0);
myC->SetBorderSize(2);
myC->SetLeftMargin( leftMargin );
myC->SetRightMargin( rightMargin );
myC->SetTopMargin( topMargin );
myC->SetBottomMargin( bottomMargin );
myC->SetFrameBorderMode(0);
myC->SetFrameBorderMode(0);
myC->SetLogy(1);
RooPlot * frame_pho1ClusterTime_SmearToData = pho1ClusterTime_SmearToData.frame(-15.0, 15.0, 100);
if(useToy) data_toy->plotOn( frame_pho1ClusterTime_SmearToData, RooFit::Name("pho1ClusterTime_SmearToData_data") );
else data->plotOn( frame_pho1ClusterTime_SmearToData, RooFit::Name("pho1ClusterTime_SmearToData_data") );
fitModelBkgSig->plotOn( frame_pho1ClusterTime_SmearToData, RooFit::Name("pho1ClusterTime_SmearToData_Bkg"), RooFit::Components("fitModelBkg"), RooFit::LineColor(kBlue) );
fitModelBkgSig->plotOn( frame_pho1ClusterTime_SmearToData, RooFit::Name("pho1ClusterTime_SmearToData_Sig"), RooFit::Components("rpSig"), RooFit::LineColor(kGreen) );
fitModelBkgSig->plotOn( frame_pho1ClusterTime_SmearToData, RooFit::Name("pho1ClusterTime_SmearToData_all"), RooFit::Components("fitModelBkgSig"), RooFit::LineColor(kRed) );
frame_pho1ClusterTime_SmearToData->SetName("pho1ClusterTime_SmearToData_frame");
frame_pho1ClusterTime_SmearToData->SetMaximum(1000.0*frame_pho1ClusterTime_SmearToData->GetMaximum());
frame_pho1ClusterTime_SmearToData->SetMinimum(1e-3);
frame_pho1ClusterTime_SmearToData->Draw();
TLegend * leg_pho1ClusterTime_SmearToData = new TLegend(0.18, 0.7, 0.93, 0.89);
leg_pho1ClusterTime_SmearToData->SetNColumns(2);
leg_pho1ClusterTime_SmearToData->SetBorderSize(0);
leg_pho1ClusterTime_SmearToData->SetTextSize(0.03);
leg_pho1ClusterTime_SmearToData->SetLineColor(1);
leg_pho1ClusterTime_SmearToData->SetLineStyle(1);
leg_pho1ClusterTime_SmearToData->SetLineWidth(1);
leg_pho1ClusterTime_SmearToData->SetFillColor(0);
leg_pho1ClusterTime_SmearToData->SetFillStyle(1001);
leg_pho1ClusterTime_SmearToData->AddEntry("pho1ClusterTime_SmearToData_data","data","lep");
leg_pho1ClusterTime_SmearToData->AddEntry("pho1ClusterTime_SmearToData_Bkg","#gamma + jets/QCD bkg","l");
leg_pho1ClusterTime_SmearToData->AddEntry("pho1ClusterTime_SmearToData_Sig",modelTitle,"l");
leg_pho1ClusterTime_SmearToData->AddEntry("pho1ClusterTime_SmearToData_all","combined fit","l");
leg_pho1ClusterTime_SmearToData->Draw();
myC->SetTitle("");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_fit_bkgsig_pho1ClusterTime_SmearToData.pdf");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_fit_bkgsig_pho1ClusterTime_SmearToData.png");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_fit_bkgsig_pho1ClusterTime_SmearToData.C");
RooPlot * frame_MET = MET.frame(0, 1000.0, 100);
if(useToy) data_toy->plotOn( frame_MET, RooFit::Name("MET_data") );
else data->plotOn( frame_MET, RooFit::Name("MET_data") );
fitModelBkgSig->plotOn( frame_MET, RooFit::Name("MET_Bkg"), RooFit::Components("fitModelBkg"), RooFit::LineColor(kBlue) );
fitModelBkgSig->plotOn( frame_MET, RooFit::Name("MET_Sig"), RooFit::Components("rpSig"), RooFit::LineColor(kGreen) );
fitModelBkgSig->plotOn( frame_MET, RooFit::Name("MET_all"), RooFit::Components("fitModelBkgSig"), RooFit::LineColor(kRed) );
frame_MET->SetName("MET_frame");
frame_MET->SetMaximum(1000.0*frame_MET->GetMaximum());
frame_MET->SetMinimum(1e-3);
frame_MET->Draw();
TLegend * leg_MET = new TLegend(0.18, 0.7, 0.93, 0.89);
leg_MET->SetNColumns(2);
leg_MET->SetBorderSize(0);
leg_MET->SetTextSize(0.03);
leg_MET->SetLineColor(1);
leg_MET->SetLineStyle(1);
leg_MET->SetLineWidth(1);
leg_MET->SetFillColor(0);
leg_MET->SetFillStyle(1001);
leg_MET->AddEntry("MET_data","data","lep");
leg_MET->AddEntry("MET_Bkg","#gamma + jets/QCD bkg","l");
leg_MET->AddEntry("MET_Sig",modelTitle,"l");
leg_MET->AddEntry("MET_all","combined fit","l");
leg_MET->Draw();
myC->SetTitle("");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_fit_bkgsig_MET.pdf");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_fit_bkgsig_MET.png");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_fit_bkgsig_MET.C");
RooPlot * frame_nBkg_LL = nBkg.frame(0.0, 1.5*npoints, 100);
RooAbsReal* pll_nBkg = nll->createProfile(nBkg) ;
nll->plotOn(frame_nBkg_LL, RooFit::ShiftToZero()) ;
pll_nBkg->plotOn(frame_nBkg_LL, RooFit::LineColor(kRed)) ;
frame_nBkg_LL->SetName("nBkg_frame_Likelihood");
RooPlot * frame_nSig_LL = nSig.frame(0.0, 0.1*npoints, 100);
RooAbsReal* pll_nSig = nll->createProfile(nSig) ;
nll->plotOn(frame_nSig_LL, RooFit::ShiftToZero()) ;
pll_nSig->plotOn(frame_nSig_LL, RooFit::LineColor(kRed)) ;
frame_nSig_LL->SetName("nSig_frame_Likelihood");
myC->SetLogy(0);
myC->SetLogz(1);
myC->SetTheta(69.64934);
myC->SetPhi(-51.375);
TH2F * ph2 = new TH2F("fit2D","; #gamma cluster time (ns); #slash{E}_{T} (GeV); PDF",100,-15,15,100,0,1000);
fitModelBkgSig->fillHistogram(ph2, RooArgList(pho1ClusterTime_SmearToData, MET));
ph2->GetXaxis()->SetTitleOffset(2.0);
ph2->GetXaxis()->SetRangeUser(-5,5);
ph2->GetXaxis()->CenterTitle(kTRUE);
ph2->GetYaxis()->SetTitleOffset(2.0);
ph2->GetYaxis()->SetRangeUser(0,500);
ph2->GetYaxis()->CenterTitle(kTRUE);
ph2->GetZaxis()->SetTitleOffset(1.8);
ph2->GetZaxis()->SetRangeUser(1e-8, 0.1);
ph2->Draw("SURF1");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_fit_bkgsig_2D_pdf.pdf");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_fit_bkgsig_2D_pdf.png");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_fit_bkgsig_2D_pdf.C");
TH2F * ph2_bkg = new TH2F("fit2D_bkg","; #gamma cluster time (ns); #slash{E}_{T} (GeV); PDF",100,-15,15,100,0,1000);
fitModelBkg->fillHistogram(ph2_bkg, RooArgList(pho1ClusterTime_SmearToData, MET));
ph2_bkg->GetXaxis()->SetTitleOffset(2.0);
ph2_bkg->GetXaxis()->SetRangeUser(-5,5);
ph2_bkg->GetXaxis()->CenterTitle(kTRUE);
ph2_bkg->GetYaxis()->SetTitleOffset(2.0);
ph2_bkg->GetYaxis()->SetRangeUser(0,500);
ph2_bkg->GetYaxis()->CenterTitle(kTRUE);
ph2_bkg->GetZaxis()->SetTitleOffset(1.8);
ph2_bkg->GetZaxis()->SetRangeUser(1e-8, 0.1);
ph2_bkg->Draw("SURF1");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_fit_bkgonly_2D_pdf.pdf");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_fit_bkgonly_2D_pdf.png");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_fit_bkgonly_2D_pdf.C");
TH2F * h2Data_toy = new TH2F("h2Data_toy","; #gamma cluster time (ns); #slash{E}_{T} (GeV); Events",100,-15,15,100,0,1000);
data_toy->fillHistogram(h2Data_toy, RooArgList(pho1ClusterTime_SmearToData, MET));
h2Data_toy->GetXaxis()->SetTitleOffset(2.0);
h2Data_toy->GetXaxis()->SetRangeUser(-5,5);
h2Data_toy->GetXaxis()->CenterTitle(kTRUE);
h2Data_toy->GetYaxis()->SetTitleOffset(2.0);
h2Data_toy->GetYaxis()->SetRangeUser(0,500);
h2Data_toy->GetYaxis()->CenterTitle(kTRUE);
h2Data_toy->GetZaxis()->SetTitleOffset(1.8);
h2Data_toy->GetZaxis()->SetRangeUser(0, 1e3);
h2Data_toy->Draw("LEGO2");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_data_toy_2D.pdf");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_data_toy_2D.png");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_data_toy_2D.C");
h2Data->GetXaxis()->SetTitleOffset(2.0);
h2Data->GetXaxis()->SetRangeUser(-10,15);
h2Data->GetXaxis()->CenterTitle(kTRUE);
h2Data->GetYaxis()->SetTitleOffset(2.0);
h2Data->GetYaxis()->SetRangeUser(0.1,600);
h2Data->GetYaxis()->CenterTitle(kTRUE);
h2Data->GetZaxis()->SetTitleOffset(1.8);
h2Data->GetZaxis()->SetRangeUser(0, 1e3);
h2Data->Draw("LEGO2");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_data_2D_LEGO2.pdf");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_data_2D_LEGO2.png");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_data_2D_LEGO2.C");
h2Data->GetYaxis()->SetTitleOffset(1.8);
h2Data->GetXaxis()->SetTitleOffset(1.5);
h2Data->Draw("COLZ");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_data_2D_COLZ.pdf");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_data_2D_COLZ.png");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_data_2D_COLZ.C");
//h2Data->SetMarkerStyle(7);
h2Data->Draw("");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_data_2D.pdf");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_data_2D.png");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_data_2D.C");
ws->import(*data);
ws->import(*data_toy);
ws->import(*rhGJets);
ws->import(*rhQCD);
ws->import(*rpSig);
ws->import(*fitModelBkg);
ws->import(nSig);
ws->import(nBkg);
//ws->import(*fitModelBkgSig);
ws->import(*frame_pho1ClusterTime_SmearToData);
ws->import(*frame_MET);
ws->import(*frame_nBkg_LL);
ws->import(*frame_nSig_LL);
ws->import(*fres);
//MakeDataCard(modelName, ws);
return ws;
};
RooWorkspace* Fit1DMETTimeDataBkgSig( TH1F * h1Data, TH1F * h1GJets, TH1F * h1QCD, TH1F * h1Sig, float lumi,float fracGJets, float fracQCD, TString modelName, TString modelTitle, TString outPlotsDir)
{
RooWorkspace* ws = new RooWorkspace( "ws_combine", "ws_combine" );
// define variables
RooRealVar bin("bin","2D bin",0,h1Data->GetSize()-2,"");
cout<<"DEBUG: bin size = "<<h1Data->GetSize()-2<<endl;
double npoints = 1.0*h1Data->Integral();
RooRealVar nGJets ("nGJets", "nGJets", fracGJets);
nGJets.setConstant(kTRUE);
RooRealVar nQCD ("nQCD", "nQCD", fracQCD);
nQCD.setConstant(kTRUE);
//RooDataHist
RooDataHist* data = new RooDataHist("data", "data", RooArgSet(bin), h1Data);
RooDataHist* rhGJets = new RooDataHist("rhGJets", "rhGJets", RooArgSet(bin), h1GJets);
RooDataHist* rhQCD = new RooDataHist("rhQCD", "rhQCD", RooArgSet(bin), h1QCD);
RooDataHist* rhSig = new RooDataHist("rhSig", "rhSig", RooArgSet(bin), h1Sig);
//pdf
RooHistPdf * rpGJets = new RooHistPdf("rpGJets", "rpGJets", RooArgSet(bin), *rhGJets, 0);
RooHistPdf * rpQCD = new RooHistPdf("rpQCD", "rpQCD", RooArgSet(bin), *rhQCD, 0);
RooHistPdf * rpSig = new RooHistPdf("rpSig", "rpSig", RooArgSet(bin), *rhSig, 0);
RooAbsPdf * fitModelBkg = new RooAddPdf("fitModelBkg", "fitModelBkg", RooArgSet(*rpGJets, *rpQCD), RooArgSet(nGJets, nQCD));
RooRealVar nSig ("rpSig_yield", "rpSig_yield", 0.0, 0.0, 0.1*npoints);
nSig.setConstant(kFALSE);
RooRealVar nBkg ("fitModelBkg_yield", "fitModelBkg_yield", npoints, 0.0, 1.5*npoints);
nBkg.setConstant(kFALSE);
RooAbsPdf * fitModelBkgSig = new RooAddPdf("fitModelBkgSig", "fitModelBkgSig", RooArgSet(*fitModelBkg, *rpSig), RooArgSet(nBkg, nSig));
//RooAbsPdf * fitModelBkg = new RooAddPdf("fitModelBkg", "fitModelBkg", RooArgSet(*rpGJets, *rpQCD), RooArgSet(nGJets, nQCD));
//fit
RooAbsReal* nll = fitModelBkgSig->createNLL(*data, RooFit::NumCPU(8)) ;
RooFitResult * fres;
fres = fitModelBkgSig->fitTo( *data, RooFit::Extended( kTRUE ), RooFit::Save( kTRUE ));
cout<<"DEBUG: fit 1D result === "<<endl;
nGJets.Print();
nQCD.Print();
nBkg.Print();
nSig.Print();
//draw some plot-s
TCanvas *myC = new TCanvas( "myC", "myC", 200, 10, 800, 800 );
myC->SetHighLightColor(2);
myC->SetFillColor(0);
myC->SetBorderMode(0);
myC->SetBorderSize(2);
myC->SetLeftMargin( leftMargin );
myC->SetRightMargin( rightMargin );
myC->SetTopMargin( topMargin );
myC->SetBottomMargin( bottomMargin );
myC->SetFrameBorderMode(0);
myC->SetFrameBorderMode(0);
myC->SetLogy(1);
RooPlot * frame_bin = bin.frame(0, h1Data->GetSize()-2, h1Data->GetSize()-2);
data->plotOn( frame_bin, RooFit::Name("bin_data") );
fitModelBkgSig->plotOn( frame_bin, RooFit::Name("bin_Bkg"), RooFit::Components("fitModelBkg"), RooFit::LineColor(kBlue) );
fitModelBkgSig->plotOn( frame_bin, RooFit::Name("bin_Sig"), RooFit::Components("rpSig"), RooFit::LineColor(kGreen) );
fitModelBkgSig->plotOn( frame_bin, RooFit::Name("bin_all"), RooFit::Components("fitModelBkgSig"), RooFit::LineColor(kRed) );
frame_bin->SetName("bin_frame");
frame_bin->SetMaximum(1000.0*frame_bin->GetMaximum());
frame_bin->SetMinimum(1e-3);
frame_bin->SetTitle("");
frame_bin->Draw();
TLegend * leg_bin = new TLegend(0.18, 0.7, 0.93, 0.89);
leg_bin->SetNColumns(2);
leg_bin->SetBorderSize(0);
leg_bin->SetTextSize(0.03);
leg_bin->SetLineColor(1);
leg_bin->SetLineStyle(1);
leg_bin->SetLineWidth(1);
leg_bin->SetFillColor(0);
leg_bin->SetFillStyle(1001);
leg_bin->AddEntry("bin_data","data","lep");
leg_bin->AddEntry("bin_Bkg","#gamma + jets/QCD bkg","l");
leg_bin->AddEntry("bin_Sig",modelTitle,"l");
leg_bin->AddEntry("bin_all","combined fit","l");
leg_bin->Draw();
DrawCMS(myC, 13, lumi);
myC->SetTitle("");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_fit_bkgsig_bin.pdf");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_fit_bkgsig_bin.png");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_fit_bkgsig_bin.C");
RooPlot * frame_nBkg_LL = nBkg.frame(0.0, 1.5*npoints, 100);
RooAbsReal* pll_nBkg = nll->createProfile(nBkg) ;
nll->plotOn(frame_nBkg_LL, RooFit::ShiftToZero()) ;
pll_nBkg->plotOn(frame_nBkg_LL, RooFit::LineColor(kRed)) ;
frame_nBkg_LL->SetName("nBkg_frame_Likelihood");
RooPlot * frame_nSig_LL = nSig.frame(0.0, 0.1*npoints, 100);
RooAbsReal* pll_nSig = nll->createProfile(nSig) ;
nll->plotOn(frame_nSig_LL, RooFit::ShiftToZero()) ;
pll_nSig->plotOn(frame_nSig_LL, RooFit::LineColor(kRed)) ;
frame_nSig_LL->SetName("nSig_frame_Likelihood");
myC->SetLogy(0);
myC->SetLogz(1);
myC->SetTheta(69.64934);
myC->SetPhi(-51.375);
ws->import(*data);
ws->import(*rhGJets);
ws->import(*rhQCD);
ws->import(*rpSig);
ws->import(*fitModelBkg);
ws->import(nSig);
ws->import(nBkg);
//ws->import(*fitModelBkgSig);
ws->import(*frame_bin);
ws->import(*frame_nBkg_LL);
ws->import(*frame_nSig_LL);
ws->import(*fres);
//MakeDataCard(modelName, ws);
return ws;
};
RooWorkspace* Fit1DMETTimeDataBkgSig( TH1F * h1Data, TH1F * h1GJets, TH1F * h1QCD, TH1F * h1Sig, TH1F * h1EWK, float lumi,float fracGJets, float fracQCD, TString modelName, TString modelTitle, TString outPlotsDir)
{
RooWorkspace* ws = new RooWorkspace( "ws_combine", "ws_combine" );
// define variables
RooRealVar bin("bin","2D bin",0,h1Data->GetSize()-2,"");
cout<<"DEBUG: bin size = "<<h1Data->GetSize()-2<<endl;
double npoints = 1.0*h1Data->Integral();
RooRealVar nGJets ("nGJets", "nGJets", fracGJets*(1.0-1.0*h1EWK->Integral()/npoints));
nGJets.setConstant(kTRUE);
RooRealVar nQCD ("nQCD", "nQCD", fracQCD*(1.0-1.0*h1EWK->Integral()/npoints));
nQCD.setConstant(kTRUE);
RooRealVar nEWK_fromMC ("nEWK_fromMC", "nEWK_fromMC", 1.0*h1EWK->Integral()/npoints);
nEWK_fromMC.setConstant(kTRUE);
//RooDataHist
RooDataHist* data = new RooDataHist("data", "data", RooArgSet(bin), h1Data);
RooDataHist* rhGJets = new RooDataHist("rhGJets", "rhGJets", RooArgSet(bin), h1GJets);
RooDataHist* rhQCD = new RooDataHist("rhQCD", "rhQCD", RooArgSet(bin), h1QCD);
RooDataHist* rhSig = new RooDataHist("rhSig", "rhSig", RooArgSet(bin), h1Sig);
RooDataHist* rhEWK = new RooDataHist("rhEWK", "rhEWK", RooArgSet(bin), h1EWK);
//pdf
RooHistPdf * rpGJets = new RooHistPdf("rpGJets", "rpGJets", RooArgSet(bin), *rhGJets, 0);
RooHistPdf * rpQCD = new RooHistPdf("rpQCD", "rpQCD", RooArgSet(bin), *rhQCD, 0);
RooHistPdf * rpSig = new RooHistPdf("rpSig", "rpSig", RooArgSet(bin), *rhSig, 0);
RooHistPdf * rpEWK = new RooHistPdf("rpEWK", "rpEWK", RooArgSet(bin), *rhEWK, 0);
RooRealVar nSig ("rpSig_yield", "rpSig_yield", 0.0, 0.0, 0.1*npoints);
//RooRealVar nSig ("rpSig_yield", "rpSig_yield", 0.0000001, 0.0, 1.0*h1Sig->Integral());
nSig.setConstant(kFALSE);
//RooRealVar nEWK ("rpEWK_yield", "rpEWK_yield", 1.0*h1EWK->Integral(), 0.0, 2.0*h1EWK->Integral());
//RooRealVar nEWK ("rpEWK_yield", "rpEWK_yield", 0.05*h1EWK->Integral(), 0.0, 0.1*h1EWK->Integral());
RooRealVar nEWK ("rpEWK_yield", "rpEWK_yield", 1.0*h1EWK->Integral(), 0.0, 1.0*npoints);
nEWK.setConstant(kFALSE);
RooRealVar nQCDGJets ("fitModelQCDGJets_yield", "fitModelQCDGJets_yield", npoints-1.0*h1EWK->Integral(), 0.0, 1.5*npoints);
nQCDGJets.setConstant(kFALSE);
RooAbsPdf * fitModelQCDGJets = new RooAddPdf("fitModelQCDGJets", "fitModelQCDGJets", RooArgSet(*rpGJets, *rpQCD), RooArgSet(nGJets, nQCD));
RooAbsPdf * fitModelBkgSig = new RooAddPdf("fitModelBkgSig", "fitModelBkgSig", RooArgSet(*fitModelQCDGJets, *rpEWK, *rpSig), RooArgSet(nQCDGJets, nEWK, nSig));
//fit
RooAbsReal* nll = fitModelBkgSig->createNLL(*data, RooFit::NumCPU(8)) ;
RooFitResult * fres;
fres = fitModelBkgSig->fitTo( *data, RooFit::Extended( kTRUE ), RooFit::Save( kTRUE ));
cout<<"DEBUG: fit 1D result === "<<endl;
nGJets.Print();
nQCD.Print();
nQCDGJets.Print();
nEWK.Print();
nSig.Print();
//draw some plot-s
TCanvas *myC = new TCanvas( "myC", "myC", 200, 10, 800, 800 );
myC->SetHighLightColor(2);
myC->SetFillColor(0);
myC->SetBorderMode(0);
myC->SetBorderSize(2);
myC->SetLeftMargin( leftMargin );
myC->SetRightMargin( rightMargin );
myC->SetTopMargin( topMargin );
myC->SetBottomMargin( bottomMargin );
myC->SetFrameBorderMode(0);
myC->SetFrameBorderMode(0);
myC->SetLogy(1);
RooPlot * frame_bin = bin.frame(0, h1Data->GetSize()-2, h1Data->GetSize()-2);
data->plotOn( frame_bin, RooFit::Name("bin_data") );
fitModelBkgSig->plotOn( frame_bin, RooFit::Name("bin_QCDGJets"), RooFit::Components("fitModelQCDGJets"), RooFit::LineColor(kBlue) );
fitModelBkgSig->plotOn( frame_bin, RooFit::Name("bin_EWK"), RooFit::Components("rpEWK"), RooFit::LineColor(kOrange) );
fitModelBkgSig->plotOn( frame_bin, RooFit::Name("bin_Sig"), RooFit::Components("rpSig"), RooFit::LineColor(kGreen) );
fitModelBkgSig->plotOn( frame_bin, RooFit::Name("bin_all"), RooFit::Components("fitModelBkgSig"), RooFit::LineColor(kRed) );
frame_bin->SetName("bin_frame");
frame_bin->SetMaximum(1000.0*frame_bin->GetMaximum());
frame_bin->SetMinimum(1e-3);
frame_bin->SetTitle("");
frame_bin->Draw();
TLegend * leg_bin = new TLegend(0.18, 0.7, 0.93, 0.89);
leg_bin->SetNColumns(2);
leg_bin->SetBorderSize(0);
leg_bin->SetTextSize(0.03);
leg_bin->SetLineColor(1);
leg_bin->SetLineStyle(1);
leg_bin->SetLineWidth(1);
leg_bin->SetFillColor(0);
leg_bin->SetFillStyle(1001);
leg_bin->AddEntry("bin_data","data","lep");
leg_bin->AddEntry("bin_QCDGJets","#gamma + jets/QCD bkg","l");
leg_bin->AddEntry("bin_EWK","EWK bkg","l");
leg_bin->AddEntry("bin_Sig",modelTitle,"l");
leg_bin->AddEntry("bin_all","combined fit","l");
leg_bin->Draw();
DrawCMS(myC, 13, lumi);
myC->SetTitle("");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_fit_bkgsig_bin.pdf");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_fit_bkgsig_bin.png");
myC->SaveAs("fit_results/2016/"+outPlotsDir+"/"+modelName+"_fit_bkgsig_bin.C");
RooPlot * frame_nQCDGJets_LL = nQCDGJets.frame(0.0, 1.5*npoints, 100);
RooAbsReal* pll_nQCDGJets = nll->createProfile(nQCDGJets) ;
nll->plotOn(frame_nQCDGJets_LL, RooFit::ShiftToZero()) ;
pll_nQCDGJets->plotOn(frame_nQCDGJets_LL, RooFit::LineColor(kRed)) ;
frame_nQCDGJets_LL->SetName("nQCDGJets_frame_Likelihood");
RooPlot * frame_nEWK_LL = nEWK.frame(0.0, 1.5*npoints, 100);
RooAbsReal* pll_nEWK = nll->createProfile(nEWK) ;
nll->plotOn(frame_nEWK_LL, RooFit::ShiftToZero()) ;
pll_nEWK->plotOn(frame_nEWK_LL, RooFit::LineColor(kRed)) ;
frame_nEWK_LL->SetName("nEWK_frame_Likelihood");
RooPlot * frame_nSig_LL = nSig.frame(0.0, 0.1*npoints, 100);
RooAbsReal* pll_nSig = nll->createProfile(nSig) ;
nll->plotOn(frame_nSig_LL, RooFit::ShiftToZero()) ;
pll_nSig->plotOn(frame_nSig_LL, RooFit::LineColor(kRed)) ;
frame_nSig_LL->SetName("nSig_frame_Likelihood");
myC->SetLogy(0);
myC->SetLogz(1);
myC->SetTheta(69.64934);
myC->SetPhi(-51.375);
ws->import(*data);
ws->import(*rhGJets);
ws->import(*rhQCD);
ws->import(*rpSig);
ws->import(*rpEWK);
ws->import(*fitModelQCDGJets);
ws->import(nSig);
ws->import(nEWK);
ws->import(nQCDGJets);
//ws->import(*fitModelBkgSig);
ws->import(*frame_bin);
ws->import(*frame_nQCDGJets_LL);
ws->import(*frame_nEWK_LL);
ws->import(*frame_nSig_LL);
ws->import(*fres);
//MakeDataCard(modelName, ws);
return ws;
};
RooWorkspace* GenerateToyData( TH1F * h1Data, TH1F * h1GJets, TH1F * h1QCD, TH1F * h1Sig, TH1F * h1EWK, float fracGJets, float fracQCD, float scaleSig)
{
RooWorkspace* ws = new RooWorkspace( "ws_combine", "ws_combine" );
// define variables
RooRealVar bin("bin","2D bin",0,h1Data->GetSize()-2,"");
cout<<"DEBUG: bin size = "<<h1Data->GetSize()-2<<endl;
double npoints = 1.0*h1Data->Integral();
RooRealVar nGJets ("nGJets", "nGJets", fracGJets*(1.0-1.0*h1EWK->Integral()/npoints));
nGJets.setConstant(kTRUE);
RooRealVar nQCD ("nQCD", "nQCD", fracQCD*(1.0-1.0*h1EWK->Integral()/npoints));
nQCD.setConstant(kTRUE);
RooRealVar nSig ("nSig", "nSig", scaleSig*h1Sig->Integral()/npoints);
nSig.setConstant(kTRUE);
RooRealVar nEWK_fromMC ("nEWK_fromMC", "nEWK_fromMC", 1.0*h1EWK->Integral()/npoints);
nEWK_fromMC.setConstant(kTRUE);
//RooDataHist
RooDataHist* data = new RooDataHist("data", "data", RooArgSet(bin), h1Data);
RooDataHist* rhGJets = new RooDataHist("rhGJets", "rhGJets", RooArgSet(bin), h1GJets);
RooDataHist* rhQCD = new RooDataHist("rhQCD", "rhQCD", RooArgSet(bin), h1QCD);
RooDataHist* rhSig = new RooDataHist("rhSig", "rhSig", RooArgSet(bin), h1Sig);
RooDataHist* rhEWK = new RooDataHist("rhEWK", "rhEWK", RooArgSet(bin), h1EWK);
//pdf
RooHistPdf * rpGJets = new RooHistPdf("rpGJets", "rpGJets", RooArgSet(bin), *rhGJets, 0);
RooHistPdf * rpQCD = new RooHistPdf("rpQCD", "rpQCD", RooArgSet(bin), *rhQCD, 0);
RooHistPdf * rpSig = new RooHistPdf("rpSig", "rpSig", RooArgSet(bin), *rhSig, 0);
RooHistPdf * rpEWK = new RooHistPdf("rpEWK", "rpEWK", RooArgSet(bin), *rhEWK, 0);
//create toy data
//TRandom3* r3 = new TRandom3(0);
//double npoints = r3->PoissonD(h1Data->Integral());
//RooDataHist* data_toy = fitModelBkg->generateBinned(RooArgSet(bin), npoints, RooFit::ExpectedData());
RooAbsPdf * fitModelBkg = new RooAddPdf("fitModelBkg", "fitModelBkg", RooArgSet(*rpGJets, *rpQCD, *rpEWK, *rpSig), RooArgSet(nGJets, nQCD, nEWK_fromMC, nSig));
RooDataHist* data_toy = fitModelBkg->generateBinned(RooArgSet(bin), npoints);
data_toy->SetName("data_toy");
ws->import(*data_toy);
return ws;
};
void MakeDataCard(TString modelName, RooWorkspace *ws, float N_obs, float N_bkg, float N_sig, TString outDataCardsDir)
{
std::string _modelName ((const char*) modelName);
std::string _wsName ((const char*)ws->GetName());
std::string _outDataCardsDir ((const char*) outDataCardsDir);
FILE * m_outfile = fopen(("fit_results/2016/"+_outDataCardsDir+"/DelayedPhotonCard_"+_modelName+".txt").c_str(), "w");
cout<<"Writting fit result to datacard: "<<("fit_results/2016/"+_outDataCardsDir+"/DelayedPhotonCard_"+_modelName+".txt").c_str()<<endl;
fprintf(m_outfile, "imax 1\n");
fprintf(m_outfile, "jmax 1\n");
fprintf(m_outfile, "kmax *\n");
fprintf(m_outfile, "---------------\n");
//fprintf(m_outfile, "shapes background bin1 fit_combineWS_%s.root %s:fitModelBkg %s:fitModelBkg_$SYSTEMATIC\n", _modelName.c_str(), _wsName.c_str(), _wsName.c_str());
fprintf(m_outfile, "shapes background bin1 fit_combineWS_%s.root %s:rpBkg %s:rpBkg_$SYSTEMATIC\n", _modelName.c_str(), _wsName.c_str(), _wsName.c_str());
fprintf(m_outfile, "shapes signal bin1 fit_combineWS_%s.root %s:rpSig %s:rpSig_$SYSTEMATIC\n", _modelName.c_str(), _wsName.c_str(), _wsName.c_str());
fprintf(m_outfile, "shapes data_obs bin1 fit_combineWS_%s.root %s:data\n", _modelName.c_str(), _wsName.c_str());
fprintf(m_outfile, "---------------\n");
fprintf(m_outfile, "bin bin1\n");
fprintf(m_outfile, "observation %6.2f\n", N_obs);
fprintf(m_outfile, "------------------------------\n");
fprintf(m_outfile, "bin bin1 bin1\n");
fprintf(m_outfile, "process signal background\n");
fprintf(m_outfile, "process 0 1\n");
fprintf(m_outfile, "rate %10.6f %6.2f\n", N_sig, N_bkg);
fprintf(m_outfile, "--------------------------------\n");
//fprintf(m_outfile, "lumi lnN 1.057 1.057\n");
fclose(m_outfile);
};
void MakeDataCard(TString modelName, RooWorkspace *ws, float N_obs, float N_QCDGJets, float N_EWK, float N_sig, TString outDataCardsDir)
{
std::string _modelName ((const char*) modelName);
std::string _wsName ((const char*)ws->GetName());
std::string _outDataCardsDir ((const char*) outDataCardsDir);
FILE * m_outfile = fopen(("fit_results/2016/"+_outDataCardsDir+"/DelayedPhotonCard_"+_modelName+".txt").c_str(), "w");
cout<<"Writting fit result to datacard: "<<("fit_results/2016/"+_outDataCardsDir+"/DelayedPhotonCard_"+_modelName+".txt").c_str()<<endl;
fprintf(m_outfile, "imax 1\n");
fprintf(m_outfile, "jmax 2\n");
fprintf(m_outfile, "kmax *\n");
fprintf(m_outfile, "---------------\n");
//fprintf(m_outfile, "shapes background bin1 fit_combineWS_%s.root %s:fitModelBkg %s:fitModelBkg_$SYSTEMATIC\n", _modelName.c_str(), _wsName.c_str(), _wsName.c_str());
fprintf(m_outfile, "shapes QCDGJets bin1 fit_combineWS_%s.root %s:rpQCDGJets %s:rpQCDGJets_$SYSTEMATIC\n", _modelName.c_str(), _wsName.c_str(), _wsName.c_str());
fprintf(m_outfile, "shapes EWK bin1 fit_combineWS_%s.root %s:rpEWK %s:rpEWK_$SYSTEMATIC\n", _modelName.c_str(), _wsName.c_str(), _wsName.c_str());
fprintf(m_outfile, "shapes signal bin1 fit_combineWS_%s.root %s:rpSig %s:rpSig_$SYSTEMATIC\n", _modelName.c_str(), _wsName.c_str(), _wsName.c_str());
fprintf(m_outfile, "shapes data_obs bin1 fit_combineWS_%s.root %s:data\n", _modelName.c_str(), _wsName.c_str());
fprintf(m_outfile, "---------------\n");
fprintf(m_outfile, "bin bin1\n");
fprintf(m_outfile, "observation %6.2f\n", N_obs);
fprintf(m_outfile, "--------------------------------------------\n");
fprintf(m_outfile, "bin bin1 bin1 bin1\n");
fprintf(m_outfile, "process signal QCDGJets EWK\n");
fprintf(m_outfile, "process 0 1 2\n");
fprintf(m_outfile, "rate %10.6f %6.2f %6.2f\n", N_sig, N_QCDGJets, N_EWK);
fprintf(m_outfile, "--------------------------------------------\n");
//fprintf(m_outfile, "lumi lnN 1.057 1.057\n");
fclose(m_outfile);
};
void MakeDataCardABCD(TH2F * h2_rate_Data, TH2F * h2_rate_Sig, TH2F * h2MCBkg, TH1F *h1DataShape_Time, TH1F *h1DataShape_MET, int Nbins_time, int Nbins_MET, TString modelName, TString outDataCardsDir, bool blindABD)
{
std::string _modelName ((const char*) modelName);
std::string _outDataCardsDir ((const char*) outDataCardsDir);
FILE * m_outfile = fopen(("fit_results/2016ABCD/"+_outDataCardsDir+"/DelayedPhotonCard_"+_modelName+".txt").c_str(), "w");
cout<<"Writting fit result to datacard: "<<("fit_results/2016ABCD/"+_outDataCardsDir+"/DelayedPhotonCard_"+_modelName+".txt").c_str()<<endl;
fprintf(m_outfile, "imax %d\n", Nbins_time*Nbins_MET);
fprintf(m_outfile, "jmax 1\n");
fprintf(m_outfile, "kmax *\n");
fprintf(m_outfile, "---------------\n");
fprintf(m_outfile, "---------------\n");
fprintf(m_outfile, "bin ");
for(int iM=0;iM<Nbins_MET;iM++)
{
for(int iT=0; iT<Nbins_time; iT++)
{
fprintf(m_outfile, "ch%d%d ",iT, iM);
}
}
fprintf(m_outfile, "\n");
fprintf(m_outfile, "observation ");
if(blindABD)
{
for(int iM=1;iM<=Nbins_MET;iM++)
{
float rate_iM_iT1 = h2MCBkg->GetBinContent(1, 1) * h1DataShape_MET->GetBinContent(iM)/h1DataShape_MET->GetBinContent(1);
for(int iT=1; iT<=Nbins_time; iT++)
{
fprintf(m_outfile, "%6.2f ", rate_iM_iT1 * h1DataShape_Time->GetBinContent(iT)/h1DataShape_Time->GetBinContent(1));
}
}
}
else
{
for(int iM=1;iM<=Nbins_MET;iM++)
{
for(int iT=1; iT<=Nbins_time; iT++)
{
fprintf(m_outfile, "%6.2f ",h2_rate_Data->GetBinContent(iT, iM));
}
}
}
fprintf(m_outfile, "\n");
fprintf(m_outfile, "------------------------------\n");
fprintf(m_outfile, "bin ");
for(int iM=0;iM<Nbins_MET;iM++)
{
for(int iT=0; iT<Nbins_time; iT++)
{
fprintf(m_outfile, "ch%d%d ch%d%d ",iT, iM, iT, iM);
}
}
fprintf(m_outfile, "\n");
fprintf(m_outfile, "process ");
for(int iM=0;iM<Nbins_MET;iM++)
{
for(int iT=0; iT<Nbins_time; iT++)
{
fprintf(m_outfile, "sig bkg ");
}
}
fprintf(m_outfile, "\n");
fprintf(m_outfile, "process ");
for(int iM=0;iM<Nbins_MET;iM++)
{
for(int iT=0; iT<Nbins_time; iT++)
{
fprintf(m_outfile, "0 1 ");
}
}
fprintf(m_outfile, "\n");
fprintf(m_outfile, "rate ");
for(int iM=1;iM<=Nbins_MET;iM++)
{
for(int iT=1; iT<=Nbins_time; iT++)
{
fprintf(m_outfile, "%e 1.0 ",h2_rate_Sig->GetBinContent(iT, iM));
}
}
fprintf(m_outfile, "\n");
fprintf(m_outfile, "--------------------------------\n");
//rate parameters
//fprintf(m_outfile, "NA rateParam ch00 bkg %6.2f\n", h2_rate_Data->GetBinContent(1, 1));
fprintf(m_outfile, "NA_2016 rateParam ch00 bkg %6.2f\n", h2MCBkg->GetBinContent(1, 1));
for(int iT=1;iT<Nbins_time; iT++)
{
//fprintf(m_outfile, "NA rateParam ch%d0 bkg %6.2f\n", iT,h2_rate_Data->GetBinContent(1, 1));
fprintf(m_outfile, "NA_2016 rateParam ch%d0 bkg %6.2f\n", iT,h2MCBkg->GetBinContent(1, 1));
//fprintf(m_outfile, "x%d rateParam ch%d0 bkg %e\n", iT, iT, h2_rate_Data->GetBinContent(iT+1, 1)/h2_rate_Data->GetBinContent(1, 1));
fprintf(m_outfile, "x%d_2016 rateParam ch%d0 bkg %e\n", iT, iT, h1DataShape_Time->GetBinContent(iT+1)/h1DataShape_Time->GetBinContent(1));
}
for(int iM=1;iM<Nbins_MET; iM++)
{
//fprintf(m_outfile, "NA rateParam ch0%d bkg %6.2f\n", iM, h2_rate_Data->GetBinContent(1, 1));
fprintf(m_outfile, "NA_2016 rateParam ch0%d bkg %6.2f\n", iM, h2MCBkg->GetBinContent(1, 1));
//fprintf(m_outfile, "y%d rateParam ch0%d bkg %e\n", iM, iM, h2_rate_Data->GetBinContent(1, iM+1)/h2_rate_Data->GetBinContent(1, 1));
fprintf(m_outfile, "y%d_2016 rateParam ch0%d bkg %e\n", iM, iM, h1DataShape_MET->GetBinContent(iM+1)/h1DataShape_MET->GetBinContent(1));
}
for(int iM=1;iM<Nbins_MET;iM++)
{
for(int iT=1; iT<Nbins_time; iT++)
{
//fprintf(m_outfile, "NA rateParam ch%d%d bkg %6.2f\n", iT, iM, h2_rate_Data->GetBinContent(1, 1));
fprintf(m_outfile, "NA_2016 rateParam ch%d%d bkg %6.2f\n", iT, iM, h2MCBkg->GetBinContent(1, 1));
//fprintf(m_outfile, "x%d rateParam ch%d%d bkg %e\n", iT, iT, iM, h2_rate_Data->GetBinContent(iT+1, 1)/h2_rate_Data->GetBinContent(1, 1));
fprintf(m_outfile, "x%d_2016 rateParam ch%d%d bkg %e\n", iT, iT, iM, h1DataShape_Time->GetBinContent(iT+1)/h1DataShape_Time->GetBinContent(1));
//fprintf(m_outfile, "y%d rateParam ch%d%d bkg %e\n", iM, iT, iM, h2_rate_Data->GetBinContent(1, iM+1)/h2_rate_Data->GetBinContent(1, 1));
fprintf(m_outfile, "y%d_2016 rateParam ch%d%d bkg %e\n", iM, iT, iM, h1DataShape_MET->GetBinContent(iM+1)/h1DataShape_MET->GetBinContent(1));
}
}
fclose(m_outfile);
};
void AddSystematics_Norm_ABCD(TH2F * h2_sys, int Nbins_time, int Nbins_MET, TString sysName, TString distType, TString modelName, TString outDataCardsDir, bool sysOnSig)
{
std::string _modelName ((const char*) modelName);
std::string _sysName ((const char*) sysName);
std::string _distType ((const char*) distType);
std::string _outDataCardsDir ((const char*) outDataCardsDir);
FILE * m_outfile = fopen(("fit_results/2016ABCD/"+_outDataCardsDir+"/DelayedPhotonCard_"+_modelName+".txt").c_str(), "a");
cout<<"Adding Systematic "<<sysName<<" to datacard: "<<("fit_results/2016ABCD/"+_outDataCardsDir+"/DelayedPhotonCard_"+_modelName+".txt").c_str()<<endl;
fprintf(m_outfile, "%s %s ", _sysName.c_str(), _distType.c_str());
for(int iM=1;iM<=Nbins_MET;iM++)
{
for(int iT=1; iT<=Nbins_time; iT++)
{
if(abs(h2_sys->GetBinContent(iT, iM)-1.0)<0.000001) fprintf(m_outfile, "- - ");
else
{
if(sysOnSig) fprintf(m_outfile, "%10.6f - ", h2_sys->GetBinContent(iT, iM));
else fprintf(m_outfile, "- %10.6f ", h2_sys->GetBinContent(iT, iM));
}
}
}
fprintf(m_outfile, "\n");
fclose(m_outfile);
}
void AddSystematics_Norm(TString modelName, float N_bkg, float N_sig, TString outDataCardsDir, TString sysName, TString distType)
{
std::string _modelName ((const char*) modelName);
std::string _sysName ((const char*) sysName);
std::string _distType ((const char*) distType);
std::string _outDataCardsDir ((const char*) outDataCardsDir);
FILE * m_outfile = fopen(("fit_results/2016/"+_outDataCardsDir+"/DelayedPhotonCard_"+_modelName+".txt").c_str(), "a");
cout<<"Adding Systematic "<<sysName<<" to datacard: "<<("fit_results/2016/"+_outDataCardsDir+"/DelayedPhotonCard_"+_modelName+".txt").c_str()<<endl;
cout<<"N_bkg: "<<N_bkg<<" N_sig: "<<N_sig<<endl;
if(N_sig > 0.001 && N_bkg > 0.001) fprintf(m_outfile, "%s %s %10.6f %10.6f\n", _sysName.c_str(), _distType.c_str(), N_sig, N_bkg); // for both signal and backgrounds
else if(N_sig > 0.001) fprintf(m_outfile, "%s %s %10.6f -\n", _sysName.c_str(), _distType.c_str(), N_sig); //for signal only
else if(N_bkg > 0.001) fprintf(m_outfile, "%s %s - %10.6f\n", _sysName.c_str(), _distType.c_str(), N_bkg); //for background only
fclose(m_outfile);
}
void AddSystematics_Norm(TString modelName, float N_QCDGJets, float N_EWK, float N_sig, TString outDataCardsDir, TString sysName, TString distType)
{
std::string _modelName ((const char*) modelName);
std::string _sysName ((const char*) sysName);
std::string _distType ((const char*) distType);
std::string _outDataCardsDir ((const char*) outDataCardsDir);
FILE * m_outfile = fopen(("fit_results/2016/"+_outDataCardsDir+"/DelayedPhotonCard_"+_modelName+".txt").c_str(), "a");
cout<<"Adding Systematic "<<sysName<<" to datacard: "<<("fit_results/2016/"+_outDataCardsDir+"/DelayedPhotonCard_"+_modelName+".txt").c_str()<<endl;
cout<<"N_QCDGJets: "<<N_QCDGJets<<" N_EWK: "<<N_EWK<<" N_sig: "<<N_sig<<endl;
if(N_sig > 0.001 && N_QCDGJets > 0.001 && N_EWK) fprintf(m_outfile, "%s %s %10.6f %10.6f %10.6f\n", _sysName.c_str(), _distType.c_str(), N_sig, N_QCDGJets, N_EWK); // for both signal and backgrounds
else
{
if(N_sig > 0.001 && N_QCDGJets > 0.001) fprintf(m_outfile, "%s %s %10.6f %10.6f -\n", _sysName.c_str(), _distType.c_str(), N_sig, N_QCDGJets); //for signal + QCDGJets
else if(N_sig > 0.001 && N_EWK > 0.001) fprintf(m_outfile, "%s %s %10.6f - %10.6f\n", _sysName.c_str(), _distType.c_str(), N_sig, N_EWK); //for signal + EWK
else if(N_QCDGJets > 0.001 && N_EWK > 0.001) fprintf(m_outfile, "%s %s - %10.6f %10.6f\n", _sysName.c_str(), _distType.c_str(), N_QCDGJets, N_EWK); //for QCDGJets + EWK
else if(N_sig > 0.001) fprintf(m_outfile, "%s %s %10.6f - -\n", _sysName.c_str(), _distType.c_str(), N_sig); //for signal only
else if(N_QCDGJets > 0.001) fprintf(m_outfile, "%s %s - %10.6f -\n", _sysName.c_str(), _distType.c_str(), N_QCDGJets); //for QCDGJetsnal only
else if(N_EWK > 0.001) fprintf(m_outfile, "%s %s - - %10.6f\n", _sysName.c_str(), _distType.c_str(), N_EWK); //for EWKnal only
}
fclose(m_outfile);
}
void AddSystematics_shape(TString modelName, TString N_bkg, TString N_sig, TString outDataCardsDir, TString sysName, TString distType)
{
std::string _modelName ((const char*) modelName);
std::string _N_bkg ((const char*) N_bkg);
std::string _N_sig ((const char*) N_sig);
std::string _sysName ((const char*) sysName);
std::string _distType ((const char*) distType);
std::string _outDataCardsDir ((const char*) outDataCardsDir);
FILE * m_outfile = fopen(("fit_results/2016/"+_outDataCardsDir+"/DelayedPhotonCard_"+_modelName+".txt").c_str(), "a");
cout<<"Adding Systematic "<<sysName<<" to datacard: "<<("fit_results/2016/"+_outDataCardsDir+"/DelayedPhotonCard_"+_modelName+".txt").c_str()<<endl;
cout<<"N_bkg: "<<N_bkg<<" N_sig: "<<N_sig<<endl;
fprintf(m_outfile, "%s %s %s %s\n", _sysName.c_str(), _distType.c_str(), _N_sig.c_str(), _N_bkg.c_str());
fclose(m_outfile);
}
void AddSystematics_shape(TString modelName, TString N_QCDGJets, TString N_EWK, TString N_sig, TString outDataCardsDir, TString sysName, TString distType)
{
std::string _modelName ((const char*) modelName);
std::string _N_QCDGJets ((const char*) N_QCDGJets);
std::string _N_EWK ((const char*) N_EWK);
std::string _N_sig ((const char*) N_sig);
std::string _sysName ((const char*) sysName);
std::string _distType ((const char*) distType);
std::string _outDataCardsDir ((const char*) outDataCardsDir);
FILE * m_outfile = fopen(("fit_results/2016/"+_outDataCardsDir+"/DelayedPhotonCard_"+_modelName+".txt").c_str(), "a");
cout<<"Adding Systematic "<<sysName<<" to datacard: "<<("fit_results/2016/"+_outDataCardsDir+"/DelayedPhotonCard_"+_modelName+".txt").c_str()<<endl;
cout<<"N_QCDGJets: "<<N_QCDGJets<<" N_EWK: "<<N_EWK<<" N_sig: "<<N_sig<<endl;
fprintf(m_outfile, "%s %s %s %s %s\n", _sysName.c_str(), _distType.c_str(), _N_sig.c_str(), _N_QCDGJets.c_str(), _N_EWK.c_str());
fclose(m_outfile);
}
void Fit1DMETTimeBiasTest( TH1F * h1Data, TH1F * h1Bkg, TH1F * h1Sig, float SoverB, int ntoys, TString modelName, float lumi, TString outBiasDir)
{
TString sSoverB = Form("%7.5f", SoverB);
std::string _SoverB ((const char*) sSoverB);
std::string _modelName ((const char*) modelName);
std::string _outBiasDir ((const char*) outBiasDir);
TFile *f_Out_bias = new TFile(("fit_results/2016/"+_outBiasDir+"/bias_"+_modelName+"_"+_SoverB+".root").c_str(),"recreate");
RooRandom::randomGenerator()->SetSeed( 0 );
double _bias, _biasNorm;
double _Ns_fit, _Ns_sigma, _Ns, _Nbkg_fit, _Nbkg_sigma, _Nbkg;
int _status, _covStatus;
TTree* outTree = new TTree("biasTree", "tree containing bias tests");
outTree->Branch("bias", &_bias, "bias/D");
outTree->Branch("biasNorm", &_biasNorm, "biasNorm/D");
outTree->Branch("Ns_fit", &_Ns_fit, "Ns_fit/D");
outTree->Branch("Ns_sigma", &_Ns_sigma, "Ns_sigma/D");
outTree->Branch("Ns", &_Ns, "Ns/D");
outTree->Branch("Nbkg_fit", &_Nbkg_fit, "Nbkg_fit/D");
outTree->Branch("Nbkg_sigma", &_Nbkg_sigma, "Nbkg_sigma/D");
outTree->Branch("Nbkg", &_Nbkg, "Nbkg/D");
outTree->Branch("status", &_status, "status/I");
outTree->Branch("covStatus", &_covStatus, "covStatus/I");
RooRealVar bin("bin","2D bin",0,h1Data->GetSize()-2,"");
RooDataHist* data = new RooDataHist("data", "data", RooArgSet(bin), h1Data);
RooDataHist* rhBkg = new RooDataHist("rhBkg", "rhBkg", RooArgSet(bin), h1Bkg);
RooDataHist* rhSig = new RooDataHist("rhSig", "rhSig", RooArgSet(bin), h1Sig);
TRandom3* r3 = new TRandom3(0);
for(int ind_toy = 0; ind_toy<ntoys; ind_toy++)
{
double nBkg_true = r3->PoissonD(h1Data->Integral());
double nSig_true = r3->PoissonD(SoverB*h1Data->Integral());
double npoints = nBkg_true + nSig_true;
RooRealVar nSig ("rpSig_yield", "rpSig_yield", nSig_true, 0.0, 1.5*npoints);
nSig.setConstant(kFALSE);
RooRealVar nBkg ("fitModelBkg_yield", "fitModelBkg_yield", nBkg_true, 0.0, 1.5*npoints);
nBkg.setConstant(kFALSE);
//RooHistPdf -> RooHistPdf
RooHistPdf * rpSig = new RooHistPdf("rpSig", "rpSig", RooArgSet(bin), *rhSig, 0);
RooHistPdf * rpBkg = new RooHistPdf("rpBkg", "rpBkg", RooArgSet(bin), *rhBkg, 0);
RooAbsPdf * fitModelBkgSig = new RooAddPdf("fitModelBkgSig", "fitModelBkgSig", RooArgSet(*rpBkg, *rpSig), RooArgSet(nBkg, nSig));
//create toy data
RooDataHist* data_toy = fitModelBkgSig->generateBinned(RooArgSet(bin), npoints);
data_toy->SetName("data_toy");
//fit
RooAbsReal* nll = fitModelBkgSig->createNLL(*data_toy, RooFit::NumCPU(8)) ;
RooFitResult * fres;
fres = fitModelBkgSig->fitTo( *data_toy, RooFit::Extended( kTRUE ), RooFit::Save( kTRUE ));
//nBkg.Print();
//nSig.Print();
_status = fres->status();
_covStatus = fres->covQual();
_Ns = nSig_true;
_Ns_fit = nSig.getVal();
_Ns_sigma = nSig.getError();
_Nbkg = nBkg_true;
_Nbkg_fit = nBkg.getVal();
_Nbkg_sigma = nBkg.getError();
_bias = _Ns - _Ns_fit;
if(abs(_Ns_sigma) >0.0) _biasNorm = _bias/_Ns_sigma;
else _biasNorm = -999.0;
std::cout << "toy iteration:" << ind_toy << std::endl;
outTree->Fill();
delete nll;
}
outTree->Write();
//draw bias plot
TCanvas *myC = new TCanvas( "myC", "myC", 200, 10, 800, 800 );
myC->SetHighLightColor(2);
myC->SetFillColor(0);
myC->SetBorderMode(0);
myC->SetBorderSize(2);
myC->SetLeftMargin( leftMargin );
myC->SetRightMargin( rightMargin );
myC->SetTopMargin( topMargin );
myC->SetBottomMargin( bottomMargin );
myC->SetFrameBorderMode(0);
myC->SetFrameBorderMode(0);
myC->SetTitle("");
TH1F * histBias = new TH1F("hbias","hbias", 100, -15, 10);
outTree->Draw("-1.0*biasNorm>>hbias","status==0 && covStatus==3");
histBias->SetTitle("");
histBias->SetLineWidth(2);
histBias->Draw();
histBias->GetXaxis()->SetTitleSize( axisTitleSize );
histBias->GetXaxis()->SetTitleOffset( axisTitleOffset );
histBias->GetYaxis()->SetTitleSize( axisTitleSize );
histBias->GetYaxis()->SetTitleOffset( axisTitleOffset );
histBias->GetXaxis()->SetTitle("(N_{s}^{fit} - N_{s}^{true})/#sigma_{N_{s}}");
histBias->GetYaxis()->SetTitle("events");
DrawCMS(myC, 13, lumi);
myC->SaveAs(("fit_results/2016/"+_outBiasDir+"/bias_"+_modelName+"_"+_SoverB+"_plot.png").c_str());
myC->SaveAs(("fit_results/2016/"+_outBiasDir+"/bias_"+_modelName+"_"+_SoverB+"_plot.pdf").c_str());
myC->SaveAs(("fit_results/2016/"+_outBiasDir+"/bias_"+_modelName+"_"+_SoverB+"_plot.C").c_str());
};
double CalculateMETTimeSignificance(TH1F * h1Bkg, TH1F * h1Sig)
{
//reference: https://arxiv.org/pdf/1007.1727.pdf
int nsteps = 2e3;
double mu_steps = 1.0e-2;
double minNll = 9999999;
double bestMu = -1.0;
//get the best mu to maximize the log likelyhood, see equation 6 in reference
for(int i = 0; i < nsteps; i++)
{
double mu = mu_steps*i;
double nll = 0;
for(int j=1; j<=h1Bkg->GetSize()-2;j++)
{
double s = h1Sig->GetBinContent(j);
double b = h1Bkg->GetBinContent(j);
nll += - ( (s+b)*std::log(mu*s+b) - (mu*s+b));
}
if(nll < minNll)
{
minNll = nll;
bestMu = mu;
}
}
//calculate the significance with the best mu obtained: q = sqrt(2(s+b)ln(1+us/b)-us)
double qnot = 0.0;
double qnot2 = 0.0;
for(int j=1; j<=h1Bkg->GetSize()-2;j++)
{
double s = h1Sig->GetBinContent(j);
double b = h1Bkg->GetBinContent(j);
qnot2 += 2.0* ( (s+b) * std::log (1.0 + bestMu*s/b) - bestMu*s);
}
if(qnot2 > 0.0) qnot = sqrt(qnot2);
return qnot;
};
double Fit1DMETTimeSignificance(TH1F *h1Data, TH1F * h1Bkg, TH1F * h1Sig, int ntoys)
{
RooMsgService::instance().setSilentMode(true);
RooRandom::randomGenerator()->SetSeed( 0 );
RooRealVar bin("bin","2D bin",0,h1Bkg->GetSize()-2,"");
RooDataHist* rhData = new RooDataHist("rhData", "rhData", RooArgSet(bin), h1Data);
RooDataHist* rhBkg = new RooDataHist("rhBkg", "rhBkg", RooArgSet(bin), h1Bkg);
RooDataHist* rhSig = new RooDataHist("rhSig", "rhSig", RooArgSet(bin), h1Sig);
TRandom3* r3 = new TRandom3(0);
double sumQnot = 0.0;
double maxQnot = -9999.0;
double minQnot = 9999.0;
int nGoodTry = 0 ;
int nTrys = 5;
double _Ns_fit, _Nbkg_fit;
for(int ind_Try = 0; (ind_Try< 10*nTrys) && (nGoodTry < nTrys); ind_Try++)
{
double nBkg_hist = h1Bkg->Integral();//r3->PoissonD(h1Bkg->Integral());
//double nSig_hist = r3->PoissonD(h1Sig->Integral());
double nSig_hist = h1Sig->Integral();
double npoints = h1Data->Integral();
double frac_Sig = nSig_hist/(nSig_hist+nBkg_hist);
double frac_Bkg = nBkg_hist/(nSig_hist+nBkg_hist);
double nSig_exp = npoints*frac_Sig;
double nBkg_exp = npoints*frac_Bkg;
RooRealVar nSig ("rpSig_yield", "rpSig_yield", nSig_exp, 0.0, 1.5*npoints);
nSig.setConstant(kFALSE);
RooRealVar nBkg ("fitModelBkg_yield", "fitModelBkg_yield", nBkg_exp, 0.0, 1.5*npoints);
nBkg.setConstant(kFALSE);
//RooHistPdf -> RooHistPdf
RooHistPdf * rpSig = new RooHistPdf("rpSig", "rpSig", RooArgSet(bin), *rhSig, 0);
RooHistPdf * rpBkg = new RooHistPdf("rpBkg", "rpBkg", RooArgSet(bin), *rhBkg, 0);
RooAbsPdf * fitModelBkgSig = new RooAddPdf("fitModelBkgSig", "fitModelBkgSig", RooArgSet(*rpBkg, *rpSig), RooArgSet(nBkg, nSig));
//create toy data
//RooDataHist* data_toy = fitModelBkgSig->generateBinned(RooArgSet(bin), npoints);
//data_toy->SetName("data_toy");
//fit
RooAbsReal* nll = fitModelBkgSig->createNLL(*rhData, RooFit::NumCPU(8)) ;
RooFitResult * fres;
fres = fitModelBkgSig->fitTo( *rhData, RooFit::Extended( kTRUE ), RooFit::Save( kTRUE ));
if(fres->status() == 0)
{
_Ns_fit = nSig.getVal();
_Nbkg_fit = nBkg.getVal();
if( _Nbkg_fit > 0.0 && _Ns_fit < 3.0*nSig_exp)
{
double qnot2 = 2.0*( (_Ns_fit + _Nbkg_fit) * std::log (1.0 + _Ns_fit/_Nbkg_fit) - _Ns_fit);
double qnot = 0.0;
if(qnot2 < 0.0) continue;
//if(qnot2<1e-8) qnot = 1e-4*sqrt(1e8 * qnot);
else qnot = sqrt(qnot2);
cout<<"DEBUG calculate significance: Ns (Ns_exp) = "<<_Ns_fit<<" ( "<<nSig_exp<<" ) Nb (Nb_exp) = "<<_Nbkg_fit<<" ( "<<nBkg_exp<<" ) qnot = "<<qnot<<" qnot2 = "<<qnot2<<endl;
nGoodTry ++;
sumQnot += qnot;
if(qnot > maxQnot) maxQnot = qnot;
if(qnot < minQnot) minQnot = qnot;
}
}
delete nll;
}
if(nGoodTry > 2) return (sumQnot - maxQnot - minQnot)/(nGoodTry-2);
else return 0.0;
};
void OptimizeBinning(std::vector<int> &timeBin, std::vector<int> &metBin, TH2F * h2Bkg, TH2F *h2Sig, float time_Low, float time_High, int time_N_fine, float met_Low, float met_High, int met_N_fine, TString modelName, TString ourBinningDir)
{
std::string _modelName ((const char*) modelName);
std::string _outBinningDir ((const char*) ourBinningDir);
//TFile *f_Out_binning = new TFile(("fit_results/2016/binning/binning_"+_modelName+".root").c_str(),"recreate");
bool debug_thisFunc = true;
//initial status: 1 bin in time, and 1 bin in MET
int nTotal_time = h2Bkg->GetNbinsX();
int nTotal_met = h2Bkg->GetNbinsY();
cout<<" binning optimization... "<<endl;
cout<<"time bins # "<<nTotal_time<<endl;
cout<<"met bins # "<<nTotal_met<<endl;
double maxSignificance = -9999.0;
bool isConverged_time = false;
bool isConverged_met = false;
bool isConverged_all = false;
/*************generate toy data**************/
TH2F * h2Data = new TH2F("h2Data","h2Data", time_N_fine, time_Low, time_High, met_N_fine, met_Low, met_High);
TH1F * h1ConvertData = new TH1F("h1ConvertData","h1ConvertData", time_N_fine*met_N_fine, 0, time_N_fine*met_N_fine);
TH1 * h1ConvertData_toy = new TH1F("h1ConvertData_toy","h1ConvertData_toy", time_N_fine*met_N_fine, 0, time_N_fine*met_N_fine);
//2D to 1D convert
for(int i=1;i<=time_N_fine;i++)
{
for(int j=1;j<=met_N_fine;j++)
{
int thisBin = (i-1)*met_N_fine + j;
h1ConvertData->SetBinContent(thisBin, h2Bkg->GetBinContent(i,j) + h2Sig->GetBinContent(i,j));
}
}
if(debug_thisFunc) cout<<"binning optimization: 2D data to 1D data conversion : "<<h2Bkg->Integral()+h2Sig->Integral()<<" -> "<<h1ConvertData->Integral()<<endl;
//toy generation
RooRealVar bin("bin","2D bin",0,h1ConvertData->GetSize()-2,"");
RooDataHist* rhData = new RooDataHist("rhData", "rhData", RooArgSet(bin), h1ConvertData);
RooHistPdf * rpData = new RooHistPdf("rpData", "rpData", RooArgSet(bin), *rhData, 0);
//create toy data
TRandom3* r3 = new TRandom3(0);
double nData_toy = r3->PoissonD(h1ConvertData->Integral());
RooDataHist* data_toy = rpData->generateBinned(RooArgSet(bin), nData_toy);
data_toy->SetName("data_toy");
h1ConvertData_toy = data_toy->createHistogram("bin", time_N_fine*met_N_fine);
if(debug_thisFunc) cout<<"binning optimization: 1D data vs toy data : "<<h1ConvertData->Integral()<<" -> "<<h1ConvertData_toy->Integral()<<endl;
//1D to 2D convert
for(int i=1;i<=time_N_fine;i++)
{
for(int j=1;j<=met_N_fine;j++)
{
int thisBin = (i-1)*met_N_fine + j;
h2Data->SetBinContent(i, j, h1ConvertData_toy->GetBinContent(thisBin));
}
}
/*************end of toy data****************/
//while( (!isConverged_time) || (!isConverged_met))
TCanvas *myC = new TCanvas( "myC", "myC", 200, 10, 800, 800 );
myC->SetHighLightColor(2);
myC->SetFillColor(0);
myC->SetBorderMode(0);
myC->SetBorderSize(2);
myC->SetLeftMargin( leftMargin );
myC->SetRightMargin( rightMargin );
myC->SetTopMargin( topMargin );
myC->SetBottomMargin( bottomMargin );
myC->SetFrameBorderMode(0);
myC->SetFrameBorderMode(0);
myC->SetTitle("");
int iteration = 0;
while( !isConverged_all )
{
//start spliting in time dimension
int new_idx_time = -99;
int new_idx_met = -99;
if(!isConverged_time)
{
TString s_hist_name = Form("_h1_qnot_time_iter_%d", iteration);
std::string _s_hist_name2 ((const char*) s_hist_name);
std::string _s_hist_name = _modelName+_s_hist_name2;
TH1F * h1_qnot_time = new TH1F(_s_hist_name.c_str(), _s_hist_name.c_str(), time_N_fine, time_Low, time_High);
for(int idx=1;idx<nTotal_time;idx++)
{
double this_time = time_Low + (time_High - time_Low) * (1.0*idx)/(1.0*time_N_fine);
if(this_time < -5.0) continue;//no further binning below -5 ns
//if(std::find(timeBin.begin(), timeBin.end(), idx) != timeBin.end()) continue; // add a new split
int dist_min = 9999;
for(int i=0;i<timeBin.size();i++)
{
if(abs(timeBin[i] - idx) < dist_min) dist_min = abs(timeBin[i] - idx);
}
if(dist_min < 5) continue; // not too narrow binning
std::vector <int> temp_bin_time;
for(int idx_temp : timeBin)
{
temp_bin_time.push_back(idx_temp);
}
temp_bin_time.push_back(idx);
std::sort(temp_bin_time.begin(), temp_bin_time.end());
if(debug_thisFunc) cout<<"DEBUG binningOptimization time: tring to add split at idx = "<<idx<<endl;
for(int inx_temp : temp_bin_time)
{
cout<<inx_temp<<" , ";
}
cout<<endl;
//construct 1D histogram of time and met
TH1F *h1Data = new TH1F ("h1Data","h1Data", (temp_bin_time.size()-1)*(metBin.size()-1), 0, (temp_bin_time.size()-1)*(metBin.size()-1)*1.0);
TH1F *h1Bkg = new TH1F ("h1Bkg","h1Bkg", (temp_bin_time.size()-1)*(metBin.size()-1), 0, (temp_bin_time.size()-1)*(metBin.size()-1)*1.0);
TH1F *h1Sig = new TH1F ("h1Sig","h1Sig", (temp_bin_time.size()-1)*(metBin.size()-1), 0, (temp_bin_time.size()-1)*(metBin.size()-1)*1.0);
for(int iT=1;iT<= temp_bin_time.size()-1; iT++)
{
for(int iM=1;iM<= metBin.size()-1; iM++)
{
int thisBin = (iT-1)*(metBin.size()-1) + iM;
float NData = h2Data->Integral(temp_bin_time[iT-1]+1, temp_bin_time[iT], metBin[iM-1]+1, metBin[iM]);
float NBkg = h2Bkg->Integral(temp_bin_time[iT-1]+1, temp_bin_time[iT], metBin[iM-1]+1, metBin[iM]);
float NSig = h2Sig->Integral(temp_bin_time[iT-1]+1, temp_bin_time[iT], metBin[iM-1]+1, metBin[iM]);
h1Data->SetBinContent(thisBin, NData);
h1Bkg->SetBinContent(thisBin, NBkg);
h1Sig->SetBinContent(thisBin, NSig);
//cout<<"iT = "<<iT<<" iM = "<<iM<<" thiBin = "<<thisBin<<" NBkg = "<<NBkg<<" NSig = "<<NSig<<endl;
}
}
if(debug_thisFunc) cout<<"DEBUG binningOptimization time: validation of 2D conversion (Bkg): "<<h2Bkg->Integral()<<" -> "<<h1Bkg->Integral()<<endl;
if(debug_thisFunc) cout<<"DEBUG binningOptimization time: validation of 2D conversion (Sig): "<<h2Sig->Integral()<<" -> "<<h1Sig->Integral()<<endl;
for(int i=1;i<= (temp_bin_time.size()-1)*(metBin.size()-1); i++)
{
if(h1Bkg->GetBinContent(i) < 1e-3 ) h1Bkg->SetBinContent(i, 1e-3);
if(h1Sig->GetBinContent(i) < 1e-3 ) h1Sig->SetBinContent(i, 1e-3);
//h1Data->SetBinContent(i, h1Bkg->GetBinContent(i) + h1Sig->GetBinContent(i));
}
//double qnot = Fit1DMETTimeSignificance(h1Data, h1Bkg, h1Sig, 10);
double qnot = CalculateMETTimeSignificance(h1Bkg, h1Sig);
if(debug_thisFunc) cout<<"DEBUG binningOptimization time: significance of new split = "<<qnot<<" vs. maxSignificance = "<<maxSignificance<<endl;
if(qnot > 1.000*maxSignificance)
{
maxSignificance = qnot;
new_idx_time = idx;
}
if(qnot>0.001) h1_qnot_time->SetBinContent(idx, qnot);
delete h1Data;
delete h1Bkg;
delete h1Sig;
}
h1_qnot_time->SetLineWidth(2);
h1_qnot_time->SetLineColor(kBlack);
h1_qnot_time->SetTitle("");
h1_qnot_time->GetXaxis()->SetTitle("new split on #gamma cluster time [ns]");
h1_qnot_time->GetYaxis()->SetTitle("q_{0}");
h1_qnot_time->GetYaxis()->SetTitleSize(axisTitleSize);
h1_qnot_time->GetYaxis()->SetRangeUser(0.15, 1.2*h1_qnot_time->GetMaximum());
h1_qnot_time->GetXaxis()->SetRangeUser(0.2+time_Low, time_High-0.2);
h1_qnot_time->GetXaxis()->SetTitleSize(axisTitleSize);
h1_qnot_time->GetYaxis()->SetTitleOffset(axisTitleOffset);
h1_qnot_time->GetXaxis()->SetTitleOffset(axisTitleOffset);
h1_qnot_time->Draw();
for(int ih=0;ih<timeBin.size();ih++)
{
TString s_ih_name = Form("h1_qnot_time_iter_%d_i%d", iteration, ih);
std::string _s_ih_name ((const char*) s_ih_name);
TH1F *h1_temp = new TH1F(_s_ih_name.c_str(), _s_ih_name.c_str(), time_N_fine, time_Low, time_High);
h1_temp->SetBinContent(timeBin[ih], 1.2*h1_qnot_time->GetMaximum());
h1_temp->SetLineWidth(3);
h1_temp->SetLineColor(kRed);
h1_temp->Draw("same");
}
if(new_idx_time > 0)
{
myC->SaveAs(("fit_results/2016/"+_outBinningDir+"/binning_"+_s_hist_name+".pdf").c_str());
myC->SaveAs(("fit_results/2016/"+_outBinningDir+"/binning_"+_s_hist_name+".png").c_str());
myC->SaveAs(("fit_results/2016/"+_outBinningDir+"/binning_"+_s_hist_name+".C").c_str());
if(debug_thisFunc) cout<<"best split point added : "<<new_idx_time<<" maxSignificance = "<<maxSignificance<<endl;
timeBin.push_back(new_idx_time);
std::sort(timeBin.begin(), timeBin.end());
}
else isConverged_time = true;
}
if(!isConverged_met)
{
TString s_hist_name = Form("_h1_qnot_met_iter_%d", iteration);
std::string _s_hist_name2 ((const char*) s_hist_name);
std::string _s_hist_name = _modelName + _s_hist_name2;
TH1F * h1_qnot_met = new TH1F(_s_hist_name.c_str(), _s_hist_name.c_str(), met_N_fine, met_Low, met_High);
for(int idx=1;idx<nTotal_met;idx++)
{
//if(std::find(metBin.begin(), metBin.end(), idx) != metBin.end()) continue; // add a new split
double this_met = met_Low + (met_High - met_Low) * (1.0*idx)/(1.0*met_N_fine);
if(this_met < 50.0) continue;//no further binning below MET 50
int dist_min = 9999;
for(int i=0;i<metBin.size();i++)
{
if(abs(metBin[i] - idx) < dist_min) dist_min = abs(metBin[i] - idx);
}
if(dist_min < 5) continue; // not too narrow binning
std::vector <int> temp_bin_met;
for(int idx_temp : metBin)
{
temp_bin_met.push_back(idx_temp);
}
temp_bin_met.push_back(idx);
std::sort(temp_bin_met.begin(), temp_bin_met.end());
if(debug_thisFunc) cout<<"DEBUG binningOptimization met: tring to add split at idx = "<<idx<<endl;
for(int inx_temp : temp_bin_met)
{
cout<<inx_temp<<" , ";
}
cout<<endl;
//construct 1D histogram of met and time
TH1F *h1Data = new TH1F ("h1Data","h1Data", (temp_bin_met.size()-1)*(timeBin.size()-1), 0, (temp_bin_met.size()-1)*(timeBin.size()-1)*1.0);
TH1F *h1Bkg = new TH1F ("h1Bkg","h1Bkg", (temp_bin_met.size()-1)*(timeBin.size()-1), 0, (temp_bin_met.size()-1)*(timeBin.size()-1)*1.0);
TH1F *h1Sig = new TH1F ("h1Sig","h1Sig", (temp_bin_met.size()-1)*(timeBin.size()-1), 0, (temp_bin_met.size()-1)*(timeBin.size()-1)*1.0);
for(int iT=1;iT<= timeBin.size()-1; iT++)
{
for(int iM=1;iM<= temp_bin_met.size()-1; iM++)
{
int thisBin = (iT-1)*(temp_bin_met.size()-1) + iM;
float NData = h2Data->Integral(timeBin[iT-1]+1, timeBin[iT], temp_bin_met[iM-1]+1, temp_bin_met[iM]);
float NBkg = h2Bkg->Integral(timeBin[iT-1]+1, timeBin[iT], temp_bin_met[iM-1]+1, temp_bin_met[iM]);
float NSig = h2Sig->Integral(timeBin[iT-1]+1, timeBin[iT], temp_bin_met[iM-1]+1, temp_bin_met[iM]);
h1Data->SetBinContent(thisBin, NData);
h1Bkg->SetBinContent(thisBin, NBkg);
h1Sig->SetBinContent(thisBin, NSig);
//cout<<"iT = "<<iT<<" iM = "<<iM<<" thiBin = "<<thisBin<<" NBkg = "<<NBkg<<" NSig = "<<NSig<<endl;
}
}
if(debug_thisFunc) cout<<"DEBUG binningOptimization met: validation of 2D conversion (Bkg): "<<h2Bkg->Integral()<<" -> "<<h1Bkg->Integral()<<endl;
if(debug_thisFunc) cout<<"DEBUG binningOptimization met: validation of 2D conversion (Sig): "<<h2Sig->Integral()<<" -> "<<h1Sig->Integral()<<endl;
for(int i=1;i<= (temp_bin_met.size()-1)*(timeBin.size()-1); i++)
{
if(h1Bkg->GetBinContent(i) < 1e-3 ) h1Bkg->SetBinContent(i, 1e-3);
if(h1Sig->GetBinContent(i) < 1e-3 ) h1Sig->SetBinContent(i, 1e-3);
//h1Data->SetBinContent(i, h1Bkg->GetBinContent(i) + h1Sig->GetBinContent(i));
}
//double qnot = Fit1DMETTimeSignificance(h1Data, h1Bkg, h1Sig, 10);
double qnot = CalculateMETTimeSignificance(h1Bkg, h1Sig);
if(debug_thisFunc) cout<<"DEBUG binningOptimization met: significance of new split = "<<qnot<<" vs. maxSignificance = "<<maxSignificance<<endl;
if(qnot > 1.000*maxSignificance)
{
maxSignificance = qnot;
new_idx_met = idx;
}
h1_qnot_met->SetBinContent(idx, qnot);
delete h1Data;
delete h1Bkg;
delete h1Sig;
}
h1_qnot_met->SetLineWidth(2);
h1_qnot_met->SetLineColor(kBlack);
h1_qnot_met->SetTitle("");
h1_qnot_met->GetXaxis()->SetTitle("new split on #slash{E}_{T} [GeV]");
h1_qnot_met->GetYaxis()->SetTitle("q_{0}");
h1_qnot_met->GetYaxis()->SetTitleSize(axisTitleSize);
h1_qnot_met->GetYaxis()->SetRangeUser(0.15, 1.2*h1_qnot_met->GetMaximum());
h1_qnot_met->GetXaxis()->SetRangeUser(10.0+met_Low, met_High-10.0);
h1_qnot_met->GetXaxis()->SetTitleSize(axisTitleSize);
h1_qnot_met->GetYaxis()->SetTitleOffset(axisTitleOffset);
h1_qnot_met->GetXaxis()->SetTitleOffset(axisTitleOffset);
h1_qnot_met->Draw();
for(int ih=0;ih<metBin.size();ih++)
{
TString s_ih_name = Form("h1_qnot_met_iter_%d_i%d", iteration, ih);
std::string _s_ih_name ((const char*) s_ih_name);
TH1F *h1_temp = new TH1F(_s_ih_name.c_str(), _s_ih_name.c_str(), met_N_fine, met_Low, met_High);
h1_temp->SetBinContent(metBin[ih], 1.2*h1_qnot_met->GetMaximum());
h1_temp->SetLineWidth(3);
h1_temp->SetLineColor(kRed);
h1_temp->Draw("same");
}
if(new_idx_met > 0)
{
myC->SaveAs(("fit_results/2016/"+_outBinningDir+"/binning_"+_s_hist_name+".pdf").c_str());
myC->SaveAs(("fit_results/2016/"+_outBinningDir+"/binning_"+_s_hist_name+".png").c_str());
myC->SaveAs(("fit_results/2016/"+_outBinningDir+"/binning_"+_s_hist_name+".C").c_str());
if(debug_thisFunc) cout<<"best split point added met : "<<new_idx_met<<" maxSignificance = "<<maxSignificance<<endl;
metBin.push_back(new_idx_met);
std::sort(metBin.begin(), metBin.end());
}
else isConverged_met = true;
}
if(isConverged_time && isConverged_met) isConverged_all = true;
else if(metBin.size()>10 || timeBin.size()>10)
{
if(metBin.size()>10) isConverged_met = true;
if(timeBin.size()>10) isConverged_time = true;
isConverged_all = (isConverged_met && isConverged_time);
}
else
{
isConverged_time = false;
isConverged_met = false;
isConverged_all = false;
}
iteration ++;
}
};
void OptimizeBinningABCDLimits(int Nbins_MET, int Nbins_Time, std::vector<int> &TimeBin, std::vector<int> &METBin, TH2F * h2Data, TH2F *h2Sig, TH2F * h2MCBkg, TH1F *h1DataShape_Time, TH1F *h1DataShape_MET, TString modelName, TString ourBinningDir, bool blindABD)
{
float NSig_total_events = h2Sig->Integral();
float NData_total_events = h2Data->Integral();
std::string _modelName ((const char*) modelName);
std::string _outBinningDir ((const char*) ourBinningDir);
bool debug_thisFunc = true;
//initial status: 1 bin in Time, and 1 bin in MET
int nTotal_Time = h2Data->GetNbinsX();
int nTotal_MET = h2Data->GetNbinsY();
cout<<" binning optimization... "<<endl;
cout<<"Time bins # "<<nTotal_Time<<endl;
cout<<"MET bins # "<<nTotal_MET<<endl;
cout<<"NSig: "<<NSig_total_events<<endl;
cout<<"NData: "<<NData_total_events<<endl;
cout<<"task is to split into "<<Nbins_MET<<" MET x "<<Nbins_Time<<" Time bins"<<endl;
std::vector <int> combIndex_Time;
std::vector <int> combIndex_MET;
cout<<"getting all the possible choices of Time splits..."<<endl;
int N_comb_Time = Combination(nTotal_Time-1, Nbins_Time-1, combIndex_Time);
cout<<"N_comb_Time = "<<N_comb_Time<<endl;
cout<<"getting all the possible choices of MET splits..."<<endl;
int N_comb_MET = Combination(nTotal_MET-1, Nbins_MET-1, combIndex_MET);
cout<<"N_comb_MET = "<<N_comb_MET<<endl;
float minLimits = 999999.9;
std::vector<int> best_split_Time;
std::vector<int> best_split_MET;
system(("rm fit_results/2016ABCD/datacards_temp/higgsCombine"+_modelName+"*.Asymptotic.mH120.root").c_str());
system(("rm fit_results/2016ABCD/datacards_temp/DelayedPhotonCard_"+_modelName+"*.txt").c_str());
float minDataRateCut = 10.0;
for(int icomb_Time = 0; icomb_Time<N_comb_Time; icomb_Time ++)
{
std::vector<int> index_Time_split;
index_Time_split.push_back(0);
for(int idxT = 0; idxT<(Nbins_Time-1); idxT++)
{
index_Time_split.push_back(combIndex_Time[icomb_Time*(Nbins_Time-1) + idxT]);
}
index_Time_split.push_back(nTotal_Time);
for(int icomb_MET = 0; icomb_MET<N_comb_MET; icomb_MET ++)
{
std::vector<int> index_MET_split;
index_MET_split.push_back(0);
for(int idxM= 0; idxM<(Nbins_MET-1); idxM++)
{
index_MET_split.push_back(combIndex_MET[icomb_MET*(Nbins_MET-1) + idxM]);
}
index_MET_split.push_back(nTotal_MET);
cout<<"calculating limits for the following Time and met splits..."<<endl;
for(int idxT = 0; idxT<(Nbins_Time+1); idxT++)
{
cout<<index_Time_split[idxT]<<" ";
}
cout<<" , ";
for(int idxM = 0; idxM<(Nbins_MET+1); idxM++)
{
cout<<index_MET_split[idxM]<<" ";
}
cout<<endl;
//make the datacards
TH2F *h2_rate_Data_inBins = new TH2F("h2_rate_Data_inBins","; #gamma Time bin; #slash{E}_{T} bin; Events", Nbins_Time, 0, 1.0*Nbins_Time, Nbins_MET, 0, 1.0*Nbins_MET);
TH1F *h1_rate_DataShape_Time_inBins = new TH1F("h1_rate_DataShape_Time_inBins","; #gamma Time bin; Events", Nbins_Time, 0, 1.0*Nbins_Time);
TH1F *h1_rate_DataShape_MET_inBins = new TH1F("h1_rate_DataShape_MET_inBins","; #slash{E}_{T} bin; Events", Nbins_MET, 0, 1.0*Nbins_MET);
TH2F *h2_rate_Sig_inBins = new TH2F("h2_rate_Sig_inBins","; #gamma Time bin; #slash{E}_{T} bin; Events", Nbins_Time, 0, 1.0*Nbins_Time, Nbins_MET, 0, 1.0*Nbins_MET);
TH2F *h2_rate_MCBkg_inBins = new TH2F("h2_rate_MCBkg_inBins","; #gamma Time bin; #slash{E}_{T} bin; Events", Nbins_Time, 0, 1.0*Nbins_Time, Nbins_MET, 0, 1.0*Nbins_MET);
float minDataRate = 999999.9;
for(int iT=1; iT<=Nbins_Time; iT++)
{
for(int iM=1; iM<=Nbins_MET; iM++)
{
float datarate_this = h2Data->Integral(index_Time_split[iT-1]+1, index_Time_split[iT], index_MET_split[iM-1]+1, index_MET_split[iM]);
if(datarate_this < minDataRate) minDataRate = datarate_this;
h2_rate_Data_inBins->SetBinContent(iT, iM, datarate_this);
h2_rate_Sig_inBins->SetBinContent(iT, iM, h2Sig->Integral(index_Time_split[iT-1]+1, index_Time_split[iT], index_MET_split[iM-1]+1, index_MET_split[iM]));
h2_rate_MCBkg_inBins->SetBinContent(iT, iM, h2MCBkg->Integral(index_Time_split[iT-1]+1, index_Time_split[iT], index_MET_split[iM-1]+1, index_MET_split[iM]));
if(iT == 1) h1_rate_DataShape_MET_inBins->SetBinContent(iM, h1DataShape_MET->Integral(index_MET_split[iM-1]+1, index_MET_split[iM]));
}
h1_rate_DataShape_Time_inBins->SetBinContent(iT, h1DataShape_Time->Integral(index_Time_split[iT-1]+1, index_Time_split[iT]));
}
//blind the top cornor bin in data
float A_ = h2_rate_Data_inBins->GetBinContent(Nbins_Time-1, Nbins_MET-1);
float B_ = h2_rate_Data_inBins->GetBinContent(Nbins_Time-1, Nbins_MET);
float D_ = h2_rate_Data_inBins->GetBinContent(Nbins_Time, Nbins_MET-1);
if(A_ > 0.0)
{
h2_rate_Data_inBins->SetBinContent(Nbins_Time, Nbins_MET, B_*D_/A_);
if(B_*D_/A_ < minDataRate) minDataRate = B_*D_/A_;
}
//if(minDataRate < minDataRateCut)
//{
//cout<<"this time and met split has a data bin with only "<<minDataRate<<" events, will not use this split"<<endl;
//continue;
//}
cout<<"in resized 2D histograms, nData = "<<h2_rate_Data_inBins->Integral()<<", nSig = "<<h2_rate_Sig_inBins->Integral()<<endl;
MakeDataCardABCD(h2_rate_Data_inBins,h2_rate_Sig_inBins, h2_rate_MCBkg_inBins, h1_rate_DataShape_Time_inBins, h1_rate_DataShape_MET_inBins, Nbins_Time, Nbins_MET, (_modelName+"_iT"+to_string(icomb_Time)+"_iM"+to_string(icomb_MET)).c_str(), "datacards_temp", blindABD);
//add systematics
TH2F *h2_lumi_sys_Sig_inBins = new TH2F("h2_lumi_sys_Sig_inBins","; #gamma time bin; #slash{E}_{T} bin; Events", Nbins_Time, 0, 1.0*Nbins_Time, Nbins_MET, 0, 1.0*Nbins_MET);
TH2F *h2_PhotonScale_sys_Sig_inBins = new TH2F("h2_PhotonScale_sys_Sig_inBins","; #gamma time bin; #slash{E}_{T} bin; Events", Nbins_Time, 0, 1.0*Nbins_Time, Nbins_MET, 0, 1.0*Nbins_MET);
TH2F *h2_PhotonSmear_sys_Sig_inBins = new TH2F("h2_PhotonSmear_sys_Sig_inBins","; #gamma time bin; #slash{E}_{T} bin; Events", Nbins_Time, 0, 1.0*Nbins_Time, Nbins_MET, 0, 1.0*Nbins_MET);
TH2F *h2_JetEScale_sys_Sig_inBins = new TH2F("h2_JetEScale_sys_Sig_inBins","; #gamma time bin; #slash{E}_{T} bin; Events", Nbins_Time, 0, 1.0*Nbins_Time, Nbins_MET, 0, 1.0*Nbins_MET);
TH2F *h2_JetESmear_sys_Sig_inBins = new TH2F("h2_JetESmear_sys_Sig_inBins","; #gamma time bin; #slash{E}_{T} bin; Events", Nbins_Time, 0, 1.0*Nbins_Time, Nbins_MET, 0, 1.0*Nbins_MET);
TH2F *h2_TimeScale_sys_Sig_inBins = new TH2F("h2_TimeScale_sys_Sig_inBins","; #gamma time bin; #slash{E}_{T} bin; Events", Nbins_Time, 0, 1.0*Nbins_Time, Nbins_MET, 0, 1.0*Nbins_MET);
TH2F *h2_TimeSmear_sys_Sig_inBins = new TH2F("h2_TimeSmear_sys_Sig_inBins","; #gamma time bin; #slash{E}_{T} bin; Events", Nbins_Time, 0, 1.0*Nbins_Time, Nbins_MET, 0, 1.0*Nbins_MET);
TH2F *h2_TimeMETCorrelation_sys_Sig_inBins = new TH2F("h2_TimeMETCorrelation_sys_Sig_inBins","; #gamma time bin; #slash{E}_{T} bin; Events", Nbins_Time, 0, 1.0*Nbins_Time, Nbins_MET, 0, 1.0*Nbins_MET);
for(int iT=1; iT<=Nbins_Time; iT++)
{
for(int iM=1; iM<=Nbins_MET; iM++)
{
h2_lumi_sys_Sig_inBins->SetBinContent(iT, iM, 1.025);
h2_PhotonScale_sys_Sig_inBins->SetBinContent(iT, iM, 1.01);
h2_PhotonSmear_sys_Sig_inBins->SetBinContent(iT, iM, 1.01);
h2_JetEScale_sys_Sig_inBins->SetBinContent(iT, iM, 1.015);
h2_JetESmear_sys_Sig_inBins->SetBinContent(iT, iM, 1.015);
h2_TimeScale_sys_Sig_inBins->SetBinContent(iT, iM, 1.015);
h2_TimeSmear_sys_Sig_inBins->SetBinContent(iT, iM, 1.005);
h2_TimeMETCorrelation_sys_Sig_inBins->SetBinContent(iT, iM, 1.00);
}
}
h2_TimeMETCorrelation_sys_Sig_inBins->SetBinContent(2, 2, 1.02);
AddSystematics_Norm_ABCD(h2_lumi_sys_Sig_inBins, Nbins_Time, Nbins_MET, "lumi_2016", "lnN", (_modelName+"_iT"+to_string(icomb_Time)+"_iM"+to_string(icomb_MET)).c_str(), "datacards_temp", true);
AddSystematics_Norm_ABCD(h2_PhotonScale_sys_Sig_inBins, Nbins_Time, Nbins_MET, "photonEScale_2016", "lnN", (_modelName+"_iT"+to_string(icomb_Time)+"_iM"+to_string(icomb_MET)).c_str(), "datacards_temp", true);
AddSystematics_Norm_ABCD(h2_PhotonSmear_sys_Sig_inBins, Nbins_Time, Nbins_MET, "photonESmear_2016", "lnN", (_modelName+"_iT"+to_string(icomb_Time)+"_iM"+to_string(icomb_MET)).c_str(), "datacards_temp", true);
AddSystematics_Norm_ABCD(h2_JetEScale_sys_Sig_inBins, Nbins_Time, Nbins_MET, "JetEScale_2016", "lnN", (_modelName+"_iT"+to_string(icomb_Time)+"_iM"+to_string(icomb_MET)).c_str(), "datacards_temp", true);
AddSystematics_Norm_ABCD(h2_JetESmear_sys_Sig_inBins, Nbins_Time, Nbins_MET, "JetESmear_2016", "lnN", (_modelName+"_iT"+to_string(icomb_Time)+"_iM"+to_string(icomb_MET)).c_str(), "datacards_temp", true);
AddSystematics_Norm_ABCD(h2_TimeScale_sys_Sig_inBins, Nbins_Time, Nbins_MET, "TimeScale_2016", "lnN", (_modelName+"_iT"+to_string(icomb_Time)+"_iM"+to_string(icomb_MET)).c_str(), "datacards_temp", true);
AddSystematics_Norm_ABCD(h2_TimeSmear_sys_Sig_inBins, Nbins_Time, Nbins_MET, "TimeSmear_2016", "lnN", (_modelName+"_iT"+to_string(icomb_Time)+"_iM"+to_string(icomb_MET)).c_str(), "datacards_temp", true);
AddSystematics_Norm_ABCD(h2_TimeMETCorrelation_sys_Sig_inBins, Nbins_Time, Nbins_MET, "TimeMETCorrelation_2016", "lnN", (_modelName+"_iT"+to_string(icomb_Time)+"_iM"+to_string(icomb_MET)).c_str(), "datacards_temp", false);
//run combine to get the limits...
cout<<"running combine tool on the fly now...."<<endl;
system(("combine -M Asymptotic fit_results/2016ABCD/datacards_temp/DelayedPhotonCard_"+_modelName+"_iT"+to_string(icomb_Time)+"_iM"+to_string(icomb_MET)+".txt -v -1 -n "+_modelName+"_iT"+to_string(icomb_Time)+"_iM"+to_string(icomb_MET)).c_str());
//extract the expected limit...
TFile * file_limit = new TFile(("higgsCombine"+_modelName+"_iT"+to_string(icomb_Time)+"_iM"+to_string(icomb_MET)+".Asymptotic.mH120.root").c_str());
TTree * tree_limit = (TTree*)file_limit->Get("limit");
Double_t limits=9999, expLimit=9999, obsLimit=9999;
tree_limit->SetBranchAddress("limit", &limits);
if(tree_limit->GetEntries() < 6)
{
cout<<"BAD BIN CHOICE: didn't get all the limits"<<endl;
continue;
}
tree_limit->GetEntry(2);
expLimit = limits;
tree_limit->GetEntry(5);
obsLimit = limits;
if((obsLimit > 5*expLimit) || (obsLimit < 0.2*expLimit))
{
cout<<"BAD BIN CHOICE: expected and observed limit are too different"<<endl;
continue;
}
cout<<"expected limit of this split = "<<limits<<endl;
if(expLimit < minLimits)
{
minLimits = expLimit;
best_split_Time.clear();
best_split_MET.clear();
for(int iT=0; iT<index_Time_split.size(); iT++)
{
best_split_Time.push_back(index_Time_split[iT]);
}
for(int iM=0; iM<index_MET_split.size(); iM++)
{
best_split_MET.push_back(index_MET_split[iM]);
}
}
file_limit->Close();
system(("mv higgsCombine"+_modelName+"*.Asymptotic.mH120.root fit_results/2016ABCD/datacards_temp/").c_str());
//delete
delete gROOT->FindObject("h2_rate_Data_inBins");
delete gROOT->FindObject("h2_rate_Sig_inBins");
}
}
cout<<"best expected limit found: "<<minLimits<<endl;
for(int iT=1; iT<best_split_Time.size()-1; iT++)
{
TimeBin.push_back(best_split_Time[iT]);
}
for(int iM=1; iM<best_split_MET.size()-1; iM++)
{
METBin.push_back(best_split_MET[iM]);
}
std::sort(TimeBin.begin(), TimeBin.end());
std::sort(METBin.begin(), METBin.end());
};
int Combination(int N, int K, std::vector<int> & comb)
{
std::string bitmask(K, 1); // K leading 1's
bitmask.resize(N, 0); // N-K trailing 0's
int N_comb = 0;
do {
for (int i = 0; i < N; ++i)
{
if (bitmask[i])
{
//std::cout << " " << i+1;
comb.push_back(i+1);
}
}
//std::cout << std::endl;
N_comb ++;
} while (std::prev_permutation(bitmask.begin(), bitmask.end()));
return N_comb;
};
void OptimizeBinningABCD(int Nbins_MET, int Nbins_time, float min_events, float min_events_sig_frac, std::vector<int> &timeBin, std::vector<int> &metBin, TH2F * h2Bkg, TH2F *h2Sig, float time_Low, float time_High, int time_N_fine, float met_Low, float met_High, int met_N_fine, TString modelName, TString ourBinningDir)
{
float NSig_total_events = h2Sig->Integral();
float NBkg_total_events = h2Bkg->Integral();
float min_events_sig = min_events_sig_frac*NSig_total_events;
std::string _modelName ((const char*) modelName);
std::string _outBinningDir ((const char*) ourBinningDir);
//TFile *f_Out_binning = new TFile(("fit_results/2016ABCD/binning/binning_"+_modelName+".root").c_str(),"recreate");
bool debug_thisFunc = false;
//initial status: 1 bin in time, and 1 bin in MET
int nTotal_time = h2Bkg->GetNbinsX();
int nTotal_met = h2Bkg->GetNbinsY();
cout<<" binning optimization... "<<endl;
cout<<"time bins # "<<nTotal_time<<endl;
cout<<"met bins # "<<nTotal_met<<endl;
cout<<"NSig: "<<NSig_total_events<<endl;
cout<<"NBkg: "<<NBkg_total_events<<endl;
cout<<"task is to split into "<<Nbins_MET<<" met x "<<Nbins_time<<" time bins"<<endl;
bool isConverged_time = false;
bool isConverged_met = false;
bool isConverged_all = false;
/*************generate toy data**************/
TH2F * h2Data = new TH2F("h2Data","h2Data", time_N_fine, time_Low, time_High, met_N_fine, met_Low, met_High);
TH1F * h1ConvertData = new TH1F("h1ConvertData","h1ConvertData", time_N_fine*met_N_fine, 0, time_N_fine*met_N_fine);
TH1 * h1ConvertData_toy = new TH1F("h1ConvertData_toy","h1ConvertData_toy", time_N_fine*met_N_fine, 0, time_N_fine*met_N_fine);
//2D to 1D convert
for(int i=1;i<=time_N_fine;i++)
{
for(int j=1;j<=met_N_fine;j++)
{
int thisBin = (i-1)*met_N_fine + j;
h1ConvertData->SetBinContent(thisBin, h2Bkg->GetBinContent(i,j) + h2Sig->GetBinContent(i,j));
}
}
if(debug_thisFunc) cout<<"binning optimization: 2D data to 1D data conversion : "<<h2Bkg->Integral()+h2Sig->Integral()<<" -> "<<h1ConvertData->Integral()<<endl;
//toy generation
RooRealVar bin("bin","2D bin",0,h1ConvertData->GetSize()-2,"");
RooDataHist* rhData = new RooDataHist("rhData", "rhData", RooArgSet(bin), h1ConvertData);
RooHistPdf * rpData = new RooHistPdf("rpData", "rpData", RooArgSet(bin), *rhData, 0);
//create toy data
TRandom3* r3 = new TRandom3(0);
double nData_toy = r3->PoissonD(h1ConvertData->Integral());
RooDataHist* data_toy = rpData->generateBinned(RooArgSet(bin), nData_toy);
data_toy->SetName("data_toy");
h1ConvertData_toy = data_toy->createHistogram("bin", time_N_fine*met_N_fine);
if(debug_thisFunc) cout<<"binning optimization: 1D data vs toy data : "<<h1ConvertData->Integral()<<" -> "<<h1ConvertData_toy->Integral()<<endl;
//1D to 2D convert
for(int i=1;i<=time_N_fine;i++)
{
for(int j=1;j<=met_N_fine;j++)
{
int thisBin = (i-1)*met_N_fine + j;
h2Data->SetBinContent(i, j, h1ConvertData_toy->GetBinContent(thisBin));
}
}
/*************end of toy data****************/
//while( (!isConverged_time) || (!isConverged_met))
TCanvas *myC = new TCanvas( "myC", "myC", 200, 10, 800, 800 );
myC->SetHighLightColor(2);
myC->SetFillColor(0);
myC->SetBorderMode(0);
myC->SetBorderSize(2);
myC->SetLeftMargin( leftMargin );
myC->SetRightMargin( rightMargin );
myC->SetTopMargin( topMargin );
myC->SetBottomMargin( bottomMargin );
myC->SetFrameBorderMode(0);
myC->SetFrameBorderMode(0);
myC->SetTitle("");
int iteration = 0;
int Nsplit_time = 0;
int Nsplit_MET = 0;
while( !isConverged_all )
{
//start spliting in time dimension
int new_idx_time = -99;
int new_idx_met = -99;
if(!isConverged_time)
{
cout<<"tring to add a time split..."<<endl;
TString s_hist_name = Form("_h1_qnot_time_iter_%d", iteration);
std::string _s_hist_name2 ((const char*) s_hist_name);
std::string _s_hist_name = _modelName+_s_hist_name2;
TH1F * h1_qnot_time = new TH1F(_s_hist_name.c_str(), _s_hist_name.c_str(), time_N_fine, time_Low, time_High);
double maxSignificance = -9999.0;
for(int idx=1;idx<nTotal_time;idx++)
{
if(std::find(timeBin.begin(), timeBin.end(), idx) != timeBin.end()) continue; // add a new split
double this_time = time_Low + (time_High - time_Low) * (1.0*idx)/(1.0*time_N_fine);
int dist_min = 9999;
for(int i=0;i<timeBin.size();i++)
{
if(abs(timeBin[i] - idx) < dist_min) dist_min = abs(timeBin[i] - idx);
}
//if(dist_min < 5) continue; // not too narrow binning
std::vector <int> temp_bin_time;
for(int idx_temp : timeBin)
{
temp_bin_time.push_back(idx_temp);
}
temp_bin_time.push_back(idx);
std::sort(temp_bin_time.begin(), temp_bin_time.end());
//if(debug_thisFunc) cout<<"DEBUG binningOptimization time: tring to add split at idx = "<<idx<<endl;
for(int inx_temp : temp_bin_time)
{
cout<<inx_temp<<" , ";
}
cout<<endl;
//avoid too narrow binning: each bin must have at least min_events
bool hasSmallBin = false;
float smallest_Bkg = 999999;
float smallest_Sig = 999999;
//construct 1D histogram of time and met
TH1F *h1Data = new TH1F ("h1Data","h1Data", (temp_bin_time.size()-1)*(metBin.size()-1), 0, (temp_bin_time.size()-1)*(metBin.size()-1)*1.0);
TH1F *h1Bkg = new TH1F ("h1Bkg","h1Bkg", (temp_bin_time.size()-1)*(metBin.size()-1), 0, (temp_bin_time.size()-1)*(metBin.size()-1)*1.0);
TH1F *h1Sig = new TH1F ("h1Sig","h1Sig", (temp_bin_time.size()-1)*(metBin.size()-1), 0, (temp_bin_time.size()-1)*(metBin.size()-1)*1.0);
for(int iT=1;iT<= temp_bin_time.size()-1; iT++)
{
for(int iM=1;iM<= metBin.size()-1; iM++)
{
int thisBin = (iT-1)*(metBin.size()-1) + iM;
float NData = h2Data->Integral(temp_bin_time[iT-1]+1, temp_bin_time[iT], metBin[iM-1]+1, metBin[iM]);
float NBkg = h2Bkg->Integral(temp_bin_time[iT-1]+1, temp_bin_time[iT], metBin[iM-1]+1, metBin[iM]);
float NSig = h2Sig->Integral(temp_bin_time[iT-1]+1, temp_bin_time[iT], metBin[iM-1]+1, metBin[iM]);
if(NBkg < pow(3.0, 1.0 * (Nbins_time - 1 - Nsplit_time + Nbins_MET - Nsplit_MET)-2.0) * min_events) hasSmallBin = true;
if(NSig < pow(3.0, 1.0 * (Nbins_time - 1 - Nsplit_time + Nbins_MET - Nsplit_MET)-2.0) * min_events_sig) hasSmallBin = true;
if(NSig < smallest_Sig) smallest_Sig = NSig;
if(NBkg < smallest_Bkg) smallest_Bkg = NBkg;
h1Data->SetBinContent(thisBin, NData);
h1Bkg->SetBinContent(thisBin, NBkg);
h1Sig->SetBinContent(thisBin, NSig);
//cout<<"iT = "<<iT<<" iM = "<<iM<<" thiBin = "<<thisBin<<" NBkg = "<<NBkg<<" NSig = "<<NSig<<endl;
}
}
if(hasSmallBin)
{
if(debug_thisFunc) cout<<"split resulting to too narror bin smallest (Sig, Bkg) bin integral = "<<smallest_Sig<<", "<<smallest_Bkg<<" - cut is "<<pow(3.0, 1.0 * (Nbins_time - 1 - Nsplit_time + Nbins_MET - Nsplit_MET) -2.0 ) * min_events_sig<<", "<<pow(3.0, 1.0 * (Nbins_time - 1 - Nsplit_time + Nbins_MET - Nsplit_MET)-2.0) * min_events<<endl;
continue;
}
if(debug_thisFunc) cout<<"DEBUG binningOptimization time: validation of 2D conversion (Bkg): "<<h2Bkg->Integral()<<" -> "<<h1Bkg->Integral()<<endl;
if(debug_thisFunc) cout<<"DEBUG binningOptimization time: validation of 2D conversion (Sig): "<<h2Sig->Integral()<<" -> "<<h1Sig->Integral()<<endl;
for(int i=1;i<= (temp_bin_time.size()-1)*(metBin.size()-1); i++)
{
if(h1Bkg->GetBinContent(i) < 1e-3 ) h1Bkg->SetBinContent(i, 1e-3);
if(h1Sig->GetBinContent(i) < 1e-3 ) h1Sig->SetBinContent(i, 1e-3);
//h1Data->SetBinContent(i, h1Bkg->GetBinContent(i) + h1Sig->GetBinContent(i));
}
//double qnot = Fit1DMETTimeSignificance(h1Data, h1Bkg, h1Sig, 10);
double qnot = CalculateMETTimeSignificance(h1Bkg, h1Sig);
//if(debug_thisFunc) cout<<"DEBUG binningOptimization time: significance of new split = "<<qnot<<" vs. maxSignificance = "<<maxSignificance<<endl;
if(qnot > 1.000*maxSignificance)
{
maxSignificance = qnot;
new_idx_time = idx;
}
if(qnot>0.001) h1_qnot_time->SetBinContent(idx, qnot);
//delete h1Data;
//delete h1Bkg;
//delete h1Sig;
delete gROOT->FindObject("h1Data");
delete gROOT->FindObject("h1Bkg");
delete gROOT->FindObject("h1Sig");
}
h1_qnot_time->SetLineWidth(2);
h1_qnot_time->SetLineColor(kBlack);
h1_qnot_time->SetTitle("");
h1_qnot_time->GetXaxis()->SetTitle("new split on #gamma cluster time [ns]");
h1_qnot_time->GetYaxis()->SetTitle("q_{0}");
h1_qnot_time->GetYaxis()->SetTitleSize(axisTitleSize);
h1_qnot_time->GetYaxis()->SetRangeUser(0.15, 1.2*h1_qnot_time->GetMaximum());
h1_qnot_time->GetXaxis()->SetRangeUser(0.2+time_Low, time_High-0.2);
h1_qnot_time->GetXaxis()->SetTitleSize(axisTitleSize);
h1_qnot_time->GetYaxis()->SetTitleOffset(axisTitleOffset);
h1_qnot_time->GetXaxis()->SetTitleOffset(axisTitleOffset);
h1_qnot_time->Draw();
for(int ih=0;ih<timeBin.size();ih++)
{
TString s_ih_name = Form("h1_qnot_time_iter_%d_i%d", iteration, ih);
std::string _s_ih_name ((const char*) s_ih_name);
TH1F *h1_temp = new TH1F(_s_ih_name.c_str(), _s_ih_name.c_str(), time_N_fine, time_Low, time_High);
h1_temp->SetBinContent(timeBin[ih], 1.2*h1_qnot_time->GetMaximum());
h1_temp->SetLineWidth(3);
h1_temp->SetLineColor(kRed);
h1_temp->Draw("same");
}
if(new_idx_time > 0)
{
myC->SaveAs(("fit_results/2016ABCD/"+_outBinningDir+"/binning_"+to_string(Nbins_time)+"x"+to_string(Nbins_MET)+_s_hist_name+".pdf").c_str());
myC->SaveAs(("fit_results/2016ABCD/"+_outBinningDir+"/binning_"+to_string(Nbins_time)+"x"+to_string(Nbins_MET)+_s_hist_name+".png").c_str());
myC->SaveAs(("fit_results/2016ABCD/"+_outBinningDir+"/binning_"+to_string(Nbins_time)+"x"+to_string(Nbins_MET)+_s_hist_name+".C").c_str());
if(debug_thisFunc) cout<<"best split point added : "<<new_idx_time<<" maxSignificance = "<<maxSignificance<<endl;
timeBin.push_back(new_idx_time);
std::sort(timeBin.begin(), timeBin.end());
Nsplit_time++;
}
else isConverged_time = true;
if(Nsplit_time+1 >= Nbins_time) isConverged_time = true;
}
if(!isConverged_met)
{
cout<<"tring to add a met split..."<<endl;
TString s_hist_name = Form("_h1_qnot_met_iter_%d", iteration);
std::string _s_hist_name2 ((const char*) s_hist_name);
std::string _s_hist_name = _modelName + _s_hist_name2;
TH1F * h1_qnot_met = new TH1F(_s_hist_name.c_str(), _s_hist_name.c_str(), met_N_fine, met_Low, met_High);
double maxSignificance = -9999.0;
for(int idx=1;idx<nTotal_met;idx++)
{
if(std::find(metBin.begin(), metBin.end(), idx) != metBin.end()) continue; // add a new split
double this_met = met_Low + (met_High - met_Low) * (1.0*idx)/(1.0*met_N_fine);
int dist_min = 9999;
for(int i=0;i<metBin.size();i++)
{
if(abs(metBin[i] - idx) < dist_min) dist_min = abs(metBin[i] - idx);
}
//if(dist_min < 5) continue; // not too narrow binning
std::vector <int> temp_bin_met;
for(int idx_temp : metBin)
{
temp_bin_met.push_back(idx_temp);
}
temp_bin_met.push_back(idx);
std::sort(temp_bin_met.begin(), temp_bin_met.end());
//if(debug_thisFunc) cout<<"DEBUG binningOptimization met: tring to add split at idx = "<<idx<<endl;
for(int inx_temp : temp_bin_met)
{
cout<<inx_temp<<" , ";
}
cout<<endl;
//avoid too narrow binning: each bin must have at least min_events
bool hasSmallBin = false;
float smallest_Bkg = 999999;
float smallest_Sig = 999999;
//construct 1D histogram of met and time
TH1F *h1Data = new TH1F ("h1Data","h1Data", (temp_bin_met.size()-1)*(timeBin.size()-1), 0, (temp_bin_met.size()-1)*(timeBin.size()-1)*1.0);
TH1F *h1Bkg = new TH1F ("h1Bkg","h1Bkg", (temp_bin_met.size()-1)*(timeBin.size()-1), 0, (temp_bin_met.size()-1)*(timeBin.size()-1)*1.0);
TH1F *h1Sig = new TH1F ("h1Sig","h1Sig", (temp_bin_met.size()-1)*(timeBin.size()-1), 0, (temp_bin_met.size()-1)*(timeBin.size()-1)*1.0);
for(int iT=1;iT<= timeBin.size()-1; iT++)
{
for(int iM=1;iM<= temp_bin_met.size()-1; iM++)
{
int thisBin = (iT-1)*(temp_bin_met.size()-1) + iM;
float NData = h2Data->Integral(timeBin[iT-1]+1, timeBin[iT], temp_bin_met[iM-1]+1, temp_bin_met[iM]);
float NBkg = h2Bkg->Integral(timeBin[iT-1]+1, timeBin[iT], temp_bin_met[iM-1]+1, temp_bin_met[iM]);
float NSig = h2Sig->Integral(timeBin[iT-1]+1, timeBin[iT], temp_bin_met[iM-1]+1, temp_bin_met[iM]);
if(NBkg < pow(3.0, 1.0* (Nbins_time - Nsplit_time + Nbins_MET - 1 - Nsplit_MET)-2.0) * min_events) hasSmallBin = true;
if(NSig < pow(3.0, 1.0* (Nbins_time - Nsplit_time + Nbins_MET - 1 - Nsplit_MET)-2.0) * min_events_sig) hasSmallBin = true;
if(NSig < smallest_Sig) smallest_Sig = NSig;
if(NBkg < smallest_Bkg) smallest_Bkg = NBkg;
h1Data->SetBinContent(thisBin, NData);
h1Bkg->SetBinContent(thisBin, NBkg);
h1Sig->SetBinContent(thisBin, NSig);
//cout<<"iT = "<<iT<<" iM = "<<iM<<" thiBin = "<<thisBin<<" NBkg = "<<NBkg<<" NSig = "<<NSig<<endl;
}
}
if(hasSmallBin)
{
if(debug_thisFunc) cout<<"split resulting to too narror bin smallest (Sig, Bkg) bin integral = "<<smallest_Sig<<", "<<smallest_Bkg<<" - cut is "<<pow(3.0, 1.0 * (Nbins_time - Nsplit_time + Nbins_MET - 1 - Nsplit_MET)-2.0) * min_events_sig<<", "<<pow(3.0, 1.0*(Nbins_time - Nsplit_time + Nbins_MET - 1 - Nsplit_MET) -2.0) * min_events<<endl;
continue;
}
if(debug_thisFunc) cout<<"DEBUG binningOptimization met: validation of 2D conversion (Bkg): "<<h2Bkg->Integral()<<" -> "<<h1Bkg->Integral()<<endl;
if(debug_thisFunc) cout<<"DEBUG binningOptimization met: validation of 2D conversion (Sig): "<<h2Sig->Integral()<<" -> "<<h1Sig->Integral()<<endl;
for(int i=1;i<= (temp_bin_met.size()-1)*(timeBin.size()-1); i++)
{
if(h1Bkg->GetBinContent(i) < 1e-3 ) h1Bkg->SetBinContent(i, 1e-3);
if(h1Sig->GetBinContent(i) < 1e-3 ) h1Sig->SetBinContent(i, 1e-3);
//h1Data->SetBinContent(i, h1Bkg->GetBinContent(i) + h1Sig->GetBinContent(i));
}
//double qnot = Fit1DMETTimeSignificance(h1Data, h1Bkg, h1Sig, 10);
double qnot = CalculateMETTimeSignificance(h1Bkg, h1Sig);
//if(debug_thisFunc) cout<<"DEBUG binningOptimization met: significance of new split = "<<qnot<<" vs. maxSignificance = "<<maxSignificance<<endl;
if(qnot > 1.000*maxSignificance)
{
maxSignificance = qnot;
new_idx_met = idx;
}
h1_qnot_met->SetBinContent(idx, qnot);
//delete h1Data;
//delete h1Bkg;
//delete h1Sig;
delete gROOT->FindObject("h1Data");
delete gROOT->FindObject("h1Bkg");
delete gROOT->FindObject("h1Sig");
}
h1_qnot_met->SetLineWidth(2);
h1_qnot_met->SetLineColor(kBlack);
h1_qnot_met->SetTitle("");
h1_qnot_met->GetXaxis()->SetTitle("new split on #slash{E}_{T} [GeV]");
h1_qnot_met->GetYaxis()->SetTitle("q_{0}");
h1_qnot_met->GetYaxis()->SetTitleSize(axisTitleSize);
h1_qnot_met->GetYaxis()->SetRangeUser(0.15, 1.2*h1_qnot_met->GetMaximum());
h1_qnot_met->GetXaxis()->SetRangeUser(10.0+met_Low, met_High-10.0);
h1_qnot_met->GetXaxis()->SetTitleSize(axisTitleSize);
h1_qnot_met->GetYaxis()->SetTitleOffset(axisTitleOffset);
h1_qnot_met->GetXaxis()->SetTitleOffset(axisTitleOffset);
h1_qnot_met->Draw();
for(int ih=0;ih<metBin.size();ih++)
{
TString s_ih_name = Form("h1_qnot_met_iter_%d_i%d", iteration, ih);
std::string _s_ih_name ((const char*) s_ih_name);
TH1F *h1_temp = new TH1F(_s_ih_name.c_str(), _s_ih_name.c_str(), met_N_fine, met_Low, met_High);
h1_temp->SetBinContent(metBin[ih], 1.2*h1_qnot_met->GetMaximum());
h1_temp->SetLineWidth(3);
h1_temp->SetLineColor(kRed);
h1_temp->Draw("same");
}
if(new_idx_met > 0)
{
myC->SaveAs(("fit_results/2016ABCD/"+_outBinningDir+"/binning_"+to_string(Nbins_time)+"x"+to_string(Nbins_MET)+_s_hist_name+".pdf").c_str());
myC->SaveAs(("fit_results/2016ABCD/"+_outBinningDir+"/binning_"+to_string(Nbins_time)+"x"+to_string(Nbins_MET)+_s_hist_name+".png").c_str());
myC->SaveAs(("fit_results/2016ABCD/"+_outBinningDir+"/binning_"+to_string(Nbins_time)+"x"+to_string(Nbins_MET)+_s_hist_name+".C").c_str());
if(debug_thisFunc) cout<<"best split point added met : "<<new_idx_met<<" maxSignificance = "<<maxSignificance<<endl;
metBin.push_back(new_idx_met);
std::sort(metBin.begin(), metBin.end());
Nsplit_MET++;
}
else isConverged_met = true;
if(Nsplit_MET+1 >= Nbins_MET) isConverged_met = true;
}
if(isConverged_time && isConverged_met) isConverged_all = true;
iteration ++;
}
};
void Draw2DBinning(TH2F * h2_rate, TString plotLabel, TString modelName, TString ourBinningDir)
{
std::string _plotLabel ((const char*) plotLabel);
std::string _modelName ((const char*) modelName);
std::string _outBinningDir ((const char*) ourBinningDir);
TCanvas *myC = new TCanvas( "myC", "myC", 200, 10, 800, 800 );
myC->SetHighLightColor(2);
myC->SetFillColor(0);
myC->SetBorderMode(0);
myC->SetBorderSize(2);
myC->SetLeftMargin( leftMargin );
myC->SetRightMargin( rightMargin );
myC->SetTopMargin( topMargin );
myC->SetBottomMargin( bottomMargin );
myC->SetFrameBorderMode(0);
myC->SetFrameBorderMode(0);
myC->SetTitle("");
myC->SetGridx(1);
myC->SetGridy(1);
h2_rate->SetMarkerSize(2);
h2_rate->Draw("COL, TEXT");
myC->SaveAs(("fit_results/2016ABCD/"+_outBinningDir+"/ABCDBinning_"+_modelName+"_"+_plotLabel+".pdf").c_str());
myC->SaveAs(("fit_results/2016ABCD/"+_outBinningDir+"/ABCDBinning_"+_modelName+"_"+_plotLabel+".png").c_str());
myC->SaveAs(("fit_results/2016ABCD/"+_outBinningDir+"/ABCDBinning_"+_modelName+"_"+_plotLabel+".C").c_str());
};
|
template <class Type>
Type hcr_min(Type a, Type b){
return 0.5 * (a + b - sqrt(1e-4 + (a-b) * (a-b)));
};
template <class Type>
Type hcr_max(Type a, Type b){
return 0.5 * (a + b + sqrt(1e-4 + (a-b) * (a-b)));
};
template <class Type>
Type hcr(Type ssb, vector<Type> hcrConf){
Type Ftarget = hcrConf(0);
Type Flim = hcrConf(1);
Type Flow = hcrConf(2);
Type Blim = hcrConf(3);
Type Blow = hcrConf(4);
Type Btrigger = hcrConf(5);
Type newF = CppAD::CondExpLt(ssb,
Blow,
Flow,
hcr_min(Ftarget, hcr_max(Flim, Flim + (ssb - Blim) * (Ftarget - Flim) / (Btrigger - Blim))));
return log(hcr_max(newF, (Type)exp(-10)));
};
extern "C" {
SEXP hcrR(SEXP ssb, SEXP hcrConf){
vector<double> s = asVector<double>(ssb);
vector<double> hc = asVector<double>(hcrConf);
vector<double> r(s.size());
r.setZero();
for(int i = 0; i < s.size(); ++i)
r(i) = hcr(s(i), hc);
return asSEXP(exp(r));
}
}
template <class Type>
void forecastSimulation(dataSet<Type>& dat, confSet& conf, paraSet<Type>& par, array<Type>& logN, array<Type>& logF, objective_function<Type> *of){
// Only for forecast simulation
if(dat.forecast.nYears == 0 || !(isDouble<Type>::value) || !(of->do_simulate))
return;
// General setup
int stateDimF=logF.dim[0];
int timeSteps=logF.dim[1];
int stateDimN=conf.keyLogFsta.dim[1];
// Setup for F
matrix<Type> fvar = get_fvar(dat, conf, par, logF);
MVMIX_t<Type> neg_log_densityF(fvar,Type(conf.fracMixF));
// Setup for N
matrix<Type> nvar = get_nvar(dat, conf, par, logN, logF);
MVMIX_t<Type> neg_log_densityN(nvar,Type(conf.fracMixN));
int nYears = dat.forecast.nYears;
for(int i = 0; i < nYears; ++i){
int indx = dat.forecast.forecastYear.size() - nYears + i;
// Update forecast
dat.forecast.updateForecast(i, logF, logN, dat, conf, par);
// Simulate F
// int forecastIndex = CppAD::Integer(dat.forecast.forecastYear(i))-1;
if(dat.forecast.simFlag(0) == 0){
Type timeScale = dat.forecast.forecastCalculatedLogSdCorrection(i);
logF.col(indx) = (vector<Type>)dat.forecast.forecastCalculatedMedian.col(i) + neg_log_densityF.simulate() * timeScale;
}
// Simulate N
if(dat.forecast.simFlag(1) == 0){
vector<Type> predN = predNFun(dat,conf,par,logN,logF,indx);
vector<Type> Nscale(logN.rows());
Nscale.setConstant((Type)1.0);
if(dat.forecast.recModel(CppAD::Integer(dat.forecast.forecastYear(indx))-1) != dat.forecast.asRecModel){
Nscale(0) = sqrt(dat.forecast.logRecruitmentVar) / sqrt(nvar(0,0));
predN(0) = dat.forecast.logRecruitmentMedian;
}
logN.col(indx) = predN + neg_log_densityN.simulate();// * Nscale;
}
}
return;
};
// template<class Type>
// void simulationForecast(){
// if(dat.forecast.nYears == 0)
// return;
// int nYears = dat.forecast.nYears;
// for(int i = 0; i < nYears; ++i){
// int indx = dat.forecast.forecastYear.size() - nYears + i;
// // Simulate F
// // Simulate N
// }
// }
|
#include "basicheaders.h"
#include "tree.h"
#include "customvector.h"
namespace lrstruct {
bool Node::stepLoopSwitcher = false;
bool Node::isStepByStepMode = false;
int Node::findDepth(Node* root) {
if(root == nullptr) {
return 0;
}
if(root->_left == nullptr && root->_right == nullptr) {
return 1;
}
else {
int l = findDepth(root->_left);
int r = findDepth(root->_right);
_depth = (1 + ((l > r) ? l : r));
return _depth;
//T O(n) S O(n)
}
}
int Node::findMinNode(Node* root) {
// Base case
if (root == nullptr)
return INT_MAX;
// Return minimum of 3 values:
// 1) Root's data 2) Min in Left Subtree
// 3) Min in right subtree
int res = root->_data.val;
int lres = findMinNode(root->_left);
int rres = findMinNode(root->_right);
if (lres < res)
res = lres;
if (rres < res)
res = rres;
return res;
}
int Node::findMaxNode(Node* root) {
// Base case
if (root == nullptr)
return INT_MIN;
// Return maximum of 3 values:
// 1) Root's data 2) Max in Left Subtree
// 3) Max in right subtree
int res = root->_data.val;
int lres = findMaxNode(root->_left);
int rres = findMaxNode(root->_right);
if (lres > res)
res = lres;
if (rres > res)
res = rres;
return res;
}
int Node::getLargestNumberBsd() {
if (_right == nullptr) {
return _data.val;
}
else {
_right->getLargestNumberBsd();
}
// never happen
return false;
}
int Node::getSmallestNumberBsd() {
if (_left == nullptr) {
return _data.val;
}
else {
_left->getSmallestNumberBsd();
}
// never happen
return false;
}
bool Node::isSymetrical() {
lrstruct::Vector <int> left_side;
lrstruct::Vector <int> right_side;
if(_left == nullptr || _right == nullptr)
return false;
_left->symetricalChecking(left_side);
_right->symetricalChecking(right_side);
if (left_side.size() != right_side.size()) {
return false;
}
for (int i = 0; static_cast<size_t>(i) < left_side.size(); i++) {
if (left_side[i] != right_side[i]) {
return false;
}
}
return true;
}
void Node::symetricalChecking(lrstruct::Vector<int>& vec) {
if (_left != nullptr && _right != nullptr) {
vec.push_back(0);
_left->symetricalChecking(vec);
_right->symetricalChecking(vec);
}
else if (_left != nullptr) {
vec.push_back(-1);
_left->symetricalChecking(vec);
}
else if (_right != nullptr) {
vec.push_back(1);
_right->symetricalChecking(vec);
}
else {
vec.push_back(2);
}
}
int Node::get_next_num(std::string &s, int &i, int& numb) {
qDebug() << "get_next_num() " << "for i = " << i << endl;
int start = i;
while (i != static_cast<int>(s.size()) && \
s[static_cast<unsigned long>(i)] != '(' && s[static_cast<unsigned long>(i)] != ')')
i++;
try {
numb = stoi(s.substr(static_cast<unsigned long>(start), static_cast<unsigned long>(i) - \
static_cast<unsigned long>(start)));
} catch (...) {
qDebug() << "Invalid input string!" << endl;
return 1;
}
return 0;
}
int Node::dfs(std::string &s, int &i, Node*& root) {
qDebug() << "dfs started " << "for i = " << i << endl;
// base case
int size = static_cast<int>(s.size());
if (i >= size || s[static_cast<unsigned long>(i)] == ')') {
// NULL is OK
root = nullptr;
return 0;
}
if(s[static_cast<unsigned long>(i)] == '(') i++;
if(s[static_cast<unsigned long>(i)] == '#') {
root = nullptr;
i++;
return 0;
}
int num;
if(get_next_num(s, i, num))
// something went wrong
return 1;
lrstruct::Data _data;
_data.val = num;
Node* temp_root = new Node(_data);
int check;
Node* left;
check = dfs(s, i, left);
if(check == 1)
return 1;
Node* right;
check = dfs(s, i, right);
if(check == 1)
return 1;
temp_root->_left = left;
temp_root->_right = right;
if (s[static_cast<unsigned long>(i)] == ')') i++;
root = temp_root;
// everything OK
return 0;
}
/**
* @brief Node::convertBracketRepresentationToBinTree
* @param inputStr
* Input string with bracket representation of binary tree
* @return
*/
int Node::convertBracketRepresentationToBinTree(std::string inputStr, Node*& root) {
qDebug() << "convertBracketRepresentationToBinTree()" << endl;
int i = 0;
int check = dfs(inputStr, i, root);
if(check == 1)
return 1;
return 0;
}
}
|
#include <windows.h>
#include <tchar.h>
#include <cstdio>
#include <vector>
using std::vector;
#define VK_LETTER_A 0x41
#define VK_LETTER_S 0x53
#define VK_LETTER_D 0x44
#define VK_LETTER_F 0x46
// 1P
#define VK_A VK_LETTER_A
#define VK_B VK_LETTER_S
#define VK_C VK_LETTER_D
#define VK_D VK_LETTER_F
#define VK_FORWARD VK_RIGHT
#define VK_BACKWARD VK_LEFT
#define VK_JUMP VK_UP
#define VK_CROUCH VK_DOWN
#define KEYDOWN(vk_code) ((::GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0)
#define KEYUP(vk_code) ((::GetAsyncKeyState(vk_code) & 0x8000) ? 0 : 1)
class HoldDown { // 压键
public:
HoldDown(void) : jump(false), backward(false), crouch(false), forward(false),
a(false), b(false), c(false), d(false)
{}
bool jump, backward, crouch, forward;
bool a,b,c,d;
};
void PrintOrigKeySeq(vector<int> q) {
vector<int>::iterator it;
for (it = q.begin(); it != q.end(); ++it) {
fprintf(stderr, "%X",*it);
}
fprintf(stderr, "\n");
}
int _tmain(int argc, int argv)
{
vector<int> orig_key_seq(16); // 原始按键序列
vector<int>::size_type last_size;
HoldDown hold_down;
while (true) {
last_size = orig_key_seq.size();
Sleep(20); // wait for directive
// direction
if (!hold_down.jump && KEYDOWN(VK_JUMP)) {
hold_down.jump = true;
orig_key_seq.push_back(0x08);
}
if (hold_down.jump && KEYUP(VK_JUMP)) {
hold_down.jump = false;
orig_key_seq.push_back(0xF8);
}
if (!hold_down.backward && KEYDOWN(VK_BACKWARD)) {
hold_down.backward = true;
orig_key_seq.push_back(0x04);
}
if (hold_down.backward && KEYUP(VK_BACKWARD)) {
hold_down.backward = false;
orig_key_seq.push_back(0xF4);
}
if (!hold_down.crouch && KEYDOWN(VK_CROUCH)) {
hold_down.crouch = true;
orig_key_seq.push_back(0x02);
}
if (hold_down.crouch && KEYUP(VK_CROUCH)) {
hold_down.crouch = false;
orig_key_seq.push_back(0xF2);
}
if (!hold_down.forward && KEYDOWN(VK_FORWARD)) {
hold_down.forward = true;
orig_key_seq.push_back(0x06);
}
if (hold_down.forward && KEYUP(VK_FORWARD)) {
hold_down.forward = false;
orig_key_seq.push_back(0xF6);
}
// ABCD
if (!hold_down.a && KEYDOWN(VK_A)) {
hold_down.a = true;
orig_key_seq.push_back(0x0A);
}
if (hold_down.a && KEYUP(VK_A)) {
hold_down.a = false;
orig_key_seq.push_back(0xFA);
}
if (!hold_down.b && KEYDOWN(VK_B)) {
hold_down.b = true;
orig_key_seq.push_back(0x0B);
}
if (hold_down.b && KEYUP(VK_B)) {
hold_down.b = false;
orig_key_seq.push_back(0xFB);
}
if (!hold_down.c && KEYDOWN(VK_C)) {
hold_down.c = true;
orig_key_seq.push_back(0x0C);
}
if (hold_down.c && KEYUP(VK_C)) {
hold_down.c = false;
orig_key_seq.push_back(0xFC);
}
if (!hold_down.d && KEYDOWN(VK_D)) {
hold_down.d = true;
orig_key_seq.push_back(0x0D);
}
if (hold_down.d && KEYUP(VK_D)) {
hold_down.d = false;
orig_key_seq.push_back(0xFD);
}
// 提取指令
if (last_size < orig_key_seq.size()) {
PrintOrigKeySeq(orig_key_seq);
}
do {
// 清空指令
static int blockcount = 0;
if (blockcount < 20) {
++blockcount;
break;
}
blockcount = 0;
orig_key_seq.clear();
} while (0);
}
return 0;
}
|
#ifndef __FGSpeedPickUp__H__
#define __FGSpeedPickUp__H__
class AudioCue;
class FGSpeedPickUp :
public LivingObject
{
protected:
AudioCue* m_pPickedUpAudio;
double m_bonusTime;
float m_speedBoost;
public:
FGSpeedPickUp(float boostAmount,double boostTime, const char* cameraName = GAME_DEFAULT_CAMERA_NAME, unsigned int drawRenderOrder = 0);
virtual ~FGSpeedPickUp();
virtual void BeginCollision(b2Fixture* fixtureCollided, b2Fixture* fixtureCollidedAgainst, GameObject* objectCollidedagainst, b2Vec2 collisionNormal, b2Vec2 contactPoint, bool touching);
virtual void OnDeath();
};
#endif
|
#pragma once
#include<iostream>
#include<fstream>
#include<string>
#include <sstream>
#include<vector>
using namespace std;
#include "PersonalInformation.h"
class ExperienceFormula
{
public:
ExperienceFormula();
ExperienceFormula(string filepath);
~ExperienceFormula();
//private:
vector <int> value;
void DefaultInit();
int CalculateHOTS2Grade(PersonalInformation personalInformation);
private:
int GetGradeFromExperience(int heroExperience);
};
|
// Matrice.cpp : main project file.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int i;//Numara coloanele
int j;//Numara randurile
int n;//Numarul maxim de coloane
int m;//Numarul maxim de randuri
cout<<"Introduceti numarul de coloane(maxim 10):";
cin>>n;
cout<<"Introduceti numarul de randuri(maxim 10):";
cin>>m;
int matr[10][10],nr;
for(j=0;j<m;j++)
{
for(i=0;i<n;i++)
{
nr=rand();
matr[i][j]= 100*nr/RAND_MAX ; // pentru a genera numere intre 0-100
}
}
cout<<"\n\n\t\tMatricea este:\n\n";
for(j=0;j<m;j++)
{
cout<<"\n";
for(i=0;i<n;i++)
{
cout<<"Marticea["<<i<<"]["<<j<<"]="<<matr[i][j]<<"\t";
}
}
cin.ignore();
cin.get();
return 0;
}
|
/**
* \file parser.hpp
* \date Jan 27, 2016
*/
#ifndef PCSH_PARSER_HPP
#define PCSH_PARSER_HPP
#include "pcsh/exportsym.h"
#include "pcsh/arena.hpp"
#include "pcsh/ir.hpp"
#include "pcsh/types.hpp"
#include <iostream>
#include <memory>
#if defined(_MSC_VER)
# pragma warning(disable:4251)
#endif // defined(_MSC_VER)
namespace pcsh {
namespace parser {
//////////////////////////////////////////////////////////////////////////
/// token_type
//////////////////////////////////////////////////////////////////////////
enum class token_type : byte
{
LPAREN,
RPAREN,
LBRACE,
RBRACE,
SEMICOLON,
ASSIGN,
PLUS,
MINUS,
ASTERISK,
DOT,
FSLASH,
QUOTE,
SYMBOL,
INTEGER,
FLOATING,
EOS,
IF,
ISEQUAL,
NONE,
FAIL
};
//////////////////////////////////////////////////////////////////////////
/// buff_string : in-memory buffer view of a stream
//////////////////////////////////////////////////////////////////////////
struct buff_string
{
cstring ptr;
size_t len;
inline bool equals(const char* s) const
{
return strncmp(ptr, s, len) == 0;
}
};
//////////////////////////////////////////////////////////////////////////
/// token
//////////////////////////////////////////////////////////////////////////
class PCSH_API token
{
public:
token(const token& rhs) : type_(rhs.type_), str_(rhs.str_), len_(rhs.len_)
{ }
inline token_type type() const
{
return type_;
}
inline bool defined() const
{
return type_ != token_type::NONE;
}
inline bool is_a(token_type x) const
{
return type_ == x;
}
inline size_t length() const
{
return len_;
}
inline buff_string str() const
{
buff_string rv = { str_, len_ };
return rv;
}
private:
token(token_type t, cstring s, size_t l) : type_(t), str_(s), len_(l)
{ }
static token get(token_type t, cstring nm = nullptr, size_t len = 0);
friend class parser;
token_type type_;
cstring str_;
size_t len_;
};
//////////////////////////////////////////////////////////////////////////
/// parser exception
//////////////////////////////////////////////////////////////////////////
void throw_parser_exception(const std::string& msg, const std::string& fname, const std::string& func, const std::string& line);
class exception
{
public:
inline ~exception()
{ }
inline const std::string& message() const { return msg_; }
inline const std::string& filename() const { return fname_; }
inline const std::string& fcn() const { return func_; }
inline const std::string& line() const { return line_; }
private:
std::string msg_;
std::string fname_;
std::string func_;
std::string line_;
inline exception(const std::string& msg, const std::string& fname, const std::string& func, const std::string& line)
: msg_(msg), fname_(fname), func_(func), line_(line)
{ }
friend void throw_parser_exception(const std::string&, const std::string&, const std::string&, const std::string&);
};
//////////////////////////////////////////////////////////////////////////
/// parser
//////////////////////////////////////////////////////////////////////////
using pos_t = size_t;
class PCSH_API parser
{
public:
parser(std::istream& is, const std::string& filename = "(test)");
~parser();
token peek(pos_t p = 0, pos_t* pactstart = nullptr);
void advance(pos_t len, bool countnl = true);
inline int line() const
{
return line_;
}
inline pos_t line_start() const
{
return line_start_;
}
pos_t curr_pos() const;
// returns a valid executable tree, except for use before assign errors.
ir::tree::ptr parse_to_tree();
void sync_stream();
private:
class buffered_stream;
class parser_engine;
buffered_stream* strm_;
int line_;
pos_t line_start_;
std::string filename_;
pos_t find_first_non_whitespace(pos_t start);
pos_t skip_till_line_end(pos_t p);
token read_string(pos_t p);
token read_number(pos_t p);
token read_name(pos_t p);
std::string copy_line(pos_t p);
};
}// namespace parser
}// namespace pcsh
#if defined(_MSC_VER)
# pragma warning(default:4251)
#endif // defined(_MSC_VER)
#endif/*PCSH_PARSER_HPP*/
|
/**********************************************************************
* Program: carLot2.cpp
* Author: Jason Cearley
* Class: CS161
* Date: 11/27/14
* Modified: 11/27/14
* Description: This program consists of a class called Date that
* consists of an int called day, an int called month and
* an int called year; a class called Car that consists of
* a string called make, a string called model, an int
* called year, a Date called datePurchased, a double
* called purchasePrice, a bool called isSold, a Date
* called dateSold, and a double called salePrice; & a
* vector of Car.
*
* A menu gives the following options:
• Add entry: this allows the user to enter the information for a
* car, which is then added to the vector. The user is
* prompted for dateSold and salePrice if and only if
* isSold is true.
*
• List current inventory: this lists the data for all Cars that
* have been purchased, but not yet sold,
* and then prints out the count of how
* many cars that is.
*
• Profit for a month: this asks the user for a month and year and
* displays the total profit for sales in that
* month.
*
• Quit: exits the program.
* *******************************************************************/
#include <iostream> // cin/cout
#include <string> // strings
#include <cstdlib> // atoi
#include <vector> // vectors
#include <iomanip> // setprecision and showpoint
#include <math.h> // NAN special value
using namespace std;
// Define Classes
class Date
{
private:
int month, day, year;
public:
Date()
{
month = 0;
day = 0;
year = 0;
}
int get_month()
{return month;}
int get_day()
{return day;}
int get_year()
{return year;}
void set_month (int m)
{month = m;}
void set_day (int d)
{day = d;}
void set_year (int y)
{year = y;}
};
class Car
{
private:
string make;
string model;
int year;
Date datePurchased, dateSold;
double purchasePrice,
salePrice;
bool isSold;
public:
Car()
{
string a = "";
int i = 0;
double d = 0.0;
make = a;
model = a;
year = i;
purchasePrice = d;
salePrice = d;
datePurchased.set_day(i);
datePurchased.set_month(i);
datePurchased.set_year(i);
dateSold.set_day(i);
dateSold.set_month(i);
dateSold.set_year(i);
}
string get_make()
{return make;}
string get_model()
{return model;}
int get_year()
{return year;}
int get_datePurchased_day()
{return datePurchased.get_day();}
int get_datePurchased_month()
{return datePurchased.get_month();}
int get_datePurchased_year()
{return datePurchased.get_year();}
int get_dateSold_day()
{return dateSold.get_day();}
int get_dateSold_month()
{return dateSold.get_month();}
int get_dateSold_year()
{return dateSold.get_year();}
double get_purchasePrice()
{return purchasePrice;}
double get_salePrice()
{return salePrice;}
bool get_isSold()
{return isSold;}
void set_make(string ma)
{make = ma;}
void set_model(string mod)
{model = mod;}
void set_year(int y)
{year = y;}
void set_datePurchased_day(int dp)
{datePurchased.set_day(dp);}
void set_datePurchased_month(int mp)
{datePurchased.set_month(mp);}
void set_datePurchased_year(int yp)
{datePurchased.set_year(yp);}
void set_dateSold_day(int ds)
{dateSold.set_day(ds);}
void set_dateSold_month(int ms)
{dateSold.set_month(ms);}
void set_dateSold_year(int ys)
{dateSold.set_year(ys);}
void set_purchasePrice(double p)
{purchasePrice = p;}
void set_salePrice(double s)
{salePrice = s;}
void set_isSold(bool sold)
{isSold = sold;}
double getProfit()
{
return (get_salePrice() - get_purchasePrice());
}
};
class CarLot
{
private:
vector <Car> vehicle;
public:
void addCar(int);
void listCurrentInv(int);
void getMonthProfit(int);
};
// Prototype Function(s)
void menu();
int user_selection();
int get_date(int);
double get_price();
bool get_sold();
bool check_date(int, int);
// Class Functions
/***********************************************************************
* This function gets the user's info for the car.
***********************************************************************/
void CarLot::addCar(int num)
{
string tempString = "";
int tempValue = 0;
double tempPrice = 0.0;
bool tempSold = false;
// Add a Car class to the vector vehicle
vehicle.push_back(Car());
cout << "Enter the Make: ";
getline(cin, tempString);
vehicle[num].set_make(tempString);
cout << endl << "Enter the Model: ";
getline(cin, tempString);
vehicle[num].set_model(tempString);
cout << endl << "Enter the Year (ex 2011): ";
tempValue = get_date(3);
vehicle[num].set_year(tempValue);
cout << endl << "Enter The Purchase Price: $";
tempPrice = get_price();
vehicle[num].set_purchasePrice(tempPrice);
do
{
cout << endl << "Enter The Month Purchased: ";
tempValue = get_date(1);
vehicle[num].set_datePurchased_month(tempValue);
cout << endl << "Enter The Day Purchased: ";
tempValue = get_date(2);
vehicle[num].set_datePurchased_day(tempValue);
}
while(!check_date(vehicle[num].get_datePurchased_month(),
vehicle[num].get_datePurchased_day()));
cout << endl << "Enter The Year Purchased: ";
tempValue = get_date(3);
vehicle[num].set_datePurchased_year(tempValue);
cout << endl << "Has this vehicle been sold (y or n)? ";
tempSold = get_sold();
vehicle[num].set_isSold(tempSold);
if (vehicle[num].get_isSold())
{
cout << endl << "What Was The Sale Price? $";
tempPrice = get_price();
vehicle[num].set_salePrice(tempPrice);
do
{
cout << endl << "Enter The Month Sold: ";
tempValue = get_date(1);
vehicle[num].set_dateSold_month(tempValue);
cout << endl << "Enter The Day Sold: ";
tempValue = get_date(2);
vehicle[num].set_dateSold_day(tempValue);
}
while(!check_date(vehicle[num].get_dateSold_month(),
vehicle[num].get_dateSold_day()));
cout << endl << "Enter The Year Sold: ";
tempValue = get_date(3);
vehicle[num].set_dateSold_year(tempValue);
}
}
/***********************************************************************
* This function lists the data for all cars currently in inventory.
***********************************************************************/
void CarLot::listCurrentInv(int num)
{
cout << fixed << showpoint << setprecision(2) << endl;
int count = 0;
for (int a = 0; a < num; a++)
{
if (!vehicle[a].get_isSold())
{
cout << "Make: " << vehicle[a].get_make() << endl
<< "Model: " << vehicle[a].get_model() << endl
<< "Year: " << vehicle[a].get_year() << endl
<< "Purchase Price: $" << vehicle[a].get_purchasePrice()
<< endl
<< "Date Purchased (mm/dd/yyyy): "
<< vehicle[a].get_datePurchased_month() << "/"
<< vehicle[a].get_datePurchased_day() << "/"
<< vehicle[a].get_datePurchased_year() << endl;
count++;
}
cout << endl;
}
cout << "There are currently " << count << " cars in inventory."
<< endl << endl;
}
/***********************************************************************
* This function lists the profit from all cars sold in a given month
* of the year.
***********************************************************************/
void CarLot::getMonthProfit(int num)
{
cout << fixed << showpoint << setprecision(2) << endl;
double profit = 0.0;
int m = 0, y = 0;
cout << "Enter The Month For Which You Would Like To See The"
<< " Profits: ";
m = get_date(1);
cout << "Enter The Year For Which You Would Like To See The"
<< " Profits: ";
y = get_date(3);
for (int a = 0; a < num; a++)
{
if (vehicle[a].get_isSold() &&
vehicle[a].get_dateSold_month() == m &&
vehicle[a].get_dateSold_year() == y)
{
profit += (vehicle[a].get_salePrice() -
vehicle[a].get_purchasePrice());
}
}
cout << "The profit for the Month/Year requested is $"
<< profit << endl << endl;
}
int main()
{
int menu_choice = 0; // Holds the user's menu choice
int index = 0; // Keep track of number of cars added
// Create a CarLot object to use class functions/variables
CarLot lot;
// Do/while loop to allow user to continue w/o exiting
do
{
menu(); // Display menu choices
menu_choice = user_selection(); // Assign menu_choice the value
// returned by the user_selection
// function
// If/else to perform user's choice
if (menu_choice == 1)
{
// Call to add function
lot.addCar(index);
index++;
}
else if (menu_choice == 2)
{
// Call to list function
lot.listCurrentInv(index);
}
else if (menu_choice == 3)
{
// Call to profit function
lot.getMonthProfit(index);
}
}
while (menu_choice != 4);
return 0;
}
/***********************************************************************
* This function displays the selection menu for the user to choose
* from.
**********************************************************************/
void menu()
{
cout << "Please choose a command from the following list:" << endl;
cout << "1. Add Entry To Inventory." << endl;
cout << "2. List Current Inventory." << endl;
cout << "3. Get Profit For A Specified Month & Year." << endl;
cout << "4. Quit." << endl;
}
/***********************************************************************
* This function gets the user's menu choice, validates it, and returns
* it back to main.
***********************************************************************/
int user_selection()
{
string number = ""; // Variable to hold user's input
unsigned found1 = 0; // Variable used to detect non-numeric entries
// Do/while loop ensures only contains valid numbers
do
{
getline (cin, number);
found1 = number.find_first_not_of ("1234", 0);
if (found1 != 4294967295 || number.size() > 1)
{
cout << "That is not a valid entry. Please select a number "
<< "between 1 and 4: "
<< endl;
}
}
while (found1 != 4294967295 || number.size() > 1);
// atoi converts string into an integer
return atoi (number.c_str());
}
/***********************************************************************
* This function gets the user's date variable, validates it, and returns
* it back to the calling function.
***********************************************************************/
int get_date(int use)
{
string number = ""; // Variable to hold user's input
unsigned found1 = 0; // Variable used to detect non-numeric entries
// This if statement is used for Months
if (use == 1)
{
// Do/while loop ensures only contains valid numbers
do
{
getline (cin, number);
found1 = number.find_first_not_of ("1234567890", 0);
if (found1 != 4294967295 || atoi(number.c_str()) < 1 ||
atoi(number.c_str()) > 12)
{
cout << "That is not a valid entry. Please try again. "
<< endl;
}
}
while (found1 != 4294967295 || atoi(number.c_str()) < 1 ||
atoi(number.c_str()) > 12);
// atoi converts string into an integer
return atoi (number.c_str());
}
// This if statement is used for Days
if (use == 2)
{
// Do/while loop ensures only contains valid numbers
do
{
getline (cin, number);
found1 = number.find_first_not_of ("1234567890", 0);
if (found1 != 4294967295 || atoi(number.c_str()) < 1 ||
atoi(number.c_str()) > 31)
{
cout << "That is not a valid entry. Please try again. "
<< endl;
}
}
while (found1 != 4294967295 || atoi(number.c_str()) < 1 ||
atoi(number.c_str()) > 31);
// atoi converts string into an integer
return atoi (number.c_str());
}
// This if statement is used for Years
if (use == 3)
{
// Do/while loop ensures only contains valid numbers
do
{
getline (cin, number);
found1 = number.find_first_not_of ("1234567890", 0);
if (found1 != 4294967295 || number.size() > 4)
{
cout << "That is not a valid entry. Please try again. "
<< endl;
}
}
while (found1 != 4294967295 || number.size() > 4);
// atoi converts string into an integer
return atoi (number.c_str());
}
return 0;
}
/***********************************************************************
* This function gets the user's input, validates it, and returns
* it as a double.
***********************************************************************/
double get_price()
{
string number = ""; // Variable to hold user's input
unsigned found1 = 0; // Variable used to detect non-numeric entries
// Do/while loop ensures only contains valid numbers
do
{
getline (cin, number);
found1 = number.find_first_not_of ("1234567890.", 0);
if (found1 != 4294967295 || number.size() > 20)
{
cout << "That is not a valid entry. Please try again: "
<< endl;
}
}
while (found1 != 4294967295 || number.size() > 20);
// atoi converts string into an integer
return atof (number.c_str());
}
/***********************************************************************
* This function gets the user's input, validates it, and returns
* it as a bool.
***********************************************************************/
bool get_sold()
{
string number = ""; // Variable to hold user's input
unsigned found1 = 0; // Variable used to detect non-numeric entries
// Do/while loop ensures only contains valid numbers
do
{
getline (cin, number);
found1 = number.find_first_not_of ("yn", 0);
if (found1 != 4294967295 || number.size() > 1)
{
cout << "That is not a valid entry. Please try again: "
<< endl;
}
}
while (found1 != 4294967295 || number.size() > 1);
if (number == "y")
{
return true;
}
else
{
return false;
}
}
/***********************************************************************
* This function validates the user's date to ensure it is correct.
***********************************************************************/
bool check_date(int m, int d)
{
if ((d <= 31 && m == 1) || (d <= 31 && m == 3) ||
(d <= 31 && m == 5) || (d <= 31 && m == 7) ||
(d <= 31 && m == 8) || (d <= 31 && m == 10) ||
(d <= 31 && m == 12))
{
return true;
}
if ((d <= 30 && m == 4) || (d <= 30 && m == 6) ||
(d <= 30 && m == 9) || (d <= 30 && m == 11))
{
return true;
}
if (d <= 28 && m == 2)
{
return true;
}
cout << "That is not a valid date. Try again. ";
return false;
}
|
#pragma once
#include <SDL2/SDL.h>
#include "Layer.hpp"
#include "Ball.hpp"
#include "Player.hpp"
#include "Score.hpp"
class GameLayer : public Layer
{
private:
void initBall();
void paintScore();
public:
GameLayer(SDL_Renderer *rend);
void init() override;
void processControls() override;
void update() override;
void draw() override;
void keysToControls();
bool isQuit();
int newEnemyTime = 0;
bool quit = 0;
Player *player1;
Player *player2;
Ball *ball;
Score *score;
};
|
#include "pch.h"
#include <boost/lexical_cast.hpp>
#include "PqColumnDataSource.h"
#include "PqResultSource.h"
#include "PqUtils.h"
PqColumnDataSource::PqColumnDataSource(PqResultSource* result_source_, const DATA_TYPE dt_, const int j) :
DbColumnDataSource(j),
result_source(result_source_),
dt(dt_)
{
}
PqColumnDataSource::~PqColumnDataSource() {
}
DATA_TYPE PqColumnDataSource::get_data_type() const {
return dt;
}
DATA_TYPE PqColumnDataSource::get_decl_data_type() const {
return dt;
}
bool PqColumnDataSource::is_null() const {
LOG_VERBOSE;
return PQgetisnull(get_result(), 0, get_j()) != 0;
}
int PqColumnDataSource::fetch_bool() const {
LOG_VERBOSE << get_result_value();
return (strcmp(get_result_value(), "t") == 0);
}
int PqColumnDataSource::fetch_int() const {
LOG_VERBOSE << get_result_value();
return atoi(get_result_value());
}
int64_t PqColumnDataSource::fetch_int64() const {
LOG_VERBOSE;
return boost::lexical_cast<int64_t>(get_result_value());
}
double PqColumnDataSource::fetch_real() const {
LOG_VERBOSE << get_result_value();
const char* value = get_result_value();
if (strcmp(value, "-Infinity") == 0) {
LOG_VERBOSE;
return -INFINITY;
}
else if (strcmp(value, "Infinity") == 0) {
LOG_VERBOSE;
return INFINITY;
}
else if (strcmp(value, "NaN") == 0) {
LOG_VERBOSE;
return NAN;
}
else {
LOG_VERBOSE;
return atof(value);
}
}
SEXP PqColumnDataSource::fetch_string() const {
LOG_VERBOSE << get_result_value();
return Rf_mkCharCE(get_result_value(), CE_UTF8);
}
SEXP PqColumnDataSource::fetch_blob() const {
LOG_VERBOSE;
const void* val = get_result_value();
size_t to_length = 0;
unsigned char* unescaped_blob = PQunescapeBytea(static_cast<const unsigned char*>(val), &to_length);
SEXP bytes = Rf_allocVector(RAWSXP, static_cast<R_xlen_t>(to_length));
memcpy(RAW(bytes), unescaped_blob, to_length);
PQfreemem(unescaped_blob);
return bytes;
}
double PqColumnDataSource::fetch_date() const {
LOG_VERBOSE;
const char* val = get_result_value();
int year = *val - 0x30;
year *= 10;
year += (*(++val) - 0x30);
year *= 10;
year += (*(++val) - 0x30);
year *= 10;
year += (*(++val) - 0x30);
val++;
int mon = 10 * (*(++val) - 0x30);
mon += (*(++val) - 0x30);
val++;
int mday = (*(++val) - 0x30) * 10;
mday += (*(++val) - 0x30);
return days_from_civil(year, mon, mday);
}
double PqColumnDataSource::fetch_datetime_local() const {
LOG_VERBOSE;
return convert_datetime(get_result_value());
}
double PqColumnDataSource::fetch_datetime() const {
LOG_VERBOSE;
return convert_datetime(get_result_value());
}
double PqColumnDataSource::fetch_time() const {
LOG_VERBOSE;
const char* val = get_result_value();
int hour = (*val - 0x30) * 10;
hour += (*(++val) - 0x30);
val++;
int min = (*(++val) - 0x30) * 10;
min += (*(++val) - 0x30);
val++;
double sec = strtod(++val, NULL);
return static_cast<double>(hour * 3600 + min * 60) + sec;
}
double PqColumnDataSource::convert_datetime(const char* val) {
struct tm date;
date.tm_isdst = -1;
date.tm_year = *val++ - 0x30;
date.tm_year *= 10;
date.tm_year += (*val++ - 0x30);
date.tm_year *= 10;
date.tm_year += (*val++ - 0x30);
date.tm_year *= 10;
date.tm_year += (*val++ - 0x30) - 1900;
LOG_VERBOSE << date.tm_year;
val++;
date.tm_mon = (*val++ - 0x30) * 10;
date.tm_mon += (*val++ - 0x30) - 1;
LOG_VERBOSE << date.tm_mon;
val++;
date.tm_mday = (*val++ - 0x30) * 10;
date.tm_mday += (*val++ - 0x30);
LOG_VERBOSE << date.tm_mday;
val++;
date.tm_hour = (*val++ - 0x30) * 10;
date.tm_hour += (*val++ - 0x30);
LOG_VERBOSE << date.tm_hour;
val++;
date.tm_min = (*val++ - 0x30) * 10;
date.tm_min += (*val++ - 0x30);
LOG_VERBOSE << date.tm_min;
val++;
char* end;
double sec = strtod(val, &end);
val = end;
LOG_VERBOSE << sec;
date.tm_sec = static_cast<int>(sec);
LOG_VERBOSE << date.tm_sec;
int utcoffset = 0;
if (*val == '+' || *val == '-') {
int tz_hours = 0, tz_minutes = 0, sign = 0;
sign = (*val++ == '+' ? +1 : -1);
LOG_VERBOSE << sign;
tz_hours = (*val++ - 0x30) * 10;
tz_hours += (*val++ - 0x30);
LOG_VERBOSE << tz_hours;
if (*val == ':') {
++val;
tz_minutes = (*val++ - 0x30) * 10;
tz_minutes += (*val++ - 0x30);
LOG_VERBOSE << tz_minutes;
}
utcoffset = sign * (tz_hours * 3600 + tz_minutes * 60);
LOG_VERBOSE << utcoffset;
}
time_t time = tm_to_time_t(date);
LOG_VERBOSE << time;
double ret = static_cast<double>(time) + (sec - date.tm_sec) - utcoffset;
LOG_VERBOSE << ret;
return ret;
}
PGresult* PqColumnDataSource::get_result() const {
return result_source->get_result();
}
const char* PqColumnDataSource::get_result_value() const {
const char* val = PQgetvalue(get_result(), 0, get_j());
LOG_VERBOSE << val;
return val;
}
|
#include "VertexBufferAttrib.h"
namespace revel
{
namespace renderer
{
} // ::revel::renderer
} // ::revel
|
class Solution {
public:
bool isMonotonic(vector<int>& A) {
int inc = 1, dec = 1, n = A.size();
for (int i = 1; i < n; ++i) {
inc += (A[i - 1] <= A[i]);
dec += (A[i - 1] >= A[i]);
}
return (inc == n) || (dec == n);
}
};
|
//
// Tower.h
// tower
//
// Created by wangpeng on 15/7/31.
//
//
#ifndef __tower__Tower__
#define __tower__Tower__
#include <stdio.h>
#include "cocos2d.h"
#include "Map1.h"
#include "RoleManager.h"
#include "BulletManager.h"
using namespace cocos2d;
enum TowerType { RED, YELLOW };
class Tower : public cocos2d::Node
{
protected:
int m_iTowerRange;
Sprite* m_tower;
TowerType m_eTowerType;
bool m_bIsMenuTower;
public:
int getTowerRange();
void setTowerRange(int iTowerRange);
//设置、获得是否为菜单中的子类
void setIsMenuTower(bool is);
bool getIsMenuTower();
void setPos(Vec2 v);
Sprite* getTowerSprite();
Vec2 getPos();
virtual bool init();
virtual bool load(std::string fileName);
void shoot(float delta);
void setTowerType(TowerType tp);
TowerType getTowerType();
CREATE_FUNC(Tower);
};
#endif /* defined(__tower__Tower__) */
|
#include <iostream>
using namespace std;
int main()
{
int number = 74;
char letter = 'y';
float mark = 324.45;
double mark2 = 2342423423.3434;
bool value = true;
unsigned int a = 875; //Only postive values
short int b = 14; // only 2 byte
long int c = 165671; //8 bytes
cout << "Size of int = " << sizeof(int) << "bytes\n";
cout << "Size of char = " << sizeof(char) << "bytes\n";
cout << "Size of float = " << sizeof(float) << "bytes\n";
cout << "Size of double = " << sizeof(double) << "bytes\n";
cout << "Size of bool = " << sizeof(bool) << "bytes\n";
cout << "Size of short int = " << sizeof(short int) << "bytes\n";
cout << "Size of long int = " << sizeof(long int) << "bytes\n";
return 0;
}
|
//KaiXinAPI_InitialLogin.h
#ifndef __KaiXinAPI_InitialLogin_H__
#define __KaiXinAPI_InitialLogin_H__
#include "KaiXinAPI.h"
typedef struct
{
int ret;
char msg[64];
char uid[32];
char verify[128];
char wapverify[128];
}tResponseInitialLogin;
extern void* KaiXinAPI_InitialLogin_JsonParse(char *text);
class TInitialLoginForm : public TWindow
{
public:
TInitialLoginForm(TApplication* pApp);
virtual ~TInitialLoginForm(void);
virtual Boolean EventHandler(TApplication * appP, EventType * eventP);
private:
Boolean _OnWinInitEvent(TApplication * pApp, EventType * pEvent);
Boolean _OnWinClose(TApplication * pApp, EventType * pEvent);
Boolean _OnCtrlSelectEvent(TApplication * pApp, EventType * pEvent);
};
#endif
|
#pragma once
class face
{
public:
face();
~face();
};
|
//---------------------------------------------------------------------------
#ifndef JsonVclUtilsH
#define JsonVclUtilsH
//---------------------------------------------------------------------------
namespace Jsonutils {
const UnicodeString JsonTrimSpaces(const UnicodeString &sJson);
}
#endif
|
// This file is subject to the terms and conditions defined in 'LICENSE' in the source code package
#ifndef JACTORIO_INCLUDE_GAME_LOGIC_CONVEYOR_CONTROLLER_H
#define JACTORIO_INCLUDE_GAME_LOGIC_CONVEYOR_CONTROLLER_H
#pragma once
namespace jactorio::game
{
class World;
/// Updates belt logic for a logic chunk
void ConveyorLogicUpdate(World& world);
} // namespace jactorio::game
#endif // JACTORIO_INCLUDE_GAME_LOGIC_CONVEYOR_CONTROLLER_H
|
#include "EurCall.h"
#include "EurPut.h"
#include <iostream>
using namespace std;
int main()
{
double T, K;
int i;
cout << "Enter Time to expiry: " << endl;
cin >> T;
cout << "Enter Strike price: " << endl;
cin >> K;
MarketData Object;
Object.GetMarketData();
cout << "Call (1) or Put (2): " << endl;
cin >> i;
EurOption* p;
switch (i)
{
case 1:
{
p = new EurCall(T, K);
break;
}
case 2:
{
p = new EurPut(T,K);
break;
}
default:
return 0;
}
cout << "The price is: " << p->PriceByBSFormula(Object.GetS0(), Object.Getsigma(), Object.Getr()) << endl;
cout << "The Delta is: " << p->DeltaByBSFormula(Object.GetS0(), Object.Getsigma(), Object.Getr()) << endl;
cout << "The Gamma is: " << p->GammaByBSFormula(Object.GetS0(), Object.Getsigma(), Object.Getr()) << endl;
cout << "The Theta is: " << p->ThetaByBSFormula(Object.GetS0(), Object.Getsigma(), Object.Getr()) << endl;
delete p;
system("pause");
}
|
//
// RoomCardManager.cpp
// demo_ddz
//
// Created by 谢小凡 on 2018/2/16.
//
#include "RoomCardManager.hpp"
#include "RoomData.hpp"
#include "CommonMethodSet.hpp"
#include "SimpleAiActionManager.hpp"
#include "SimpleToastManager.hpp"
#include "audio/include/SimpleAudioEngine.h"
using namespace CocosDenshion;
using namespace cocos2d;
static int Start_Touch_Card_Index = -1;
static Vec2 CardBirthPos(569, 365);
static std::map<RestCTName, std::string> rest_path = {
{RestCTName::DoubleKing, "table_gz_sw.png"},
{RestCTName::SingleKing, "table_gz_dw.png"},
{RestCTName::Straight, "table_gz_shunzi.png"},
{RestCTName::Three, "table_gz_sanzhang.png"},
{RestCTName::Pair, "table_gz_dz.png"},
{RestCTName::Flush, "table_gz_hs.png"}
};
static int GapX_Widest = 65;
static int GapX_Normal = 58;
static int GapX_Narrow = 50;
RoomCardManager::~RoomCardManager() {
RoomDataManager::getInstance()->rmAllCardData();
clearAllCard();
}
void RoomCardManager::createCard(const std::vector<int>& vec) {
if (!_total_card_vec.empty()) {
RoomDataManager::getInstance()->rmAllCardData();
clearAllCard();
}
// 创建 待发牌堆
auto iter_rest = vec.begin() + RoomDataManager::getInstance()->getDealCardNum();
std::for_each(vec.begin(), iter_rest, [this](const int& id){
UICard* card = UICard::create(id);
card->setVisible(false);
this->addChild(card);
_total_card_vec.push_back(card);
});
// 创建 底牌
std::for_each(iter_rest, vec.end(), [this](const int& id){
UICard* card = UICard::create(id);
card->setModel(UICard::Model::RESTCARD);
this->addChild(card);
const static float x = Director::getInstance()->getVisibleSize().width * 0.5;
const static float y = Director::getInstance()->getVisibleSize().height - card->getSizeAfterZoom().height * 0.5;
static int i = 0;
float px = (i++ % 3 - 1) * (card->getSizeAfterZoom().width + 6.0);
card->setPosition(Vec2(px + x, y));
_total_card_vec.push_back(card);
_rest_card_vec.push_back(card);
});
}
void RoomCardManager::clearAllCard() {
auto iter = _total_card_vec.begin();
while (iter != _total_card_vec.end()) {
UICard* card = *iter;
iter = _total_card_vec.erase(iter);
card->removeFromParent();
}
_inside_card.clear();
_outside_card.clear();
_selected_card.clear();
_rest_card_vec.clear();
rmRestCardType();
SimpleAiActionManager::getInstance()->clearAllNumData();
_inside_align_config.at(0).gap_x = GapX_Normal;
/**used for debug. */
clearAllDebugMing();
}
void RoomCardManager::callbackForDeal() {
auto pFun = [&](int index){
auto& vec = _inside_card.at(index);
// 排序
std::sort(vec.begin(), vec.end(), [](const UICard* c1, const UICard* c2){
return c1->getCardData()->getId() > c2->getCardData()->getId();
});
// 挪位
const auto& inside_config = _inside_align_config.at(index);
for (int i = 0; i < vec.size(); ++i) {
UICard* card = vec.at(i);
SingleCardConfig config = getSingleCardConfig(i, vec.size(), inside_config);
MoveTo* mt_1 = MoveTo::create(0.15f, inside_config.align_point);
CallFunc* call = CallFunc::create([card, i]{card->setLocalZOrder(i);});
MoveTo* mt_2 = MoveTo::create(0.15f, config.point);
card->runAction(Sequence::create(DelayTime::create(0.4f), mt_1, DelayTime::create(0.08f), call, mt_2, nullptr));
}
// ai manager
SimpleAiActionManager::getInstance()->addNumData(vec, index);
};
for (int i = 0; i < _inside_card.size(); ++i)
pFun(i);
/**used for debug. */
if (_debug_ming) {
updateDebugMingVec(1);
updateDebugMingVec(2);
}
}
void RoomCardManager::callbackForPushRestCard(int landlord) {
resetSelected(landlord);
for (UICard* card : _rest_card_vec) {
UICard* c2 = UICard::create(card->getCardData());
c2->setModel(UICard::Model::RESTCARD);
c2->setFaceTowardUp(true);
c2->setPosition(card->getPosition());
_total_card_vec.push_back(c2);
this->addChild(c2);
pushCardToInside(card, landlord);
card->setModel(UICard::Model::HANDCARD);
}
// 位置更新
auto& card_vec = _inside_card.at(landlord);
std::sort(card_vec.begin(), card_vec.end(), [](const UICard* c1, const UICard* c2){
return c1->getCardData()->getId() > c2->getCardData()->getId();
});
if (landlord == 0) _inside_align_config.at(0).gap_x = GapX_Narrow;
int size = static_cast<int>(card_vec.size());
for (int i = 0; i < size; ++i) {
UICard* card = card_vec.at(i);
const auto& info = getSingleCardConfig(i, size, _inside_align_config.at(landlord));
card->setLocalZOrder(info.zorder);
card->setScale(info.scale);
if (std::find(_rest_card_vec.begin(), _rest_card_vec.end(), card) == _rest_card_vec.end())
card->runAction(MoveTo::create(0.2f, Vec2(info.point.x, card->getPositionY())));
else
card->setPosition(info.point);
}
if (landlord == 0) {
// 底牌插入动画
for (auto card : _rest_card_vec) {
float delta_y = card->getSizeAfterZoom().height * 0.3;
card->setPositionY(card->getPositionY() + delta_y);
card->runAction(Sequence::create(DelayTime::create(0.7f), MoveBy::create(0.3f, Vec2(0, -delta_y)), nullptr));
card->setFaceTowardUp(true);
}
} else { /**used for debug. */
updateDebugMingVec(landlord);
}
// ai manager
SimpleAiActionManager::getInstance()->addNumData(_rest_card_vec, landlord);
SimpleAiActionManager::getInstance()->setPreId(landlord);
// identify rest card
auto type = SimpleAiActionManager::getInstance()->identifyRestCard(_rest_card_vec);
if (type != RestCTName::Common) {
initRestCardType(rest_path[type],
SimpleAiActionManager::getInstance()->getRestCardMutiple(type));
}
}
bool RoomCardManager::callbackForPopCard(int index) {
/** 出牌流程
* - 如果开启调试明牌:将调试明牌区引用到选牌区
* - 判断 选牌区牌组是否符合出牌要求
* 符合: 将选择的牌 移动到 出牌区 执行出牌动作
* 不符合: 返回false
*/
/**used for debug. */
if (_debug_ming && index != -1)
updateSelectedVecByDebugMing(index);
// judge
auto& selected = _selected_card[index];
auto type = SimpleAiActionManager::getInstance()->doActionPlay(selected, index);
if (type.getCTName() == CTName::Undef)
return false;
// toast
SimpleToastManager::getInstance()->playToast(type.getDescribe());
// action
pushCardToOutside(index);
updateCardDisplayForInside(index);
updateCardDisplayForOutside(index);
return true;
}
void RoomCardManager::pushCardToInside(UICard* card, int index) {
// RoomDataManager::getInstance()->addCardData(card->getCardData(), index);
_inside_card[index].push_back(card);
updateCardCountLabel(index);
}
void RoomCardManager::refCardToSelected(const std::vector<int>& num_vec, int index) {
auto foundX = [](const CardVec& vec, int num){
size_t ret = 0;
for (; ret != vec.size(); ++ret)
if (!vec.at(ret)->isSelected() && vec.at(ret)->getCardData()->getNumber() == num)
break;
return ret;
};
resetSelected(index);
CardVec& inside_vec = _inside_card[index];
for (int num : num_vec) {
size_t i = foundX(inside_vec, num);
if (i != inside_vec.size())
refCardToSelected(inside_vec.at(i), index);
}
/** used for debug **/
if (_debug_ming && index != 0)
updateDebugMingSelected(index);
}
void RoomCardManager::refCardToSelected(UICard* card, int index) {
auto& selected_vec = _selected_card[index];
if (std::find(selected_vec.begin(), selected_vec.end(), card) != selected_vec.end())
return;
selected_vec.push_back(card);
if (!card->isSelected() && index == 0)
card->runAction(MoveBy::create(0.1f, Vec2(0, card->getSizeAfterZoom().height*0.15)));
card->switchSelected(true);
}
void RoomCardManager::derefCardFromSelected(UICard* card, int index) {
auto& selected_vec = _selected_card[index];
auto iter = std::find(selected_vec.begin(), selected_vec.end(), card);
if (iter == selected_vec.end())
return;
selected_vec.erase(iter);
if (card->isSelected() && index == 0)
card->runAction(MoveBy::create(0.1f, Vec2(0, -card->getSizeAfterZoom().height*0.15)));
card->switchSelected(false);
}
void RoomCardManager::resetSelected(int index) {
auto& selected_vec = _selected_card[index];
while (!selected_vec.empty()) {
auto iter = selected_vec.begin();
derefCardFromSelected(*iter, index);
}
/** used for debug **/
if (_debug_ming && index != 0)
updateDebugMingSelected(index);
}
void RoomCardManager::pushCardToOutside(int index) {
/* data process order:
* 清空上一次出的牌
* 清理 RoomData
* 从select区复制到out区
* 清空 select区
*/
clearCardFromOutside(index);
auto& inside_vec = _inside_card[index];
auto& selected_vec = _selected_card[index];
auto& outside_vec = _outside_card[index];
for (UICard* card : selected_vec) outside_vec.push_back(card);
selected_vec.clear();
for (UICard* card : outside_vec) {
// RoomDataManager::getInstance()->rmCardData(card->getCardData(), index);
auto iter = std::find(inside_vec.begin(), inside_vec.end(), card);
if (iter != inside_vec.end()) inside_vec.erase(iter);
}
/**used for debug. */
if (_debug_ming && index != -1)
updateDebugMingVec(index);
}
void RoomCardManager::clearCardFromOutside(int index) {
auto& vec = _outside_card[index];
auto iter = vec.begin();
while (iter != vec.end()) {
UICard* card = *iter;
auto t_iter = std::find(_total_card_vec.begin(), _total_card_vec.end(), card);
if (t_iter != _total_card_vec.end())
_total_card_vec.erase(t_iter);
iter = vec.erase(iter);
card->removeFromParent();
}
}
void RoomCardManager::openListenerForTouchCard() {
if (_listener_touch_card) {
_listener_touch_card->setEnabled(true);
return;
}
_listener_touch_card = EventListenerTouchOneByOne::create();
_listener_touch_card->setSwallowTouches(true);
_listener_touch_card->onTouchBegan = [this](Touch* touch, Event*){
int i = this->getTouchCardIndex(touch);
if (i == -1)
return false;
Start_Touch_Card_Index = i;
this->updateMaskLayerForTouchCard(i, i);
SimpleAudioEngine::getInstance()->playEffect("sound/effect/select_card.mp3");
return true;
};
_listener_touch_card->onTouchMoved = [this](Touch* touch, Event*){
int i = this->getTouchCardIndex(touch);
if (i != -1)
this->updateMaskLayerForTouchCard(Start_Touch_Card_Index, i);
};
_listener_touch_card->onTouchEnded = [this](Touch* touch, Event*){
for (UICard* card : _inside_card[0]) {
if (!card->hasMask())
continue;
card->rmMask();
card->isSelected() ? this->derefCardFromSelected(card, 0) : this->refCardToSelected(card, 0);
// log("selected card size = %lu", _selected_card.at(0).size());
}
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(_listener_touch_card, this);
}
void RoomCardManager::stopListenerForTouchCard() {
if (_listener_touch_card)
_listener_touch_card->setEnabled(false);
}
void RoomCardManager::setDebugMing(bool open) {
_debug_ming = open;
if (_debug_ming) {
updateDebugMingVec(1);
updateDebugMingVec(2);
} else {
clearAllDebugMing();
}
}
void RoomCardManager::clearAllDebugMing() {
for (auto& pair : _debug_card) {
auto iter = pair.second.begin();
while (iter != pair.second.end()) {
UICard* card = *iter;
iter = pair.second.erase(iter);
card->removeFromParent();
}
}
_debug_card.clear();
}
bool RoomCardManager::init() {
initCardAlignConfig();
initCardCountLabel();
return true;
}
void RoomCardManager::initCardAlignConfig() {
// 座位0,1,2的手牌位置参数
CardAlignConfig zero_inside(Vec2(591, 86), 0, 99, GapX_Normal, 0, 1.00);
CardAlignConfig one_inside( Vec2(960, 383), 1, 99, 0, 0, 0.35);
CardAlignConfig two_inside( Vec2(178, 383), -1, 99, 0, 0, 0.35);
_inside_align_config.push_back(zero_inside);
_inside_align_config.push_back(one_inside);
_inside_align_config.push_back(two_inside);
// 座位0,1,2的出牌位置参数
CardAlignConfig zero_outside(Vec2(569, 275), 0, 99, 36, 0, 0.60);
CardAlignConfig one_outside (Vec2(890, 393), 1, 99, -30, 0, 0.50);
CardAlignConfig two_outside (Vec2(248, 393), -1, 99, 30, 0, 0.50);
_outside_align_config.push_back(zero_outside);
_outside_align_config.push_back(one_outside);
_outside_align_config.push_back(two_outside);
// 座位1,2的调试显示手牌位置参数
CardAlignConfig one_ming(Vec2(960, 550), 1, 10, -25, -45, 0.40);
CardAlignConfig two_ming(Vec2(178, 550), -1, 10, 25, -45, 0.40);
_ming_align_config.push_back(one_ming);
_ming_align_config.push_back(two_ming);
}
void RoomCardManager::initCardCountLabel() {
for (int i = 0; i < _inside_align_config.size(); ++i) {
auto label = Label::createWithBMFont("fonts/fonts_yellow_num.fnt", "");
label->setPosition(_inside_align_config.at(i).align_point + Vec2(0, 4));
label->setScale(0.75);
label->setLocalZOrder(RoomDataManager::getInstance()->getTotalCardNum() + 1);
this->addChild(label);
_inside_card_count.push_back(label);
}
}
void RoomCardManager::updateCardCountLabel(int index) {
if (index == 0)
return;
ssize_t val = _inside_card[index].size();
std::string count = val == 0 ? "" : std::to_string(val);
auto& label = _inside_card_count.at(index);
label->setString(count);
}
void RoomCardManager::updateCardDisplayForInside(int index) {
auto& vec = _inside_card.at(index);
int size = static_cast<int>(vec.size());
CardAlignConfig& align = _inside_align_config[index];
// 调整手牌间距
if (index == 0) {
if (size > 9 && size <= 17 && align.gap_x != GapX_Normal)
align.gap_x = GapX_Normal;
else if (size <= 9 && align.gap_x != GapX_Widest)
align.gap_x = GapX_Widest;
}
for (int i = 0; i < size; ++i) {
UICard* card = vec.at(i);
SingleCardConfig info = getSingleCardConfig(i, size, align);
card->runAction(MoveTo::create(0.1f, Vec2(info.point.x, card->getPositionY())));
}
updateCardCountLabel(index);
// if (vec.size() == 2)
// RoomAnimationManager::getInstance()->playAlertAnima(index, 2);
// else if (vec.size() == 1)
// RoomAnimationManager::getInstance()->playAlertAnima(index, 1);
}
void RoomCardManager::updateCardDisplayForOutside(int index) {
auto& vec = _outside_card[index];
int size = static_cast<int>(vec.size());
if (index == 0) {
for (int i = 0; i < size; ++i) {
UICard* card = vec.at(i);
if (card->hasMask())
card->rmMask();
const SingleCardConfig& config = getSingleCardConfig(i, size, _outside_align_config[index]);
MoveBy* mb = MoveBy::create(0.12f, Vec2(0, card->getSizeAfterZoom().height * 0.4));
CallFunc* fade_out = CallFunc::create([card]{
card->getFaceUp()->runAction(FadeOut::create(0.12f));
for (auto& child : card->getFaceUp()->getChildren()) child->runAction(FadeOut::create(0.12f));
});
Spawn* sp = Spawn::create(ScaleTo::create(0.12f, config.scale), MoveTo::create(0.12f, config.point), nullptr);
CallFunc* call = CallFunc::create([card, config]{
card->setLocalZOrder(config.zorder);
card->setModel(UICard::Model::TABLECARD);
});
CallFunc* fade_in = CallFunc::create([card]{
card->getFaceUp()->runAction(FadeIn::create(0.12f));
for (auto& child : card->getFaceUp()->getChildren()) child->runAction(FadeIn::create(0.12f));
});
card->runAction(Sequence::create(fade_out, mb, call, sp, fade_in, nullptr));
}
} else {
for (int i = 0; i < size; ++i) {
UICard* card = vec.at(i);
card->setModel(UICard::Model::TABLECARD);
card->setFaceTowardUp(true);
const SingleCardConfig& config = getSingleCardConfig(i, size, _outside_align_config[index]);
card->setLocalZOrder(config.zorder);
card->setScale(config.scale);
card->runAction(MoveTo::create(0.15f, config.point));
}
}
SimpleAudioEngine::getInstance()->playEffect("sound/effect/play_card.mp3");
}
int RoomCardManager::getTouchCardIndex(Touch* touch) const {
const auto& vec = _inside_card.at(0);
if (vec.empty())
return -1;
Vec2 first_card_pos = vec.front()->getLeftBottomPosition();
Size card_size = vec.front()->getSizeAfterZoom();
Vec2 touch_in_card = this->convertTouchToNodeSpace(touch);
if (touch_in_card.x < first_card_pos.x ||
touch_in_card.x > first_card_pos.x +
(vec.size() - 1) * _inside_align_config.at(0).gap_x +
card_size.width)
return -1;
int ret = MIN((touch_in_card.x - first_card_pos.x) / _inside_align_config.at(0).gap_x,
static_cast<int>(vec.size() - 1));
Vec2 target_pos = vec.at(ret)->getLeftBottomPosition();
if (touch_in_card.y < target_pos.y ||
touch_in_card.y > target_pos.y + card_size.height)
return -1;
return ret;
}
void RoomCardManager::updateMaskLayerForTouchCard(int first, int last) {
if (first > last)
std::swap(first, last);
auto& vec = _inside_card[0];
for (int i = 0; i != vec.size(); ++i)
i >= first && i <= last ? vec.at(i)->addMask() : vec.at(i)->rmMask();
}
void RoomCardManager::adjustCardAlign(UICard* card, int idx, int size, const CardAlignConfig& align) {
SingleCardConfig config = getSingleCardConfig(idx, size, align);
card->setScale(config.scale);
card->setPosition(config.point);
card->setLocalZOrder(config.zorder);
}
void RoomCardManager::updateDebugMingVec(int index) {
if (!_debug_ming || index == 0)
return;
const auto& inside_vec = _inside_card[index];
auto& debug_vec = _debug_card[index];
if (inside_vec.size() == debug_vec.size())
return;
// remove from debug_vec
auto d_iter = debug_vec.begin();
while (inside_vec.size() < debug_vec.size() && d_iter != debug_vec.end()) {
int id = (*d_iter)->getCardData()->getId();
bool need_remove = true;
for (auto& card : inside_vec) {
int cmp = card->getCardData()->getId();
if (cmp > id) continue;
if (cmp == id) need_remove = false;
break;
}
if (need_remove) {
UICard* card = *d_iter;
d_iter = debug_vec.erase(d_iter);
card->removeFromParent();
}
else
++d_iter;
}
// add to debug_vec
auto i_iter = inside_vec.begin();
while (inside_vec.size() > debug_vec.size() && i_iter != inside_vec.end()) {
int id = (*i_iter)->getCardData()->getId();
bool need_add = true;
auto d_iter = debug_vec.begin();
for ( ; d_iter != debug_vec.end(); ++d_iter) {
int cmpId = (*d_iter)->getCardData()->getId();
if (cmpId > id) continue;
if (cmpId == id) need_add = false;
break;
}
if (need_add) {
UICard* card = UICard::create(id);
card->setModel(UICard::Model::TABLECARD);
card->setFaceTowardUp(true);
debug_vec.insert(d_iter, card);
card->openTouchListenerForDebug();
this->addChild(card);
}
++i_iter;
}
// adjust debug_card position
int size = static_cast<int>(debug_vec.size());
const auto& config = _ming_align_config.at(index - 1);
for (int i = 0; i < size; ++i)
adjustCardAlign(debug_vec.at(i), i, size, config);
}
void RoomCardManager::updateSelectedVecByDebugMing(int index) {
if (!_debug_ming || index == 0)
return;
auto& debug_vec = _debug_card[index];
auto& inside_vec = _inside_card[index];
for (size_t i = 0; i < debug_vec.size(); ++i)
debug_vec[i]->isSelected() ? refCardToSelected(inside_vec[i], index)
: derefCardFromSelected(inside_vec[i], index);
}
void RoomCardManager::updateDebugMingSelected(int index) {
if (!_debug_ming || index == 0)
return;
auto& debug_vec = _debug_card[index];
auto& inside_vec = _inside_card[index];
for (size_t i = 0; i < inside_vec.size(); ++i) {
if (inside_vec[i]->isSelected()) {
debug_vec[i]->addMask();
debug_vec[i]->switchSelected(true);
} else {
debug_vec[i]->rmMask();
debug_vec[i]->switchSelected(false);
}
}
}
void RoomCardManager::initRestCardType(const std::string& path, int x) {
Sprite* sp = Sprite::createWithSpriteFrameName("table_gz_frame.png");
Sprite* type = Sprite::createWithSpriteFrameName(path);
Sprite* val = Sprite::createWithSpriteFrameName("table_gz_x" + std::to_string(x) + ".png");
type->setPosition(20, sp->getContentSize().height*0.5);
sp->addChild(type);
val->setPosition(47, sp->getContentSize().height*0.5);
sp->addChild(val);
this->addChild(sp, 10, "RestCarType");
sp->setPosition(Director::getInstance()->getVisibleSize().width * 0.5,
Director::getInstance()->getVisibleSize().height - 40);
sp->setRotation(-15);
}
void RoomCardManager::rmRestCardType() {
auto child = this->getChildByName("RestCarType");
if (child) child->removeFromParent();
}
|
#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<cmath>
#define eps 1e-8
#define NMAX 100
using namespace std;
typedef vector<double> vec;
typedef vector<vec> mat;
int col[NMAX];
int r;
mat gauss(mat A, vec b){
/*
GaussianEliminationの特殊な場合として,Ax = b を解く
*/
int n = A.size();
mat Z(n, vec(n+1));
// Zの初期化
for(int i=0; i<n; ++i){
for(int j=0; j<n; ++j){
Z[i][j] = A[i][j];
}
Z[i][n] = b[i];
}
r = 0;
while(r < n){
double z_pq = Z[r][r];
int p = r, q = r;
for(int i=r; i<n; ++i){
for(int j=r; j<n; ++j){
if(abs(z_pq) < abs(Z[i][j])){
z_pq = Z[i][j];
p = i;
q = j;
}
}
}
if(abs(z_pq) < eps){
break;
}
if(p != r){
for(int j=0; j<n+1; ++j){
swap(Z[p][j], Z[r][j]); //行pとrの交換
}
swap(row[p], row[r]);
}
if(q != r){
for(int i=0; i<n; ++i){
swap(Z[i][q], Z[i][r]); //列qとrの交換
}
swap(col[q], col[r]);
}
double alpha;
for(int i=r+1; i<n; ++i){
alpha = Z[i][r] / Z[r][r];
for(int j=r; j<n+1; ++j){
Z[i][j] -= alpha * Z[r][j];
}
}
r++;
}
for(int k=r-1; k >= 1; --k){
for(int i=0; i<=k-1; ++i){
double alpha = Z[i][k] / Z[k][k];
for(int j=k; j<n+1; ++j){
Z[i][j] -= alpha * Z[k][j];
}
}
}
for(int k=0; k<r; ++k){
double alpha = Z[k][k];
for(int j=0; j<n+1; ++j){
Z[k][j] /= alpha;
}
}
return Z;
}
int main(){
return 0;
}
|
#include <iostream>
#include<vector>
using namespace std;
bool func(vector<int> v,long long int sum)
{
long long int lsum,rsum;
lsum=0;
rsum=sum;
for(int i=0;i<v.size();i++)
{
lsum+=(i>0)?v[i-1]:0;
rsum-=v[i];
if(lsum==rsum)
return 1;
}
return 0;
}
int main() {
int tc;
cin>>tc;
while(tc--)
{
int n;
cin>>n;
long long int sum=0;
vector<int> v;
while(n--)
{
int p;
cin>>p;
v.push_back(p);
sum+=p;
}
if(func(v,sum))
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;
}
|
#ifndef _Scene_h_
#define _Scene_h_
class Scene
{
public:
void __cdecl SetRenderAABB(bool);
};
#endif
|
#pragma once
#include <map>
#include <vector>
#include <string>
#include "Common.hpp"
#include "Platform.hpp"
namespace rustling
{
class PlatformMgr
{
protected:
static std::vector<cl_platform_id> platforms;
public:
static std::size_t getNumPlatforms();
static Platform makePlatform(cl_device_type type);
static std::vector<Platform> makePlatforms(cl_device_type type);
static std::map<cl_device_type, cl_uint> checkDevices(cl_platform_id platform);
};
}
|
#include "catch.hpp"
#include "base/piecewise_interval.h"
#include "base/interval.h"
#include "base/interval_algo.h"
#include "base/std_ext/math.h"
#include <iostream>
#include <sstream>
using namespace std;
using namespace ant;
TEST_CASE("Interval: Default ctor", "[base]") {
REQUIRE_NOTHROW( interval<int> a(0,10); );
}
TEST_CASE("Interval: Length", "[base]") {
interval<double> a(0,10);
REQUIRE(a.Length()==10);
}
TEST_CASE("Interval: Inersect", "[base]") {
interval<int> a(0,100);
interval<int> b(50,150);
interval<int> c = intersect(a,b);
REQUIRE(c.Start()==50);
REQUIRE(c.Stop()==100);
interval<int> d = intersect(b,a);
REQUIRE(c.Start()==50);
REQUIRE(c.Stop()==100);
}
TEST_CASE("Interval: Parse from string", "[base]") {
interval<double> a(std_ext::NaN, std_ext::NaN);
stringstream ss_a;
ss_a << "[7.3:6.9]";
REQUIRE(ss_a >> a);
REQUIRE(a.Start() == Approx(7.3));
REQUIRE(a.Stop() == Approx(6.9));
stringstream ss_b;
ss_b << a;
interval<double> b(std_ext::NaN, std_ext::NaN);
REQUIRE(ss_b >> b);
REQUIRE(b == a);
stringstream ss_c;
ss_c << "5.6:2.1 [4.3:6.9]";
interval<double> c1(std_ext::NaN, std_ext::NaN);
REQUIRE(ss_c >> c1);
REQUIRE(c1.Start() == Approx(5.6));
REQUIRE(c1.Stop() == Approx(2.1));
interval<double> c2(std_ext::NaN, std_ext::NaN);
REQUIRE(ss_c >> c2);
REQUIRE(c2.Start() == Approx(4.3));
REQUIRE(c2.Stop() == Approx(6.9));
stringstream ss_d;
ss_d << "456";
interval<int> d1(0,0);
REQUIRE(ss_d >> d1);
REQUIRE(d1.Start() == 456);
REQUIRE(d1.Stop() == 456);
stringstream ss_e;
ss_e << "6.7:23.1";
interval<double> e(std_ext::NaN, std_ext::NaN);
REQUIRE(ss_e >> e);
REQUIRE(e.Start() == Approx(6.7));
REQUIRE(e.Stop() == Approx(23.1));
}
TEST_CASE("Piecewiese Interval: Default ctor", "[base]") {
REQUIRE_NOTHROW( PiecewiseInterval<int> a; );
}
TEST_CASE("Piecewiese Interval: ctor from interval initializer list", "[base]") {
REQUIRE_NOTHROW( PiecewiseInterval<int> a({ interval<int>(2,3) }); );
}
TEST_CASE("Piecewiese Interval: Print ", "[base]") {
PiecewiseInterval<int> a({interval<int>(2,3),interval<int>(5,7)});
stringstream ss_out;
ss_out << a;
REQUIRE(ss_out.str() == "[[2:3][5:7]]");
}
TEST_CASE("Piecewiese Interval: Contrains ", "[base]") {
PiecewiseInterval<int> a({interval<int>(1,3),interval<int>(5,7)});
REQUIRE(a.Contains(2));
REQUIRE(!a.Contains(0));
REQUIRE(a.Contains(6));
REQUIRE(!a.Contains(9));
}
TEST_CASE("Piecewiese Interval: Compact1 ", "[base]") {
PiecewiseInterval<int> a({interval<int>(2,4),interval<int>(3,7)});
a.Compact();
REQUIRE(a.size()==1);
REQUIRE(a.front() == interval<int>(2,7));
}
TEST_CASE("Piecewiese Interval: Compact2 ", "[base]") {
PiecewiseInterval<int> a({interval<int>(2,4), interval<int>(0,1), interval<int>(3,7), interval<int>(-5,0)});
a.Compact();
REQUIRE(a.size()==2);
REQUIRE(a == PiecewiseInterval<int>({interval<int>(2,7),interval<int>(-5,1)}));
}
TEST_CASE("Piecewiese Interval: Parse from string", "[base]") {
stringstream ss_a;
ss_a << "[[2:3][5:7]]";
PiecewiseInterval<int> a;
REQUIRE(ss_a >> a);
REQUIRE(a.size() == 2);
REQUIRE(a.front() == interval<int>(2,3));
REQUIRE(a.back() == interval<int>(5,7));
stringstream ss_b;
ss_b << "2;6-7";
PiecewiseInterval<int> b;
REQUIRE(ss_b >> b);
REQUIRE(b.size() == 2);
REQUIRE(b.front() == interval<int>(2,2));
REQUIRE(b.back() == interval<int>(6,7));
PiecewiseInterval<int> c_in({{4,5},{3,1},{7,8}});
stringstream ss_c;
ss_c << c_in;
PiecewiseInterval<int> c_out;
REQUIRE(ss_c >> c_out);
REQUIRE(c_in == c_out);
}
TEST_CASE("Interval algos", "[base]") {
const interval<double> a = {0, 10};
REQUIRE(step(a,3,1) == Approx(5.0));
std::vector<double> x;
for(auto s =stepper(a,3); !s.Done(); s.Next()) {
x.push_back(s.value);
}
REQUIRE(x.size() == 3);
REQUIRE(x.at(0) == Approx(0));
REQUIRE(x.at(1) == Approx(5));
REQUIRE(x.at(2) == Approx(10));
x.clear();
for(const auto& v : Range(a,3)) {
x.push_back(v);
}
REQUIRE(x.size() == 3);
REQUIRE(x.at(0) == Approx(0));
REQUIRE(x.at(1) == Approx(5));
REQUIRE(x.at(2) == Approx(10));
}
|
// ****************** CHydroSimulatorDrv.cpp *******************************
// Generated by TwinCAT Target for MATLAB/Simulink (TE1400)
// MATLAB R2019a (win64)
// TwinCAT 3.1.4022
// TwinCAT Target 1.2.1237
// Beckhoff Automation GmbH & Co. KG (www.beckhoff.com)
// *************************************************************
#include "TcPch.h"
#pragma hdrstop
#define DEVICE_MAIN
#include "CHydroSimulatorDrv.h"
#include "CHydroSimulator.h"
#include "CHydroSimulatorClassFactory.h"
#include "HydroSimulatorVersion.h"
DECLARE_GENERIC_DEVICE(HydroSimulatorDRV)
#undef DEVICE_MAIN
IOSTATUS CHydroSimulatorDrv::OnLoad( )
{
TRACE(_T("CHydroSimulatorClassFactory::OnLoad()\n") );
m_pObjClassFactory = new CHydroSimulatorClassFactory();
return IOSTATUS_SUCCESS;
}
VOID CHydroSimulatorDrv::OnUnLoad( )
{
delete m_pObjClassFactory;
}
unsigned long _cdecl CHydroSimulatorDrv::HydroSimulator_GetVersion( )
{
return(0);
}
|
#ifndef METROMAP_UI_MAPVIEW_H
#define METROMAP_UI_MAPVIEW_H
#include <QPointF>
#include <QWidget>
template <typename T> class QList;
namespace Ui {
class MapView;
} // Ui
namespace metro {
class CrossOverItem;
class MetroMapMainWindow;
class StationItem;
class RailTrackItem;
class MapView : public QWidget
{
Q_OBJECT
enum mode_t {
SHOW,
EDIT
};
public:
explicit MapView(MetroMapMainWindow* ctrl, QWidget* parent = 0);
~MapView();
signals:
void stationSelected(quint32 id);
void stationDeselected(quint32 id);
void fromSelected(quint32 id);
void toSelected(quint32 id);
void stationEdited(quint32 id);
void stationAdded(quint32 id);
void stationRemoved(quint32 id);
public slots:
void slotSelectStations(quint32 id);
void slotSelectStations(const QList<quint32>& stations);
void slotShowRoute(const QList<quint32>& stations);
void slotToShowMode();
void slotToEditMode();
private slots:
void slotMapChanged();
void slotDeselectStation(quint32 id);
void slotAddStation();
void slotAddStation(const QPointF& pos);
void slotEditStation();
void slotRemoveStation();
private:
void initScene();
void renderStations();
void renderRailTracks();
void renderCrossOvers();
void renderEditLabelAndLines();
StationItem* stationItemById(quint32 id) const;
RailTrackItem* railTrackItemById(quint32 from, quint32 to) const;
CrossOverItem* crossOverItemById(quint32 from, quint32 to) const;
void clearSelection();
void transparenceRoute(const QList<quint32>& route);
QList<quint32> selectedStations() const;
void selectStation(StationItem* item);
StationItem* addStation(quint32 id, const QColor& color, const QPointF& pos = QPointF());
void setEnableStationsMoving(bool enable);
void showContextMenu(const QPoint& pos);
bool eventFilter(QObject* watched, QEvent* event);
private:
Ui::MapView* m_ui;
MetroMapMainWindow* m_controller;
mode_t m_mode;
bool m_hasRoute;
quint32 m_from;
quint32 m_to;
};
} // metro
#endif // METROMAP_UI_MAPVIEW_H
|
#include "Vector3.h"
#include <math.h>
using namespace kyrbos;
//---------------------------------------------
Vector3::Vector3(float x, float y, float z){
this->x = x;
this->y = y;
this->z = z;
}
//---------------------------------------------
Vector3::Vector3() : x(0), y(0), z(0){
}
//---------------------------------------------
Vector3 Vector3::operator +(const Vector3& vector) const{
return Vector3(this->x + vector.x , this->y + vector.y , this->z + vector.z);
}
//---------------------------------------------
Vector3& Vector3::operator +=(const Vector3& vector){
x+= vector.x;
y+= vector.y;
z+= vector.z;
return *this;
}
//---------------------------------------------
Vector3 Vector3::operator -(const Vector3& vector) const{
return Vector3(this->x - vector.x , this->y - vector.y , this->z - vector.z);
}
//---------------------------------------------
Vector3& Vector3::operator -=(const Vector3& vector){
x-= vector.x;
y-= vector.y;
z-= vector.z;
return *this;
}
//---------------------------------------------
Vector3 Vector3::operator *(const float& escalar) const{
return Vector3(this->x * escalar , this->y * escalar , this->z * escalar);
}
//---------------------------------------------
Vector3& Vector3::operator *=(const float& escalar){
x*= escalar;
y*= escalar;
z*= escalar;
return *this;
}
//---------------------------------------------
Vector3 Vector3::operator /(const float& n) const {
return Vector3(this->x / n , this->y / n , this->z / n);
}
//---------------------------------------------
Vector3& Vector3::operator /=(const float& n){
x/= n;
y/= n;
z/= n;
return *this;
}
//---------------------------------------------
Vector3& Vector3::operator =(const Vector3& vector){
x= vector.x;
y= vector.y;
z= vector.z;
return *this;
}
//---------------------------------------------
bool Vector3::operator ==(const Vector3& vector) const{
return (this->x == vector.x && this->y == vector.y && this->z == vector.z);
}
//---------------------------------------------
bool Vector3::operator !=( const Vector3& vector) const{
return !(*this == vector);
}
//---------------------------------------------
float Vector3::GetMagnitude() const{
return sqrt(x*x+y*y+z*z);
}
//---------------------------------------------
Vector3 Vector3::Normalize(){
float mag = this->GetMagnitude();
return Vector3(this->x / mag , this->y / mag , this->z / mag);
}
//---------------------------------------------
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "TankTurret.h"
#include "Classes/Engine/World.h"
void UTankTurret::RotateTurret(float RelativeSpeed)
{
RelativeSpeed = FMath::Clamp<float>(RelativeSpeed, -1, 1);
auto ElevationChange = MaxDegreesPerSecond * RelativeSpeed * GetWorld()->DeltaTimeSeconds;
auto RawNewElevation = RelativeRotation.Yaw + ElevationChange;
SetRelativeRotation(FRotator(RelativeRotation.Pitch, RawNewElevation, RelativeRotation.Roll));
}
|
#pragma once
#include "slice.h"
namespace data
{
class blank_slice : public slice
{
public:
blank_slice()
{
}
virtual pslice clone() const
{
return pslice ( new blank_slice );
}
virtual pslice clone(const std::vector<unsigned> &other) const
{
return clone();
}
virtual unsigned size() const
{
return 0;
}
virtual const double &get_value(unsigned index, aera::chars=aera::C_Time, int channel=0) const
{
assert(false);
throw not_implemented(HERE);
}
virtual std::vector<aera::chars> get_chars() const
{
return std::vector<aera::chars>();
}
// fat interface
// raw
virtual raw_record get_raw_record(unsigned index) const
{
throw not_implemented(HERE);
}
// tdd
virtual unsigned get_channel_count() const
{
throw not_implemented(HERE);
}
};
}
|
/*
* Copyright (C) 2012-2016 Open Source Robotics Foundation
*
* 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.
*
*/
/*
* Author: Jennifer Buehler
*/
#ifndef COLLISION_BENCHMARK_MESHHELPER
#define COLLISION_BENCHMARK_MESHHELPER
#include <collision_benchmark/MeshData.hh>
#include <assimp/Exporter.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <assimp/cimport.h>
#include <boost/filesystem.hpp>
#include <vector>
#include <string>
namespace collision_benchmark
{
std::string SetOrReplaceFileExtension(const std::string &in,
const std::string &ext)
{
boost::filesystem::path p(in);
boost::filesystem::path swapped = p.replace_extension(ext);
return swapped.string();
}
aiMaterial * GetDefaultMaterial()
{
aiMaterial* mat = new aiMaterial();
/*mat->AddProperty(&srcMat.diffuse, 1,AI_MATKEY_COLOR_DIFFUSE);
mat->AddProperty(&srcMat.specular, 1,AI_MATKEY_COLOR_SPECULAR);
mat->AddProperty(&srcMat.ambient, 1,AI_MATKEY_COLOR_AMBIENT);
mat->AddProperty(&srcMat.transparency, 1, AI_MATKEY_SHININESS);
int m = (int)aiShadingMode_Phong;
mat->AddProperty(&m, 1, AI_MATKEY_SHADING_MODEL);
if (srcMat.name.length)
mat->AddProperty(&srcMat.name, AI_MATKEY_NAME);
*/
return mat;
}
template<typename Float = float>
aiScene *
CreateTrimeshScene(const typename
collision_benchmark::MeshData<Float, 3>::ConstPtr &meshData)
{
// Create new aiScene (aiMesh)
aiScene *assimpScene = new aiScene;
aiMesh *assimpMesh = new aiMesh;
assimpScene->mNumMeshes = 1;
assimpScene->mMeshes = new aiMesh*[1];
assimpScene->mMeshes[0] = assimpMesh;
aiNode * rootNode = new aiNode();
rootNode->mName.Set("Root");
rootNode->mNumMeshes = 1;
rootNode->mMeshes = new unsigned int[1];
rootNode->mMeshes[0] = 0;
assimpScene->mRootNode = rootNode;
// add an empty material (required otherwise get assimp errors
// in PretransformVertices when exporting)
assimpScene->mNumMaterials = 1;
assimpScene->mMaterials = new aiMaterial*[1];
assimpScene->mMaterials[0] = GetDefaultMaterial();
assimpMesh->mMaterialIndex = 0;
int numVertices = meshData->GetVertices().size();
int numFaces = meshData->GetFaces().size();
// Set vertices and normals
assimpMesh->mNumVertices = numVertices;
assimpMesh->mVertices = new aiVector3D[numVertices];
assimpMesh->mNormals = new aiVector3D[numVertices];
aiVector3D itAIVector3d;
typedef MeshData<Float, 3> MeshDataT;
typedef typename MeshDataT::Vertex Vertex;
typedef typename MeshDataT::Face Face;
const std::vector<Vertex>& vertices = meshData->GetVertices();
const std::vector<Face>& faces = meshData->GetFaces();
for (unsigned int i = 0; i < numVertices; ++i)
{
itAIVector3d.Set(vertices[i].X(),
vertices[i].Y(),
vertices[i].Z());
assimpMesh->mVertices[i] = itAIVector3d;
// this normal has no meaning, it will have to be
// calculated in a postprocessing step. Unfortunately had
// problems doing it locally with
// aiApplyPostProcessing (assimpScene, aiProcess_GenNormals)
// so do it in the exporter instead.
assimpMesh->mNormals[i] = itAIVector3d;
}
// Set faces
assimpMesh->mNumFaces = numFaces;
assimpMesh->mFaces = new aiFace[assimpMesh->mNumFaces];
for (unsigned int i = 0; i < assimpMesh->mNumFaces; ++i)
{
aiFace* itAIFace = &assimpMesh->mFaces[i];
itAIFace->mNumIndices = 3;
itAIFace->mIndices = new unsigned int[3];
itAIFace->mIndices[0] = faces[i].val[0];
itAIFace->mIndices[1] = faces[i].val[1];
itAIFace->mIndices[2] = faces[i].val[2];
}
return assimpScene;
}
/**
* \param filename file to write to. It does not need to have an extension,
* as \e outformat will be added as extension. If it has an extension,
* it will be replace by \e outformat
* \param outformat format to write it as, must be of the types
* supported by assimp (e.g. "dae", "stl", "obj")
* \param meshData the mesh data to be written
*/
template<typename Float = float>
bool WriteTrimesh(const std::string &filename,
const std::string &outformat,
const typename collision_benchmark::MeshData
<Float, 3>::ConstPtr &meshData)
{
aiScene * scene = CreateTrimeshScene(meshData);
if (!scene)
{
std::cerr << "Could not create trimesh scene" << std::endl;
return false;
}
std::string fname = SetOrReplaceFileExtension(filename, outformat);
// std::cout << "Writing to file " << fname << std::endl;
Assimp::Exporter exporter;
if (exporter.Export(scene, outformat, fname, aiProcess_GenNormals)\
!= AI_SUCCESS)
{
std::cerr << "Could not write " << fname << " in the format "
<< outformat << ". Error: " << exporter.GetErrorString()
<< std::endl;
return false;
}
delete scene;
return true;
}
} // namespace
#endif // COLLISION_BENCHMARK_MESHHELPER
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
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 University of Oxford 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.
*/
#ifndef TESTCRYPTDIVISIONRULES_HPP_
#define TESTCRYPTDIVISIONRULES_HPP_
#include <cxxtest/TestSuite.h>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include "ArchiveOpener.hpp"
#include "HoneycombMeshGenerator.hpp"
#include "PottsMeshGenerator.hpp"
#include "CellsGenerator.hpp"
#include "MeshBasedCellPopulation.hpp"
#include "NodeBasedCellPopulation.hpp"
#include "CryptCellsGenerator.hpp"
#include "FixedG1GenerationalCellCycleModel.hpp"
#include "DifferentiatedCellProliferativeType.hpp"
#include "AbstractCellBasedTestSuite.hpp"
#include "RandomDirectionCentreBasedDivisionRule.hpp"
#include "CryptCentreBasedDivisionRule.hpp"
#include "CryptVertexBasedDivisionRule.hpp"
#include "CryptShovingCaBasedDivisionRule.hpp"
#include "SmartPointers.hpp"
// This test is always run sequentially (never in parallel)
#include "FakePetscSetup.hpp"
class TestCryptDivisionRules : public AbstractCellBasedTestSuite
{
public:
void TestCryptCentreBasedDivisionRule1d()
{
// Create a 2d cell population
MutableMesh<1,1> mesh;
mesh.ConstructLinearMesh(21);
ChastePoint<1> shifted_point;
shifted_point.rGetLocation()[0] = 10.5;
mesh.SetNode(10, shifted_point);
std::vector<CellPtr> cells;
MAKE_PTR(WildTypeCellMutationState, p_healthy_state);
MAKE_PTR(DifferentiatedCellProliferativeType, p_diff_type);
for (unsigned node_index=0; node_index<mesh.GetNumNodes(); node_index++)
{
FixedG1GenerationalCellCycleModel* p_model = new FixedG1GenerationalCellCycleModel();
CellPtr p_cell(new Cell(p_healthy_state, p_model));
p_cell->SetCellProliferativeType(p_diff_type);
double birth_time = 0.0 - node_index;
p_cell->SetBirthTime(birth_time);
cells.push_back(p_cell);
}
MeshBasedCellPopulation<1,1> cell_population(mesh, cells);
CellPtr p_cell0 = cell_population.GetCellUsingLocationIndex(0);
// Set the division rule for our population to be the random direction division rule
boost::shared_ptr<AbstractCentreBasedDivisionRule<1,1> > p_division_rule_to_set(new CryptCentreBasedDivisionRule<1,1>());
cell_population.SetCentreBasedDivisionRule(p_division_rule_to_set);
// Get the division rule back from the population
boost::shared_ptr<AbstractCentreBasedDivisionRule<1,1> > p_division_rule = cell_population.GetCentreBasedDivisionRule();
std::pair<c_vector<double, 1>, c_vector<double, 1> > positions = p_division_rule->CalculateCellDivisionVector(p_cell0, cell_population);
c_vector<double, 1> parent_position = positions.first;
c_vector<double, 1> daughter_position = positions.second;
TS_ASSERT_DELTA(parent_position[0], 0.0, 1e-4);
TS_ASSERT_DELTA(daughter_position[0], 0.15, 1e-4);
}
void TestCryptCentreBasedDivisionRule2d()
{
// Create a 2d cell population
c_vector<double,2> location;
location[0] = 1.0;
location[1] = 1.0;
Node<2>* p_node = new Node<2>(0u,location, false);
MutableMesh<2,2> conf_mesh;
conf_mesh.AddNode(p_node);
// Create cells
std::vector<CellPtr> conf_cells;
CryptCellsGenerator<FixedG1GenerationalCellCycleModel> cells_generator;
cells_generator.Generate(conf_cells, &conf_mesh, std::vector<unsigned>(), true);
// Create cell population
MeshBasedCellPopulation<2,2> cell_population(conf_mesh, conf_cells);
cell_population.SetMeinekeDivisionSeparation(0.1);
CellPtr p_cell0 = *(cell_population.Begin());
// Set the division rule for our population to be the random direction division rule
boost::shared_ptr<AbstractCentreBasedDivisionRule<2,2> > p_division_rule_to_set(new CryptCentreBasedDivisionRule<2,2>());
cell_population.SetCentreBasedDivisionRule(p_division_rule_to_set);
// Get the division rule back from the population
boost::shared_ptr<AbstractCentreBasedDivisionRule<2,2> > p_division_rule = cell_population.GetCentreBasedDivisionRule();
std::pair<c_vector<double, 2>, c_vector<double, 2> > positions = p_division_rule->CalculateCellDivisionVector(p_cell0, cell_population);
c_vector<double, 2> parent_position = positions.first;
c_vector<double, 2> daughter_position = positions.second;
TS_ASSERT_DELTA(parent_position[0], 1.0417, 1e-4);
TS_ASSERT_DELTA(parent_position[1], 1.0275, 1e-4);
TS_ASSERT_DELTA(daughter_position[0], 0.9582, 1e-4);
TS_ASSERT_DELTA(daughter_position[1], 0.9724, 1e-4);
}
void TestCryptCentreBasedDivisionRule3d()
{
// Create a 3d cell population
TrianglesMeshReader<3,3> mesh_reader("mesh/test/data/3D_Single_tetrahedron_element");
MutableMesh<3,3> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
std::vector<CellPtr> cells;
CellsGenerator<FixedG1GenerationalCellCycleModel,3> cells_generator;
cells_generator.GenerateBasic(cells, mesh.GetNumNodes());
MeshBasedCellPopulation<3,3> cell_population(mesh, cells);
CellPtr p_cell0 = *(cell_population.Begin());
// Set the division rule for our population to be the random direction division rule
boost::shared_ptr<AbstractCentreBasedDivisionRule<3,3> > p_division_rule_to_set(new CryptCentreBasedDivisionRule<3,3>());
cell_population.SetCentreBasedDivisionRule(p_division_rule_to_set);
// Get the division rule back from the population
boost::shared_ptr<AbstractCentreBasedDivisionRule<3,3> > p_division_rule = cell_population.GetCentreBasedDivisionRule();
TS_ASSERT_THROWS_THIS(p_division_rule->CalculateCellDivisionVector(p_cell0, cell_population),
"CryptCentreBasedDivisionRule is not implemented for SPACE_DIM == 3");
}
void TestCryptVertexBasedDivisionRule()
{
// Create a vertex cell population
std::vector<Node<2>*> nodes;
nodes.push_back(new Node<2>(0, true, 2.0, 0.0));
nodes.push_back(new Node<2>(1, true, 0.0, 2.0));
nodes.push_back(new Node<2>(2, true, -2.0, 0.0));
nodes.push_back(new Node<2>(3, true, 0.0, -2.0));
std::vector<Node<2>*> nodes_elem_1;
nodes_elem_1.push_back(nodes[0]);
nodes_elem_1.push_back(nodes[1]);
nodes_elem_1.push_back(nodes[2]);
nodes_elem_1.push_back(nodes[3]);
std::vector<VertexElement<2,2>*> vertex_elements;
vertex_elements.push_back(new VertexElement<2,2>(0, nodes_elem_1));
MutableVertexMesh<2,2> vertex_mesh(nodes, vertex_elements);
std::vector<CellPtr> cells;
CellsGenerator<FixedG1GenerationalCellCycleModel, 1> cells_generator;
cells_generator.GenerateBasic(cells, vertex_mesh.GetNumElements());
VertexBasedCellPopulation<2> cell_population(vertex_mesh, cells);
CellPtr p_cell0 = cell_population.GetCellUsingLocationIndex(0);
// Set the division rule for our population to be the random direction division rule
boost::shared_ptr<AbstractVertexBasedDivisionRule<2> > p_division_rule_to_set(new CryptVertexBasedDivisionRule<2>());
cell_population.SetVertexBasedDivisionRule(p_division_rule_to_set);
// Get the division rule back from the population
boost::shared_ptr<AbstractVertexBasedDivisionRule<2> > p_division_rule = cell_population.GetVertexBasedDivisionRule();
c_vector<double, 2> division_axis = p_division_rule->CalculateCellDivisionVector(p_cell0, cell_population);
TS_ASSERT_DELTA(division_axis[0], 1.0, 1e-4);
TS_ASSERT_DELTA(division_axis[1], 0.0, 1e-4);
}
void TestAddCellWithCryptShovingBasedDivisionRule()
{
/**
* In this test we create a new CryptShovingCaBasedDivisionRule, divide a cell with it
* and check that the new cells are in the correct locations. First, we test where
* there is space around the cells. This is the default setup.
*/
// Create a simple Potts mesh
PottsMeshGenerator<2> generator(3, 0, 0, 4, 0, 0,1,0,0,false, true); // Periodic in x
PottsMesh<2>* p_mesh = generator.GetMesh();
// Create 6 cells in the bottom 2 rows
std::vector<unsigned> location_indices;
for (unsigned index=0; index<6; index++)
{
location_indices.push_back(index);
}
std::vector<CellPtr> cells;
CellsGenerator<FixedG1GenerationalCellCycleModel, 1> cells_generator;
cells_generator.GenerateBasic(cells, location_indices.size()); // Note all cells are stem cells by default.
// Create cell population
CaBasedCellPopulation<2> cell_population(*p_mesh, cells, location_indices);
// Check the cell locations
unsigned cell_locations[6] = {0,1,2,3,4,5};
unsigned index = 0;
for (AbstractCellPopulation<2>::Iterator cell_iter = cell_population.Begin();
cell_iter != cell_population.End();
++cell_iter)
{
TS_ASSERT_EQUALS(cell_population.GetLocationIndexUsingCell(*cell_iter),cell_locations[index])
++index;
}
// Make a new cell to add
MAKE_PTR(WildTypeCellMutationState, p_state);
MAKE_PTR(TransitCellProliferativeType, p_transit_type);
FixedG1GenerationalCellCycleModel* p_model = new FixedG1GenerationalCellCycleModel();
CellPtr p_new_cell(new Cell(p_state, p_model));
p_new_cell->SetCellProliferativeType(p_transit_type);
p_new_cell->SetBirthTime(-1);
// Set the division rule for our population to be the cryot shoving division rule
boost::shared_ptr<AbstractCaBasedDivisionRule<2> > p_division_rule_to_set(new CryptShovingCaBasedDivisionRule());
cell_population.SetCaBasedDivisionRule(p_division_rule_to_set);
// Get the division rule back from the population and try to add new cell by dividing cell at site 0;
boost::shared_ptr<AbstractCaBasedDivisionRule<2> > p_division_rule = cell_population.GetCaBasedDivisionRule();
// Select left cell in bottom row
CellPtr p_cell_0 = cell_population.GetCellUsingLocationIndex(0);
// The CryptShovingCaBasedDivisionRule method IsRoomToDivide() always returns true
TS_ASSERT((p_division_rule->IsRoomToDivide(p_cell_0,cell_population)));
/*
* Test adding the new cell in the population; this calls CalculateDaughterNodeIndex().
* The new cell moves into node 3. This is because stem cells always divide upwards
*/
cell_population.AddCell(p_new_cell, p_cell_0);
// Now check the cells are in the correct place
TS_ASSERT_EQUALS(cell_population.GetNumRealCells(), 7u);
// Note the cell on node 3 has been shoved to node 6 and the new cell is on node 3
unsigned new_cell_locations[7] = {0,1,2,6,4,5,3};
index = 0;
for (AbstractCellPopulation<2>::Iterator cell_iter = cell_population.Begin();
cell_iter != cell_population.End();
++cell_iter)
{
TS_ASSERT_EQUALS(cell_population.GetLocationIndexUsingCell(*cell_iter),new_cell_locations[index])
++index;
}
//Now divide a non stem cell
// Select transit cell we just added
CellPtr p_cell_3 = cell_population.GetCellUsingLocationIndex(3);
FixedG1GenerationalCellCycleModel* p_model_2 = new FixedG1GenerationalCellCycleModel();
CellPtr p_new_cell_2(new Cell(p_state, p_model_2));
p_new_cell_2->SetCellProliferativeType(p_transit_type);
p_new_cell_2->SetBirthTime(-1);
/*
* Test adding the new cell in the population; this calls CalculateDaughterNodeIndex().
* The new cell moves into node 7.
*/
cell_population.AddCell(p_new_cell_2, p_cell_3);
// Now check the cells are in the correct place
TS_ASSERT_EQUALS(cell_population.GetNumRealCells(), 8u);
// Note the cell on node 4 has been shoved to node 7 and the new cell is on node 4
unsigned new_cell_locations_2[8] = {0,1,2,6,7,5,3,4};
index = 0;
for (AbstractCellPopulation<2>::Iterator cell_iter = cell_population.Begin();
cell_iter != cell_population.End();
++cell_iter)
{
TS_ASSERT_EQUALS(cell_population.GetLocationIndexUsingCell(*cell_iter),new_cell_locations_2[index])
++index;
}
}
void TestAddCellWithCryptShovingBasedDivisionRuleAndShovingRequired()
{
/**
* In this test of CryptShovingCaBasedDivisionRule we check the case where there is
* no room to divide without the cells being shoved to the edge of the mesh.
*/
// Create a simple Potts mesh
PottsMeshGenerator<2> generator(3, 0, 0, 3, 0, 0, 1, 0, 0, false, true); // x periodic
PottsMesh<2>* p_mesh = generator.GetMesh();
// Create 9 cells, one for each node
std::vector<unsigned> location_indices;
for (unsigned index=0; index<9; index++)
{
location_indices.push_back(index);
}
std::vector<CellPtr> cells;
CellsGenerator<FixedG1GenerationalCellCycleModel, 1> cells_generator;
cells_generator.GenerateBasic(cells, location_indices.size());
// Create cell population
CaBasedCellPopulation<2> cell_population(*p_mesh, cells, location_indices);
// Make a new cell to add
MAKE_PTR(WildTypeCellMutationState, p_state);
MAKE_PTR(StemCellProliferativeType, p_stem_type);
FixedG1GenerationalCellCycleModel* p_model = new FixedG1GenerationalCellCycleModel();
CellPtr p_new_cell(new Cell(p_state, p_model));
p_new_cell->SetCellProliferativeType(p_stem_type);
p_new_cell->SetBirthTime(-1);
// Set the division rule for our population to be the crypt shoving division rule
boost::shared_ptr<AbstractCaBasedDivisionRule<2> > p_division_rule_to_set(new CryptShovingCaBasedDivisionRule());
cell_population.SetCaBasedDivisionRule(p_division_rule_to_set);
// Get the division rule back from the population and try to add new cell by dividing cell at site 0
boost::shared_ptr<AbstractCaBasedDivisionRule<2> > p_division_rule = cell_population.GetCaBasedDivisionRule();
// Select bottom left cell
CellPtr p_cell_0 = cell_population.GetCellUsingLocationIndex(0);
// Can't divide without shoving into top
TS_ASSERT_THROWS_THIS(p_division_rule->CalculateDaughterNodeIndex(p_new_cell, p_cell_0, cell_population),
"Cells reaching the top of the crypt need to increase length to at least double the sloughing height.");
}
void TestArchiveCryptCentreBasedDivisionRule()
{
FileFinder archive_dir("archive", RelativeTo::ChasteTestOutput);
std::string archive_file = "CryptCentreBasedDivisionRule.arch";
{
boost::shared_ptr<AbstractCentreBasedDivisionRule<2,2> > p_division_rule(new CryptCentreBasedDivisionRule<2,2>());
ArchiveOpener<boost::archive::text_oarchive, std::ofstream> arch_opener(archive_dir, archive_file);
boost::archive::text_oarchive* p_arch = arch_opener.GetCommonArchive();
(*p_arch) << p_division_rule;
}
{
boost::shared_ptr<AbstractCentreBasedDivisionRule<2,2> > p_division_rule;
ArchiveOpener<boost::archive::text_iarchive, std::ifstream> arch_opener(archive_dir, archive_file);
boost::archive::text_iarchive* p_arch = arch_opener.GetCommonArchive();
(*p_arch) >> p_division_rule;
typedef CryptCentreBasedDivisionRule<2,2> CryptRule;
TS_ASSERT(dynamic_cast<CryptRule*>(p_division_rule.get()));
}
}
void TestArchiveCryptVertexBasedDivisionRule()
{
FileFinder archive_dir("archive", RelativeTo::ChasteTestOutput);
std::string archive_file = "CryptVertexBasedDivisionRule.arch";
{
boost::shared_ptr<AbstractVertexBasedDivisionRule<2> > p_division_rule(new CryptVertexBasedDivisionRule<2>());
ArchiveOpener<boost::archive::text_oarchive, std::ofstream> arch_opener(archive_dir, archive_file);
boost::archive::text_oarchive* p_arch = arch_opener.GetCommonArchive();
(*p_arch) << p_division_rule;
}
{
boost::shared_ptr<AbstractVertexBasedDivisionRule<2> > p_division_rule;
ArchiveOpener<boost::archive::text_iarchive, std::ifstream> arch_opener(archive_dir, archive_file);
boost::archive::text_iarchive* p_arch = arch_opener.GetCommonArchive();
(*p_arch) >> p_division_rule;
typedef CryptVertexBasedDivisionRule<2> CryptRule;
TS_ASSERT(dynamic_cast<CryptRule*>(p_division_rule.get()));
}
}
void TestArchivingCryptShovingCaBasedDivisionRule()
{
EXIT_IF_PARALLEL; // Beware of processes overwriting the identical archives of other processes
OutputFileHandler handler("archive", false);
std::string archive_filename = handler.GetOutputDirectoryFullPath() + "CryptShovingCaBasedDivisionRule.arch";
{
CryptShovingCaBasedDivisionRule division_rule;
std::ofstream ofs(archive_filename.c_str());
boost::archive::text_oarchive output_arch(ofs);
// Serialize via pointer to most abstract class possible
AbstractCaBasedDivisionRule<2>* const p_division_rule = &division_rule;
output_arch << p_division_rule;
}
{
AbstractCaBasedDivisionRule<2>* p_division_rule;
// Create an input archive
std::ifstream ifs(archive_filename.c_str(), std::ios::binary);
boost::archive::text_iarchive input_arch(ifs);
// Restore from the archive
input_arch >> p_division_rule;
TS_ASSERT(p_division_rule != NULL);
// Tidy up
delete p_division_rule;
}
}
};
#endif /*TESTCRYPTDIVISIONRULES_HPP_*/
|
#include "LCD.hpp"
#include "Nunchuck.hpp"
#include <Arduino.h>
#define __AVR_ATmega328P__
void print_data_text(Nunchuck::Data data)
{
Serial.print("Z=");
Serial.print(data.zbut);
Serial.print("\tC=");
Serial.print(data.cbut);
Serial.print("\tJoyX=");
Serial.print(data.joyx);
Serial.print("\tJoyY=");
Serial.print(data.joyy);
Serial.print("\tAccelX=");
Serial.print(data.accx);
Serial.print("\tAccelY=");
Serial.print(data.accy);
Serial.print("\tAccelZ=");
Serial.println(data.accz);
}
void setup()
{
// init serial
Serial.begin(115200);
while (!Serial); // wait for serial port to connect
Serial.println("Serial connection ready");
// init nunchuck
Nunchuck::handshake();
Serial.println("Wii Nunchuck ready");
// init LCD
LCD::init();
Serial.println("LCD ready");
}
int loop_cnt = 0;
void loop()
{
/*
* We want to get new data and display it every 100ms.
* Originally we had a delay(100), but somehow broke it.
* This way works.
*/
if (loop_cnt % 10 == 0) { // 10*10 ms => every 100ms
// get data from nunchuck
Nunchuck::Data newData = Nunchuck::getNewData();
// pass that data to the lcd
LCD::setData(newData);
// actually refresh the screen
LCD::refresh();
// slow debug output to serial (100*10 ms => every second)
if (loop_cnt % 100 == 0) {
print_data_text(newData);
}
}
loop_cnt++;
delay(10);
}
|
#include "GunnerDie.h"
#include "../../../../../GameDefines/GameDefine.h"
GunnerDie::GunnerDie(Gunner* headGunner) :GunnerState(headGunner)
{
pGunner->setVy(Define::ENEMY_MIN_JUMP_VELOCITY);
timeDie = 0;
translateY = 25.0f;
}
::StateGunner GunnerDie::getState()
{
return StateGunner::Die;
}
void GunnerDie::update(float dt)
{
pGunner->addVy(translateY);
timeDie += dt;
if (timeDie >= 0.45f)
{
pGunner->setDraw(false);
return;
}
}
|
#ifndef _ROS_body_tracker_msgs_BodyTracker_h
#define _ROS_body_tracker_msgs_BodyTracker_h
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "ros/msg.h"
#include "geometry_msgs/Point32.h"
namespace body_tracker_msgs
{
class BodyTracker : public ros::Msg
{
public:
typedef int32_t _body_id_type;
_body_id_type body_id;
typedef int32_t _tracking_status_type;
_tracking_status_type tracking_status;
typedef int32_t _gesture_type;
_gesture_type gesture;
typedef bool _face_found_type;
_face_found_type face_found;
typedef int32_t _face_left_type;
_face_left_type face_left;
typedef int32_t _face_top_type;
_face_top_type face_top;
typedef int32_t _face_width_type;
_face_width_type face_width;
typedef int32_t _face_height_type;
_face_height_type face_height;
typedef int32_t _age_type;
_age_type age;
typedef int32_t _gender_type;
_gender_type gender;
typedef const char* _name_type;
_name_type name;
typedef geometry_msgs::Point32 _position2d_type;
_position2d_type position2d;
typedef geometry_msgs::Point32 _position3d_type;
_position3d_type position3d;
typedef geometry_msgs::Point32 _face_center_type;
_face_center_type face_center;
BodyTracker():
body_id(0),
tracking_status(0),
gesture(0),
face_found(0),
face_left(0),
face_top(0),
face_width(0),
face_height(0),
age(0),
gender(0),
name(""),
position2d(),
position3d(),
face_center()
{
}
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
union {
int32_t real;
uint32_t base;
} u_body_id;
u_body_id.real = this->body_id;
*(outbuffer + offset + 0) = (u_body_id.base >> (8 * 0)) & 0xFF;
*(outbuffer + offset + 1) = (u_body_id.base >> (8 * 1)) & 0xFF;
*(outbuffer + offset + 2) = (u_body_id.base >> (8 * 2)) & 0xFF;
*(outbuffer + offset + 3) = (u_body_id.base >> (8 * 3)) & 0xFF;
offset += sizeof(this->body_id);
union {
int32_t real;
uint32_t base;
} u_tracking_status;
u_tracking_status.real = this->tracking_status;
*(outbuffer + offset + 0) = (u_tracking_status.base >> (8 * 0)) & 0xFF;
*(outbuffer + offset + 1) = (u_tracking_status.base >> (8 * 1)) & 0xFF;
*(outbuffer + offset + 2) = (u_tracking_status.base >> (8 * 2)) & 0xFF;
*(outbuffer + offset + 3) = (u_tracking_status.base >> (8 * 3)) & 0xFF;
offset += sizeof(this->tracking_status);
union {
int32_t real;
uint32_t base;
} u_gesture;
u_gesture.real = this->gesture;
*(outbuffer + offset + 0) = (u_gesture.base >> (8 * 0)) & 0xFF;
*(outbuffer + offset + 1) = (u_gesture.base >> (8 * 1)) & 0xFF;
*(outbuffer + offset + 2) = (u_gesture.base >> (8 * 2)) & 0xFF;
*(outbuffer + offset + 3) = (u_gesture.base >> (8 * 3)) & 0xFF;
offset += sizeof(this->gesture);
union {
bool real;
uint8_t base;
} u_face_found;
u_face_found.real = this->face_found;
*(outbuffer + offset + 0) = (u_face_found.base >> (8 * 0)) & 0xFF;
offset += sizeof(this->face_found);
union {
int32_t real;
uint32_t base;
} u_face_left;
u_face_left.real = this->face_left;
*(outbuffer + offset + 0) = (u_face_left.base >> (8 * 0)) & 0xFF;
*(outbuffer + offset + 1) = (u_face_left.base >> (8 * 1)) & 0xFF;
*(outbuffer + offset + 2) = (u_face_left.base >> (8 * 2)) & 0xFF;
*(outbuffer + offset + 3) = (u_face_left.base >> (8 * 3)) & 0xFF;
offset += sizeof(this->face_left);
union {
int32_t real;
uint32_t base;
} u_face_top;
u_face_top.real = this->face_top;
*(outbuffer + offset + 0) = (u_face_top.base >> (8 * 0)) & 0xFF;
*(outbuffer + offset + 1) = (u_face_top.base >> (8 * 1)) & 0xFF;
*(outbuffer + offset + 2) = (u_face_top.base >> (8 * 2)) & 0xFF;
*(outbuffer + offset + 3) = (u_face_top.base >> (8 * 3)) & 0xFF;
offset += sizeof(this->face_top);
union {
int32_t real;
uint32_t base;
} u_face_width;
u_face_width.real = this->face_width;
*(outbuffer + offset + 0) = (u_face_width.base >> (8 * 0)) & 0xFF;
*(outbuffer + offset + 1) = (u_face_width.base >> (8 * 1)) & 0xFF;
*(outbuffer + offset + 2) = (u_face_width.base >> (8 * 2)) & 0xFF;
*(outbuffer + offset + 3) = (u_face_width.base >> (8 * 3)) & 0xFF;
offset += sizeof(this->face_width);
union {
int32_t real;
uint32_t base;
} u_face_height;
u_face_height.real = this->face_height;
*(outbuffer + offset + 0) = (u_face_height.base >> (8 * 0)) & 0xFF;
*(outbuffer + offset + 1) = (u_face_height.base >> (8 * 1)) & 0xFF;
*(outbuffer + offset + 2) = (u_face_height.base >> (8 * 2)) & 0xFF;
*(outbuffer + offset + 3) = (u_face_height.base >> (8 * 3)) & 0xFF;
offset += sizeof(this->face_height);
union {
int32_t real;
uint32_t base;
} u_age;
u_age.real = this->age;
*(outbuffer + offset + 0) = (u_age.base >> (8 * 0)) & 0xFF;
*(outbuffer + offset + 1) = (u_age.base >> (8 * 1)) & 0xFF;
*(outbuffer + offset + 2) = (u_age.base >> (8 * 2)) & 0xFF;
*(outbuffer + offset + 3) = (u_age.base >> (8 * 3)) & 0xFF;
offset += sizeof(this->age);
union {
int32_t real;
uint32_t base;
} u_gender;
u_gender.real = this->gender;
*(outbuffer + offset + 0) = (u_gender.base >> (8 * 0)) & 0xFF;
*(outbuffer + offset + 1) = (u_gender.base >> (8 * 1)) & 0xFF;
*(outbuffer + offset + 2) = (u_gender.base >> (8 * 2)) & 0xFF;
*(outbuffer + offset + 3) = (u_gender.base >> (8 * 3)) & 0xFF;
offset += sizeof(this->gender);
uint32_t length_name = strlen(this->name);
varToArr(outbuffer + offset, length_name);
offset += 4;
memcpy(outbuffer + offset, this->name, length_name);
offset += length_name;
offset += this->position2d.serialize(outbuffer + offset);
offset += this->position3d.serialize(outbuffer + offset);
offset += this->face_center.serialize(outbuffer + offset);
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
union {
int32_t real;
uint32_t base;
} u_body_id;
u_body_id.base = 0;
u_body_id.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0);
u_body_id.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1);
u_body_id.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2);
u_body_id.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3);
this->body_id = u_body_id.real;
offset += sizeof(this->body_id);
union {
int32_t real;
uint32_t base;
} u_tracking_status;
u_tracking_status.base = 0;
u_tracking_status.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0);
u_tracking_status.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1);
u_tracking_status.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2);
u_tracking_status.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3);
this->tracking_status = u_tracking_status.real;
offset += sizeof(this->tracking_status);
union {
int32_t real;
uint32_t base;
} u_gesture;
u_gesture.base = 0;
u_gesture.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0);
u_gesture.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1);
u_gesture.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2);
u_gesture.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3);
this->gesture = u_gesture.real;
offset += sizeof(this->gesture);
union {
bool real;
uint8_t base;
} u_face_found;
u_face_found.base = 0;
u_face_found.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0);
this->face_found = u_face_found.real;
offset += sizeof(this->face_found);
union {
int32_t real;
uint32_t base;
} u_face_left;
u_face_left.base = 0;
u_face_left.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0);
u_face_left.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1);
u_face_left.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2);
u_face_left.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3);
this->face_left = u_face_left.real;
offset += sizeof(this->face_left);
union {
int32_t real;
uint32_t base;
} u_face_top;
u_face_top.base = 0;
u_face_top.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0);
u_face_top.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1);
u_face_top.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2);
u_face_top.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3);
this->face_top = u_face_top.real;
offset += sizeof(this->face_top);
union {
int32_t real;
uint32_t base;
} u_face_width;
u_face_width.base = 0;
u_face_width.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0);
u_face_width.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1);
u_face_width.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2);
u_face_width.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3);
this->face_width = u_face_width.real;
offset += sizeof(this->face_width);
union {
int32_t real;
uint32_t base;
} u_face_height;
u_face_height.base = 0;
u_face_height.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0);
u_face_height.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1);
u_face_height.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2);
u_face_height.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3);
this->face_height = u_face_height.real;
offset += sizeof(this->face_height);
union {
int32_t real;
uint32_t base;
} u_age;
u_age.base = 0;
u_age.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0);
u_age.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1);
u_age.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2);
u_age.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3);
this->age = u_age.real;
offset += sizeof(this->age);
union {
int32_t real;
uint32_t base;
} u_gender;
u_gender.base = 0;
u_gender.base |= ((uint32_t) (*(inbuffer + offset + 0))) << (8 * 0);
u_gender.base |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1);
u_gender.base |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2);
u_gender.base |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3);
this->gender = u_gender.real;
offset += sizeof(this->gender);
uint32_t length_name;
arrToVar(length_name, (inbuffer + offset));
offset += 4;
for(unsigned int k= offset; k< offset+length_name; ++k){
inbuffer[k-1]=inbuffer[k];
}
inbuffer[offset+length_name-1]=0;
this->name = (char *)(inbuffer + offset-1);
offset += length_name;
offset += this->position2d.deserialize(inbuffer + offset);
offset += this->position3d.deserialize(inbuffer + offset);
offset += this->face_center.deserialize(inbuffer + offset);
return offset;
}
const char * getType(){ return "body_tracker_msgs/BodyTracker"; };
const char * getMD5(){ return "5fee6a28da28b41e53df055348e02173"; };
};
}
#endif
|
#include <bits/stdc++.h>
#define MAX 1000001
#define M 100000000
#define ll long long
#define ld long double
#define ESP 0.0001
using namespace std;
struct node {
struct node* child[26];
int val;
};
node *root;
int addString(string s) {
int l = s.length();
node *temp = root;
for (int i=0;i<l;i++) {
if (temp->child[s[i]-'a']==NULL) temp->child[s[i]-'a'] = new node();
temp = temp->child[s[i]-'a'];
(temp->val)++;
}
return 0;
}
int query(string s) {
int l = s.length();
node *temp = root;
int res;
for (int i=0;i<l;i++) {
temp = temp->child[s[i]-'a'];
if (temp==NULL) return 0;
res = (temp->val);
}
return res;
}
int n, q;
int main() {
root = new node();
cin >> n >> q;
for (int i=0;i<n;i++) {
string x;
cin >> x;
addString(x);
}
for (int i=0;i<q;i++) {
string x;
cin >> x;
cout << query(x) << endl;
}
return 0;
}
|
#include "Map.h"
Map::Map(sf::RenderWindow * window, std::string path)
{
this->window = window;
std::fstream f;
f.open(path);
std::string a;
while (!f.eof())
{
getline(f, a);
map.push_back(a);
}
f.close();
tex1.loadFromFile("Image\\Wall.png");
tex2.loadFromFile("Image\\Road.png");
tex3.loadFromFile("Image\\Road.png");
wall.setTexture(tex1);
road.setTexture(tex2);
safezone.setTexture(tex3);
}
Map::~Map()
{
}
void Map::Draw(sf::Vector2f pos_)
{
int x1 = (pos_.x - 500) / 70;
int x2 = x1 + 14;
int y1 = (pos_.y - 400) / 70;
int y2 = y1 + 11;
for (int i = y1; i < y2; i++) {
for (int j = x1; j < x2; j++) {
if ((i >= 0 && i < map.size() && j >= 0 && j < map[i].size()) && map[i][j] == '1') {
road.setPosition(j * 70, i * 70);
window->draw(road);
}
if ((i >= 0 && i < map.size() && j >= 0 && j < map[i].size()) && map[i][j] == '3') {
safezone.setPosition(j * 70, i * 70);
window->draw(safezone);
}
}
}
}
void Map::Draw_road(sf::Vector2f pos_)
{
int x1 = (pos_.x - 500) / 70;
int x2 = x1 + 14;
int y1 = (pos_.y - 400) / 70;
int y2 = y1 + 11;
for (int i = y1; i < y2; i++) {
for (int j = x1; j < x2; j++) {
if ((i >= 0 && i < map.size() && j >= 0 && j < map[i].size()) && map[i][j] == '2') {
wall.setPosition(j * 70, i * 70 - 20);
window->draw(wall);
}
}
}
}
|
#include "image_viewer.hpp"
#include <string>
#include <iostream>
#include <exception>
int main(int argc, char* argv[]){
ImageViewer iv(argv[1]);
iv.enterMainLoop();
return 0;
}
|
#ifndef EasyTcpServer_hpp_
#define EasyTcpServer_hpp_
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include<Windows.h>
#include<WinSock2.h>
//链接windows 动态库
#pragma comment(lib,"ws2_32.lib")
#else
#include<unistd.h>
#include<arpa/inet.h>
#include<string.h>
#define SOCKET int
#define INVALID_SOCKET (SOCKET)(~0)
#define SOCKET_ERROR (-1)
#endif // _WIN32
#include<vector>
#include<iostream>
#include "MessageHeader.hpp"
class EasyTcpServer {
private:
SOCKET _socket;
std::vector<SOCKET> g_client;
public:
EasyTcpServer()
{
_socket = INVALID_SOCKET;
}
virtual ~EasyTcpServer()
{
CloseService();
}
//初始化socket
SOCKET InitSocket()
{
#ifdef _WIN32
//启动windows socket
WORD word = MAKEWORD(2, 2);
WSADATA data;
WSAStartup(word, &data);
#endif
if (INVALID_SOCKET != _socket) {
printf("socket关闭连接。 \n");
CloseService();
}
_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (INVALID_SOCKET == _socket)
{
printf("建立socket错误。 \n");
}
else {
printf("建立socket成功。 \n");
}
return _socket;
}
//绑定端口
void BindPort(const char * ip,unsigned short port)
{
// 调用绑定端口时 判断是否初始化
if (INVALID_SOCKET == _socket) {
printf("socket初始化。 \n");
InitSocket();
}
sockaddr_in _sin = {};
_sin.sin_family = AF_INET;
_sin.sin_port = htons(port);
#ifdef _WIN32
//对ip地址判断是否为空
if (ip) {
_sin.sin_addr.S_un.S_addr = inet_addr(ip);
}
else {
_sin.sin_addr.S_un.S_addr = INADDR_ANY;
}
#else
if (ip) {
_sin.sin_addr.s_addr = inet_addr(ip);
}
else {
_sin.sin_addr.s_addr = INADDR_ANY;
}
#endif // _WIN32
int ret = bind(_socket, (sockaddr*)&_sin, sizeof(_sin));
if (SOCKET_ERROR== ret)
{
printf("错误,绑定网络端口失败.....\n");
}
else {
printf("绑定网络端口成功.....\n");
}
}
//监听端口
int Linsten_s(int n) {
int ret = listen(_socket, n);
if (SOCKET_ERROR== ret) {
printf("错误,监听网络端口失败......\n");
}
else {
printf("监听网络端口成功......\n");
}
return ret;
}
//接收客户端连接
SOCKET receive_s() {
sockaddr_in clientAddr = {};
int nAddrLen = sizeof(sockaddr_in);
SOCKET _clientSock = INVALID_SOCKET;
#ifdef WIN32
_clientSock = accept(_socket, (sockaddr*)&clientAddr, &nAddrLen);
#else
_clientSock = accept(_socket, (sockaddr*)&clientAddr,(socklen_t*)&nAddrLen);
#endif // WIN32
if (INVALID_SOCKET == _clientSock)
{
printf("接收到无效的客户端 socket.....\n");
}
else {
NEWUserLogin userLogin;
//发给新连接客户端信息
send(_clientSock, (char*)&userLogin, userLogin.dataLength, 0);
//通知其他客户端有新成员加入
SendDataAll(&userLogin);
g_client.push_back(_clientSock);
printf("新客户端加入。socket = %d,ip地址:=%s \n", (int)_clientSock, inet_ntoa(clientAddr.sin_addr));
}
return _clientSock;
}
//关闭socket
void CloseService() {
if (_socket!=INVALID_SOCKET) {
#ifdef _WIN32
for (int n =(int) g_client.size() - 1; n >= 0;n--) {
closesocket(g_client[n]);
}
closesocket(_socket);
WSACleanup();
#else
for (int n = (int)g_client.size() - 1; n >= 0; n--) {
close(g_client[n]);
}
close(_socket);
#endif //
}
}
//处理网络消息
bool OnRun() {
if (isRun()) {
fd_set fd_read;
fd_set fd_write;
fd_set fd_exp;
// 清空 fd 集合 宏
FD_ZERO(&fd_read);
FD_ZERO(&fd_write);
FD_ZERO(&fd_exp);
//宏 set套接字
FD_SET(_socket, &fd_read);
FD_SET(_socket, &fd_write);
FD_SET(_socket, &fd_exp);
SOCKET max_sock = _socket;
for (size_t n = 0; n < g_client.size(); n++) {
FD_SET(g_client[n], &fd_read);
if (max_sock < g_client[n]) {
max_sock =g_client[n];
}
}
timeval t_s = {1,0};
int ret = select(max_sock + 1, &fd_read, &fd_write, &fd_exp, &t_s);
if (ret < 0) {
printf("select 任务结束。\n");
CloseService();
return false;
}
if (FD_ISSET(_socket, &fd_read)) {
FD_CLR(_socket, &fd_read);
receive_s();
}
for (int n = (int)g_client.size() - 1; n >= 0; n--) {
if (FD_ISSET(g_client[n],&fd_read)) {
if (-1== processs(g_client[n])) {
auto iter = g_client.begin() + n;
if (iter!= g_client.end())
{
g_client.erase(iter);
}
}
}
}
return true;
}
return false;
}
//是否工作中
bool isRun() {
return _socket != INVALID_SOCKET;
}
//接收数据 处理粘包 拆分包
int processs(SOCKET _clientSock) {
// 5 接收客户端数据请求
//字节缓冲区
char szRecv[4096] = {};
int _cLen = recv(_clientSock, szRecv, sizeof(dataHead), 0);
dataHead* header = (dataHead*)szRecv;
if (_cLen <= 0)
{
printf("客户端已退出,连接接收。\n");
return -1;
}
recv(_clientSock, szRecv + sizeof(dataHead), header->dataLength - sizeof(dataHead), 0);
OnNetMsg(_clientSock, header);
return 0;
}
//发送数据
int SendData(SOCKET _sock,dataHead* header) {
if (isRun() && header) {
send(_sock, (char*)header, header->dataLength, 0);
}
return SOCKET_ERROR;
}
void SendDataAll( dataHead* header) {
if (isRun() && header) {
for (int n = 0; n < g_client.size(); n++) {
SendData(g_client[n], header);
}
}
}
//响应网络消息
void OnNetMsg(SOCKET _sock,dataHead* header) {
switch (header->cmd)
{
case CMD_LOGIN:
{
Login* login = (Login*)header;
printf("收到命令 数据长度 :%d ,userName=%s\n", login->dataLength, login->userName);
//账号密码验证
LoginResult ret;
send(_sock, (char*)&ret, sizeof(ret), 0);
}
break;
case CMD_LOGINOUT: {
Loginout* lout = (Loginout*)header;
printf("收到命令 数据长度 :%d ,userName=%s\n", lout->dataLength, lout->userName);
//账号密码验证
LoginResult ret;
send(_sock, (char*)&ret, sizeof(ret), 0);
}
break;
default: {
dataHead hd_Len = { 0,CMD_ERROR };
send(_sock, (char*)&hd_Len, sizeof(dataHead), 0);
}
break;
}
}
};
#endif // !EasyTcpServer_hpp_
|
//
// server.cc
// ~~~~~~~~~
//
#include <boost/bind.hpp>
#include <boost/thread/thread.hpp>
#include <string>
#include <iostream>
#include <thread>
#include "logger.h"
#include "server_information.h"
#include "leaderboard.h"
#include "server.h"
#include "static_request_handler.h"
#include "common_request_handler.h"
#include "not_found_request_handler.h"
#include "status_request_handler.h"
#include "proxy_request_handler.h"
#include "health_request_handler.h"
#include "leaderboard_request_handler.h"
#include "snake_request_handler.h"
using boost::asio::ip::tcp;
server::server(boost::asio::io_service& io_service, unsigned short port,
std::vector<std::shared_ptr<NginxConfig>> config_blocks)
: io_service_(io_service),
acceptor_(io_service, tcp::endpoint(tcp::v4(), port)),
accept_status_response_(accept_status::READY)
{
create_all_handlers(config_blocks);
start_accept();
}
void server::create_all_handlers(std::vector<std::shared_ptr<NginxConfig>> config_blocks)
{
for (int i = 0; i < config_blocks.size(); i++)
{
if (config_blocks[i]->getStatementType())
{
request_handler* handler = CreateHandlerByHandlerType(*config_blocks[i]);
if (handler != nullptr) {
path_map_[config_blocks[i]->getUrl()] = handler;
}
}
}
// Create 404 handler
NginxConfigStatement s;
s.setStatementType(NginxConfigStatement::NOT_FOUND_HANDLER);
NginxConfig config(s);
request_handler* handler = CreateHandlerByHandlerType(config);
path_map_["/"] = handler;
ServerInformation *info = ServerInformation::setInstance(path_map_);
Leaderboard* lb = Leaderboard::setleaderDB();
}
request_handler* server::CreateHandlerByHandlerType(NginxConfig config)
{
if (config.getStatementType() == NginxConfigStatement::STATIC_HANDLER)
{
static_request_handler* srh = new static_request_handler;
return (srh->Init(config.getUrl(), config));
}
if (config.getStatementType() == NginxConfigStatement::ECHO_HANDLER)
{
common_request_handler* crh = new common_request_handler;
return (crh->Init(config.getUrl(), config));
}
if (config.getStatementType() == NginxConfigStatement::NOT_FOUND_HANDLER)
{
NotFoundRequestHandler* nfrh = new NotFoundRequestHandler;
return (nfrh->Init(config.getUrl(), config));
}
if (config.getStatementType() == NginxConfigStatement::STATUS_HANDLER)
{
StatusRequestHandler* srh = new StatusRequestHandler;
return (srh->Init(config.getUrl(), config));
}
if (config.getStatementType() == NginxConfigStatement::PROXY_HANDLER)
{
ProxyRequestHandler* prh = new ProxyRequestHandler;
return (prh->Init(config.getUrl(), config));
}
if (config.getStatementType() == NginxConfigStatement::HEALTH_HANDLER)
{
HealthRequestHandler* hrh = new HealthRequestHandler;
return (hrh->Init(config.getUrl(), config));
}
if (config.getStatementType() == NginxConfigStatement::LEADERBOARD_HANDLER)
{
LeaderboardRequestHandler* lrh = new LeaderboardRequestHandler;
return (lrh->Init(config.getUrl(), config));
}
if (config.getStatementType() == NginxConfigStatement::SNAKE_HANDLER)
{
SnakeRequestHandler* srh = new SnakeRequestHandler;
return (srh->Init(config.getUrl(), config));
}
return nullptr;
}
server::~server()
{
for (std::pair<std::string, request_handler*> e : path_map_)
{
delete e.second;
}
}
boost::asio::io_service& server::get_io_service() const
{
return io_service_;
}
server::accept_status server::get_accept_status_response() const
{
return accept_status_response_;
}
void server::start_accept()
{
session* new_session = new session(io_service_, path_map_);
acceptor_.async_accept(new_session->socket(),
boost::bind(&server::handle_accept, this, new_session,
boost::asio::placeholders::error));
}
void server::handle_accept(session* new_session,
const boost::system::error_code& error)
{
Logger * logger = Logger::getLogger();
if (!error)
{
logger->logDebug("handle_accept in Server", "Incoming request from IP: " + new_session->socket().remote_endpoint().address().to_string());
boost::thread t(boost::bind(&session::start, new_session));
accept_status_response_ = accept_status::ACCEPT_SUCCESS;
}
else
{
logger->logError("handle_accept in Server", "Unable to make a connection.");
delete new_session;
accept_status_response_ = accept_status::ACCEPT_ERROR_ENCOUNTERED;
}
start_accept();
}
|
#include "utils.h"
unsigned long get_current_time(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (tv.tv_sec*1000000 + tv.tv_usec);
}
void swapPointerUsePointer(int8_t **p, int8_t **q)
{
int8_t *t = *p;
*p = *q;
*q = t;
}
void swapPointerUseReference(int8_t *&p, int8_t *&q)
{
int8_t *t = p;
p = q;
q = t;
}
void ListPath(string const &path, vector<string> &paths) {
paths.clear();
struct dirent *entry;
/*Check if path is a valid directory path. */
struct stat s;
lstat(path.c_str(), &s);
if (!S_ISDIR(s.st_mode)) {
fprintf(stderr, "Error: %s is not a valid directory!\n", path.c_str());
exit(1);
}
DIR *dir = opendir(path.c_str());
if (dir == nullptr) {
fprintf(stderr, "Error: Open %s path failed.\n", path.c_str());
exit(1);
}
while ((entry = readdir(dir)) != nullptr) {
/*
if (entry->d_type == DT_REG || entry->d_type == DT_UNKNOWN) {
string name = entry->d_name;
cout << "name: "<<name<<endl;
paths.push_back(name);
}*/
string name = entry->d_name;
int type = (int)(entry->d_type);
if(type != 8)
{
if((strcmp(name.c_str(), ".")!=0) && (strcmp(name.c_str(), "..")!=0) && (strcmp(name.c_str(), "results")!=0))
{
#if(YUV420OPEN)
if((strcmp(name.c_str(), "yuv")==0))
{
cout << "Dir name: "<<name<<endl;
paths.push_back(name);
}
#else
if(strcmp(name.c_str(), "yuv")!=0)
{
cout << "Dir name: "<<name<<endl;
paths.push_back(name);
}
#endif
}
}
}
closedir(dir);
}
void ListImages(string const &path, vector<string> &images) {
images.clear();
struct dirent *entry;
/*Check if path is a valid directory path. */
struct stat s;
lstat(path.c_str(), &s);
if (!S_ISDIR(s.st_mode)) {
fprintf(stderr, "Error: %s is not a valid directory!\n", path.c_str());
exit(1);
}
DIR *dir = opendir(path.c_str());
if (dir == nullptr) {
fprintf(stderr, "Error: Open %s path failed.\n", path.c_str());
exit(1);
}
while ((entry = readdir(dir)) != nullptr) {
if (entry->d_type == DT_REG || entry->d_type == DT_UNKNOWN) {
string name = entry->d_name;
string ext = name.substr(name.find_last_of(".") + 1);
if ((ext == "JPEG") || (ext == "jpeg") || (ext == "JPG") ||
(ext == "jpg") || (ext == "PNG") || (ext == "png") || (ext == "420")) {
images.push_back(name);
}
}
}
closedir(dir);
}
float overlap(float x1, float w1, float x2, float w2) {
float left = max(x1 - w1 / 2.0, x2 - w2 / 2.0);
float right = min(x1 + w1 / 2.0, x2 + w2 / 2.0);
return right - left;
}
float cal_iou(vector<float> box, vector<float>truth) {
float w = overlap(box[0], box[2], truth[0], truth[2]);
float h = overlap(box[1], box[3], truth[1], truth[3]);
if(w < 0 || h < 0) return 0;
float inter_area = w * h;
float union_area = box[2] * box[3] + truth[2] * truth[3] - inter_area;
return inter_area * 1.0 / union_area;
}
void GetSigMatrix(float *SigMatrix, float *ExpMatrix, float scale){
for(int i=-128;i<128;i++){
SigMatrix[i+128] = sigmoid(i * scale);
ExpMatrix[i+128] = exp(i * scale);
}
}
void GetSigMatrix(float *SigMatrix, float *ExpMatrix, int8_t *ImgScaleMatrix, float scale, float img_scale){
for(int i=-128;i<128;i++){
SigMatrix[i+128] = sigmoid(i * scale);
ExpMatrix[i+128] = exp(i * scale);
ImgScaleMatrix[i+128] = (i+128)*img_scale;
}
}
float sigmoid(float p) {
return 1.0 / (1. + exp(-p * 1.0));
}
void CPUCalcSoftmax(const float *data, size_t size, float *result) {
assert(data && result);
double sum = 0.0f;
for (size_t i = 0; i < size; i++) {
result[i] = exp(data[i]);
sum += result[i];
}
for (size_t i = 0; i < size; i++) {
result[i] /= sum;
}
}
Mat convertTo3Channels(const Mat& binImg)
{
Mat three_channel = Mat::zeros(binImg.rows, binImg.cols, CV_8UC3);
vector<Mat> channels;
for (int i=0;i<3;i++)
{
channels.push_back(binImg);
}
merge(channels,three_channel);
return three_channel;
}
vector<cv::Mat> splitImage(cv::Mat image, int num,int type) {
int rows = image.rows;
int cols = image.cols;
vector<cv::Mat> v;
if (type == 0) {//垂直分割
for (int i = 0; i < num; i++) {
int star = rows / num*i;
int end = rows / num*(i + 1);
if (i == num - 1) {
end = rows;
}
//cv::Mat b = image.rowRange(star, end);
v.push_back(image.rowRange(star, end));
}
}
else if (type == 1) {//水平分割
for (int i = 0; i < num; i++){
int star = cols / num*i;
int end = cols / num*(i + 1);
if (i == num - 1) {
end = cols;
}
//cv::Mat b = image.colRange(star, end);
/*解决水平分割的Bug:必须clone()*/
v.push_back(image.colRange(star, end).clone());
}
}
return v;
}
cv::Mat catImage(vector<cv::Mat> v, int type) {
cv::Mat dest= v.at(0);
for (size_t i = 1; i < v.size(); i++)
{
if (type == 0)//垂直拼接
{
cv::vconcat(dest, v.at(i), dest);
}
else if (type == 1)//水平拼接
{
cv::hconcat(dest, v.at(i), dest);
}
}
return dest;
}
void* fast_memcpy(void *dst, const void *src, size_t sz)
{
void *r = dst;
//先进行uint64_t长度的拷贝,一般而言,内存地址都是对齐的,
size_t n = sz & ~(sizeof(uint64_t) - 1);
uint64_t *src_u64 = (uint64_t *) src;
uint64_t *dst_u64 = (uint64_t *) dst;
while (n)
{// 每次循环拷贝了2次uint64_t字长的数据
*dst_u64++ = *src_u64++;
*dst_u64++ = *src_u64++;
n -= sizeof(uint64_t)*2;
}
//将没有非8字节字长取整的部分copy
n = sz & (sizeof(uint64_t) - 1);
uint8_t *src_u8 = (uint8_t *) src;
uint8_t *dst_u8 = (uint8_t *) dst;
while (n-- )
{
*dst_u8++ = *src_u8++;
}
return r;
}
void neon_memcpy(int8_t* dst, int8_t* src, int len){
int8x16_t reg;
int i;
int len2 = len % 16;
int len1 = len - len2;
// use neon
for(i = 0; i < len1; i += 16){
reg = vld1q_s8(src);
vst1q_s8(dst, reg);
src += 16;
dst += 16;
}
// duplicate the rest data
while(len2--){
*dst++ = *src++;
}
}
void neon_norm(uint8_t* src, int8_t* dst, int len, float* mean, float scale){
if(mean[0] != 0.f){
#define USE_NEON_SUB
}
if(scale != 1.0){
#define USE_NEON_MUL
}
if(mean[0] == mean[1] && mean[1] == mean[2]){
// 保持精度的浮点运算方法
float32x4_t bgr_mean = vdupq_n_f32(mean[0]);
float32x4_t snum = vdupq_n_f32(scale);
int cnt = len - (len % 8);
int i;
for(i = 0; i < cnt; i += 8){
uint8x8_t bgr_u8 = vld1_u8(src + i);
uint16x8_t bgr_u16 = vmovl_u8(bgr_u8);
uint16x4_t bgr_u16_low = vget_low_u16(bgr_u16);
uint16x4_t bgr_u16_high = vget_high_u16(bgr_u16);
uint32x4_t bgr_u32_low = vmovl_u16(bgr_u16_low);
uint32x4_t bgr_u32_high = vmovl_u16(bgr_u16_high);
float32x4_t bgr_f32_low = vcvtq_f32_u32(bgr_u32_low);
float32x4_t bgr_f32_high = vcvtq_f32_u32(bgr_u32_high);
#ifdef USE_NEON_SUB
bgr_f32_low = vsubq_f32(bgr_f32_low, bgr_mean);
bgr_f32_high = vsubq_f32(bgr_f32_high, bgr_mean);
#endif
#ifdef USE_NEON_MUL
bgr_f32_low = vmulq_f32(bgr_f32_low, snum);
#endif
int32x4_t res_s32_low = vcvtq_s32_f32(bgr_f32_low);
int32x4_t res_s32_high = vcvtq_s32_f32(bgr_f32_high);
int16x4_t res_s16_low = vqmovn_s32(res_s32_low);
int16x4_t res_s16_high = vqmovn_s32(res_s32_high);
int16x8_t res_s16 = vcombine_s16(res_s16_low, res_s16_high);
int8x8_t res = vqmovn_s16(res_s16);
vst1_s8(dst + i, res);
}
while(i < len){
#ifdef USE_NEON_SUB
dst[i] = (int8_t)((float)(src[i]) - mean[0]);
#endif
#ifdef USE_NEON_MUL
dst[i] *= scale;
#endif
i++;
}
// // 低精度无符号整型计算
// uint8x16_t bgr_mean = vdupq_n_u8((uint8_t)mean[0]);
// int cnt = len - (len % 16);
// int i;
// for(i =0; i < cnt; i += 16){
// uint8x16_t bgr = vld1q_u8(src + i);
// int8x16_t res = vreinterpretq_s8_u8(vsubq_u8(bgr, bgr_mean));
// vst1q_s8(dst + i, res);
// }
// while(i < len){
// dst[i] = (int8_t)(src[i]) - (int8_t)mean[0];
// i++;
// }
}
else{
float32x4_t b_mean = vdupq_n_f32(mean[2]);
float32x4_t g_mean = vdupq_n_f32(mean[1]);
float32x4_t r_mean = vdupq_n_f32(mean[0]);
float32x4_t snum = vdupq_n_f32(scale);
int8x8x3_t bgr_res = {vdup_n_s8(0), vdup_n_s8(0), vdup_n_s8(0)};
int cnt = len - (len % 8);
int i;
for(i = 0; i < cnt; i += 24){
uint8x8x3_t bgr = vld3_u8(src + i);
// method one
uint8x8_t b_u8 = bgr.val[0];
uint8x8_t g_u8 = bgr.val[1];
uint8x8_t r_u8 = bgr.val[2];
uint16x8_t b_u16 = vmovl_u8(b_u8);
uint16x8_t g_u16 = vmovl_u8(g_u8);
uint16x8_t r_u16 = vmovl_u8(r_u8);
// bgr low process
uint16x4_t b_u16_low = vget_low_u16(b_u16);
uint16x4_t g_u16_low = vget_low_u16(g_u16);
uint16x4_t r_u16_low = vget_low_u16(r_u16);
uint32x4_t b_u32_low = vmovl_u16(b_u16_low);
uint32x4_t g_u32_low = vmovl_u16(g_u16_low);
uint32x4_t r_u32_low = vmovl_u16(r_u16_low);
float32x4_t b_f32_low = vcvtq_f32_u32(b_u32_low);
float32x4_t g_f32_low = vcvtq_f32_u32(g_u32_low);
float32x4_t r_f32_low = vcvtq_f32_u32(r_u32_low);
#ifdef USE_NEON_SUB
b_f32_low = vsubq_f32(b_f32_low, b_mean);
g_f32_low = vsubq_f32(g_f32_low, g_mean);
r_f32_low = vsubq_f32(r_f32_low, r_mean);
#endif
#ifdef USE_NEON_MUL
b_f32_low = vmulq_f32(b_f32_low, snum);
g_f32_low = vmulq_f32(g_f32_low, snum);
r_f32_low = vmulq_f32(r_f32_low, snum);
#endif
int32x4_t bres_s32_low = vcvtq_s32_f32(b_f32_low);
int32x4_t gres_s32_low = vcvtq_s32_f32(g_f32_low);
int32x4_t rres_s32_low = vcvtq_s32_f32(r_f32_low);
int16x4_t bres_s16_low = vqmovn_s32(bres_s32_low);
int16x4_t gres_s16_low = vqmovn_s32(gres_s32_low);
int16x4_t rres_s16_low = vqmovn_s32(rres_s32_low);
// bgr high process
uint16x4_t b_u16_high = vget_high_u16(b_u16);
uint16x4_t g_u16_high = vget_high_u16(g_u16);
uint16x4_t r_u16_high = vget_high_u16(r_u16);
uint32x4_t b_u32_high = vmovl_u16(b_u16_high);
uint32x4_t g_u32_high = vmovl_u16(g_u16_high);
uint32x4_t r_u32_high = vmovl_u16(r_u16_high);
float32x4_t b_f32_high = vcvtq_f32_u32(b_u32_high);
float32x4_t g_f32_high = vcvtq_f32_u32(g_u32_high);
float32x4_t r_f32_high = vcvtq_f32_u32(r_u32_high);
#ifdef USE_NEON_SUB
b_f32_high = vsubq_f32(b_f32_high, b_mean);
g_f32_high = vsubq_f32(g_f32_high, g_mean);
r_f32_high = vsubq_f32(r_f32_high, r_mean);
#endif
#ifdef USE_NEON_MUL
b_f32_high = vmulq_f32(b_f32_high, snum);
g_f32_high = vmulq_f32(g_f32_high, snum);
r_f32_high = vmulq_f32(r_f32_high, snum);
#endif
int32x4_t bres_s32_high = vcvtq_s32_f32(b_f32_high);
int32x4_t gres_s32_high = vcvtq_s32_f32(g_f32_high);
int32x4_t rres_s32_high = vcvtq_s32_f32(r_f32_high);
int16x4_t bres_s16_high = vqmovn_s32(bres_s32_high);
int16x4_t gres_s16_high = vqmovn_s32(gres_s32_high);
int16x4_t rres_s16_high = vqmovn_s32(rres_s32_high);
int16x8_t bres_s16 = vcombine_s16(bres_s16_low, bres_s16_high);
int16x8_t gres_s16 = vcombine_s16(gres_s16_low, gres_s16_high);
int16x8_t rres_s16 = vcombine_s16(rres_s16_low, rres_s16_high);
int8x8_t bres_s8 = vqmovn_s16(bres_s16);
int8x8_t gres_s8 = vqmovn_s16(gres_s16);
int8x8_t rres_s8 = vqmovn_s16(rres_s16);
bgr_res.val[0] = bres_s8;
bgr_res.val[1] = gres_s8;
bgr_res.val[2] = rres_s8;
vst3_s8(dst + i, bgr_res);
// // method two
// vst3_s8(dst, {vqmovn_s16(vcombine_s16(vqmovn_s32(vcvtq_s32_f32(vmulq_f32(vsubq_f32(vcvtq_f32_u32(vmovl_u16( vget_low_u16(vmovl_u8(bgr.val[0])))), b_mean), snum))),
// vqmovn_s32(vcvtq_s32_f32(vmulq_f32(vsubq_f32(vcvtq_f32_u32(vmovl_u16(vget_high_u16(vmovl_u8(bgr.val[0])))), b_mean), snum))))),
// vqmovn_s16(vcombine_s16(vqmovn_s32(vcvtq_s32_f32(vmulq_f32(vsubq_f32(vcvtq_f32_u32(vmovl_u16( vget_low_u16(vmovl_u8(bgr.val[1])))), g_mean), snum))),
// vqmovn_s32(vcvtq_s32_f32(vmulq_f32(vsubq_f32(vcvtq_f32_u32(vmovl_u16(vget_high_u16(vmovl_u8(bgr.val[1])))), g_mean), snum))))),
// vqmovn_s16(vcombine_s16(vqmovn_s32(vcvtq_s32_f32(vmulq_f32(vsubq_f32(vcvtq_f32_u32(vmovl_u16( vget_low_u16(vmovl_u8(bgr.val[2])))), r_mean), snum))),
// vqmovn_s32(vcvtq_s32_f32(vmulq_f32(vsubq_f32(vcvtq_f32_u32(vmovl_u16(vget_high_u16(vmovl_u8(bgr.val[2])))), r_mean), snum)))))});
// // method three // 不显示结果
// vst3_s8(dst, {vqmovn_s16(vcombine_s16(vqmovn_s32(vreinterpretq_s32_f32(vmulq_f32(vsubq_f32(vreinterpretq_f32_u32(vmovl_u16( vget_low_u16(vmovl_u8(bgr.val[0])))), b_mean), snum))),
// vqmovn_s32(vreinterpretq_s32_f32(vmulq_f32(vsubq_f32(vreinterpretq_f32_u32(vmovl_u16(vget_high_u16(vmovl_u8(bgr.val[0])))), b_mean), snum))))),
// vqmovn_s16(vcombine_s16(vqmovn_s32(vreinterpretq_s32_f32(vmulq_f32(vsubq_f32(vreinterpretq_f32_u32(vmovl_u16( vget_low_u16(vmovl_u8(bgr.val[1])))), g_mean), snum))),
// vqmovn_s32(vreinterpretq_s32_f32(vmulq_f32(vsubq_f32(vreinterpretq_f32_u32(vmovl_u16(vget_high_u16(vmovl_u8(bgr.val[1])))), g_mean), snum))))),
// vqmovn_s16(vcombine_s16(vqmovn_s32(vreinterpretq_s32_f32(vmulq_f32(vsubq_f32(vreinterpretq_f32_u32(vmovl_u16( vget_low_u16(vmovl_u8(bgr.val[2])))), r_mean), snum))),
// vqmovn_s32(vreinterpretq_s32_f32(vmulq_f32(vsubq_f32(vreinterpretq_f32_u32(vmovl_u16(vget_high_u16(vmovl_u8(bgr.val[2])))), r_mean), snum)))))});
}
while(i < len){
#ifdef USE_NEON_SUB
dst[i] = (int8_t)((float)(src[i]) - mean[2]);
#endif
#ifdef USE_NEON_MUL
dst[i] *= scale;
#endif
#ifdef USE_NEON_SUB
dst[i] = (int8_t)((float)(src[i]) - mean[1]);
#endif
#ifdef USE_NEON_MUL
dst[i] *= scale;
#endif
#ifdef USE_NEON_SUB
dst[i] = (int8_t)((float)(src[i]) - mean[0]);
#endif
#ifdef USE_NEON_MUL
dst[i] *= scale;
#endif
i += 3;
}
}
}
|
/* Copyright 2017-2018 All Rights Reserved.
* Gyeonghwan Hong (redcarrottt@gmail.com)
*
* [Contact]
* Gyeonghwan Hong (redcarrottt@gmail.com)
*
* 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.
*/
#ifndef __TRACE_RUNNER_H__
#define __TRACE_RUNNER_H__
#include "../common/inc/csv.h"
#include "../core/inc/API.h"
#include "../core/inc/NMPolicy.h"
#include "../core/inc/ServerAdapterStateListener.h"
#include "../common/inc/DebugLog.h"
#include "../device/inc/BtServerAdapter.h"
#include "../device/inc/WfdServerAdapter.h"
#include <string>
#include <thread>
#define DEBUG_SHOW_DATA 0
#define DEBUG_SHOW_TIME 0
#define TEST_DATA_SIZE (128)
class PacketTraceReader {
public:
void read_header() {
this->mCSVReader->read_header(io::ignore_extra_column, "TimeUS", "Length");
}
bool read_a_row(int &ts_us, int &payload_length) {
std::string ts_us_str, payload_length_str;
bool ret = this->mCSVReader->read_row(ts_us_str, payload_length_str);
if (ret) {
// LOG_VERB("ROW: %s / %s", ts_us_str.c_str(), payload_length_str.c_str());
ts_us = std::stoi(ts_us_str);
payload_length = std::stoi(payload_length_str);
}
return ret;
}
PacketTraceReader(std::string filename) {
this->mCSVReader =
new io::CSVReader<2, io::trim_chars<>,
io::double_quote_escape<',', '\"'>>(filename.c_str());
}
private:
io::CSVReader<2, io::trim_chars<>, io::double_quote_escape<',', '\"'>>
*mCSVReader;
};
class EventTraceReader {
public:
void read_header() {
this->mCSVReader->read_header(io::ignore_extra_column, "TimeUS", "Event");
}
bool read_a_row(int &ts_us, std::string &event_description) {
std::string ts_us_str;
bool ret = this->mCSVReader->read_row(ts_us_str, event_description);
if (ret) {
LOG_VERB("ROW: %s / %s", ts_us_str.c_str(), event_description.c_str());
ts_us = std::stoi(ts_us_str);
}
return ret;
}
EventTraceReader(std::string filename) {
this->mCSVReader =
new io::CSVReader<2, io::trim_chars<>,
io::double_quote_escape<',', '\"'>>(filename.c_str());
}
private:
io::CSVReader<2, io::trim_chars<>, io::double_quote_escape<',', '\"'>>
*mCSVReader;
}; /* class EventTraceReader */
class TraceRunner : sc::ServerAdapterStateListener {
public:
void start(sc::NMPolicy *switch_policy);
static void on_start_sc(bool is_success);
private:
static TraceRunner *sTraceRunner;
private:
void send_test_data(void);
void send_workload(std::string &packet_trace_filename,
std::string &event_trace_filename);
bool check_event(EventTraceReader *event_trace_reader, int next_packet_ts_us,
bool &next_event_ts_ready, int &next_event_ts_us);
int sleep_workload(int next_ts_us);
void receiving_thread(void);
private:
/* implement sc::ServerAdapterStateListener */
virtual void onUpdateServerAdapterState(sc::ServerAdapter *adapter,
sc::ServerAdapterState old_state,
sc::ServerAdapterState new_state);
private:
static char *generate_simple_string(char *str, size_t size);
public:
static TraceRunner *trace_runner(std::string packet_trace_filename,
std::string event_trace_filename);
private:
TraceRunner(std::string packet_trace_filename,
std::string event_trace_filename) {
this->mPacketTraceFilename.assign(packet_trace_filename);
this->mEventTraceFilename.assign(event_trace_filename);
}
private:
/* Attributes */
std::string mPacketTraceFilename;
std::string mEventTraceFilename;
int mRecentTSUs = 0;
/* Components */
std::thread *mThread;
sc::BtServerAdapter *mBtAdapter;
sc::WfdServerAdapter *mWfdAdapter;
}; /* class TraceRunner */
#endif /* !defined(__TRACE_RUNNER_H__) */
|
#include "util.hpp"
using namespace cv;
using namespace std;
void detectAndDraw( Mat img, CascadeClassifier& cascade,
CascadeClassifier& nestedCascade,
double scale, bool tryflip )
{
double t = 0;
std::vector<Rect> faces, faces2;
const static Scalar colors[] =
{
Scalar(255,0,0),
Scalar(255,128,0),
Scalar(255,255,0),
Scalar(0,255,0),
Scalar(0,128,255),
Scalar(0,255,255),
Scalar(0,0,255),
Scalar(255,0,255)
};
Mat gray, smallImg;
cvtColor( img, gray, COLOR_BGR2GRAY );
double fx = 1 / scale;
resize( gray, smallImg, Size(), fx, fx);
equalizeHist( smallImg, smallImg );
t = (double)getTickCount();
cascade.detectMultiScale( smallImg, faces,
1.1, 2, 0
//|CASCADE_FIND_BIGGEST_OBJECT
//|CASCADE_DO_ROUGH_SEARCH
|CASCADE_SCALE_IMAGE,
Size(30, 30) );
if( tryflip )
{
flip(smallImg, smallImg, 1);
cascade.detectMultiScale( smallImg, faces2,
1.1, 2, 0
//|CASCADE_FIND_BIGGEST_OBJECT
//|CASCADE_DO_ROUGH_SEARCH
|CASCADE_SCALE_IMAGE,
Size(30, 30) );
for( std::vector<Rect>::const_iterator r = faces2.begin(); r != faces2.end(); ++r )
{
faces.push_back(Rect(smallImg.cols - r->x - r->width, r->y, r->width, r->height));
}
}
t = (double)getTickCount() - t;
//printf( "detection time = %g ms\n", t*1000/getTickFrequency());
for ( size_t i = 0; i < faces.size(); i++ )
{
Rect r = faces[i];
Mat smallImgROI;
std::vector<Rect> nestedObjects;
Point center;
Scalar color = colors[i%8];
int radius;
double aspect_ratio = (double)r.width/r.height;
if( 0.75 < aspect_ratio && aspect_ratio < 1.3 )
{
center.x = cvRound((r.x + r.width*0.5)*scale);
center.y = cvRound((r.y + r.height*0.5)*scale);
radius = cvRound((r.width + r.height)*0.25*scale);
circle( img, center, radius, color, 3, 8, 0 );
}
else
rectangle( img, cv::Point(cvRound(r.x*scale), cvRound(r.y*scale)),
cv::Point(cvRound((r.x + r.width-1)*scale), cvRound((r.y + r.height-1)*scale)),
color, 3, 8, 0);
if( nestedCascade.empty() )
continue;
smallImgROI = smallImg( r );
nestedCascade.detectMultiScale( smallImgROI, nestedObjects,
1.1, 2, 0
//|CASCADE_FIND_BIGGEST_OBJECT
//|CASCADE_DO_ROUGH_SEARCH
//|CASCADE_DO_CANNY_PRUNING
|CASCADE_SCALE_IMAGE,
Size(30, 30) );
for ( size_t j = 0; j < nestedObjects.size(); j++ )
{
Rect nr = nestedObjects[j];
center.x = cvRound((r.x + nr.x + nr.width*0.5)*scale);
center.y = cvRound((r.y + nr.y + nr.height*0.5)*scale);
radius = cvRound((nr.width + nr.height)*0.25*scale);
circle( img, center, radius, color, 3, 8, 0 );
}
}
//imshow( "result", img );
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.