hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
07ae0ed1ffac81fe5b17227dc340277dc1242f24 | 669 | hpp | C++ | Screen.hpp | TheSovietStorm/PathTracer | 1c8a5d077f7fea37371ea1425966b77b751202c8 | [
"MIT"
] | null | null | null | Screen.hpp | TheSovietStorm/PathTracer | 1c8a5d077f7fea37371ea1425966b77b751202c8 | [
"MIT"
] | null | null | null | Screen.hpp | TheSovietStorm/PathTracer | 1c8a5d077f7fea37371ea1425966b77b751202c8 | [
"MIT"
] | null | null | null | //
// Created by Peter Zdankin on 26.03.18.
//
#ifndef PATHTRACER_SCREEN_HPP
#define PATHTRACER_SCREEN_HPP
#include <vector>
#include "Point.hpp"
class Screen{
private:
uint64_t width;
uint64_t height;
std::vector<unsigned char> data;
public:
Screen():width(1000), height(1000){
data.resize(4000000);
}
Screen(uint64_t _width, uint64_t _height):width(_width), height(_height){
data.resize(4*_width * _height);
}
void setPixel(uint64_t x, uint64_t y, Point c);
uint64_t getWidth() const;
uint64_t getHeight() const;
void clear();
void save(const char *filename);
};
#endif //PATHTRACER_SCREEN_HPP
| 21.580645 | 79 | 0.674141 | [
"vector"
] |
07aee85e2d0c0729be024c53724ffce89f90ef76 | 32,173 | cpp | C++ | DTest/main.cpp | bo3b/iZ3D | ced8b3a4b0a152d0177f2e94008918efc76935d5 | [
"MIT"
] | 27 | 2020-11-12T19:24:54.000Z | 2022-03-27T23:10:45.000Z | DTest/main.cpp | bo3b/iZ3D | ced8b3a4b0a152d0177f2e94008918efc76935d5 | [
"MIT"
] | 2 | 2020-11-02T06:30:39.000Z | 2022-02-23T18:39:55.000Z | DTest/main.cpp | bo3b/iZ3D | ced8b3a4b0a152d0177f2e94008918efc76935d5 | [
"MIT"
] | 3 | 2021-08-16T00:21:08.000Z | 2022-02-23T19:19:36.000Z | #include <DXUT.h>
#include <DXUTmisc.h>
#include <SDKmisc.h>
#include <SDKmesh.h>
#include <D3DX9Mesh.h>
#include <shlwapi.h>
#include "../../../Shared/ProductNames.h"
#include "../../S3DAPI/StereoAPI.h"
//--------------------------------------------------------------------------------------
// D3D9 data
//--------------------------------------------------------------------------------------
namespace d3d9
{
ID3DXEffect* g_pEffect = NULL;
ID3DXMesh* g_pMesh = NULL;
ID3DXFont* g_pFont = NULL;
D3DMATERIAL9* g_pMeshMaterials = NULL;
DWORD g_dwNumMeshMaterials = NULL;
D3DXHANDLE g_pTechnique = NULL;
D3DXHANDLE g_pWorldVariable = NULL;
D3DXHANDLE g_pViewVariable = NULL;
D3DXHANDLE g_pProjectionVariable = NULL;
D3DXHANDLE g_pEyeVariable = NULL;
D3DXHANDLE g_pLightPosVariable = NULL;
D3DXHANDLE g_pDiffuseVariable = NULL;
D3DXHANDLE g_pSpecularVariable = NULL;
bool CALLBACK IsDeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat, bool bWindowed, void* pUserContext );
HRESULT CALLBACK OnCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext );
HRESULT CALLBACK OnResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext );
void CALLBACK OnFrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext );
void CALLBACK OnLostDevice( void* pUserContext );
void CALLBACK OnDestroyDevice( void* pUserContext );
};
//--------------------------------------------------------------------------------------
// D3D10 data
//--------------------------------------------------------------------------------------
namespace d3d10
{
CDXUTSDKMesh g_Mesh;
ID3DX10Font* g_pFont = NULL;
ID3DX10Sprite* g_pFontSprite = NULL;
ID3D10Effect* g_pEffect = NULL;
ID3D10InputLayout* g_pVertexLayout = NULL;
ID3D10EffectTechnique* g_pTechnique = NULL;
ID3D10EffectMatrixVariable* g_pWorldVariable = NULL;
ID3D10EffectMatrixVariable* g_pViewVariable = NULL;
ID3D10EffectMatrixVariable* g_pProjectionVariable = NULL;
ID3D10EffectVectorVariable* g_pEyeVariable = NULL;
ID3D10EffectVectorVariable* g_pLightPosVariable = NULL;
ID3D10EffectVectorVariable* g_pDiffuseVariable = NULL;
ID3D10EffectVectorVariable* g_pSpecularVariable = NULL;
bool CALLBACK IsDeviceAcceptable( UINT Adapter, UINT Output, D3D10_DRIVER_TYPE DeviceType, DXGI_FORMAT BufferFormat, bool bWindowed, void* pUserContext );
HRESULT CALLBACK OnCreateDevice( ID3D10Device* pd3dDevice, const DXGI_SURFACE_DESC* pBufferSurfaceDesc, void* pUserContext );
HRESULT CALLBACK OnResizedSwapChain( ID3D10Device* pd3dDevice, IDXGISwapChain* pSwapChain, const DXGI_SURFACE_DESC* pBufferSurfaceDesc, void* pUserContext );
void CALLBACK OnReleasingSwapChain( void* pUserContext );
void CALLBACK OnDestroyDevice( void* pUserContext );
void CALLBACK OnFrameRender( ID3D10Device* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext );
};
//--------------------------------------------------------------------------------------
// Shared
//--------------------------------------------------------------------------------------
DXUTDeviceSettings g_AppDeviceSettings;
IStereoAPI* g_StereoAPI = 0;
D3DXMATRIX g_World;
D3DXMATRIX g_View;
D3DXMATRIX g_Projection;
D3DXVECTOR3 g_Eye( 0.0, 0.0, -10.0 );
D3DXVECTOR3 g_At( 0.0, 0.0, 0.0 );
D3DXVECTOR3 g_Up( 0.0, 1.0, 0.0 );
D3DXVECTOR3 g_LightPos( 0.0f, 10.0f, -5.0f );
D3DXCOLOR g_ClearColor( 0.0f, 0.05f, 0.1f, 1.0f );
LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext );
void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext );
void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext );
bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext );
void BeginStereo()
{
if (g_StereoAPI) {
g_StereoAPI->BeginStereoBlock();
}
}
void EndStereo()
{
if (g_StereoAPI) {
g_StereoAPI->EndStereoBlock();
}
}
HRESULT InitializeDX9(BOOL Windowed, DWORD Width, DWORD Height, DWORD RefreshRate, BOOL vsync)
{
// Check for hardware T&L
DWORD Flags = 0;
D3DCAPS9 D3DCaps;
DXUTGetD3D9Object()->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &D3DCaps);
if (D3DCaps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
{
Flags = D3DCREATE_HARDWARE_VERTEXPROCESSING;
if (D3DCaps.DevCaps & D3DDEVCAPS_PUREDEVICE) {
Flags |= D3DCREATE_PUREDEVICE;
}
}
else {
Flags = D3DCREATE_SOFTWARE_VERTEXPROCESSING;
}
// Fill up device settings
g_AppDeviceSettings.d3d9.AdapterOrdinal = D3DADAPTER_DEFAULT;
g_AppDeviceSettings.d3d9.DeviceType = D3DDEVTYPE_HAL;
g_AppDeviceSettings.d3d9.BehaviorFlags = Flags;
g_AppDeviceSettings.d3d9.pp.BackBufferWidth = Width;
g_AppDeviceSettings.d3d9.pp.BackBufferHeight = Height;
g_AppDeviceSettings.d3d9.pp.BackBufferFormat = D3DFMT_X8R8G8B8;
g_AppDeviceSettings.d3d9.pp.BackBufferCount = 2;
g_AppDeviceSettings.d3d9.pp.MultiSampleType = D3DMULTISAMPLE_NONE;
g_AppDeviceSettings.d3d9.pp.SwapEffect = D3DSWAPEFFECT_DISCARD;
g_AppDeviceSettings.d3d9.pp.hDeviceWindow = DXUTGetHWND();
g_AppDeviceSettings.d3d9.pp.Windowed = Windowed;
g_AppDeviceSettings.d3d9.pp.EnableAutoDepthStencil = TRUE;
g_AppDeviceSettings.d3d9.pp.AutoDepthStencilFormat = D3DFMT_D24S8;
g_AppDeviceSettings.d3d9.pp.Flags = 0;
g_AppDeviceSettings.d3d9.pp.FullScreen_RefreshRateInHz = Windowed ? 0 : RefreshRate;
g_AppDeviceSettings.d3d9.pp.PresentationInterval = vsync ? D3DPRESENT_INTERVAL_ONE : D3DPRESENT_INTERVAL_IMMEDIATE;
// Resize window
// Further back buffer size will be retrieved from window client rect
if (Windowed)
{
RECT rcClient, rcWindow;
POINT ptDiff;
GetClientRect(DXUTGetHWND(), &rcClient);
GetWindowRect(DXUTGetHWND(), &rcWindow);
ptDiff.x = (rcWindow.right - rcWindow.left) - rcClient.right;
ptDiff.y = (rcWindow.bottom - rcWindow.top) - rcClient.bottom;
MoveWindow( DXUTGetHWND(),
100,
100,
Width + ptDiff.x,
Height + ptDiff.y,
TRUE );
}
return DXUTCreateDeviceFromSettings(&g_AppDeviceSettings);
}
HMONITOR GetPrimaryMonitorHandle()
{
const POINT ptZero = { 0, 0 };
return MonitorFromPoint(ptZero, MONITOR_DEFAULTTOPRIMARY);
}
HRESULT FindPrimaryMonitor(DXUTD3D10DeviceSettings& d3d10)
{
HMONITOR hPrimaryMonitor = GetPrimaryMonitorHandle();
// Search for this monitor in our enumeration hierarchy.
CD3D10Enumeration* pd3dEnum = DXUTGetD3D10Enumeration();
CGrowableArray <CD3D10EnumAdapterInfo*>* pAdapterList = pd3dEnum->GetAdapterInfoList();
for( int iAdapter = 0; iAdapter < pAdapterList->GetSize(); ++iAdapter )
{
CD3D10EnumAdapterInfo* pAdapterInfo = pAdapterList->GetAt( iAdapter );
for( int o = 0; o < pAdapterInfo->outputInfoList.GetSize(); ++o )
{
CD3D10EnumOutputInfo* pOutputInfo = pAdapterInfo->outputInfoList.GetAt( o );
DXGI_OUTPUT_DESC Desc;
pOutputInfo->m_pOutput->GetDesc( &Desc );
if( hPrimaryMonitor == Desc.Monitor )
{
d3d10.AdapterOrdinal = pAdapterInfo->AdapterOrdinal;
d3d10.Output = pOutputInfo->Output;
return S_OK;
}
}
}
return E_FAIL;
}
HRESULT InitializeDX10(BOOL Windowed, DWORD Width, DWORD Height, DWORD RefreshRate, BOOL vsync)
{
HRESULT hr;
g_AppDeviceSettings.ver = DXUT_D3D10_DEVICE;
g_AppDeviceSettings.d3d10.AdapterOrdinal = 0;
g_AppDeviceSettings.d3d10.DriverType = D3D10_DRIVER_TYPE_HARDWARE;
g_AppDeviceSettings.d3d10.Output = 0;
g_AppDeviceSettings.d3d10.CreateFlags = 0;
g_AppDeviceSettings.d3d10.SyncInterval = vsync ? 1 : 0;
g_AppDeviceSettings.d3d10.PresentFlags = 0;
g_AppDeviceSettings.d3d10.AutoCreateDepthStencil = TRUE;
g_AppDeviceSettings.d3d10.AutoDepthStencilFormat = DXGI_FORMAT_D24_UNORM_S8_UINT;
FindPrimaryMonitor(g_AppDeviceSettings.d3d10);
if (Windowed)
{
DXGI_RATIONAL RefreshRateRational = { 0, 1 };
g_AppDeviceSettings.d3d10.sd.BufferDesc.Width = Width;
g_AppDeviceSettings.d3d10.sd.BufferDesc.Height = Height;
g_AppDeviceSettings.d3d10.sd.BufferDesc.RefreshRate = RefreshRateRational;
g_AppDeviceSettings.d3d10.sd.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
g_AppDeviceSettings.d3d10.sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
g_AppDeviceSettings.d3d10.sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
}
else
{
IDXGIFactory* Factory = DXUTGetDXGIFactory();
if (!Factory) {
return E_FAIL;
}
IDXGIAdapter* Adapter;
V_RETURN( Factory->EnumAdapters(g_AppDeviceSettings.d3d10.AdapterOrdinal, &Adapter) );
IDXGIOutput* Output;
V_RETURN( Adapter->EnumOutputs(g_AppDeviceSettings.d3d10.Output, &Output) );
// Find closest matching mode;
DXGI_MODE_DESC ClosestModeToMatch;
DXGI_MODE_DESC ClosestMatchingMode;
{
DXGI_RATIONAL RefreshRateRational = { RefreshRate, 1 };
ClosestModeToMatch.Width = Width;
ClosestModeToMatch.Height = Height;
ClosestModeToMatch.RefreshRate = RefreshRateRational;
ClosestModeToMatch.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
ClosestModeToMatch.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
ClosestModeToMatch.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
V_RETURN( Output->FindClosestMatchingMode(&ClosestModeToMatch, &ClosestMatchingMode, NULL) );
}
g_AppDeviceSettings.d3d10.sd.BufferDesc = ClosestMatchingMode;
}
DXGI_SAMPLE_DESC SampleDesc = { 0, 0 };
g_AppDeviceSettings.d3d10.sd.SampleDesc = SampleDesc;
g_AppDeviceSettings.d3d10.sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
g_AppDeviceSettings.d3d10.sd.BufferCount = 1;
g_AppDeviceSettings.d3d10.sd.OutputWindow = DXUTGetHWND();
g_AppDeviceSettings.d3d10.sd.Windowed = Windowed;
g_AppDeviceSettings.d3d10.sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
g_AppDeviceSettings.d3d10.sd.Flags = 0;
return DXUTCreateDeviceFromSettings(&g_AppDeviceSettings);
}
//--------------------------------------------------------------------------------------
// Entry point to the program. Initializes everything and goes into a message processing
// loop. Idle time is used to render the scene.
//--------------------------------------------------------------------------------------
INT WINAPI wWinMain( HINSTANCE, HINSTANCE, LPWSTR cmdLine, int )
{
// Enable run-time memory check for debug builds.
#ifdef _DEBUG
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif
// Remove the working directory from the search path to work around the DLL preloading vulnerability
HMODULE hKernel = GetModuleHandle(L"Kernel32.dll");
if (hKernel)
{
typedef BOOL (WINAPI *SetDllDirectoryWType)(LPCWSTR lpPathName);
SetDllDirectoryWType pfnSetDllDirectory = (SetDllDirectoryWType)GetProcAddress(hKernel, "SetDllDirectoryW");
if (pfnSetDllDirectory)
pfnSetDllDirectory(L"");
typedef BOOL (WINAPI *SetSearchPathModeType)(DWORD Flags);
SetSearchPathModeType pfnSetSearchPathMode = (SetSearchPathModeType)GetProcAddress(hKernel, "SetSearchPathMode");
if (pfnSetSearchPathMode)
pfnSetSearchPathMode(BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE);
}
// Setup AppData as search path
TCHAR szPath[ MAX_PATH ];
if( SUCCEEDED(SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szPath )) )
{
PathAppend( szPath, TEXT(PRODUCT_NAME));
PathAppend( szPath, TEXT("DTest"));
}
SetCurrentDirectory(szPath);
// Set DXUT callbacks
DXUTSetCallbackD3D9DeviceAcceptable( d3d9::IsDeviceAcceptable );
DXUTSetCallbackD3D9DeviceCreated( d3d9::OnCreateDevice );
DXUTSetCallbackD3D9DeviceReset( d3d9::OnResetDevice );
DXUTSetCallbackD3D9FrameRender( d3d9::OnFrameRender );
DXUTSetCallbackD3D9DeviceLost( d3d9::OnLostDevice );
DXUTSetCallbackD3D9DeviceDestroyed( d3d9::OnDestroyDevice );
DXUTSetCallbackD3D10DeviceAcceptable( d3d10::IsDeviceAcceptable );
DXUTSetCallbackD3D10DeviceCreated( d3d10::OnCreateDevice );
DXUTSetCallbackD3D10SwapChainResized( d3d10::OnResizedSwapChain );
DXUTSetCallbackD3D10SwapChainReleasing( d3d10::OnReleasingSwapChain );
DXUTSetCallbackD3D10DeviceDestroyed( d3d10::OnDestroyDevice );
DXUTSetCallbackD3D10FrameRender( d3d10::OnFrameRender );
DXUTSetCallbackMsgProc( MsgProc );
DXUTSetCallbackKeyboard( OnKeyboard );
DXUTSetCallbackFrameMove( OnFrameMove );
DXUTSetCallbackDeviceChanging( ModifyDeviceSettings );
#ifdef _DEBUG
bool MBoxOnErrors = true;
#else
bool MBoxOnErrors = false;
#endif
DXUTInit( true, MBoxOnErrors, NULL );
DXUTSetCursorSettings( true, true );
DXUTCreateWindow( L"Dynamic Test" );
// Parse command line & retrieve settings
DXUTDeviceVersion DeviceVersion = DXUT_D3D10_DEVICE;
BOOL Windowed = TRUE;
DWORD Width = 800;
DWORD Height = 600;
DWORD RefreshRate = 60;
BOOL VSync = TRUE;
BOOL StereoAPI = FALSE;
{
LPWSTR* szArgList;
int argCount;
szArgList = CommandLineToArgvW(GetCommandLine(), &argCount);
if (szArgList)
{
for (int i = 1; i<argCount; ++i)
{
if (StrCmp(szArgList[i], L"-dx9") == 0) {
DeviceVersion = DXUT_D3D9_DEVICE;
}
else if (StrCmp(szArgList[i], L"-dx10") == 0) {
DeviceVersion = DXUT_D3D10_DEVICE;
}
else if (StrCmp(szArgList[i], L"-stereo_api") == 0) {
StereoAPI = TRUE;
}
else if (StrCmp(szArgList[i], L"-fullscreen") == 0)
{
Windowed = FALSE;
DEVMODE CurrentMode;
if ( EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &CurrentMode) )
{
Width = CurrentMode.dmPelsWidth;
Height = CurrentMode.dmPelsHeight;
RefreshRate = CurrentMode.dmDisplayFrequency;
}
}
else if (StrCmp(szArgList[i], L"-no_vsync") == 0) {
VSync = FALSE;
}
}
}
LocalFree(szArgList);
}
// Try to create DX10 device
g_AppDeviceSettings.ver = DeviceVersion;
if (g_AppDeviceSettings.ver == DXUT_D3D10_DEVICE)
{
if ( FAILED( InitializeDX10(Windowed, Width, Height, RefreshRate, VSync) ) )
{
// Try to initialize DX9 as well
g_AppDeviceSettings.ver = DXUT_D3D9_DEVICE;
}
}
if (g_AppDeviceSettings.ver == DXUT_D3D9_DEVICE)
{
if ( FAILED( InitializeDX9(Windowed, Width, Height, RefreshRate, VSync) ) ) {
return EXIT_FAILURE;
}
}
if (StereoAPI)
{
if (HMODULE hMod = GetStereoLibraryHandle()) {
CreateStereoAPI( hMod, &g_StereoAPI );
}
}
DXUTMainLoop();
SAFE_RELEASE(g_StereoAPI);
return DXUTGetExitCode();
}
//--------------------------------------------------------------------------------------
// Called right before creating a D3D9 or D3D10 device, allowing the app to modify the device settings as needed
//--------------------------------------------------------------------------------------
bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext )
{
if ( DXUT_D3D9_DEVICE == pDeviceSettings->ver )
{
// DXUT gives invalid settings for DX9, use own
pDeviceSettings->d3d9 = g_AppDeviceSettings.d3d9;
// Resice back buffer
if (g_AppDeviceSettings.d3d9.pp.Windowed)
{
RECT clientRect;
GetClientRect(DXUTGetHWND(), &clientRect);
pDeviceSettings->d3d9.pp.BackBufferWidth = clientRect.right - clientRect.left;
pDeviceSettings->d3d9.pp.BackBufferHeight = clientRect.bottom - clientRect.top;
}
// Correct aspect
float fAspect = static_cast<float>(pDeviceSettings->d3d9.pp.BackBufferWidth) / static_cast<float>(pDeviceSettings->d3d9.pp.BackBufferHeight);
D3DXMatrixPerspectiveFovLH( &g_Projection, D3DX_PI * 0.25f, fAspect, 0.5f, 100.0f );
}
else {
g_AppDeviceSettings.d3d10 = pDeviceSettings->d3d10;
}
return true;
}
//--------------------------------------------------------------------------------------
// Handle updates to the scene. This is called regardless of which D3D API is used
//--------------------------------------------------------------------------------------
void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext )
{
// Rotate cube around the origin
D3DXMatrixRotationY( &g_World, (float)fTime );
}
//--------------------------------------------------------------------------------------
// Handle messages to the application
//--------------------------------------------------------------------------------------
LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext )
{
return 0;
}
//--------------------------------------------------------------------------------------
// Handle key presses
//--------------------------------------------------------------------------------------
void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext )
{
}
namespace d3d9 {
//--------------------------------------------------------------------------------------
// Rejects any D3D9 devices that aren't acceptable to the app by returning false
//--------------------------------------------------------------------------------------
bool CALLBACK IsDeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat, bool bWindowed, void* pUserContext )
{
// No fallback defined by this app, so reject any device that doesn't support at least ps2.0
if( pCaps->PixelShaderVersion < D3DPS_VERSION(2, 0) ) {
return false;
}
// Skip backbuffer formats that don't support alpha blending
IDirect3D9* pD3D = DXUTGetD3D9Object();
if( FAILED( pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal,
pCaps->DeviceType,
AdapterFormat,
D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
D3DRTYPE_TEXTURE,
BackBufferFormat ) ) )
{
return false;
}
return true;
}
//--------------------------------------------------------------------------------------
// Create any D3D9 resources that will live through a device reset (D3DPOOL_MANAGED)
// and aren't tied to the back buffer size
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext )
{
HRESULT hr;
// Load the mesh
ID3DXMesh* pMesh = 0;
ID3DXBuffer* pD3DXMtrlBuffer = 0;
V_RETURN( D3DXLoadMeshFromX( L"data\\models\\logo\\logo.x",
D3DXMESH_MANAGED,
pd3dDevice,
NULL,
&pD3DXMtrlBuffer,
NULL,
&g_dwNumMeshMaterials,
&g_pMesh ) );
// Copy materials
D3DXMATERIAL* pD3DXMaterials = (D3DXMATERIAL*)pD3DXMtrlBuffer->GetBufferPointer();
if (pD3DXMaterials)
{
g_pMeshMaterials = new D3DMATERIAL9[g_dwNumMeshMaterials];
for (DWORD i = 0; i<g_dwNumMeshMaterials; ++i)
{
g_pMeshMaterials[i] = pD3DXMaterials[i].MatD3D;
}
}
SAFE_RELEASE(pD3DXMtrlBuffer);
// Load effect
LPD3DXBUFFER pErrors;
DWORD dwShaderFlags = D3DXFX_NOT_CLONEABLE | D3DXSHADER_NO_PRESHADER | D3DXFX_LARGEADDRESSAWARE;
hr = D3DXCreateEffectFromFile( pd3dDevice,
L"data\\shaders\\DTestDX9.fx",
NULL,
NULL,
dwShaderFlags,
NULL,
&g_pEffect,
&pErrors );
if ( !SUCCEEDED(hr) )
{
if (pErrors) {
DXUTOutputDebugStringA( (char*)pErrors->GetBufferPointer() );
}
else {
DXUTOutputDebugStringW( L"Can't create effect.\n" );
}
return hr;
}
// Obtain the technique
g_pTechnique = g_pEffect->GetTechniqueByName( "Render" );
g_pWorldVariable = g_pEffect->GetParameterByName( NULL, "World" );
g_pViewVariable = g_pEffect->GetParameterByName( NULL, "View" );
g_pProjectionVariable = g_pEffect->GetParameterByName( NULL, "Projection" );
g_pEyeVariable = g_pEffect->GetParameterByName( NULL, "Eye" );
g_pDiffuseVariable = g_pEffect->GetParameterByName( NULL, "Diffuse" );
g_pSpecularVariable = g_pEffect->GetParameterByName( NULL, "Specular" );
g_pLightPosVariable = g_pEffect->GetParameterByName( NULL, "LightPos" );
// Create font
V_RETURN( D3DXCreateFont( pd3dDevice,
36,
0,
FW_BOLD,
1,
FALSE,
DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS,
DEFAULT_QUALITY,
DEFAULT_PITCH | FF_DONTCARE,
L"Arial",
&g_pFont ) );
// Initialize the world matrices
D3DXMatrixIdentity( &g_World );
// Initialize the view matrix
D3DXMatrixLookAtLH( &g_View, &g_Eye, &g_At, &g_Up );
return S_OK;
}
//--------------------------------------------------------------------------------------
// Create any D3D9 resources that won't live through a device reset (D3DPOOL_DEFAULT)
// or that are tied to the back buffer size
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext )
{
HRESULT hr;
if (g_pEffect) {
V_RETURN( g_pEffect->OnResetDevice() );
}
g_AppDeviceSettings.d3d9.pp.BackBufferWidth = pBackBufferSurfaceDesc->Width;
g_AppDeviceSettings.d3d9.pp.BackBufferHeight = pBackBufferSurfaceDesc->Height;
g_AppDeviceSettings.d3d9.pp.BackBufferFormat = pBackBufferSurfaceDesc->Format;
g_AppDeviceSettings.d3d9.pp.MultiSampleType = pBackBufferSurfaceDesc->MultiSampleType;
g_AppDeviceSettings.d3d9.pp.MultiSampleQuality = pBackBufferSurfaceDesc->MultiSampleQuality;
return S_OK;
}
//--------------------------------------------------------------------------------------
// Render the scene using the D3D9 device
//--------------------------------------------------------------------------------------
void CALLBACK OnFrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext )
{
HRESULT hr;
// Clear the render target and the zbuffer
D3DXCOLOR ClearColorGamma;
ClearColorGamma.r = powf(g_ClearColor.r, 1.0f / 2.2f);
ClearColorGamma.g = powf(g_ClearColor.g, 1.0f / 2.2f);
ClearColorGamma.b = powf(g_ClearColor.b, 1.0f / 2.2f);
ClearColorGamma.a = 1.0f;
V( pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, ClearColorGamma, 1.0f, 0 ) );
// Render the scene
if (g_StereoAPI) {
g_StereoAPI->BeginStereoBlock();
}
if( SUCCEEDED( pd3dDevice->BeginScene() ) )
{
// Update the effect's variables.
V( g_pEffect->SetMatrix( g_pWorldVariable, &g_World ) );
V( g_pEffect->SetMatrix( g_pViewVariable, &g_View ) );
V( g_pEffect->SetMatrix( g_pProjectionVariable, &g_Projection ) );
V( g_pEffect->SetValue( g_pEyeVariable, &g_Eye, sizeof(D3DXVECTOR3) ) );
V( g_pEffect->SetValue( g_pLightPosVariable, &g_LightPos, sizeof(D3DXVECTOR3) ) );
V( g_pEffect->SetTechnique( g_pTechnique ) );
BeginStereo();
{
// Apply the technique contained in the effect and render the mesh
UINT cPasses;
V( g_pEffect->Begin( &cPasses, 0 ) );
{
for(DWORD iPass = 0; iPass < cPasses; ++iPass)
{
for (DWORD iMat = 0; iMat < g_dwNumMeshMaterials; ++iMat)
{
V( g_pEffect->SetValue( g_pDiffuseVariable, &g_pMeshMaterials[iMat].Diffuse, sizeof(D3DCOLORVALUE) ) );
V( g_pEffect->SetValue( g_pSpecularVariable, &g_pMeshMaterials[iMat].Specular, sizeof(D3DCOLORVALUE) ) );
V( g_pEffect->BeginPass( iPass ) );
V( g_pMesh->DrawSubset(iMat) );
V( g_pEffect->EndPass() );
}
}
}
V( g_pEffect->End() );
if (g_StereoAPI)
{
// just to illustrate that you can make subblocks
g_StereoAPI->BeginMonoBlock();
{
RECT rect;
rect.left = g_AppDeviceSettings.d3d9.pp.BackBufferWidth / 2 - 125;
rect.right = rect.left + 250;
rect.top = 50;
rect.bottom = rect.top + 40;
g_pFont->DrawText( NULL, _T("Text is MONO"), -1, &rect, DT_CENTER, D3DCOLOR_RGBA(255,255,255,255) );
}
g_StereoAPI->EndMonoBlock();
}
}
EndStereo();
V( pd3dDevice->EndScene() );
}
if (g_StereoAPI) {
g_StereoAPI->EndStereoBlock();
}
}
//--------------------------------------------------------------------------------------
// Release D3D9 resources created in the OnResetDevice callback
//--------------------------------------------------------------------------------------
void CALLBACK OnLostDevice( void* pUserContext )
{
if (g_pEffect) {
g_pEffect->OnLostDevice();
}
}
//--------------------------------------------------------------------------------------
// Release D3D9 resources created in the OnCreateDevice callback
//--------------------------------------------------------------------------------------
void CALLBACK OnDestroyDevice( void* pUserContext )
{
SAFE_RELEASE( g_pEffect );
SAFE_RELEASE( g_pMesh );
SAFE_RELEASE( g_pFont );
SAFE_DELETE_ARRAY( g_pMeshMaterials );
}
} // namespace d3d9
namespace d3d10 {
//--------------------------------------------------------------------------------------
// Reject any D3D10 devices that aren't acceptable by returning false
//--------------------------------------------------------------------------------------
bool CALLBACK IsDeviceAcceptable( UINT Adapter, UINT Output, D3D10_DRIVER_TYPE DeviceType, DXGI_FORMAT BufferFormat, bool bWindowed, void* pUserContext )
{
return true;
}
//--------------------------------------------------------------------------------------
// Create any D3D10 resources that aren't dependant on the back buffer
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnCreateDevice( ID3D10Device* pd3dDevice, const DXGI_SURFACE_DESC* pBufferSurfaceDesc, void* pUserContext )
{
HRESULT hr;
// Find the D3DX effect file
DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS;
#ifdef _DEBUG
dwShaderFlags |= D3D10_SHADER_DEBUG;
#endif
ID3D10Blob* pErrors = 0;
hr = D3DX10CreateEffectFromFile( L"data\\shaders\\DTestDX10.fx",
NULL,
NULL,
"fx_4_0",
dwShaderFlags,
0,
pd3dDevice,
NULL,
NULL,
&g_pEffect,
&pErrors,
NULL );
if ( !SUCCEEDED(hr) )
{
if (pErrors) {
DXUTOutputDebugStringA( (char*)pErrors->GetBufferPointer() );
}
else {
DXUTOutputDebugStringW( L"Can't create effect.\n" );
}
return hr;
}
// Obtain the technique
g_pTechnique = g_pEffect->GetTechniqueByName( "Render" );
g_pWorldVariable = g_pEffect->GetVariableByName( "World" )->AsMatrix();
g_pViewVariable = g_pEffect->GetVariableByName( "View" )->AsMatrix();
g_pProjectionVariable = g_pEffect->GetVariableByName( "Projection" )->AsMatrix();
g_pEyeVariable = g_pEffect->GetVariableByName( "Eye" )->AsVector();
g_pDiffuseVariable = g_pEffect->GetVariableByName( "Diffuse" )->AsVector();
g_pSpecularVariable = g_pEffect->GetVariableByName( "Specular" )->AsVector();
g_pLightPosVariable = g_pEffect->GetVariableByName( "LightPos" )->AsVector();
// Define the input layout
const D3D10_INPUT_ELEMENT_DESC layout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D10_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D10_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D10_INPUT_PER_VERTEX_DATA, 0 },
};
UINT numElements = sizeof( layout ) / sizeof( layout[0] );
// Create the input layout
D3D10_PASS_DESC PassDesc;
g_pTechnique->GetPassByIndex(0)->GetDesc( &PassDesc );
V_RETURN( pd3dDevice->CreateInputLayout( layout,
numElements,
PassDesc.pIAInputSignature,
PassDesc.IAInputSignatureSize,
&g_pVertexLayout ) );
// Set the input layout
pd3dDevice->IASetInputLayout( g_pVertexLayout );
// Load the mesh
V_RETURN( g_Mesh.Create( pd3dDevice, L"data\\models\\logo\\logo.sdkmesh", true ) );
// Create font
V_RETURN( D3DX10CreateSprite(pd3dDevice, 0, &g_pFontSprite) );
V_RETURN( D3DX10CreateFont( pd3dDevice,
36,
0,
FW_BOLD,
1,
FALSE,
DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS,
DEFAULT_QUALITY,
DEFAULT_PITCH | FF_DONTCARE,
L"Arial",
&g_pFont ) );
// Initialize the world matrices
D3DXMatrixIdentity( &g_World );
// Initialize the view matrix
D3DXMatrixLookAtLH( &g_View, &g_Eye, &g_At, &g_Up );
g_pEyeVariable->SetFloatVector( (float*)&g_Eye );
g_pViewVariable->SetMatrix( (float*)&g_View );
// Initialize light
g_pLightPosVariable->SetFloatVector( (float*)&g_LightPos);
return S_OK;
}
//--------------------------------------------------------------------------------------
// Create any D3D10 resources that depend on the back buffer
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnResizedSwapChain( ID3D10Device* pd3dDevice, IDXGISwapChain* pSwapChain, const DXGI_SURFACE_DESC* pBufferSurfaceDesc, void* pUserContext )
{
float fAspect = static_cast<float>(pBufferSurfaceDesc->Width) / static_cast<float>(pBufferSurfaceDesc->Height);
D3DXMatrixPerspectiveFovLH( &g_Projection, D3DX_PI * 0.25f, fAspect, 0.5f, 100.0f );
return S_OK;
}
//--------------------------------------------------------------------------------------
// Render the scene using the D3D10 device
//--------------------------------------------------------------------------------------
void CALLBACK OnFrameRender( ID3D10Device* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext )
{
// Clear the back buffer
ID3D10RenderTargetView* pRTV = DXUTGetD3D10RenderTargetView();
pd3dDevice->ClearRenderTargetView( pRTV, g_ClearColor );
// Clear the depth stencil
ID3D10DepthStencilView* pDSV = DXUTGetD3D10DepthStencilView();
pd3dDevice->ClearDepthStencilView( pDSV, D3D10_CLEAR_DEPTH, 1.0, 0 );
// Update matrices
g_pWorldVariable->SetMatrix( (FLOAT*)&g_World );
g_pViewVariable->SetMatrix( (FLOAT*)&g_View );
g_pProjectionVariable->SetMatrix( (FLOAT*)&g_Projection );
// Render
BeginStereo();
{
g_Mesh.Render( pd3dDevice, g_pTechnique, 0, 0, 0, g_pDiffuseVariable, g_pSpecularVariable );
if (g_StereoAPI)
{
// just to illustrate that you can make subblocks
g_StereoAPI->BeginMonoBlock();
{
RECT rect;
rect.left = g_AppDeviceSettings.d3d10.sd.BufferDesc.Width / 2 - 125;
rect.right = rect.left + 250;
rect.top = 50;
rect.bottom = rect.top + 40;
g_pFontSprite->Begin(D3DX10_SPRITE_SAVE_STATE);
g_pFont->DrawText( g_pFontSprite, _T("Text is MONO"), -1, &rect, DT_CENTER, D3DCOLOR_RGBA(255,255,255,255) );
g_pFontSprite->Flush();
g_pFontSprite->End();
// Restore states broken by font
pd3dDevice->OMSetBlendState(NULL, NULL, 0xffffffff);
pd3dDevice->OMSetDepthStencilState(NULL, 0);
}
g_StereoAPI->EndMonoBlock();
}
}
EndStereo();
}
//--------------------------------------------------------------------------------------
// Release D3D10 resources created in OnResizedSwapChain
//--------------------------------------------------------------------------------------
void CALLBACK OnReleasingSwapChain( void* pUserContext )
{
}
//--------------------------------------------------------------------------------------
// Release D3D10 resources created in OnCreateDevice
//--------------------------------------------------------------------------------------
void CALLBACK OnDestroyDevice( void* pUserContext )
{
SAFE_RELEASE( g_pVertexLayout );
SAFE_RELEASE( g_pFont );
SAFE_RELEASE( g_pFontSprite );
SAFE_RELEASE( g_pEffect );
g_Mesh.Destroy();
}
} // namespace d3d10 | 36.149438 | 158 | 0.635688 | [
"mesh",
"render"
] |
07b26352964cf834146ce8eb675307bd2b01972c | 6,963 | hpp | C++ | engine/WeaponType.hpp | rigertd/LegacyMUD | cf351cca466158f0682f6c877b88d5c2eb59e240 | [
"BSD-3-Clause"
] | 1 | 2021-04-24T06:01:57.000Z | 2021-04-24T06:01:57.000Z | engine/WeaponType.hpp | rigertd/LegacyMUD | cf351cca466158f0682f6c877b88d5c2eb59e240 | [
"BSD-3-Clause"
] | null | null | null | engine/WeaponType.hpp | rigertd/LegacyMUD | cf351cca466158f0682f6c877b88d5c2eb59e240 | [
"BSD-3-Clause"
] | null | null | null | /*********************************************************************//**
* \author Rachel Weissman-Hohler
* \created 02/01/2017
* \modified 03/08/2017
* \course CS467, Winter 2017
* \file WeaponType.hpp
*
* \details Header file for WeaponType class. Defines the members and
* functions that apply to all weapon types. Weapon types
* define in-game weapon types that an item may use as its
* type. Weapon types allow the world builder to define a type
* once and then create many items of that type.
************************************************************************/
#ifndef WEAPON_TYPE_HPP
#define WEAPON_TYPE_HPP
#include <string>
#include <atomic>
#include <vector>
#include "ItemType.hpp"
#include "ItemRarity.hpp"
#include "EquipmentSlot.hpp"
#include "DamageType.hpp"
#include "AreaSize.hpp"
#include "DataType.hpp"
#include "ObjectType.hpp"
#include "EffectType.hpp"
namespace legacymud { namespace engine {
/*!
* \details This class defines in-game weapon types that an item may use
* as its type. Weapon types allow the world builder to define a
* type once and then create many items of that type.
*/
class WeaponType: public ItemType {
public:
WeaponType();
WeaponType(int damage, DamageType type, AreaSize range, int critMultiplier, int weight, ItemRarity rarity, std::string description, std::string name, int cost, EquipmentSlot slotType);
WeaponType(int damage, DamageType type, AreaSize range, int critMultiplier, int weight, ItemRarity rarity, std::string description, std::string name, int cost, EquipmentSlot slotType, int anID);
/*!
* \brief Gets the damage of this weapon type.
*
* \return Returns an int with the damage for this weapon type.
*/
virtual int getDamage() const;
/*!
* \brief Gets the damage type of this weapon type.
*
* \return Returns a DamageType with the damage type for this weapon type.
*/
virtual DamageType getDamageType() const;
/*!
* \brief Gets the range of this weapon type.
*
* \return Returns an AreaSize with the range for this weapon type.
*/
virtual AreaSize getRange() const;
/*!
* \brief Gets the crit multiplier of this weapon type.
*
* \return Returns an int with the crit multiplier for this weapon type.
*/
virtual int getCritMultiplier() const;
/*!
* \brief Sets the damage of this weapon type.
*
* \param[in] damage Specifies the damage.
*
* \return Returns a bool indicating whether or not setting the damage was
* sucessful.
*/
virtual bool setDamage(int damage);
/*!
* \brief Sets the damage type of this weapon type.
*
* \param[in] type Specifies the damage type.
*
* \return Returns a bool indicating whether or not setting the damage type was
* sucessful.
*/
virtual bool setDamageType(DamageType type);
/*!
* \brief Sets the range of this weapon type.
*
* \param[in] range Specifies the range.
*
* \return Returns a bool indicating whether or not setting the range was
* sucessful.
*/
virtual bool setRange(AreaSize range);
/*!
* \brief Sets the crit multiplier of this weapon type.
*
* \param[in] multiplier Specifies the crit multiplier.
*
* \return Returns a bool indicating whether or not setting the crit multiplier
* was sucessful.
*/
virtual bool setCritMultiplier(int multiplier);
/*!
* \brief Gets the object type.
*
* \return Returns an ObjectType indicating the actual class the object
* belongs to.
*/
virtual ObjectType getObjectType() const;
/*!
* \brief Serializes this object for writing to file.
*
* \return Returns a std::string with the serialized data.
*/
virtual std::string serialize();
/*!
* \brief Deserializes and creates an object of this type from the
* specified string of serialized data.
*
* \param[in] string Holds the data to be deserialized.
*
* \return Returns an InteractiveNoun* with the newly created object.
*/
static WeaponType* deserialize(std::string);
/*!
* \brief Creates a copy of this object.
*
* This function creates a new object with the same attributes as this
* object and returns a pointer to the new object.
*
* \return Returns a pointer to the newly created object or nullptr if
* the copy was unsuccessful.
*/
virtual InteractiveNoun* copy();
/*!
* \brief Edits an attribute of this object.
*
* This function edits the specified attribute of this object. It asks
* the user for the new value and then sets it to that.
*
* \param[in] aPlayer Specifies the player that is doing the editing.
* \param[in] attribute Specifies the attribute to edit.
*
* \return Returns bool indicating whether or not editing the attribute
* was successful.
*/
//virtual bool editAttribute(Player *aPlayer, std::string attribute);
/*!
* \brief Edits this object.
*
* This function edits this object. It interacts with the user to determine
* which attributes to update and what the new values should be and then
* makes those changes.
*
* \param[in] aPlayer Specifies the player that is doing the editing.
*
* \return Returns bool indicating whether or not editing this object
* was successful.
*/
virtual bool editWizard(Player *aPlayer);
/*!
* \brief Gets the attribute signature of the class.
*
* This function returns a map of string to DataType with the
* attributes required by the Action class to instantiate a new
* action.
*
* \return Returns a map of std::string to DataType indicating
* the required attributes.
*/
static std::map<std::string, DataType> getAttributeSignature();
private:
std::atomic<int> damage;
std::atomic<DamageType> damageType;
std::atomic<AreaSize> range;
std::atomic<int> critMultiplier;
};
}}
#endif | 35.707692 | 202 | 0.57188 | [
"object",
"vector"
] |
07bd167b891894ba77b4458625238bf9cbf56f8e | 1,044 | cpp | C++ | Kattis/zipline.cpp | YourName0729/competitive-programming | 437ef18a46074f520e0bfa0bdd718bb6b1c92800 | [
"MIT"
] | 3 | 2021-02-19T17:01:11.000Z | 2021-03-11T16:50:19.000Z | Kattis/zipline.cpp | YourName0729/competitive-programming | 437ef18a46074f520e0bfa0bdd718bb6b1c92800 | [
"MIT"
] | null | null | null | Kattis/zipline.cpp | YourName0729/competitive-programming | 437ef18a46074f520e0bfa0bdd718bb6b1c92800 | [
"MIT"
] | null | null | null | // geometry
// https://open.kattis.com/problems/zipline
#include <vector>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <stack>
#include <cmath>
#include <map>
#include <utility>
#include <queue>
#include <iomanip>
#include <deque>
#define Forcase int __t;cin>>__t;getchar();for(int ___t=1;___t<=__t;___t++)
#define For(i, n) for(int i=0;i<n;i++)
#define Fore(e, arr) for(auto e:arr)
#define INF 1e9
using ull = unsigned long long;
using ll = long long;
using namespace std;
double w, g, h, r;
double ans() {
if (g == r || h == r) {
return sqrt(w * w + (g - h) * (g - h));
}
double perc = (g - r) / (h - r);
double x1 = perc / (perc + 1) * w;
double x2 = (1 / perc) / ((1 / perc) + 1) * w;
return sqrt(x1 * x1 + (g - r) * (g - r)) + sqrt(x2 * x2 + (h - r) * (h - r));
}
int main() {
Forcase {
cin >> w >> g >> h >> r;
cout << fixed << sqrt(w * w + (g - h) * (g - h)) << ' ';
cout << fixed << ans() << '\n';
}
return 0;
} | 20.88 | 81 | 0.52682 | [
"geometry",
"vector"
] |
07c2d14505389efb31708886fdcb6d6acfc51bbd | 6,110 | cpp | C++ | main.cpp | LC-John/SIMD_YUV_Convertion | c26c34cbbf684ac00970bc829454e1360099e66e | [
"MIT"
] | 2 | 2020-04-07T12:50:02.000Z | 2020-06-01T15:51:52.000Z | main.cpp | LC-John/SIMD_YUV_Convertion | c26c34cbbf684ac00970bc829454e1360099e66e | [
"MIT"
] | null | null | null | main.cpp | LC-John/SIMD_YUV_Convertion | c26c34cbbf684ac00970bc829454e1360099e66e | [
"MIT"
] | null | null | null | #include "convert.h"
#include <cstdio>
#include <time.h>
#include <cstring>
using namespace std;
void reset_progressbar(char* buf, int* ptr)
{
*ptr = 1;
buf[0] = '[';
buf[20 + 2] = ']';
memset(buf+1, '-', 21);
buf[20 + 3] = '\0';
}
int main(int argc, char *argv[])
{
double m_time_yuv2rgb = 0, m_time_merge = 0, m_time_rgb2yuv = 0;
double t1_time_yuv2argb = 0, t1_time_argb2rgb = 0, t1_time_rgb2yuv = 0;
double t2_time_yuv2argb = 0, t2_time_argb2rgb = 0, t2_time_rgb2yuv = 0;
char progress_buf[100];
int curr_progress = 1;
clock_t start, end;
SIMD_MODE mode = SIMD_NO;
if (argc < 6)
return -1;
if (argc >= 7)
{
if (strncmp(argv[6], "-no", 3) == 0)
mode = SIMD_NO;
else if (strncmp(argv[6], "-mmx", 4) == 0)
mode = SIMD_MMX;
else if (strncmp(argv[6], "-sse", 4) == 0)
mode = SIMD_SSE;
else if (strncmp(argv[6], "-avx", 4) == 0)
mode = SIMD_AVX;
else
return -2;
}
printf("\nMerging <%s> and <%s>\n", argv[1], argv[2]);
if (load_yuv420_2(argv[1], argv[2]) < 0)
{
printf("Cannot load figures from <%s> or <%s>, abort!\n", argv[1], argv[2]);
return -2;
}
//printf(" Figures <%s> and <%s> loaded!\n", argv[1], argv[2]);
reset_progressbar(progress_buf, &curr_progress);
for (int i = 0; i < n_frame; i++)
{
if (i % (n_frame / 20) == 0)
progress_buf[curr_progress++] = '>';
printf (" %s [%d%%] frame = %d\r",
progress_buf, (int)((float)(i+1)/(float)n_frame*100), i+1);
fflush(stdout);
start = clock();
yuv420_2_rgb888_2(mode);
end = clock();
m_time_yuv2rgb += (double)(end - start) / CLOCKS_PER_SEC;
start = clock();
merge_rgb888(3 + 3 * i, mode);
end = clock();
m_time_merge += (double)(end - start) / CLOCKS_PER_SEC;
start = clock();
rgb888_2_yuv420(i, mode);
end = clock();
m_time_rgb2yuv += (double)(end - start) / CLOCKS_PER_SEC;
}
printf("\n");
if (store_yuv420_vedio(argv[5]) < 0)
{
printf("Cannot save vedio to <%s>, abort!\n", argv[5]);
return -3;
}
//printf(" Merged vedio <%s> saved!\n", argv[5]);
//printf("Merge <%s> and <%s> done!\n", argv[1], argv[2]);
printf("\nTransforming <%s>\n", argv[1]);
if (load_yuv420(argv[1]) < 0)
{
printf("Caanot load figure from <%s>, abort!\n", argv[1]);
return -1;
}
//printf(" Figure <%s> loaded!\n", argv[1]);
reset_progressbar(progress_buf, &curr_progress);
for (int i = 0; i < n_frame; i++)
{
if (i % (n_frame / 20) == 0)
progress_buf[curr_progress++] = '>';
printf (" %s [%d%%] frame = %d\r",
progress_buf, (int)((float)(i+1)/(float)n_frame*100), i+1);
fflush(stdout);
start = clock();
yuv420_2_argb8888(3 + 3 * i, mode);
end = clock();
t1_time_yuv2argb += (double)(end - start) / CLOCKS_PER_SEC;
start = clock();
argb8888_2_rgb888(mode);
end = clock();
t1_time_argb2rgb += (double)(end - start) / CLOCKS_PER_SEC;
start = clock();
rgb888_2_yuv420(i, mode);
end = clock();
t1_time_rgb2yuv += (double)(end - start) / CLOCKS_PER_SEC;
}
printf("\n");
if (store_yuv420_vedio(argv[3]) < 0)
{
printf("Caanot save vedio to <%s>, abort!\n", argv[3]);
return -2;
}
//printf(" Transformed vedio <%s> saved!\n", argv[3]);
//printf("Transforming <%s> done!\n", argv[1]);
printf("\nTransforming <%s>\n", argv[2]);
if (load_yuv420(argv[2]) < 0)
{
printf("Cannot load figure from <%s>, abort!\n", argv[2]);
return -1;
}
//printf(" Figure <%s> loaded!\n", argv[2]);
reset_progressbar(progress_buf, &curr_progress);
for (int i = 0; i < n_frame; i++)
{
if (i % (n_frame / 20) == 0)
progress_buf[curr_progress++] = '>';
printf (" %s [%d%%] frame = %d\r",
progress_buf, (int)((float)(i+1)/(float)n_frame*100), i+1);
fflush(stdout);
start = clock();
yuv420_2_argb8888(3 + 3 * i, mode);
end = clock();
t2_time_yuv2argb += (double)(end - start) / CLOCKS_PER_SEC;
start = clock();
argb8888_2_rgb888(mode);
end = clock();
t2_time_argb2rgb += (double)(end - start) / CLOCKS_PER_SEC;
start = clock();
rgb888_2_yuv420(i, mode);
end = clock();
t2_time_rgb2yuv += (double)(end - start) / CLOCKS_PER_SEC;
}
printf("\n");
if (store_yuv420_vedio(argv[4]) < 0)
{
printf ("Cannot save figure to <%s>, abort!\n", argv[4]);
return -2;
}
//printf(" Transformed vedio <%s]> saved!\n", argv[4]);
//printf("Transforming <%s> done!\n", argv[2]);
printf("\n\nRESULT:\n");
printf("Merge <%s> and <%s>:\n", argv[1], argv[2]);
printf(" Total YUV420 to RGB888 time cost = %f\n", m_time_yuv2rgb);
printf(" Total RGB888 merging time cost = %f\n", m_time_merge);
printf(" Total RGB888 to YUV420 time cost = %f\n", m_time_rgb2yuv);
printf(" Total time cost = %f\n", m_time_yuv2rgb+m_time_rgb2yuv+m_time_merge);
printf("Transform <%s>:\n", argv[1]);
printf(" Total YUV420 to ARGB8888 time cost = %f\n", t1_time_yuv2argb);
printf(" Total ARGB8888 to RGB888 time cost = %f\n", t1_time_argb2rgb);
printf(" Total RGB888 to YUV420 time cost = %f\n", t1_time_rgb2yuv);
printf(" Total time cost = %f\n", t1_time_argb2rgb+t1_time_rgb2yuv+t1_time_yuv2argb);
printf("Transform <%s>:\n", argv[2]);
printf(" Total YUV420 to ARGB8888 time cost = %f\n", t2_time_yuv2argb);
printf(" Total ARGB8888 to RGB888 time cost = %f\n", t2_time_argb2rgb);
printf(" Total RGB888 to YUV420 time cost = %f\n", t2_time_rgb2yuv);
printf(" Total time cost = %f\n", t2_time_argb2rgb+t2_time_rgb2yuv+t2_time_yuv2argb);
printf("\n\n");
return 0;
}
| 33.387978 | 90 | 0.544354 | [
"transform"
] |
07c4912a032bf0bc6cbc1e05957da352fa06c9c6 | 22,827 | cpp | C++ | Library/QHull/rbox.cpp | GuoxinFang/ReinforcedFDM | bde4d1890de805ce3e626a010866303a2b132b63 | [
"BSD-3-Clause"
] | 43 | 2020-08-31T08:56:48.000Z | 2022-03-29T08:20:28.000Z | ThirdPartyDependence/QHullLib/rbox.cpp | zhangjiangzhao123/MultiAxis_3DP_MotionPlanning-1 | 7338bd7a1cdf9173d8715032fed29b6a0b2b21a1 | [
"BSD-3-Clause"
] | null | null | null | ThirdPartyDependence/QHullLib/rbox.cpp | zhangjiangzhao123/MultiAxis_3DP_MotionPlanning-1 | 7338bd7a1cdf9173d8715032fed29b6a0b2b21a1 | [
"BSD-3-Clause"
] | 10 | 2020-08-31T09:52:57.000Z | 2021-11-20T15:47:12.000Z | /*<html><pre> -<a href="index.htm#TOC"
>-------------------------------</a><a name="TOP">-</a>
rbox.c
Generate input points for qhull.
notes:
50 points generated for 'rbox D4'
This code needs a full rewrite. It needs separate procedures for each
distribution with common, helper procedures.
WARNING:
incorrect range if qh_RANDOMmax is defined wrong (user.h)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <limits.h>
#include <time.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#include "user.h"
#if __MWERKS__ && __POWERPC__
#include <SIOUX.h>
#include <Files.h>
#include <console.h>
#include <Desk.h>
#endif
#ifdef _MSC_VER /* Microsoft Visual C++ */
#pragma warning( disable : 4244) /* conversion from double to int */
#endif
#define MINVALUE 0.8
#define MAXdim 200
#define PI 3.1415926535897932384
#define DEFAULTzbox 1e6
char prompt[]= "\n\
-rbox- generate various point distributions. Default is random in cube.\n\
\n\
args (any order, space separated): Version: 2001/06/24\n\
3000 number of random points in cube, lens, spiral, sphere or grid\n\
D3 dimension 3-d\n\
c add a unit cube to the output ('c G2.0' sets size)\n\
d add a unit diamond to the output ('d G2.0' sets size)\n\
l generate a regular 3-d spiral\n\
r generate a regular polygon, ('r s Z1 G0.1' makes a cone)\n\
s generate cospherical points\n\
x generate random points in simplex, may use 'r' or 'Wn'\n\
y same as 'x', plus simplex\n\
Pn,m,r add point [n,m,r] first, pads with 0\n\
\n\
Ln lens distribution of radius n. Also 's', 'r', 'G', 'W'.\n\
Mn,m,r lattice (Mesh) rotated by [n,-m,0], [m,n,0], [0,0,r], ...\n\
'27 M1,0,1' is {0,1,2} x {0,1,2} x {0,1,2}. Try 'M3,4 z'.\n\
W0.1 random distribution within 0.1 of the cube's or sphere's surface\n\
Z0.5 s random points in a 0.5 disk projected to a sphere\n\
Z0.5 s G0.6 same as Z0.5 within a 0.6 gap\n\
\n\
Bn bounding box coordinates, default %2.2g\n\
h output as homogeneous coordinates for cdd\n\
n remove command line from the first line of output\n\
On offset coordinates by n\n\
t use time as the random number seed (default is command line)\n\
tn use n as the random number seed\n\
z print integer coordinates, default 'Bn' is %2.2g\n\
";
/* ------------------------------ prototypes ----------------*/
int roundi( double a);
void out1( double a);
void out2n( double a, double b);
void out3n( double a, double b, double c);
int qh_rand( void);
void qh_srand( int seed);
/* ------------------------------ globals -------------------*/
FILE *fp;
int isinteger= 0;
double out_offset= 0.0;
/*--------------------------------------------
-rbox- main procedure of rbox application
*/
//int main(int argc, char **argv) {
// int i,j,k;
// int gendim;
// int cubesize, diamondsize, seed=0, count, apex;
// int dim=3 , numpoints= 0, totpoints, addpoints=0;
// int issphere=0, isaxis=0, iscdd= 0, islens= 0, isregular=0, iswidth=0, addcube=0;
// int isgap=0, isspiral=0, NOcommand= 0, adddiamond=0, istime=0;
// int isbox=0, issimplex=0, issimplex2=0, ismesh=0;
// double width=0.0, gap=0.0, radius= 0.0;
// double coord[MAXdim], offset, meshm=3.0, meshn=4.0, meshr=5.0;
// double *simplex, *simplexp;
// int nthroot, mult[MAXdim];
// double norm, factor, randr, rangap, lensangle= 0, lensbase= 1;
// double anglediff, angle, x, y, cube= 0.0, diamond= 0.0;
// double box= qh_DEFAULTbox; /* scale all numbers before output */
// double randmax= qh_RANDOMmax;
// char command[200], *s, seedbuf[200];
// time_t timedata;
//
//#if __MWERKS__ && __POWERPC__
// char inBuf[BUFSIZ], outBuf[BUFSIZ], errBuf[BUFSIZ];
// SIOUXSettings.showstatusline= False;
// SIOUXSettings.tabspaces= 1;
// SIOUXSettings.rows= 40;
// if (setvbuf (stdin, inBuf, _IOFBF, sizeof(inBuf)) < 0 /* w/o, SIOUX I/O is slow*/
// || setvbuf (stdout, outBuf, _IOFBF, sizeof(outBuf)) < 0
// || (stdout != stderr && setvbuf (stderr, errBuf, _IOFBF, sizeof(errBuf)) < 0))
// fprintf ( stderr, "qhull internal warning (main): could not change stdio to fully buffered.\n");
// argc= ccommand(&argv);
//#endif
// if (argc == 1) {
// printf (prompt, box, DEFAULTzbox);
// exit(1);
// }
// if ((s = strrchr( argv[0], '\\'))) /* Borland gives full path */
// strcpy (command, s+1);
// else
// strcpy (command, argv[0]);
// if ((s= strstr (command, ".EXE"))
// || (s= strstr (command, ".exe")))
// *s= '\0';
// /* ============= read flags =============== */
// for (i=1; i < argc; i++) {
// if (strlen (command) + strlen(argv[i]) + 1 < sizeof(command) ) {
// strcat (command, " ");
// strcat (command, argv[i]);
// }
// if (isdigit (argv[i][0])) {
// numpoints= atoi (argv[i]);
// continue;
// }
// if (argv[i][0] == '-')
// (argv[i])++;
// switch (argv[i][0]) {
// case 'c':
// addcube= 1;
// if (i+1 < argc && argv[i+1][0] == 'G')
// cube= (double) atof (&argv[++i][1]);
// break;
// case 'd':
// adddiamond= 1;
// if (i+1 < argc && argv[i+1][0] == 'G')
// diamond= (double) atof (&argv[++i][1]);
// break;
// case 'h':
// iscdd= 1;
// break;
// case 'l':
// isspiral= 1;
// break;
// case 'n':
// NOcommand= 1;
// break;
// case 'r':
// isregular= 1;
// break;
// case 's':
// issphere= 1;
// break;
// case 't':
// istime= 1;
// if (isdigit (argv[i][1]))
// seed= atoi (&argv[i][1]);
// else {
// seed= time (&timedata);
// sprintf (seedbuf, "%d", seed);
// strcat (command, seedbuf);
// }
// break;
// case 'x':
// issimplex= 1;
// break;
// case 'y':
// issimplex2= 1;
// break;
// case 'z':
// isinteger= 1;
// break;
// case 'B':
// box= (double) atof (&argv[i][1]);
// isbox= 1;
// break;
// case 'D':
// dim= atoi (&argv[i][1]);
// if (dim < 1
// || dim > MAXdim) {
// fprintf (stderr, "rbox error: dim %d too large or too small\n", dim);
// exit (1);
// }
// break;
// case 'G':
// if (argv[i][1])
// gap= (double) atof (&argv[i][1]);
// else
// gap= 0.5;
// isgap= 1;
// break;
// case 'L':
// if (argv[i][1])
// radius= (double) atof (&argv[i][1]);
// else
// radius= 10;
// islens= 1;
// break;
// case 'M':
// ismesh= 1;
// s= argv[i]+1;
// if (*s)
// meshn= strtod (s, &s);
// if (*s == ',')
// meshm= strtod (++s, &s);
// else
// meshm= 0.0;
// if (*s == ',')
// meshr= strtod (++s, &s);
// else
// meshr= sqrt (meshn*meshn + meshm*meshm);
// if (*s) {
// fprintf (stderr, "rbox warning: assuming 'M3,4,5' since mesh args are not integers or reals\n");
// meshn= 3.0, meshm=4.0, meshr=5.0;
// }
// break;
// case 'O':
// out_offset= (double) atof (&argv[i][1]);
// break;
// case 'P':
// addpoints++;
// break;
// case 'W':
// width= (double) atof (&argv[i][1]);
// iswidth= 1;
// break;
// case 'Z':
// if (argv[i][1])
// radius= (double) atof (&argv[i][1]);
// else
// radius= 1.0;
// isaxis= 1;
// break;
// default:
// fprintf (stderr, "rbox warning: unknown flag %s.\nExecute 'rbox' without arguments for documentation.\n", argv[i]);
// }
// }
// /* ============= defaults, constants, and sizes =============== */
// if (isinteger && !isbox)
// box= DEFAULTzbox;
// if (addcube) {
// cubesize= floor(ldexp(1.0,dim)+0.5);
// if (cube == 0.0)
// cube= box;
// }else
// cubesize= 0;
// if (adddiamond) {
// diamondsize= 2*dim;
// if (diamond == 0.0)
// diamond= box;
// }else
// diamondsize= 0;
// if (islens) {
// if (isaxis) {
// fprintf (stderr, "rbox error: can not combine 'Ln' with 'Zn'\n");
// exit(1);
// }
// if (radius <= 1.0) {
// fprintf (stderr, "rbox error: lens radius %.2g should be greater than 1.0\n",
// radius);
// exit(1);
// }
// lensangle= asin (1.0/radius);
// lensbase= radius * cos (lensangle);
// }
// if (!numpoints) {
// if (issimplex2)
// ; /* ok */
// else if (isregular + issimplex + islens + issphere + isaxis + isspiral + iswidth + ismesh) {
// fprintf (stderr, "rbox error: missing count\n");
// exit(1);
// }else if (adddiamond + addcube + addpoints)
// ; /* ok */
// else {
// numpoints= 50; /* ./rbox D4 is the test case */
// issphere= 1;
// }
// }
// if ((issimplex + islens + isspiral + ismesh > 1)
// || (issimplex + issphere + isspiral + ismesh > 1)) {
// fprintf (stderr, "rbox error: can only specify one of 'l', 's', 'x', 'Ln', or 'Mn,m,r' ('Ln s' is ok).\n");
// exit(1);
// }
// fp= stdout;
// /* ============= print header with total points =============== */
// if (issimplex || ismesh)
// totpoints= numpoints;
// else if (issimplex2)
// totpoints= numpoints+dim+1;
// else if (isregular) {
// totpoints= numpoints;
// if (dim == 2) {
// if (islens)
// totpoints += numpoints - 2;
// }else if (dim == 3) {
// if (islens)
// totpoints += 2 * numpoints;
// else if (isgap)
// totpoints += 1 + numpoints;
// else
// totpoints += 2;
// }
// }else
// totpoints= numpoints + isaxis;
// totpoints += cubesize + diamondsize + addpoints;
// if (iscdd)
// fprintf(fp, "%s\nbegin\n %d %d %s\n",
// NOcommand ? "" : command,
// totpoints, dim+1,
// isinteger ? "integer" : "real");
// else if (NOcommand)
// fprintf(fp, "%d\n%d\n", dim, totpoints);
// else
// fprintf(fp, "%d %s\n%d\n", dim, command, totpoints);
// /* ============= seed randoms =============== */
// if (istime == 0) {
// for (s=command; *s; s++) {
// if (issimplex2 && *s == 'y') /* make 'y' same seed as 'x' */
// i= 'x';
// else
// i= *s;
// seed= 11*seed + i;
// }
// } /* else, seed explicitly set to n or to time */
// qh_RANDOMseed_(seed);
// /* ============= explicit points =============== */
// for (i=1; i < argc; i++) {
// if (argv[i][0] == 'P') {
// s= argv[i]+1;
// count= 0;
// if (iscdd)
// out1( 1.0);
// while (*s) {
// out1( strtod (s, &s));
// count++;
// if (*s) {
// if (*s++ != ',') {
// fprintf (stderr, "rbox error: missing comma after coordinate in %s\n\n", argv[i]);
// exit (1);
// }
// }
// }
// if (count < dim) {
// for (k= dim-count; k--; )
// out1( 0.0);
// }else if (count > dim) {
// fprintf (stderr, "rbox error: %d coordinates instead of %d coordinates in %s\n\n",
// count, dim, argv[i]);
// exit (1);
// }
// fprintf (fp, "\n");
// }
// }
// /* ============= simplex distribution =============== */
// if (issimplex+issimplex2) {
// if (!(simplex= (double *)malloc( dim * (dim+1) * sizeof(double)))) {
// fprintf (stderr, "insufficient memory for simplex\n");
// exit(0);
// }
// simplexp= simplex;
// if (isregular) {
// for (i= 0; i<dim; i++) {
// for (k= 0; k<dim; k++)
// *(simplexp++)= i==k ? 1.0 : 0.0;
// }
// for (k= 0; k<dim; k++)
// *(simplexp++)= -1.0;
// }else {
// for (i= 0; i<dim+1; i++) {
// for (k= 0; k<dim; k++) {
// randr= qh_RANDOMint;
// *(simplexp++)= 2.0 * randr/randmax - 1.0;
// }
// }
// }
// if (issimplex2) {
// simplexp= simplex;
// for (i= 0; i<dim+1; i++) {
// if (iscdd)
// out1( 1.0);
// for (k= 0; k<dim; k++)
// out1( *(simplexp++) * box);
// fprintf (fp, "\n");
// }
// }
// for (j= 0; j<numpoints; j++) {
// if (iswidth)
// apex= qh_RANDOMint % (dim+1);
// else
// apex= -1;
// for (k= 0; k<dim; k++)
// coord[k]= 0.0;
// norm= 0.0;
// for (i= 0; i<dim+1; i++) {
// randr= qh_RANDOMint;
// factor= randr/randmax;
// if (i == apex)
// factor *= width;
// norm += factor;
// for (k= 0; k<dim; k++) {
// simplexp= simplex + i*dim + k;
// coord[k] += factor * (*simplexp);
// }
// }
// for (k= 0; k<dim; k++)
// coord[k] /= norm;
// if (iscdd)
// out1( 1.0);
// for (k=0; k < dim; k++)
// out1( coord[k] * box);
// fprintf (fp, "\n");
// }
// isregular= 0; /* continue with isbox */
// numpoints= 0;
// }
// /* ============= mesh distribution =============== */
// if (ismesh) {
// nthroot= pow (numpoints, 1.0/dim) + 0.99999;
// for (k= dim; k--; )
// mult[k]= 0;
// for (i= 0; i < numpoints; i++) {
// for (k= 0; k < dim; k++) {
// if (k == 0)
// out1( mult[0] * meshn + mult[1] * (-meshm));
// else if (k == 1)
// out1( mult[0] * meshm + mult[1] * meshn);
// else
// out1( mult[k] * meshr );
// }
// fprintf (fp, "\n");
// for (k= 0; k < dim; k++) {
// if (++mult[k] < nthroot)
// break;
// mult[k]= 0;
// }
// }
// }
//
// /* ============= regular points for 's' =============== */
// else if (isregular && !islens) {
// if (dim != 2 && dim != 3) {
// fprintf(stderr, "rbox error: regular points can be used only in 2-d and 3-d\n\n");
// exit(1);
// }
// if (!isaxis || radius == 0.0) {
// isaxis= 1;
// radius= 1.0;
// }
// if (dim == 3) {
// if (iscdd)
// out1( 1.0);
// out3n( 0.0, 0.0, -box);
// if (!isgap) {
// if (iscdd)
// out1( 1.0);
// out3n( 0.0, 0.0, box);
// }
// }
// angle= 0.0;
// anglediff= 2.0 * PI/numpoints;
// for (i=0; i < numpoints; i++) {
// angle += anglediff;
// x= radius * cos (angle);
// y= radius * sin (angle);
// if (dim == 2) {
// if (iscdd)
// out1( 1.0);
// out2n( x*box, y*box);
// }else {
// norm= sqrt (1.0 + x*x + y*y);
// if (iscdd)
// out1( 1.0);
// out3n( box*x/norm, box*y/norm, box/norm);
// if (isgap) {
// x *= 1-gap;
// y *= 1-gap;
// norm= sqrt (1.0 + x*x + y*y);
// if (iscdd)
// out1( 1.0);
// out3n( box*x/norm, box*y/norm, box/norm);
// }
// }
// }
// }
// /* ============= regular points for 'r Ln D2' =============== */
// else if (isregular && islens && dim == 2) {
// double cos_0;
//
// angle= lensangle;
// anglediff= 2 * lensangle/(numpoints - 1);
// cos_0= cos (lensangle);
// for (i=0; i < numpoints; i++, angle -= anglediff) {
// x= radius * sin (angle);
// y= radius * (cos (angle) - cos_0);
// if (iscdd)
// out1( 1.0);
// out2n( x*box, y*box);
// if (i != 0 && i != numpoints - 1) {
// if (iscdd)
// out1( 1.0);
// out2n( x*box, -y*box);
// }
// }
// }
// /* ============= regular points for 'r Ln D3' =============== */
// else if (isregular && islens && dim != 2) {
// if (dim != 3) {
// fprintf(stderr, "rbox error: regular points can be used only in 2-d and 3-d\n\n");
// exit(1);
// }
// angle= 0.0;
// anglediff= 2* PI/numpoints;
// if (!isgap) {
// isgap= 1;
// gap= 0.5;
// }
// offset= sqrt (radius * radius - (1-gap)*(1-gap)) - lensbase;
// for (i=0; i < numpoints; i++, angle += anglediff) {
// x= cos (angle);
// y= sin (angle);
// if (iscdd)
// out1( 1.0);
// out3n( box*x, box*y, 0);
// x *= 1-gap;
// y *= 1-gap;
// if (iscdd)
// out1( 1.0);
// out3n( box*x, box*y, box * offset);
// if (iscdd)
// out1( 1.0);
// out3n( box*x, box*y, -box * offset);
// }
// }
// /* ============= apex of 'Zn' distribution + gendim =============== */
// else {
// if (isaxis) {
// gendim= dim-1;
// if (iscdd)
// out1( 1.0);
// for (j=0; j < gendim; j++)
// out1( 0.0);
// out1( -box);
// fprintf (fp, "\n");
// }else if (islens)
// gendim= dim-1;
// else
// gendim= dim;
// /* ============= generate random point in unit cube =============== */
// for (i=0; i < numpoints; i++) {
// norm= 0.0;
// for (j=0; j < gendim; j++) {
// randr= qh_RANDOMint;
// coord[j]= 2.0 * randr/randmax - 1.0;
// norm += coord[j] * coord[j];
// }
// norm= sqrt (norm);
// /* ============= dim-1 point of 'Zn' distribution ========== */
// if (isaxis) {
// if (!isgap) {
// isgap= 1;
// gap= 1.0;
// }
// randr= qh_RANDOMint;
// rangap= 1.0 - gap * randr/randmax;
// factor= radius * rangap / norm;
// for (j=0; j<gendim; j++)
// coord[j]= factor * coord[j];
// /* ============= dim-1 point of 'Ln s' distribution =========== */
// }else if (islens && issphere) {
// if (!isgap) {
// isgap= 1;
// gap= 1.0;
// }
// randr= qh_RANDOMint;
// rangap= 1.0 - gap * randr/randmax;
// factor= rangap / norm;
// for (j=0; j<gendim; j++)
// coord[j]= factor * coord[j];
// /* ============= dim-1 point of 'Ln' distribution ========== */
// }else if (islens && !issphere) {
// if (!isgap) {
// isgap= 1;
// gap= 1.0;
// }
// j= qh_RANDOMint % gendim;
// if (coord[j] < 0)
// coord[j]= -1.0 - coord[j] * gap;
// else
// coord[j]= 1.0 - coord[j] * gap;
// /* ============= point of 'l' distribution =============== */
// }else if (isspiral) {
// if (dim != 3) {
// fprintf(stderr, "rbox error: spiral distribution is available only in 3d\n\n");
// exit(1);
// }
// coord[0]= cos(2*PI*i/(numpoints - 1));
// coord[1]= sin(2*PI*i/(numpoints - 1));
// coord[2]= 2.0*(double)i/(double)(numpoints-1) - 1.0;
// /* ============= point of 's' distribution =============== */
// }else if (issphere) {
// factor= 1.0/norm;
// if (iswidth) {
// randr= qh_RANDOMint;
// factor *= 1.0 - width * randr/randmax;
// }
// for (j=0; j<dim; j++)
// coord[j]= factor * coord[j];
// }
// /* ============= project 'Zn s' point in to sphere =============== */
// if (isaxis && issphere) {
// coord[dim-1]= 1.0;
// norm= 1.0;
// for (j=0; j<gendim; j++)
// norm += coord[j] * coord[j];
// norm= sqrt (norm);
// for (j=0; j<dim; j++)
// coord[j]= coord[j] / norm;
// if (iswidth) {
// randr= qh_RANDOMint;
// coord[dim-1] *= 1 - width * randr/randmax;
// }
// /* ============= project 'Zn' point onto cube =============== */
// }else if (isaxis && !issphere) { /* not very interesting */
// randr= qh_RANDOMint;
// coord[dim-1]= 2.0 * randr/randmax - 1.0;
// /* ============= project 'Ln' point out to sphere =============== */
// }else if (islens) {
// coord[dim-1]= lensbase;
// for (j=0, norm= 0; j<dim; j++)
// norm += coord[j] * coord[j];
// norm= sqrt (norm);
// for (j=0; j<dim; j++)
// coord[j]= coord[j] * radius/ norm;
// coord[dim-1] -= lensbase;
// if (iswidth) {
// randr= qh_RANDOMint;
// coord[dim-1] *= 1 - width * randr/randmax;
// }
// if (qh_RANDOMint > randmax/2)
// coord[dim-1]= -coord[dim-1];
// /* ============= project 'Wn' point toward boundary =============== */
// }else if (iswidth && !issphere) {
// j= qh_RANDOMint % gendim;
// if (coord[j] < 0)
// coord[j]= -1.0 - coord[j] * width;
// else
// coord[j]= 1.0 - coord[j] * width;
// }
// /* ============= write point =============== */
// if (iscdd)
// out1( 1.0);
// for (k=0; k < dim; k++)
// out1( coord[k] * box);
// fprintf (fp, "\n");
// }
// }
// /* ============= write cube vertices =============== */
// if (addcube) {
// for (j=0; j<cubesize; j++) {
// if (iscdd)
// out1( 1.0);
// for (k=dim-1; k>=0; k--) {
// if (j & ( 1 << k))
// out1( cube);
// else
// out1( -cube);
// }
// fprintf (fp, "\n");
// }
// }
// /* ============= write diamond vertices =============== */
// if (adddiamond) {
// for (j=0; j<diamondsize; j++) {
// if (iscdd)
// out1( 1.0);
// for (k=dim-1; k>=0; k--) {
// if (j/2 != k)
// out1( 0.0);
// else if (j & 0x1)
// out1( diamond);
// else
// out1( -diamond);
// }
// fprintf (fp, "\n");
// }
// }
// if (iscdd)
// fprintf (fp, "end\nhull\n");
// return 0;
// } /* rbox */
/*------------------------------------------------
-outxxx - output functions
*/
int roundi( double a) {
if (a < 0.0) {
if (a - 0.5 < INT_MIN) {
fprintf(stderr, "rbox input error: coordinate %2.2g is too large. Reduce 'Bn'\n", a);
exit (1);
}
return a - 0.5;
}else {
if (a + 0.5 > INT_MAX) {
fprintf(stderr, "rbox input error: coordinate %2.2g is too large. Reduce 'Bn'\n", a);
exit (1);
}
return a + 0.5;
}
} /* roundi */
void out1(double a) {
if (isinteger)
fprintf(fp, "%d ", roundi( a+out_offset));
else
fprintf(fp, qh_REAL_1, a+out_offset);
} /* out1 */
void out2n( double a, double b) {
if (isinteger)
fprintf(fp, "%d %d\n", roundi(a+out_offset), roundi(b+out_offset));
else
fprintf(fp, qh_REAL_2n, a+out_offset, b+out_offset);
} /* out2n */
void out3n( double a, double b, double c) {
if (isinteger)
fprintf(fp, "%d %d %d\n", roundi(a+out_offset), roundi(b+out_offset), roundi(c+out_offset));
else
fprintf(fp, qh_REAL_3n, a+out_offset, b+out_offset, c+out_offset);
} /* out3n */
/*-------------------------------------------------
-rand & srand- generate pseudo-random number between 1 and 2^31 -2
from Park & Miller's minimimal standard random number generator
Communications of the ACM, 31:1192-1201, 1988.
notes:
does not use 0 or 2^31 -1
this is silently enforced by qh_srand()
copied from geom2.c
*/
static int seed = 1; /* global static */
int qh_rand( void) {
#define qh_rand_a 16807
#define qh_rand_m 2147483647
#define qh_rand_q 127773 /* m div a */
#define qh_rand_r 2836 /* m mod a */
int lo, hi, test;
hi = seed / qh_rand_q; /* seed div q */
lo = seed % qh_rand_q; /* seed mod q */
test = qh_rand_a * lo - qh_rand_r * hi;
if (test > 0)
seed= test;
else
seed= test + qh_rand_m;
return seed;
} /* rand */
void qh_srand( int newseed) {
if (newseed < 1)
seed= 1;
else if (newseed >= qh_rand_m)
seed= qh_rand_m - 1;
else
seed= newseed;
} /* qh_srand */
| 28.713208 | 129 | 0.47216 | [
"mesh",
"3d"
] |
07c4a90fe1e5821a85f2211cf585c0db31c41cab | 957 | cpp | C++ | amazon_question5.cpp | 19yetnoob/-6Companies30days | 93f8dc6370cae7a8907d02b3ac8de610b73b8d9f | [
"MIT"
] | null | null | null | amazon_question5.cpp | 19yetnoob/-6Companies30days | 93f8dc6370cae7a8907d02b3ac8de610b73b8d9f | [
"MIT"
] | null | null | null | amazon_question5.cpp | 19yetnoob/-6Companies30days | 93f8dc6370cae7a8907d02b3ac8de610b73b8d9f | [
"MIT"
] | null | null | null | class Solution{
public:
vector<vector<string>> displayContacts(int n, string contact[], string s)
{
vector<vector<string>>ans;
string check="";
//int size = sizeof(contact)/sizeof(contact[0]);
for(int i=0;i<s.size();i++){
check+=s[i];
set<string>v;
vector<string>a;
for(int j=0;j<n;j++){
// cout<<"dd"<<endl;
string c=contact[j];
string test="";
for(int k=0;k<=i;k++)
{
test+=c[k];
}
//cout<<test<<endl;
if(test==check)
v.insert(c);
}
if(v.size()==0)
a.push_back("0");
else
{
for(auto b:v)
a.push_back(b);
}
ans.push_back(a);
}
return ans;
}
};
| 25.184211 | 77 | 0.361546 | [
"vector"
] |
07ca5a6b8197a8f19161bef4b256e62f8d2f4dcd | 13,690 | cpp | C++ | src/Kernel/Math/DoubleList.cpp | cea-trust-platform/trust-code | c4f42d8f8602a8cc5e0ead0e29dbf0be8ac52f72 | [
"BSD-3-Clause"
] | 12 | 2021-06-30T18:50:38.000Z | 2022-03-23T09:03:16.000Z | src/Kernel/Math/DoubleList.cpp | pledac/trust-code | 46ab5c5da3f674185f53423090f526a38ecdbad1 | [
"BSD-3-Clause"
] | null | null | null | src/Kernel/Math/DoubleList.cpp | pledac/trust-code | 46ab5c5da3f674185f53423090f526a38ecdbad1 | [
"BSD-3-Clause"
] | 2 | 2021-10-04T09:19:39.000Z | 2021-12-15T14:21:04.000Z | /****************************************************************************
* Copyright (c) 2015 - 2016, CEA
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name of the copyright holder 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.
*
*****************************************************************************/
//////////////////////////////////////////////////////////////////////////////
//
// File: DoubleList.cpp
// Directory: $TRUST_ROOT/src/Kernel/Math
// Version: /main/10
//
//////////////////////////////////////////////////////////////////////////////
//
// WARNING: DO NOT EDIT THIS FILE! Only edit the template file DoubleList.cpp.P
//
//
#include <DoubleList.h>
#include <Nom.h>
// Description:
// Ecriture d'une liste sur un flot de sortie
// les elements separes par des virgules figurent entre des accolades
// Precondition:
// Parametre: Sortie& os
// Signification: le flot de sortie a utiliser
// Valeurs par defaut:
// Contraintes:
// Acces: entree/sortie
// Retour: Sortie&
// Signification: le flot d'entree modifie
// Contraintes:
// Exception:
// Effets de bord:
// Postcondition:
Sortie& DoubleList::printOn(Sortie& os) const
{
DoubleList_Curseur curseur(*this);
Nom accouverte = "{";
Nom accfermee = "}";
Nom virgule = ",";
os << accouverte << " " ;
while(curseur)
{
// if(est_dernier()) GF sinon on a une virgule de trop
if(curseur.list().est_dernier())
os << curseur.valeur() << " " ;
else
os << curseur.valeur() << " " << virgule << " " ;
++curseur;
}
os << accfermee;
return os;
}
// Description:
// Lecture d'une liste sur un flot d'entree
// les elements separes par des virgules figurent entre des accolades
// Precondition:
// Parametre: Entree& is
// Signification: le flot d'entree a utiliser
// Valeurs par defaut:
// Contraintes:
// Acces: entree/sortie
// Retour: Entree&
// Signification: le flot d'entree modifie
// Contraintes:
// Exception:
// Effets de bord:
// Postcondition:
Entree& DoubleList::readOn(Entree& is)
{
Nom accouverte = "{";
Nom accfermee = "}";
Nom virgule = ",";
Nom nom;
double t;
is >> nom;
assert(nom==accouverte);
while(nom != accfermee)
{
is >> t;
add(t);
is >> nom;
assert((nom==accfermee)||(nom==virgule));
}
return is ;
}
// Description:
// Constructeur par copie
// Precondition:
// Parametre: const DoubleList& list
// Signification: la liste a copier
// Valeurs par defaut:
// Contraintes:
// Acces:
// Retour:
// Signification:
// Contraintes:
// Exception:
// Effets de bord:
// Postcondition:
DoubleList::DoubleList(const DoubleList& a_list) : DoubleListElem()
{
min_data=a_list.min_data;
max_data=a_list.max_data;
if(a_list.est_vide() )
{
suivant_=this;
}
else
{
data=a_list.data;
dernier_=this;
if(a_list.suivant_)
{
DoubleListElem* next = new DoubleListElem(*a_list.suivant_); //Recursif !!
suivant_ = next;
}
else
suivant_ =0;
}
}
// Description:
// Affectation
// Les elements sont copies
// Precondition:
// Parametre: const DoubleList& list
// Signification: la liste a copier
// Valeurs par defaut:
// Contraintes:
// Acces:
// Retour: DoubleList&
// Signification: *this
// Contraintes:
// Exception:
// Effets de bord:
// Postcondition:
DoubleList& DoubleList::operator=(const DoubleList& a_list)
{
if(a_list.est_vide())
{
suivant_=this;
}
else
{
vide();
DoubleList_Curseur curseur(a_list);
while(curseur)
{
add(curseur.valeur());
++curseur;
}
}
return *this;
}
// Description:
// Renvoie le dernier element de la liste
// Precondition:
// Parametre:
// Signification:
// Valeurs par defaut:
// Contraintes:
// Acces:
// Retour: const DoubleList&
// Signification: le dernier element de la liste
// Contraintes:
// Exception:
// Effets de bord:
// Postcondition:
const DoubleListElem& DoubleList::dernier() const
{
return *dernier_;
/* if (est_dernier()) return *this;
DoubleList_Curseur curseur(*this);
while(curseur)
if (curseur.list().est_dernier()) break;
else ++curseur;
return curseur.list(); */
}
// Description:
// Renvoie le dernier element de la liste
// Precondition:
// Parametre:
// Signification:
// Valeurs par defaut:
// Contraintes:
// Acces:
// Retour: DoubleList&
// Signification: le dernier element de la liste
// Contraintes:
// Exception:
// Effets de bord:
// Postcondition:
DoubleListElem& DoubleList::dernier()
{
return *dernier_;
/*
if (est_dernier()) return *this;
DoubleList_Curseur curseur(*this);
while(curseur)
if (curseur.list().est_dernier()) break;
else ++curseur;
return curseur.list();
*/
}
// Description:
// insertion en queue
// Precondition:
// Parametre: double double_to_add
// Signification: element a ajouter
// Valeurs par defaut:
// Contraintes:
// Acces:
// Retour: DoubleList&
// Signification: *this
// Contraintes:
// Exception:
// Effets de bord:
// Postcondition:
DoubleList& DoubleList::add(double double_to_add)
{
if (double_to_add<min_data)
min_data=double_to_add;
if (double_to_add>max_data)
max_data=double_to_add;
if( est_vide())
{
data=double_to_add;
suivant_=0;
return *this;
}
else
{
if(est_dernier())
{
DoubleListElem* next=new DoubleListElem(double_to_add);
suivant_ = next;
dernier_ = next;
}
else
{
dernier().add(double_to_add);
dernier_ = &dernier_->suivant();
}
return *this;
}
}
// Description:
// Renvoie la taille de la liste
// Une liste vide est de taille nulle
// Precondition:
// Parametre:
// Signification:
// Valeurs par defaut:
// Contraintes:
// Acces:
// Retour: int
// Signification: nombre d'elements de la liste
// Contraintes:
// Exception:
// Effets de bord:
// Postcondition:
int DoubleList::size() const
{
if(est_vide())
return 0;
int i=0;
DoubleList_Curseur curseur(*this);
while(curseur)
{
++i;
++curseur;
}
return i;
}
// Description:
// Ajout d'un element a la liste ssi il n'existe pas deja
// Precondition:
// Parametre: double x
// Signification: l'element a ajouter
// Valeurs par defaut:
// Contraintes:
// Acces:
// Retour: DoubleList&
// Signification: *this
// Contraintes:
// Exception:
// Effets de bord:
// Postcondition:
DoubleList& DoubleList::add_if_not(double x)
{
if (!contient(x))
return add(x);
else
return *this;
}
// Description:
// Verifie si un element appartient ou non a la liste
// Precondition:
// Parametre: double x
// Signification: L'element a rechercher
// Valeurs par defaut:
// Contraintes:
// Acces:
// Retour: int
// Signification: 1 si la liste contient l'element, 0 sinon
// Contraintes:
// Exception:
// Effets de bord:
// Postcondition:
int DoubleList::contient(double x) const
{
if(est_vide() || x>max_data || x<min_data)
return 0;
DoubleList_Curseur curseur(*this);
while(curseur)
{
if (curseur.valeur()==x)
return 1;
++curseur;
}
return 0;
}
// Description:
// renvoie le rang d'un element dans la liste
// si un element apparait plusieurs fois, renvoie le rang du premier.
// Precondition:
// Parametre: int i
// Signification: L'element a rechercher
// Valeurs par defaut:
// Contraintes:
// Acces:
// Retour: int
// Signification: le rang du premier element de la liste valant i,
// -1 si la liste ne contient pas i.
// Contraintes:
// Exception:
// Effets de bord:
// Postcondition:
int DoubleList::rang(double x) const
{
if(est_vide() || x>max_data || x<min_data)
return -1;
int compteur=0;
DoubleList_Curseur curseur(*this);
while(curseur)
{
if (curseur.valeur()==x)
return compteur;
++compteur;
++curseur;
}
return -1;
}
// Description:
// Operateur d'acces au ieme int de la liste
// Precondition:
// Parametre: int i
// Signification: l'indice de l'element a trouver
// Valeurs par defaut:
// Contraintes:
// Acces:
// Retour: double&
// Signification: le ieme element de la liste
// Contraintes:
// Exception:
// Effets de bord:
// Postcondition:
double& DoubleList::operator[](int i)
{
DoubleList_Curseur curseur(*this);
while(curseur && i--)
++curseur;
if(i!=-1)
{
Cerr << "Overflow list " << finl;
Process::exit();
}
return curseur.valeur();
}
// Description:
// Operateur d'acces au ieme int de la liste
// Precondition:
// Parametre: int i
// Signification: l'indice de l'element a trouver
// Valeurs par defaut:
// Contraintes:
// Acces:
// Retour: const double&
// Signification: le ieme element de la liste
// Contraintes:
// Exception:
// Effets de bord:
// Postcondition:
const double& DoubleList::operator[](int i) const
{
DoubleList_Curseur curseur(*this);
while(curseur && i--)
++curseur;
if(i!=-1)
{
Cerr << "Overflow list " << finl;
Process::exit();
}
return curseur.valeur();
}
// Description:
// Operateur de comparaison de deux listes
// Precondition:
// Parametre: const DoubleList& list1
// Signification: premiere liste a comparer
// Valeurs par defaut:
// Contraintes:
// Acces:
// Parametre: const DoubleList& list2
// Signification: seconde liste a comparer
// Valeurs par defaut:
// Contraintes:
// Acces:
// Retour: int
// Signification: 1 si les listes sont egales, 0 sinon
// Contraintes:
// Exception:
// Effets de bord:
// Postcondition:
int operator ==(const DoubleList& list1 , const DoubleList& list2)
{
int retour=1;
if(list1.data != list2.data)
retour= 0;
if( (!list1.est_dernier()) && (list2.est_dernier()) )
retour= 0;
if( (list1.est_dernier()) && (!list2.est_dernier()) )
retour= 0;
if( (!list1.est_dernier()) && (!list2.est_dernier()) )
retour= (*list1.suivant_ == *list2.suivant_);
return retour;
}
// Description:
// Supprime un element contenu dans la liste
// Precondition:
// Parametre: double obj
// Signification: l'element a supprimer de la liste
// Valeurs par defaut:
// Contraintes:
// Acces:
// Retour:
// Signification:
// Contraintes:
// Exception:
// Effets de bord:
// Postcondition:
void DoubleList::suppr(double obj)
{
if(valeur()==obj)
{
if(suivant_)
{
DoubleListElem* next=suivant_;
suivant_=next->suivant_;
data=next->valeur();
next->suivant_=0;
delete next;
}
else
{
suivant_=this;
dernier_=this;
}
calcule_min_max();
return;
}
DoubleList_Curseur curseur_pre=*this;
DoubleList_Curseur curseur=*suivant_;
while(curseur)
{
if(curseur.valeur()==obj)
{
DoubleListElem* next=&curseur_pre.list().suivant();
curseur_pre.list().suivant_=curseur.list().suivant_;
if (next->suivant_==0)
dernier_=&curseur_pre.list();
else
next->suivant_=0;
delete next;
calcule_min_max();
return ;
}
++curseur;
++curseur_pre;
}
Cerr << "WARNING during deletion of an element in a list " << finl;
Cerr << "One has not found object == : " << obj << finl;
}
void DoubleList::calcule_min_max()
{
min_data=DMAXFLOAT;
max_data=-DMAXFLOAT;
DoubleList_Curseur curseur=*this;
while(curseur)
{
double la_valeur=curseur.valeur();
if (la_valeur<min_data)
min_data=la_valeur;
if (la_valeur>max_data)
max_data=la_valeur;
++curseur;
}
}
// Description:
// Vide la liste
// Precondition:
// Parametre:
// Signification:
// Valeurs par defaut:
// Contraintes:
// Acces:
// Retour:
// Signification:
// Contraintes:
// Exception:
// Effets de bord:
// Postcondition:
void DoubleList::vide()
{
if (!est_vide())
if(suivant_)
delete suivant_;
suivant_=this;
dernier_=this;
calcule_min_max();
}
| 24.359431 | 260 | 0.622863 | [
"object"
] |
07d19d17a6f2a8df5a1fdf008a14ed46d3d6c224 | 6,516 | hpp | C++ | legacy/OrderConditionHelpersMPFR.hpp | dzhang314/RKTK | 0aa0dfe5980732186573a13d9bcc6d5ba7542549 | [
"MIT"
] | 2 | 2020-06-07T13:05:30.000Z | 2020-12-30T13:26:19.000Z | legacy/OrderConditionHelpersMPFR.hpp | dzhang314/RKTK | 0aa0dfe5980732186573a13d9bcc6d5ba7542549 | [
"MIT"
] | null | null | null | legacy/OrderConditionHelpersMPFR.hpp | dzhang314/RKTK | 0aa0dfe5980732186573a13d9bcc6d5ba7542549 | [
"MIT"
] | 1 | 2020-06-07T13:05:36.000Z | 2020-06-07T13:05:36.000Z | #ifndef RKTK_ORDER_CONDITION_HELPERS_MPFR_HPP_INCLUDED
#define RKTK_ORDER_CONDITION_HELPERS_MPFR_HPP_INCLUDED
// C++ standard library headers
#include <cstddef> // for std::size_t
// GNU MPFR multiprecision library headers
#include <mpfr.h>
namespace rktk::detail {
/*
* The following functions are helper subroutines used in the calculation
* of Runge-Kutta order conditions. Their names are deliberately short and
* unreadable because they are intended to be called thousands of times
* in machine-generated code. Brevity keeps generated file sizes down.
*
* lrs - Lower-triangular matrix Row Sums
* elm - ELementwise Multiplication
* esq - Elementwise SQuare
* dot - DOT product
* lvm - Lower-triangular Matrix-Vector multiplication
* sqr - Scalar sQuaRe
* sri - Set to Reciprocal of (unsigned) Integer
* res - RESult (special operation used to evaluate partial
* derivatives of Runge-Kutta order conditions)
*/
static inline void lrsm(mpfr_ptr dst, std::size_t dst_size,
mpfr_srcptr mat) {
for (std::size_t i = 0, k = 0; i < dst_size; ++i) {
mpfr_set(dst + i, mat + k, MPFR_RNDN);
++k;
for (std::size_t j = 0; j < i; ++j, ++k) {
mpfr_add(dst + i, dst + i, mat + k, MPFR_RNDN);
}
}
}
static inline void lrsm(mpfr_ptr dst_du, std::size_t n,
std::size_t mat_di) {
for (std::size_t i = 0, k = 0; i < n; ++i) {
mpfr_set_si(dst_du + i, k == mat_di, MPFR_RNDN);
++k;
for (std::size_t j = 0; j < i; ++j, ++k) {
mpfr_add_si(dst_du + i, dst_du + i, k == mat_di, MPFR_RNDN);
}
}
}
static inline void lrsm(mpfr_ptr dst_re, mpfr_ptr dst_du, std::size_t n,
mpfr_srcptr mat_re, std::size_t mat_di) {
lrsm(dst_re, n, mat_re);
for (std::size_t i = 0, k = 0; i < n; ++i) {
mpfr_set_si(dst_du + i, k == mat_di, MPFR_RNDN);
++k;
for (std::size_t j = 0; j < i; ++j, ++k) {
mpfr_add_si(dst_du + i, dst_du + i, k == mat_di, MPFR_RNDN);
}
}
}
static inline void elmm(mpfr_ptr dst, std::size_t n,
mpfr_srcptr v, mpfr_srcptr w) {
for (std::size_t i = 0; i < n; ++i) {
mpfr_mul(dst + i, v + i, w + i, MPFR_RNDN);
}
}
static inline void elmm(mpfr_ptr dst_du, std::size_t n,
mpfr_srcptr v_re, mpfr_srcptr v_du,
mpfr_srcptr w_re, mpfr_srcptr w_du) {
for (std::size_t i = 0; i < n; ++i) {
mpfr_fmma(dst_du + i, v_du + i, w_re + i, v_re + i, w_du + i,
MPFR_RNDN);
}
}
static inline void elmm(mpfr_ptr dst_re, mpfr_ptr dst_du, std::size_t n,
mpfr_srcptr v_re, mpfr_srcptr v_du,
mpfr_srcptr w_re, mpfr_srcptr w_du) {
elmm(dst_re, n, v_re, w_re);
for (std::size_t i = 0; i < n; ++i) {
mpfr_fmma(dst_du + i, v_du + i, w_re + i, v_re + i, w_du + i,
MPFR_RNDN);
}
}
static inline void esqm(mpfr_ptr dst, std::size_t n, mpfr_srcptr v) {
for (std::size_t i = 0; i < n; ++i) {
mpfr_sqr(dst + i, v + i, MPFR_RNDN);
}
}
static inline void esqm(mpfr_ptr dst_du, std::size_t n,
mpfr_srcptr v_re, mpfr_srcptr v_du) {
for (std::size_t i = 0; i < n; ++i) {
mpfr_mul(dst_du + i, v_re + i, v_du + i, MPFR_RNDN);
mpfr_mul_2ui(dst_du + i, dst_du + i, 1, MPFR_RNDN);
}
}
static inline void esqm(mpfr_ptr dst_re, mpfr_ptr dst_du, std::size_t n,
mpfr_srcptr v_re, mpfr_srcptr v_du) {
for (std::size_t i = 0; i < n; ++i) {
mpfr_mul(dst_du + i, v_re + i, v_du + i, MPFR_RNDN);
mpfr_mul_2ui(dst_du + i, dst_du + i, 1, MPFR_RNDN);
mpfr_sqr(dst_re + i, v_re + i, MPFR_RNDN);
}
}
static inline void dotm(mpfr_ptr dst, std::size_t n,
mpfr_srcptr v, mpfr_srcptr w) {
if (n == 0) {
mpfr_set_zero(dst, 0);
} else {
mpfr_mul(dst, v, w, MPFR_RNDN);
for (std::size_t i = 1; i < n; ++i) {
mpfr_fma(dst, v + i, w + i, dst, MPFR_RNDN);
}
}
}
static inline void lvmm(mpfr_ptr dst, std::size_t dst_size,
std::size_t mat_size, mpfr_srcptr mat,
mpfr_srcptr vec) {
std::size_t skp = mat_size - dst_size;
std::size_t idx = skp * (skp + 1) / 2 - 1;
for (std::size_t i = 0; i < dst_size; ++i, idx += skp, ++skp) {
dotm(dst + i, i + 1, mat + idx, vec);
}
}
static inline void lvmm(mpfr_ptr dst_du, std::size_t dst_size,
std::size_t mat_size,
mpfr_srcptr mat_re, std::size_t mat_di,
mpfr_srcptr vec_re, mpfr_srcptr vec_du) {
std::size_t skp = mat_size - dst_size;
std::size_t idx = skp * (skp + 1) / 2 - 1;
for (std::size_t i = 0; i < dst_size; ++i, idx += skp, ++skp) {
dotm(dst_du + i, i + 1, mat_re + idx, vec_du);
if (idx <= mat_di && mat_di <= idx + i) {
mpfr_add(dst_du + i, dst_du + i, vec_re + mat_di - idx,
MPFR_RNDN);
}
}
}
static inline void lvmm(mpfr_ptr dst_re, mpfr_ptr dst_du,
std::size_t dst_size, std::size_t mat_size,
mpfr_srcptr mat_re, std::size_t mat_di,
mpfr_srcptr vec_re, mpfr_srcptr vec_du) {
lvmm(dst_re, dst_size, mat_size, mat_re, vec_re);
std::size_t skp = mat_size - dst_size;
std::size_t idx = skp * (skp + 1) / 2 - 1;
for (std::size_t i = 0; i < dst_size; ++i, idx += skp, ++skp) {
dotm(dst_du + i, i + 1, mat_re + idx, vec_du);
if (idx <= mat_di && mat_di <= idx + i) {
mpfr_add(dst_du + i, dst_du + i, vec_re + mat_di - idx,
MPFR_RNDN);
}
}
}
} // namespace rktk::detail
#endif // RKTK_ORDER_CONDITION_HELPERS_MPFR_HPP_INCLUDED
| 38.785714 | 77 | 0.506599 | [
"vector"
] |
07dd98175680ecbbae4ee158af371148ec590c18 | 658 | cpp | C++ | chapter_4_computation/exercise/sequence_of_numbers.cpp | jamie-prog/programming_principles_and_practice | abd4fec2cd02fc0bab69c9b11e13d9fce04039f9 | [
"Apache-2.0"
] | null | null | null | chapter_4_computation/exercise/sequence_of_numbers.cpp | jamie-prog/programming_principles_and_practice | abd4fec2cd02fc0bab69c9b11e13d9fce04039f9 | [
"Apache-2.0"
] | null | null | null | chapter_4_computation/exercise/sequence_of_numbers.cpp | jamie-prog/programming_principles_and_practice | abd4fec2cd02fc0bab69c9b11e13d9fce04039f9 | [
"Apache-2.0"
] | null | null | null | #include "../../std_lib_facilities.h"
int main(void)
{
vector<double> distances;
cout << "Enter a number (abort with NaN): ";
for (double temp; cin >> temp; )
{
cout << "Enter a number (abort with NaN): ";
distances.push_back(temp);
}
sort(distances);
double sum{0};
for (size_t i{0}; i < distances.size(); ++i)
sum += distances[i];
cout << "The sum is " << sum << "\n"
<< "The smallest distance is " << distances[0] << "\n"
<< "The largest distance is " << distances[distances.size() - 1] << "\n"
<< "The mean distance is " << sum / distances.size() << "\n";
} | 26.32 | 81 | 0.522796 | [
"vector"
] |
07debbb192682b934398825ffe9b7dffdf1f2474 | 20,865 | cpp | C++ | gmsh/Geo/boundaryLayersData.cpp | Poofee/fastFEM | 14eb626df973e2123604041451912c867ab7188c | [
"MIT"
] | 4 | 2019-05-06T09:35:08.000Z | 2021-05-14T16:26:45.000Z | gmsh/Geo/boundaryLayersData.cpp | Poofee/fastFEM | 14eb626df973e2123604041451912c867ab7188c | [
"MIT"
] | null | null | null | gmsh/Geo/boundaryLayersData.cpp | Poofee/fastFEM | 14eb626df973e2123604041451912c867ab7188c | [
"MIT"
] | 1 | 2019-06-28T09:23:43.000Z | 2019-06-28T09:23:43.000Z | // Gmsh - Copyright (C) 1997-2019 C. Geuzaine, J.-F. Remacle
//
// See the LICENSE.txt file for license information. Please report all
// issues on https://gitlab.onelab.info/gmsh/gmsh/issues.
#include "boundaryLayersData.h"
#include "GmshConfig.h"
#include "GModel.h"
#include "MLine.h"
#include "MTriangle.h"
#include "MEdge.h"
#include "OS.h"
#include "Context.h"
#if !defined(HAVE_MESH)
BoundaryLayerField *getBLField(GModel *gm) { return 0; }
bool buildAdditionalPoints2D(GFace *gf) { return false; }
bool buildAdditionalPoints3D(GRegion *gr) { return false; }
edgeColumn BoundaryLayerColumns::getColumns(MVertex *v1, MVertex *v2, int side)
{
return edgeColumn(BoundaryLayerData(), BoundaryLayerData());
}
#else
#include "Field.h"
/*
^ ni
|
|
+-----------------+
bi /
bj /
/\
/ \ nj
/ Z
+
*/
SVector3 interiorNormal(const SPoint2 &p1, const SPoint2 &p2, const SPoint2 &p3)
{
SVector3 ez(0, 0, 1);
SVector3 d(p1.x() - p2.x(), p1.y() - p2.y(), 0);
SVector3 h(p3.x() - 0.5 * (p2.x() + p1.x()), p3.y() - 0.5 * (p2.y() + p1.y()),
0);
SVector3 n = crossprod(d, ez);
n.normalize();
if(dot(n, h) > 0) return n;
return n * (-1.);
}
edgeColumn BoundaryLayerColumns::getColumns(MVertex *v1, MVertex *v2, int side)
{
Equal_Edge aaa;
MEdge e(v1, v2);
std::map<MVertex *, BoundaryLayerFan>::const_iterator it1 = _fans.find(v1);
std::map<MVertex *, BoundaryLayerFan>::const_iterator it2 = _fans.find(v2);
int N1 = getNbColumns(v1);
int N2 = getNbColumns(v2);
int nbSides = _normals.count(e);
// if(nbSides != 1)printf("I'm here %d sides\n",nbSides);
// Standard case, only two extruded columns from the two vertices
if(N1 == 1 && N2 == 1) return edgeColumn(getColumn(v1, 0), getColumn(v2, 0));
// one fan on
if(nbSides == 1) {
if(it1 != _fans.end() && it2 == _fans.end()) {
if(aaa(it1->second._e1, e))
return edgeColumn(getColumn(v1, 0), getColumn(v2, 0));
else
return edgeColumn(getColumn(v1, N1 - 1), getColumn(v2, 0));
}
if(it2 != _fans.end() && it1 == _fans.end()) {
if(aaa(it2->second._e1, e))
return edgeColumn(getColumn(v1, 0), getColumn(v2, 0));
else
return edgeColumn(getColumn(v1, 0), getColumn(v2, N2 - 1));
}
if(it2 != _fans.end() && it1 != _fans.end()) {
int c1, c2;
if(aaa(it1->second._e1, e))
c1 = 0;
else
c1 = N1 - 1;
if(aaa(it2->second._e1, e))
c2 = 0;
else
c2 = N2 - 1;
return edgeColumn(getColumn(v1, c1), getColumn(v2, c2));
}
// fan on the right
if(N1 == 1 || N2 == 2) {
const BoundaryLayerData &c10 = getColumn(v1, 0);
const BoundaryLayerData &c20 = getColumn(v2, 0);
const BoundaryLayerData &c21 = getColumn(v2, 1);
if(dot(c10._n, c20._n) > dot(c10._n, c21._n))
return edgeColumn(c10, c20);
else
return edgeColumn(c10, c21);
}
// fan on the left
if(N1 == 2 || N2 == 1) {
const BoundaryLayerData &c10 = getColumn(v1, 0);
const BoundaryLayerData &c11 = getColumn(v1, 1);
const BoundaryLayerData &c20 = getColumn(v2, 0);
if(dot(c10._n, c20._n) > dot(c11._n, c20._n))
return edgeColumn(c10, c20);
else
return edgeColumn(c11, c20);
}
// Msg::Error("Impossible Boundary Layer Configuration : "
// "one side and no fans %d %d", N1, N2);
// FIXME WRONG
return N1 ? edgeColumn(getColumn(v1, 0), getColumn(v1, 0)) :
edgeColumn(getColumn(v2, 0), getColumn(v2, 0));
}
else if(nbSides == 2) {
int i1 = 0, i2 = 1, j1 = 0, j2 = 1;
if(it1 != _fans.end()) {
i1 = aaa(it1->second._e1, e) ? 0 : N1 - 1;
i2 = !aaa(it1->second._e1, e) ? 0 : N1 - 1;
}
if(it2 != _fans.end()) {
j1 = aaa(it2->second._e1, e) ? 0 : N2 - 1;
j2 = !aaa(it2->second._e1, e) ? 0 : N2 - 1;
}
const BoundaryLayerData &c10 = getColumn(v1, i1);
const BoundaryLayerData &c11 = getColumn(v1, i2);
const BoundaryLayerData &c20 = getColumn(v2, j1);
const BoundaryLayerData &c21 = getColumn(v2, j2);
if(side == 0) {
if(dot(c10._n, c20._n) > dot(c10._n, c21._n))
return edgeColumn(c10, c20);
else
return edgeColumn(c10, c21);
}
if(side == 1) {
if(dot(c11._n, c20._n) > dot(c11._n, c21._n))
return edgeColumn(c11, c20);
else
return edgeColumn(c11, c21);
}
}
Msg::Error("Not yet Done in BoundaryLayerData nbSides = %d, ", nbSides);
static BoundaryLayerData error;
static edgeColumn error2(error, error);
return error2;
}
static void treat2Connections(GFace *gf, MVertex *_myVert, MEdge &e1, MEdge &e2,
BoundaryLayerColumns *_columns,
std::vector<SVector3> &_dirs, bool fan)
{
std::vector<SVector3> N1, N2;
for(std::multimap<MEdge, SVector3, Less_Edge>::iterator itm =
_columns->_normals.lower_bound(e1);
itm != _columns->_normals.upper_bound(e1); ++itm)
N1.push_back(itm->second);
for(std::multimap<MEdge, SVector3, Less_Edge>::iterator itm =
_columns->_normals.lower_bound(e2);
itm != _columns->_normals.upper_bound(e2); ++itm)
N2.push_back(itm->second);
if(N1.size() == N2.size()) {
for(std::size_t SIDE = 0; SIDE < N1.size(); SIDE++) {
if(!fan) {
SVector3 x = N1[SIDE] * 1.01 + N2[SIDE];
x.normalize();
_dirs.push_back(x);
}
else if(fan) {
// if the angle is greater than PI, than reverse the sense
double alpha1 = atan2(N1[SIDE].y(), N1[SIDE].x());
double alpha2 = atan2(N2[SIDE].y(), N2[SIDE].x());
double AMAX = std::max(alpha1, alpha2);
double AMIN = std::min(alpha1, alpha2);
MEdge ee[2];
if(alpha1 > alpha2) {
ee[0] = e2;
ee[1] = e1;
}
else {
ee[0] = e1;
ee[1] = e2;
}
if(AMAX - AMIN >= M_PI) {
double temp = AMAX;
AMAX = AMIN + 2 * M_PI;
AMIN = temp;
MEdge eee0 = ee[0];
ee[0] = ee[1];
ee[1] = eee0;
}
double frac = fabs(AMAX - AMIN) / M_PI;
int n =
(int)(frac * CTX::instance()->mesh.boundaryLayerFanPoints + 0.5);
int fanSize = fan ? n : 0;
_columns->addFan(_myVert, ee[0], ee[1], true);
for(int i = -1; i <= fanSize; i++) {
double t = (double)(i + 1) / (fanSize + 1);
double alpha = t * AMAX + (1. - t) * AMIN;
SVector3 x(cos(alpha), sin(alpha), 0);
x.normalize();
_dirs.push_back(x);
}
}
/*
else {
_dirs.push_back(N1[SIDE]);
_dirs.push_back(N2[SIDE]);
}
*/
}
}
}
static void treat3Connections(GFace *gf, MVertex *_myVert, MEdge &e1, MEdge &e2,
MEdge &e3, BoundaryLayerColumns *_columns,
std::vector<SVector3> &_dirs)
{
std::vector<SVector3> N1, N2, N3;
for(std::multimap<MEdge, SVector3, Less_Edge>::iterator itm =
_columns->_normals.lower_bound(e1);
itm != _columns->_normals.upper_bound(e1); ++itm)
N1.push_back(itm->second);
for(std::multimap<MEdge, SVector3, Less_Edge>::iterator itm =
_columns->_normals.lower_bound(e2);
itm != _columns->_normals.upper_bound(e2); ++itm)
N2.push_back(itm->second);
for(std::multimap<MEdge, SVector3, Less_Edge>::iterator itm =
_columns->_normals.lower_bound(e3);
itm != _columns->_normals.upper_bound(e3); ++itm)
N3.push_back(itm->second);
SVector3 x1, x2;
if(N1.size() == 2) {
}
else if(N2.size() == 2) {
std::vector<SVector3> temp = N1;
N1.clear();
N1 = N2;
N2.clear();
N2 = temp;
}
else if(N3.size() == 2) {
std::vector<SVector3> temp = N1;
N1.clear();
N1 = N3;
N3.clear();
N3 = temp;
}
else {
Msg::Error("Impossible boundary layer configuration");
}
if(dot(N1[0], N2[0]) > dot(N1[0], N3[0])) {
x1 = N1[0] * 1.01 + N2[0];
x2 = N1[1] * 1.01 + N3[0];
}
else {
x1 = N1[1] * 1.01 + N2[0];
x2 = N1[0] * 1.01 + N3[0];
}
x1.normalize();
_dirs.push_back(x1);
x2.normalize();
_dirs.push_back(x2);
}
static bool isEdgeOfFaceBL(GFace *gf, GEdge *ge, BoundaryLayerField *blf)
{
if(blf->isEdgeBL(ge->tag())) return true;
/*
std::list<GFace*> faces = ge->faces();
for(std::list<GFace*>::iterator it = faces.begin();
it != faces.end() ; ++it){
if((*it) == gf)return false;
}
for(std::list<GFace*>::iterator it = faces.begin();
it != faces.end() ; ++it){
if(blf->isFaceBL((*it)->tag()))return true;
}
*/
return false;
}
static void getEdgesData(GFace *gf, BoundaryLayerField *blf,
BoundaryLayerColumns *_columns,
std::set<MVertex *> &_vertices,
std::set<MEdge, Less_Edge> &allEdges,
std::multimap<MVertex *, MVertex *> &tangents)
{
// get all model edges
std::vector<GEdge *> edges = gf->edges();
std::vector<GEdge *> const &embedded_edges = gf->embeddedEdges();
edges.insert(edges.begin(), embedded_edges.begin(), embedded_edges.end());
// iterate on model edges
std::vector<GEdge *>::iterator ite = edges.begin();
while(ite != edges.end()) {
// check if this edge generates a boundary layer
if(isEdgeOfFaceBL(gf, *ite, blf)) {
for(std::size_t i = 0; i < (*ite)->lines.size(); i++) {
MVertex *v1 = (*ite)->lines[i]->getVertex(0);
MVertex *v2 = (*ite)->lines[i]->getVertex(1);
allEdges.insert(MEdge(v1, v2));
_columns->_non_manifold_edges.insert(std::make_pair(v1, v2));
_columns->_non_manifold_edges.insert(std::make_pair(v2, v1));
_vertices.insert(v1);
_vertices.insert(v2);
}
}
else {
MVertex *v1 = (*ite)->lines[0]->getVertex(0);
MVertex *v2 = (*ite)->lines[0]->getVertex(1);
MVertex *v3 = (*ite)->lines[(*ite)->lines.size() - 1]->getVertex(1);
MVertex *v4 = (*ite)->lines[(*ite)->lines.size() - 1]->getVertex(0);
tangents.insert(std::make_pair(v1, v2));
tangents.insert(std::make_pair(v3, v4));
}
++ite;
}
}
static void getNormals(GFace *gf, BoundaryLayerField *blf,
BoundaryLayerColumns *_columns,
std::set<MEdge, Less_Edge> &allEdges)
{
// assume that the initial mesh has been created i.e. that there exist
// triangles inside the domain. Triangles are used to define exterior normals
for(std::size_t i = 0; i < gf->triangles.size(); i++) {
SPoint2 p0, p1, p2;
MVertex *v0 = gf->triangles[i]->getVertex(0);
MVertex *v1 = gf->triangles[i]->getVertex(1);
MVertex *v2 = gf->triangles[i]->getVertex(2);
reparamMeshEdgeOnFace(v0, v1, gf, p0, p1);
reparamMeshEdgeOnFace(v0, v2, gf, p0, p2);
MEdge me01(v0, v1);
if(allEdges.find(me01) != allEdges.end()) {
SVector3 v01 = interiorNormal(p0, p1, p2);
_columns->_normals.insert(std::make_pair(me01, v01));
}
MEdge me02(v0, v2);
if(allEdges.find(me02) != allEdges.end()) {
SVector3 v02 = interiorNormal(p0, p2, p1);
_columns->_normals.insert(std::make_pair(me02, v02));
}
MEdge me21(v2, v1);
if(allEdges.find(me21) != allEdges.end()) {
SVector3 v21 = interiorNormal(p2, p1, p0);
_columns->_normals.insert(std::make_pair(me21, v21));
}
}
}
static void addColumnAtTheEndOfTheBL(GEdge *ge, GVertex *gv,
BoundaryLayerColumns *_columns,
BoundaryLayerField *blf)
{
if(!blf->isEdgeBL(ge->tag())) {
std::vector<MVertex *> invert;
for(std::size_t i = 0; i < ge->mesh_vertices.size(); i++)
invert.push_back(ge->mesh_vertices[ge->mesh_vertices.size() - i - 1]);
GVertex *g0 = ge->getBeginVertex();
GVertex *g1 = ge->getEndVertex();
if(g0 && g1){
MVertex *v0 = g0->mesh_vertices[0];
MVertex *v1 = g1->mesh_vertices[0];
SVector3 t(v1->x() - v0->x(), v1->y() - v0->y(), v1->z() - v0->z());
t.normalize();
if(g0 == gv)
_columns->addColumn(t, v0, ge->mesh_vertices);
else if(g1 == gv)
_columns->addColumn(t * -1.0, v1, invert);
}
}
}
void getLocalInfoAtNode(MVertex *v, BoundaryLayerField *blf, double &hwall)
{
hwall = blf->hwall_n;
if(v->onWhat()->dim() == 0) {
hwall = blf->hwall(v->onWhat()->tag());
}
else if(v->onWhat()->dim() == 1) {
GEdge *ge = (GEdge *)v->onWhat();
Range<double> bounds = ge->parBounds(0);
double t_begin = bounds.low();
double t_end = bounds.high();
double t;
v->getParameter(0, t);
if(ge->getBeginVertex() && ge->getEndVertex()){
double hwall_beg = blf->hwall(ge->getBeginVertex()->tag());
double hwall_end = blf->hwall(ge->getEndVertex()->tag());
double x = (t - t_begin) / (t_end - t_begin);
double hwallLin = hwall_beg + x * (hwall_end - hwall_beg);
double hwall_mid = std::min(hwall_beg, hwall_end);
double hwallQuad = hwall_beg * (1 - x) * (1 - x) +
hwall_mid * 2 * x * (1 - x) + hwall_end * x * x;
// we prefer a quadratic growing:
hwall = 0 * hwallLin + 1 * hwallQuad;
}
}
}
bool buildAdditionalPoints2D(GFace *gf)
{
BoundaryLayerColumns *_columns = gf->getColumns();
_columns->clearData();
FieldManager *fields = gf->model()->getFields();
int nBL = fields->getNumBoundaryLayerFields();
if(nBL == 0) return false;
// Note: boundary layers must be separate (must not touch each other)
bool addedAdditionalPoints = false;
for(int i = 0; i < nBL; ++i) {
// GET THE FIELD THAT DEFINES THE DISTANCE FUNCTION
Field *bl_field = fields->get(fields->getBoundaryLayerField(i));
if(bl_field == nullptr) continue;
BoundaryLayerField *blf = dynamic_cast<BoundaryLayerField *>(bl_field);
blf->setupFor2d(gf->tag());
std::set<MVertex *> _vertices;
std::set<MEdge, Less_Edge> allEdges;
std::multimap<MVertex *, MVertex *> tangents;
getEdgesData(gf, blf, _columns, _vertices, allEdges, tangents);
if(!_vertices.size()) continue;
getNormals(gf, blf, _columns, allEdges);
// for all boundry points
for(std::set<MVertex *>::iterator it = _vertices.begin();
it != _vertices.end(); ++it) {
bool endOfTheBL = false;
SVector3 dirEndOfBL;
std::vector<MVertex *> columnEndOfBL;
std::vector<MVertex *> _connections;
std::vector<SVector3> _dirs;
// get all vertices that are connected to that
// vertex among all boundary layer vertices !
bool fan =
(*it)->onWhat()->dim() == 0 && blf->isFanNode((*it)->onWhat()->tag());
for(std::multimap<MVertex *, MVertex *>::iterator itm =
_columns->_non_manifold_edges.lower_bound(*it);
itm != _columns->_non_manifold_edges.upper_bound(*it); ++itm)
_connections.push_back(itm->second);
// A trailing edge topology : 3 edges incident to a vertex
if(_connections.size() == 3) {
MEdge e1(*it, _connections[0]);
MEdge e2(*it, _connections[1]);
MEdge e3(*it, _connections[2]);
treat3Connections(gf, *it, e1, e2, e3, _columns, _dirs);
}
// STANDARD CASE, one vertex connected to two neighboring vertices
else if(_connections.size() == 2) {
MEdge e1(*it, _connections[0]);
MEdge e2(*it, _connections[1]);
treat2Connections(gf, *it, e1, e2, _columns, _dirs, fan);
}
else if(_connections.size() == 1) {
MEdge e1(*it, _connections[0]);
std::vector<SVector3> N1;
std::multimap<MEdge, SVector3, Less_Edge>::iterator itm;
for(itm = _columns->_normals.lower_bound(e1);
itm != _columns->_normals.upper_bound(e1); ++itm)
N1.push_back(itm->second);
// one point has only one side and one normal : it has to be at the end
// of the BL then, we have the tangent to the connecting edge
// *it _connections[0]
// --------- + -----------
// NO BL BL
if(N1.size() == 1) {
std::vector<MVertex *> Ts;
for(std::multimap<MVertex *, MVertex *>::iterator itm =
tangents.lower_bound(*it);
itm != tangents.upper_bound(*it); ++itm)
Ts.push_back(itm->second);
// end of the BL --> let's add a column that correspond to the
// model edge that lies after the end of teh BL
if(Ts.size() == 1) {
// printf("HERE WE ARE IN FACE %d %d\n",gf->tag(),Ts.size());
// printf("Classif dim %d
// %d\n",(*it)->onWhat()->dim(),Ts[0]->onWhat()->dim());
GEdge *ge = dynamic_cast<GEdge *>(Ts[0]->onWhat());
GVertex *gv = dynamic_cast<GVertex *>((*it)->onWhat());
if(ge && gv) {
addColumnAtTheEndOfTheBL(ge, gv, _columns, blf);
}
}
else {
Msg::Error(
"Impossible BL Configuration -- One Edge -- Tscp.size() = %d",
Ts.size());
}
}
else if(N1.size() == 2) {
SPoint2 p0, p1;
reparamMeshEdgeOnFace(_connections[0], *it, gf, p0, p1);
double alpha1 = atan2(N1[0].y(), N1[0].x());
double alpha2 = atan2(N1[1].y(), N1[1].x());
double alpha3 = atan2(p1.y() - p0.y(), p1.x() - p0.x());
double AMAX = std::max(alpha1, alpha2);
double AMIN = std::min(alpha1, alpha2);
if(alpha3 > AMAX) {
double temp = AMAX;
AMAX = AMIN + 2 * M_PI;
AMIN = temp;
}
if(alpha3 < AMIN) {
double temp = AMIN;
AMIN = AMAX - 2 * M_PI;
AMAX = temp;
}
double frac = fabs(AMAX - AMIN) / M_PI;
int n =
(int)(frac * CTX::instance()->mesh.boundaryLayerFanPoints + 0.5);
int fanSize = fan ? n : 0;
if(fan) _columns->addFan(*it, e1, e1, true);
for(int i = -1; i <= fanSize; i++) {
double t = (double)(i + 1) / (fanSize + 1);
double alpha = t * AMAX + (1. - t) * AMIN;
SVector3 x(cos(alpha), sin(alpha), 0);
x.normalize();
_dirs.push_back(x);
}
}
}
// if(_dirs.size() > 1)printf("%d directions\n",_dirs.size());
// now create the BL points
for(std::size_t DIR = 0; DIR < _dirs.size(); DIR++) {
SVector3 n = _dirs[DIR];
// < ------------------------------- > //
// N = X(p0+ e n) - X(p0) //
// = e * (dX/du n_u + dX/dv n_v) //
// < ------------------------------- > //
/* if (endOfTheBL){
printf("%g %g %d %d %g\n", (*it)->x(), (*it)->y(), DIR,
(int)_dirs.size(), dot(n, dirEndOfBL));
}
*/
if(endOfTheBL && dot(n, dirEndOfBL) > .99) {
// printf( "coucou c'est moi\n");
}
else {
MVertex *first = *it;
double hwall;
getLocalInfoAtNode(first, blf, hwall);
std::vector<MVertex *> _column;
SPoint2 par =
gf->parFromPoint(SPoint3(first->x(), first->y(), first->z()));
double L = hwall;
while(1) {
// printf("L = %g\n",L);
if(L > blf->thickness) break;
SPoint2 pnew(par.x() + L * n.x(), par.y() + L * n.y());
GPoint pp = gf->point(pnew);
MFaceVertex *_current =
new MFaceVertex(pp.x(), pp.y(), pp.z(), gf, pnew.x(), pnew.y());
_current->bl_data = new MVertexBoundaryLayerData;
_column.push_back(_current);
int ith = _column.size();
L += hwall * pow(blf->ratio, ith);
}
_columns->addColumn(n, *it, _column /*,_metrics*/);
}
}
}
addedAdditionalPoints = true;
}
#if 0 // DEBUG STUFF
char name[256];
sprintf(name, "points_face_%d.pos", gf->tag());
FILE *f = Fopen(name,"w");
if(f){
fprintf(f,"View \"\" {\n");
for(std::set<MVertex*>::iterator it = _vertices.begin(); it != _vertices.end() ; ++it){
MVertex *v = *it;
for(int i=0;i<_columns->getNbColumns(v);i++){
const BoundaryLayerData &data = _columns->getColumn(v,i);
for(std::size_t j = 0; j < data._column.size(); j++){
MVertex *blv = data._column[j];
fprintf(f,"SP(%g,%g,%g){%d};\n",blv->x(),blv->y(),blv->z(),v->getNum());
}
}
}
fprintf(f,"};\n");
fclose(f);
}
#endif
return addedAdditionalPoints;
}
#endif
| 33.816856 | 91 | 0.543686 | [
"mesh",
"vector",
"model"
] |
07e0f447452a2184993885391de811666a362ac7 | 1,939 | cpp | C++ | strings-3.8.cpp | dazmodel/cpp-study | 169569b8e29eab209f15bec042c6aac014737356 | [
"MIT"
] | null | null | null | strings-3.8.cpp | dazmodel/cpp-study | 169569b8e29eab209f15bec042c6aac014737356 | [
"MIT"
] | null | null | null | strings-3.8.cpp | dazmodel/cpp-study | 169569b8e29eab209f15bec042c6aac014737356 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <iterator>
#include <vector>
#include <sstream>
using namespace std;
// Разделяем строку на части по заданному разделителю
vector<string> split(const string& s, char delimiter) {
vector<string> tokens;
string token;
istringstream tokenStream(s);
while (getline(tokenStream, token, delimiter))
{
tokens.push_back(token);
}
return tokens;
}
int main() {
// Читаем предложение, введенное пользователем в консоли
string text;
cout << "Bydem iskat slova, kotorie nahodiatsa mejdy slovami-granicami intervala poiska." << endl;
cout << "Naprimer, predlojenie: Y lykomoria dyb zelenii, zlataia tsep na dube tom." << endl;
cout << "Slovo-na4alo intervala: dyb" << endl;
cout << "Slovo-konec intervala: na" << endl;
cout << "Iskomij rezyltat: dub zelenii, zlataia tsep na" << endl;
cout << endl;
cout << "Vvedite predlojenie, razdelite slova probelami: " << endl;
getline(cin, text);
// Делим предложение на слова
vector<string> words = split(text, ' ');
cout << endl;
// Вводим слово-начало интервала
cout << "Vvedite slovo-na4alo intervala: " << endl;
string strBegin;
getline(cin, strBegin);
// Вводим слово-конец интервала
cout << "Vvedite slovo-konec intervala: " << endl;
string strEnd;
getline(cin, strEnd);
cout << endl;
// Вычисляем границы интервала
int intBegin = 0;
int intEnd = 0;
for (int i = 0; i < words.size(); i ++ ) {
if ( words[i].compare(strBegin) == 0) {
intBegin = text.find(strBegin);
}
if ( words[i].compare(strEnd) == 0) {
intEnd = text.find(strEnd);
}
}
// Печатаем результат
if ( intBegin != intEnd ) {
cout << "Iskomij interval: " << text.substr(intBegin, text.length() - intBegin - text.substr(intEnd, text.length() - 1).length() + strEnd.length()) << endl;
} else {
cout << "V zadannom intervale ni4ego ne naideno!" << endl;
}
return 0;
} | 26.202703 | 160 | 0.654977 | [
"vector"
] |
2e3ca7e67039154dff9ab35c919386fc7bf4325a | 3,862 | cpp | C++ | source/specializer.cpp | jhs67/autoshader | 170450d96d962cddff6d12e929a89a376a1716bd | [
"0BSD"
] | null | null | null | source/specializer.cpp | jhs67/autoshader | 170450d96d962cddff6d12e929a89a376a1716bd | [
"0BSD"
] | null | null | null | source/specializer.cpp | jhs67/autoshader | 170450d96d962cddff6d12e929a89a376a1716bd | [
"0BSD"
] | null | null | null | //
// File: specializer.cpp
//
// Created by Jon Spencer on 2019-05-14 11:36:50
// Copyright (c) Jon Spencer. See LICENSE file.
//
#include "specializer.h"
#include "shadersource.h"
#include "descriptorset.h"
namespace autoshader {
namespace {
auto writerSrc =
R"({0}struct {1}Specializer {{
{0} int32_t values[{2}];
{0} vk::SpecializationMapEntry map[{2}];
{0} uint32_t mapIndex;
{0} {1}Specializer() : mapIndex(0) {{}}
{0} std::pair<vk::ShaderStageFlags,vk::SpecializationInfo> info() {{
{0} return std::make_pair({3},
{0} vk::SpecializationInfo{{ mapIndex, map, mapIndex * sizeof(int32_t), values }});
{0} }}
)";
auto intSrc =
R"(
{0} {5}Specializer& set{1}({3} v) {{
{0} if (mapIndex >= {2})
{0} throw std::runtime_error("autoshader specializer overflow");
{0} values[mapIndex] = int32_t(v);
{0} map[mapIndex] = vk::SpecializationMapEntry{{ {4}, uint32_t(mapIndex * sizeof(int32_t)), sizeof(int32_t) }};
{0} ++mapIndex;
{0} return *this;
{0} }}
)";
auto floatSrc =
R"(
{0} {5}Specializer& set{1}({3} v) {{
{0} if (mapIndex >= {2})
{0} throw std::runtime_error("autoshader specializer overflow");
{0} memcpy(&values[mapIndex], &v, sizeof(int32_t));
{0} map[mapIndex] = vk::SpecializationMapEntry{{ {4}, uint32_t(mapIndex * sizeof(int32_t)), sizeof(int32_t) }};
{0} ++mapIndex;
{0} return *this;
{0} }}
)";
string capitalize(string s) {
if (s.size() > 0)
s[0] = toupper(s[0]);
return s;
}
void specializer_value(fmt::memory_buffer &r, spirv_cross::Compiler &comp,
const string &indent, size_t count, uint32_t id, const string &name,
uint32_t constantID, const string &specname) {
auto type = comp.get_type(comp.get_constant(id).constant_type);
if (type.basetype == spirv_cross::SPIRType::Float) {
format_to(r, floatSrc, indent, name, count, type_string(comp, type),
constantID, specname);
}
else {
format_to(r, intSrc, indent, name, count, type_string(comp, type),
constantID, specname);
}
}
void shader_specializer(fmt::memory_buffer &r, spirv_cross::Compiler &comp, string pre,
const string &indent) {
struct SpecToWrite {
uint32_t id;
string name;
};
// grab all the names specialization constants
std::map<uint32_t, SpecToWrite> specs;
auto consts = comp.get_specialization_constants();
for (auto &c : consts) {
auto n = comp.get_name(c.id);
if (n.empty())
continue;
specs.emplace(c.constant_id, SpecToWrite{ c.id, move(n) });
}
// group the workgroup size constants
spirv_cross::SpecializationConstant x, y, z;
comp.get_work_group_size_specialization_constants(x, y, z);
if (uint32_t(x.id) != 0 || x.constant_id != 0)
specs.emplace(x.constant_id, SpecToWrite{ x.id, "WorkGroupSizeX" });
if (uint32_t(y.id) != 0 || y.constant_id != 0)
specs.emplace(y.constant_id, SpecToWrite{ y.id, "WorkGroupSizeY" });
if (uint32_t(z.id) != 0 || z.constant_id != 0)
specs.emplace(z.constant_id, SpecToWrite{ z.id, "WorkGroupSizeZ" });
// common case - no specialization constant
if (specs.empty())
return;
format_to(r, writerSrc, indent, capitalize(pre), specs.size(),
get_shader_stage_flags(comp));
for (auto &t : specs) {
specializer_value(r, comp, indent, specs.size(),
t.second.id, t.second.name, t.first, capitalize(pre));
}
format_to(r, "{0}}};\n\n", indent);
}
}
//-------------------------------------------------------------------------------------------
//-- write out utility methods for creating vk::SpecializationInfo records.
void specializers(fmt::memory_buffer &r, vector<ShaderRecord> &sh,
const string &indent) {
for (auto &s : sh) {
shader_specializer(r, *s.comp, sh.size() == 1 ? "" : get_execution_string(*s.comp),
indent);
}
}
} // namespace autoshader
| 29.257576 | 114 | 0.630243 | [
"vector"
] |
2e42fa530c5a73efff70116dae0e3bcaa24ad4e9 | 3,952 | cpp | C++ | src/Pocket.cpp | Felipeasg/heekscad | 0b70cbeb998e864b1ea0af0685863f5a90da1504 | [
"BSD-3-Clause"
] | 2 | 2019-09-15T15:22:32.000Z | 2021-01-22T10:20:42.000Z | src/Pocket.cpp | Felipeasg/HeeksCAD | 0b70cbeb998e864b1ea0af0685863f5a90da1504 | [
"BSD-3-Clause"
] | null | null | null | src/Pocket.cpp | Felipeasg/HeeksCAD | 0b70cbeb998e864b1ea0af0685863f5a90da1504 | [
"BSD-3-Clause"
] | 1 | 2022-03-05T05:08:06.000Z | 2022-03-05T05:08:06.000Z | // Pocket.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "stdafx.h"
#include "Pocket.h"
#include "Shape.h"
#include "RuledSurface.h"
#include "../interface/PropertyDouble.h"
#include "Part.h"
HPocket::HPocket(double length)
{
m_length = length;
m_faces->m_visible=false;
}
HPocket::HPocket()
{
m_length = 0;
}
bool HPocket::IsDifferent(HeeksObj* other)
{
HPocket* pocket = (HPocket*)other;
if(pocket->m_length != m_length)
return true;
return HeeksObj::IsDifferent(other);
}
void HPocket::ReloadPointers()
{
DynamicSolid::ReloadPointers();
HeeksObj *child = GetFirstChild();
while(child)
{
CSketch* sketch = dynamic_cast<CSketch*>(child);
if(sketch)
{
m_sketch = sketch;
break;
}
child = GetNextChild();
}
Update();
}
gp_Trsf HPocket::GetTransform()
{
if(m_sketch && m_sketch->m_coordinate_system)
return m_sketch->m_coordinate_system->GetMatrix();
return gp_Trsf();
}
void HPocket::Update()
{
if(m_sketch)
{
std::vector<TopoDS_Face> faces = m_sketch->GetFaces();
std::list<TopoDS_Shape> facelist(faces.begin(),faces.end());
std::list<TopoDS_Shape> new_shapes;
CreateExtrusions(facelist, new_shapes, gp_Vec(0, 0, m_length), 0.0, true);
SetShapes(new_shapes);
}
DynamicSolid* solid = dynamic_cast<DynamicSolid*>(HEEKSOBJ_OWNER);
if(solid)
solid->Update();
}
void HPocket::glCommands(bool select, bool marked, bool no_color)
{
//TODO: only do this when the sketch is dirty
glPushMatrix();
if(m_sketch)
{
Update();
if(m_sketch->m_coordinate_system)
m_sketch->m_coordinate_system->ApplyMatrix();
// DrawShapes();
}
//Draw everything else
ObjList::glCommands(select,marked,no_color);
glPopMatrix();
}
void OnPocketSetHeight(double b, HeeksObj* o)
{
((HPocket*)o)->m_length = b;
wxGetApp().Repaint();
}
void HPocket::GetProperties(std::list<Property *> *list)
{
list->push_back(new PropertyDouble(_("Height"), m_length, this,OnPocketSetHeight));
ObjList::GetProperties(list);
}
void HPocket::WriteXML(TiXmlNode *root)
{
TiXmlElement * element = new TiXmlElement( "Pad" );
return;
root->LinkEndChild( element );
// instead of ObjList::WriteBaseXML(element), write the id of solids, or the object
std::list<HeeksObj*>::iterator It;
for(It=m_objects.begin(); It!=m_objects.end() ;It++)
{
HeeksObj* object = *It;
if(CShape::IsTypeAShape(object->GetType()))
{
TiXmlElement* solid_element = new TiXmlElement( "solid" );
element->LinkEndChild( solid_element );
solid_element->SetAttribute("id", object->m_id);
}
object->WriteXML(element);
}
HeeksObj::WriteBaseXML(element);
}
// static member function
HeeksObj* HPocket::ReadFromXMLElement(TiXmlElement* element)
{
HPocket* new_object = new HPocket;
return new_object;
#if 0
// instead of ( ObjList:: ) new_object->ReadBaseXML(pElem);
// loop through all the objects
for(TiXmlElement* pElem = TiXmlHandle(element).FirstChildElement().Element(); pElem; pElem = pElem->NextSiblingElement())
{
std::string name(pElem->Value());
if(name == "solid")
{
int id = 0;
pElem->Attribute("id", &id);
}
else
{
// load other objects normal
HeeksObj* object = wxGetApp().ReadXMLElement(pElem);
if(object)new_object->Add(object, NULL);
}
}
new_object->HeeksObj::ReadBaseXML(element);
return (ObjList*)new_object;
#endif
}
// static
void HPocket::PocketSketch(CSketch* sketch, double length)
{
HPocket *pad = new HPocket(length);
sketch->HEEKSOBJ_OWNER->Add(pad,NULL);
sketch->HEEKSOBJ_OWNER->Remove(sketch);
#ifdef MULTIPLE_OWNERS
sketch->RemoveOwner(sketch->Owner());
#else
sketch->m_owner = NULL;
#endif
sketch->m_draw_with_transform = false;
pad->Add(sketch,NULL);
pad->ReloadPointers();
}
| 22.202247 | 123 | 0.674089 | [
"object",
"shape",
"vector",
"solid"
] |
2e473622e50718adf99bc8c398a3321dc460864f | 47,098 | hpp | C++ | need to install for velocity smothor/ecl_utilities/include/ecl/utilities/function_objects.hpp | michaelczhou/control | c5ee58bf65c7d8e7517659a52169cea3e4e81d46 | [
"MIT"
] | 1 | 2022-03-11T03:31:15.000Z | 2022-03-11T03:31:15.000Z | RasPi_Dev/ros_ws/src/third_packages/ecl/ecl_utilities/include/ecl/utilities/function_objects.hpp | bravetree/xtark_driver_dev | 1708888161cf20c0d1f45c99d0da4467d69c26c8 | [
"BSD-3-Clause"
] | null | null | null | RasPi_Dev/ros_ws/src/third_packages/ecl/ecl_utilities/include/ecl/utilities/function_objects.hpp | bravetree/xtark_driver_dev | 1708888161cf20c0d1f45c99d0da4467d69c26c8 | [
"BSD-3-Clause"
] | null | null | null | /**
* @file /include/ecl/utilities/function_objects.hpp
*
* @brief Functional objects and generators.
*
* @date June 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef ECL_UTILITIES_FUNCTION_OBJECTS_HPP_
#define ECL_UTILITIES_FUNCTION_OBJECTS_HPP_
/*****************************************************************************
** Includes
*****************************************************************************/
#include <ecl/concepts/nullary_function.hpp>
#include "../utilities/references.hpp"
/*****************************************************************************
** Namespaces
*****************************************************************************/
namespace ecl {
/*****************************************************************************
** Using
*****************************************************************************/
/*****************************************************************************
** Interface [NullaryFunction]
*****************************************************************************/
/**
* @brief Virtual interface definition for nullary function objects.
*
* Virtual interface definition for nullary function objects (i.e. functions
* that take no arguments).
*
* @tparam R : the return type.
*
* @sa @ref functionobjectsGuide "FunctionObjects".
*/
template <typename R = void>
class NullaryFunction {
public:
typedef R result_type; /**< @brief The result type. **/
virtual result_type operator()() = 0; /**< @brief Virtual function call required by nullary function objects. **/
virtual ~NullaryFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/
};
/*****************************************************************************
** Interface [UnaryFunction]
*****************************************************************************/
/**
* @brief Virtual interface definition for unary function objects.
*
* Virtual interface definition for unary function objects (i.e. functions
* that take a single arguments).
*
* @tparam A : the argument type.
* @tparam R : the return type.
*
* @sa @ref functionobjectsGuide "FunctionObjects".
*/
template <typename A, typename R = void>
class UnaryFunction {
public:
typedef R result_type; /**< @brief The result type. **/
typedef A argument_type; /**< @brief The first argument type. **/
/**
* @brief Virtual function call required by unary function objects.
* @param arg : the argument.
**/
virtual result_type operator()(argument_type arg) = 0; /**<@brief Virtual function call required by unary function objects. **/
virtual ~UnaryFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/
};
/*****************************************************************************
** Interface [BinaryFunction]
*****************************************************************************/
/**
* @brief Virtual interface definition for binary function objects.
*
* Virtual interface definition for binary function objects (i.e. functions
* that take a pair of arguments).
*
* @tparam R : the return type.
* @tparam A1 : the first argument type.
* @tparam A2 : the second argument type.
*
* @sa @ref functionobjectsGuide "FunctionObjects".
*/
template <typename A1, typename A2, typename R = void>
class BinaryFunction {
public:
typedef R result_type; /**< @brief The result type. **/
typedef A1 first_argument_type; /**< @brief The first argument type. **/
typedef A2 second_argument_type; /**< @brief The second argument type. **/
/**
* @brief Virtual function call required by binary function objects.
*
* Virtual function call required by binary function objects.
* @param arg1 : the first argument.
* @param arg2 : the second argument.
**/
virtual result_type operator()(first_argument_type arg1, second_argument_type arg2) = 0; /**<@brief Virtual function call required by binary function objects. **/
virtual ~BinaryFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/
};
/*****************************************************************************
** Interface [FreeFunctions]
*****************************************************************************/
/**
* @brief Nullary function object for void global/static functions.
*
* Creates a function object from a void global/static function.
*
* @tparam R : the return type.
*
* @sa ecl::utilities::NullaryFreeFunction<void>, generateFunctionObject, @ref functionobjectsGuide "FunctionObjects".
*/
template <typename R = void>
class NullaryFreeFunction : public NullaryFunction<R>
{
public:
/**
* @brief Nullary function object constructor for global/static functions with no args.
*
* Accepts a global/static function with no args and builds the function object around it.
*
* @param function : the global/static function.
*/
NullaryFreeFunction( R (*function)() ) : free_function(function) {}
virtual ~NullaryFreeFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/
/**
* @brief A nullary function object call.
*
* Redirects the nullary function object call to the composited global/static function.
*
* @return R : the function's return value.
*/
R operator()() { return free_function(); }
private:
R (*free_function)();
};
/**
* @brief Specialisation for free nullary functions that return void.
*
* Specialisation for free nullary functions that return void.
*
* @sa NullaryFreeFunction, generateFunctionObject, @ref functionobjectsGuide "FunctionObjects".
*/
template <>
class NullaryFreeFunction<void> : public NullaryFunction<void>
{
public:
/**
* @brief Nullary function object constructor for void global/static functions with no args.
*
* Accepts a void global/static function with no args and builds the function object around it.
*
* @param function : the global/static function.
*/
NullaryFreeFunction( void (*function)() ) : free_function(function) {}
virtual ~NullaryFreeFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/
/**
* @brief A nullary function object call.
*
* Redirects the nullary function object call to the composited global/static function.
*
* @return R : the function's return value.
*/
void operator()() { free_function(); }
private:
void (*free_function)();
};
/**
* @brief Unary function object for global/static functions.
*
* Creates a function object from a global/static function with a single argument.
*
* @sa generateFunctionObject
*
* @tparam A : the argument type.
* @tparam R : the return type.
*
* @sa @ref functionobjectsGuide "FunctionObjects".
*/
template <typename A, typename R = void>
class UnaryFreeFunction : public UnaryFunction<A,R>
{
public:
/**
* @brief Unary function object constructor for global/static functions.
*
* Accepts a global/static function with a single argument and builds
* the function object around it.
*
* @param function : a global/static function with a single argument.
*/
UnaryFreeFunction( R (*function)(A) ) : free_function(function) {}
virtual ~UnaryFreeFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/
/**
* @brief A unary function object call.
*
* Redirects the unary function object call to the composited global/static function.
*
* @return R : the function's return value.
*/
R operator()(A a) { return free_function(a); }
private:
R (*free_function)(A);
};
/**
* @brief Specialisations for free unary functions with no return type.
*
* Specialisations for free unary functions with no return type.
*
* @tparam A : the argument type.
*
* @sa ecl::utilities::UnaryFreeFunction, generateFunctionObject, @ref functionobjectsGuide "FunctionObjects".
*/
template <typename A>
class UnaryFreeFunction<A,void> : public UnaryFunction<A,void>
{
public:
/**
* @brief Unary function object constructor for global/static unary functions with no return type.
*
* Accepts a void global/static function with a single argument and builds
* the function object around it.
*
* @param function : a global/static function with a single argument.
*/
UnaryFreeFunction( void (*function)(A) ) : free_function(function) {}
virtual ~UnaryFreeFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/
/**
* @brief A unary function object call.
*
* Redirects the unary function object call to the composited void global/static function.
*
* @return R : the function's return value.
*/
void operator()(A a) { free_function(a); }
private:
void (*free_function)(A);
};
/*****************************************************************************
** Interface [BoundFreeFunctions]
*****************************************************************************/
/**
* @brief Nullary function object for bound unary global/static functions.
*
* Binds the argument to a unary global/static function and uses this to
* construct a nullary function object.
*
* <b>Usage: </b>
* @code
* void f(int i) {}
*
* int main() {
* BoundUnaryFreeFunction<int,void> function_object(f,1);
* function_object();
* }
* @endcode
*
* Note, often the use of generateFunctionObject is simpler.
*
* @tparam A : the type of the argument to be bound.
* @tparam R : the return type.
*
* @sa ecl::utilities::BoundUnaryFreeFunction<A,void>, generateFunctionObject, @ref functionobjectsGuide "FunctionObjects".
*/
template <typename A, typename R = void>
class BoundUnaryFreeFunction : public NullaryFunction<R>
{
public:
/**
* @brief Binds a unary function and creates a nullary function object.
*
* Accepts both the function and a value for its single argument, binds them
* and creates a nullary function object.
* @param function : the unary global/static function.
* @param a : the argument to bind.
*/
BoundUnaryFreeFunction( R (*function)(A), A a ) : free_function(function), argument(a) {}
virtual ~BoundUnaryFreeFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/
/**
* @brief A nullary function object call.
*
* Redirects the function object call to the bound global/static function.
*
* @return R : the function's return value.
*/
R operator()() { return free_function(argument); }
private:
R (*free_function)(A);
A argument;
};
/**
* @brief Specialisation for bound void unary functions.
*
* Specialises BoundUnaryFreeFunction for functions with no return type.
*
* @tparam A : the type of the argument to be bound.
*
* @sa ecl::utilities::BoundUnaryFreeFunction, generateFunctionObject, @ref functionobjectsGuide "FunctionObjects".
*/
template <typename A>
class BoundUnaryFreeFunction<A,void> : public NullaryFunction<void>
{
public:
/**
* @brief Binds a unary function and creates a nullary function object.
*
* Accepts both the function and a value for its single argument, binds them
* and creates a nullary function object.
* @param function : the unary global/static function.
* @param a : the argument to bind.
*/
BoundUnaryFreeFunction( void (*function)(A), A a ) : free_function(function), argument(a) {}
virtual ~BoundUnaryFreeFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/
/**
* @brief A nullary function object call.
*
* Redirects the nullary function object call to the bound global/static function.
*
* @return void : the function's return value.
*/
void operator()() { free_function(argument); }
private:
void (*free_function)(A);
A argument;
};
/*****************************************************************************
* Interface [MemberFunctions]
*****************************************************************************
* Could make copies+refs here, just like mem_fun and mem_fun_ref but I can't
* see the need for copy style setups.
****************************************************************************/
/**
* @brief Unary function object for member functions without arguments.
*
* Creates a function object from a member function without arguments
* (note, the single argument to this unary function object is the class
* instance itself).
*
* <b>Usage: </b>
* @code
* class A {
* public:
* void f() { //...
* }
* };
*
* int main() {
* A a;
* NullaryMemberFunction<A,void> function_object(&A::f);
* function_object(a);
* }
* @endcode
*
* @tparam C : the member function's class type type.
* @tparam R : the return type.
*
* @sa ecl::utilities::NullaryMemberFunction<C,void>, generateFunctionObject, @ref functionobjectsGuide "FunctionObjects".
*/
template <typename C, typename R = void>
class NullaryMemberFunction : public UnaryFunction<C&,R> {
public:
/**
* @brief Unary function object constructor for member functions without arguments.
*
* Accepts a void member function, and builds
* the function object around it.
*
* @param function : a void member function.
*/
NullaryMemberFunction( R (C::*function)()) : member_function(function) {}
virtual ~NullaryMemberFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/
/**
* @brief A unary function object call.
*
* Uses the specified class instance to redirect the function call to the
* void member function.
*
* @param class_object : the member function's class instance.
* @return R : the function's return value.
*/
R operator()(C &class_object) {
return (class_object.*member_function)();
}
private:
R (C::*member_function)();
};
/**
* @brief Specialisation of the unary function object for void member functions without arguments.
*
* Specialisation for a function object from a void member function without arguments (note, the single
* argument to this unary function object is the class instance itself).
*
* @tparam C : the member function's class type type.
*
* @sa ecl::utilities::NullaryMemberFunction, generateFunctionObject, @ref functionobjectsGuide "FunctionObjects".
*/
template <typename C>
class NullaryMemberFunction<C,void> : public UnaryFunction<C&,void> {
public:
/**
* @brief Unary function object constructor for void member functions.
*
* Accepts a void member function without arguments, and builds
* the function object around it.
*
* @param function : a void member function.
*/
NullaryMemberFunction( void (C::*function)()) : member_function(function) {}
virtual ~NullaryMemberFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/
/**
* @brief A unary function object call.
*
* Uses the specified class instance to redirect the function call to the
* void member function.
*
* @param class_object : the member function's class instance.
*/
void operator()(C &class_object) {
(class_object.*member_function)();
}
private:
void (C::*member_function)();
};
/**
* @brief Binary function object for unary member functions.
*
* Creates a function object from a unary member function.
*
* <b>Usage: </b>
* @code
* class A {
* public:
* void f(int i) { //...
* }
* };
*
* int main() {
* A a;
* UnaryMemberFunction<A,int,void> function_object(&A::f);
* function_object(a,1);
* }
* @endcode
*
* @tparam C : the member function's class type.
* @tparam A : the member function's argument type.
* @tparam R : the return type.
*
* @sa ecl::utilities::UnaryMemberFunction<C,A,void>, generateFunctionObject, @ref functionobjectsGuide "FunctionObjects".
*/
template <typename C, typename A, typename R = void>
class UnaryMemberFunction : public BinaryFunction<C&,A,R> {
public:
/**
* @brief Binary function object constructor for unary member functions.
*
* Accepts a unary member function, and builds
* the function object around it.
*
* @param function : a unary member function.
*/
UnaryMemberFunction( R (C::*function)(A)) : member_function(function) {}
virtual ~UnaryMemberFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/
/**
* @brief A binary function object call.
*
* Uses the specified class instance and argument to redirect the function call to the
* unary member function.
*
* @param class_object : the member function's class instance.
* @param a : the member function's argument value.
* @return R : the function's return value.
*/
R operator()(C &class_object, A a) {
return (class_object.*member_function)(a);
}
private:
R (C::*member_function)(A);
};
/**
* @brief Specialisation of the binary function object for void unary member functions.
*
* Specialises the binary member function object for void member functions.
*
* @tparam C : the member function's class type.
* @tparam A : the member function's argument type.
*
* @sa ecl::utilities::UnaryMemberFunction @sa generateFunctionObject, @ref functionobjectsGuide "FunctionObjects".
*/
template <typename C, typename A>
class UnaryMemberFunction<C,A,void> : public BinaryFunction<C&,A,void> {
public:
/**
* @brief Binary function object constructor for unary member functions.
*
* Accepts a unary member function, and builds
* the function object around it.
*
* @param function : a unary member function.
*/
UnaryMemberFunction( void (C::*function)(A)) : member_function(function) {}
virtual ~UnaryMemberFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/
/**
* @brief A binary function object call.
*
* Uses the specified class instance and argument to redirect the function call to the
* unary member function.
*
* @param class_object : the member function's class instance.
* @param a : the member function's argument value.
* @return R : the function's return value.
*/
void operator()(C &class_object, A a) {
(class_object.*member_function)(a);
}
private:
void (C::*member_function)(A);
};
/*****************************************************************************
** Interface [BoundMemberFunctions]
*****************************************************************************/
/**
* @brief Nullary function object for bound nullary member functions.
*
* Binds the class instance for a nullary member function and uses this to
* construct a nullary function object.
*
* <b>Usage: </b>
* @code
* class A {
* public:
* void f() { //...
* }
*
* int main() {
* A a;
* BoundNullaryMemberFunction<A,void> function_object(&A::f,a);
* function_object();
* }
* @endcode
*
* @tparam C : the member function's class type.
* @tparam R : the return type.
*
* @sa ecl::utilities::BoundNullaryMemberFunction<C,void>, generateFunctionObject, @ref functionobjectsGuide "FunctionObjects".
*/
template <typename C, typename R = void>
class BoundNullaryMemberFunction : public NullaryFunction<R> {
public:
/**
* @brief Binds a unary member function and creates a nullary function object.
*
* Accepts the function pointer and class instance, binds them
* and creates a nullary function object.
* @param function : the void member function.
* @param class_object : the member function's class instance.
*/
BoundNullaryMemberFunction( R (C::*function)(), C &class_object) :
member_class(class_object),
member_function(function)
{}
virtual ~BoundNullaryMemberFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/
/**
* @brief A nullary function object call.
*
* Redirects the nullary function object call to the bound member function.
*
* @return R : the function's return value.
*/
R operator()() { return (member_class.*member_function)(); }
private:
C &member_class;
R (C::*member_function)();
};
/**
* @brief Specialisation of the bound nullary member function for void functions.
*
* Binds the class instance for a nullary member function and uses this to
* construct a nullary function object. This is the specialisation for nullary
* member functions with void return type.
*
* @tparam C : the member function's class type.
*
* @sa ecl::utilities::BoundNullaryMemberFunction, generateFunctionObject, @ref functionobjectsGuide "FunctionObjects".
*/
template <typename C>
class BoundNullaryMemberFunction<C,void> : public NullaryFunction<void> {
public:
/**
* @brief Binds a unary member function and creates a nullary function object.
*
* Accepts the function pointer and class instance, binds them
* and creates a nullary function object.
* @param function : the void member function.
* @param class_object : the member function's class instance.
*/
BoundNullaryMemberFunction( void (C::*function)(), C &class_object) :
member_class(class_object),
member_function(function)
{}
virtual ~BoundNullaryMemberFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/
/**
* @brief A nullary function object call.
*
* Redirects the nullary function object call to the bound member function.
*/
void operator()() { (member_class.*member_function)(); }
private:
C &member_class;
void (C::*member_function)();
};
/**
* @brief Unary function object for partially bound unary member functions.
*
* Binds the class instance but not the argument for a unary member function and uses this to
* construct a unary function object.
*
* <b>Usage: </b>
* @code
* class A {
* public:
* void f(int i) { //...
* }
*
* int main() {
* A a;
* PartiallyBoundUnaryMemberFunction<A,int,void> function_object(&A::f,a);
* function_object(1);
* }
* @endcode
*
* @sa generateFunctionObject
*
* @tparam C : the member function's class type.
* @tparam A : the member function's argument type.
* @tparam R : the return type.
*
* @sa @ref functionobjectsGuide "FunctionObjects".
*/
template <typename C, typename A, typename R = void>
class PartiallyBoundUnaryMemberFunction : public UnaryFunction<A,R> {
public:
/**
* @brief Binds a unary member function and creates a nullary function object.
*
* Accepts the function, class instance only (not the argument), binds them
* and creates a unary function object.
* @param function : the unary global/static function.
* @param class_object : the member function's class instance.
*/
PartiallyBoundUnaryMemberFunction( R (C::*function)(A), C &class_object) :
member_class(class_object),
member_function(function)
{}
virtual ~PartiallyBoundUnaryMemberFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/
/**
* @brief A unary function object call.
*
* Redirects the unary function object call to the bound member function.
*
* @param a : the argument passed to the function.
* @return R : the function's return value.
*/
R operator()(A a) {
return (member_class.*member_function)(a);
}
private:
C &member_class;
void (C::*member_function)(A);
};
/**
* @brief Nullary function object for bound unary member functions.
*
* Binds the class instance and argument for a unary member function and uses this to
* construct a nullary function object.
*
* <b>Usage: </b>
* @code
* class A {
* public:
* void f(int i) { //...
* }
*
* int main() {
* A a;
* BoundUnaryMemberFunction<A,int,void> function_object(&A::f,a,1);
* function_object();
* }
* @endcode
*
* @sa generateFunctionObject
*
* @tparam C : the member function's class type.
* @tparam A : the member function's argument type.
* @tparam R : the return type.
*
* @sa @ref functionobjectsGuide "FunctionObjects".
*/
template <typename C, typename A, typename R = void>
class BoundUnaryMemberFunction : public NullaryFunction<R> {
public:
/**
* @brief Binds a unary member function and creates a nullary function object.
*
* Accepts the function, class instance and a value for its single argument, binds them
* and creates a nullary function object.
* @param function : the unary global/static function.
* @param class_object : the member function's class instance.
* @param a : the value of the argument to bind.
*/
BoundUnaryMemberFunction( R (C::*function)(A), C &class_object, A a) :
member_class(class_object),
member_function(function),
argument(a)
{}
virtual ~BoundUnaryMemberFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/
/**
* @brief A nullary function object call.
*
* Redirects the nullary function object call to the bound member function.
*
* @return R : the function's return value.
*/
R operator()() {
return (member_class.*member_function)(argument);
}
private:
C &member_class;
void (C::*member_function)(A);
A argument;
};
/**
* @brief Binary function object for partially bound binary member functions.
*
* Binds the class instance but not the arguments for a binary member function and uses this to
* construct a binary function object.
*
* <b>Usage: </b>
* @code
* class A {
* public:
* void f(int i, string n) { //...
* }
*
* int main() {
* A a;
* PartiallyBoundBinaryMemberFunction<A,int,string,void> function_object(&A::f,a);
* function_object(1,"dude");
* }
* @endcode
*
* @sa generateFunctionObject
*
* @tparam C : the member function's class type.
* @tparam A : the member function's first argument type.
* @tparam B : the member function's second argument type.
* @tparam R : the return type.
*
* @sa @ref functionobjectsGuide "FunctionObjects".
*/
template <typename C, typename A, typename B, typename R = void>
class PartiallyBoundBinaryMemberFunction : public BinaryFunction<A,B,R> {
public:
/**
* @brief Binds a binary member function and creates a binary function object.
*
* Accepts the function, class instance only (not the arguments), binds them
* and creates a binary function object.
* @param function : the unary global/static function.
* @param class_object : the member function's class instance.
*/
PartiallyBoundBinaryMemberFunction( R (C::*function)(A, B), C &class_object) :
member_class(class_object),
member_function(function)
{}
virtual ~PartiallyBoundBinaryMemberFunction() {}; /**< @brief This ensures any children objects are deleted correctly. **/
/**
* @brief A binary function object call.
*
* Redirects the binary function object call to the bound member function.
*
* @param a : the first argument passed to the function (type A).
* @param b : the second argument passed to the function (type B).
* @return R : the function's return value.
*/
R operator()(A a, B b) {
return (member_class.*member_function)(a, b);
}
private:
C &member_class;
void (C::*member_function)(A, B);
};
/*****************************************************************************
** Function Object Wrappers
*****************************************************************************/
/**
* @brief Create a NullaryFunction object composited from an existing function object.
*
* Takes a nullary function object (strictly by definition) and creates a
* NullaryFunction child object. This
* is useful in utilising the inheritance from NullaryFunction (needed for slots
* and similar classes).
*
* @tparam FunctionObject : type of the function object to be wrapped.
* @tparam R : the return type.
*
* @sa @ref functionobjectsGuide "FunctionObjects".
*/
template <typename FunctionObject, typename Result = void>
class NullaryFunctionCopy : public NullaryFunction<Result>
{
public:
/**
* @brief NullaryFunction child constructor for nullary function objects.
*
* Creates a child of the NullaryFunction class by copying a nullary function
* object (one that is purely by definition).
*
* @param f_o : the function object to be assigned to the NullaryFunction child.
*/
NullaryFunctionCopy(const FunctionObject &f_o ) : function_object(f_o) {
ecl_compile_time_concept_check(NullaryFunction<FunctionObject>);
}
virtual ~NullaryFunctionCopy() {}; /**< @brief This ensures any children objects are deleted correctly. **/
/**
* @brief The nullary function object call.
*
* Redirects the call to the composited nullary function object call.
*
* @return R : the function's return value.
*/
Result operator()() { return function_object(); }
private:
FunctionObject function_object;
};
/**
* @brief Specialisation of NullaryFunctionCopy for void return types.
*
* Specialises the NullaryFunctionCopy class for void return types.
*
* @tparam FunctionObject : type of the function object to be wrapped.
*
* @sa @ref functionobjectsGuide "FunctionObjects".
*/
template <typename FunctionObject>
class NullaryFunctionCopy<FunctionObject,void> : public NullaryFunction<void>
{
public:
/**
* @brief NullaryFunction child constructor for nullary function objects.
*
* Creates a child of the NullaryFunction class by copying a nullary function
* object (one that is purely by definition).
*
* @param f_o : the function object to be assigned to the NullaryFunction child.
*/
explicit NullaryFunctionCopy( const FunctionObject &f_o ) : function_object(f_o) {
ecl_compile_time_concept_check(NullaryFunction<FunctionObject>);
}
virtual ~NullaryFunctionCopy() {}; /**< @brief This ensures any children objects are deleted correctly. **/
/**
* @brief The nullary function object call.
*
* Redirects the call to the composited nullary function object call.
*/
void operator()() { function_object(); }
private:
FunctionObject function_object;
};
/**
* @brief Creates a nullary function from a reference wrapper.
*
* Takes a reference wrapper containing a nullary function (strictly by definition) object
* reference and creates a NullaryFunction descendant. This
* is useful in utilising the inheritance from NullaryFunction (needed for slots
* and similar classes).
*
* @tparam FunctionObject : type of the function object to be referenced.
* @tparam Result : the return type of the nullary function.
*
* @sa NullaryFunctionReference<FunctionObject,void>, @ref functionobjectsGuide "FunctionObjects".
*/
template <typename FunctionObject, typename Result = void>
class NullaryFunctionReference : public NullaryFunction<Result>
{
public:
/**
* @brief Creates a NullaryFunction descendant from a reference wrapper.
*
* Creates a NullaryFunction descendant by reference (not copying).
*
* @param wrapper : the reference wrapper holding the nullary function object to be referenced.
*/
explicit NullaryFunctionReference( const ReferenceWrapper<FunctionObject> &wrapper ) : function_object(wrapper.reference()) {
ecl_compile_time_concept_check(NullaryFunction<FunctionObject>);
}
virtual ~NullaryFunctionReference() {}; /**< @brief This ensures any children objects are deleted correctly. **/
/**
* @brief The nullary function object call.
*
* Redirects the call to the referenced nullary function object call.
*
* @return R : the function's return value.
*/
Result operator()() { return function_object(); }
private:
FunctionObject &function_object;
};
/**
* @brief Creates a void nullary function from a reference wrapper.
*
* Takes a reference wrapper containing a nullary function (strictly by definition) object
* reference and creates a NullaryFunction descendant. This
* is a specialisation which caters to nullary function objects with void return type.
*
* @tparam FunctionObject : type of the function object to be referenced.
*
* @sa NullaryFunctionReference, @ref functionobjectsGuide "FunctionObjects".
*/
template <typename FunctionObject>
class NullaryFunctionReference< FunctionObject, void > : public NullaryFunction<void>
{
public:
/**
* @brief Creates a NullaryFunction descendant from a reference wrapper.
*
* Creates a NullaryFunction descendant by reference (not copying).
*
* @param wrapper : the reference wrapper holding the nullary function object to be referenced.
*/
explicit NullaryFunctionReference( const ReferenceWrapper<FunctionObject> &wrapper ) : function_object(wrapper.reference()) {
ecl_compile_time_concept_check(NullaryFunction<FunctionObject>);
}
virtual ~NullaryFunctionReference() {}; /**< @brief This ensures any children objects are deleted correctly. **/
/**
* @brief The nullary function object call.
*
* Redirects the call to the referenced nullary function object call.
*/
void operator()() { function_object(); }
private:
FunctionObject &function_object;
};
/**
* @brief Create a UnaryFunction object composited from an existing function object.
*
* Takes a unary function object (strictly by definition) and creates a
* UnaryFunction child object. This
* is useful in utilising the inheritance from UnaryFunction (needed for slots
* and similar classes).
*
* @tparam FunctionObject : type of the function object to be wrapped.
* @tparam T : the unary data type.
* @tparam R : the return type.
*
* @sa @ref functionobjectsGuide "FunctionObjects".
*/
template <typename FunctionObject, typename T, typename Result = void>
class UnaryFunctionCopy : public UnaryFunction<T, Result>
{
public:
/**
* @brief UnaryFunction child constructor for unary function objects.
*
* Creates a child of the UnaryFunction class by copying a unary function
* object (one that is purely by definition).
*
* @param f_o : the function object to be assigned to the UnaryFunction child.
*/
UnaryFunctionCopy(const FunctionObject &f_o ) : function_object(f_o) {
// ecl_compile_time_concept_check(UnaryFunction<FunctionObject>);
}
virtual ~UnaryFunctionCopy() {}; /**< @brief This ensures any children objects are deleted correctly. **/
/**
* @brief The unary function object call.
*
* Redirects the call to the composited nullary function object call.
*
* @return R : the function's return value.
*/
Result operator()(T t) { return function_object(t); }
private:
FunctionObject function_object;
};
/**
* @brief Specialisation of UnaryFunctionCopy for void return types.
*
* Specialises the UnaryFunctionCopy class for void return types.
*
* @tparam FunctionObject : type of the function object to be wrapped.
*
* @sa @ref functionobjectsGuide "FunctionObjects".
*/
template <typename FunctionObject, typename T>
class UnaryFunctionCopy<FunctionObject,T,void> : public UnaryFunction<T, void>
{
public:
/**
* @brief UnaryFunction child constructor for unary function objects.
*
* Creates a child of the UnaryFunction class by copying a unary function
* object (one that is purely by definition).
*
* @param f_o : the function object to be assigned to the UnaryFunction child.
*/
explicit UnaryFunctionCopy( const FunctionObject &f_o ) : function_object(f_o) {
// ecl_compile_time_concept_check(UnaryFunction<FunctionObject>);
}
virtual ~UnaryFunctionCopy() {}; /**< @brief This ensures any children objects are deleted correctly. **/
/**
* @brief The unary function object call.
*
* Redirects the call to the composited unary function object call.
*/
void operator()(T t) { function_object(t); }
private:
FunctionObject function_object;
};
/**
* @brief Creates a unary function from a reference wrapper.
*
* Takes a reference wrapper containing a unary function (strictly by definition) object
* reference and creates a UnaryFunction descendant. This
* is useful in utilising the inheritance from UnaryFunction (needed for slots
* and similar classes).
*
* @tparam FunctionObject : type of the function object to be referenced.
* @tparam Result : the return type of the unary function.
*
* @sa UnaryFunctionReference<FunctionObject,void>, @ref functionobjectsGuide "FunctionObjects".
*/
template <typename FunctionObject, typename T, typename Result = void>
class UnaryFunctionReference : public UnaryFunction<T, Result>
{
public:
/**
* @brief Creates a UnaryFunction descendant from a reference wrapper.
*
* Creates a UnaryFunction descendant by reference (not copying).
*
* @param wrapper : the reference wrapper holding the unary function object to be referenced.
*/
explicit UnaryFunctionReference( const ReferenceWrapper<FunctionObject> &wrapper ) : function_object(wrapper.reference()) {
// ecl_compile_time_concept_check(UnaryFunction<FunctionObject>);
}
virtual ~UnaryFunctionReference() {}; /**< @brief This ensures any children objects are deleted correctly. **/
/**
* @brief The unary function object call.
*
* Redirects the call to the referenced unary function object call.
*
* @return R : the function's return value.
*/
Result operator()(T t) { return function_object(t); }
private:
FunctionObject &function_object;
};
/**
* @brief Creates a void unary function from a reference wrapper.
*
* Takes a reference wrapper containing a unary function (strictly by definition) object
* reference and creates a UnaryFunction descendant. This
* is a specialisation which caters to unary function objects with void return type.
*
* @tparam FunctionObject : type of the function object to be referenced.
*
* @sa UnaryFunctionReference, @ref functionobjectsGuide "FunctionObjects".
*/
template <typename ReferenceWrapper, typename T>
class UnaryFunctionReference< ReferenceWrapper, T, void > : public UnaryFunction<T,void>
{
public:
typedef typename ReferenceWrapper::type FunctionObject; /**< The wrapper's function object reference type. **/
/**
* @brief Creates a UnaryFunction descendant from a reference wrapper.
*
* Creates a UnaryFunction descendant by reference (not copying).
*
* @param wrapper : the reference wrapper holding the unary function object to be referenced.
*/
explicit UnaryFunctionReference( const ReferenceWrapper &wrapper ) : function_object(wrapper.reference()) {
// ecl_compile_time_concept_check(UnaryFunction<FunctionObject>);
}
virtual ~UnaryFunctionReference() {}; /**< @brief This ensures any children objects are deleted correctly. **/
/**
* @brief The unary function object call.
*
* Redirects the call to the referenced unary function object call.
*/
void operator()(T t) { function_object(t); }
private:
FunctionObject &function_object;
};
/*****************************************************************************
** Nullary Function Generators
*****************************************************************************/
/**
* @brief Generate a nullary function object from a void global/static function.
*
* Overloaded function type, this particular overload generates a nullary
* function object from a void global/static function.
*
* @tparam R : the return type.
* @param function : the void global/static function.
* @return NullaryFreeFunction<R> : nullary function object.
*
* @sa @ref functionobjectsGuide "FunctionObjects".
*/
template <typename R>
NullaryFreeFunction<R> generateFunctionObject( R (*function)() ) {
return NullaryFreeFunction<R>( function );
}
/**
* @brief Generate a unary function object from a unary global/static function.
*
* Overloaded function type, this particular overload generates a unary
* function object from a unary global/static function.
*
* @tparam A : the function's argument type.
* @tparam R : the function's return type.
* @param function : the unary global/static function.
* @return UnaryFreeFunction<R> : unary function object.
*
* @sa @ref functionobjectsGuide "FunctionObjects".
*/
template <typename A, typename R>
UnaryFreeFunction<A,R> generateFunctionObject( R (*function)(A) ) {
return UnaryFreeFunction<A,R>( function );
}
/**
* @brief Generate a nullary function object from a bound unary global/static function.
*
* Overloaded function type, this particular overload generates a nullary
* function object from a bound unary global/static function.
*
* @tparam A : the function's argument type.
* @tparam R : the return type.
* @tparam I : a mask for the function's argument type.
* @param function : the void global/static function.
* @param a : the argument value to bind.
* @return BoundUnaryFreeFunction<A,R> : nullary function object.
*
* @sa @ref functionobjectsGuide "FunctionObjects".
*/
template <typename A, typename R, typename I>
BoundUnaryFreeFunction<A,R> generateFunctionObject( R (*function)(A), I& a ) {
return BoundUnaryFreeFunction<A,R>( function, a );
}
/**
* @brief Generate a nullary function object from a bound unary global/static function.
*
* Overloaded function type, this particular overload generates a nullary
* function object from a bound unary global/static function (with supplied const argument).
* The const argument bind allows for binding from temporaries.
*
* @tparam A : the function's argument type.
* @tparam R : the return type.
* @tparam I : a mask for the function's argument type.
* @param function : the void global/static function.
* @param a : the argument value to bind (const).
* @return BoundUnaryFreeFunction<A,R> : nullary function object.
*
* @sa @ref functionobjectsGuide "FunctionObjects".
*/
template <typename A, typename R, typename I>
BoundUnaryFreeFunction<A,R> generateFunctionObject( R (*function)(A), const I& a ) {
return BoundUnaryFreeFunction<A,R>( function, a );
}
/**
* @brief Generate a unary function object from a nullary member function.
*
* Overloaded function type, this particular overload generates a unary
* function object from a void member function.
*
* @tparam C : the member function's class type.
* @tparam R : the member function's return type.
* @param function : the void member function.
* @return NullaryMemberFunction<C,R> : unary function object.
*
* @sa @ref functionobjectsGuide "FunctionObjects".
*/
template <typename C, typename R>
NullaryMemberFunction<C,R> generateFunctionObject( R (C::*function)() ) {
return NullaryMemberFunction<C,R>( function );
}
/**
* @brief Generate a nullary function object by binding a nullary member function with its instance.
*
* Overloaded function type, this particular overload generates a nullary
* function object by binding the class instance to a void member function.
*
* @tparam C : the member function's class type.
* @tparam R : the member function's return type.
* @param function : the void member function.
* @param c : the member function's class instance.
* @return NullaryMemberFunction<C,R> : unary function object.
*
* @sa @ref functionobjectsGuide "FunctionObjects".
*/
template <typename C, typename R>
BoundNullaryMemberFunction<C,R> generateFunctionObject( R (C::*function)(), C &c ) {
return BoundNullaryMemberFunction<C,R>( function, c );
}
/**
* @brief Generate a binary function object from a unary member function.
*
* Overloaded function type, this particular overload generates a binary
* function object from a unary member function.
*
* @tparam C : the member function's class type.
* @tparam A : the member function's argument type.
* @tparam R : the member function's return type.
* @param function : the unary member function.
* @return UnaryMemberFunction<C,A,R> : binary function object.
*
* @sa @ref functionobjectsGuide "FunctionObjects".
*/
template <typename C, typename A, typename R>
UnaryMemberFunction<C,A,R> generateFunctionObject( R (C::*function)(A) ) {
return UnaryMemberFunction<C,A,R>( function );
}
/**
* @brief Generate a unary function object by partially binding a unary member function.
*
* Overloaded function type, this particular overload generates a unary
* function object by binding the class instance but not the argument to
* a unary member function.
*
* @tparam C : the member function's class type.
* @tparam A : the member function's argument type.
* @tparam R : the member function's return type.
*
* @param function : the void member function.
* @param c : the member function's class instance.
* @return PartiallyBoundUnaryMemberFunction<C,R> : nullary function object.
*
* @sa @ref functionobjectsGuide "FunctionObjects".
*/
template <typename C, typename A, typename R>
PartiallyBoundUnaryMemberFunction<C,A,R> generateFunctionObject( R (C::*function)(A), C& c) {
return PartiallyBoundUnaryMemberFunction<C,A,R>( function, c);
}
/**
* @brief Generate a nullary function object by binding a unary member function.
*
* Overloaded function type, this particular overload generates a nullary
* function object by binding the class instance and argument to a unary member function.
*
* @tparam C : the member function's class type.
* @tparam A : the member function's argument type.
* @tparam R : the member function's return type.
* @tparam I : a mask for the function's argument type.
* @param function : the void member function.
* @param c : the member function's class instance.
* @param a : the argument value to bind.
* @return BoundUnaryMemberFunction<C,R> : nullary function object.
*
* @sa @ref functionobjectsGuide "FunctionObjects".
*/
template <typename C, typename A, typename R, typename I>
BoundUnaryMemberFunction<C,A,R> generateFunctionObject( R (C::*function)(A), C& c, I& a ) {
// The I here is a bit of a trick...if you use A in the constructor above instead of I
// then it gets confused trying to deduce A as often the function arg and the input value
// are different types (e.g. const int& as opposed to int). So fix A in the template
// direction first, then pass it a type I which can be converted on the fly where needed.
return BoundUnaryMemberFunction<C,A,R>( function, c, a );
}
/**
* @brief Generate a nullary function object by binding a unary member function.
*
* Overloaded function type, this particular overload generates a nullary
* function object by binding the class instance and argument to a unary member function.
* The const argument bind allows for binding from temporaries.
*
* @tparam C : the member function's class type.
* @tparam A : the member function's argument type.
* @tparam R : the member function's return type.
* @tparam I : a mask for the function's argument type.
* @param function : the void member function.
* @param c : the member function's class instance.
* @param a : the argument value to bind (const).
* @return BoundUnaryMemberFunction<C,R> : nullary function object.
*
* @sa @ref functionobjectsGuide "FunctionObjects".
*/
template <typename C, typename A, typename R, typename I>
BoundUnaryMemberFunction<C,A,R> generateFunctionObject( R (C::*function)(A), C& c, const I& a ) {
// This one differs from the previous due to the const reference - this allows things like
// temporaries to pass through unscathed to a function with an argument like const int&.
return BoundUnaryMemberFunction<C,A,R>( function, c, a );
}
}; // namespace ecl
#endif /* ECL_UTILITIES_FUNCTION_OBJECTS_HPP_ */
| 34.253091 | 163 | 0.684148 | [
"object"
] |
2e47ed6c133f5abb5ae584fc24207e305374f16a | 3,530 | cpp | C++ | Algorithms/FancierAlgorithms/PatchBasedInpaintingScaleConsistent.cpp | jingtangliao/ff | d308fe62045e241a4822bb855df97ee087420d9b | [
"Apache-2.0"
] | 39 | 2015-01-01T07:59:51.000Z | 2021-10-01T18:11:46.000Z | Algorithms/FancierAlgorithms/PatchBasedInpaintingScaleConsistent.cpp | jingtangliao/ff | d308fe62045e241a4822bb855df97ee087420d9b | [
"Apache-2.0"
] | 1 | 2019-04-24T09:56:15.000Z | 2019-04-24T14:45:46.000Z | Algorithms/FancierAlgorithms/PatchBasedInpaintingScaleConsistent.cpp | jingtangliao/ff | d308fe62045e241a4822bb855df97ee087420d9b | [
"Apache-2.0"
] | 18 | 2015-01-11T15:10:23.000Z | 2022-02-24T20:02:10.000Z | /*=========================================================================
*
* Copyright David Doria 2011 daviddoria@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.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "PatchBasedInpaintingScaleConsistent.h"
void PatchBasedInpaintingScaleConsistent::FindBestPatch(CandidatePairs& candidatePairs, PatchPair& bestPatchPair)
{
//std::cout << "FindBestPatchScaleConsistent: There are " << this->SourcePatches.size() << " source patches at the beginning." << std::endl;
EnterFunction("FindBestPatchScaleConsistent()");
this->PatchCompare->SetPairs(&candidatePairs);
this->PatchCompare->SetImage(this->BlurredImage);
this->PatchCompare->SetMask(this->MaskImage);
this->PatchCompare->SetMembershipImage(this->MembershipImage);
this->PatchCompare->ComputeAllSourceDifferences();
std::sort(candidatePairs.begin(), candidatePairs.end(), SortFunctorWrapper(this->PatchSortFunction));
//std::cout << "Blurred score for pair 0: " << candidatePairs[0].GetAverageAbsoluteDifference() << std::endl;
candidatePairs.InvalidateAll();
std::vector<float> blurredScores(candidatePairs.size());
for(unsigned int i = 0; i < candidatePairs.size(); ++i)
{
blurredScores[i] = candidatePairs[i].DifferenceMap[PatchPair::AverageAbsoluteDifference];
}
// Create a temporary image to fill for now, but we might not actually end up filling this patch.
FloatVectorImageType::Pointer tempImage = FloatVectorImageType::New();
Helpers::DeepCopy<FloatVectorImageType>(this->CurrentOutputImage, tempImage);
// Fill the detailed image hole with a part of the blurred image
Helpers::CopySourcePatchIntoHoleOfTargetRegion<FloatVectorImageType>(this->BlurredImage, tempImage, this->MaskImage, candidatePairs[0].SourcePatch.Region, candidatePairs[0].TargetPatch.Region);
this->PatchCompare->SetPairs(&candidatePairs);
this->PatchCompare->SetImage(tempImage);
this->PatchCompare->SetMask(this->MaskImage);
this->PatchCompare->SetMembershipImage(this->MembershipImage);
this->PatchCompare->ComputeAllSourceAndTargetDifferences();
//std::cout << "Detailed score for pair 0: " << candidatePairs[0].GetAverageAbsoluteDifference() << std::endl;
for(unsigned int i = 0; i < candidatePairs.size(); ++i)
{
candidatePairs[i].DifferenceMap[PatchPair::AverageAbsoluteDifference] = blurredScores[i] + candidatePairs[i].DifferenceMap[PatchPair::AverageAbsoluteDifference];
}
std::cout << "Total score for pair 0: " << candidatePairs[0].DifferenceMap[PatchPair::AverageAbsoluteDifference] << std::endl;
std::sort(candidatePairs.begin(), candidatePairs.end(), SortFunctorWrapper(this->PatchSortFunction));
// Return the result by reference.
bestPatchPair = candidatePairs[0];
//std::cout << "There are " << this->SourcePatches.size() << " source patches at the end of FindBestPatchScaleConsistent()." << std::endl;
LeaveFunction("FindBestPatchScaleConsistent()");
}
| 50.428571 | 195 | 0.720113 | [
"vector"
] |
2e4893a4bfc74f3949468d94ab0c93be6ba3b1f2 | 434 | cc | C++ | src/canvas_gradient.cc | knocknote/libhtml5 | 46e18a9122097b4d681c91f0747aa78a20611cab | [
"MIT"
] | 7 | 2019-08-29T05:22:05.000Z | 2020-07-07T15:35:50.000Z | src/canvas_gradient.cc | blastrain/libhtml5 | 46e18a9122097b4d681c91f0747aa78a20611cab | [
"MIT"
] | 3 | 2019-07-12T09:43:31.000Z | 2019-09-10T03:36:45.000Z | src/canvas_gradient.cc | blastrain/libhtml5 | 46e18a9122097b4d681c91f0747aa78a20611cab | [
"MIT"
] | 3 | 2019-10-25T05:35:30.000Z | 2020-07-21T21:40:52.000Z | #include "canvas_gradient.h"
USING_NAMESPACE_HTML5;
CanvasGradient::CanvasGradient(emscripten::val v) :
Object(v)
{
}
CanvasGradient::~CanvasGradient()
{
}
CanvasGradient *CanvasGradient::create(emscripten::val v)
{
auto grad = new CanvasGradient(v);
grad->autorelease();
return grad;
}
void CanvasGradient::addColorStop(double offset, std::string color)
{
HTML5_CALL(this->v, addColorStop, offset, color);
}
| 17.36 | 67 | 0.723502 | [
"object"
] |
2e4f050f2ac84ea3b5448d15882ea7000a6e082b | 4,821 | ipp | C++ | sb/gl/detail/shader_support.ipp | ScottBailey/libsb | 078517f0dc8f168034044a969badafc177b8a398 | [
"BSD-3-Clause"
] | null | null | null | sb/gl/detail/shader_support.ipp | ScottBailey/libsb | 078517f0dc8f168034044a969badafc177b8a398 | [
"BSD-3-Clause"
] | null | null | null | sb/gl/detail/shader_support.ipp | ScottBailey/libsb | 078517f0dc8f168034044a969badafc177b8a398 | [
"BSD-3-Clause"
] | null | null | null | #ifndef sb_gl_detail_shader_support_h
#define sb_gl_detail_shader_support_h
/*
Copyright (c) 2014, Scott Bailey
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> 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 SCOTT BAILEY 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.
*/
// depending on mode GL vs GLES:
#if !defined(ANDROID)
# include <GL/glew.h>
# include <string.h> // memset()
#endif
#include <iostream>
#include <sstream>
#include <memory>
namespace sb {
namespace gl {
#if defined(USING_ALOG)
# include "alog.h"
#else
inline void alog(const std::string&, const std::string&)
{
;
}
#endif
inline GLuint link_program( GLuint vertex_shader, GLuint fragment_shader, const std::vector<std::string>& attribute_name_list,
std::string* error_string )
{
alog( "link_program","entry");
// Link the program
GLuint progID = glCreateProgram();
glAttachShader(progID, vertex_shader);
glAttachShader(progID, fragment_shader);
// add teh attributes
for( GLuint i = 0; i < attribute_name_list.size(); ++i)
glBindAttribLocation(progID, i, attribute_name_list[i].c_str());
glLinkProgram(progID);
// Check the program
GLint result = GL_TRUE;
glGetProgramiv(progID, GL_LINK_STATUS, &result);
if( result == GL_FALSE)
{
glGetProgramiv(progID, GL_INFO_LOG_LENGTH, &result);
if ( result > 1 )
{
alog( "link_program","retrieving log info");
std::unique_ptr<char[]> temp( new char[result] );
memset(temp.get(),0,result);
GLsizei rv_len;
glGetProgramInfoLog(progID, result, &rv_len, temp.get());
std::stringstream ss;
ss << "error: " << temp.get();
alog("link_program",ss.str());
alog("link_program", "*** MEMORY LEAK? ***" );
if( error_string )
*error_string = ss.str();
}
alog( "link_program","error exit");
return 0; // remove, this is a memory leak
}
// glDeleteShader(vsID);
// glDeleteShader(fsID);
alog( "link_program","successful exit");
return progID;
}
inline GLuint load_shader( const std::string& shader_code, const GLenum& shader_type, std::string* error_string)
{
alog( "load_shader","entry");
// Compile the shader
GLuint shader_id = glCreateShader(shader_type);
if( !shader_id )
alog( "load_shader", "bad shader type");
GLint sz = shader_code.size();
const char* chars = shader_code.c_str();
glShaderSource( shader_id, 1, &chars, &sz);
glCompileShader(shader_id);
// Check Vertex Shader
GLint result = GL_FALSE;
glGetShaderiv( shader_id, GL_COMPILE_STATUS, &result);
if( result == GL_FALSE )
{
alog( "load_shader","retrieving log length");
glGetShaderiv( shader_id, GL_INFO_LOG_LENGTH, &result);
if( result > 1 )
{
alog( "load_shader","retrieving log info");
std::unique_ptr<char[]> temp( new char[result] );
memset(temp.get(),0,result);
GLsizei rv_len;
glGetShaderInfoLog(shader_id, result, &rv_len, temp.get());
std::stringstream ss;
ss << "error: " << temp.get();
alog("load_shader",ss.str());
if(error_string)
*error_string = ss.str();
glDeleteShader(shader_id);
}
alog( "load_shader","error exit");
return 0;
}
alog( "load_shader","successful exit");
return shader_id;
}
} // namespace gl
} // namespace sb
#endif
| 31.509804 | 127 | 0.671645 | [
"vector"
] |
2e5726f51e6229eac10cf863186d54b7b8757846 | 1,230 | cc | C++ | chromecast/base/process_utils.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | chromecast/base/process_utils.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | chromecast/base/process_utils.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromecast/base/process_utils.h"
#include <errno.h>
#include <stddef.h>
#include <stdio.h>
#include "base/logging.h"
#include "base/posix/safe_strerror.h"
#include "base/strings/string_util.h"
namespace chromecast {
bool GetAppOutput(const std::vector<std::string>& argv, std::string* output) {
DCHECK(output);
// Join the args into one string, creating the command.
std::string command = base::JoinString(argv, " ");
// Open the process.
FILE* fp = popen(command.c_str(), "r");
if (!fp) {
LOG(ERROR) << "popen (" << command << ") failed: "
<< base::safe_strerror(errno);
return false;
}
// Fill |output| with the stdout from the process.
output->clear();
while (!feof(fp)) {
char buffer[256];
size_t bytes_read = fread(buffer, 1, sizeof(buffer), fp);
if (bytes_read <= 0)
break;
output->append(buffer, bytes_read);
}
// pclose() function waits for the associated process to terminate and returns
// the exit status.
return (pclose(fp) == 0);
}
} // namespace chromecast
| 26.170213 | 80 | 0.662602 | [
"vector"
] |
2e668dc40b9940c0bbd48cf865d80e18bb9fabbc | 4,207 | cc | C++ | mtpd/device_manager_test.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | null | null | null | mtpd/device_manager_test.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | null | null | null | mtpd/device_manager_test.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | 1 | 2020-11-04T22:31:45.000Z | 2020-11-04T22:31:45.000Z | // Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "mtpd/device_manager.h"
#include <string>
#include <vector>
#include <gtest/gtest.h>
#include <base/compiler_specific.h>
#include <base/stl_util.h>
#include <base/test/task_environment.h>
#include "mtpd/device_event_delegate.h"
namespace mtpd {
namespace {
class DeviceManagerTest : public testing::Test {
public:
DeviceManagerTest() = default;
private:
// DeviceManager needs the current thread to have a task runner.
base::test::TaskEnvironment task_environment_{
base::test::TaskEnvironment::ThreadingMode::MAIN_THREAD_ONLY};
DISALLOW_COPY_AND_ASSIGN(DeviceManagerTest);
};
TEST_F(DeviceManagerTest, ParseStorageName) {
struct ParseStorageNameTestCase {
const char* input;
bool expected_result;
const char* expected_bus;
uint32_t expected_storage_id;
} test_cases[] = {
{"usb:123:4", true, "usb:123", 4},
{"usb:1,2,3:4", true, "usb:1,2,3", 4},
{"notusb:123:4", false, "", 0},
{"usb:123:4:badfield", false, "", 0},
{"usb:123:not_number", false, "", 0},
};
for (size_t i = 0; i < base::size(test_cases); ++i) {
std::string bus;
uint32_t storage_id = static_cast<uint32_t>(-1);
bool result =
DeviceManager::ParseStorageName(test_cases[i].input, &bus, &storage_id);
EXPECT_EQ(test_cases[i].expected_result, result);
if (test_cases[i].expected_result) {
EXPECT_EQ(test_cases[i].expected_bus, bus);
EXPECT_EQ(test_cases[i].expected_storage_id, storage_id);
}
}
}
class TestDeviceEventDelegate : public DeviceEventDelegate {
public:
TestDeviceEventDelegate() {}
~TestDeviceEventDelegate() {}
// DeviceEventDelegate implementation.
void StorageAttached(const std::string& storage_name) override {}
void StorageDetached(const std::string& storage_name) override {}
private:
DISALLOW_COPY_AND_ASSIGN(TestDeviceEventDelegate);
};
class TestDeviceManager : public DeviceManager {
public:
explicit TestDeviceManager(DeviceEventDelegate* delegate)
: DeviceManager(delegate) {}
~TestDeviceManager() {}
bool AddStorage(const std::string& storage_name,
const StorageInfo& storage_info) {
return AddStorageForTest(storage_name, storage_info);
}
private:
DISALLOW_COPY_AND_ASSIGN(TestDeviceManager);
};
// Devices do not actually have a root node, so one is synthesized.
TEST_F(DeviceManagerTest, GetFileInfoForSynthesizedRootNode) {
const std::string kDummyStorageName = "usb:1,2:65432";
StorageInfo dummy_storage_info;
TestDeviceEventDelegate dummy_device_event_delegate;
TestDeviceManager device_manager(&dummy_device_event_delegate);
bool ret = device_manager.AddStorage(kDummyStorageName, dummy_storage_info);
EXPECT_TRUE(ret);
std::vector<FileEntry> file_entries;
std::vector<uint32_t> file_ids;
file_ids.push_back(0);
ret = device_manager.GetFileInfo(kDummyStorageName, file_ids, &file_entries);
EXPECT_TRUE(ret);
ASSERT_EQ(1U, file_entries.size());
const FileEntry& file_entry = file_entries[0];
EXPECT_EQ(0, file_entry.item_id());
EXPECT_EQ(0, file_entry.parent_id());
EXPECT_EQ("/", file_entry.file_name());
EXPECT_EQ(0, file_entry.file_size());
EXPECT_EQ(0, file_entry.modification_time());
EXPECT_EQ(LIBMTP_FILETYPE_FOLDER, file_entry.file_type());
}
// Devices do not actually have a root node, and it is not possible to read
// from the synthesized one.
TEST_F(DeviceManagerTest, ReadFileFromSynthesizedRootNodeFails) {
const std::string kDummyStorageName = "usb:1,2:65432";
StorageInfo dummy_storage_info;
TestDeviceEventDelegate dummy_device_event_delegate;
TestDeviceManager device_manager(&dummy_device_event_delegate);
bool ret = device_manager.AddStorage(kDummyStorageName, dummy_storage_info);
EXPECT_TRUE(ret);
std::vector<uint8_t> data;
ret = device_manager.ReadFileChunk(kDummyStorageName, 0 /* node id */,
0 /* offset */, 1 /* byte */, &data);
EXPECT_FALSE(ret);
EXPECT_TRUE(data.empty());
}
} // namespace
} // namespace mtpd
| 31.871212 | 80 | 0.730212 | [
"vector"
] |
2e72bd39099e58dded48590645833cc927d024ea | 3,553 | cpp | C++ | lib/ErriezBH1750/platformio/src/main.cpp | Erriez/ESP8266UbidotsSensors | 498d932aca5c0a4d9f3f2a701e60f22ee068669d | [
"MIT"
] | null | null | null | lib/ErriezBH1750/platformio/src/main.cpp | Erriez/ESP8266UbidotsSensors | 498d932aca5c0a4d9f3f2a701e60f22ee068669d | [
"MIT"
] | null | null | null | lib/ErriezBH1750/platformio/src/main.cpp | Erriez/ESP8266UbidotsSensors | 498d932aca5c0a4d9f3f2a701e60f22ee068669d | [
"MIT"
] | 2 | 2020-01-30T18:35:58.000Z | 2021-12-02T14:22:53.000Z | /*
* MIT License
*
* Copyright (c) 2018 Erriez
*
* 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.
*/
/* DHT22 - AM2303 temperature and relative humidity sensor example for Arduino
*
* Required library:
* https://github.com/Erriez/ErriezDHT22
*/
#include <ErriezDHT22.h>
// Connect DTH22 data pin to Arduino DIGITAL pin
#define DHT22_PIN 2
// Create DHT22 sensor object
DHT22 sensor = DHT22(DHT22_PIN);
// Function prototypes
void printTemperature(int16_t temperature);
void printHumidity(int16_t humidity);
void setup()
{
// Initialize serial port
Serial.begin(115200);
Serial.println(F("DHT22 temperature and humidity sensor example\n"));
// Initialize sensor
sensor.begin();
}
void loop()
{
// Check minimum interval of 2000 ms between sensor reads
if (sensor.available()) {
// Read temperature from sensor (blocking)
int16_t temperature = sensor.readTemperature();
// Read humidity from sensor (blocking)
int16_t humidity = sensor.readHumidity();
// Print temperature
printTemperature(temperature);
// Print humidity
printHumidity(humidity);
}
}
void printTemperature(int16_t temperature)
{
// Check valid temperature value
if (temperature == ~0) {
// Temperature error (Check hardware connection)
Serial.println(F("Temperature: Error"));
} else {
// Print temperature
Serial.print(F("Temperature: "));
Serial.print(temperature / 10);
Serial.print(F("."));
Serial.print(temperature % 10);
// Print degree Celsius symbols
// Choose if (1) for normal or if (0) for extended ASCII degree symbol
if (1) {
// Print *C characters which are displayed correctly in the serial
// terminal of the Arduino IDE
Serial.println(F(" *C"));
} else {
// Note: Extended characters are not supported in the Arduino IDE and
// displays ?C. This is displayed correctly with other serial terminals
// such as Tera Term.
// Degree symbol is ASCII code 248 (decimal).
char buf[4];
snprintf_P(buf, sizeof(buf), PSTR(" %cC"), 248);
Serial.println(buf);
}
}
}
void printHumidity(int16_t humidity)
{
// Check valid humidity value
if (humidity == ~0) {
// Humidity error (Check hardware connection)
Serial.println(F("Humidity: Error"));
} else {
// Print humidity
Serial.print(F("Humidity: "));
Serial.print(humidity / 10);
Serial.print(F("."));
Serial.print(humidity % 10);
Serial.println(F(" %"));
}
Serial.println();
}
| 29.857143 | 81 | 0.695469 | [
"object"
] |
2e72f9e38944878cf4a51a74561cec4017f67445 | 912 | cpp | C++ | Gems/FastNoise/Code/Source/FastNoiseEditorModule.cpp | Schneidex69/o3de | d9ec159f0e07ff86957e15212232413c4ff4d1dc | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-19T23:54:05.000Z | 2021-07-19T23:54:05.000Z | Gems/FastNoise/Code/Source/FastNoiseEditorModule.cpp | Schneidex69/o3de | d9ec159f0e07ff86957e15212232413c4ff4d1dc | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/FastNoise/Code/Source/FastNoiseEditorModule.cpp | Schneidex69/o3de | d9ec159f0e07ff86957e15212232413c4ff4d1dc | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "FastNoise_precompiled.h"
#include <FastNoiseEditorModule.h>
#include <FastNoiseSystemComponent.h>
#include <EditorFastNoiseGradientComponent.h>
namespace FastNoiseGem
{
FastNoiseEditorModule::FastNoiseEditorModule()
{
m_descriptors.insert(m_descriptors.end(), {
EditorFastNoiseGradientComponent::CreateDescriptor()
});
}
AZ::ComponentTypeList FastNoiseEditorModule::GetRequiredSystemComponents() const
{
AZ::ComponentTypeList requiredComponents = FastNoiseModule::GetRequiredSystemComponents();
return requiredComponents;
}
}
AZ_DECLARE_MODULE_CLASS(Gem_FastNoiseEditor, FastNoiseGem::FastNoiseEditorModule)
| 28.5 | 100 | 0.753289 | [
"3d"
] |
2e7a316a3ff8e68c8cdcbf8c33a689124926074a | 1,859 | cpp | C++ | tester.cpp | williamwu88/Flying-Stickman | d11c05e87bde481200ed1f3aaf5a0f4e4982d9ae | [
"MIT"
] | null | null | null | tester.cpp | williamwu88/Flying-Stickman | d11c05e87bde481200ed1f3aaf5a0f4e4982d9ae | [
"MIT"
] | null | null | null | tester.cpp | williamwu88/Flying-Stickman | d11c05e87bde481200ed1f3aaf5a0f4e4982d9ae | [
"MIT"
] | null | null | null | #include "tester.h"
#include "gamestate.h"
#include "player.h"
#include <iostream>
Tester::Tester(std::unique_ptr<GameStateFactory>& factory)
: state(factory->createGameState()),
paused(false) {}
Tester::~Tester()
{
delete state;
}
void Tester::run(int num_frames) {
std::srand(std::time(nullptr));
for (int i = 0; i < num_frames; ++i) {
if (paused) {
simulateTogglePause();
} else {
// Jump (1/100) or pause (1/250) randomly
int roll = std::rand();
if (roll < RAND_MAX / 100.0) {
simulateJump();
} else if (roll > RAND_MAX * 249.0 / 250.0) {
simulateTogglePause();
}
}
simulateUpdate();
assertCollisionBehaviour();
std::cout << std::endl;
}
}
void Tester::simulateUpdate() {
state->update(paused);
std::cout << "Update simulated" << std::endl;
}
void Tester::simulateJump() {
state->getPlayer()->jump();
std::cout << "Jump simulated" << std::endl;
}
void Tester::simulateTogglePause() {
paused = !paused;
if (paused) {
std::cout << "Paused" << std::endl;
} else {
std::cout << "Unpaused" << std::endl;
}
}
bool Tester::assertCollisionBehaviour() {
// Ensure that collisions stop movement of background and obstacles
if (state->getPlayerColliding()) {
std::vector<Entity*> obstacles = state->findEntitiesByNameContains("obstacle");
for (auto* obstacle : obstacles) {
Obstacle* o = dynamic_cast<Obstacle*>(obstacle);
if (o->isMoving()) {
std::cerr << "Invalid obstacle collision behaviour" << std::endl;
return false;
}
}
}
std::cout << "Passed obstacle collision behaviour test." << std::endl;
return true;
}
| 25.121622 | 87 | 0.557289 | [
"vector"
] |
2e91ed81d42c0edf882b15464c5cc7343864349b | 408 | hpp | C++ | src/yarr/algo/at_each_aligned.hpp | tgockel/yarrpp | bddc2e16b2dbb585fe23beb7cddf81a5bcba81a3 | [
"Apache-2.0"
] | null | null | null | src/yarr/algo/at_each_aligned.hpp | tgockel/yarrpp | bddc2e16b2dbb585fe23beb7cddf81a5bcba81a3 | [
"Apache-2.0"
] | null | null | null | src/yarr/algo/at_each_aligned.hpp | tgockel/yarrpp | bddc2e16b2dbb585fe23beb7cddf81a5bcba81a3 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <yarr/config.hpp>
#include <yarr/optimization_macros.hpp>
#include <cstdint>
namespace yarr
{
template <typename... TFArgs, typename... FApply>
void at_each_aligned(char* first, char* last, FApply&&... transform);
template <typename... TFArgs, typename... FApply>
void at_each_aligned(const char* first, const char* last, FApply&&... transform);
}
#include "at_each_aligned.ipp"
| 20.4 | 81 | 0.732843 | [
"transform"
] |
2e9a8cfe42c00e930c5796981ec00a6fc80fc542 | 1,588 | cpp | C++ | solutions/852-E-Peak-Index-in-a-Mountain-Array/main.cpp | ARW2705/leet-code-solutions | fa551e5b15f5340e5be3b832db39638bcbf0dc78 | [
"MIT"
] | null | null | null | solutions/852-E-Peak-Index-in-a-Mountain-Array/main.cpp | ARW2705/leet-code-solutions | fa551e5b15f5340e5be3b832db39638bcbf0dc78 | [
"MIT"
] | null | null | null | solutions/852-E-Peak-Index-in-a-Mountain-Array/main.cpp | ARW2705/leet-code-solutions | fa551e5b15f5340e5be3b832db39638bcbf0dc78 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
/*
Let's call an array A a mountain if the following properties hold:
A.length >= 3
There exists some 0 < i < A.length - 1
such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... >
A[A.length - 1]
Given an array that is definitely a mountain, return
any i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ...
> A[A.length - 1].
Example 1:
Input: [0,1,0]
Output: 1
Example 2:
Input: [0,2,1,0]
Output: 1
Note:
3 <= A.length <= 10000
0 <= A[i] <= 10^6
A is a mountain, as defined above.
*/
std::string vectorToString(std::vector<int>& m) {
std::string result = "[";
for (size_t i=0; i < m.size(); ++i) {
result += std::to_string(m[i]);
if (i < m.size() - 1) {
result += ", ";
}
}
result += "]";
return result;
}
void printResult(std::vector<int>& m, int expected, int result) {
std::cout
<< "For mountain: "
<< vectorToString(m)
<< ", expected peak at "
<< expected
<< ", got "
<< result
<< (expected == result ? "\nPASS\n": "\nFAIL\n");
}
int peakIndexInMountainArray(std::vector<int>& A) {
int maxIndex = 0;
for (size_t i=0; i < A.size(); ++i) {
if (A[i] > A[maxIndex]) {
maxIndex = i;
}
}
return maxIndex;
}
int main() {
std::vector<int> m1 { 0, 1, 0 };
printResult(m1, 1, peakIndexInMountainArray(m1));
std::vector<int> m2 { 0, 2, 1, 0 };
printResult(m2, 1, peakIndexInMountainArray(m2));
std::vector<int> m3 { 0, 10, 5, 2 };
printResult(m3, 1, peakIndexInMountainArray(m3));
return 0;
}
| 20.358974 | 66 | 0.555416 | [
"vector"
] |
2e9ee7db1753e7e899587ea298bc1a02c77c5ba3 | 14,868 | cpp | C++ | code/plugins/Shared/motion.cpp | porames25/xray-oxygen | 1f3f46a7a1ffc2be1de04a1ec665862127894ef7 | [
"Apache-2.0"
] | 7 | 2018-03-27T12:36:07.000Z | 2020-06-26T11:31:52.000Z | code/plugins/Shared/motion.cpp | porames25/xray-oxygen | 1f3f46a7a1ffc2be1de04a1ec665862127894ef7 | [
"Apache-2.0"
] | 2 | 2018-05-26T23:17:14.000Z | 2019-04-14T18:33:27.000Z | code/plugins/Shared/motion.cpp | Graff46/xray-oxygen | 543e79929c0e8debe57f5c567eaf11e5fe08216f | [
"Apache-2.0"
] | 5 | 2020-10-18T11:55:26.000Z | 2022-03-28T07:21:35.000Z | #include "stdafx.h"
#pragma hdrstop
#include "motion.h"
#include "envelope.h"
#define EOBJ_OMOTION 0x1100
#define EOBJ_SMOTION 0x1200
#define EOBJ_OMOTION_VERSION 0x0005
#define EOBJ_SMOTION_VERSION 0x0007
#ifdef _LW_EXPORT
extern void ReplaceSpaceAndLowerCase(shared_str& s);
#endif
//------------------------------------------------------------------------------------------
// CCustomMotion
//------------------------------------------------------------------------------------------
CCustomMotion::CCustomMotion()
{
iFrameStart =0;
iFrameEnd =0;
fFPS =30.f;
}
CCustomMotion::CCustomMotion(CCustomMotion* source){
*this = *source;
}
CCustomMotion::~CCustomMotion()
{
}
void CCustomMotion::Save(IWriter& F)
{
#ifdef _LW_EXPORT
ReplaceSpaceAndLowerCase(name);
#endif
F.w_stringZ (name);
F.w_u32 (iFrameStart);
F.w_u32 (iFrameEnd);
F.w_float (fFPS);
}
bool CCustomMotion::Load(IReader& F)
{
F.r_stringZ (name);
iFrameStart = F.r_u32();
iFrameEnd = F.r_u32();
fFPS = F.r_float();
return true;
}
//------------------------------------------------------------------------------------------
// Object Motion
//------------------------------------------------------------------------------------------
COMotion::COMotion():CCustomMotion()
{
mtype =mtObject;
for (int ch=0; ch<ctMaxChannel; ch++)
envs[ch] = xr_new<CEnvelope> ();
}
COMotion::COMotion(COMotion* source):CCustomMotion(source)
{
// bone motions
for (int ch=0; ch<ctMaxChannel; ch++)
envs[ch] = xr_new<CEnvelope> (source->envs[ch]);
}
COMotion::~COMotion()
{
Clear ();
}
void COMotion::Clear()
{
for (int ch=0; ch<ctMaxChannel; ch++) xr_delete(envs[ch]);
}
void COMotion::_Evaluate(float t, Fvector& T, Fvector& R)
{
T.x = envs[ctPositionX]->Evaluate(t);
T.y = envs[ctPositionY]->Evaluate(t);
T.z = envs[ctPositionZ]->Evaluate(t);
R.y = envs[ctRotationH]->Evaluate(t);
R.x = envs[ctRotationP]->Evaluate(t);
R.z = envs[ctRotationB]->Evaluate(t);
}
void COMotion::SaveMotion(const char* buf){
CMemoryWriter F;
F.open_chunk (EOBJ_OMOTION);
Save (F);
F.close_chunk ();
if (!F.save_to(buf))
Log ("!Can't save object motion:",buf);
}
bool COMotion::LoadMotion(const char* buf)
{
destructor<IReader> F(FS.r_open(buf));
R_ASSERT(F().find_chunk(EOBJ_OMOTION));
return Load (F());
}
void COMotion::Save(IWriter& F)
{
CCustomMotion::Save(F);
F.w_u16 (EOBJ_OMOTION_VERSION);
for (int ch=0; ch<ctMaxChannel; ch++)
envs[ch]->Save(F);
}
bool COMotion::Load(IReader& F)
{
CCustomMotion::Load(F);
u16 vers = F.r_u16();
if (vers==0x0003){
Clear ();
for (int ch=0; ch<ctMaxChannel; ch++){
envs[ch] = xr_new<CEnvelope> ();
envs[ch]->Load_1(F);
}
}else if (vers==0x0004){
Clear ();
envs[ctPositionX] = xr_new<CEnvelope>(); envs[ctPositionX]->Load_2(F);
envs[ctPositionY] = xr_new<CEnvelope>(); envs[ctPositionY]->Load_2(F);
envs[ctPositionZ] = xr_new<CEnvelope>(); envs[ctPositionZ]->Load_2(F);
envs[ctRotationP] = xr_new<CEnvelope>(); envs[ctRotationP]->Load_2(F);
envs[ctRotationH] = xr_new<CEnvelope>(); envs[ctRotationH]->Load_2(F);
envs[ctRotationB] = xr_new<CEnvelope>(); envs[ctRotationB]->Load_2(F);
}else{
if (vers!=EOBJ_OMOTION_VERSION) return false;
Clear ();
for (int ch=0; ch<ctMaxChannel; ch++){
envs[ch] = xr_new<CEnvelope> ();
envs[ch]->Load_2(F);
}
}
return true;
}
#if defined _EDITOR || defined _MAYA_EXPORT
void COMotion::CreateKey(float t, const Fvector& P, const Fvector& R)
{
envs[ctPositionX]->InsertKey(t,P.x);
envs[ctPositionY]->InsertKey(t,P.y);
envs[ctPositionZ]->InsertKey(t,P.z);
envs[ctRotationH]->InsertKey(t,R.y);
envs[ctRotationP]->InsertKey(t,R.x);
envs[ctRotationB]->InsertKey(t,R.z);
}
void COMotion::DeleteKey(float t)
{
envs[ctPositionX]->DeleteKey(t);
envs[ctPositionY]->DeleteKey(t);
envs[ctPositionZ]->DeleteKey(t);
envs[ctRotationH]->DeleteKey(t);
envs[ctRotationP]->DeleteKey(t);
envs[ctRotationB]->DeleteKey(t);
}
int COMotion::KeyCount()
{
return (u32)envs[ctPositionX]->keys.size();
}
using KeyIt = KeyVec::iterator;
void COMotion::FindNearestKey(float t, float& mn, float& mx, float eps)
{
KeyIt min_k;
KeyIt max_k;
envs[ctPositionX]->FindNearestKey(t, min_k, max_k, eps);
mn = (min_k!=envs[ctPositionX]->keys.end())?(*min_k)->time:t;
mx = (max_k!=envs[ctPositionX]->keys.end())?(*max_k)->time:t;
}
float COMotion::GetLength(float* mn, float* mx)
{
float ln,len=0.f;
for (int ch=0; ch<ctMaxChannel; ch++)
if ((ln=envs[ch]->GetLength(mn,mx))>len) len=ln;
return len;
}
BOOL COMotion::ScaleKeys(float from_time, float to_time, float scale_factor)
{
BOOL bRes=TRUE;
for (int ch=0; ch<ctMaxChannel; ch++)
if (FALSE==(bRes=envs[ch]->ScaleKeys(from_time, to_time, scale_factor, 1.f/fFPS))) break;
return bRes;
}
BOOL COMotion::NormalizeKeys(float from_time, float to_time, float speed)
{
if (to_time < from_time) return FALSE;
CEnvelope* E = Envelope(ctPositionX);
float new_tm = 0;
float t0 = E->keys.front()->time;
FloatVec tms;
tms.push_back(t0);
for (KeyIt it = E->keys.begin() + 1; it != E->keys.end(); it++) {
if ((*it)->time > from_time) {
if ((*it)->time < to_time + EPS) {
float dist = 0;
Fvector PT, T, R;
_Evaluate(t0, PT, R);
for (float tm = t0 + 1.f / fFPS; tm <= (*it)->time; tm += EPS_L) {
_Evaluate(tm, T, R);
dist += PT.distance_to(T);
PT.set(T);
}
new_tm += dist / speed;
t0 = (*it)->time;
tms.push_back(new_tm);
}
else {
float dt = (*it)->time - t0;
t0 = (*it)->time;
new_tm += dt;
tms.push_back(new_tm);
}
}
}
for (int ch = 0; ch < ctMaxChannel; ch++)
{
E = Envelope(EChannelType(ch));
auto f_it = tms.begin();
VERIFY(tms.size() == E->keys.size());
for (KeyIt k_it = E->keys.begin(); k_it != E->keys.end(); k_it++, f_it++)
(*k_it)->time = *f_it;
}
return TRUE;
}
#endif
//------------------------------------------------------------------------------------------
// Skeleton Motion
//------------------------------------------------------------------------------------------
#if defined (_EDITOR) || defined(_MAYA_EXPORT) || defined(_MAX_EXPORT) || defined(_LW_EXPORT)
//#include "SkeletonCustom.h"
CSMotion::CSMotion():CCustomMotion()
{
mtype =mtSkeleton;
m_BoneOrPart =BI_NONE;
fSpeed =1.0f;
fAccrue =2.0f;
fFalloff =2.0f;
fPower =1.f;
m_Flags.zero ();
}
CSMotion::CSMotion(CSMotion* source):CCustomMotion(source){
// bone motions
st_BoneMotion* src;
st_BoneMotion* dest;
for(u32 i=0; i<bone_mots.size(); i++){
dest = &bone_mots[i];
src = &source->bone_mots[i];
for (int ch=0; ch<ctMaxChannel; ch++)
dest->envs[ch] = xr_new<CEnvelope> (src->envs[ch]);
}
}
CSMotion::~CSMotion(){
Clear();
}
void CSMotion::Clear()
{
for(st_BoneMotion &it: bone_mots)
{
for (int ch=0; ch<ctMaxChannel; ch++) xr_delete(it.envs[ch]);
}
bone_mots.clear();
}
st_BoneMotion* CSMotion::FindBoneMotion(shared_str name)
{
for (st_BoneMotion &it : bone_mots)
if (it.name.equal(name)) return ⁢
return 0;
}
void CSMotion::add_empty_motion (shared_str const &bone_id)
{
VERIFY (!FindBoneMotion(bone_id));
st_BoneMotion motion;
motion.SetName (bone_id.c_str());
// flRKeyAbsent = (1<<1),
motion.m_Flags.assign ( 1 << 1);
for (int ch=0; ch<ctMaxChannel; ch++){
motion.envs[ch] = xr_new<CEnvelope> ();
// motion.envs[ch];
}
bone_mots.push_back (motion);
}
void CSMotion::CopyMotion(CSMotion* source){
Clear();
iFrameStart = source->iFrameStart;
iFrameEnd = source->iFrameEnd;
fFPS = source->fFPS;
st_BoneMotion* src;
st_BoneMotion* dest;
bone_mots.resize(source->bone_mots.size());
for(u32 i=0; i<bone_mots.size(); i++){
dest = &bone_mots[i];
src = &source->bone_mots[i];
for (int ch=0; ch<ctMaxChannel; ch++)
dest->envs[ch] = xr_new<CEnvelope> (src->envs[ch]);
}
}
void CSMotion::_Evaluate(int bone_idx, float t, Fvector& T, Fvector& R)
{
VERIFY(bone_idx<(int)bone_mots.size());
CEnvelope** envs = bone_mots[bone_idx].envs;
T.x = envs[ctPositionX]->Evaluate(t);
T.y = envs[ctPositionY]->Evaluate(t);
T.z = envs[ctPositionZ]->Evaluate(t);
R.y = envs[ctRotationH]->Evaluate(t);
R.x = envs[ctRotationP]->Evaluate(t);
R.z = envs[ctRotationB]->Evaluate(t);
}
void CSMotion::WorldRotate(int boneId, float h, float p, float b)
{
R_ASSERT((boneId>=0)&&(boneId<(int)bone_mots.size()));
st_BoneMotion& BM = bone_mots[boneId];
BM.envs[ctRotationH]->RotateKeys(h);
BM.envs[ctRotationP]->RotateKeys(p);
BM.envs[ctRotationB]->RotateKeys(b);
}
void CSMotion::SaveMotion(const char* buf){
CMemoryWriter F;
F.open_chunk (EOBJ_SMOTION);
Save (F);
F.close_chunk ();
if (!F.save_to(buf))
Log ("!Can't save skeleton motion:",buf);
}
bool CSMotion::LoadMotion(const char* buf)
{
destructor<IReader> F(FS.r_open(buf));
R_ASSERT (F().find_chunk(EOBJ_SMOTION));
return Load (F());
}
void CSMotion::Save(IWriter& F)
{
CCustomMotion::Save(F);
F.w_u16 (EOBJ_SMOTION_VERSION);
F.w_s8 (m_Flags.get());
F.w_u16 (m_BoneOrPart);
F.w_float (fSpeed);
F.w_float (fAccrue);
F.w_float (fFalloff);
F.w_float (fPower);
F.w_u16 ((u16)bone_mots.size());
for (st_BoneMotion &it : bone_mots)
{
xr_strlwr (it.name);
F.w_stringZ (it.name);
F.w_u8 (it.m_Flags.get());
for (int ch=0; ch<ctMaxChannel; ch++)
it.envs[ch]->Save(F);
}
F.w_u32 (0);
}
bool CSMotion::Load(IReader& F)
{
CCustomMotion::Load(F);
u16 vers = F.r_u16();
if (vers==0x0004){
m_BoneOrPart= u16(F.r_u32()&0xffff);
m_Flags.set (esmFX,F.r_u8());
m_Flags.set (esmStopAtEnd,F.r_u8());
fSpeed = F.r_float();
fAccrue = F.r_float();
fFalloff = F.r_float();
fPower = F.r_float();
bone_mots.resize(F.r_u32());
string64 temp_buf;
for(auto bm_it=bone_mots.begin(); bm_it!=bone_mots.end(); bm_it++){
bm_it->SetName (itoa(int(bm_it-bone_mots.begin()),temp_buf,10));
bm_it->m_Flags.assign((u8)F.r_u32());
for (int ch=0; ch<ctMaxChannel; ch++){
bm_it->envs[ch] = xr_new<CEnvelope> ();
bm_it->envs[ch]->Load_1(F);
}
}
}else{
if (vers==0x0005){
m_Flags.assign ((u8)F.r_u32());
m_BoneOrPart= u16(F.r_u32()&0xffff);
fSpeed = F.r_float();
fAccrue = F.r_float();
fFalloff = F.r_float();
fPower = F.r_float();
bone_mots.resize(F.r_u32());
string64 buf;
for (st_BoneMotion &it : bone_mots)
{
F.r_stringZ (buf,sizeof(buf));
it.SetName (buf);
it.m_Flags.assign((u8)F.r_u32());
for (int ch=0; ch<ctMaxChannel; ch++){
it.envs[ch] = xr_new<CEnvelope> ();
it.envs[ch]->Load_1(F);
}
}
}else{
if (vers>=0x0006)
{
m_Flags.assign (F.r_u8());
m_BoneOrPart= F.r_u16();
fSpeed = F.r_float();
fAccrue = F.r_float();
fFalloff = F.r_float();
fPower = F.r_float();
bone_mots.resize(F.r_u16());
string64 buf;
for (st_BoneMotion &it : bone_mots)
{
F.r_stringZ (buf,sizeof(buf));
it.SetName (buf);
it.m_Flags.assign(F.r_u8());
for (int ch=0; ch<ctMaxChannel; ch++){
it.envs[ch] = xr_new<CEnvelope> ();
it.envs[ch]->Load_2(F);
}
}
}
}
}
for (st_BoneMotion &it : bone_mots)
{
xr_strlwr(it.name);
}
return true;
}
void CSMotion::Optimize()
{
for (st_BoneMotion &it : bone_mots)
{
for (int ch=0; ch<ctMaxChannel; ch++)
it.envs[ch]->Optimize();
}
}
void CSMotion::SortBonesBySkeleton(BoneVec& bones)
{
BoneMotionVec new_bone_mots;
for (BoneIt b_it=bones.begin(); b_it!=bones.end(); b_it++){
st_BoneMotion* BM = FindBoneMotion((*b_it)->Name()); R_ASSERT(BM);
new_bone_mots.push_back(*BM);
}
bone_mots.clear ();
bone_mots = new_bone_mots;
}
#endif
void SAnimParams::Set(float start_frame, float end_frame, float fps)
{
min_t=start_frame/fps;
max_t=end_frame/fps;
}
void SAnimParams::Set(CCustomMotion* M)
{
Set((float)M->FrameStart(),(float)M->FrameEnd(),M->FPS());
t_current = min_t;
tmp = t_current;
// bPlay=true;
}
void SAnimParams::Update(float dt, float speed, bool loop)
{
if (!bPlay) return;
bWrapped = false;
t_current +=speed*dt;
tmp = t_current;
if (t_current>max_t)
{
bWrapped= true;
if (loop)
{
float len = max_t-min_t;
float k = float(iFloor((t_current-min_t)/len));
t_current = t_current-k*len;
}else
t_current = max_t;
tmp = t_current;
}
}
//------------------------------------------------------------------------------
// Clip
//------------------------------------------------------------------------------
#define EOBJ_CLIP_VERSION 2
#define EOBJ_CLIP_VERSION_CHUNK 0x9000
#define EOBJ_CLIP_DATA_CHUNK 0x9001
void CClip::Save(IWriter& F)
{
F.open_chunk (EOBJ_CLIP_VERSION_CHUNK);
F.w_u16 (EOBJ_CLIP_VERSION);
F.close_chunk ();
F.open_chunk (EOBJ_CLIP_DATA_CHUNK);
F.w_stringZ (name);
for (int k=0; k<4; k++){
F.w_stringZ (cycles[k].name);
F.w_u16 (cycles[k].slot);
}
F.w_stringZ (fx.name);
F.w_u16 (fx.slot);
F.w_float (fx_power);
F.w_float (length);
F.close_chunk ();
}
//------------------------------------------------------------------------------
bool CClip::Load(IReader& F)
{
R_ASSERT (F.find_chunk(EOBJ_CLIP_VERSION_CHUNK));
u16 ver = F.r_u16();
if (ver!=EOBJ_CLIP_VERSION) return false;
R_ASSERT(F.find_chunk(EOBJ_CLIP_DATA_CHUNK));
F.r_stringZ (name);
for (int k=0; k<4; k++){
F.r_stringZ (cycles[k].name);
cycles[k].slot = F.r_u16();
}
F.r_stringZ (fx.name);
fx.slot = F.r_u16();
fx_power = F.r_float();
length = F.r_float();
return true;
}
//------------------------------------------------------------------------------
bool CClip::Equal(CClip* c)
{
if (!name.equal(c->name)) return false;
if (!cycles[0].equal(c->cycles[0])) return false;
if (!cycles[1].equal(c->cycles[1])) return false;
if (!cycles[2].equal(c->cycles[2])) return false;
if (!cycles[3].equal(c->cycles[3])) return false;
if (!fx.equal(c->fx)) return false;
if (length!=c->length) return false;
return true;
}
//------------------------------------------------------------------------------
| 25.993007 | 97 | 0.570689 | [
"object"
] |
2ea66a5f0c55f017adce1b08cc8b3b25c0ed1ccf | 15,076 | cpp | C++ | zztlib/gameBoard.cpp | inmatarian/freezzt | 5dc4ce83ffee27a398ed77416e1d4164d191d993 | [
"MIT"
] | 5 | 2015-07-06T19:45:12.000Z | 2021-03-30T02:13:07.000Z | zztlib/gameBoard.cpp | inmatarian/freezzt | 5dc4ce83ffee27a398ed77416e1d4164d191d993 | [
"MIT"
] | null | null | null | zztlib/gameBoard.cpp | inmatarian/freezzt | 5dc4ce83ffee27a398ed77416e1d4164d191d993 | [
"MIT"
] | null | null | null | /**
* @file
* @author Inmatarian <inmatarian@gmail.com>
* @section LICENSE
* Insert copyright and license information here.
*/
#include <list>
#include <vector>
#include <string>
#include <cassert>
#include "debug.h"
#include "zstring.h"
#include "defines.h"
#include "gameBoard.h"
#include "gameWorld.h"
#include "abstractPainter.h"
#include "abstractMusicStream.h"
#include "zztEntity.h"
#include "zztThing.h"
#include "scriptable.h"
#include "zztoopInterp.h"
#include "player.h"
const int FIELD_SIZE = 1500;
typedef std::list<ZZTThing::AbstractThing*> ThingList;
typedef std::list<ZZTOOP::Interpreter*> ProgramsList;
typedef std::vector<ZZTEntity> Field;
class GameBoardPrivate
{
public:
GameBoardPrivate( GameBoard *pSelf );
virtual ~GameBoardPrivate();
void collectGarbage();
void drawMessageLine( AbstractPainter *painter );
public:
GameWorld *world;
Field field;
ThingList thingList;
ThingList thingGarbage;
ProgramsList programs;
unsigned int boardCycle;
ZString message;
int messageLife;
int northExit;
int southExit;
int westExit;
int eastExit;
bool darkness;
private:
GameBoard *self;
};
GameBoardPrivate::GameBoardPrivate( GameBoard *pSelf )
: world(0),
boardCycle(0),
messageLife(0),
northExit(0),
southExit(0),
westExit(0),
eastExit(0),
darkness(false),
self( pSelf )
{
field.resize(FIELD_SIZE);
}
GameBoardPrivate::~GameBoardPrivate()
{
// clean out the thing list
while ( !thingList.empty() ) {
ZZTThing::AbstractThing *thing = thingList.front();
thingList.pop_front();
delete thing;
}
collectGarbage();
while ( !programs.empty() ) {
ZZTOOP::Interpreter *prog = programs.front();
programs.pop_front();
delete prog;
}
self = 0;
}
void GameBoardPrivate::collectGarbage()
{
while ( !thingGarbage.empty() ) {
ZZTThing::AbstractThing *thing = thingGarbage.front();
thingGarbage.pop_front();
delete thing;
}
}
void GameBoardPrivate::drawMessageLine( AbstractPainter *painter )
{
if ( messageLife <= 0 ) return;
int x = 29 - ( message.size() / 2 );
if ( x < 0 ) x = 0;
const int color = (boardCycle % 8) + Defines::DARK_GRAY;
painter->drawText( x, 24, color, message );
}
static int fieldHash( int x, int y )
{
return (y * 60) + x;
}
// I'm too lazy to do it any other way
static const char torchShape[9][16] = {
"### ###",
"## ##",
"# #",
"# #",
" * ",
"# #",
"# #",
"## ##",
"### ###"
};
static bool beyondVisible( const int x, const int y, const int px, const int py )
{
const int dx = 7 + (px - x);
const int dy = 4 + (py - y);
if ( dx < 0 || dy < 0 || dx >= 15 || dy >= 9 ) return true;
return torchShape[dy][dx]=='#';
}
// ---------------------------------------------------------------------------
GameBoard::GameBoard()
: d( new GameBoardPrivate(this) )
{
}
GameBoard::~GameBoard()
{
delete d;
d = 0;
}
GameBoard *GameBoard::addEmptyBoard( GameWorld *world, int pos )
{
GameBoard *board = new GameBoard();
world->addBoard( pos, board );
ZZTThing::Player *player = new ZZTThing::Player();
player->setBoard( board );
player->setPos( 30, 12 );
player->setCycle( 1 );
ZZTEntity underEnt = ZZTEntity::createEntity( ZZTEntity::EmptySpace, 0x07 );
player->setUnderEntity( underEnt );
ZZTEntity playerEnt = ZZTEntity::createEntity( ZZTEntity::Player, 0x1f );
playerEnt.setThing( player );
board->setEntity( 30, 12, playerEnt );
board->addThing( player );
for ( int x = 0; x < 60; x++ ) {
board->setEntity( x, 0, ZZTEntity::createEntity( ZZTEntity::Normal, 0x0e ) );
board->setEntity( x, 24, ZZTEntity::createEntity( ZZTEntity::Normal, 0x0e ) );
}
for ( int y = 1; y < 24; y++ ) {
board->setEntity( 0, y, ZZTEntity::createEntity( ZZTEntity::Normal, 0x0e ) );
board->setEntity( 59, y, ZZTEntity::createEntity( ZZTEntity::Normal, 0x0e ) );
}
return board;
}
void GameBoard::setWorld( GameWorld *world )
{
d->world = world;
}
GameWorld * GameBoard::world() const
{
return d->world;
}
AbstractMusicStream *GameBoard::musicStream() const
{
return world()->musicStream();
}
void GameBoard::clear()
{
for ( int x = 0; x < FIELD_SIZE; x++ ) {
d->field[x] = ZZTEntity();
}
}
const ZZTEntity & GameBoard::entity( int x, int y ) const
{
if ( x < 0 || x >= 60 || y < 0 || y >= 25 ) {
return ZZTEntity::sharedEdgeOfBoardEntity();
}
return d->field[ fieldHash(x, y) ];
}
void GameBoard::setEntity( int x, int y, const ZZTEntity &entity )
{
if ( x < 0 || x >= 60 || y < 0 || y >= 25 ) {
return;
}
d->field[ fieldHash(x, y) ] = entity;
}
void GameBoard::replaceEntity( int x, int y, const ZZTEntity &newEntity )
{
if ( x < 0 || x >= 60 || y < 0 || y >= 25 ) {
return;
}
const int index = fieldHash(x, y);
ZZTThing::AbstractThing *thing = d->field[index].thing();
if ( thing ) {
// wipe it from existance
d->thingList.remove( thing );
d->thingGarbage.push_back( thing );
thing = 0;
}
d->field[index] = newEntity;
}
void GameBoard::clearEntity( int x, int y )
{
replaceEntity( x, y, ZZTEntity::createEntity( ZZTEntity::EmptySpace, 0x07 ) );
}
void GameBoard::exec()
{
for ( int i = 0; i<FIELD_SIZE; i++ ) {
d->field[i].exec();
}
// update board cycle
d->boardCycle += 1;
d->messageLife -= 1;
d->collectGarbage();
}
void GameBoard::paint( AbstractPainter *painter )
{
// copy thing characters out to entities
ThingList::iterator iter;
for( iter = d->thingList.begin(); iter != d->thingList.end(); ++iter )
{
ZZTThing::AbstractThing *thing = *iter;
thing->updateEntity();
}
ZZTThing::Player *plyr = player();
const int px = plyr->xPos();
const int py = plyr->yPos();
// paint all entities
for ( int i = 0; i<FIELD_SIZE; i++ )
{
const int x = (i%60);
const int y = (i/60);
if ( d->world->transitionTile(x, y) ) {
// don't paint over transition tiles
continue;
}
ZZTEntity &entity = d->field[i];
if ( isDark() &&
!entity.isVisibleInDarkness() &&
( world()->currentTorchCycles() == 0 ||
beyondVisible( x, y, px, py ) ) )
{
painter->paintChar( x, y, 0xb0, 0x07 );
continue;
}
entity.paint( painter, x, y );
}
d->drawMessageLine( painter );
}
const ZString & GameBoard::message() const
{
return d->message;
}
void GameBoard::setMessage( const ZString &mesg )
{
d->message.clear();
if ( mesg.empty() ) {
d->messageLife = 0;
}
else {
d->message += ' ';
d->message += mesg;
d->message += ' ';
d->messageLife = 90;
}
}
int GameBoard::northExit() const { return d->northExit; }
int GameBoard::southExit() const { return d->southExit; }
int GameBoard::westExit() const { return d->westExit; }
int GameBoard::eastExit() const { return d->eastExit; }
void GameBoard::setNorthExit( int exit ) { d->northExit = exit; }
void GameBoard::setSouthExit( int exit ) { d->southExit = exit; }
void GameBoard::setWestExit( int exit ) { d->westExit = exit; }
void GameBoard::setEastExit( int exit ) { d->eastExit = exit; }
bool GameBoard::isDark() const { return d->darkness; }
void GameBoard::setDark( bool dark ) { d->darkness = dark; };
void GameBoard::addThing( ZZTThing::AbstractThing *thing )
{
d->thingList.push_back( thing );
ZZTEntity &ent = d->field[ fieldHash( thing->xPos(), thing->yPos() ) ];
ent.setThing( thing );
thing->updateEntity();
}
void GameBoard::addInterpreter( ZZTOOP::Interpreter *interp )
{
// Gameboard owns the programs, not the Scriptable Objects
d->programs.push_back( interp );
#if 0
zdebug() << "GameBoard::addProgramBank" << prog << prog->length();
zout() << "\n";
for ( signed short i = 0; i < prog->length(); i++ ) {
signed char c = (*prog)[i];
if ( c == 0x0d ) zout() << " \\n ";
else if ( c >= ' ' ) zout() << ZString(1, c);
else zout() << "?";
}
zout() << "\n";
#endif
}
void GameBoard::moveThing( ZZTThing::AbstractThing *thing, int newX, int newY )
{
if ( newX < 0 || newX >= 60 || newY < 0 || newY >= 25 ) {
return;
}
// get thing's entity
ZZTEntity thingEnt = d->field[ fieldHash( thing->xPos(), thing->yPos() ) ];
// get the neighbor's entity
ZZTEntity newUnderEnt = d->field[ fieldHash(newX, newY) ];
// restore what was there before him.
d->field[ fieldHash( thing->xPos(), thing->yPos() ) ] = thing->underEntity();
// push neighbor underneath him
thing->setUnderEntity( newUnderEnt );
// put thing's entity in the new spot
d->field[ fieldHash(newX, newY) ] = thingEnt;
// move to new spot
thing->setPos( newX, newY );
}
void GameBoard::switchThings( ZZTThing::AbstractThing *left,
ZZTThing::AbstractThing *right )
{
// get their positions
int lx = left->xPos(),
ly = left->yPos(),
rx = right->xPos(),
ry = right->yPos();
// get things entities
ZZTEntity leftEnt = d->field[ fieldHash(lx, ly) ];
ZZTEntity rightEnt = d->field[ fieldHash(rx, ry) ];
// swap them
d->field[ fieldHash(lx, ly) ] = rightEnt;
d->field[ fieldHash(rx, ry) ] = leftEnt;
// get their underneaths
leftEnt = left->underEntity();
rightEnt = right->underEntity();
// swap them
left->setUnderEntity( rightEnt );
right->setUnderEntity( leftEnt );
// now swap positions
left->setPos( rx, ry );
right->setPos( lx, ly );
}
void GameBoard::makeBullet( int x, int y, int x_step, int y_step, bool playerType )
{
if ( x < 0 || x >= 60 || y < 0 || y >= 25 ) {
return;
}
ZZTEntity ent = d->field[ fieldHash(x,y) ];
if ( ent.isWalkable() || ent.isSwimable() )
{
// create a bullet
ZZTThing::Bullet *bullet = new ZZTThing::Bullet;
bullet->setXPos( x );
bullet->setYPos( y );
bullet->setDirection( x_step, y_step );
bullet->setType( playerType );
bullet->setBoard( this );
bullet->setUnderEntity( ent );
bullet->setCycle( 1 );
ZZTEntity bulletEnt = ZZTEntity::createEntity( ZZTEntity::Bullet, 0x0f );
bulletEnt.setThing( bullet );
d->field[ fieldHash(x,y) ] = bulletEnt;
d->thingList.push_back( bullet );
}
else {
// simulate a bullet
handleBulletCollision( x, y, x_step, y_step, playerType );
}
}
void GameBoard::handleBulletCollision( int x, int y, int x_step, int y_step, bool playerType )
{
ZZTEntity ent = entity( x, y );
if ( playerType )
{
switch( ent.id() ) {
case ZZTEntity::Object:
// send :shot message
break;
case ZZTEntity::Breakable:
case ZZTEntity::Gem:
clearEntity( x, y );
musicStream()->playEvent( AbstractMusicStream::Breakable );
break;
case ZZTEntity::Bear:
case ZZTEntity::Ruffian:
case ZZTEntity::Slime:
case ZZTEntity::Shark:
case ZZTEntity::Lion:
case ZZTEntity::Tiger:
case ZZTEntity::CentipedeHead:
case ZZTEntity::CentipedeSegment:
deleteThing( ent.thing() );
musicStream()->playEvent( AbstractMusicStream::KillEnemy );
break;
default: break;
}
}
else
{
switch( ent.id() ) {
case ZZTEntity::Player:
// hurt player
break;
default: break;
}
}
}
void GameBoard::makeStar( int x, int y )
{
if ( x < 0 || x >= 60 || y < 0 || y >= 25 ) {
return;
}
ZZTEntity ent = d->field[ fieldHash(x,y) ];
if ( ! ( ent.isWalkable() || ent.isSwimable() ) ) {
return;
}
ZZTThing::Star *star = new ZZTThing::Star;
star->setXPos( x );
star->setYPos( y );
star->setBoard( this );
star->setUnderEntity( ent );
star->setCycle( 1 );
ZZTEntity starEnt = ZZTEntity::createEntity( ZZTEntity::Star, 0x0f );
starEnt.setThing( star );
d->field[ fieldHash(x,y) ] = starEnt;
d->thingList.push_back( star );
}
void GameBoard::deleteThing( ZZTThing::AbstractThing *thing )
{
thing->handleDeleted();
d->thingList.remove( thing );
d->thingGarbage.push_back( thing );
d->field[ fieldHash(thing->xPos(), thing->yPos()) ] = thing->underEntity();
}
unsigned int GameBoard::cycle() const
{
return d->boardCycle;
}
ZZTThing::Player *GameBoard::player() const
{
assert( d->thingList.size() > 0 );
ZZTThing::Player *player =
dynamic_cast<ZZTThing::Player *>(d->thingList.front());
assert( player );
return player;
}
void GameBoard::pushEntities( int x, int y, int x_step, int y_step )
{
if ( entity( x, y ).isWalkable() ) {
return;
}
// only push cardinal directions, not in diagonals or idle
if ( ! ( ( x_step == 0 && y_step != 0 ) ||
( x_step != 0 && y_step == 0 ) ) ) {
return;
}
// normalize to 1 or -1
x_step = ( x_step > 0 ) ? 1
: ( x_step < 0 ) ? -1 : 0;
// normalize to 1 or -1
y_step = ( y_step > 0 ) ? 1
: ( y_step < 0 ) ? -1 : 0;
// iterate through pushables until we find a walkable
int tx = x, ty = y;
int pushCount = 0;
while (true)
{
const ZZTEntity &ent = entity( tx, ty );
if ( ent.isWalkable() ) {
break;
}
if ( !ent.isPushable( x_step, y_step ) ) {
return;
}
tx += x_step;
ty += y_step;
pushCount += 1;
}
// okay, we're at a walkable. copy everything back now.
int px = tx, py = ty;
while ( tx != x || ty != y )
{
px -= x_step;
py -= y_step;
if ( entity( px, py ).isThing() ) {
moveThing( entity( px, py ).thing(), tx, ty );
}
else {
ZZTEntity p_ent = entity( px, py );
setEntity( tx, ty, p_ent );
}
tx = px;
ty = py;
}
if ( pushCount >= 1 ) {
musicStream()->playEvent( AbstractMusicStream::Push );
}
setEntity( x, y, ZZTEntity::createEntity( ZZTEntity::EmptySpace, 0x07 ) );
}
void GameBoard::sendLabel( const ZString &to, const ZString &label,
const ZZTThing::AbstractThing *from )
{
ZString upperTo = to.upper();
const bool toAll = ( upperTo == "ALL" );
const bool toOthers = ( upperTo == "OTHERS" );
ThingList::iterator iter;
for( iter = d->thingList.begin(); iter != d->thingList.end(); ++iter )
{
ZZTThing::AbstractThing *thing = *iter;
if ( thing->entityID() != ZZTEntity::Object )
continue;
ZZTThing::ScriptableThing *object = dynamic_cast<ZZTThing::ScriptableThing*>(thing);
const ZString upperName = object->objectName().upper();
if ( toAll || upperTo == upperName ||
(toOthers && (from != thing)) )
{
object->seekLabel( label );
}
}
}
bool GameBoard::isAnyEntity( unsigned char id, unsigned char color ) const
{
// The ANY condition only checks lower nibble for color. We'll be using
// the upper nibble to flag a DON'T CHECK COLOR.
const bool checkColor = (color & 0xF0);
// what, O(n) search? ZOMG! Boo.
for ( int i = 0; i<FIELD_SIZE; i++ ) {
const ZZTEntity ent = d->field[i];
if ( ent.id() == id ) {
if ( checkColor && color == ( ent.color() & 0x0F ) )
return true;
}
}
return false;
}
| 23.229584 | 94 | 0.599297 | [
"object",
"vector"
] |
2eb7addbde753701e91a0f2b5787eb655401737a | 13,631 | cc | C++ | src/fcst/source/reactions/bv_kinetics.cc | jeremyjiezhou/Learn-PyTorch | 7e4404609bacd2ec796f6ca3ea118e8e34ab4a22 | [
"MIT"
] | 24 | 2016-10-04T20:49:55.000Z | 2022-03-12T19:07:10.000Z | src/fcst/source/reactions/bv_kinetics.cc | jeremyjiezhou/Learn-PyTorch | 7e4404609bacd2ec796f6ca3ea118e8e34ab4a22 | [
"MIT"
] | null | null | null | src/fcst/source/reactions/bv_kinetics.cc | jeremyjiezhou/Learn-PyTorch | 7e4404609bacd2ec796f6ca3ea118e8e34ab4a22 | [
"MIT"
] | 9 | 2016-12-11T22:15:03.000Z | 2020-11-21T13:51:05.000Z | //---------------------------------------------------------------------------
//
// FCST: Fuel Cell Simulation Toolbox
//
// Copyright (C) 2006-13 by Energy Systems Design Laboratory, University of Alberta
//
// This software is distributed under the MIT License.
// For more information, see the README file in /doc/LICENSE
//
// - Class: bv_kinetics.cc
// - Description: Butler-Volmer Kinetics model class
// - Developers: M. Secanell, M. Moore and M. Bhaiya
// - $Id: bv_kinetics.cc 2605 2014-08-15 03:36:44Z secanell $
//
//---------------------------------------------------------------------------
#include "reactions/bv_kinetics.h"
namespace NAME = FuelCellShop::Kinetics;
const std::string NAME::ButlerVolmerKinetics::concrete_name ("ButlerVolmerKinetics");
NAME::ButlerVolmerKinetics const* NAME::ButlerVolmerKinetics::PROTOTYPE = new NAME::ButlerVolmerKinetics(true);
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
NAME::ButlerVolmerKinetics::ButlerVolmerKinetics(const bool construct_replica)
:
BaseKinetics ()
{
if (construct_replica)
this->get_mapFactory()->insert(std::pair<std::string, BaseKinetics* > (this->concrete_name, this) );
}
//---------------------------------------------------------------------------
NAME::ButlerVolmerKinetics::ButlerVolmerKinetics()
:
BaseKinetics ()
{
FcstUtilities::log << "Butler Volmer kinetics." << std::endl;
}
//---------------------------------------------------------------------------
NAME::ButlerVolmerKinetics::~ButlerVolmerKinetics()
{}
//---------------------------------------------------------------------------
void
NAME::ButlerVolmerKinetics::current_density (std::vector<double>& coef)
{
if (!kin_param_initialized)
init_kin_param();
n_quad = phi_m.size();
coef.resize(n_quad);
double species_comp;
// Compute the coefficient, first loop over the quadrature points
for (unsigned int i=0; i<n_quad; ++i)
{
species_comp = 1.;
//loop over each species in the reaction and compute its contribution to the current density
for (std::map< VariableNames, SolutionVariable >::const_iterator iter=reactants_map.begin(); iter != reactants_map.end(); ++iter)
{
if (iter->second[i] < 0.0)
species_comp = 0.0;
else
species_comp = species_comp*( pow(iter->second[i]/ref_conc.at(iter->first), gamma.at(iter->first)));
}
coef[i] = (catalyst->exchange_current_density(T[i]))*species_comp*( exp( alpha_a*F*(phi_s[i]-phi_m[i]-(catalyst->voltage_cell_th(T[i])))/(R*T[i]) )
-
exp((-alpha_c*F*(phi_s[i]-phi_m[i]-(catalyst->voltage_cell_th(T[i]))))/(R*T[i])) );
if (std::isinf(coef[i]))
coef[i] = std::numeric_limits<double>::max()*1e-150;
else if (std::isnan(coef[i]))
coef[i] = 0.0;
}
}
//---------------------------------------------------------------------------
void
NAME::ButlerVolmerKinetics::derivative_current (std::map< VariableNames, std::vector<double> >& dcoef_du)
{
Assert( derivative_flags.size() != 0, ExcMessage("Derivative flags are not set using set_derivative_flags method before the ButlerVolmerKinetics::derivative_current.") );
if (!kin_param_initialized)
init_kin_param();
n_quad = phi_m.size();
double species_comp;
// Loop over the flags
for (unsigned int i=0; i<derivative_flags.size(); ++i)
{
std::vector<double> dcurrent(n_quad, 0.); // Defaulting all derivatives to 0.0
if ( (derivative_flags[i] == oxygen_molar_fraction) ||
(derivative_flags[i] == hydrogen_molar_fraction)||
(reactants_map.find(derivative_flags[i])!=reactants_map.end()) )
{
for (unsigned int j=0; j<n_quad; ++j)
{
species_comp = 1.;
// Loop over each species in the reaction and compute its contribution
for (std::map< VariableNames, SolutionVariable >::const_iterator iter=reactants_map.begin(); iter != reactants_map.end(); ++iter)
{
if (iter->second[j] < 0.0)
{
species_comp *= 0.0;
}
else if ( derivative_flags[i] == oxygen_molar_fraction && iter->first == oxygen_concentration )
{
Assert( electrolyte->get_H_O2() != 0.0, ExcMessage("Derivatives at the moment are defined only using Thin fim (Henry's law) case for Oxygen molar fraction."));
if ( gamma.at(iter->first)-1. >= 0. )
species_comp *= ( (gamma.at(iter->first)*pow(1./(ref_conc.at(iter->first)),gamma.at(iter->first))*(p_total/electrolyte->get_H_O2())) *pow(iter->second[j],gamma.at(iter->first)-1.) );
else
species_comp *= ( (gamma.at(iter->first)*pow(1./(ref_conc.at(iter->first)),gamma.at(iter->first))*(p_total/electrolyte->get_H_O2())) /pow(iter->second[j],1.-gamma.at(iter->first)) );
}
else if ( derivative_flags[i] == hydrogen_molar_fraction && iter->first == hydrogen_concentration )
{
Assert( electrolyte->get_H_H2() != 0.0, ExcMessage("Derivatives at the moment are defined only using Thin fim (Henry's law) case for Hydrogen molar fraction."));
if ( gamma.at(iter->first)-1. >= 0. )
species_comp *= ( (gamma.at(iter->first)*pow(1./(ref_conc.at(iter->first)),gamma.at(iter->first))*(p_total/electrolyte->get_H_H2())) *pow(iter->second[j],gamma.at(iter->first)-1.) );
else
species_comp *= ( (gamma.at(iter->first)*pow(1./(ref_conc.at(iter->first)),gamma.at(iter->first))*(p_total/electrolyte->get_H_H2())) /pow(iter->second[j],1.-gamma.at(iter->first)) );
}
else if ( iter->first == derivative_flags[i] )
{
if ( gamma.at(iter->first)-1. >= 0. )
species_comp *= ( (gamma.at(iter->first)*pow(1./(ref_conc.at(iter->first)),gamma.at(iter->first))) *pow(iter->second[j],gamma.at(iter->first)-1.) );
else
species_comp *= ( (gamma.at(iter->first)*pow(1./(ref_conc.at(iter->first)),gamma.at(iter->first))) /pow(iter->second[j],1.-gamma.at(iter->first)) );
}
else
species_comp *= ( pow(iter->second[j]/ref_conc.at(iter->first), gamma.at(iter->first)) );
}
dcurrent[j] = (catalyst->exchange_current_density(T[j]))*species_comp* ( exp( alpha_a*F*(phi_s[j]-phi_m[j]-(catalyst->voltage_cell_th(T[j])))/(R*T[j]) )
-
exp(-alpha_c*F*(phi_s[j]-phi_m[j]-(catalyst->voltage_cell_th(T[j])))/(R*T[j]) ) );
if (std::isinf(dcurrent[j]))
dcurrent[j] = std::numeric_limits<double>::max()*1e-150;
else if (std::isnan(dcurrent[j]))
dcurrent[j] = 0.0;
}
dcoef_du[ derivative_flags[i] ] = dcurrent;
}// x_O2 / x_H2 / Reactant concentrations
else if (derivative_flags[i] == protonic_electrical_potential)
{
for (unsigned int j=0; j<n_quad; ++j)
{
species_comp = 1.;
// Loop over each species in the reaction and compute its contribution
for (std::map< VariableNames, SolutionVariable >::const_iterator iter=reactants_map.begin(); iter != reactants_map.end(); ++iter)
{
if (iter->second[j] < 0.0)
species_comp *= 0.0;
else
species_comp *= ( pow(iter->second[j]/ref_conc.at(iter->first), gamma.at(iter->first)) );
}
dcurrent[j] = (catalyst->exchange_current_density(T[j]))*species_comp*( exp( alpha_a*F*(phi_s[j]-phi_m[j]-(catalyst->voltage_cell_th(T[j])))/(R*T[j]) )*( -alpha_a*F/(R*T[j]) )
-
exp(-alpha_c*F*(phi_s[j]-phi_m[j]-(catalyst->voltage_cell_th(T[j])))/(R*T[j]) )*( alpha_c*F/(R*T[j]) ) );
if (std::isinf(dcurrent[j]))
dcurrent[j] = std::numeric_limits<double>::max()*1e-150;
else if (std::isnan(dcurrent[j]))
dcurrent[j] = 0.0;
}
dcoef_du[protonic_electrical_potential] = dcurrent;
}//phi_m
else if (derivative_flags[i] == electronic_electrical_potential)
{
for (unsigned int j=0; j<n_quad; ++j)
{
species_comp = 1.;
// Loop over each species in the reaction and compute its contribution
for (std::map< VariableNames, SolutionVariable >::const_iterator iter=reactants_map.begin(); iter != reactants_map.end(); ++iter)
{
if (iter->second[j] < 0.0)
species_comp *= 0.0;
else
species_comp *= ( pow(iter->second[j]/ref_conc.at(iter->first), gamma.at(iter->first)) );
}
dcurrent[j] = (catalyst->exchange_current_density(T[j]))*species_comp*( exp( alpha_a*F*(phi_s[j]-phi_m[j]-(catalyst->voltage_cell_th(T[j])))/(R*T[j]) )*( alpha_a*F/(R*T[j]) )
-
exp(-alpha_c*F*(phi_s[j]-phi_m[j]-(catalyst->voltage_cell_th(T[j])))/(R*T[j]) )*(-alpha_c*F/(R*T[j]) ) );
if (std::isinf(dcurrent[j]))
dcurrent[j] = std::numeric_limits<double>::max()*1e-150;
else if (std::isnan(dcurrent[j]))
dcurrent[j] = 0.0;
}
dcoef_du[electronic_electrical_potential] = dcurrent;
}//phi_s
else if (derivative_flags[i] == temperature_of_REV)
{
for (unsigned int j=0; j<n_quad; ++j)
{
species_comp = 1.;
// Loop over each species in the reaction and compute its contribution
for (std::map< VariableNames, SolutionVariable >::const_iterator iter=reactants_map.begin(); iter != reactants_map.end(); ++iter)
{
if (iter->second[j] < 0.0)
species_comp *= 0.0;
else
species_comp *= ( pow(iter->second[j]/ref_conc.at(iter->first), gamma.at(iter->first)) );
}
double first_term = (catalyst->derivative_exchange_current_density(T[j]))*( exp( alpha_a*F*(phi_s[j]-phi_m[j]-(catalyst->voltage_cell_th(T[j])))/(R*T[j]) )
-
exp((-alpha_c*F*(phi_s[j]-phi_m[j]-(catalyst->voltage_cell_th(T[j]))))/(R*T[j])) );
double intermed_c = ( alpha_c*F*(phi_s[j]-phi_m[j]-(catalyst->voltage_cell_th(T[j])))/(R*pow(T[j],2.))) + (alpha_c*F*(catalyst->dvoltage_cell_th_dT(T[j]))/(R*T[j]));
double intermed_a = (-alpha_a*F*(phi_s[j]-phi_m[j]-(catalyst->voltage_cell_th(T[j])))/(R*pow(T[j],2.))) - (alpha_a*F*(catalyst->dvoltage_cell_th_dT(T[j]))/(R*T[j]));
double second_term = (catalyst->exchange_current_density(T[j])) * ( exp( alpha_a*F*(phi_s[j]-phi_m[j]-(catalyst->voltage_cell_th(T[j])))/(R*T[j]) )*intermed_a
-
exp((-alpha_c*F*(phi_s[j]-phi_m[j]-(catalyst->voltage_cell_th(T[j]))))/(R*T[j]))*intermed_c );
dcurrent[j] = species_comp*(first_term + second_term);
if (std::isinf(dcurrent[j]))
dcurrent[j] = std::numeric_limits<double>::max()*1e-150;
else if (std::isnan(dcurrent[j]))
dcurrent[j] = 0.0;
}
dcoef_du[temperature_of_REV] = dcurrent;
}//T
else
{
dcoef_du[ derivative_flags[i] ] = dcurrent;
}//everything else
}//end of derivative_flags loop
} | 53.246094 | 210 | 0.468418 | [
"vector",
"model"
] |
2eb8b81862f3c4a8a5dceaf327bbf67d117e0b88 | 7,734 | cpp | C++ | llvm-5.0.1.src/lib/DebugInfo/CodeView/TypeName.cpp | ShawnLess/TBD | fc98e93b3462509022fdf403978cd82aa05c2331 | [
"Apache-2.0"
] | 60 | 2017-12-21T06:49:58.000Z | 2022-02-24T09:43:52.000Z | llvm-5.0.1.src/lib/DebugInfo/CodeView/TypeName.cpp | ShawnLess/TBD | fc98e93b3462509022fdf403978cd82aa05c2331 | [
"Apache-2.0"
] | null | null | null | llvm-5.0.1.src/lib/DebugInfo/CodeView/TypeName.cpp | ShawnLess/TBD | fc98e93b3462509022fdf403978cd82aa05c2331 | [
"Apache-2.0"
] | 17 | 2017-12-20T09:54:56.000Z | 2021-06-24T05:39:36.000Z | //===- TypeName.cpp ------------------------------------------- *- C++ --*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/CodeView/TypeName.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
#include "llvm/DebugInfo/CodeView/TypeVisitorCallbacks.h"
#include "llvm/Support/FormatVariadic.h"
using namespace llvm;
using namespace llvm::codeview;
namespace {
class TypeNameComputer : public TypeVisitorCallbacks {
/// The type collection. Used to calculate names of nested types.
TypeCollection &Types;
TypeIndex CurrentTypeIndex = TypeIndex::None();
/// Name of the current type. Only valid before visitTypeEnd.
SmallString<256> Name;
public:
explicit TypeNameComputer(TypeCollection &Types) : Types(Types) {}
StringRef name() const { return Name; }
/// Paired begin/end actions for all types. Receives all record data,
/// including the fixed-length record prefix.
Error visitTypeBegin(CVType &Record) override;
Error visitTypeBegin(CVType &Record, TypeIndex Index) override;
Error visitTypeEnd(CVType &Record) override;
#define TYPE_RECORD(EnumName, EnumVal, Name) \
Error visitKnownRecord(CVType &CVR, Name##Record &Record) override;
#define TYPE_RECORD_ALIAS(EnumName, EnumVal, Name, AliasName)
#define MEMBER_RECORD(EnumName, EnumVal, Name)
#include "llvm/DebugInfo/CodeView/CodeViewTypes.def"
};
} // namespace
Error TypeNameComputer::visitTypeBegin(CVType &Record) {
llvm_unreachable("Must call visitTypeBegin with a TypeIndex!");
return Error::success();
}
Error TypeNameComputer::visitTypeBegin(CVType &Record, TypeIndex Index) {
// Reset Name to the empty string. If the visitor sets it, we know it.
Name = "";
CurrentTypeIndex = Index;
return Error::success();
}
Error TypeNameComputer::visitTypeEnd(CVType &CVR) { return Error::success(); }
Error TypeNameComputer::visitKnownRecord(CVType &CVR,
FieldListRecord &FieldList) {
Name = "<field list>";
return Error::success();
}
Error TypeNameComputer::visitKnownRecord(CVRecord<TypeLeafKind> &CVR,
StringIdRecord &String) {
Name = String.getString();
return Error::success();
}
Error TypeNameComputer::visitKnownRecord(CVType &CVR, ArgListRecord &Args) {
auto Indices = Args.getIndices();
uint32_t Size = Indices.size();
Name = "(";
for (uint32_t I = 0; I < Size; ++I) {
assert(Indices[I] < CurrentTypeIndex);
Name.append(Types.getTypeName(Indices[I]));
if (I + 1 != Size)
Name.append(", ");
}
Name.push_back(')');
return Error::success();
}
Error TypeNameComputer::visitKnownRecord(CVType &CVR,
StringListRecord &Strings) {
auto Indices = Strings.getIndices();
uint32_t Size = Indices.size();
Name = "\"";
for (uint32_t I = 0; I < Size; ++I) {
Name.append(Types.getTypeName(Indices[I]));
if (I + 1 != Size)
Name.append("\" \"");
}
Name.push_back('\"');
return Error::success();
}
Error TypeNameComputer::visitKnownRecord(CVType &CVR, ClassRecord &Class) {
Name = Class.getName();
return Error::success();
}
Error TypeNameComputer::visitKnownRecord(CVType &CVR, UnionRecord &Union) {
Name = Union.getName();
return Error::success();
}
Error TypeNameComputer::visitKnownRecord(CVType &CVR, EnumRecord &Enum) {
Name = Enum.getName();
return Error::success();
}
Error TypeNameComputer::visitKnownRecord(CVType &CVR, ArrayRecord &AT) {
Name = AT.getName();
return Error::success();
}
Error TypeNameComputer::visitKnownRecord(CVType &CVR, VFTableRecord &VFT) {
Name = VFT.getName();
return Error::success();
}
Error TypeNameComputer::visitKnownRecord(CVType &CVR, MemberFuncIdRecord &Id) {
Name = Id.getName();
return Error::success();
}
Error TypeNameComputer::visitKnownRecord(CVType &CVR, ProcedureRecord &Proc) {
StringRef Ret = Types.getTypeName(Proc.getReturnType());
StringRef Params = Types.getTypeName(Proc.getArgumentList());
Name = formatv("{0} {1}", Ret, Params).sstr<256>();
return Error::success();
}
Error TypeNameComputer::visitKnownRecord(CVType &CVR,
MemberFunctionRecord &MF) {
StringRef Ret = Types.getTypeName(MF.getReturnType());
StringRef Class = Types.getTypeName(MF.getClassType());
StringRef Params = Types.getTypeName(MF.getArgumentList());
Name = formatv("{0} {1}::{2}", Ret, Class, Params).sstr<256>();
return Error::success();
}
Error TypeNameComputer::visitKnownRecord(CVType &CVR, FuncIdRecord &Func) {
Name = Func.getName();
return Error::success();
}
Error TypeNameComputer::visitKnownRecord(CVType &CVR, TypeServer2Record &TS) {
Name = TS.getName();
return Error::success();
}
Error TypeNameComputer::visitKnownRecord(CVType &CVR, PointerRecord &Ptr) {
if (Ptr.isPointerToMember()) {
const MemberPointerInfo &MI = Ptr.getMemberInfo();
StringRef Pointee = Types.getTypeName(Ptr.getReferentType());
StringRef Class = Types.getTypeName(MI.getContainingType());
Name = formatv("{0} {1}::*", Pointee, Class);
} else {
if (Ptr.isConst())
Name.append("const ");
if (Ptr.isVolatile())
Name.append("volatile ");
if (Ptr.isUnaligned())
Name.append("__unaligned ");
Name.append(Types.getTypeName(Ptr.getReferentType()));
if (Ptr.getMode() == PointerMode::LValueReference)
Name.append("&");
else if (Ptr.getMode() == PointerMode::RValueReference)
Name.append("&&");
else if (Ptr.getMode() == PointerMode::Pointer)
Name.append("*");
}
return Error::success();
}
Error TypeNameComputer::visitKnownRecord(CVType &CVR, ModifierRecord &Mod) {
uint16_t Mods = static_cast<uint16_t>(Mod.getModifiers());
SmallString<256> TypeName;
if (Mods & uint16_t(ModifierOptions::Const))
Name.append("const ");
if (Mods & uint16_t(ModifierOptions::Volatile))
Name.append("volatile ");
if (Mods & uint16_t(ModifierOptions::Unaligned))
Name.append("__unaligned ");
Name.append(Types.getTypeName(Mod.getModifiedType()));
return Error::success();
}
Error TypeNameComputer::visitKnownRecord(CVType &CVR,
VFTableShapeRecord &Shape) {
Name = formatv("<vftable {0} methods>", Shape.getEntryCount());
return Error::success();
}
Error TypeNameComputer::visitKnownRecord(
CVType &CVR, UdtModSourceLineRecord &ModSourceLine) {
return Error::success();
}
Error TypeNameComputer::visitKnownRecord(CVType &CVR,
UdtSourceLineRecord &SourceLine) {
return Error::success();
}
Error TypeNameComputer::visitKnownRecord(CVType &CVR, BitFieldRecord &BF) {
return Error::success();
}
Error TypeNameComputer::visitKnownRecord(CVType &CVR,
MethodOverloadListRecord &Overloads) {
return Error::success();
}
Error TypeNameComputer::visitKnownRecord(CVType &CVR, BuildInfoRecord &BI) {
return Error::success();
}
Error TypeNameComputer::visitKnownRecord(CVType &CVR, LabelRecord &R) {
return Error::success();
}
std::string llvm::codeview::computeTypeName(TypeCollection &Types,
TypeIndex Index) {
TypeNameComputer Computer(Types);
CVType Record = Types.getType(Index);
if (auto EC = visitTypeRecord(Record, Index, Computer)) {
consumeError(std::move(EC));
return "<unknown UDT>";
}
return Computer.name();
}
| 31.696721 | 80 | 0.667184 | [
"shape"
] |
e48546fceedfdc75c828b9c97312564f108d54f9 | 1,287 | cpp | C++ | LeetCode/Tag/Dynamic Programming/cpp/213.house-robber-II.cpp | pakosel/competitive-coding-problems | 187a2f13725e06ab3301ae2be37f16fbec0c0588 | [
"MIT"
] | 17 | 2017-08-12T14:42:46.000Z | 2022-02-26T16:35:44.000Z | LeetCode/Tag/Dynamic Programming/cpp/213.house-robber-II.cpp | pakosel/competitive-coding-problems | 187a2f13725e06ab3301ae2be37f16fbec0c0588 | [
"MIT"
] | 21 | 2019-09-20T07:06:27.000Z | 2021-11-02T10:30:50.000Z | LeetCode/Tag/Dynamic Programming/cpp/213.house-robber-II.cpp | pakosel/competitive-coding-problems | 187a2f13725e06ab3301ae2be37f16fbec0c0588 | [
"MIT"
] | 21 | 2017-05-28T10:15:07.000Z | 2021-07-20T07:19:58.000Z | class Solution {
/* Since this question is a follow-up to House Robber,
* we can assume we already have a way to solve the simpler question,
* i.e. given a 1 row of house, we know how to rob them.
* We modify it a bit to rob a given range of houses [lo, hi].
*/
int rob(vector<int>& nums, int lo, int hi) {
int include = 0, exclude = 0;
for (int i = lo; i <= hi; ++i) {
int incl = exclude + nums[i];
exclude = max(include, exclude);
include = incl;
}
return max(include, exclude);
}
public:
/* you can break the circle by assuming a house is not robbed
* Since every house is either robbed or not robbed and at least half
* of the houses are not robbed, the solution is simply the larger of
* two cases with consecutive houses, i.e. house i not robbed, break the circle,
* solve it, or house i + 1 not robbed. Hence, the following solution.
* I chose i = n and i + 1 = 0 for simpler coding. But, you can choose whichever two consecutive ones.
*/
int rob(vector<int>& nums) {
if (!nums.size()) return 0;
if (nums.size() == 1) return nums[0];
return max (rob(nums, 0, nums.size()-2), rob(nums, 1, nums.size()-1));
}
}; | 41.516129 | 106 | 0.59596 | [
"vector"
] |
e48a828e73545eb1c5b60d108e0880b41c437172 | 3,795 | cpp | C++ | PSME/application/src/rest/endpoints/chassis/chassis_reset.cpp | opencomputeproject/HWMgmt-DeviceMgr-PSME | 2a00188aab6f4bef3776987f0842ef8a8ea972ac | [
"Apache-2.0"
] | 5 | 2021-10-07T15:36:37.000Z | 2022-03-01T07:21:49.000Z | PSME/application/src/rest/endpoints/chassis/chassis_reset.cpp | opencomputeproject/DM-Redfish-PSME | 912f7b6abf5b5c2aae33c75497de4753281c6a51 | [
"Apache-2.0"
] | null | null | null | PSME/application/src/rest/endpoints/chassis/chassis_reset.cpp | opencomputeproject/DM-Redfish-PSME | 912f7b6abf5b5c2aae33c75497de4753281c6a51 | [
"Apache-2.0"
] | 1 | 2021-03-24T19:37:58.000Z | 2021-03-24T19:37:58.000Z | /*
* Edgecore DeviceManager
* Copyright 2020-2021 Edgecore Networks, Inc.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include "agent-framework/module/requests/common.hpp"
#include "agent-framework/module/responses/common.hpp"
#include "agent-framework/module/constants/compute.hpp"
#include "psme/core/agent/agent_manager.hpp"
#include "psme/rest/constants/constants.hpp"
#include "psme/rest/validators/json_validator.hpp"
#include "psme/rest/validators/schemas/reset.hpp"
#include "psme/rest/endpoints/chassis/chassis_reset.hpp"
#include "psme/rest/server/error/error_factory.hpp"
#include "psme/rest/model/handlers/generic_handler_deps.hpp"
#include "psme/rest/model/handlers/generic_handler.hpp"
#include "psme/rest/utils/ec_common_utils.hpp"
#include "ecsys_helper/ecsys_helper.hpp"
using namespace psme::rest::utils;
using namespace psme::rest;
using namespace psme::rest::constants;
using namespace psme::rest::validators;
using namespace ecsys_helper;
endpoint::ChassisReset::ChassisReset(const std::string& path) : EndpointBase(path) {}
endpoint::ChassisReset::~ChassisReset() {}
void endpoint::ChassisReset::post(const server::Request& request, server::Response& response) {
char command[BUFFER_LEN] = {0};
char resultA[BUFFER_LEN] = {0};
const auto& json = JsonValidator::validate_request_body<schema::ResetPostSchema>(request);
agent_framework::model::attribute::Attributes attributes{};
if (json.is_member(constants::Common::RESET_TYPE)) {
const auto& reset_type = json[constants::Common::RESET_TYPE].as_string();
attributes.set_value(agent_framework::model::literals::System::POWER_STATE, reset_type);
using ResetType = agent_framework::model::enums::ResetType;
const auto reset_type_e = ResetType::from_string(reset_type);
switch (reset_type_e) {
case agent_framework::model::enums::ResetType::None:
case agent_framework::model::enums::ResetType::ForceOn:
case agent_framework::model::enums::ResetType::Nmi:
default:
break;
case agent_framework::model::enums::ResetType::On:
case agent_framework::model::enums::ResetType::GracefulRestart:
sprintf(command, "%s" ,"psme.sh set restart");
EcCommonUtils::exec_shell(command, resultA, 0);
break;
case agent_framework::model::enums::ResetType::PushPowerButton:
case agent_framework::model::enums::ResetType::ForceRestart:
sprintf(command, "%s" ,"psme.sh set force_restart");
EcCommonUtils::exec_shell(command, resultA, 0);
break;
case agent_framework::model::enums::ResetType::ForceOff:
sprintf(command, "%s" ,"psme.sh set force_off");
EcCommonUtils::exec_shell(command, resultA, 0);
break;
case agent_framework::model::enums::ResetType::GracefulShutdown:
sprintf(command, "%s" ,"psme.sh set shutdown");
EcCommonUtils::exec_shell(command, resultA, 0);
break;
}
}
if(!strncmp(resultA, "NOT support.", 12))
response.set_status(server::status_5XX::NOT_IMPLEMENTED);
else
response.set_status(server::status_2XX::OK);
}
| 39.947368 | 96 | 0.747299 | [
"model"
] |
e48b80cee6dd0b88c3024b2401573f553c118013 | 10,195 | hpp | C++ | include/exec_fused.hpp | geraldc-unm/Comb | 790d054f9722e6752a27a1c2e08c135f9d5b8e75 | [
"MIT"
] | 21 | 2018-10-03T18:15:04.000Z | 2022-02-16T08:07:50.000Z | include/exec_fused.hpp | geraldc-unm/Comb | 790d054f9722e6752a27a1c2e08c135f9d5b8e75 | [
"MIT"
] | 5 | 2019-10-07T23:06:57.000Z | 2021-08-16T16:10:58.000Z | include/exec_fused.hpp | geraldc-unm/Comb | 790d054f9722e6752a27a1c2e08c135f9d5b8e75 | [
"MIT"
] | 6 | 2019-09-13T16:47:33.000Z | 2022-03-03T16:17:32.000Z | //////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2018-2021, Lawrence Livermore National Security, LLC.
//
// Produced at the Lawrence Livermore National Laboratory
//
// LLNL-CODE-758885
//
// All rights reserved.
//
// This file is part of Comb.
//
// For details, see https://github.com/LLNL/Comb
// Please also see the LICENSE file for MIT license.
//////////////////////////////////////////////////////////////////////////////
#ifndef _FUSED_HPP
#define _FUSED_HPP
#include "config.hpp"
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <type_traits>
#include "memory.hpp"
#include "ExecContext.hpp"
#include "exec_utils.hpp"
inline bool& comb_allow_per_message_pack_fusing()
{
static bool allow = true;
return allow;
}
inline bool& comb_allow_pack_loop_fusion()
{
static bool allow = true;
return allow;
}
namespace detail {
template < typename body_type >
struct adapter_2d {
IdxT begin0, begin1;
IdxT len1;
body_type body;
template < typename body_type_ >
adapter_2d(IdxT begin0_, IdxT end0_, IdxT begin1_, IdxT end1_, body_type_&& body_)
: begin0(begin0_)
, begin1(begin1_)
, len1(end1_ - begin1_)
, body(std::forward<body_type_>(body_))
{ COMB::ignore_unused(end0_); }
COMB_HOST COMB_DEVICE
void operator() (IdxT i) const
{
IdxT i0 = i / len1;
IdxT i1 = i - i0 * len1;
//LOGPRINTF("adapter_2d (%i+%i %i+%i)%i\n", i0, begin0, i1, begin1, i);
//assert(0 <= i0 + begin0 && i0 + begin0 < 3);
//assert(0 <= i1 + begin1 && i1 + begin1 < 3);
body(i0 + begin0, i1 + begin1);
}
};
template < typename body_type >
struct adapter_3d {
IdxT begin0, begin1, begin2;
IdxT len2, len12;
body_type body;
template < typename body_type_ >
adapter_3d(IdxT begin0_, IdxT end0_, IdxT begin1_, IdxT end1_, IdxT begin2_, IdxT end2_, body_type_&& body_)
: begin0(begin0_)
, begin1(begin1_)
, begin2(begin2_)
, len2(end2_ - begin2_)
, len12((end1_ - begin1_) * (end2_ - begin2_))
, body(std::forward<body_type_>(body_))
{ COMB::ignore_unused(end0_); }
COMB_HOST COMB_DEVICE
void operator() (IdxT i) const
{
IdxT i0 = i / len12;
IdxT idx12 = i - i0 * len12;
IdxT i1 = idx12 / len2;
IdxT i2 = idx12 - i1 * len2;
//LOGPRINTF("adapter_3d (%i+%i %i+%i %i+%i)%i\n", i0, begin0, i1, begin1, i2, begin2, i);
//assert(0 <= i0 + begin0 && i0 + begin0 < 3);
//assert(0 <= i1 + begin1 && i1 + begin1 < 3);
//assert(0 <= i2 + begin2 && i2 + begin2 < 13);
body(i0 + begin0, i1 + begin1, i2 + begin2);
}
};
struct fused_packer
{
DataT const** srcs;
DataT** bufs;
LidxT const** idxs;
IdxT const* lens;
DataT const* src = nullptr;
DataT* bufk = nullptr;
DataT* buf = nullptr;
LidxT const* idx = nullptr;
IdxT len = 0;
fused_packer(DataT const** srcs_, DataT** bufs_, LidxT const** idxs_, IdxT const* lens_)
: srcs(srcs_)
, bufs(bufs_)
, idxs(idxs_)
, lens(lens_)
{ }
COMB_HOST COMB_DEVICE
void set_outer(IdxT k)
{
len = lens[k];
idx = idxs[k];
bufk = bufs[k];
}
COMB_HOST COMB_DEVICE
void set_inner(IdxT j)
{
src = srcs[j];
buf = bufk + j*len;
}
// must be run for all i in [0, len)
COMB_HOST COMB_DEVICE
void operator()(IdxT i)
{
// if (i == 0) {
// LOGPRINTF("fused_packer buf %p, src %p, idx %p, len %i\n", buf, src, idx, len); FFLUSH(stdout);
// }
buf[i] = src[idx[i]];
}
};
struct fused_unpacker
{
DataT** dsts;
DataT const** bufs;
LidxT const** idxs;
IdxT const* lens;
DataT* dst = nullptr;
DataT const* bufk = nullptr;
DataT const* buf = nullptr;
LidxT const* idx = nullptr;
IdxT len = 0;
fused_unpacker(DataT** dsts_, DataT const** bufs_, LidxT const** idxs_, IdxT const* lens_)
: dsts(dsts_)
, bufs(bufs_)
, idxs(idxs_)
, lens(lens_)
{ }
COMB_HOST COMB_DEVICE
void set_outer(IdxT k)
{
len = lens[k];
idx = idxs[k];
bufk = bufs[k];
}
COMB_HOST COMB_DEVICE
void set_inner(IdxT j)
{
dst = dsts[j];
buf = bufk + j*len;
}
// must be run for all i in [0, len)
COMB_HOST COMB_DEVICE
void operator()(IdxT i)
{
// if (i == 0) {
// LOGPRINTF("fused_packer buf %p, dst %p, idx %p, len %i\n", buf, dst, idx, len); FFLUSH(stdout);
// }
dst[idx[i]] = buf[i];
}
};
template < typename context_type >
struct FuserStorage
{
// note that these numbers are missing a factor of m_num_vars
IdxT m_num_fused_iterations = 0;
IdxT m_num_fused_loops_enqueued = 0;
IdxT m_num_fused_loops_executed = 0;
IdxT m_num_fused_loops_total = 0;
// vars for fused loops, stored in backend accessible memory
DataT** m_vars = nullptr;
IdxT m_num_vars = 0;
LidxT const** m_idxs = nullptr;
IdxT* m_lens = nullptr;
DataT ** get_dsts() { return m_vars; }
DataT const** get_srcs() { return (DataT const**)m_vars; }
void allocate(context_type& con, std::vector<DataT*> const& variables, IdxT num_loops)
{
if (m_vars == nullptr) {
m_num_fused_iterations = 0;
m_num_fused_loops_enqueued = 0;
m_num_fused_loops_executed = 0;
m_num_fused_loops_total = num_loops;
// allocate per variable vars
m_num_vars = variables.size();
m_vars = (DataT**)con.util_aloc.allocate(m_num_vars*sizeof(DataT const*));
// variable vars initialized here
for (IdxT i = 0; i < m_num_vars; ++i) {
m_vars[i] = variables[i];
}
// allocate per item vars
m_idxs = (LidxT const**)con.util_aloc.allocate(num_loops*sizeof(LidxT const*));
m_lens = (IdxT*) con.util_aloc.allocate(num_loops*sizeof(IdxT));
// item vars initialized in pack
}
}
// There is potentially a race condition on these buffers as the allocations
// are released back into the pool and could be used for another fuser
// before this fuser is done executing.
// This is safe for messages because there is synchronization between the
// allocations (irecv, isend) and deallocations (wait_recv, wait_send).
void deallocate(context_type& con)
{
if (m_vars != nullptr && this->m_num_fused_loops_executed == this->m_num_fused_loops_total) {
// deallocate per variable vars
con.util_aloc.deallocate(m_vars); m_vars = nullptr;
m_num_vars = 0;
// deallocate per item vars
con.util_aloc.deallocate(m_idxs); m_idxs = nullptr;
con.util_aloc.deallocate(m_lens); m_lens = nullptr;
}
}
};
template < typename context_type >
struct FuserPacker : FuserStorage<context_type>
{
using base = FuserStorage<context_type>;
DataT** m_bufs = nullptr;
void allocate(context_type& con, std::vector<DataT*> const& variables, IdxT num_items)
{
if (this->m_vars == nullptr) {
base::allocate(con, variables, num_items);
this->m_bufs = (DataT**)con.util_aloc.allocate(num_items*sizeof(DataT*));
}
}
// enqueue packing loops for all variables
void enqueue(context_type& /*con*/, DataT* buf, LidxT const* indices, const IdxT nitems)
{
this->m_bufs[this->m_num_fused_loops_enqueued] = buf;
this->m_idxs[this->m_num_fused_loops_enqueued] = indices;
this->m_lens[this->m_num_fused_loops_enqueued] = nitems;
this->m_num_fused_iterations += nitems;
this->m_num_fused_loops_enqueued += 1;
}
void exec(context_type& con)
{
IdxT num_fused_loops = this->m_num_fused_loops_enqueued - this->m_num_fused_loops_executed;
IdxT avg_iterations = (this->m_num_fused_iterations + num_fused_loops - 1) / num_fused_loops;
con.fused(num_fused_loops, this->m_num_vars, avg_iterations,
fused_packer(this->get_srcs(), this->m_bufs+this->m_num_fused_loops_executed,
this->m_idxs+this->m_num_fused_loops_executed,
this->m_lens+this->m_num_fused_loops_executed));
this->m_num_fused_iterations = 0;
this->m_num_fused_loops_executed = this->m_num_fused_loops_enqueued;
}
void deallocate(context_type& con)
{
if (this->m_vars != nullptr && this->m_num_fused_loops_executed == this->m_num_fused_loops_total) {
base::deallocate(con);
con.util_aloc.deallocate(this->m_bufs); this->m_bufs = nullptr;
}
}
};
template < typename context_type >
struct FuserUnpacker : FuserStorage<context_type>
{
using base = FuserStorage<context_type>;
DataT const** m_bufs = nullptr;
void allocate(context_type& con, std::vector<DataT*> const& variables, IdxT num_items)
{
if (this->m_vars == nullptr) {
base::allocate(con, variables, num_items);
this->m_bufs = (DataT const**)con.util_aloc.allocate(num_items*sizeof(DataT const*));
}
}
// enqueue unpacking loops for all variables
void enqueue(context_type& /*con*/, DataT const* buf, LidxT const* indices, const IdxT nitems)
{
this->m_bufs[this->m_num_fused_loops_enqueued] = buf;
this->m_idxs[this->m_num_fused_loops_enqueued] = indices;
this->m_lens[this->m_num_fused_loops_enqueued] = nitems;
this->m_num_fused_iterations += nitems;
this->m_num_fused_loops_enqueued += 1;
}
void exec(context_type& con)
{
IdxT num_fused_loops = this->m_num_fused_loops_enqueued - this->m_num_fused_loops_executed;
IdxT avg_iterations = (this->m_num_fused_iterations + num_fused_loops - 1) / num_fused_loops;
con.fused(num_fused_loops, this->m_num_vars, avg_iterations,
fused_unpacker(this->get_dsts(), this->m_bufs+this->m_num_fused_loops_executed,
this->m_idxs+this->m_num_fused_loops_executed,
this->m_lens+this->m_num_fused_loops_executed));
this->m_num_fused_iterations = 0;
this->m_num_fused_loops_executed = this->m_num_fused_loops_enqueued;
}
void deallocate(context_type& con)
{
if (this->m_vars != nullptr && this->m_num_fused_loops_executed == this->m_num_fused_loops_total) {
base::deallocate(con);
con.util_aloc.deallocate(this->m_bufs); this->m_bufs = nullptr;
}
}
};
} // namespace detail
#endif // _FUSED_HPP
| 28.240997 | 110 | 0.642962 | [
"vector"
] |
e48cf7015a065d01554c851b2de0731627d67e38 | 7,194 | hxx | C++ | main/connectivity/source/inc/ado/ACollection.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/connectivity/source/inc/ado/ACollection.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/connectivity/source/inc/ado/ACollection.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 _CONNECTIVITY_ADO_COLLECTION_HXX_
#define _CONNECTIVITY_ADO_COLLECTION_HXX_
#include <cppuhelper/implbase3.hxx>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/container/XIndexAccess.hpp>
#include "ado/Awrapadox.hxx"
#include "ado/Aolevariant.hxx"
#include <com/sun/star/lang/XServiceInfo.hpp>
namespace connectivity
{
namespace ado
{
namespace starcontainer = ::com::sun::star::container;
namespace starlang = ::com::sun::star::lang;
namespace staruno = ::com::sun::star::uno;
namespace starbeans = ::com::sun::star::beans;
typedef ::cppu::WeakImplHelper3< starcontainer::XNameAccess,
starcontainer::XIndexAccess,
starlang::XServiceInfo> OCollectionBase;
//************************************************************
// OCollection
//************************************************************
template <class T,class SimT,class OCl> class OCollection : public OCollectionBase
{
private:
OCollection( const OCollection& ); // never implemented
OCollection& operator=( const OCollection& ); // never implemented
protected:
vector<OCl*> m_aElements;
::cppu::OWeakObject& m_rParent;
::osl::Mutex& m_rMutex; // mutex of the parent
T* m_pCollection;
public:
OCollection(::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex,T* _pCollection)
: m_rParent(_rParent)
,m_rMutex(_rMutex)
,m_pCollection(_pCollection)
{
m_pCollection->AddRef();
}
~OCollection()
{
m_pCollection->Release();
}
virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (staruno::RuntimeException)
{
return ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.ACollection");
}
virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& _rServiceName ) throw(staruno::RuntimeException)
{
staruno::Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
const ::rtl::OUString* pSupported = aSupported.getConstArray();
for (sal_Int32 i=0; i<aSupported.getLength(); ++i, ++pSupported)
if (pSupported->equals(_rServiceName))
return sal_True;
return sal_False;
}
virtual staruno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(staruno::RuntimeException)
{
staruno::Sequence< ::rtl::OUString > aSupported(1);
aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.Container");
return aSupported;
}
// dispatch the refcounting to the parent
virtual void SAL_CALL acquire() throw()
{
m_rParent.acquire();
}
virtual void SAL_CALL release() throw()
{
m_rParent.release();
}
// ::com::sun::star::container::XElementAccess
virtual staruno::Type SAL_CALL getElementType( ) throw(staruno::RuntimeException)
{
return::getCppuType(static_cast< staruno::Reference< starbeans::XPropertySet>*>(NULL));
}
virtual sal_Bool SAL_CALL hasElements( ) throw(staruno::RuntimeException)
{
::osl::MutexGuard aGuard(m_rMutex);
return getCount() > 0;
}
// starcontainer::XIndexAccess
virtual sal_Int32 SAL_CALL getCount( ) throw(staruno::RuntimeException)
{
::osl::MutexGuard aGuard(m_rMutex);
sal_Int32 nCnt = 0;
m_pCollection->get_Count(&nCnt);
return nCnt;
}
virtual staruno::Any SAL_CALL getByIndex( sal_Int32 Index ) throw(starlang::IndexOutOfBoundsException, starlang::WrappedTargetException, staruno::RuntimeException)
{
::osl::MutexGuard aGuard(m_rMutex);
if (Index < 0 || Index >= getCount())
throw starlang::IndexOutOfBoundsException();
SimT* pCol = NULL;
m_pCollection->get_Item(OLEVariant(Index),&pCol);
if(!pCol)
throw starlang::IndexOutOfBoundsException();
OCl* pIndex = new OCl(pCol);
m_aElements.push_back(pIndex);
return staruno::makeAny( staruno::Reference< starbeans::XPropertySet >(pIndex));
}
// starcontainer::XNameAccess
virtual staruno::Any SAL_CALL getByName( const ::rtl::OUString& aName ) throw(starcontainer::NoSuchElementException, starlang::WrappedTargetException, staruno::RuntimeException)
{
::osl::MutexGuard aGuard(m_rMutex);
SimT* pCol = NULL;
m_pCollection->get_Item(OLEVariant(aName),&pCol);
if(!pCol)
throw starlang::IndexOutOfBoundsException();
OCl* pIndex = new OCl(pCol);
m_aElements.push_back(pIndex);
return staruno::makeAny( staruno::Reference< starbeans::XPropertySet >(pIndex));
}
virtual staruno::Sequence< ::rtl::OUString > SAL_CALL getElementNames( ) throw(staruno::RuntimeException)
{
::osl::MutexGuard aGuard(m_rMutex);
sal_Int32 nLen = getCount();
staruno::Sequence< ::rtl::OUString > aNameList(nLen);
::rtl::OUString* pStringArray = aNameList.getArray();
OLEVariant aVar;
for (sal_Int32 i=0;i<nLen;++i)
{
aVar.setInt32(i);
SimT* pIdx = NULL;
m_pCollection->get_Item(aVar,&pIdx);
pIdx->AddRef();
_bstr_t sBSTR;
pIdx->get_Name(&sBSTR);
(*pStringArray) = (sal_Unicode*)sBSTR;
pIdx->Release();
++pStringArray;
}
return aNameList;
}
virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName ) throw(staruno::RuntimeException)
{
::osl::MutexGuard aGuard(m_rMutex);
SimT* pCol = NULL;
m_pCollection->get_Item(OLEVariant(aName),&pCol);
return pCol != NULL;
}
void SAL_CALL disposing()
{
::osl::MutexGuard aGuard(m_rMutex);
for (::std::vector<OCl*>::const_iterator i = m_aElements.begin(); i != m_aElements.end(); ++i)
{
(*i)->disposing();
(*i)->release();
}
m_aElements.clear();
}
};
class OIndex;
class OKey;
class OColumn;
class OTable;
class OView;
class OGroup;
class OUser;
typedef OCollection< ADOIndexes,ADOIndex,OIndex> OIndexes;
typedef OCollection< ADOKeys,ADOKey,OKey> OKeys;
typedef OCollection< ADOColumns,ADOColumn,OColumn> OColumns;
typedef OCollection< ADOTables,ADOTable,OTable> OTables;
typedef OCollection< ADOViews,ADOView,OView> OViews;
typedef OCollection< ADOGroups,ADOGroup,OGroup> OGroups;
typedef OCollection< ADOUsers,ADOUser,OUser> OUsers;
}
}
#endif // _CONNECTIVITY_ADO_COLLECTION_HXX_
| 31.552632 | 180 | 0.66903 | [
"vector"
] |
e49aa58143e15dec0eb187ee18b992d5a3459a6b | 2,271 | cpp | C++ | OpenGL_S/OpenGL_S/BeamBillboard.cpp | CreoDen-dev/COSMO | 1603c734fc592dad58b553625e5ce90046d99758 | [
"Apache-2.0"
] | null | null | null | OpenGL_S/OpenGL_S/BeamBillboard.cpp | CreoDen-dev/COSMO | 1603c734fc592dad58b553625e5ce90046d99758 | [
"Apache-2.0"
] | null | null | null | OpenGL_S/OpenGL_S/BeamBillboard.cpp | CreoDen-dev/COSMO | 1603c734fc592dad58b553625e5ce90046d99758 | [
"Apache-2.0"
] | null | null | null | #include "BeamBillboard.h"
BeamBillboard::BeamBillboard() {
}
BeamBillboard::BeamBillboard(vec3 p, vec3 e, GLfloat w, GLfloat lt, GLuint tex) {
this->start = p;
this->end = e;
this->width = w;
this->texture = tex;
this->timer = lt;
this->useOuterNorm = false;
GLfloat len = glm::length(e - p);
GLfloat vertices[] =
{
// Positions // Texture Coords
len, 0.f, w / 2.f, 0., 1., 0., 1.0f, 0.0f, // Top Right
len, 0.f, -w / 2.f, 0., 1., 0., 1.0f, 1.0f, // Bottom Right
0.f, 0.f, -w / 2.f, 0., 1., 0., 0.0f, 1.0f, // Bottom Left
0.f, 0.f, w / 2.f, 0., 1., 0., 0.0f, 0.0f // Top Left
};
GLuint indices[] =
{
0, 1, 3,
1, 2, 3
};
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &EBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid *)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid *)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid *)(6 * sizeof(GLfloat)));
glEnableVertexAttribArray(2);
glBindVertexArray(0);
}
void BeamBillboard::render(Shader & shader, Camera * camera) {
vec3 front = glm::normalize(this->end - this->start);
vec3 norm;
if (this->useOuterNorm)
norm = this->outerNorm;
else
norm = glm::normalize(camera->position + front * glm::dot(camera->position - this->start, front) - this->start);
mat4 model(vec4(front, 0.), vec4(norm, 0.), vec4(glm::cross(front, norm), 0.), vec4(this->start, 1.));
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
glBindVertexArray(this->VAO);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, this->texture);
glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
}
GLboolean BeamBillboard::update(GLfloat delta) {
this->timer -= delta;
return this->timer > 0.f;
}
| 28.746835 | 114 | 0.677235 | [
"render",
"model"
] |
e49af9ab142c8b0b59e36e33ee64c3d7f9046a7f | 4,552 | cpp | C++ | Silver/Silver/silver_core.cpp | c272/silver | 2721731c7803882e5b70118253237d565a3b6709 | [
"Apache-2.0"
] | null | null | null | Silver/Silver/silver_core.cpp | c272/silver | 2721731c7803882e5b70118253237d565a3b6709 | [
"Apache-2.0"
] | 1 | 2018-09-16T14:09:18.000Z | 2018-09-16T14:09:18.000Z | Silver/Silver/silver_core.cpp | c272/silver | 2721731c7803882e5b70118253237d565a3b6709 | [
"Apache-2.0"
] | null | null | null | //Including SILVER_CORE header and includes.
#include "silver_inc.h"
#include "silver_core.h"
#include "silver_primitive.h"
#include "silver_renderbus.h"
// SECTION 0
// GLOBAL DECLARATION
SDL_GLContext slvr::glGhostContext = NULL;
bool slvr::isGlInitialized = false;
// SECTION I
// FUNCTION DECLARATION
//Starts SDL and GLEW for OpenGL commands. Runs when a window is created.
void slvr::slInitBasic() {
//Checking if SDL/GLEW is already up and running.
if (slvr::isGlInitialized == false) {
std::cout << "Initializing...\n";
//Initializing SDL.
if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
std::cout << "FATAL ERROR: SDL could not initialize. Please check dump for errors.\n";
exit(-1);
}
//Starting GLEW.
glewExperimental = true;
glewInit();
//Setting initialized bool to true.
slvr::isGlInitialized = true;
}
}
///The main window of Silver, must be started to display things on screen.
///Parameters: (std::string [nameofwindow], int [widthofwindow], int [heightofwindow], OPTIONAL int [iscentered=false])
slvr::Window::Window(std::string name, int width, int height, bool centered = false) {
//Starting SDL and OpenGL.
slvr::slInitBasic();
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
//Creating window and GLContext.
//Checking whether to create as SDL_WINDOWPOS_CENTERED or SDL_WINDOWPOS_UNDEFINED.
if (centered) {
winlocation = SDL_CreateWindow(name.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL|SDL_WINDOW_RESIZABLE);
}
else {
winlocation = SDL_CreateWindow(name.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_OPENGL|SDL_WINDOW_RESIZABLE);
}
//GLContext being addressed into class.
slvr::glGhostContext = SDL_GL_CreateContext(winlocation);
glContextLocation = &slvr::glGhostContext;
//Finished construction.
SDL_SetWindowBordered(winlocation, SDL_TRUE);
}
//Window destructor, deletes all dangling pointers and memory.
slvr::Window::~Window() {
//Deleting dangling pointers and window before removing class.
slvr::glGhostContext = NULL;
glContextLocation = NULL;
SDL_DestroyWindow(winlocation);
winlocation = NULL;
}
///slvr::Window::getWindow()
///Gets the window pointer from private storage to use as a raw variable.
///Parameters: ()
SDL_Window* slvr::Window::getWindow() {
return winlocation;
}
///slvr::Window::poll()
///Returns the currently pressed key or event enum.
///Parameters: ()
SLVR_KEY slvr::Window::poll() {
if (SDL_PollEvent(&quitEvent) != 0) {
switch (quitEvent.type) {
case SDL_QUIT:
return QUIT;
break;
case SDL_KEYDOWN:
switch (quitEvent.key.keysym.sym) {
case SDLK_a:
return a;
break;
case SDLK_b:
return b;
break;
case SDLK_c:
return c;
break;
case SDLK_d:
return d;
break;
case SDLK_e:
return e;
break;
case SDLK_f:
return f;
break;
case SDLK_g:
return g;
break;
case SDLK_h:
return h;
break;
case SDLK_i:
return i;
break;
case SDLK_j:
return j;
break;
case SDLK_k:
return k;
break;
case SDLK_l:
return l;
break;
case SDLK_m:
return m;
break;
case SDLK_n:
return n;
break;
case SDLK_o:
return o;
break;
case SDLK_p:
return p;
break;
case SDLK_q:
return q;
case SDLK_r:
return r;
break;
case SDLK_s:
return s;
break;
case SDLK_t:
return t;
break;
case SDLK_u:
return u;
break;
case SDLK_v:
return v;
break;
case SDLK_w:
return w;
break;
case SDLK_x:
return x;
break;
case SDLK_y:
return y;
break;
case SDLK_z:
return z;
break;
//TODO: Implement the rest of the keys from A-Z and 0-9, plus symbols.
default:
return NOKEY;
}
break;
default:
return NOKEY;
}
}
else {
return NOKEY;
}
}
///slvr::Window::renderTest()
///Renders a basic test card to check the window is working correctly.
///Parameters: ()
void slvr::Window::renderTest() {
if (slvr::isGlInitialized == true && winlocation != NULL && glContextLocation!=NULL) {
//Everything's setup already, render test to screen now.
glClearColor(0.0f, 0.0f, 0.7f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
//Rendering.
SDL_GL_SwapWindow(winlocation);
}
else {
std::cout << "ERROR: Cannot render test card, GL is not initialized, or init() function has not been run.\n";
}
}
| 23.106599 | 152 | 0.685413 | [
"render"
] |
e49fed5e883b85e5d898b9e0b894cd7be3fbdeb6 | 11,448 | cc | C++ | builtin/python/python_converters.cc | mldbai/mldb | 0554aa390a563a6294ecc841f8026a88139c3041 | [
"Apache-2.0"
] | 665 | 2015-12-09T17:00:14.000Z | 2022-03-25T07:46:46.000Z | builtin/python/python_converters.cc | mldbai/mldb | 0554aa390a563a6294ecc841f8026a88139c3041 | [
"Apache-2.0"
] | 797 | 2015-12-09T19:48:19.000Z | 2022-03-07T02:19:47.000Z | builtin/python/python_converters.cc | mldbai/mldb | 0554aa390a563a6294ecc841f8026a88139c3041 | [
"Apache-2.0"
] | 103 | 2015-12-25T04:39:29.000Z | 2022-02-03T02:55:22.000Z | /** python_converters.cc
Jeremy Barnes, 7 December 2015
Copyright (c) 2015 mldb.ai inc. All rights reserved.
This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.
*/
#include "python_converters.h"
#include "python_interpreter.h"
#include "from_python_converter.h"
#include "mldb_python_converters.h"
#include "Python.h"
#include "datetime.h"
#include <iostream>
using namespace std;
namespace bp = boost::python;
namespace MLDB {
namespace Python {
/******************************************************************************/
/* DATE TO DATE TIME */
/******************************************************************************/
PyObject*
DateToPython::
convert(const Date& date)
{
tm time = date.toTm();
// no incref required because returning it transfers ownership
return PyDateTime_FromDateAndTime(
time.tm_year + 1900,
time.tm_mon + 1,
time.tm_mday,
time.tm_hour,
time.tm_min,
time.tm_sec,
0.
);
}
/******************************************************************************/
/* DATE FROM PYTHON */
/******************************************************************************/
void*
DateFromPython::
convertible(PyObject* obj_ptr)
{
//ExcAssert(&PyDateTime_DateTimeType);
if (!obj_ptr)
return nullptr;
if (!PyDateTime_Check(obj_ptr) && !PyFloat_Check(obj_ptr) &&
!PyLong_Check(obj_ptr) && !PyUnicode_Check(obj_ptr)) {
return nullptr;
}
return obj_ptr;
}
void
DateFromPython::
construct(PyObject* obj_ptr, void* storage)
{
if (PyFloat_Check(obj_ptr)) {
Date x = Date::fromSecondsSinceEpoch(PyFloat_AS_DOUBLE(obj_ptr));
new (storage) Date(x);
} else if (PyLong_Check(obj_ptr)) {
Date x = Date::fromSecondsSinceEpoch(PyLong_AS_LONG(obj_ptr));
new (storage) Date(x);
} else if (PyUnicode_Check(obj_ptr)) {
std::string str = bp::extract<std::string>(obj_ptr)();
Date x = Date::parseIso8601DateTime(str);
new (storage) Date(x);
} else {
new (storage) Date(
PyDateTime_GET_YEAR(obj_ptr),
PyDateTime_GET_MONTH(obj_ptr),
PyDateTime_GET_DAY(obj_ptr),
PyDateTime_DATE_GET_HOUR(obj_ptr),
PyDateTime_DATE_GET_MINUTE(obj_ptr),
PyDateTime_DATE_GET_SECOND(obj_ptr),
static_cast<double>(
PyDateTime_DATE_GET_MICROSECOND(obj_ptr)) / 1000000.);
}
}
/******************************************************************************/
/* DATE TO DOUBLE */
/******************************************************************************/
PyObject*
DateToPyFloat::
convert(const Date& date)
{
return PyFloat_FromDouble(date.secondsSinceEpoch());
}
/******************************************************************************/
/* LONG FROM PYTHON */
/******************************************************************************/
void*
StringFromPyUnicode::
convertible(PyObject* obj_ptr)
{
if (!PyUnicode_Check(obj_ptr)){
return 0;
}
return obj_ptr;
}
void
StringFromPyUnicode::
construct(PyObject* obj_ptr, void* storage)
{
PyObject* from_unicode;
if (PyUnicode_Check(obj_ptr)){
from_unicode = PyUnicode_AsUTF8String(obj_ptr);
}
else {
from_unicode = obj_ptr;
}
ExcCheck(from_unicode!=nullptr, "Error converting unicode to ASCII");
new (storage) std::string(
bp::extract<std::string>(from_unicode)());
Py_XDECREF(from_unicode);
}
void*
Utf8StringPyConverter::
convertible(PyObject* obj_ptr)
{
if (!PyUnicode_Check(obj_ptr)){
return 0;
}
return obj_ptr;
}
void
Utf8StringPyConverter::
construct(PyObject* obj_ptr, void* storage)
{
PyObject* from_unicode;
if (PyUnicode_Check(obj_ptr)){
from_unicode = PyUnicode_AsUTF8String(obj_ptr);
}
else {
from_unicode = obj_ptr;
}
ExcCheck(from_unicode!=nullptr, "Error converting unicode to ASCII");
new (storage) Utf8String(
bp::extract<std::string>(from_unicode)());
Py_XDECREF(from_unicode);
}
PyObject*
Utf8StringPyConverter::
convert(const Utf8String & str)
{
return PyUnicode_FromStringAndSize(str.rawData(), str.rawLength());
}
/******************************************************************************/
/* Json::Value CONVERTER */
/******************************************************************************/
void*
JsonValueConverter::
convertible(PyObject* obj)
{
return obj;
}
template<typename LstType>
Json::Value
construct_lst(PyObject * pyObj)
{
Json::Value val(Json::ValueType::arrayValue);
LstType tpl = bp::extract<LstType>(pyObj);
for(int i = 0; i < len(tpl); i++) {
bp::object obj = bp::object(tpl[i]);
val.append(JsonValueConverter::construct_recur(obj.ptr()));
}
return val;
}
Json::Value
JsonValueConverter::
construct_recur(PyObject * pyObj)
{
Json::Value val;
if (PyBool_Check(pyObj)) {
bool b = bp::extract<bool>(pyObj);
val = b;
}
else if(PyLong_Check(pyObj)) {
int64_t i = bp::extract<int64_t>(pyObj);
val = i;
}
else if(PyFloat_Check(pyObj)) {
float flt = bp::extract<float>(pyObj);
val = flt;
}
else if(PyUnicode_Check(pyObj)) {
// https://docs.python.org/2/c-api/unicode.html#c.PyUnicode_AsUTF8String
PyObject* from_unicode = PyUnicode_AsUTF8String(pyObj);
if(!from_unicode) {
PyObject* str_obj = PyObject_Str(pyObj);
std::string str_rep = "<Unable to create str representation of object>";
if(str_obj) {
str_rep = bp::extract<std::string>(str_obj);
}
// not returned so needs to be garbage collected
Py_DECREF(str_obj);
throw MLDB::Exception("Unable to encode unicode to UTF-8"
"Str representation: "+str_rep);
}
else {
std::string str = bp::extract<std::string>(from_unicode);
val = Utf8String(str);
// not returned so needs to be garbage collected
Py_DECREF(from_unicode);
}
}
//else if(PyDateTime_Check(pyObj)) {
// throw MLDB::Exception("do datetime!!");
//}
else if(PyTuple_Check(pyObj)) {
val = construct_lst<bp::tuple>(pyObj);
}
else if(PyList_Check(pyObj)) {
val = construct_lst<bp::list>(pyObj);
}
else if(PyDict_Check(pyObj)) {
val = Json::objectValue;
PyDict pyDict = bp::extract<PyDict>(pyObj)();
bp::list keys = pyDict.keys();
for(int i = 0; i < len(keys); i++) {
// if(!PyString_Check(keys[i]))
// throw MLDB::Exception("PyDict to JsVal only supports string keys");
std::string key = bp::extract<std::string>(keys[i]);
bp::object obj = bp::object(pyDict[keys[i]]);
val[key] = construct_recur(obj.ptr());
}
}
else if(pyObj == Py_None) {
// nothing to do. leave Json::Value empty
}
else {
// try to create a string reprensetation of object for a better error msg
PyObject* str_obj = PyObject_Str(pyObj);
PyObject* rep_obj = PyObject_Repr(pyObj);
std::string str_rep = "<Unable to create str representation of object>";
if(str_obj && rep_obj) {
str_rep = bp::extract<std::string>(rep_obj);
str_rep += " ";
str_rep += bp::extract<std::string>(str_obj);
}
// not returned so needs to be garbage collected
Py_DECREF(str_obj);
Py_DECREF(rep_obj);
throw MLDB::Exception("Unknown type in PyDict to JsVal converter. "
"Str representation: "+str_rep);
}
return val;
}
void
JsonValueConverter::
construct(PyObject* obj, void* storage)
{
Json::Value* js = new (storage) Json::Value();
(*js) = construct_recur(obj);
}
bp::object*
JsonValueConverter::
convert_recur(const Json::Value & js)
{
if(js.isIntegral()) {
//TODO this is pretty ugly. find the right way to do this
int i = js.asInt();
auto int_as_str = boost::lexical_cast<std::string>(i);
PyObject* pyobj = PyLong_FromString(const_cast<char*>(int_as_str.c_str()), NULL, 10);
// When you want a bp::object to manage a pointer to PyObject* pyobj one does:
// bp::object o(bp::handle<>(pyobj));
// In this case, the o object, manages the pyobj, it won’t increase the reference count on construction.
return new bp::object(bp::handle<>(pyobj));
// using the code below will always return a long
// return new bp::int(js.asInt());
}
else if(js.isDouble()) {
return new bp::object(js.asDouble());
}
else if(js.isString()) {
return new bp::str(js.asString());
}
else if(js.isArray()) {
bp::list* lst = new bp::list();
for(int i=0; i<js.size(); i++) {
lst->append(js[i]);
}
return lst;
}
else if(js.isObject()) {
PyDict * dict = new PyDict();
for (const std::string & id : js.getMemberNames()) {
(*dict)[id.c_str()] = js[id];
}
return dict;
}
else {
throw MLDB::Exception("Unknown type is JsVal to PyDict converter");
}
}
PyObject*
JsonValueConverter::
convert(const Json::Value & js)
{
return bp::incref(convert_recur(js)->ptr());
}
void pythonConvertersInit(const EnterThreadToken & thread)
{
namespace bp = boost::python;
PyDateTime_IMPORT;
from_python_converter< Date, DateFromPython >();
from_python_converter< std::string, StringFromPyUnicode>();
from_python_converter< Utf8String, Utf8StringPyConverter>();
bp::to_python_converter< Utf8String, Utf8StringPyConverter>();
from_python_converter< Path, StrConstructableIdFromPython<Path> >();
from_python_converter< CellValue, CellValueConverter >();
from_python_converter<std::pair<string, string>,
PairConverter<string, string> >();
bp::to_python_converter<std::pair<string, string>,
PairConverter<string, string> >();
from_python_converter< Path, PathConverter>();
from_python_converter< Json::Value, JsonValueConverter>();
bp::to_python_converter< Json::Value, JsonValueConverter> ();
bp::class_<MLDB::Any, boost::noncopyable>("any", bp::no_init)
.def("as_json", &MLDB::Any::asJson)
;
}
RegisterPythonInitializer regMe(&pythonConvertersInit);
} // namespace Python
} // namespace MLDB
| 30.366048 | 114 | 0.533805 | [
"object"
] |
e4a792b2338668a97293519dc77a18553fe6aa0e | 7,982 | cxx | C++ | src/tutorials/c++/basics/doSumProdInference.cxx | jasjuang/opengm | 3c098e91244c98dbd3aafdc5e3a54dad67b7dfd9 | [
"MIT"
] | 318 | 2015-01-07T15:22:02.000Z | 2022-01-22T10:10:29.000Z | src/tutorials/c++/basics/doSumProdInference.cxx | jasjuang/opengm | 3c098e91244c98dbd3aafdc5e3a54dad67b7dfd9 | [
"MIT"
] | 89 | 2015-03-24T14:33:01.000Z | 2020-07-10T13:59:13.000Z | src/tutorials/c++/basics/doSumProdInference.cxx | jasjuang/opengm | 3c098e91244c98dbd3aafdc5e3a54dad67b7dfd9 | [
"MIT"
] | 119 | 2015-01-13T08:35:03.000Z | 2022-03-01T01:49:08.000Z | /***********************************************************************
* Tutorial: Inference on the Sum-Prod-Semiring (marginalization)
* Author: Joerg Hendrik Kappes
* Date: 09.07.2014
* Dependencies: None
*
* Description:
* ------------
* This Example construct a model and find the labeling with the lowest energy
*
************************************************************************/
#include <iostream>
#include <opengm/opengm.hxx>
#include <opengm/graphicalmodel/graphicalmodel.hxx>
#include <opengm/operations/adder.hxx>
#include <opengm/functions/potts.hxx>
#include <opengm/inference/icm.hxx>
#include <opengm/inference/messagepassing/messagepassing.hxx>
#include <opengm/inference/trws/trws_trws.hxx>
#include <opengm/inference/trws/smooth_nesterov.hxx>
//*******************
//** Typedefs
//*******************
typedef double ValueType; // type used for values
typedef size_t IndexType; // type used for indexing nodes and factors (default : size_t)
typedef size_t LabelType; // type used for labels (default : size_t)
typedef opengm::Multiplier OpType; // operation used to combine terms
typedef opengm::ExplicitFunction<ValueType,IndexType,LabelType> ExplicitFunction; // shortcut for explicite function
typedef opengm::PottsFunction<ValueType,IndexType,LabelType> PottsFunction; // shortcut for Potts function
typedef opengm::meta::TypeListGenerator<ExplicitFunction,PottsFunction>::type FunctionTypeList; // list of all function the model cal use (this trick avoids virtual methods) - here only one
typedef opengm::DiscreteSpace<IndexType, LabelType> SpaceType; // type used to define the feasible statespace
typedef opengm::GraphicalModel<ValueType,OpType,FunctionTypeList,SpaceType> Model; // type of the model
typedef Model::FunctionIdentifier FunctionIdentifier; // type of the function identifier
Model buildGrid(){
IndexType N = 6;
IndexType M = 4;
int data[] = { 4, 4, 4, 4, 6, 0,
0, 7, 2, 4, 4, 0,
9, 9, 4, 4, 9, 9,
2, 2, 9, 9, 9, 9 };
std::cout << "Start building the grid model ... "<<std::endl;
// Build empty Model
LabelType numLabel = 2;
std::vector<LabelType> numbersOfLabels(N*M,numLabel);
Model gm(SpaceType(numbersOfLabels.begin(), numbersOfLabels.end()));
// Add 1st order functions and factors to the model
for(IndexType variable = 0; variable < gm.numberOfVariables(); ++variable) {
// construct 1st order function
const LabelType shape[] = {gm.numberOfLabels(variable)};
ExplicitFunction f(shape, shape + 1);
f(0) = std::exp(-std::fabs(data[variable] - 2.0));
f(1) = std::exp(-std::fabs(data[variable] - 8.0));
// add function
FunctionIdentifier id = gm.addFunction(f);
// add factor
IndexType variableIndex[] = {variable};
gm.addFactor(id, variableIndex, variableIndex + 1);
}
// add 2nd order functions for all variables neighbored on the grid
{
// add a potts function to the model
PottsFunction potts(numLabel, numLabel, 0.1, 0.4);
FunctionIdentifier pottsid = gm.addFunction(potts);
IndexType vars[] = {0,1};
for(IndexType n=0; n<N;++n){
for(IndexType m=0; m<M;++m){
vars[0] = n + m*N;
if(n+1<N){ //check for right neighbor
vars[1] = (n+1) + (m )*N;
OPENGM_ASSERT(vars[0] < vars[1]); // variables need to be ordered!
gm.addFactor(pottsid, vars, vars + 2);
}
if(m+1<M){ //check for lower neighbor
vars[1] = (n ) + (m+1)*N;
OPENGM_ASSERT(vars[0] < vars[1]); // variables need to be ordered!
gm.addFactor(pottsid, vars, vars + 2);
}
}
}
}
return gm;
}
Model buildChain(size_t N){
std::cout << "Start building the chain model ... "<<std::endl;
LabelType numLabel = 10;
std::vector<LabelType> numbersOfLabels(N,numLabel);
Model gm(SpaceType(numbersOfLabels.begin(), numbersOfLabels.end()));
// Add 1st order functions and factors to the model
for(IndexType variable = 0; variable < gm.numberOfVariables(); ++variable) {
// construct 1st order function
const LabelType shape[] = {gm.numberOfLabels(variable)};
ExplicitFunction f(shape, shape + 1);
for (size_t i=0; i<numLabel; ++i)
f(i) = static_cast<ValueType>(rand()) / (RAND_MAX) * 1000.0;
FunctionIdentifier id = gm.addFunction(f);
IndexType variableIndex[] = {variable};
gm.addFactor(id, variableIndex, variableIndex + 1);
}
// add 2nd order functions for all variables neighbored on the chain
for(IndexType variable = 0; variable < gm.numberOfVariables()-1; ++variable) {
// construct 1st order function
const IndexType vars[] = {variable,variable+1};
const LabelType shape[] = {gm.numberOfLabels(variable),gm.numberOfLabels(variable+1)};
ExplicitFunction f(shape, shape + 2);
for (size_t i=0; i<numLabel; ++i)
for (size_t j=0; j<numLabel; ++j)
f(i,j) = static_cast<ValueType>(rand()) / (RAND_MAX) * 1000.0;
FunctionIdentifier id = gm.addFunction(f);
gm.addFactor(id, vars, vars + 2);
}
return gm;
}
void inferBP(const Model& gm, bool normalization = true){
typedef opengm::BeliefPropagationUpdateRules<Model, opengm::Integrator> UpdateRules;
typedef opengm::MessagePassing<Model, opengm::Integrator, UpdateRules, opengm::MaxDistance> LBP;
LBP::Parameter parameter(size_t(100)); //maximal number of iterations=0
parameter.useNormalization_ = normalization;
LBP lbp(gm, parameter);
lbp.infer();
Model::IndependentFactorType marg;
for(IndexType var=0; var<gm.numberOfVariables(); ++var)
{
std::cout<< "Variable 0 has the following marginal distribution P(x_"<<var<<") :";
lbp.marginal(var,marg);
for(LabelType i=0; i<gm.numberOfLabels(var); ++i)
std::cout <<marg(&i) << " ";
std::cout<<std::endl;
}
}
//void inferNesterov(const Model& gm){
// //This is a dummy - Bogdan will finalize it ...
//
// typedef opengm::NesterovAcceleratedGradient<Model,opengm::Integrator> INF;
// INF::Parameter parameter(100); //maximal number of iterations
// parameter.verbose_=true;
//
// INF inf(gm, parameter);
//
// inf.infer();
//
// Model::IndependentFactorType marg;
// for(IndexType var=0; var<gm.numberOfVariables(); ++var)
// {
// std::cout<< "Variable 0 has the following marginal distribution P(x_"<<var<<") :";
// inf.marginal(var,marg);
// for(LabelType i=0; i<gm.numberOfLabels(var); ++i)
// std::cout <<marg(&i) << " ";
// std::cout<<std::endl;
// }
//
//}
int main(int argc, char** argv) {
std::cout <<"Sum-Prod-Semiring"<<std::endl;
// Infer with LBP
std::cout << "Start LBP inference ... " <<std::endl;
Model gmGrid = buildGrid();
inferBP(gmGrid);
Model gmChain = buildChain(10);
std::cout<< "Inference on small chain with no normalization" <<std::endl;
inferBP(gmChain,false);
std::cout<< "Inference on small chain with normalization" <<std::endl;
inferBP(gmChain,true);
Model gmChain2 = buildChain(4);
std::cout<< "Inference on large chain with no normalization" <<std::endl;
inferBP(gmChain2,false);
std::cout<< "Inference on large chain with normalization" <<std::endl;
inferBP(gmChain2,true);
//std::cout<< "Inference on large chain with Nesterov" <<std::endl;
//inferNesterov(gmChain2);
return 0;
};
| 40.72449 | 192 | 0.600351 | [
"shape",
"vector",
"model"
] |
e4a9da554bb3bcebf47431b3e8de5b735e95d610 | 380 | hpp | C++ | LeetCode/1005_MaximizeSumOfArrayAfterKNegations.hpp | defUserName-404/Online-Judge | 197ac5bf3e2149474b191eeff106b12cd723ec8c | [
"MIT"
] | null | null | null | LeetCode/1005_MaximizeSumOfArrayAfterKNegations.hpp | defUserName-404/Online-Judge | 197ac5bf3e2149474b191eeff106b12cd723ec8c | [
"MIT"
] | null | null | null | LeetCode/1005_MaximizeSumOfArrayAfterKNegations.hpp | defUserName-404/Online-Judge | 197ac5bf3e2149474b191eeff106b12cd723ec8c | [
"MIT"
] | null | null | null | #include <algorithm>
#include <vector>
// W/A
class Solution
{
public:
int largestSumAfterKNegations(std::vector<int> &nums, int k);
};
int Solution::largestSumAfterKNegations(std::vector<int> &nums, int k)
{
std::sort(nums.begin(), nums.end());
int sum = 0, negatives = 0;
for (int &x : nums)
{
if (x < 0)
}
return sum;
}
| 14.615385 | 70 | 0.573684 | [
"vector"
] |
e4aebf6e027cab4096817c5b7c8a4ee6d4a72b1e | 1,031 | cxx | C++ | StRoot/RTS/EventTracker/FtfBaseHit.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | 2 | 2018-12-24T19:37:00.000Z | 2022-02-28T06:57:20.000Z | StRoot/RTS/EventTracker/FtfBaseHit.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | StRoot/RTS/EventTracker/FtfBaseHit.cxx | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | //:>------------------------------------------------------------------
//: FILE: FtfBaseHit.cxx
//: HISTORY:
//: 1sep1999 ppy first version
//:<------------------------------------------------------------------
//:>------------------------------------------------------------------
//: CLASS: FtfBaseHit
//: DESCRIPTION: Functions associated with this class
//: AUTHOR: ppy - Pablo Yepes, yepes@physics.rice.edu
//:>------------------------------------------------------------------
#include "FtfBaseHit.h"
#include "FtfGeneral.h"
#include "rtsLog.h"
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void FtfBaseHit::print ( ) { print (11) ; } ;
void FtfBaseHit::print ( int point_level )
{
if ( point_level > 9 )
LOG(NOTE, "hit Row x y z\n" ) ;
if ( fmod((double)point_level,10.) > 0 )
LOG(NOTE, "%3d %2d %6.2f %6.2f %6.2f \n",
id, row, x, y, z ) ;
}
| 34.366667 | 75 | 0.327837 | [
"3d"
] |
e4b03dfe10cb6bb68e9c9d4c786ed2944055bde0 | 13,308 | cpp | C++ | main.cpp | etienneSG/Tools | 45f4aa34e7266c307edcd92be3e903b27d90a041 | [
"BSD-3-Clause"
] | null | null | null | main.cpp | etienneSG/Tools | 45f4aa34e7266c307edcd92be3e903b27d90a041 | [
"BSD-3-Clause"
] | null | null | null | main.cpp | etienneSG/Tools | 45f4aa34e7266c307edcd92be3e903b27d90a041 | [
"BSD-3-Clause"
] | null | null | null | #include "array2d.h"
#include "hcube_iterator.h"
#include "knapsack.h"
#include "n_choose_k_iterator.h"
#include "quick_sort.h"
#include "random_iterator.h"
#include "time_tools.h"
#include "tolerance.h"
#include <algorithm>
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
using namespace std;
int array2d_test()
{
cout << "************* Array2d test *************" << endl;
int fail = 0;
int p = 3; int n = 4;
Array2d<int> tab(p,n);
for (int j = 0; j < tab.nb_rows(); j++)
tab(j,0) = j+1;
for (int i = 0; i < tab.nb_columns(); i++)
tab(1,i) = i+2;
tab.resize(4,2);
tab.push_back_column(vector<int>(4,9));
tab.insert_row(0, vector<int>(3,6));
tab.insert_column(1, vector<int>(5,7));
tab.resize(5,5);
tab.resize(6,5,1);
tab.print();
if (tab.nb_rows()!=6 || tab.nb_columns()!=5
|| tab(0,0)!=6 || tab(0,1)!=7 || tab(0,2)!=6 || tab(0,3)!=6 || tab(0,4)!=0
|| tab(1,0)!=1 || tab(1,1)!=7 || tab(1,2)!=0 || tab(1,3)!=9 || tab(1,4)!=0
|| tab(2,0)!=2 || tab(2,1)!=7 || tab(2,2)!=3 || tab(2,3)!=9 || tab(2,4)!=0
|| tab(3,0)!=3 || tab(3,1)!=7 || tab(3,2)!=0 || tab(3,3)!=9 || tab(3,4)!=0
|| tab(4,0)!=0 || tab(4,1)!=7 || tab(4,2)!=0 || tab(4,3)!=9 || tab(4,4)!=0
|| tab(5,0)!=1 || tab(5,1)!=1 || tab(5,2)!=1 || tab(5,3)!=1 || tab(5,4)!=1 )
{
fail++;
}
tab.clear();
Array2d<short> tab_1(2,3);
tab_1(0,0) = 0; tab_1(0,1) = 2; tab_1(0,2) = 0;
tab_1(1,0) = 3; tab_1(1,1) = 0; tab_1(1,2) = 1;
Array2d<short> tab_2(2,3);
tab_2(0,0) = 1; tab_2(0,1) = 1; tab_2(0,2) = 3;
tab_2(1,0) = 5; tab_2(1,1) = 0; tab_2(1,2) = -4;
short dot_prod = tab_1.dot_product(tab_2);
if (dot_prod != 13)
fail++;
Array2d<short> tab_3(tab_1);
if (tab_1.nb_rows() != tab_3.nb_rows() || tab_1.nb_columns() != tab_3.nb_columns()) {
fail++;
}
else {
for (int j = 0; j < tab_3.nb_rows(); j++) {
for (int i = 0; i < tab_3.nb_columns(); i++) {
if (tab_1(j,i) != tab_3(j,i))
fail++;
}
}
}
Array2d<short> tab_4;
tab_4.push_back_column(vector<short>(3,1));
if (tab_4.nb_rows()!=3 || tab_4.nb_columns()!=1
|| tab_4(0,0)!=1 || tab_4(1,0)!=1 || tab_4(2,0)!=1 )
{
fail++;
}
Array2d<short> tab_5;
tab_5.push_back_row(vector<short>(3,1));
if (tab_5.nb_rows()!=1 || tab_5.nb_columns()!=3
|| tab_5(0,0)!=1 || tab_5(0,1)!=1 || tab_5(0,2)!=1 )
{
fail++;
}
Array2d<short> tab_6(2,2);
tab_6.copy(tab_5);
if (tab_6.nb_rows()!=1 || tab_6.nb_columns()!=3
|| tab_6(0,0)!=1 || tab_6(0,1)!=1 || tab_6(0,2)!=1 )
{
fail++;
}
if (fail > 0) {
cout << "===> FAIL <===" << endl;
}
return fail;
}
int hcube_iterator_test()
{
cout << "********* Hcube_iterator test **********" << endl;
unsigned int n = 2;
unsigned int k = 3;
Hcube_iterator myIt(n,k);
vector< vector<unsigned int> > Solution(9, vector<unsigned int>(k,0));
Solution[0][0] = 0; Solution[0][1] = 0;
Solution[1][0] = 0; Solution[1][1] = 1;
Solution[2][0] = 0; Solution[2][1] = 2;
Solution[3][0] = 2; Solution[3][1] = 2;
Solution[4][0] = 2; Solution[4][1] = 1;
Solution[5][0] = 2; Solution[5][1] = 0;
Solution[6][0] = 1; Solution[6][1] = 0;
Solution[7][0] = 1; Solution[7][1] = 1;
Solution[8][0] = 1; Solution[8][1] = 2;
while (!myIt.is_ended())
{
myIt.print();
for (unsigned int i = 0; i < Solution.size(); i++)
{
if (Solution[i][0]==myIt(0) && Solution[i][1]==myIt(1))
{
Solution.erase(Solution.begin()+i);
break;
}
}
++myIt;
}
if (Solution.size()!=0)
{
cout << "===> FAIL <===" << endl;
return 1;
}
else
return 0;
}
int KnapSack_test1()
{
cout << "*********** Knapsack test 1 ************" << endl;
int fail = 0;
// Input of the knapsack
int myVal[] = {100, 60, 120, 50};
unsigned int myWt[]= {20, 20, 30, 10};
int n = sizeof(myVal)/sizeof(int);
vector<int> val(myVal, myVal + n);
vector<unsigned int> wt(myWt, myWt + n);
unsigned int W = 50;
Knapsack<int> knapsack(W, wt, val); // Create the knapsack problem
int opt = knapsack(); // Solve the knapsack problem
vector<bool> Solution; //
knapsack.get_chosen_objects(Solution); // Get the list of chosen objects
cout << "Optimal value of the knapsack: " << opt << endl;
cout << "Affectation of the knapsack: ";
for (unsigned int i = 0; i < Solution.size(); i++)
cout << Solution[i] << " ";
cout << endl;
if (opt!=220
|| Solution.size()!=(unsigned int)n
|| Solution[0]!=1
|| Solution[1]!=0
|| Solution[2]!=1
|| Solution[3]!=0)
{
fail++;
cout << "===> FAIL <===" << endl;
}
return fail;
}
int KnapSack_test2()
{
cout << "*********** Knapsack test 2 ************" << endl;
int fail = 0;
// Input of the knapsack
int myVal[] = {100, 60, 120, 70};
unsigned int myWt[]= {20, 20, 30, 10};
int n = sizeof(myVal)/sizeof(int);
vector<int> val(myVal, myVal + n);
vector<unsigned int> wt(myWt, myWt + n);
unsigned int W = 50;
Knapsack<int> knapsack; // Create the knapsack problem
int opt = knapsack(W, wt, val); // Solve the knapsack problem
cout << "Optimal value of the knapsack: " << opt << endl;
if (opt!=230)
{
fail++;
cout << "===> FAIL <===" << endl;
}
return fail;
}
int KnapSack_test3()
{
cout << "*********** Knapsack test 3 ************" << endl;
int fail = 0;
// Input of the knapsack at his creation
double myVal1[] = {5, 12.6, 8, 9.7, 7};
unsigned int myWt1[]= {10, 80, 53, 10, 24};
int n1 = sizeof(myVal1)/sizeof(double);
vector<double> val1(myVal1, myVal1 + n1);
vector<unsigned int> wt1(myWt1, myWt1 + n1);
unsigned int W1 = 64;
// Create the knapsack problem
Knapsack<double> knapsack(W1, wt1, val1);
// Input of the knapsack for resolution
double myVal2[] = {-12.7, 31.5, 40.8, 15.7};
unsigned int myWt2[]= {20, 10, 30, 20};
int n2 = sizeof(myVal2)/sizeof(double);
vector<double> val2(myVal2, myVal2 + n2);
vector<unsigned int> wt2(myWt2, myWt2 + n2);
unsigned int W2 = 50;
knapsack(W2, wt2, val2); // Solve the knapsack problem
double opt = knapsack.get_optimal_value(); // Get the optimal vallue of the knapsack
vector<bool> Solution; // Get the list of chosen objects
knapsack.get_chosen_objects(Solution); // Get the list of chosen objects
cout << "Optimal value of the knapsack: " << opt << endl;
cout << "Affectation of the knapsack: ";
for (unsigned int i = 0; i < Solution.size(); i++)
cout << Solution[i] << " ";
cout << endl;
if (fabs(opt-72.3) > 1E-9
|| Solution.size()!=(unsigned int)n2
|| Solution[0]!=0
|| Solution[1]!=1
|| Solution[2]!=1
|| Solution[3]!=0)
{
fail++;
cout << "===> FAIL <===" << endl;
}
return fail;
}
int n_choose_k_iterator_test()
{
cout << "******* N_choose_K_iterator test *******" << endl;
unsigned int n = 5;
unsigned int k = 2;
N_choose_K_iterator myIt(n,k);
vector< vector<unsigned int> > Solution(10, vector<unsigned int>(k,0));
Solution[0][0] = 0; Solution[0][1] = 1;
Solution[1][0] = 0; Solution[1][1] = 2;
Solution[2][0] = 0; Solution[2][1] = 3;
Solution[3][0] = 0; Solution[3][1] = 4;
Solution[4][0] = 2; Solution[4][1] = 3;
Solution[5][0] = 2; Solution[5][1] = 4;
Solution[6][0] = 3; Solution[6][1] = 4;
Solution[7][0] = 1; Solution[7][1] = 2;
Solution[8][0] = 1; Solution[8][1] = 3;
Solution[9][0] = 1; Solution[9][1] = 4;
while (!myIt.is_ended())
{
myIt.print();
for (unsigned int i = 0; i < Solution.size(); i++)
{
if (Solution[i][0]==myIt(0) && Solution[i][1]==myIt(1))
{
Solution.erase(Solution.begin()+i);
break;
}
}
++myIt;
}
if (Solution.size()!=0)
{
cout << "===> FAIL <===" << endl;
return 1;
}
else
return 0;
}
int quick_sort_test()
{
cout << "********** Quick_sort test 1 ***********" << endl;
unsigned int n = 10;
vector<int> tab(n, 0);
for (unsigned int i = 0; i < tab.size(); i++)
tab[i] = i;
random_shuffle(tab.begin(), tab.end());
cout << "Shuffle vector: ";
for (unsigned int i = 0; i < tab.size(); i++)
cout << tab[i] << " ";
cout << endl;
Quick_sort<int> quick_sort;
quick_sort(tab.begin(), tab.end());
cout << "Sorted vector: ";
for (unsigned int i = 0; i < tab.size(); i++)
cout << tab[i] << " ";
cout << endl;
if (tab.size()!=n)
{
cout << "===> FAIL <===" << endl;
return 1;
}
for (unsigned int i = 0; i < n; i++)
if (tab[i]!=(int)i)
{
cout << "===> FAIL <===" << endl;
return 1;
}
return 0;
}
struct Point2d
{
int _i;
int _j;
Point2d(int i=0, int j=0): _i(i), _j(j) {};
bool operator<(Point2d & P)
{
if (_i < P._i)
return true;
else if (P._i < _i)
return false;
else
return (_j < P._j ? true : false);
};
void Print() { cout << "(" << _i << "," << _j << ")" << endl; };
};
int quick_sort_test2()
{
cout << "********** Quick_sort test 2 ***********" << endl;
int fail = 0;
unsigned int n = 6;
vector<Point2d> tab(n, 0);
for (unsigned int i = 0; i < tab.size(); i++)
{
tab[i]._i = i/3, tab[i]._j = i%3;
}
random_shuffle(tab.begin(), tab.end());
cout << "Shuffle vector:" << endl;
for (unsigned int i = 0; i < tab.size(); i++)
tab[i].Print();
Quick_sort<Point2d> quick_sort;
quick_sort(tab.begin(), tab.end());
cout << "Sorted vector:" << endl;
for (unsigned int i = 0; i < tab.size(); i++)
tab[i].Print();
if (tab.size()!=n)
{
fail= 1;
}
for (int i = 0; i < (int)n; i++)
if (tab[i]._i != i/3 || tab[i]._j != i%3)
{
fail = 1;
}
if (fail>0)
cout << "===> FAIL <===" << endl;
return fail;
}
int random_iterator_test()
{
cout << "********* Random_iterator test *********" << endl;
int total = 0;
int N = 5;
Random_iterator myIt(N);
while (!myIt.is_ended())
{
cout << myIt() << " ";
total += myIt();
++myIt;
}
cout << endl;
if (total!=N*(N-1)/2)
{
cout << "===> FAIL <===" << endl;
return 1;
}
else
return 0;
}
int time_tools_test()
{
cout << "*********** Time tools test ************" << endl;
int fail = 0;
try
{
cout << "CPU time: " << get_cpu_time() << " s." << endl;
cout << "Wall time: " << get_wall_time() << "s." << endl;
cout << "The current date/time is: " << get_human_readable_time() << endl;
}
catch (...)
{
cout << "===> FAIL <===" << endl;
fail++;
}
return fail;
}
/**
* @brief Test the class #Tolerance
*/
int tolerance_test()
{
cout << "************ Tolerance test ************" << endl;
int error_code = 0;
Tolerance myTol1(1e-3, 1e-2);
std::cout << "Absolute and relative difference " << std::flush;
double a = 3.6;
double b = 12.4;
if ( !myTol1.close(a, b) && myTol1.lower_not_close(a,b) && myTol1.lower_or_close(a,b) )
std::cout << "OK" << std::endl;
else
{
error_code++;
std::cout << "failed (return code: 1)" << std::endl;
}
std::cout << "Absolute difference and relative close " << std::flush;
a = 3.;
b = 3.002 ;
if ( myTol1.close(a, b) && !myTol1.lower_not_close(a,b) && myTol1.lower_or_close(a,b) )
std::cout << "OK" << std::endl;
else
{
error_code++;
std::cout << "failed (return code: 1)" << std::endl;
}
Tolerance myTol2(1., 1e-2);
std::cout << "Absolute close and relative difference " << std::flush;
a = 3.;
b = 3.1 ;
if ( myTol2.close(a, b) && !myTol2.lower_not_close(a,b) && myTol2.lower_or_close(a,b) )
std::cout << "OK" << std::endl;
else
{
error_code++;
std::cout << "failed (return code: 1)" << std::endl;
}
std::cout << "Absolute and relative close " << std::flush;
a = 3.;
b = 3.001;
if ( myTol2.close(a, b) && !myTol2.lower_not_close(a,b) && myTol2.lower_or_close(a,b) )
std::cout << "OK" << std::endl;
else
{
error_code++;
std::cout << "failed (return code: 1)" << std::endl;
}
return error_code;
}
int main()
{
/* initialize random seed: */
srand (time(NULL));
int nb_failure = 0;
nb_failure += array2d_test();
std::cout << std::endl;
nb_failure += hcube_iterator_test();
std::cout << std::endl;
nb_failure += KnapSack_test1();
std::cout << std::endl;
nb_failure += KnapSack_test2();
std::cout << std::endl;
nb_failure += KnapSack_test3();
std::cout << std::endl;
nb_failure += n_choose_k_iterator_test();
std::cout << std::endl;
nb_failure += quick_sort_test();
std::cout << std::endl;
nb_failure += quick_sort_test2();
std::cout << std::endl;
nb_failure += random_iterator_test();
std::cout << std::endl;
nb_failure += time_tools_test();
std::cout << std::endl;
nb_failure += tolerance_test();
std::cout << std::endl;
cout << "*********************************" << endl;
switch (nb_failure)
{
case 0:
cout << "No failure. Well done!" << endl;
break;
case 1:
cout << nb_failure << " test failed." << endl;
break;
default:
cout << nb_failure << " tests failed." << endl;
break;
}
return nb_failure;
}
| 23.388401 | 89 | 0.52893 | [
"vector"
] |
e4b1443f4ab8699f7ccec21f2974430492ad1a53 | 2,436 | cpp | C++ | LeetCode/Problems/Algorithms/#282_ExpressionAddOperators_sol2_backtracking_O(N4^N)_time_O(N)_extra_space_292ms_14.4MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | 1 | 2022-01-26T14:50:07.000Z | 2022-01-26T14:50:07.000Z | LeetCode/Problems/Algorithms/#282_ExpressionAddOperators_sol2_backtracking_O(N4^N)_time_O(N)_extra_space_292ms_14.4MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | LeetCode/Problems/Algorithms/#282_ExpressionAddOperators_sol2_backtracking_O(N4^N)_time_O(N)_extra_space_292ms_14.4MB.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | class Solution {
private:
using ll = long long;
void back(const string& NUM_STR, const int& TARGET_SUM, int startIdx, ll prevTerm, ll currentSum,
string& currentExpression, vector<string>& expressions){
if(startIdx == (int)NUM_STR.length()){
if(currentSum == TARGET_SUM){
expressions.push_back(currentExpression);
}
}else{
ll num = 0;
for(int i = startIdx; i < (int)NUM_STR.length(); ++i){
num = num * 10 + (NUM_STR[i]- '0');
if(NUM_STR[startIdx] == '0' && i > startIdx){
return;
}
if(currentExpression.empty()){
currentExpression += to_string(num);
back(NUM_STR, TARGET_SUM, i + 1, num, num, currentExpression, expressions);
currentExpression.clear();
}else{
for(char currentOperator: {'+', '-', '*'}){
ll nextPrevTerm = 0;
ll nextSum = 0;
if(currentOperator == '+'){
nextPrevTerm = num;
nextSum = currentSum + num;
}else if(currentOperator == '-'){
nextPrevTerm = -num;
nextSum = currentSum - num;
}else if(currentOperator == '*'){
nextPrevTerm = prevTerm * num;
nextSum = currentSum + prevTerm * num - prevTerm;
}
const int EXPRESSION_LENGTH = currentExpression.length();
currentExpression += currentOperator;
currentExpression += to_string(num);
back(NUM_STR, TARGET_SUM, i + 1, nextPrevTerm, nextSum, currentExpression, expressions);
currentExpression.resize(EXPRESSION_LENGTH);
}
}
}
}
}
public:
vector<string> addOperators(string numStr, int target) {
const int N = numStr.length();
string currentExpression;
vector<string> expressions;
back(numStr, target, 0, 0, 0, currentExpression, expressions);
return expressions;
}
}; | 43.5 | 113 | 0.454844 | [
"vector"
] |
e4b3a49b40e4ff082f63081a95f63b491486b42a | 36,150 | cc | C++ | Volume_11/Number_3/Sanderson2006/cpu_demo/rd_base.cc | kyeonghopark/jgt-code | 08bbcc298e12582e32cb56a52e70344c57689d73 | [
"MIT"
] | 415 | 2015-10-24T17:37:12.000Z | 2022-02-18T04:09:07.000Z | Volume_11/Number_3/Sanderson2006/cpu_demo/rd_base.cc | kyeonghopark/jgt-code | 08bbcc298e12582e32cb56a52e70344c57689d73 | [
"MIT"
] | 8 | 2016-01-15T13:23:16.000Z | 2021-05-27T01:49:50.000Z | Volume_11/Number_3/Sanderson2006/cpu_demo/rd_base.cc | kyeonghopark/jgt-code | 08bbcc298e12582e32cb56a52e70344c57689d73 | [
"MIT"
] | 77 | 2015-10-24T22:36:29.000Z | 2022-03-24T01:03:54.000Z | /*****************************************************************************/
/* */
/* Copyright (c) 2005 Allen R. Sanderson */
/* */
/* Scientific Computing and Imaging Institute */
/* University of Utah */
/* Salt Lake City, Utah */
/* */
/* */
/* Permission is granted to modify and/or distribute this program so long */
/* as the program is distributed free of charge and this header is retained */
/* as part of the program. */
/* */
/*****************************************************************************/
#include <iostream>
#include <stdio.h>
#include <math.h>
#include "rand.h"
#include "gammp.h"
#include "rd_base.h"
using namespace std;
#define LERP( t, x0, x1 ) \
( (float) (x0) + (t) * ( (float) (x1) - (float) (x0)) )
#define SGN( x ) \
( (x) < 0 ? -1.0 : 1.0 )
#define INDEX( x, range ) \
( (int) (x*range) + range )
#define MAX_GAMMP 500
/******************************************************************************
rd_base
******************************************************************************/
rd_base::rd_base( ) :
cell_mult_(1),
gradient_( 0 ),
theta_( 0.5 ),
nMorphs(0),
relaxation_(RED_BLACK),
reaction_(TURING),
laplacian_(INHOMOGENEOUS),
diffusion_(ANISOTROPIC),
solution_(EXPLICIT),
vector_data(0),
vector_diverge(0),
morphigen(0),
dmorphigen(0),
diff_rate(0),
react_rate(0),
d_tensor(0),
d_template(0),
u_h(0),
rhs_func(0),
residuals(0),
errors(0),
tmp(0),
neighborhood(8),
min_error_(1.0e-4)
{
gammp_table = new float[2*MAX_GAMMP+1];
gammp_table[MAX_GAMMP] = 0;
for( unsigned int i=1; i<=MAX_GAMMP; i++ ) {
float val = gammp( 3.0, 10.0 * (float) i / (float) MAX_GAMMP );
gammp_table[MAX_GAMMP-i] = -0.25 * val;
gammp_table[MAX_GAMMP+i] = +0.25 * val;
}
}
/******************************************************************************
frand - Pick a random number between min and max.
******************************************************************************/
float rd_base::frand( float min, float max, long &seed ) {
return (min + gasdev( &seed ) * (max - min));
}
/******************************************************************************
next_step_euler - next_step - explicit euler solution
******************************************************************************/
bool rd_base::next_step_explicit_euler( )
{
react_and_diffuse( );
/* Add the change in the morphigen to each cell. */
for( unsigned int n=0; n<nMorphs; n++ ) {
for (int j=0; j<height_; j++) {
for (int i=0; i<width_; i++) {
double mval = morphigen[n][j][i];
morphigen[n][j][i] += dmorphigen[n][j][i];
if( morphigen[n][j][i] < 0.0 )
morphigen[n][j][i] = 0.0;
}
}
}
return false;
}
/******************************************************************************
next_step - semi implicit euler solution
******************************************************************************/
#define LOCK_STEP 1
//#define STAGGERED 1
bool rd_base::next_step_implicit_euler( )
{
#ifdef LOCK_STEP
// Get the inital RHS for the morphigen which is the
// current value plus the its current reaction.
for( unsigned int m=0; m<nMorphs; m++ )
implicit_euler_rhs( rhs_func[m], (morphigen_type) m );
// Solve for the next value.
for( unsigned int m=0; m<nMorphs; m++ )
implicit_solve( morphigen[m], rhs_func[m], theta_*diff_rate[m] );
#else //STAGGERED
for( unsigned int m=0; m<nMorphs; m++ ) {
// Get the inital RHS for the morphigen which is the
// current value plus the its current reaction.
implicit_euler_rhs( rhs_func[m], (morphigen_type) m );
// Solve for the next value.
implicit_solve( morphigen[m], rhs_func[m], theta_*diff_rate[m] );
}
#endif
}
/******************************************************************************
implicit_solve - base solution
******************************************************************************/
void rd_base::implicit_solve( float **v, float **rhs, float diffusion ) {
int nr_steps = 20; // Number of smoothing steps for the exact solution.
int cc = 0, dd = 0, max_iterations = 100;
float current_residual = 1.0e4, last_residual = 1.0e5;
float max_difference = min_error_, max_residual = min_error_;
// Initerate until a) the residual is below the maximum value,
// b) the residual does not change for a set number of iterations,
// or c) if the maximum number of iterations is reached.
while( cc++ < max_iterations ) {
// Set the current error to zero.
for (unsigned int j=0; j<height_; j++)
for (unsigned int i=0; i<width_; i++)
errors[j][i] = 0;
// Get the next solution using relaxation.
bool converged = false;
for(unsigned int i=0; i<nr_steps && !converged; i++)
converged = relax( v, rhs, diffusion );
// Calculate the sum of squares residual.
current_residual = implicit_euler_residual(residuals, v, rhs, diffusion );
// Stop if the current residual is below the maximum value.
if( current_residual < max_residual )
break;
// Stop if the current residual does not change significantly
// after 5 iterations.
if( fabs(last_residual-current_residual) > max_difference ) {
dd = 1;
last_residual = current_residual;
} else if( ++dd == 5 )
break;
}
// Clamp any negative results to zero
for (unsigned int j=0; j<height_; j++)
for (unsigned int i=0; i<width_; i++)
if( v[j][i] < 0 )
v[j][i] = 0;
}
/******************************************************************************
difference - mulitgrid difference
******************************************************************************/
float rd_base::difference( float **u_new, float **u_old )
{
register float sum = 0.0;
for (int j=0; j<height_; j+=1) {
for (int i=0; i<width_; i+=1) {
register float diff = u_new[j][i] - u_old[j][i];
sum += diff * diff;
}
}
return sqrt( sum / ((width_/1)*(height_/1)) );
}
/******************************************************************************
relax - relaxation using XXX relaxation
******************************************************************************/
inline bool rd_base::relax( float **u, float **rhs, float diff )
{
if( relaxation_ == RED_BLACK )
return relax_gs_rb( u, rhs, diff );
else if( relaxation_ == GAUSS_SEIDEL )
return relax_gs( u, rhs, diff );
else if( relaxation_ == JACOBI )
return relax_jacobi( u, rhs, diff );
}
/******************************************************************************
relax_gs - relaxation using Gauss-Seidel relaxation
******************************************************************************/
bool rd_base::relax_gs( float **u, float **rhs, float diff )
{
bool convergence = true;
for (int j=0; j<height_; j+=1) {
int j_1 = jminus1[j];
int j1 = jplus1 [j];
for (int i=0; i<width_; i+=1) {
int i_1 = iminus1[i];
int i1 = iplus1 [i];
float old_u = u[j][i];
u[j][i] = implicit_euler_relax( u, rhs, diff,
i_1, j_1,
i, j,
i1, j1 );
if( convergence && fabs( old_u - u[j][i] ) > min_error_ )
convergence = false;
}
}
return convergence;
}
/******************************************************************************
relax_gs_rb - relaxation using Gauss-Seidel red-black relaxation
******************************************************************************/
bool rd_base::relax_gs_rb( float **u, float **rhs, float diff )
{
bool convergence = true;
for( int pass=0; pass<2; pass++ ) {
for (int j=0; j<height_; j+=1) {
int j_1 = jminus1[j];
int j1 = jplus1 [j];
// j/1 gives the actual row,
// the remainder gives even - old,
int offset = (j/1) % 2;
// If on the second pass flip;
if( pass )
offset = !offset;
for (int i=offset*1; i<width_; i+=(1*2)) {
float old_u = u[j][i];
int i_1 = iminus1[i];
int i1 = iplus1 [i];
u[j][i] = implicit_euler_relax( u, rhs, diff,
i_1, j_1,
i, j,
i1, j1 );
if( convergence && fabs( old_u - u[j][i] ) > min_error_ )
convergence = false;
}
}
}
return convergence;
}
/******************************************************************************
relax_jacobi - relaxation using Jacobi relaxation
******************************************************************************/
bool rd_base::relax_jacobi( float **u, float **rhs, float diff )
{
bool convergence = true;
for (int j=0; j<height_; j+=1) {
int j_1 = jminus1[j];
int j1 = jplus1 [j];
for (int i=0; i<width_; i+=1) {
int i_1 = iminus1[i];
int i1 = iplus1 [i];
tmp[j][i] = implicit_euler_relax( u, rhs, diff,
i_1, j_1,
i, j,
i1, j1 );
if( convergence && fabs( u[j][i] - tmp[j][i] ) > min_error_ )
convergence = false;
}
}
for (int j=0; j<height_; j+=1)
for (int i=0; i<width_; i+=1)
u[j][i] = tmp[j][i];
return convergence;
}
/******************************************************************************
relax - relaxation for a single grid location
******************************************************************************/
inline float rd_base::implicit_euler_relax( float **u,
float **rhs, float diff,
int i_1, int j_1,
int i, int j,
int i1, int j1 )
{
float h = 1.0 / 1;
float h2 = h * h;
// Solve for the grid next value current values of the neighbors.
// This is just the diffusion with u[j][i] on the LHS.
float f3 =
( (d_tensor[j][i1 ][0][1] * (u[j1][i1 ] - u[j_1][i1 ]) -
d_tensor[j][i_1][0][1] * (u[j1][i_1] - u[j_1][i_1]) ) +
(d_tensor[j1 ][i][1][0] * (u[j1 ][i1] - u[j1 ][i_1]) -
d_tensor[j_1][i][1][0] * (u[j_1][i1] - u[j_1][i_1]) ) ) / h2;
float d_t0 = d_tensor[j ][i1][0][0] + d_tensor[j ][i ][0][0];
float d_t1 = d_tensor[j ][i ][0][0] + d_tensor[j ][i_1][0][0];
float d_t2 = d_tensor[j1][i ][1][1] + d_tensor[j ][i ][1][1];
float d_t3 = d_tensor[j ][i ][1][1] + d_tensor[j_1][i ][1][1];
float f1a = (d_t0 * u[j ][i1] + d_t1 * u[j ][i_1] +
d_t2 * u[j1][i ] + d_t3 * u[j_1][i ]) / h2;
float f1b_mult = -(d_t0 + d_t1 + d_t2 + d_t3) / h2;
float val = (rhs[j][i] + diff * (f1a + f3)) /
(time_step_inv_ - diff * f1b_mult);
return val;
}
/******************************************************************************
Implicit RHS Calculation.
******************************************************************************/
void rd_base::implicit_euler_rhs( float **rhs, morphigen_type mt )
{
int n = (int) mt;
if( theta_ == 1.0 ) {
for (int j=0; j <height_; j++)
for (int i=0; i<width_; i++)
rhs[j][i] = morphigen[n][j][i] * time_step_inv_ +
react_rate[j][i] * reaction( n, i, j );
} else {
float diff = (1.0-theta_) * diff_rate[n];
for (int j=0; j<height_; j++)
for (int i=0; i<width_; i++)
rhs[j][i] = morphigen[n][j][i] * time_step_inv_ +
react_rate[j][i] * reaction( n, i, j ) +
diff * diffusion( morphigen[n], i, j ) ;
}
}
/******************************************************************************
The residual is the difference between the RHS
(current u + current u reaction) and the LHS (next u - next u diffusion).
******************************************************************************/
float rd_base::implicit_euler_residual( float **resid,
float **u,
float **rhs,
float diff )
{
float sum = 0.0;
for (int j=0; j<height_; j+=1) {
for (int i=0; i<width_; i+=1) {
resid[j][i] = rhs[j][i] -
(u[j][i] * time_step_inv_ - diff * diffusion( u, i, j ) );
sum += resid[j][i] * resid[j][i];
}
}
return sqrt( sum / ((height_/1)*(width_/1)) );
}
/******************************************************************************
react_and_diffuse.
******************************************************************************/
void rd_base::react_and_diffuse( )
{
// Compute the change in the morphigen in each cell.
for (unsigned int j=0; j<height_; j++) {
for (unsigned int i=0; i<width_; i++) {
for( unsigned int n=0; n<nMorphs; n++ ) {
dmorphigen[n][j][i] =
react_rate[j][i] * reaction( n, i, j ) +
diff_rate[n] * diffusion( morphigen[n], i, j );
}
}
}
}
/******************************************************************************
Diffusion equations.
******************************************************************************/
float rd_base::diffusion( float **morph, unsigned int i, unsigned int j )
{
float diff = 0;
int j_1 = jminus1[j];
int j1 = jplus1 [j];
int i_1 = iminus1[i];
int i1 = iplus1 [i];
if( laplacian_ == INHOMOGENEOUS ) {
// float e1 = 0.5, e2 = 0.5, e3 = 0.5, e4 = 0.5;
float f1 =
( (d_tensor[j ][i1 ][0][0] + d_tensor[j][i][0][0]) * (morph[j ][i1 ] - morph[j][i]) +
(d_tensor[j ][i_1][0][0] + d_tensor[j][i][0][0]) * (morph[j ][i_1] - morph[j][i]) +
(d_tensor[j1 ][i ][1][1] + d_tensor[j][i][1][1]) * (morph[j1 ][i ] - morph[j][i]) +
(d_tensor[j_1][i ][1][1] + d_tensor[j][i][1][1]) * (morph[j_1][i ] - morph[j][i]) );
// / 2.0; - the divide by 2 is not needed as it was already done for the principal
// difusivity values. This only holds when solely using f1 and f3
/*
float f2 =
( (d_tensor[j1 ][i1][0][0] + d_tensor[j1 ][i ][0][0]) * (morph[j1 ][i1] - morph[j1 ][i ]) -
(d_tensor[j1 ][i ][0][0] + d_tensor[j1 ][i_1][0][0]) * (morph[j1 ][i ] - morph[j1 ][i_1]) ) / 8.0 +
( (d_tensor[j ][i1][0][0] + d_tensor[j ][i ][0][0]) * (morph[j ][i1] - morph[j ][i ]) -
(d_tensor[j ][i ][0][0] + d_tensor[j ][i_1][0][0]) * (morph[j ][i ] - morph[j ][i_1]) ) / 4.0 +
( (d_tensor[j_1][i1][0][0] + d_tensor[j_1][i ][0][0]) * (morph[j_1][i1] - morph[j_1][i ]) -
(d_tensor[j_1][i ][0][0] + d_tensor[j_1][i_1][0][0]) * (morph[j_1][i ] - morph[j_1][i_1]) ) / 8.0 +
( (d_tensor[j1][i1 ][1][1] + d_tensor[j ][i1 ][1][1]) * (morph[j1][i1 ] - morph[j ][i1 ]) -
(d_tensor[j ][i1 ][1][1] + d_tensor[j_1][i1 ][1][1]) * (morph[j ][i1 ] - morph[j_1][i1 ]) ) / 8.0 +
( (d_tensor[j1][i ][1][1] + d_tensor[j ][i ][1][1]) * (morph[j1][i ] - morph[j ][i ]) -
(d_tensor[j ][i ][1][1] + d_tensor[j_1][i ][1][1]) * (morph[j ][i ] - morph[j_1][i ]) ) / 4.0 +
( (d_tensor[j1][i_1][1][1] + d_tensor[j ][i_1][1][1]) * (morph[j1][i_1] - morph[j ][i_1]) -
(d_tensor[j ][i_1][1][1] + d_tensor[j_1][i_1][1][1]) * (morph[j ][i_1] - morph[j_1][i_1]) ) / 8.0;
*/
float f3 =
( (d_tensor[j][i1 ][0][1] * (morph[j1][i1 ] - morph[j_1][i1 ]) -
d_tensor[j][i_1][0][1] * (morph[j1][i_1] - morph[j_1][i_1]) ) +
(d_tensor[j1 ][i][1][0] * (morph[j1 ][i1] - morph[j1 ][i_1]) -
d_tensor[j_1][i][1][0] * (morph[j_1][i1] - morph[j_1][i_1]) ) );
// / 4.0; - the divide by 4 is not needed as it was already done
// for the secondary difusivity values. This only holds when
// solely using f1 and f3
/*
float f4 =
(d_tensor[j][i1][0][1] * (morph[j1][i1] - morph[j][i1]) -
d_tensor[j][i ][0][1] * (morph[j1][i ] - morph[j][i ]) +
d_tensor[j][i ][0][1] * (morph[j][i ] - morph[j_1][i]) -
d_tensor[j][i_1][0][1] * (morph[j][i_1] - morph[j_1][i_1]) ) / 2.0 +
(d_tensor[j1][i][1][0] * (morph[j1][i1] - morph[j1][i]) -
d_tensor[j ][i][1][0] * (morph[j ][i1] - morph[j ][i]) +
d_tensor[j ][i][1][0] * (morph[j ][i] - morph[j ][i_1]) -
d_tensor[j_1][i][1][0] * (morph[j_1][i] - morph[j_1][i_1]) ) / 2.0;
*/
/* diff = e1 * f1 + e2 * f2 + e3 * f3 + e4 * f4; */
diff = f1 + f3;
} else {
/* 4 Neighborhood - isotropic. */
if( neighborhood == 4 ) {
diff = (morph[j_1][i] + morph[j1][i] +
-4.0 * morph[j][i] +
morph[j][i_1] + morph[j][i1]);
/* 8 Neighborhood - anisotropic. */
} else if( neighborhood == 8 ) {
diff = (d_template[j][i][0][0] * morph[j_1][i_1] +
d_template[j][i][0][1] * morph[j_1][i ] +
d_template[j][i][0][2] * morph[j_1][i1 ] +
d_template[j][i][1][0] * morph[j][i_1] +
d_template[j][i][1][1] * morph[j][i ] +
d_template[j][i][1][2] * morph[j][i1 ] +
d_template[j][i][2][0] * morph[j1][i_1] +
d_template[j][i][2][1] * morph[j1][i ] +
d_template[j][i][2][2] * morph[j1][i1 ]);
}
}
return diff;
}
/******************************************************************************
Contiguous memory allocation 1D
******************************************************************************/
char *rd_base::alloc( unsigned int i,
unsigned int bytes )
{
char *p1 = 0;
if( p1 = (char *) malloc( i * bytes ) ) {
}
return p1;
}
/******************************************************************************
Contiguous memory allocation 2D
******************************************************************************/
char **rd_base::alloc( unsigned int j, unsigned int i,
unsigned int bytes )
{
char **p2 = 0, *p1 = 0;
unsigned int ic = i * bytes;
if( p2 = (char **) malloc( j * sizeof( char * ) +
j * i * bytes ) ) {
p1 = (char *) (p2 + j);
for( unsigned int jc=0; jc<j; jc++ ) {
p2[jc] = p1;
p1 += ic;
}
}
return p2;
}
/******************************************************************************
Contiguous memory allocation 3D
******************************************************************************/
char ***rd_base::alloc( unsigned int k, unsigned int j, unsigned int i,
unsigned int bytes )
{
char ***p3 = 0, **p2 = 0, *p1 = 0;
unsigned int ic = i * bytes;
if( p3 = (char ***) malloc( k * sizeof( char ** ) +
k * j * sizeof( char * ) +
k * j * i * bytes ) ) {
p2 = (char **) (p3 + k);
p1 = (char *) (p3 + k + k * j);
for( unsigned int kc=0; kc<k; kc++ ) {
p3[kc] = p2;
p2 += j;
for( unsigned int jc=0; jc<j; jc++ ) {
p3[kc][jc] = p1;
p1 += ic;
}
}
}
return p3;
}
/******************************************************************************
Contiguous memory allocation 4D
******************************************************************************/
char ****rd_base::alloc( unsigned int l, unsigned int k,
unsigned int j, unsigned int i,
unsigned int bytes )
{
char ****p4 = 0, ***p3 = 0, **p2 = 0, *p1 = 0;
unsigned int ic = i * bytes;
if( p4 = (char ****) malloc( l * sizeof( char *** ) +
l * k * sizeof( char ** ) +
l * k * j * sizeof( char * ) +
l * k * j * i * bytes ) ) {
p3 = (char ***) (p4 + l);
p2 = (char **) (p4 + l + l * k);
p1 = (char *) (p4 + l + l * k + l * k * j);
for( unsigned int lc=0; lc<l; lc++ ) {
p4[lc] = p3;
p3 += k;
for( unsigned int kc=0; kc<k; kc++ ) {
p4[lc][kc] = p2;
p2 += j;
for( unsigned int jc=0; jc<j; jc++ ) {
p4[lc][kc][jc] = p1;
p1 += ic;
}
}
}
}
return p4;
}
/******************************************************************************
Initalize the base system
******************************************************************************/
void rd_base::alloc(unsigned int *dims, int mult)
{
cell_mult_ = mult;
height_ = dims[0] * cell_mult_;
width_ = dims[1] * cell_mult_;
if( vector_data ) {
free( vector_data );
free( vector_diverge );
free( morphigen );
free( dmorphigen );
free( diff_rate );
free( react_rate );
free( d_tensor );
free( d_template );
free( u_h );
free( rhs_func );
free( residuals );
free( errors );
free( tmp );
}
vector_data = (float ***) alloc( height_, width_, 4, sizeof( float ) );
vector_diverge = (float ***) alloc( height_, width_, 4, sizeof( float ) );
morphigen = (float ***) alloc( nMorphs, height_, width_, sizeof( float ) );
dmorphigen = (float ***) alloc( nMorphs, height_, width_, sizeof( float ) );
diff_rate = (float *) alloc( nMorphs, sizeof( float ) );
react_rate = (float **) alloc( height_, width_, sizeof( float ) );
d_tensor = (float ****) alloc( height_, width_, 2, 2, sizeof( float ) );
d_template = (float ****) alloc( height_, width_, 3, 3, sizeof( float ) );
rhs_func = (float ***) alloc( 2, height_, width_, sizeof( float ) );
u_h = (float **) alloc( height_, width_, sizeof( float ) );
residuals = (float **) alloc( height_, width_, sizeof( float ) );
errors = (float **) alloc( height_, width_, sizeof( float ) );
tmp = (float **) alloc( height_, width_, sizeof( float ) );
iminus1ZeroFlux = (int*) alloc( width_, sizeof( int ) );
iplus1ZeroFlux = (int*) alloc( width_, sizeof( int ) );
jminus1ZeroFlux = (int*) alloc( height_, sizeof( int ) );
jplus1ZeroFlux = (int*) alloc( height_, sizeof( int ) );
iminus1Periodic = (int*) alloc( width_, sizeof( int ) );
iplus1Periodic = (int*) alloc( width_, sizeof( int ) );
jminus1Periodic = (int*) alloc( height_, sizeof( int ) );
jplus1Periodic = (int*) alloc( height_, sizeof( int ) );
unsigned int i = 0;
iminus1ZeroFlux[i] = i;
iplus1ZeroFlux [i] = i + 1;
iminus1Periodic[i] = (i + width_ - 1) % width_;
iplus1Periodic [i] = (i + 1) % width_;
for( i=1; i<width_-1; i+=1) {
iminus1ZeroFlux[i] = iminus1Periodic[i] = (i - 1);
iplus1ZeroFlux [i] = iplus1Periodic [i] = (i + 1);
}
iminus1ZeroFlux[i] = i - 1;
iplus1ZeroFlux [i] = i;
iminus1Periodic[i] = (i + width_ - 1) % width_;
iplus1Periodic [i] = (i + 1) % width_;
unsigned int j = 0;
jminus1ZeroFlux[j] = j;
jplus1ZeroFlux [j] = j + 1;
jminus1Periodic[j] = (j + height_ - 1) % height_;
jplus1Periodic [j] = (j + 1) % height_;
for( j=1; j<height_-1; j+=1) {
jminus1ZeroFlux[j] = jminus1Periodic[j] = (j - 1);
jplus1ZeroFlux [j] = jplus1Periodic [j] = (j + 1);
}
jminus1ZeroFlux[j] = j - 1;
jplus1ZeroFlux [j] = j;
jminus1Periodic[j] = (j + height_ - 1) % height_;
jplus1Periodic [j] = (j + 1) % height_;
}
/******************************************************************************
Initalize the base vars.
******************************************************************************/
void rd_base::initialize( float ***vector, bool reset )
{
register int k0, k1, k_1, j0, j1, j_1, i0, i1, i_1;
register float u, v;
vector_min=MAX_FLOAT, vector_max=-MAX_FLOAT;
for (int jj=0; jj<height_; jj++) {
if( height_ > 1 ) {
j0 = (int) (jj / cell_mult_);
j1 = (j0+1) % (height_ / cell_mult_);
v = (float) (jj % cell_mult_) / (float) (cell_mult_);
} else {
j0 = 0;
j1 = 0;
v = 0;
}
for (int ii=0; ii<width_; ii++) {
if( width_ > 1 ) {
i0 = (int) (ii / cell_mult_);
i1 = (i0+1) % (width_ / cell_mult_);
u = (float) (ii % cell_mult_) / (float) (cell_mult_);
} else {
i0 = 0;
i1 = 0;
u = 0;
}
for( int index=0; index<4; index++ )
vector_data[jj][ii][index] =
LERP( v,
LERP( u,
vector[j0][i0][index],
vector[j0][i1][index] ),
LERP( u,
vector[j1][i0][index],
vector[j1][i1][index] ) );
}
}
for (int j=0; j<height_; j++) {
int j_1 = jminus1[j];
int j1 = jplus1 [j];
for (int i=0; i<width_; i++) {
int i_1 = iminus1[i];
int i1 = iplus1 [i];
vector_diverge[j][i][0] =
(vector_data[j][i][0] - vector_data[j][i_1][0]);
vector_diverge[j][i][1] =
(vector_data[j][i][1] - vector_data[j_1][i][1]);
vector_diverge[j][i][2] = 0;
vector_diverge[j][i][3] =
vector_diverge[j][i][0] +
vector_diverge[j][i][1] +
vector_diverge[j][i][2];
if( vector_min > vector_data[j][i][3] )
vector_min = vector_data[j][i][3];
if( vector_max < vector_data[j][i][3] )
vector_max = vector_data[j][i][3];
}
}
/* Min - max are the same. */
if( vector_max-vector_min < 1.0e-8 ) {
vector_min -= 1.0;
vector_max += 1.0;
}
/* Min - max have a small range. */
else if( vector_max-vector_min < 1.0e-4 ) {
float ave = (vector_max+vector_min) / 2.0;
float diff = (vector_max-vector_min);
vector_min = ave - 1.0e3 * diff;
vector_max = ave + 1.0e3 * diff;
}
}
/******************************************************************************
Set the reaction and diffusion rates.
******************************************************************************/
void rd_base::set_rates( bool rate_type )
{
fprintf( stdout, "Rate unnormalized %f %f\n", vector_min, vector_max );
// Variable Reaction rates.
set_reaction_rates( react_rate, rate_type );
// Normally the diffusion rates are divided by the cell size.
// However, this is done in the interface.
// float cell_size = 1.00;
// float cell_area = cell_size * cell_size;
float ts;
if( solution_ == EXPLICIT )
ts = time_step_;
else
ts = 1.0;
// Constant Diffusion rates.
diff_rate[0] = ts * a_diff_rate_;
diff_rate[1] = ts * b_diff_rate_;
cerr << "Diffusion Rates " << diff_rate[0] << " " << diff_rate[1] << endl;
cerr << "Diffusion Rates " << a_diff_rate_ << " " << b_diff_rate_ << endl;
}
/******************************************************************************
Set the reaction rates.
******************************************************************************/
void rd_base::set_reaction_rates( float **rate,
bool rate_type )
{
float scale = 1.0 / (vector_max-vector_min);
float min_mag_norm=MAX_FLOAT, max_mag_norm=-MAX_FLOAT;
float ts, u;
if( solution_ == EXPLICIT )
ts = time_step_;
else // if( solution_ == IMPLICIT )
ts = 1.0;
/* Normalize the values at the posts. */
for (int k=0, kk=0; k<height_; k++) {
for (int j=0, jj=0; j<height_; j++) {
for (int i=0, ii=0; i<width_; i++) {
u = (vector_data[j][i][3]-vector_min) * scale;
if( reaction_ == TURING )
rate[j][i] = ts / (rr_coef_1_ + rr_coef_2_ * u);
else
rate[j][i] = ts * (rr_coef_1_ + rr_coef_2_ * u);
if( min_mag_norm > rate[j][i] ) min_mag_norm = rate[j][i];
if( max_mag_norm < rate[j][i] ) max_mag_norm = rate[j][i];
}
}
}
fprintf( stdout,
"Rate normalized %f %f\n\n", min_mag_norm, max_mag_norm );
}
/******************************************************************************
Set the Diffusion Matrix.
******************************************************************************/
void rd_base::set_diffusion( unsigned int diffusion )
{
if( laplacian_ == UNIFORM )
set_diffusion_uniform( );
else if( laplacian_ == INHOMOGENEOUS )
set_diffusion_inhomogeneous( );
}
/******************************************************************************
Set the Diffusion Matrix.
******************************************************************************/
#define BOX 0
void rd_base::set_diffusion_uniform()
{
// First set up the diffusion tensors - this is exactly the same as for the
// inhomogeneoust method.
set_diffusion_inhomogeneous( );
// By assuming the diffusion does not change with cell location
// a mask for convolving can be created.
// This is not correct but is what Witkin and Kass assumed
// and it gives descent results.
for (int jj=0; jj<height_; jj++) {
for (int ii=0; ii<width_; ii++) {
// Remove the predivsion done for the invarient method.
d_tensor[jj][ii][0][0] *= 2.0;
d_tensor[jj][ii][0][1] *= 4.0;
d_tensor[jj][ii][1][0] *= 4.0;
d_tensor[jj][ii][1][1] *= 2.0;
// This for the + plus (cross) template of the Laplacian.
float f = (1./4.); // Const for the cross derivatives.
d_template[jj][ii][0][0] = f * d_tensor[jj][ii][0][1];
d_template[jj][ii][0][1] = 1. * d_tensor[jj][ii][1][1];
d_template[jj][ii][0][2] = -f * d_tensor[jj][ii][0][1];
d_template[jj][ii][1][0] = 1. * d_tensor[jj][ii][0][0];
d_template[jj][ii][1][1] = -2. *
(d_tensor[jj][ii][0][0] + d_tensor[jj][ii][1][1]);
d_template[jj][ii][1][2] = 1. * d_tensor[jj][ii][0][0];
d_template[jj][ii][2][0] = -f * d_tensor[jj][ii][1][0];
d_template[jj][ii][2][1] = 1. * d_tensor[jj][ii][1][1];
d_template[jj][ii][2][2] = f * d_tensor[jj][ii][1][0];
// For adding in the x template with the + template for a box template.
if( BOX ) {
float b = (1./2.) * (2./3.); // (1./2.) is a const do not change.
d_template[jj][ii][0][0] += b * 1. * d_tensor[jj][ii][0][1];
d_template[jj][ii][0][1] += b * -2. * d_tensor[jj][ii][1][1];
d_template[jj][ii][0][2] += b * 1. * d_tensor[jj][ii][0][1];
d_template[jj][ii][1][0] += b * -2. * d_tensor[jj][ii][0][0];
d_template[jj][ii][1][1] += b *
( 4.0 * (d_tensor[jj][ii][0][0] + d_tensor[jj][ii][1][1]) -
2.0 * (d_tensor[jj][ii][0][1] + d_tensor[jj][ii][1][0]) );
d_template[jj][ii][1][2] += b * -2. * d_tensor[jj][ii][0][0];
d_template[jj][ii][2][0] += b * 1. * d_tensor[jj][ii][1][0];
d_template[jj][ii][2][1] += b * -2. * d_tensor[jj][ii][1][1];
d_template[jj][ii][2][2] += b * 1. * d_tensor[jj][ii][1][0];
}
}
}
// For debugging - make sure the sum of the template is zero.
int jj = height_ / 4;
int ii = width_ / 4;
float sum = 0;
fprintf( stdout, " %d %d\n", ii, jj );
fprintf( stdout, " %f %f\n %f %f\n\n",
d_tensor[jj][ii][0][0],
d_tensor[jj][ii][0][1],
d_tensor[jj][ii][1][0],
d_tensor[jj][ii][1][1] );
for( int mj=0; mj<3; mj++ ) {
for( int mi=0; mi<3; mi++ ) {
sum += d_template[jj][ii][mj][mi];
fprintf( stdout, " %f ", d_template[jj][ii][mj][mi] );
}
fprintf( stdout, "\n" );
}
fprintf( stdout, "\n" );
fprintf( stdout, "\nsum %f \n\n", sum );}
/******************************************************************************
Set the Diffusion Matrix.
******************************************************************************/
void rd_base::set_diffusion_inhomogeneous()
{
float min_mag_norm[4], max_mag_norm[4];
for( unsigned int t=0; t<4; t++ ) {
min_mag_norm[t] = MAX_FLOAT;
max_mag_norm[t] = -MAX_FLOAT;
}
/* Calculate the diffusion tensor between the post values. */
if( gradient_ ) {
int i0, i1, i_1, j0, j1, j_1, k0, k1, k_1;
float u, v, w;
float dg, grad[3], dotSign = 1.0;
if( reaction_ == rd_base::TURING )
dotSign = -1.0;
for (int j=1; j<height_-1; j++) {
for (int i=1; i<width_-1; i++) {
dg = 0;
// Calculate the gradient using central differences
// of the a morphigen.
grad[0] = morphigen[0][j ][i+1] - morphigen[0][j ][i-1];
grad[1] = morphigen[0][j+1][i ] - morphigen[0][j-1][i ];
if( fabs(grad[0]) > MIN_FLOAT || fabs(grad[1]) > MIN_FLOAT ) {
grad[2] = sqrt(grad[0]*grad[0] + grad[1]*grad[1]);
// Get the dot product of the morphigen gradient and
// the vector field.
float dotProd = dotSign * (grad[0] * vector_data[j][i][0] +
grad[1] * vector_data[j][i][1]) / grad[2];
// Depending on the dot product change the diffusion.
dg = gammp_table[ INDEX(dotProd, MAX_GAMMP) ];
}
// setup the principal diffusivity matrix
float pd00 = diff_coef_1_ + dg;
float pd11 = diff_coef_2_ - dg;
// Square the difusion matrix so that it is positive.
pd00 *= pd00;
pd11 *= pd11;
float cos_ang = vector_data[j][i][0];
float sin_ang = vector_data[j][i][1];
float cos2 = cos_ang*cos_ang;
float sin2 = sin_ang*sin_ang;
// Calculate the tensor for this particular vector.
// NOTE: premultiple the principal difisivity valuies by 1/2
// NOTE: premultiple the secondary difisivity valuies by 1/4
// This is so that it does not need to be done when calculating
// the finite differences.
d_tensor[j][i][0][0] = (pd00 * cos2 + pd11 * sin2) * 0.5;
d_tensor[j][i][0][1] =
d_tensor[j][i][1][0] = (pd00 - pd11) * cos_ang * sin_ang * 0.25;
d_tensor[j][i][1][1] = (pd00 * sin2 + pd11 * cos2) * 0.5;
for( unsigned int t=0; t<4; t++ ) {
if( min_mag_norm[t] > d_tensor[j][i][t/2][t%2] )
min_mag_norm[t] = d_tensor[j][i][t/2][t%2];
if( max_mag_norm[t] < d_tensor[j][i][t/2][t%2] )
max_mag_norm[t] = d_tensor[j][i][t/2][t%2];
}
}
}
} else {
for (int j=0; j<height_; j++) {
for (int i=0; i<width_; i++) {
// setup the principal diffusivity matrix
float pd00 = diff_coef_1_;
float pd11 = diff_coef_2_;
// Square the difusion matrix so that it is positive.
pd00 *= pd00;
pd11 *= pd11;
float cos_ang = vector_data[j][i][0];
float sin_ang = vector_data[j][i][1];
float cos2 = cos_ang*cos_ang;
float sin2 = sin_ang*sin_ang;
/*
if( j == height_ / 4 && i == width_ / 4 ) {
cerr << aval << endl;
cerr << pd00 << endl;
cerr << pd11 << endl;
cerr << cos_ang << endl;
cerr << sin_ang << endl;
}
*/
// Calculate the tensor for this particular vector.
// NOTE: premultiple the principal diffusivity valuies by 1/2
// NOTE: premultiple the secondary diffusivity valuies by 1/4
// This is so that it does not need to be done when calculating
// the finite differences.
d_tensor[j][i][0][0] = (pd00 * cos2 + pd11 * sin2) * 0.5;
d_tensor[j][i][0][1] =
d_tensor[j][i][1][0] = (pd00 - pd11) * cos_ang * sin_ang * 0.25;
d_tensor[j][i][1][1] = (pd00 * sin2 + pd11 * cos2) * 0.5;
for( unsigned int t=0; t<4; t++ ) {
if( min_mag_norm[t] > d_tensor[j][i][t/2][t%2] )
min_mag_norm[t] = d_tensor[j][i][t/2][t%2];
if( max_mag_norm[t] < d_tensor[j][i][t/2][t%2] )
max_mag_norm[t] = d_tensor[j][i][t/2][t%2];
}
}
}
// For debugging print out what the mask would look like.
// int j = height_ / 4;
// int i = width_ / 4;
// int i1 = i+1;
// int j1 = j+1;
// int i_1 = i-1;
// int j_1 = j-1;
// fprintf( stdout, " %d %d\n", i, j );
// fprintf( stdout, " %f %f\n %f %f\n\n",
// d_tensor[j][i][0][0] * 2.0,
// d_tensor[j][i][0][1] * 4.0,
// d_tensor[j][i][1][0] * 4.0,
// d_tensor[j][i][1][1] * 2.0 );
// fprintf( stdout, " %f %f %f\n %f %f %f\n\n",
// d_tensor[j ][i1][0][0], d_tensor[j][i ][0][0], d_tensor[j ][i_1][0][0],
// d_tensor[j1][i ][1][1], d_tensor[j][i ][1][1], d_tensor[j_1][i ][1][1] );
// fprintf( stdout, "Nonuniforn Anisotropic\n %f %f %f\n %f %f %f\n %f %f %f\n\n\n",
// -d_tensor[j ][i1 ][0][1],
// (d_tensor[j1][i ][1][1] + d_tensor[j][i][1][1]),
// d_tensor[j ][i_1][0][1],
// ( d_tensor[j ][i ][0][0] + d_tensor[j][i_1][0][0]),
// -( d_tensor[j ][i1][0][0] + 2.0*d_tensor[j][i ][0][0] + d_tensor[j ][i_1][0][0]) -
// ( d_tensor[j1][i ][1][1] + 2.0*d_tensor[j][i ][1][1] + d_tensor[j_1][i ][1][1]),
// ( d_tensor[j ][i1][0][0] + d_tensor[j][i ][0][0]),
// d_tensor[j1 ][i][1][0],
// (d_tensor[j ][i][1][1] + d_tensor[j_1][i][1][1]),
// -d_tensor[j_1][i][1][0] );
// fprintf( stdout, "Uniforn Anisotropic - Approximation\n %f %f %f\n %f %f %f\n %f %f %f\n\n\n",
// -d_tensor[j][i][0][1],
// (d_tensor[j][i][1][1] + d_tensor[j][i][1][1]),
// d_tensor[j][i][0][1],
// ( d_tensor[j][i][0][0] + d_tensor[j][i][0][0]),
// -( d_tensor[j][i][0][0] + 2.0*d_tensor[j][i][0][0] + d_tensor[j][i][0][0]) -
// ( d_tensor[j][i][1][1] + 2.0*d_tensor[j][i][1][1] + d_tensor[j][i][1][1]),
// ( d_tensor[j][i][0][0] + d_tensor[j][i][0][0]),
// d_tensor[j][i][1][0],
// (d_tensor[j][i][1][1] + d_tensor[j][i][1][1]),
// -d_tensor[j][i][1][0] );
}
// fprintf( stdout, "Tensors" );
// for( unsigned int t=0; t<4; t++ )
// fprintf( stdout, " %f %f", min_mag_norm[t], max_mag_norm[t] );
// fprintf( stdout, "\n" );
}
| 29.036145 | 107 | 0.481549 | [
"vector",
"3d"
] |
e4b97748560633275d5d37c511281e256726582e | 3,219 | cc | C++ | tests/tools/nnpackage_run/src/rawformatter.cc | glistening/ONE-1 | cadf3a4da4f4340081862abbd3900af7c4b0e22d | [
"Apache-2.0"
] | null | null | null | tests/tools/nnpackage_run/src/rawformatter.cc | glistening/ONE-1 | cadf3a4da4f4340081862abbd3900af7c4b0e22d | [
"Apache-2.0"
] | null | null | null | tests/tools/nnpackage_run/src/rawformatter.cc | glistening/ONE-1 | cadf3a4da4f4340081862abbd3900af7c4b0e22d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019 Samsung Electronics Co., Ltd. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "rawformatter.h"
#include "nnfw.h"
#include "nnfw_util.h"
#include <iostream>
#include <fstream>
#include <stdexcept>
namespace nnpkg_run
{
void RawFormatter::loadInputs(const std::string &filename, std::vector<Allocation> &inputs)
{
uint32_t num_inputs;
NNPR_ENSURE_STATUS(nnfw_input_size(session_, &num_inputs));
// Support multiple inputs
// Option 1: Get comman-separated input file list like --load:raw a,b,c
// Option 2: Get prefix --load:raw in
// Internally access in.0, in.1, in.2, ... in.{N-1} where N is determined by nnfw info
// query api.
//
// Currently Option 2 is implemented.
try
{
for (uint32_t i = 0; i < num_inputs; ++i)
{
nnfw_tensorinfo ti;
NNPR_ENSURE_STATUS(nnfw_input_tensorinfo(session_, i, &ti));
// allocate memory for data
auto bufsz = bufsize_for(&ti);
inputs[i].alloc(bufsz);
std::ifstream file(filename + "." + std::to_string(i), std::ios::ate | std::ios::binary);
auto filesz = file.tellg();
if (bufsz != filesz)
{
throw std::runtime_error("Input " + std::to_string(i) +
" size does not match: " + std::to_string(bufsz) +
" expected, but " + std::to_string(filesz) + " provided.");
}
file.seekg(0, std::ios::beg);
file.read(reinterpret_cast<char *>(inputs[i].data()), filesz);
file.close();
NNPR_ENSURE_STATUS(nnfw_set_input(session_, i, ti.dtype, inputs[i].data(), bufsz));
NNPR_ENSURE_STATUS(nnfw_set_input_layout(session_, i, NNFW_LAYOUT_CHANNELS_LAST));
}
}
catch (const std::exception &e)
{
std::cerr << e.what() << std::endl;
std::exit(-1);
}
};
void RawFormatter::dumpOutputs(const std::string &filename, std::vector<Allocation> &outputs)
{
uint32_t num_outputs;
NNPR_ENSURE_STATUS(nnfw_output_size(session_, &num_outputs));
try
{
for (uint32_t i = 0; i < num_outputs; i++)
{
nnfw_tensorinfo ti;
NNPR_ENSURE_STATUS(nnfw_output_tensorinfo(session_, i, &ti));
auto bufsz = bufsize_for(&ti);
std::ofstream file(filename + "." + std::to_string(i), std::ios::out | std::ios::binary);
file.write(reinterpret_cast<const char *>(outputs[i].data()), bufsz);
file.close();
std::cerr << filename + "." + std::to_string(i) + " is generated.\n";
}
}
catch (const std::runtime_error &e)
{
std::cerr << "Error during dumpOutputs on nnpackage_run : " << e.what() << std::endl;
std::exit(-1);
}
}
} // end of namespace nnpkg_run
| 32.846939 | 98 | 0.641814 | [
"vector"
] |
e4bd6391cab1a687ebdd0ac42db9d3c82372b7fc | 33,580 | hpp | C++ | tmp/xlua/support.hpp | xuantao/xlua | 0c2d3e9dd55a8b238472b6ae5955feb64d00058c | [
"MIT"
] | 1 | 2019-10-24T13:49:23.000Z | 2019-10-24T13:49:23.000Z | tmp/xlua/support.hpp | xuantao/xlua | 0c2d3e9dd55a8b238472b6ae5955feb64d00058c | [
"MIT"
] | null | null | null | tmp/xlua/support.hpp | xuantao/xlua | 0c2d3e9dd55a8b238472b6ae5955feb64d00058c | [
"MIT"
] | null | null | null | #pragma once
XLUA_NAMESPACE_BEGIN
template <typename Cat, typename Ty, bool AllowNil>
struct SupportCategory {
typedef Cat category; // value, object or not support
typedef Ty value_type; // load value type
static constexpr bool allow_nil = AllowNil; // load as function parameter is allow nil
};
template <typename Ty, bool AllowNil>
struct ValueCategory : SupportCategory<value_category_tag, Ty, AllowNil> {};
template <typename Ty>
struct ObjectCategory : SupportCategory<object_category_tag_, Ty, std::is_pointer<Ty>::value> {};
namespace internal {
template <typename Ty>
struct IsLarge {
static constexpr bool is_integer = std::numeric_limits<Ty>::is_integer;
static constexpr bool value = std::numeric_limits<Ty>::digits > 32;
};
struct void_tag {};
struct enum_tag {};
struct declared_tag {};
/* traits dispacth tag, declared/enum/void tag */
template <typename Ty>
struct DisaptchTag {
typedef typename std::conditional<IsLuaType<Ty>::value, declared_tag,
typename std::conditional<std::is_enum<Ty>::value, enum_tag, void_tag>::type>::type type_tag;
};
template <typename Ty>
struct DisaptchTag<Ty*> {
typedef typename std::conditional<IsLuaType<Ty>::value, declared_tag, void_tag>::type type_tag;
};
/* object value */
template <typename Ty>
struct ObjectSupport : ObjectCategory<ObjectWrapper<Ty>> {
typedef Support<Ty*> supporter;
static inline bool Check(State* l, int index) {
return supporter::Load(l, index) != nullptr;
}
static inline ObjectWrapper<Ty> Load(State* l, int index) {
return ObjectWrapper<Ty>(supporter::Load(l, index));
}
static inline void Push(State* l, const Ty& obj) {
l->state_.PushUd(obj, supporter::TypeInfo());
}
static inline void Push(State* l, Ty&& obj) {
l->state_.PushUd(std::move(obj), supporter::TypeInfo());
}
};
/* object pointer */
template <typename Ty>
struct ObjectSupport<Ty*> : ObjectCategory<Ty*> {
typedef Support<Ty*> supporter;
static inline bool Check(State* l, int index) {
return l->state_.IsUd<Ty>(index, supporter::TypeInfo());
}
static inline Ty* Load(State* l, int index) {
return l->state_.LoadUd<Ty>(index, supporter::TypeInfo());
}
static inline void Push(State* l, Ty* ptr) {
l->state_.PushUd(ptr, supporter::TypeInfo());
}
};
template <typename Ty, typename Tag>
struct ExportSupport : SupportCategory<not_support_tag, void, true> {
};
/* declared type support */
template <typename Ty>
struct ExportSupport<Ty, declared_tag> : ObjectSupport<Ty> {
static inline const TypeDesc* TypeInfo() {
return xLuaGetTypeDesc(Identity<typename std::remove_pointer<Ty>::type>());
}
static inline const char* Name() { return TypeInfo()->name; }
};
/* enum support */
template <typename Ty>
struct ExportSupport<Ty, enum_tag> : ValueCategory<Ty, false> {
typedef Support<typename std::underlying_type<Ty>::type> supporter;
typedef typename supporter::value_type underlying_type;
static inline const char* Name() { return typeid(Ty).name(); }
static inline bool Check(State* l, int index) {
return supporter::Check(l, index);
}
static inline Ty Load(State* l, int index) {
return static_cast<Ty>(supporter::Load(l, index));
}
static inline void Push(State* l, Ty value) {
supporter::Push(l, static_cast<underlying_type>(value));
}
};
/* number value support */
template <typename Ty>
struct NumberSupport : ValueCategory<Ty, false> {
static inline bool Check(State* l, int index) {
return lua_type(l->GetLuaState(), index) == LUA_TNUMBER;
}
static inline Ty Load(State* l, int index) {
return DoLoad<Ty>(l, index);
}
static inline void Push(State* l, Ty value) {
DoPush(l, value);
}
private:
template <typename U, typename std::enable_if<std::is_floating_point<U>::value, int>::type = 0>
static inline void DoPush(State* l, U val) {
lua_pushnumber(l->GetLuaState(), static_cast<U>(val));
}
template <typename U, typename std::enable_if<IsLarge<U>::is_integer && !IsLarge<U>::value, int>::type = 0>
static inline void DoPush(State* l, U val) {
lua_pushnumber(l->GetLuaState(), val);
}
template <typename U, typename std::enable_if<IsLarge<U>::is_integer && IsLarge<U>::value, int>::type = 0>
static inline void DoPush(State* l, U val) {
lua_pushinteger(l->GetLuaState(), val);
}
template <typename U, typename std::enable_if<std::is_floating_point<U>::value, int>::type = 0>
static inline U DoLoad(State* l, int index) {
return static_cast<U>(lua_tonumber(l->GetLuaState(), index));
}
template <typename U, typename std::enable_if<IsLarge<U>::is_integer && !IsLarge<U>::value, int>::type = 0>
static inline U DoLoad(State* l, int index) {
return static_cast<U>(lua_tonumber(l->GetLuaState(), index));
}
template <typename U, typename std::enable_if<IsLarge<U>::is_integer && IsLarge<U>::value, int>::type = 0>
static inline U DoLoad(State* l, int index) {
return static_cast<U>(lua_tointeger(l->GetLuaState(), index));
}
};
/* collection support */
template <typename Ty, typename CollTy>
struct CollectionSupport : ObjectSupport<Ty> {
static inline ICollection* TypeInfo() { return &coll_; }
static inline const char* Name() { return TypeInfo()->Name(); }
private:
static CollTy coll_;
};
template <typename Ty, typename CollTy> CollTy CollectionSupport<Ty, CollTy>::coll_;
template <typename Ty, typename CollTy>
struct CollectionSupport<Ty*, CollTy> : ObjectSupport<Ty*> {
typedef CollectionSupport<Ty, CollTy> supporter;
static inline ICollection* TypeInfo() { return supporter::TypeInfo(); }
static inline const char* Name() { return supporter::Name(); }
};
} // namespace internal
/* export type support */
template <typename Ty>
struct Support : internal::ExportSupport<Ty, typename internal::DisaptchTag<Ty>::type_tag> {
};
/* lua var support */
template <>
struct Support<Variant> : ValueCategory<Variant, true> {
static inline const char* Name() { return "xlua::Variant"; }
static inline bool Check(State* s, int index) { return true; }
static inline Variant Load(State* s, int index) { return s->GetVar(index); }
static inline void Push(State* s, const Variant& var) { s->PushVar(var); }
};
template <>
struct Support<Table> : ValueCategory<Table, true> {
static inline const char* Name() { return "xlua::Table"; }
static inline bool Check(State* s, int index) {
return lua_type(s->GetLuaState(), index) == LUA_TTABLE;
}
static inline Table Load(State* s, int index) { return s->GetVar(index).ToTable(); }
static inline void Push(State* s, const Table& var) { s->PushVar(var); }
};
template <>
struct Support<Function> : ValueCategory<Function, true> {
static inline const char* Name() { return "xlua::Function"; }
static inline bool Check(State* s, int index) {
return lua_type(s->GetLuaState(), index) == LUA_TFUNCTION;
}
static inline Function Load(State* s, int index) { return s->GetVar(index).ToFunction(); }
static inline void Push(State* s, const Function& var) { s->PushVar(var); }
};
template <>
struct Support<UserData> : ValueCategory<UserData, true> {
static inline const char* Name() { return "xlua::UserData"; }
static inline bool Check(State* s, int index) {
int lty = lua_type(s->GetLuaState(), index);
return lty == LUA_TUSERDATA || lty == LUA_TLIGHTUSERDATA;
}
static inline UserData Load(State* s, int index) { return s->GetVar(index).ToUserData(); }
static inline void Push(State* s, const UserData& var) { s->PushVar(var); }
};
/* nil support */
template <>
struct Support<std::nullptr_t> : ValueCategory<std::nullptr_t, true> {
static inline bool Check(State* s, int index) { return lua_isnil(s->GetLuaState(), index); }
static inline std::nullptr_t Load(State*, int) { return nullptr; }
static inline void Push(State* s, std::nullptr_t) { lua_pushnil(s->GetLuaState()); }
};
#define _XLUA_NUMBER_SUPPORT(Type) \
template <> struct Support<Type> : internal::NumberSupport<Type> { \
static const char* Name() { return #Type; } \
};
_XLUA_NUMBER_SUPPORT(char)
_XLUA_NUMBER_SUPPORT(unsigned char)
_XLUA_NUMBER_SUPPORT(short)
_XLUA_NUMBER_SUPPORT(unsigned short)
_XLUA_NUMBER_SUPPORT(int)
_XLUA_NUMBER_SUPPORT(unsigned int)
_XLUA_NUMBER_SUPPORT(long)
_XLUA_NUMBER_SUPPORT(unsigned long)
_XLUA_NUMBER_SUPPORT(long long)
_XLUA_NUMBER_SUPPORT(unsigned long long)
_XLUA_NUMBER_SUPPORT(float)
_XLUA_NUMBER_SUPPORT(double)
/* boolean type support */
template <>
struct Support<bool> : ValueCategory<bool, true> {
static inline const char* Name() { return "boolean"; }
static inline bool Check(State* s, int index) {
int lty = lua_type(s->GetLuaState(), index);
return lty == LUA_TNIL || lty == LUA_TBOOLEAN;
}
static inline bool Load(State* s, int index) {
return lua_toboolean(s->GetLuaState(), index);
}
static inline void Push(State* s, bool b) {
lua_pushboolean(s->GetLuaState(), b);
}
};
/* string type support */
template <>
struct Support<char*> : ValueCategory<const char*, true> {
static inline const char* Name() {
return "char*";
}
static inline bool Check(State* s, int index) {
return lua_type(s->GetLuaState(), index) == LUA_TSTRING;
}
static inline const char* Load(State* s, int index) {
return lua_tostring(s->GetLuaState(), index);
}
static inline void Push(State* s, const char* p) {
if (p) lua_pushstring(s->GetLuaState(), p);
else lua_pushnil(s->GetLuaState());
}
};
// char array is act as const char*
template <size_t N>
struct Support<char[N]> : ValueCategory<char*, true> {
static_assert(N > 0, "char array size must greater than 0");
static inline const char* Name() {
return "char[]";
}
static inline bool Check(State* s, int index) {
return Support<char*>::Check(s, index);
}
static inline void Push(State* s, const char* p) {
Support<char*>::Push(s, p);
}
static inline char* Load(State* s, int index) = delete;
};
//template <size_t N>
//struct Support<const char[N]> : ValueCategory<const char*, true> {
// static_assert(N > 0, "char array size must greater than 0");
// static inline const char* Name() {
// return "const char[]";
// }
//
// static inline bool Check(State* s, int index) {
// return Support<const char*>::Check(s, index);
// }
//
// static inline char* Load(State* s, int index) = delete;
//
// static inline void Push(State* s, const char* p) {
// Support<const char*>::Push(s, p);
// }
//};
template <class Trait, class Alloc>
struct Support<std::basic_string<char, Trait, Alloc>> : ValueCategory<std::basic_string<char, Trait, Alloc>, true>{
typedef std::basic_string<char, Trait, Alloc> value_type;
static inline const char* Name() { return "std::string"; }
static inline bool Check(State* s, int index) {
return Support<char*>::Check(s, index);
}
static inline value_type Load(State* s, int index) {
size_t len = 0;
const char* str = lua_tolstring(s->GetLuaState(), index, &len);
if (str && len)
return value_type(str, len);
return value_type();
}
static inline void Push(State* s, const value_type& str) {
lua_pushlstring(s->GetLuaState(), str.c_str(), str.size());
}
};
/* only used for check is nil */
template <>
struct Support<void> : ValueCategory<void, false> {
static inline const char* Name() { return "void"; }
static inline bool Check(State* s, int index) { return lua_type(s->GetLuaState(), index) == LUA_TNIL; }
static inline void Load(State* s, int index) = delete;
static inline void Push(State* s) = delete;
};
/* light user data support */
template <>
struct Support<void*> : ValueCategory<void*, true> {
static inline const char* Name() {
return "void*";
}
static inline bool Check(State* s, int index) {
return lua_type(s->GetLuaState(), index) == LUA_TLIGHTUSERDATA;
}
static inline void* Load(State* s, int index) {
return lua_touserdata(s->GetLuaState(), index);
}
static inline void Push(State* s, const void* p) {
if (p) lua_pushlightuserdata(s->GetLuaState(), const_cast<void*>(p));
else lua_pushnil(s->GetLuaState());
}
};
namespace internal {
/* get parameter name and the lua type name */
template <size_t Idx>
struct ParamName {
template <typename... Args>
static inline void GetName(char* buff, size_t sz, State* s, int index) {
constexpr size_t param_idx = sizeof...(Args) - Idx;
using supporter = typename SupportTraits<
typename std::tuple_element<param_idx, std::tuple<Args...>>::type>::supporter;
int w = snprintf(buff, sz, "[%d] %s(%s), ", (int)(param_idx + 1),
supporter::Name(), s->GetTypeName(index));
if (w > 0 && w < sz)
ParamName<Idx - 1>::template GetName(buff + w, sz - w, s, index + 1);
}
};
template <>
struct ParamName<1> {
template <typename... Args>
static inline void GetName(char* buff, size_t sz, State* s, int index) {
constexpr size_t param_idx = sizeof...(Args) - 1;
using supporter = typename SupportTraits<
typename std::tuple_element<param_idx, std::tuple<Args...>>::type>::supporter;
snprintf(buff, sz, "[%d] %s(%s)", (int)(param_idx + 1),
supporter::Name(), s->GetTypeName(index));
}
};
template <>
struct ParamName<0> {
template <typename... Args>
static inline void GetName(char* buff, size_t sz, State* s, int index) {
snprintf(buff, sz, "none");
}
};
template <typename... Args>
inline char* GetParameterNames(char* buff, size_t len, State* s, int index) {
ParamName<sizeof...(Args)>::template GetName<Args...>(buff, len, s, 1);
return buff;
}
template <typename Ty, typename std::enable_if<SupportTraits<Ty>::is_allow_nil, int>::type = 0>
inline bool DoCheckParam(State* s, int index) {
static_assert(SupportTraits<Ty>::is_support, "not xlua support type");
using supporter = typename SupportTraits<Ty>::supporter;
return lua_isnil(s->GetLuaState(), index) || supporter::Check(s, index);
}
template <typename Ty, typename std::enable_if<!SupportTraits<Ty>::is_allow_nil, int>::type = 0>
inline bool DoCheckParam(State* s, int index) {
static_assert(SupportTraits<Ty>::is_support, "not xlua support type");
using supporter = typename SupportTraits<Ty>::supporter;
return supporter::Check(s, index);
}
template <size_t Idx>
struct ParamChecker {
template <typename... Args>
static inline bool Do(State* s, int index) {
using type = typename std::tuple_element<sizeof...(Args) - Idx, std::tuple<Args...>>::type;
return DoCheckParam<type>(s, index) &&
ParamChecker<Idx-1>::template Do<Args...>(s, index + 1);
}
};
template <>
struct ParamChecker<1> {
template <typename... Args>
static inline bool Do(State* s, int index) {
using type = typename std::tuple_element<sizeof...(Args) - 1, std::tuple<Args...>>::type;
return DoCheckParam<type>(s, index);
}
};
template <>
struct ParamChecker<0> {
template <typename... Args>
static inline bool Do(State* s, int index) {
return true;
}
};
template <typename... Args>
inline bool CheckParameters(State* s, int index) {
return ParamChecker<sizeof...(Args)>::template Do<Args...>(s, index);
}
template <typename Fy, typename Ry, typename... Args, size_t... Idxs>
inline auto DoLuaCall(State* s, Fy f, index_sequence<Idxs...>) -> typename std::enable_if<!std::is_void<Ry>::value, int>::type {
if (CheckParameters<Args...>(s, 1)) {
s->Push(f(SupportTraits<Args>::supporter::Load(s, Idxs + 1)...));
return 1;
} else {
char buff[1024];
luaL_error(s->GetLuaState(), "attemp to call export function failed, paramenter is not accpeted,\nparams{%s}",
GetParameterNames<Args...>(buff, 1024, s, 1));
return 0;
}
}
template <typename Fy, typename Ry, typename... Args, size_t... Idxs>
inline auto DoLuaCall(State* s, Fy f, index_sequence<Idxs...>) -> typename std::enable_if<std::is_void<Ry>::value, int>::type {
if (CheckParameters<Args...>(s, 1)) {
f(SupportTraits<Args>::supporter::Load(s, Idxs + 1)...);
} else {
char buff[1024];
luaL_error(s->GetLuaState(), "attemp to call export function failed, paramenter is not accpeted,\nparams{%s}",
GetParameterNames<Args...>(buff, 1024, s, 1));
}
return 0;
}
template <typename Fy, typename Ry, typename... Args>
inline int DoLuaCall(State* s, Fy f) {
return DoLuaCall<Fy, Ry, Args...>(s, f, make_index_sequence_t<sizeof...(Args)>());
}
template <typename Ry, typename... Args>
inline auto MakeFunc(Function f) -> typename std::enable_if<std::is_void<Ry>::value, std::function<Ry(Args...)>>::type{
return [f](Args... args) mutable {
f(std::tie(), args...);
};
}
template <typename Ry, typename... Args>
inline auto MakeFunc(Function f) -> typename std::enable_if<!std::is_void<Ry>::value, std::function<Ry(Args...)>>::type {
return [f](Args... args) mutable -> Ry {
Ry val;
f(std::tie(val), args...);
return std::move(val);
};
}
} // namespace internal
/* function support */
template <>
struct Support<int(lua_State*)> : ValueCategory<int(lua_State*), true> {
typedef int (*value_type)(lua_State*);
static inline const char* Name() { return "lua_cfunction"; }
static inline bool Check(State* s, int index) {
return lua_iscfunction(s->GetLuaState(), index);
}
static inline void Push(State* s, value_type f) {
if (f) lua_pushcfunction(s->GetLuaState(), f);
else lua_pushnil(s->GetLuaState());
}
static inline value_type Load(State* l, int index) {
return lua_tocfunction(l->GetLuaState(), index);
}
};
template <>
struct Support<int(State*)> : ValueCategory<int(State*), true>{
typedef int (*value_type)(State*);
static inline const char* Name() { return "xlua_cfunction"; }
static inline bool Check(State* s, int index) {
return lua_tocfunction(s->GetLuaState(), index) == &Call;
}
static inline value_type Load(State* s, int index) {
if (!Check(s, index))
return nullptr;
lua_getupvalue(s->GetLuaState(), index, 1);
void* f = lua_touserdata(s->GetLuaState(), -1);
lua_pop(s->GetLuaState(), 1);
return static_cast<value_type>(f);
}
static inline void Push(State* s, value_type f) {
if (!f) {
lua_pushnil(s->GetLuaState());
} else {
lua_pushlightuserdata(s->GetLuaState(), static_cast<void*>(f));
lua_pushcclosure(s->GetLuaState(), &Call, 1);
}
}
private:
static int Call(lua_State* l) {
auto* f = static_cast<value_type>(lua_touserdata(l, lua_upvalueindex(1)));
return f(internal::GetState(l));
};
};
template <typename Ry, typename... Args>
struct Support<Ry(Args...)> : ValueCategory<Ry(Args...), true> {
typedef Ry (*value_type)(Args...);
typedef value_category_tag category;
static inline bool Name() { return "cfunction"; }
static inline bool Check(State* s, int index) {
return lua_tocfunction(s->GetLuaState(), index) == &Call;
}
static inline value_type Load(State* s, int index) {
if (!Check(s, index))
return nullptr;
lua_getupvalue(s->GetLuaState(), index, 1);
void* f = lua_touserdata(s->GetLuaState(), -1);
lua_pop(s->GetLuaState(), 1);
return static_cast<value_type>(f);
}
static inline void Push(State* s, value_type f) {
if (!f) {
lua_pushnil(s->GetLuaState());
} else {
lua_pushlightuserdata(s->GetLuaState(), static_cast<void*>(f));
lua_pushcclosure(s->GetLuaState(), &Call, 1);
}
}
private:
int Call(lua_State* l) {
auto f = static_cast<value_type>(lua_touserdata(l, lua_upvalueindex(1)));
return internal::DoLuaCall<value_type, Ry, Args...>(internal::GetState(l), f);
}
};
template <typename Ry, typename... Args>
struct Support<std::function<Ry(Args...)>> : ValueCategory<std::function<Ry(Args...)>, true> {
typedef std::function<Ry(Args...)> value_type;
typedef internal::ObjData<value_type> ObjData;
static inline const char* Name() { return "std::function"; }
static inline bool Check(State* s, int index) {
return lua_type(s->GetLuaState(), index) == LUA_TFUNCTION;
}
static inline value_type Load(State* s, int index) {
int lty = lua_type(s->GetLuaState(), index);
if (lty == LUA_TNIL || lty != LUA_TFUNCTION)
return value_type();
// same type
if (lua_tocfunction(s->GetLuaState(), index) == &Call) {
lua_getupvalue(s->GetLuaState(), index, 1);
auto* d = static_cast<ObjData*>(lua_touserdata(s->GetLuaState(), -1));
lua_pop(s->GetLuaState(), 1);
return d->obj;
}
// other type funtion
return internal::MakeFunc<Ry, Args...>(s->Get<Function>(index));
}
static inline void Push(State* s, const value_type& val) {
if (!val) {
lua_pushnil(s->GetLuaState());
} else {
s->state_.NewAloneObj<value_type>(val);
lua_pushcclosure(s->GetLuaState(), &Call, 1);
}
}
private:
static int Call(lua_State* l) {
auto* d = static_cast<ObjData*>(lua_touserdata(l, lua_upvalueindex(1)));
return internal::DoLuaCall<value_type&, Ry, Args...>(internal::GetState(l), d->obj);
}
};
struct std_shared_ptr_tag {};
/* smart ptr support */
template <typename Ty>
struct Support<std::shared_ptr<Ty>> : ValueCategory<std::shared_ptr<Ty>, true> {
static_assert(SupportTraits<Ty>::is_obj_type, "shared_ptr only support object type");
typedef std::shared_ptr<Ty> value_type;
typedef typename SupportTraits<Ty>::supporter supporter;
static const char* Name() { return "std::shared_ptr"; }
static bool Check(State* s, int index) {
auto* ud = s->state_.LoadRawUd(index);
if (ud == nullptr || ud->minor != internal::UdMinor::SmartPtr)
return false;
auto* ptr = static_cast<internal::ObjUd*>(ud)->As<internal::SmartPtrData>();
if (ptr->tag != tag_)
return false;
return s->state_.IsUd<Ty>(ud, supporter::TypeInfo());
}
static value_type Load(State* s, int index) {
auto* ud = s->state_.LoadRawUd(index);
if (ud == nullptr || ud->minor != internal::UdMinor::kSmartPtr)
return value_type();
auto* ptr = static_cast<internal::ObjUd*>(ud)->As<internal::SmartPtrData>();
if (ptr->tag != tag_)
return value_type();
auto* obj = internal::As(ud, supporter::TypeInfo());
return value_type(*static_cast<value_type*>(ptr->data), (Ty*)obj);
}
static void Push(State* s, const value_type& ptr) {
if (!ptr)
lua_pushnil(s->GetLuaState());
else
s->state_.PushSmartPtr(ptr.get(), ptr, tag_, supporter::TypeInfo());
}
static void Push(State* l, value_type&& ptr) {
if (!ptr)
lua_pushnil(l->GetLuaState());
else
l->state_.PushSmartPtr(ptr.get(), std::move(ptr), tag_, supporter::TypeInfo());
}
private:
static size_t tag_;
};
template <typename Ty>
size_t Support<std::shared_ptr<Ty>>::tag_ = typeid(std_shared_ptr_tag).hash_code();
/* std array support */
template <typename Ty, size_t N>
struct Support<std::array<Ty, N>> : ValueCategory<std::array<Ty, N>, true> {
//TODO:
};
namespace internal {
/* vector collection processor */
template <typename VecTy>
struct VectorCollection : ICollection {
typedef VecTy vector_type;
typedef typename VecTy::value_type value_type;
typedef typename SupportTraits<value_type>::supporter supporter;
const char* Name() override { return "std::vector"; }
int Index(void* obj, State* s) override {
auto* vec = As(obj);
int idx = LoadIndex(s);
if (idx == 0 || !CheckRange(s, idx, vec->size()))
return 0;
s->Push(vec->at(idx - 1));
return 1;
}
int NewIndex(void* obj, State* s) override {
auto* vec = As(obj);
int idx = LoadIndex(s);
if (idx == 0 || !CheckRange(s, idx, vec->size() + 1) || !CheckValue(s))
return 0;
if (idx == (int)vec->size() + 1)
vec->push_back(supporter::Load(s, 3));
else
(*vec)[idx - 1] = supporter::Load(s, 3);
return 0;
}
int Insert(void* obj, State* s) override {
auto* vec = As(obj);
int idx = LoadIndex(s);
if (idx == 0 || !CheckRange(s, idx, vec->size()) || !CheckValue(s))
return 0;
vec->insert(vec->begin() + (idx - 1), supporter::Load(s, 3));
s->Push(true);
return 1;
}
int Remove(void* obj, State* s) override {
auto* vec = As(obj);
int idx = LoadIndex(s);
if (idx == 0 || !CheckRange(s, idx, vec->size()))
return 0;
vec->erase(vec->begin() + (idx - 1));
return 0;
}
int Iter(void* obj, State* s) override {
lua_pushcfunction(s->GetLuaState(), &sIter);
lua_pushlightuserdata(s->GetLuaState(), obj);
lua_pushnumber(s->GetLuaState(), 0);
return 3;
}
int Length(void* obj) override {
return (int)As(obj)->size();
}
void Clear(void* obj) override {
As(obj)->clear();
}
protected:
static inline vector_type* As(void* obj) { return static_cast<vector_type*>(obj); }
inline int LoadIndex(State* s) {
if (!lua_isnumber(s->GetLuaState(), 2)) {
luaL_error(s->GetLuaState(), "vector only accept number index key");
return 0;
}
int idx = s->Get<int>(2);
if (idx <= 0) {
luaL_error(s->GetLuaState(), "vector index must greater than '0'");
return 0;
}
return idx;
}
inline bool CheckRange(State* s, int idx, size_t sz) {
if (idx > 0 && idx <= (int)sz)
return true;
luaL_error(s->GetLuaState(), "vector index is out of range");
return false;
}
inline bool CheckValue(State* s) {
if (internal::DoCheckParam<value_type>(s, 3))
return true;
luaL_error(s->GetLuaState(), "vector value is not allow");
return false;
}
static int sIter(lua_State* l) {
auto* obj = As(lua_touserdata(l, 1));
int idx = (int)lua_tonumber(l, 2);
if (idx < obj->size()) {
lua_pushnumber(l, idx + 1); // next key
internal::GetState(l)->Push(obj->at(idx)); // value
} else {
lua_pushnil(l);
lua_pushnil(l);
}
return 2;
}
};
/* map collection processor */
template <typename MapTy>
struct MapCollection : ICollection {
typedef MapTy map_type;
typedef typename map_type::iterator iterator;
typedef typename map_type::key_type key_type;
typedef typename map_type::mapped_type value_type;
typedef typename SupportTraits<key_type>::supporter key_supporter;
typedef typename SupportTraits<value_type>::supporter value_supporter;
const char* Name() override { return "std::map"; }
int Index(void* obj, State* s) override {
if (!CheckKey(s))
return 0;
key_type key = key_supporter::Load(s, 2);
auto* map = As(obj);
auto it = map->find(key);
if (it == map->end())
s->PushNil();
else
s->Push(it->second);
return 1;
}
int NewIndex(void* obj, State* s) override {
if (!CheckKey(s))
return 0;
key_type key = key_supporter::Load(s, 2);
auto* map = As(obj);
if (s->IsNil(3)) {
map->erase(key);
} else if (CheckValue(s)) {
auto it = map->find(key);
if (it == map->end())
map->insert(std::make_pair(key, (value_type)value_supporter::Load(s, 3)));
else
it->second = value_supporter::Load(s, 3);
}
return 0;
}
int Insert(void* obj, State* s) override {
if (!CheckKey(s) || !CheckValue(s))
return 0;
key_type key = key_supporter::Load(s, 2);
auto* map = As(obj);
if (map->cend() == map->find(key)) {
map->insert(std::make_pair(key, (value_type)value_supporter::Load(s, 3)));
s->Push(true);
} else {
s->Push(false);
}
return 1;
}
int Remove(void* obj, State* s) override {
if (CheckKey(s)) {
key_type key = key_supporter::Load(s, 2);
auto* map = As(obj);
map->erase(key);
}
return 0;
}
int Iter(void* obj, State* s) override {
lua_pushcfunction(s->GetLuaState(), &sIter);
lua_pushlightuserdata(s->GetLuaState(), obj);
s->state_.NewAloneObj<iterator>(As(obj)->begin());
return 0;
}
int Length(void* obj) override {
return (int)As(obj)->size();
}
void Clear(void* obj) override {
As(obj)->clear();
}
protected:
static inline map_type* As(void* obj) { return static_cast<map_type*>(obj); }
inline bool CheckKey(State* s) {
if (key_supporter::Check(s, 2))
return true;
luaL_error(s->GetLuaState(), "vector index is out of range");
return false;
}
inline bool CheckValue(State* s) {
if (internal::DoCheckParam<value_type>(s, 3))
return true;
luaL_error(s->GetLuaState(), "vector value is not allow");
return false;
}
static int sIter(lua_State* l) {
auto* obj = As(lua_touserdata(l, 1));
auto* data = static_cast<internal::ObjData<iterator>*>(lua_touserdata(l, 2));
if (data->obj != obj->end()) {
lua_pushvalue(l, 1);
value_supporter::Push(internal::GetState(l), data->obj->second);
++ data->obj; // move iterator
} else {
lua_pushnil(l);
lua_pushnil(l);
}
return 2;
}
};
} // namespace internal
template <typename Ty, typename Alloc>
struct Support<std::vector<Ty, Alloc>>
: internal::CollectionSupport<std::vector<Ty, Alloc>, internal::VectorCollection<std::vector<Ty, Alloc>>> {
};
template <typename Ty, typename Alloc>
struct Support<std::vector<Ty, Alloc>*>
: internal::CollectionSupport<std::vector<Ty, Alloc>*, internal::VectorCollection<std::vector<Ty, Alloc>>> {
};
template <typename KeyType, typename ValueType, typename PrTy, typename Alloc>
struct Support<std::map<KeyType, ValueType, PrTy, Alloc>>
: internal::CollectionSupport<std::map<KeyType, ValueType, PrTy, Alloc>,
internal::MapCollection<std::map<KeyType, ValueType, PrTy, Alloc>>> {
};
template <typename KeyType, typename ValueType, typename PrTy, typename Alloc>
struct Support<std::map<KeyType, ValueType, PrTy, Alloc>*>
: internal::CollectionSupport<std::map<KeyType, ValueType, PrTy, Alloc>*,
internal::MapCollection<std::map<KeyType, ValueType, PrTy, Alloc>>> {
};
XLUA_NAMESPACE_END
| 35.236097 | 132 | 0.588475 | [
"object",
"vector"
] |
e4c1246435ae7f57a0dd4f635ecf0f5abe6fe824 | 1,532 | hpp | C++ | mark.hpp | ibaned/omega_h_v1 | 9ab9efca33d66e4411f87206a7bd1534cec116e4 | [
"MIT"
] | null | null | null | mark.hpp | ibaned/omega_h_v1 | 9ab9efca33d66e4411f87206a7bd1534cec116e4 | [
"MIT"
] | null | null | null | mark.hpp | ibaned/omega_h_v1 | 9ab9efca33d66e4411f87206a7bd1534cec116e4 | [
"MIT"
] | null | null | null | #ifndef MARK_HPP
#define MARK_HPP
namespace omega_h {
unsigned* mark_down(
unsigned nlows,
unsigned const* highs_of_lows_offsets,
unsigned const* highs_of_lows,
unsigned const* marked_highs);
unsigned* mark_up(
unsigned high_dim,
unsigned low_dim,
unsigned nhighs,
unsigned const* lows_of_highs,
unsigned const* marked_lows);
struct mesh;
unsigned* mesh_mark_down_local(struct mesh* m, unsigned high_dim, unsigned low_dim,
unsigned const* marked_highs);
unsigned* mesh_mark_down(struct mesh* m, unsigned high_dim, unsigned low_dim,
unsigned const* marked_highs);
unsigned* mesh_mark_up(struct mesh* m, unsigned low_dim, unsigned high_dim,
unsigned const* marked_lows);
void mesh_mark_dual_layers(
struct mesh* m,
unsigned** marked,
unsigned nlayers);
unsigned* mark_class(
unsigned nents,
unsigned target_dim,
unsigned target_id,
unsigned const* class_dim_of_ents,
unsigned const* class_id_of_ents);
unsigned* mesh_mark_class(struct mesh* m, unsigned ent_dim,
unsigned target_dim, unsigned target_id);
unsigned* mesh_mark_class_closure_verts(struct mesh* m, unsigned target_dim,
unsigned target_id);
unsigned* mesh_mark_slivers(struct mesh* m, double good_qual, unsigned nlayers);
unsigned* mark_part_boundary(
unsigned nsides,
unsigned const* elems_of_sides_offsets);
void mesh_unmark_boundary(
struct mesh* m,
unsigned ent_dim,
unsigned* marked);
unsigned* mesh_mark_part_boundary(struct mesh* m);
}
#endif
| 24.709677 | 83 | 0.755875 | [
"mesh"
] |
e4c256db3e02a502a0dc54c1b8d99530cb7ea64e | 7,999 | hpp | C++ | cpp-projects/opengl-utility/opengl/buffer/atomic_buffer_object.hpp | FlorianLance/toolbox | 87882a14ec86852d90527c81475b451b9f6e12cf | [
"MIT"
] | null | null | null | cpp-projects/opengl-utility/opengl/buffer/atomic_buffer_object.hpp | FlorianLance/toolbox | 87882a14ec86852d90527c81475b451b9f6e12cf | [
"MIT"
] | null | null | null | cpp-projects/opengl-utility/opengl/buffer/atomic_buffer_object.hpp | FlorianLance/toolbox | 87882a14ec86852d90527c81475b451b9f6e12cf | [
"MIT"
] | 1 | 2021-07-06T14:47:41.000Z | 2021-07-06T14:47:41.000Z |
#pragma once
// local
#include "opengl/utility/gl_utility.hpp"
// static void bind_ranges(std::vector<GLuint> &buffers, GLuint first, std::vector<GLintptr> offsets = {}){
// glBindBuffersRange(
// GL_ATOMIC_COUNTER_BUFFER, // GLenum target,
// first, // GLuint first,
// static_cast<GLsizei>(buffers.size()), // GLsizei count,
// buffers.data(), // const GLuint *buffers,
// &offset, // const GLintptr *offsets,
// &size
// );
// }
// glMapBufferRange and glMapNamedBufferRange map all or part of the data store of a specified buffer object into the client's address space. offset and length indicate the range of data in the buffer object that is to be mapped, in terms of basic machine units. access is a bitfield containing flags which describe the requested mapping. These flags are described below.
// A pointer to the beginning of the mapped range is returned once all pending operations on the buffer object have completed, and may be used to modify and/or query the corresponding range of the data store according to the following flag bits set in access:
// GL_MAP_READ_BIT indicates that the returned pointer may be used to read buffer object data. No GL error is generated if the pointer is used to query a mapping which excludes this flag, but the result is undefined and system errors (possibly including program termination) may occur.
// GL_MAP_WRITE_BIT indicates that the returned pointer may be used to modify buffer object data. No GL error is generated if the pointer is used to modify a mapping which excludes this flag, but the result is undefined and system errors (possibly including program termination) may occur.
// GL_MAP_PERSISTENT_BIT indicates that the mapping is to be made in a persistent fashion and that the client intends to hold and use the returned pointer during subsequent GL operation. It is not an error to call drawing commands (render) while buffers are mapped using this flag. It is an error to specify this flag if the buffer's data store was not allocated through a call to the glBufferStorage command in which the GL_MAP_PERSISTENT_BIT was also set.
// GL_MAP_COHERENT_BIT indicates that a persistent mapping is also to be coherent. Coherent maps guarantee that the effect of writes to a buffer's data store by either the client or server will eventually become visible to the other without further intervention from the application. In the absence of this bit, persistent mappings are not coherent and modified ranges of the buffer store must be explicitly communicated to the GL, either by unmapping the buffer, or through a call to glFlushMappedBufferRange or glMemoryBarrier.
// The following optional flag bits in access may be used to modify the mapping:
// GL_MAP_INVALIDATE_RANGE_BIT indicates that the previous contents of the specified range may be discarded. Data within this range are undefined with the exception of subsequently written data. No GL error is generated if subsequent GL operations access unwritten data, but the result is undefined and system errors (possibly including program termination) may occur. This flag may not be used in combination with GL_MAP_READ_BIT.
// GL_MAP_INVALIDATE_BUFFER_BIT indicates that the previous contents of the entire buffer may be discarded. Data within the entire buffer are undefined with the exception of subsequently written data. No GL error is generated if subsequent GL operations access unwritten data, but the result is undefined and system errors (possibly including program termination) may occur. This flag may not be used in combination with GL_MAP_READ_BIT.
// GL_MAP_FLUSH_EXPLICIT_BIT indicates that one or more discrete subranges of the mapping may be modified. When this flag is set, modifications to each subrange must be explicitly flushed by calling glFlushMappedBufferRange. No GL error is set if a subrange of the mapping is modified and not flushed, but data within the corresponding subrange of the buffer are undefined. This flag may only be used in conjunction with GL_MAP_WRITE_BIT. When this option is selected, flushing is strictly limited to regions that are explicitly indicated with calls to glFlushMappedBufferRange prior to unmap; if this option is not selected glUnmapBuffer will automatically flush the entire mapped range when called.
// GL_MAP_UNSYNCHRONIZED_BIT indicates that the GL should not attempt to synchronize pending operations on the buffer prior to returning from glMapBufferRange or glMapNamedBufferRange. No GL error is generated if pending operations which source or modify the buffer overlap the mapped region, but the result of such previous and any subsequent operations is undefined.
// glMapBufferRange
// auto data = glMapNamedBufferRange(
// buffers[COUNTER_BUFFER], // GLuint buffer : Specifies the name of the buffer object for glMapNamedBufferRange.
// 0, // GLintptr offset : Specifies the starting offset within the buffer of the range to be mapped.
// 1, // GLsizeiptr length : Specifies the length of the range to be mapped.
// GL_MAP_WRITE_BIT// GLbitfield access : Specifies a combination of access flags indicating the desired access to the mapped range.
// );
// reinterpret_cast<GLuint*>(data)[0] = 0;
// glMapNamedBufferRange(
// buffers[COUNTER_BUFFER], // GLuint buffer,
// 0, // GLintptr offset,
// 1, // GLsizeiptr length,
// // GLbitfield access
// );
namespace tool::gl{
struct ABO{
ABO() = default;
ABO(const ABO&) = delete;
ABO& operator=(const ABO&) = delete;
ABO(ABO&& other) = default;
ABO& operator=(ABO&& other) = default;
~ABO(){
clean();
}
constexpr GLuint id() const{return m_id;}
constexpr GLsizeiptr size() const{return m_size;}
void generate(){
if(m_id != 0){
std::cerr << "[GL] ABO already generated: " << m_id << "\n";
return;
}
glCreateBuffers(1, &m_id);
}
bool bind_to_index(GLuint index) const{
if(m_id == 0){
std::cerr << "[GL] ABO not generated, cannot bind it.\n";
return false;
}
glBindBufferBase(
GL_ATOMIC_COUNTER_BUFFER,
index,
m_id
);
return true;
}
void set_data_storage(GLsizeiptr sizeData, GLenum usage = 0){
glNamedBufferStorage(
m_id, // GLuint buffer,
m_size = sizeData, // GLsizeiptr size,
nullptr, // const void *data,
usage // GLbitfield flags
);
}
void update_data(GLuint *data, GLsizeiptr sizeData, GLintptr offset = 0){
if(m_size == 0){
std::cerr << "[GL] ABO no storage initialized.\n";
return;
}
if(sizeData > m_size){
std::cerr << "[GL] ABO size is bigger than storage.\n";
return;
}
glNamedBufferSubData(
m_id, // GLuint buffer: Specifies the name of the buffer object for glNamedBufferSubData.
offset, // GLintptr offset: Specifies the offset into the buffer object's data store where data replacement will begin, measured in bytes.
sizeData, // GLsizeiptr size: Specifies the size in bytes of the data store region being replaced.
data // const void *data: pecifies a pointer to the new data that will be copied into the data store.
);
}
void clean(){
if(m_id == 0){
return;
}
glDeleteBuffers(1, &m_id);
m_id = 0;
}
private:
GLuint m_id = 0;
GLsizeiptr m_size = 0;
};
}
| 57.546763 | 704 | 0.682335 | [
"render",
"object",
"vector"
] |
e4c4a6b9ce3a597f353a2a1d4f01c32de5e5e018 | 4,172 | cpp | C++ | ElfUtils/LinuxMap.cpp | AdrianaDJ/orb | 6aba588b9cd74c28045c950880febc3f5102032f | [
"BSD-2-Clause"
] | 1 | 2021-10-18T03:20:42.000Z | 2021-10-18T03:20:42.000Z | ElfUtils/LinuxMap.cpp | AdrianaDJ/orb | 6aba588b9cd74c28045c950880febc3f5102032f | [
"BSD-2-Clause"
] | 3 | 2022-02-13T22:28:55.000Z | 2022-02-27T11:05:02.000Z | ElfUtils/LinuxMap.cpp | AdrianaDJ/orb | 6aba588b9cd74c28045c950880febc3f5102032f | [
"BSD-2-Clause"
] | 1 | 2021-01-15T22:58:10.000Z | 2021-01-15T22:58:10.000Z | // Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ElfUtils/LinuxMap.h"
#include <absl/strings/str_format.h>
#include <absl/strings/str_split.h>
#include <sys/stat.h>
#include <unistd.h>
#include <filesystem>
#include "ElfUtils/ElfFile.h"
#include "OrbitBase/Logging.h"
#include "OrbitBase/ReadFileToString.h"
#include "OrbitBase/SafeStrerror.h"
namespace orbit_elf_utils {
using orbit_elf_utils::ElfFile;
using orbit_grpc_protos::ModuleInfo;
static ErrorMessageOr<uint64_t> FileSize(const std::string& file_path) {
struct stat stat_buf {};
int ret = stat(file_path.c_str(), &stat_buf);
if (ret != 0) {
return ErrorMessage(absl::StrFormat("Unable to call stat with file \"%s\": %s", file_path,
SafeStrerror(errno)));
}
return stat_buf.st_size;
}
ErrorMessageOr<std::vector<ModuleInfo>> ReadModules(int32_t pid) {
std::filesystem::path proc_maps_path{absl::StrFormat("/proc/%d/maps", pid)};
OUTCOME_TRY(proc_maps_data, orbit_base::ReadFileToString(proc_maps_path));
return ParseMaps(proc_maps_data);
}
ErrorMessageOr<std::vector<ModuleInfo>> ParseMaps(std::string_view proc_maps_data) {
struct AddressRange {
uint64_t start_address;
uint64_t end_address;
bool is_executable;
};
const std::vector<std::string> proc_maps = absl::StrSplit(proc_maps_data, '\n');
std::map<std::string, AddressRange> address_map;
for (const std::string& line : proc_maps) {
std::vector<std::string> tokens = absl::StrSplit(line, ' ', absl::SkipEmpty());
// tokens[4] is the inode column. If inode equals 0, then the memory is not
// mapped to a file (might be heap, stack or something else)
if (tokens.size() != 6 || tokens[4] == "0") continue;
const std::string& module_path = tokens[5];
// This excludes mapped character or block devices.
if (absl::StartsWith(module_path, "/dev/")) continue;
std::vector<std::string> addresses = absl::StrSplit(tokens[0], '-');
if (addresses.size() != 2) continue;
uint64_t start = std::stoull(addresses[0], nullptr, 16);
uint64_t end = std::stoull(addresses[1], nullptr, 16);
bool is_executable = tokens[1].size() == 4 && tokens[1][2] == 'x';
auto iter = address_map.find(module_path);
if (iter == address_map.end()) {
address_map[module_path] = {start, end, is_executable};
} else {
AddressRange& address_range = iter->second;
address_range.start_address = std::min(address_range.start_address, start);
address_range.end_address = std::max(address_range.end_address, end);
address_range.is_executable |= is_executable;
}
}
std::vector<ModuleInfo> result;
for (const auto& [module_path, address_range] : address_map) {
// Filter out entries which are not executable
if (!address_range.is_executable) continue;
if (!std::filesystem::exists(module_path)) continue;
ErrorMessageOr<uint64_t> file_size = FileSize(module_path);
if (!file_size) continue;
ErrorMessageOr<std::unique_ptr<ElfFile>> elf_file = ElfFile::Create(module_path);
if (!elf_file) {
// TODO: Shouldn't this result in ErrorMessage?
ERROR("Unable to load module \"%s\": %s - will ignore.", module_path,
elf_file.error().message());
continue;
}
ErrorMessageOr<uint64_t> load_bias = elf_file.value()->GetLoadBias();
// Every loadable module contains a load bias.
if (!load_bias) {
ERROR("No load bias found for module %s", module_path.c_str());
continue;
}
ModuleInfo module_info;
module_info.set_name(std::filesystem::path{module_path}.filename());
module_info.set_file_path(module_path);
module_info.set_file_size(file_size.value());
module_info.set_address_start(address_range.start_address);
module_info.set_address_end(address_range.end_address);
module_info.set_build_id(elf_file.value()->GetBuildId());
module_info.set_load_bias(load_bias.value());
result.push_back(module_info);
}
return result;
}
} // namespace orbit_elf_utils | 35.65812 | 94 | 0.696788 | [
"vector"
] |
e4c7338501061f6b6910a9a81aef86e08c6cab19 | 522 | cpp | C++ | LeetCode/Solutions/LC0784.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 54 | 2019-05-13T12:13:09.000Z | 2022-02-27T02:59:00.000Z | LeetCode/Solutions/LC0784.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 2 | 2020-10-02T07:16:43.000Z | 2020-10-19T04:36:19.000Z | LeetCode/Solutions/LC0784.cpp | Mohammed-Shoaib/HackerRank-Problems | ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b | [
"MIT"
] | 20 | 2020-05-26T09:48:13.000Z | 2022-03-18T15:18:27.000Z | /*
Problem Statement: https://leetcode.com/problems/letter-case-permutation/
Time: O(2ⁿ • n)
Space: O(2ⁿ)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
vector<string> letterCasePermutation(string S) {
vector<string> perms = { "" };
for (char& c: S) {
vector<string> state;
for (string& perm: perms) {
state.push_back(perm + (char) tolower(c));
if (isalpha(c))
state.push_back(perm + (char) toupper(c));
}
perms = move(state);
}
return perms;
}
}; | 20.88 | 73 | 0.641762 | [
"vector"
] |
e4c9d150b5b291ef7a5c86f979f45a8a90237c84 | 3,401 | cpp | C++ | src/internal/FirstOrderProvider.cpp | gergondet/tvm | e40c11ada9ba8d3e875072d77843e49845b267b9 | [
"BSD-3-Clause"
] | 2 | 2021-03-15T00:54:58.000Z | 2022-02-01T20:15:47.000Z | src/internal/FirstOrderProvider.cpp | ANYbotics/tvm | fb3c7334fc496a5226ec9ee7568dc6ce51c22046 | [
"BSD-3-Clause"
] | null | null | null | src/internal/FirstOrderProvider.cpp | ANYbotics/tvm | fb3c7334fc496a5226ec9ee7568dc6ce51c22046 | [
"BSD-3-Clause"
] | null | null | null | /* Copyright 2017-2018 CNRS-AIST JRL and CNRS-UM LIRMM
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <tvm/internal/FirstOrderProvider.h>
#include <tvm/exception/exceptions.h>
namespace tvm
{
namespace internal
{
FirstOrderProvider::FirstOrderProvider(int m)
: m_(m)
{
resizeCache(); //resize value_
}
void FirstOrderProvider::resizeCache()
{
resizeValueCache();
resizeJacobianCache();
}
void FirstOrderProvider::resizeValueCache()
{
if (isOutputEnabled((int)Output::Value))
value_.resize(m_);
}
void FirstOrderProvider::resizeJacobianCache()
{
if (isOutputEnabled((int)Output::Jacobian))
{
for (auto v : variables_.variables())
jacobian_[v.get()].resize(m_, v->space().tSize());
}
}
void FirstOrderProvider::addVariable(VariablePtr v, bool linear)
{
if(variables_.add(v))
{
jacobian_[v.get()].resize(m_, v->space().tSize());
linear_[v.get()] = linear;
addVariable_(v);
}
}
void FirstOrderProvider::addVariable(const VariableVector & vv, bool linear)
{
for(auto v : vv.variables())
{
addVariable(v, linear);
}
}
void FirstOrderProvider::removeVariable(VariablePtr v)
{
variables_.remove(*v);
jacobian_.erase(v.get());
removeVariable_(v);
}
void FirstOrderProvider::addVariable_(VariablePtr)
{
//do nothing
}
void FirstOrderProvider::removeVariable_(VariablePtr)
{
//do nothing
}
void FirstOrderProvider::splitJacobian(const MatrixConstRef & J, const std::vector<VariablePtr>& vars, bool keepProperties)
{
Eigen::DenseIndex s = 0;
for (const auto& v : vars)
{
auto n = static_cast<Eigen::DenseIndex>(v->space().tSize());
jacobian_[v.get()].keepProperties(keepProperties) = J.middleCols(s, n);
s += n;
}
}
void FirstOrderProvider::resize(int m)
{
m_ = m;
resizeCache();
}
} // namespace internal
} // namespace tvm
| 27.877049 | 125 | 0.709203 | [
"vector"
] |
e4d37e520dedbeb5032ef26e74382ff006c9ede2 | 15,035 | cc | C++ | DQM/SiStripCommissioningSummary/src/SummaryGenerator.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | DQM/SiStripCommissioningSummary/src/SummaryGenerator.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | DQM/SiStripCommissioningSummary/src/SummaryGenerator.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #include "DQM/SiStripCommissioningSummary/interface/SummaryGenerator.h"
#include "DQM/SiStripCommissioningSummary/interface/SummaryGeneratorControlView.h"
#include "DQM/SiStripCommissioningSummary/interface/SummaryGeneratorReadoutView.h"
#include "DataFormats/SiStripCommon/interface/SiStripEnumsAndStrings.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include <iostream>
#include <sstream>
#include <cmath>
#include "TH2F.h"
#include "TProfile.h"
using namespace sistrip;
// -----------------------------------------------------------------------------
//
SummaryGenerator::SummaryGenerator(std::string name)
: map_(), entries_(-1.), max_(-1. * sistrip::invalid_), min_(1. * sistrip::invalid_), label_(""), myName_(name) {
// TH1::SetDefaultSumw2(true); // use square of weights to calc error
}
// -----------------------------------------------------------------------------
//
SummaryGenerator* SummaryGenerator::instance(const sistrip::View& view) {
SummaryGenerator* generator = nullptr;
if (view == sistrip::CONTROL_VIEW) {
generator = new SummaryGeneratorControlView();
} else if (view == sistrip::READOUT_VIEW) {
generator = new SummaryGeneratorReadoutView();
} else {
generator = nullptr;
}
if (generator) {
LogTrace(mlSummaryPlots_) << "[SummaryGenerator::" << __func__ << "]"
<< " Built \"" << generator->myName() << "\" object!";
} else {
edm::LogWarning(mlSummaryPlots_) << "[SummaryGenerator::" << __func__ << "]"
<< " Unexpected view: \"" << SiStripEnumsAndStrings::view(view)
<< "\" Unable to build Generator!"
<< " Returning NULL pointer!";
}
return generator;
}
// -----------------------------------------------------------------------------
//
std::string SummaryGenerator::name(const sistrip::RunType& run_type,
const sistrip::Monitorable& mon,
const sistrip::Presentation& pres,
const sistrip::View& view,
const std::string& directory) {
std::stringstream ss;
ss << sistrip::summaryHisto_ << sistrip::sep_;
ss << SiStripEnumsAndStrings::presentation(pres) << sistrip::sep_;
ss << SiStripEnumsAndStrings::runType(run_type) << sistrip::sep_;
ss << SiStripEnumsAndStrings::view(view) << sistrip::sep_;
ss << SiStripEnumsAndStrings::monitorable(mon);
//LogTrace(mlSummaryPlots_)
//<< "[SummaryGenerator::" << __func__ << "]"
//<< " Histogram name: \"" << ss.str() << "\"";
return ss.str();
}
// -----------------------------------------------------------------------------
//
/*
fix nbins for 1D distribution? to 1024? then change within summary
methods with SetBins() methods? but must limit nbins to < 1024!!!
*/
TH1* SummaryGenerator::histogram(const sistrip::Presentation& pres, const uint32_t& xbins) {
if (!xbins) {
return nullptr;
}
TH1* summary = nullptr;
if (pres == sistrip::HISTO_1D) {
summary = new TH1F("", "", 1024, 0., static_cast<float>(1024));
} else if (pres == sistrip::HISTO_2D_SUM) {
summary = new TH1F("", "", xbins, 0., static_cast<float>(xbins));
} else if (pres == sistrip::HISTO_2D_SCATTER) {
summary = new TH2F("", "", 100 * xbins, 0., static_cast<float>(100 * xbins), 1025, 0., 1025.);
} else if (pres == sistrip::PROFILE_1D) {
summary = new TProfile("", "", xbins, 0., static_cast<float>(xbins), 0., 1025.);
} else {
summary = nullptr;
}
if (summary) {
LogTrace(mlSummaryPlots_) << "[SummaryGenerator::" << __func__ << "]"
<< " Histogram name: \"" << summary->GetName() << "\"";
} else {
edm::LogVerbatim(mlSummaryPlots_) << "[SummaryGenerator::" << __func__ << "]"
<< " Unexpected presentation: \"" << SiStripEnumsAndStrings::presentation(pres)
<< "\" Unable to build summary plot!"
<< " Returning NULL pointer!";
}
return summary;
}
// -----------------------------------------------------------------------------
//
void SummaryGenerator::format(const sistrip::RunType& run_type,
const sistrip::Monitorable& mon,
const sistrip::Presentation& pres,
const sistrip::View& view,
const std::string& directory,
const sistrip::Granularity& gran,
TH1& summary_histo) {
// Set name, title and entries
//std::stringstream ss;
//std::string name = SummaryGenerator::name( run_type, mon, pres, view, directory );
//summary_histo.SetName( name.c_str() );
//summary_histo.SetTitle( name.c_str() );
if (entries_ >= 0.) {
summary_histo.SetEntries(entries_);
}
// X axis
summary_histo.GetXaxis()->SetLabelSize(0.03);
summary_histo.GetXaxis()->SetTitleSize(0.03);
summary_histo.GetXaxis()->SetTitleOffset(3.5);
//gPad->SetBottomMargin(0.2);
// Y axis
summary_histo.GetYaxis()->SetLabelSize(0.03);
summary_histo.GetYaxis()->SetTitleSize(0.03);
summary_histo.GetYaxis()->SetTitleOffset(1.5);
//gPad->SetLeftMargin(0.2);
// Axis label
if (pres == sistrip::HISTO_1D) {
std::string xtitle = label_ + " (for " + directory + ")";
summary_histo.GetXaxis()->SetTitle(xtitle.c_str());
summary_histo.GetYaxis()->SetTitle("Frequency");
summary_histo.GetXaxis()->SetTitleOffset(1.5); //@@ override value set above
} else {
std::string xtitle = SiStripEnumsAndStrings::granularity(gran) + " within " + directory;
summary_histo.GetXaxis()->SetTitle(xtitle.c_str());
summary_histo.GetYaxis()->SetTitle(label_.c_str());
//summary_histo.GetXaxis()->SetTitleOffset(1.5); //@@ override value set above (3.5?)
}
// Formatting for 2D plots
if (pres == sistrip::HISTO_2D_SCATTER) {
// Markers (open circles)
summary_histo.SetMarkerStyle(2);
summary_histo.SetMarkerSize(0.6);
}
// Semi-generic formatting
if (pres == sistrip::HISTO_2D_SUM || pres == sistrip::HISTO_2D_SCATTER || pres == sistrip::PROFILE_1D) {
/*
//put solid and dotted lines on summary to separate top- and
//2nd-from-top- level bin groups.
uint16_t topLevel = 0, topLevelOld = 0, secondLevel = 0, secondLevelOld = 0;
std::string::size_type pos = 0;
for ( HistoData::iterator ibin = map_.begin(); ibin != map_.end(); ibin++) {
//draw line if top and second level numbers change.
pos = ibin->first.find(sistrip::dot_,0);
if (pos != std::string::npos) {
if ((topLevel=atoi(std::string(ibin->first,0,pos).c_str())) != topLevelOld) {
topLevel = topLevelOld;
//
}
else if (ibin->first.find(sistrip::dot_,pos+1) != std::string::npos) {
if ((secondLevelOld=atoi(std::string(ibin->first,pos+1,(ibin->first.find(sistrip::dot_,pos+1)- (pos+1))).c_str())) != secondLevel) {
secondLevel = secondLevelOld;
//
}}}
}
*/
}
}
// -----------------------------------------------------------------------------
//
void SummaryGenerator::clearMap() {
HistoData::iterator iter = map_.begin();
for (; iter != map_.end(); iter++) {
iter->second.clear();
}
map_.clear();
entries_ = -1.;
max_ = -1. * sistrip::invalid_;
min_ = 1. * sistrip::invalid_;
}
// -----------------------------------------------------------------------------
//
void SummaryGenerator::printMap() {
std::stringstream ss;
ss << "[SummaryGenerator::" << __func__ << "]"
<< " Printing contents of map: " << std::endl;
HistoData::iterator iter = map_.begin();
for (; iter != map_.end(); iter++) {
ss << " bin/entries: " << iter->first << "/" << iter->second.size() << " ";
if (!iter->second.empty()) {
ss << " value/error: ";
std::vector<Data>::const_iterator jter = iter->second.begin();
for (; jter != iter->second.end(); jter++) {
ss << jter->first << "/" << jter->second << " ";
}
}
ss << std::endl;
}
ss << " Max value: " << max_ << std::endl << " Min value: " << min_ << std::endl;
LogTrace(mlSummaryPlots_) << ss.str();
}
// -----------------------------------------------------------------------------
//
void SummaryGenerator::fillMap(const std::string& top_level_dir,
const sistrip::Granularity& gran,
const uint32_t& device_key,
const float& value,
const float& error) {
// Check if value is valid
if (value > 1. * sistrip::valid_) {
return;
}
// Calculate maximum and minimum values in std::map
if (value > max_) {
max_ = value;
}
if (value < min_) {
min_ = value;
}
// Check if error is valid
if (error < 1. * sistrip::valid_) {
fill(top_level_dir, gran, device_key, value, error);
} else {
fill(top_level_dir, gran, device_key, value, 0.);
}
}
// -----------------------------------------------------------------------------
//
void SummaryGenerator::fill(const std::string& top_level_dir,
const sistrip::Granularity& gran,
const uint32_t& device_key,
const float& value,
const float& error) {
LogTrace(mlSummaryPlots_) << "[SummaryGenerator::" << __func__ << "]"
<< " Derived implementation does not exist!...";
}
//------------------------------------------------------------------------------
//
void SummaryGenerator::histo1D(TH1& his) {
// Check number of entries in map
if (map_.empty()) {
edm::LogWarning(mlSummaryPlots_) << "[SummaryGenerator::" << __func__ << "]"
<< " No contents in std::map to histogram!";
return;
}
// Retrieve histogram
TH1F* histo = dynamic_cast<TH1F*>(&his);
if (!histo) {
edm::LogWarning(mlSummaryPlots_) << "[SummaryGenerator::" << __func__ << "]"
<< " NULL pointer to TH1F histogram!";
return;
}
// Calculate bin range
int32_t high = static_cast<int32_t>(fabs(max_) > 20. ? max_ + 0.05 * fabs(max_) : max_ + 1.);
int32_t low = static_cast<int32_t>(fabs(min_) > 20. ? min_ - 0.05 * fabs(min_) : min_ - 1.);
int32_t range = high - low;
// increase number of bins for floats
// if ( max_ - static_cast<int32_t>(max_) > 1.e-6 &&
// min_ - static_cast<int32_t>(min_) > 1.e-6 ) {
// range = 100 * range;
// }
// Set histogram binning
histo->SetBins(range, static_cast<float>(low), static_cast<float>(high));
// Iterate through std::map, set bin labels and fill histogram
entries_ = 0.;
HistoData::const_iterator ibin = map_.begin();
for (; ibin != map_.end(); ibin++) {
if (ibin->second.empty()) {
continue;
}
BinData::const_iterator ii = ibin->second.begin();
for (; ii != ibin->second.end(); ii++) {
// bin (value) and weight (error)
histo->Fill(ii->first); //, ii->second );
entries_++;
}
}
}
//------------------------------------------------------------------------------
//
void SummaryGenerator::histo2DSum(TH1& his) {
// Check number of entries in map
if (map_.empty()) {
edm::LogWarning(mlSummaryPlots_) << "[SummaryGenerator::" << __func__ << "]"
<< " No contents in std::map to histogram!";
return;
}
// Retrieve histogram
TH1F* histo = dynamic_cast<TH1F*>(&his);
if (!histo) {
edm::LogWarning(mlSummaryPlots_) << "[SummaryGenerator::" << __func__ << "]"
<< " NULL pointer to TH1F histogram!";
return;
}
// Iterate through map, set bin labels and fill histogram
entries_ = 0.;
uint16_t bin = 0;
HistoData::const_iterator ibin = map_.begin();
for (; ibin != map_.end(); ibin++) {
bin++;
histo->GetXaxis()->SetBinLabel(static_cast<Int_t>(bin), ibin->first.c_str());
if (ibin->second.empty()) {
continue;
}
BinData::const_iterator ii = ibin->second.begin();
for (; ii != ibin->second.end(); ii++) {
// x (bin), y (value) and weight (error)
histo->Fill(static_cast<Double_t>(bin - 0.5),
static_cast<Double_t>(ii->first)); //, ii->second );
entries_ += 1. * ii->first;
}
}
}
//------------------------------------------------------------------------------
//
void SummaryGenerator::histo2DScatter(TH1& his) {
// Check number of entries in map
if (map_.empty()) {
edm::LogWarning(mlSummaryPlots_) << "[SummaryGenerator::" << __func__ << "]"
<< " No contents in std::map to histogram!";
return;
}
// Retrieve histogram
TH2F* histo = dynamic_cast<TH2F*>(&his);
if (!histo) {
edm::LogWarning(mlSummaryPlots_) << "[SummaryGenerator::" << __func__ << "]"
<< " NULL pointer to TH2F histogram!";
return;
}
// Iterate through std::map, set bin labels and fill histogram
entries_ = 0.;
uint16_t bin = 0;
HistoData::const_iterator ibin = map_.begin();
for (; ibin != map_.end(); ibin++) {
bin++;
histo->GetXaxis()->SetBinLabel(static_cast<Int_t>(bin), ibin->first.c_str());
if (ibin->second.empty()) {
continue;
}
BinData::const_iterator ii = ibin->second.begin();
for (; ii != ibin->second.end(); ii++) {
// x (bin), y (value) and weight (error)
histo->Fill(static_cast<Double_t>(bin - 0.5),
static_cast<Double_t>(ii->first)); // , ii->second );
entries_++;
}
}
}
//------------------------------------------------------------------------------
//
void SummaryGenerator::profile1D(TH1& his) {
// Check number of entries in map
if (map_.empty()) {
edm::LogWarning(mlSummaryPlots_) << "[SummaryGenerator::" << __func__ << "]"
<< " No contents in std::map to histogram!";
return;
}
// Retrieve histogram
TProfile* histo = dynamic_cast<TProfile*>(&his);
if (!histo) {
edm::LogWarning(mlSummaryPlots_) << "[SummaryGenerator::" << __func__ << "]"
<< " NULL pointer to TProfile histogram!";
return;
}
// Iterate through std::map, set bin labels and fill histogram
entries_ = 0.;
uint16_t bin = 0;
HistoData::const_iterator ibin = map_.begin();
for (; ibin != map_.end(); ibin++) {
bin++;
histo->GetXaxis()->SetBinLabel(static_cast<Int_t>(bin), ibin->first.c_str());
if (ibin->second.empty()) {
continue;
}
BinData::const_iterator ii = ibin->second.begin();
for (; ii != ibin->second.end(); ii++) {
// x (bin), y (value) and weight (error)
histo->Fill(static_cast<Double_t>(bin - .5),
static_cast<Double_t>(ii->first)); //, ii->second );
entries_++;
}
}
}
| 35.797619 | 137 | 0.539009 | [
"object",
"vector",
"solid"
] |
e4fa389efd6c39c933793e0318b0f55c9cc84e35 | 2,637 | cpp | C++ | lib/atlas/source/atlas/core/Log.cpp | yaoyao0821/bsoid_test | 6222653652cf29cc09c1bb2435874573f31a6369 | [
"MIT"
] | null | null | null | lib/atlas/source/atlas/core/Log.cpp | yaoyao0821/bsoid_test | 6222653652cf29cc09c1bb2435874573f31a6369 | [
"MIT"
] | null | null | null | lib/atlas/source/atlas/core/Log.cpp | yaoyao0821/bsoid_test | 6222653652cf29cc09c1bb2435874573f31a6369 | [
"MIT"
] | null | null | null | #include "atlas/core/Platform.hpp"
#include "atlas/core/Log.hpp"
#ifdef ATLAS_PLATFORM_WINDOWS
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#include <chrono>
#include <ctime>
#include <cstring>
#include <sstream>
#include <iomanip>
#include <vector>
#include <cstdarg>
static const int kMaxLogLength = 16 * 1024;
static const std::vector<std::string> kLevelStrings =
std::vector<std::string>
{
"debug",
"info",
"warning",
"error",
"critical"
};
namespace atlas
{
namespace core
{
namespace Log
{
static void _log(std::string const& message)
{
char buf[kMaxLogLength];
memcpy(buf, message.c_str(), message.size() + 1);
#ifdef ATLAS_PLATFORM_WINDOWS
strncat_s(buf, "\n", 3);
WCHAR wszBuf[kMaxLogLength] = { 0 };
MultiByteToWideChar(CP_UTF8, 0, buf, -1, wszBuf, sizeof(wszBuf));
OutputDebugStringW(wszBuf);
WideCharToMultiByte(CP_ACP, 0, wszBuf, -1, buf, sizeof(buf),
nullptr, FALSE);
printf("%s", buf);
fflush(stdout);
#else
strncat(buf, "\n", 3);
fprintf(stdout, "%s", buf);
fflush(stdout);
#endif
}
static std::string getTimeStamp()
{
auto now = std::chrono::system_clock::now();
auto nowTime = std::chrono::system_clock::to_time_t(now);
std::stringstream stream;
stream << std::put_time(std::localtime(&nowTime), "%T");
return stream.str();
}
void log(SeverityLevel level, std::string const& message)
{
std::string logMessage = "";
// Get the current time stamp
logMessage.append(getTimeStamp());
logMessage.append(" ");
std::string sevLevel = "[";
int levelNum = static_cast<int>(level);
sevLevel.append(kLevelStrings[levelNum]);
sevLevel.append("] : ");
logMessage.append(sevLevel);
logMessage.append(message);
_log(logMessage);
}
void log(SeverityLevel level, const char* format, ...)
{
char buffer[kMaxLogLength];
va_list args;
va_start(args, format);
vsprintf(buffer, format, args);
va_end(args);
log(level, std::string(buffer));
}
}
}
} | 26.908163 | 81 | 0.50967 | [
"vector"
] |
e4fcc93146f0e407ce723a0acce37f27fd313b42 | 13,570 | cpp | C++ | software/protoDUNE/util/rssi_sink.cpp | slaclab/proto-dune | e487ee6d40359b40776098410d7fd302b9631448 | [
"BSD-3-Clause-LBNL"
] | null | null | null | software/protoDUNE/util/rssi_sink.cpp | slaclab/proto-dune | e487ee6d40359b40776098410d7fd302b9631448 | [
"BSD-3-Clause-LBNL"
] | 2 | 2017-05-11T04:22:27.000Z | 2018-09-18T16:10:29.000Z | software/protoDUNE/util/rssi_sink.cpp | slaclab/proto-dune | e487ee6d40359b40776098410d7fd302b9631448 | [
"BSD-3-Clause-LBNL"
] | 2 | 2017-04-03T21:59:53.000Z | 2020-12-13T00:14:20.000Z | // -*-Mode: C;-*-
/* ---------------------------------------------------------------------- *//*!
*
* @file rssi_sink.cpp
* @brief Primitive RSSI receiver for data from the RCEs. This is
* a very small modification of Ryan's original implementation.
* @verbatim
* Copyright 2013
* by
*
* The Board of Trustees of the
* Leland Stanford Junior University.
* All rights reserved.
*
* @endverbatim
*
* @par Facility:
* util
*
* @author
* <russell@slac.stanford.edu>
*
* @par Date created:
* <2018/06/05>
*
* @par Credits:
* SLAC
*
\* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- *\
HISTORY
-------
DATE WHO WHAT
---------- --- ---------------------------------------------------------
2018.06.05 jjr Added documentation/history header.
Modified the copying/accessing of the data in acceptFrame
to use a faster access. This allowed the rate to go to
at least 1.7Gbps
\* ---------------------------------------------------------------------- */
#include <cinttypes>
#include <rogue/protocols/udp/Core.h>
#include <rogue/protocols/udp/Client.h>
#include <rogue/protocols/rssi/Client.h>
#include <rogue/protocols/rssi/Transport.h>
#include <rogue/protocols/rssi/Application.h>
#include <rogue/protocols/packetizer/CoreV2.h>
#include <rogue/protocols/packetizer/Core.h>
#include <rogue/protocols/packetizer/Transport.h>
#include <rogue/protocols/packetizer/Application.h>
#include <rogue/interfaces/stream/Frame.h>
#include <rogue/interfaces/stream/FrameIterator.h>
#include <rogue/interfaces/stream/Buffer.h>
#include <rogue/Logging.h>
#include <getopt.h>
#include <fcntl.h>
#include <unistd.h>
/* ---------------------------------------------------------------------- *//*!
\brief Class to parse and capture the command line parameters
*/
/* ---------------------------------------------------------------------- */
class Parameters
{
public:
Parameters (int argc, char *const argv[]);
public:
char const *getIp () const { return m_ip; }
int getNframes () const { return m_nframes; }
int getCopyFlag () const { return m_copy; }
int getNdump () const { return m_ndump; }
char const *getOfilename () const { return m_ofilename; }
int getRefresh () const { return m_refresh; }
void echo () const;
static void reportUsage ();
public:
char const *m_ip; /*!< The RSSI source IP -mandatory */
char const *m_ofilename; /*!< Output file -optional */
int m_nframes; /*!< Number of input frames-optional */
int m_ndump; /*!< Number of 64-bit words to dump -optional*/
bool m_copy; /*!< Copy the input data -optional */
int m_refresh; /*!< Refresh rate -default = 1 second */
};
/* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- *//*!
\brief Parse out the command line parameters
\param[in] argc The count of command line parameters
\param[in] argv Teh vector of command line parameters
\par
This class exits if the command line parameters are ill-specified
*/
/* ---------------------------------------------------------------------- */
Parameters::Parameters (int argc, char *const argv[])
{
int c;
// Default the number of frames
m_nframes = 64;
m_copy = false;
m_ofilename = NULL;
m_ndump = 0;
m_refresh = 1;
while ( (c = getopt (argc, argv, "ca:n:o:r:")) != EOF)
{
if (c == 'n') { m_nframes = strtol (optarg, NULL, 0); }
else if (c == 'a') { m_copy = true;
m_ndump = strtol (optarg, NULL, 0); }
else if (c == 'c') { m_copy = true; }
else if (c == 'o') { m_copy = true; m_ofilename = optarg; }
else if (c == 'r') { m_refresh = strtol (optarg, NULL, 0); }
}
if (optind < argc)
{
m_ip = argv[optind];
}
else
{
reportUsage ();
exit (-1);
}
return;
}
/* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- *//*!
brief Echo the input parameters
*/
/* ---------------------------------------------------------------------- */
void Parameters::echo () const
{
std::cout << "Starting on IP: " << m_ip << std::endl
<< " refresh rate: " << m_refresh << std::endl;
if (m_nframes)
{
std::cout << " receive frames: " << m_nframes << std::endl;
}
if (m_copy)
{
std::cout << " copy : " << (m_copy ? "yes" : "no") << std::endl;
}
if (m_ndump)
{
std::cout << " dump : " << m_ndump << std::endl;
}
if (m_ofilename)
{
std::cout << " output file : " << m_ofilename << std::endl;
}
std::cout << std::endl;
return;
}
/* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- *//*!
\brief Report the command line usage
*/
/* ---------------------------------------------------------------------- */
void Parameters::reportUsage ()
{
using namespace std;
cout
<< "Usage:" << std::endl
<< "$ rssi_sink [a:cn:o:r:] ip" << endl
<< " where:" << endl
<< " ip: The ip address of data source" << endl
<< " a: Number of hex words to dump (debugging aid)" << endl
<< " n: The number of incoming frames to buffer, default = 64" << endl
<< " c: If present, the frame data is copied into a temporary buffer" << endl
<< " o: If present, then name of an output file" << endl
<< " r: The display refresh rate in seconds (default = 1 second)" << endl
<< endl
<< " Example:" << endl
<< " $ rssi_sink -r 2 -n 100 -a 32 -o/tmp/dump.dat 192.168.2.110" << endl
<< endl
<< " Sets display refresh rate to 2 seconds" << endl
<< " Allocates 100 frames" << endl
<< " Dumps the first 32 64-bit words" << endl
<< " Writes the binary output to /tmp/dump.dat" << endl
<< " Sets the source IP to 192.168.2.110" << endl;
return;
}
/* ---------------------------------------------------------------------- */
/* ---------------------------------------------------------------------- *//*!
\brief Create the output file
\return The file descriptor or -1 in case the file could not be created.
\param[in] filename The name of the file to create
*/
/* ---------------------------------------------------------------------- */
static int create_file (char const *filename)
{
int fd = -1;
fd = creat (filename, S_IRUSR | S_IWUSR
| S_IRGRP | S_IWGRP
| S_IROTH);
if (fd >= 0)
{
fprintf (stderr, "Output file is: %s\n", filename);
}
else
{
fprintf (stderr, "Error opening output file: %s err = %d\n",
filename, errno);
}
return fd;
}
/* ---------------------------------------------------------------------- */
static void dump (uint64_t const *d,
int n);
//! Receive slave data, count frames and total bytes for example purposes.
class TestSink : public rogue::interfaces::stream::Slave {
public:
uint32_t rxCount;
uint64_t rxBytes;
uint32_t rxLast;
int ndump;
bool copy;
int fd;
TestSink(bool copyFlag = false, int ndump = 0, int outputFd = -1) {
rxCount = 0;
rxBytes = 0;
rxLast = 0;
ndump = 0;
copy = copyFlag;
fd = outputFd;
}
void acceptFrame ( boost::shared_ptr<rogue::interfaces::stream::Frame> frame ) {
rxLast = frame->getPayload();
rxBytes += rxLast;
rxCount++;
auto err = frame->getError ();
if (err)
{
std::cout << "Frame error: " << err << std::endl;
}
//std::cout << "Got:" << rxLast << " bytes" << std::endl;
// Copy to buffer
if (copy)
{
// std::cout << "Copying nbytes: " << rxLast << std::endl;
// iterator to start of buffer
rogue::interfaces::stream::Frame::iterator iter = frame->beginRead();
rogue::interfaces::stream::Frame::iterator end = frame->endRead ();
uint8_t *buff = (uint8_t *)malloc(frame->getPayload());
uint8_t *dst = buff;
//Iterate through contigous buffers
while ( iter != end ) {
rogue::interfaces::stream::Frame::iterator nxt = iter.endBuffer();
auto size = iter.remBuffer ();
auto *src = iter.ptr ();
memcpy(dst, src, size);
dst += size;
iter = nxt;
}
if (fd >= 0)
{
ssize_t nwrote = write (fd, buff, rxLast);
if (nwrote != rxLast)
{
fprintf (stderr, "Error %d writing the output file\n", errno);
exit (errno);
}
}
if (ndump)
{
dump ((uint64_t const *)buff, ndump);
}
free(buff);
}
}
};
int main (int argc, char **argv) {
Parameters prms (argc, argv);
struct timeval last;
struct timeval curr;
struct timeval diff;
double timeDiff;
uint64_t lastBytes;
uint64_t diffBytes;
double bw;
char const *daqHost = prms.getIp (); ///"192.168.2.110";
int nframes = prms.getNframes ();
bool copyFlag = prms.getCopyFlag ();
char const *ofilename = prms.getOfilename();
int ndump = prms.getNdump ();
int refresh = prms.getRefresh ();
prms.echo ();
int fd = ofilename ? create_file (ofilename) : -1;
rogue::Logging::setLevel(rogue::Logging::Info);
// Create the UDP client, jumbo = true
rogue::protocols::udp::ClientPtr
udp = rogue::protocols::udp::Client::create(daqHost, 8192, true);
printf("daq host =%s\n",daqHost);
// Make enough room for 'nframes' outstanding buffers
udp->setRxBufferCount (nframes);
// RSSI
rogue::protocols::rssi::ClientPtr
rssi = rogue::protocols::rssi::Client::create(udp->maxPayload());
// Packetizer, ibCrc = false, obCrc = true
////rogue::protocols::packetizer::CoreV2Ptr
//// pack = rogue::protocols::packetizer::CoreV2::create(false,true);
rogue::protocols::packetizer::CorePtr
pack = rogue::protocols::packetizer::Core::create();
// Connect the RSSI engine to the UDP client
udp->setSlave(rssi->transport());
rssi->transport()->setSlave(udp);
// Connect the RSSI engine to the packetizer
rssi->application()->setSlave(pack->transport());
pack->transport()->setSlave(rssi->application());
// Create a test sink and connect to channel 1 of the packetizer
boost::shared_ptr<TestSink>
sink = boost::make_shared<TestSink>(copyFlag, ndump, fd);
pack->application(0)->setSlave(sink);
rssi->start();
// Loop forever showing counts
lastBytes = 0;
gettimeofday(&last,NULL);
int count = 0;
while(1)
{
sleep (refresh);
gettimeofday (&curr, NULL);
timersub (&curr,&last,&diff);
diffBytes = sink->rxBytes - lastBytes;
lastBytes = sink->rxBytes;
timeDiff = (double)diff.tv_sec + ((double)diff.tv_usec / 1e6);
bw = (((float)diffBytes * 8.0) / timeDiff) / 1e9;
gettimeofday(&last,NULL);
char eol = diffBytes ? '\n' : '\r';
printf("%6u RSSI = %i. RxLast=%i, RxCount=%i, RxTotal=%li, Bw=%f, DropRssi=%i, DropPack=%i%c",
count++,
rssi->getOpen(),
sink->rxLast,
sink->rxCount,
sink->rxBytes,
bw,
rssi->getDropCount(),
pack->getDropCount(),
eol);
fflush (stdout);
}
}
/* ---------------------------------------------------------------------- *//*!
\brief Primitive hex dump routine
\param[in] d Pointer to the data to be dumped
\param[in] n The number of 64-bit words to dump
*/
/* ---------------------------------------------------------------------- */
static void dump (uint64_t const *d, int n)
{
for (int idx = 0; idx < n; idx++)
{
if ( (idx & 0x3) == 0) printf ("%2x:", idx);
printf (" %16.16" PRIx64 , d[idx]);
if ((idx & 0x3) == 3) putchar ('\n');
}
return;
}
/* ---------------------------------------------------------------------- */
| 29.182796 | 100 | 0.452763 | [
"vector"
] |
900070f78c15a8b727b8527f292c5dade4d33b67 | 786 | cpp | C++ | Section 1/Section 1 Code Files/regex.cpp | irshadqemu/C-Standard-Template-Library-in-Practice | 05a52a03c2fc50031f065da41d89cfbf651499f9 | [
"MIT"
] | 17 | 2019-10-10T21:09:51.000Z | 2022-01-13T15:54:24.000Z | Section 1/Section 1 Code Files/regex.cpp | irshadqemu/C-Standard-Template-Library-in-Practice | 05a52a03c2fc50031f065da41d89cfbf651499f9 | [
"MIT"
] | null | null | null | Section 1/Section 1 Code Files/regex.cpp | irshadqemu/C-Standard-Template-Library-in-Practice | 05a52a03c2fc50031f065da41d89cfbf651499f9 | [
"MIT"
] | 16 | 2019-10-10T21:09:55.000Z | 2022-02-13T11:42:52.000Z | #include <string>
#include <iostream>
#include <regex>
using namespace std;
int main() {
string s("This is a large string containing some numbers like 408 and (382), it also contains some phone numbers like (921) 523-1101, 117-332-1019, and +13314560987. These should all match, but ignore our lone numbers like 433-0988 and (281)2121 since those are not phone numbers.");
//define our matching object
cmatch matcher;
regex allPhoneNumbers(R"delim((\+\d{1,3})?[\.\-\)\(]*([0-9]{3})[\.\-\)\(\ ]*([0-9]{3})[\.\-\)\(\ ]*([0-9]{4}))delim");
while(regex_search(s.c_str(), matcher, allPhoneNumbers,
regex_constants::match_default)){
cout << "Matches: " << "\n";
cout << "[" << matcher[0] << "]\n";
s = matcher.suffix().str();
}
return 0;
}
| 27.103448 | 285 | 0.614504 | [
"object"
] |
07eeae2e5fdabacfa4b9de1f79872ece241e3517 | 2,002 | cpp | C++ | libraries/lib-network-manager/curl/CurlResponseFactory.cpp | Schweini07/audacium | f785b4e040043fd2ff15972578099e01843ec8e9 | [
"CC-BY-3.0"
] | null | null | null | libraries/lib-network-manager/curl/CurlResponseFactory.cpp | Schweini07/audacium | f785b4e040043fd2ff15972578099e01843ec8e9 | [
"CC-BY-3.0"
] | null | null | null | libraries/lib-network-manager/curl/CurlResponseFactory.cpp | Schweini07/audacium | f785b4e040043fd2ff15972578099e01843ec8e9 | [
"CC-BY-3.0"
] | null | null | null | /*!********************************************************************
Audacity: A Digital Audio Editor
@file CurlResponseFactory.cpp
@brief Define an implementation of IResponseFactory using libcurl.
Dmitry Vedenko
**********************************************************************/
#include "CurlResponseFactory.h"
#include <algorithm>
#include "CurlResponse.h"
namespace audacity
{
namespace network_manager
{
constexpr decltype(std::thread::hardware_concurrency ()) MIN_CURL_THREADS = 6;
CurlResponseFactory::CurlResponseFactory ()
: mThreadPool (std::make_unique<ThreadPool>(
std::max (
MIN_CURL_THREADS,
std::thread::hardware_concurrency ()
)))
{
}
void CurlResponseFactory::setProxy (const std::string& proxy)
{
mHandleManager->setProxy (proxy);
}
ResponsePtr CurlResponseFactory::performRequest (RequestVerb verb, const Request& request)
{
return performRequest (verb, request, nullptr, 0);
}
ResponsePtr CurlResponseFactory::performRequest (RequestVerb verb, const Request& request, const void* data, size_t size)
{
if (!mThreadPool)
return {};
std::shared_ptr<CurlResponse> response = std::make_shared<CurlResponse> (
verb, request, mHandleManager.get ()
);
std::vector<uint8_t> buffer;
if (data != nullptr && size != 0)
{
const uint8_t* start = static_cast<const uint8_t*>(data);
const uint8_t* end = static_cast<const uint8_t*>(data) + size;
buffer.insert (buffer.begin (), start, end);
}
mThreadPool->enqueue ([response, dataBuffer = std::move (buffer)]() {
if (!dataBuffer.empty())
response->perform (dataBuffer.data (), dataBuffer.size ());
else
response->perform (nullptr, 0);
});
return response;
}
void CurlResponseFactory::terminate ()
{
mThreadPool.reset ();
mHandleManager.reset ();
}
}
}
| 24.716049 | 122 | 0.595904 | [
"vector"
] |
07f44cfa2f822b7d9c4e55766488d1b6c83cc437 | 82,379 | cpp | C++ | src/mainwindow.cpp | ryan-cranfill/monster-mash | c1b906d996885f8a4011bdf7558e62e968e1e914 | [
"Apache-2.0"
] | 3 | 2021-07-25T17:38:19.000Z | 2022-01-17T03:11:16.000Z | src/mainwindow.cpp | ryan-cranfill/monster-mash | c1b906d996885f8a4011bdf7558e62e968e1e914 | [
"Apache-2.0"
] | null | null | null | src/mainwindow.cpp | ryan-cranfill/monster-mash | c1b906d996885f8a4011bdf7558e62e968e1e914 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020-2021 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "mainwindow.h"
#include <igl/per_vertex_normals.h>
#include <igl/writeOBJ.h>
#include <image/imageUtils.h>
#include <miscutils/camera.h>
#include <shaderMatcap/shaderMatcap.h>
#include "loadsave.h"
#include "macros.h"
#include "reconstruction.h"
#include "shaderTextureVertexCoords.h"
using namespace std;
using namespace igl;
using namespace Eigen;
MainWindow::MainWindow(int w, int h, const std::string &windowTitle)
: MyWindow(w, h, windowTitle) {
viewportW = w;
viewportH = h;
// setMouseEventsSimulationByTouch(false);
initOpenGL();
initImageLayers();
recreateMergedImgs();
// main
depthBuffer = Img<float>(windowWidth, windowHeight, 1);
frameBuffer = Imguc(windowWidth, windowHeight, 4);
// init screen image
screenImg = Imguc(windowWidth, windowHeight, 4, 3);
}
MainWindow::~MainWindow() { destroyOpenGL(); }
void MainWindow::initOpenGL() {
// opengl
GLMeshInitBuffers(glData.meshData);
glData.shaderMatcap = loadShaders(SHADERMATCAP_VERT, SHADERMATCAP_FRAG);
glData.shaderTexture =
loadShaders(SHADERTEXVERTCOORDS_VERT, SHADERTEXVERTCOORDS_FRAG);
deque<string> textureFns{
datadirname + "/shaders/matcapOrange.jpg",
};
loadTexturesToGPU(textureFns, glData.textureNames);
if (shadingOpts.matcapImg != -1)
glBindTexture(GL_TEXTURE_2D, glData.textureNames[shadingOpts.matcapImg]);
}
void MainWindow::destroyOpenGL() { GLMeshDestroyBuffers(glData.meshData); }
bool MainWindow::paintEvent() {
if (!repaint) {
SDL_Delay(1);
return false;
}
repaint = false;
MEASURE_TIME_START(tStartAll);
MyPainter painter(this);
painter.setColor(bgColor);
painter.clearToColor();
rasterizeGPUClear();
screenImg.fill(0);
MyPainter painterOther(screenImg);
bool transitionRunning = drawModeTransition(painter, painterOther);
if (transitionRunning) repaint = true;
if ((manipulationMode.isGeometryModeActive() || showModel) &&
!transitionRunning) {
repaint = true;
// draw background
if (!backgroundImg.isNull() && shadingOpts.showBackgroundImg)
painter.drawTexture(glData.backgroundImgTexName);
// animation
if (manipulationMode.mode == ANIMATE_MODE) {
cpAnimationPlaybackAndRecord();
}
// draw 3D model
computeNormals(shadingOpts.useNormalSmoothing);
drawGeometryMode(painter, painterOther);
// deformation
if (!defPaused) {
double defDiff = handleDeformations();
// DEBUG_CMD_MM(cout << defDiff << endl;);
if (defDiff < 0.01 &&
!(manipulationMode.mode == ANIMATE_MODE && isAnimationPlaying() &&
!cpData.cpsAnim
.empty()) // always repaint if there's animation playing
) {
repaint = false;
}
} else
repaint = false;
// export animation frame
// cout << exportAnimationRunning() << endl;
if (exportAnimationRunning()) exportAnimationFrame();
if (showMessages) drawMessages(painter);
}
if (manipulationMode.isImageModeActive() && !transitionRunning) {
drawImageMode(painter, painterOther);
painterOther.paint();
}
if (!transitionRunning) painter.drawImage(0, 0, screenImg);
painter.paint();
double tAllElapsed = 0;
MEASURE_TIME_END(tStartAll, tAllElapsed);
#ifndef __EMSCRIPTEN__
// cout << tAllElapsed << "ms, " << 1000.0/tAllElapsed << " FPS" << endl;
#endif
const int delay = 8 - tAllElapsed;
if (delay > 0) SDL_Delay(delay);
return true;
}
double MainWindow::handleDeformations() {
double tElapsedMsARAP = 0;
auto *defCurr = &def;
if (manipulationMode.mode == DEFORM_MODE) defCurr = &defDeformMode;
if (mesh.VCurr.rows() == 0) {
// mesh empty, skipping
return 0;
}
double defDiff;
MEASURE_TIME(defDiff = defEng.deform(*defCurr, mesh), tElapsedMsARAP);
defData.VCurr = mesh.VCurr;
defData.Faces = mesh.F;
defData.VRestOrig = mesh.VRest;
return defDiff;
}
void MainWindow::startModeTransition(const ManipulationMode &prevMode,
const ManipulationMode &currMode) {
transitionPrevMode = prevMode;
transitionCurrMode = currMode;
startTransition = true;
repaint = true;
}
bool MainWindow::drawModeTransition(MyPainter &painter,
MyPainter &painterOther) {
if (startTransition) {
recomputeCameraCenter();
transitionStartTimepoint = chrono::high_resolution_clock::now();
startTransition = false;
transitionRunning = true;
transitionCamData = camData;
rotVerTo = 0, rotVerFrom = 0, rotHorTo = 0, rotHorFrom = 0;
rotHorFrom = transitionCamData.rotHor;
rotVerFrom = transitionCamData.rotVer;
if (transitionCurrMode.mode == DEFORM_MODE) {
rotHorTo = camDataDeformMode.rotHor;
rotVerTo = camDataDeformMode.rotVer;
} else if (transitionCurrMode.mode == ANIMATE_MODE) {
rotHorTo = camDataAnimateMode.rotHor;
rotVerTo = camDataAnimateMode.rotVer;
}
// choose the shortest path around the circle
auto angPos360 = [](float ang) -> float {
ang = fmod(ang, 360);
if (ang < 0) ang = 360 + ang;
return ang;
};
auto shortest = [&](float fromIn, float toIn, float &fromOut,
float &toOut) {
fromIn = angPos360(fromIn);
toIn = angPos360(toIn);
float d1 = toIn - fromIn; // CCW
float d2 = -toIn - (-fromIn); // CW
d1 = angPos360(d1);
d2 = angPos360(d2);
DEBUG_CMD_MM(cout << "fromIn: " << fromIn << ", toIn: " << toIn
<< ", d1: " << d1 << ", d2: " << d2 << endl;);
fromOut = fromIn;
if (d1 < d2) {
toOut = fromIn + d1;
} else {
toOut = fromIn - d2;
}
};
shortest(rotHorFrom, rotHorTo, rotHorFrom, rotHorTo);
shortest(rotVerFrom, rotVerTo, rotVerFrom, rotVerTo);
}
if (!transitionRunning) return false;
int duration =
chrono::duration_cast<chrono::milliseconds>(
chrono::high_resolution_clock::now() - transitionStartTimepoint)
.count();
if (duration >= transitionDuration) {
transitionRunning = false;
return false;
}
if (transitionPrevMode.isImageModeActive() &&
transitionCurrMode.isImageModeActive()) {
transitionRunning = false;
return false;
}
auto lerp = [](const auto &to, const auto &from, double t) -> auto {
return t * to + (1 - t) * from;
};
double t = static_cast<double>(duration) / transitionDuration;
rotHor = lerp(rotHorTo, rotHorFrom, t);
rotVer = lerp(rotVerTo, rotVerFrom, t);
rotPrev = Vector2d(rotHor, rotVer);
// draw background
if (!backgroundImg.isNull() && shadingOpts.showBackgroundImg)
painter.drawTexture(glData.backgroundImgTexName);
// draw 3D model
computeNormals(shadingOpts.useNormalSmoothing);
drawGeometryMode(painter, painterOther);
// draw sketch
double t2 = 0;
if (transitionCurrMode.isImageModeActive())
t2 = t;
else if (transitionPrevMode.isImageModeActive())
t2 = 1 - t;
if (t2 > 0) {
if (transitionPrevMode.mode == ANIMATE_MODE) {
// we assume that screenImg contains geometry mode rasterized information
// only
painter.drawImage(0, 0, screenImg, 1 - t2);
}
Imguc bg(windowWidth, windowHeight, 4, 3);
bg.fill(bgColor);
painter.drawImage(0, 0, bg, t2);
drawImageMode(painter, painterOther, t2);
}
return true;
}
void MainWindow::computeNormals(bool smoothing) {
// compute normals
auto &V = defData.VCurr;
auto &F = defData.Faces;
auto &N = defData.normals;
if (V.rows() == 0) {
// mesh empty, skipping
return;
}
per_vertex_normals(V, F, PER_VERTEX_NORMALS_WEIGHTING_TYPE_DEFAULT, N);
// normals may have some NaN's, treat them before smoothing
fora(i, 0, N.rows()) {
bool nan = false;
fora(j, 0, 3) {
if (isnan(N(i, j))) {
nan = true;
break;
}
}
if (nan) {
N.row(i) = Vector3d(0, 0, 1);
}
}
if (smoothing) {
auto &L = defEng.L;
if (L.rows() == N.rows()) {
fora(i, 0, shadingOpts.normalSmoothingIters) {
N += shadingOpts.normalSmoothingStep * L * N;
N.rowwise().normalize();
}
}
}
}
void MainWindow::drawGeometryMode(MyPainter &painterModel,
MyPainter &painterOther) {
auto *defData = &this->defData;
auto &V = defData->VCurr;
auto &Vr = defData->VRestOrig;
auto &F = defData->Faces;
auto &N = defData->normals;
auto &showControlPoints = cpData.showControlPoints;
if (false && autoRotateDir != -1 && manipulationMode.mode == DEFORM_MODE) {
// auto rotate
int redrawFPS = 60;
if (redrawFPS > 0) {
const double rot = 50.0 / redrawFPS;
double dHor = 0, dVer = 0;
if (autoRotateDir == 0)
dHor = rot;
else if (autoRotateDir == 1)
dHor = -rot;
else if (autoRotateDir == 2)
dVer = rot;
else if (autoRotateDir == 3)
dVer = -rot;
if (autoRotateDir != -1) rotateViewportIncrement(dHor, dVer);
}
}
if (V.rows() == 0) {
// mesh empty, skipping
return;
}
// draw the 3D view
const Vector3d ¢roid = cameraCenter;
if (forceRecomputeCameraCenter) {
recomputeCameraCenter();
forceRecomputeCameraCenter = false;
}
float near = -5000;
float far = 10000;
float scale2 = scale;
if (!ortho) {
float maxDepth =
std::max(Vr.col(0).maxCoeff() - Vr.col(0).minCoeff(),
std::max(Vr.col(1).maxCoeff() - Vr.col(1).minCoeff(),
Vr.col(2).maxCoeff() - Vr.col(2).minCoeff()));
near = 500;
far = near + 1.5 * maxDepth;
scale2 *= 1.5;
}
float rotHor2 = rotHor, rotVer2 = rotVer;
Vector2d translateView2 = translateView;
if (imageSpaceView) {
ortho = true;
if (!imageSpaceViewRotTrans) {
rotHor2 = 0;
rotVer2 = 0;
}
translateView2.fill(0);
near = -5000;
far = 10000;
}
buildCameraMatrices(ortho, viewportW / scale2, viewportH / scale2, near, far,
rotVer2, rotHor2, translateView2, centroid, glData.P,
glData.M);
if (imageSpaceView) {
// translate in image space
const Vector3d shift =
(glData.P * (cameraCenterViewSpace +
Vector3d(translateView.x(), translateView.y(), 0))
.homogeneous())
.hnormalized();
glData.P = Affine3d(Translation3d(Vector3d(shift(0), shift(1), 0) +
Vector3d(-1, -1, 0))) *
Ref<Matrix4d>(glData.P);
}
flyCameraM =
Affine3d( // from bottom to top
Translation3d(translateCam) // translate
*
AngleAxisd(rotateCam(2) / 180.0 * M_PI, Vector3d::UnitZ()) // rotate
*
AngleAxisd(rotateCam(1) / 180.0 * M_PI, Vector3d::UnitY()) // rotate
*
AngleAxisd(rotateCam(0) / 180.0 * M_PI, Vector3d::UnitX()) // rotate
)
.matrix();
glData.M = flyCameraM * glData.M;
proj3DView = Affine3d(Scaling<double>(0.5 * viewportW, 0.5 * viewportH, 1) *
Translation3d(1, 1, 0)) *
Ref<Matrix4d>(glData.P) * Ref<Matrix4d>(glData.M);
proj3DViewInv = proj3DView.inverse();
glData.P =
Affine3d(Scaling(1., -1., 1.)).matrix() *
glData
.P; // convert from cartesian (OpenGL) to image coordinates (flip y)
glViewport(0, 0, viewportW, viewportH);
drawModelOpenGL(V, Vr, F, N);
if (showControlPoints) {
if (manipulationMode.mode == ANIMATE_MODE) {
if (!use3DCPTrajectoryVisualization)
visualizeCPAnimTrajectories2D(painterOther);
}
if (!use3DCPVisualization) {
cpVisualize2D(painterOther);
}
}
// draw rubber band
if (rubberBandActive) {
double x1 = mousePressStart(0);
double y1 = mousePressStart(1);
double x2 = mouseCurrPos(0);
double y2 = mouseCurrPos(1);
if (x1 > x2) swap(x1, x2);
if (y1 > y2) swap(y1, y2);
painterOther.setColor(0, 0, 0, 255);
painterOther.drawRect(x1, y1, x2, y2);
}
}
void MainWindow::rotateViewportIncrement(double rotHorInc, double rotVerInc) {
rotPrev += Vector2d(rotHorInc, rotVerInc);
rotHor = rotPrev(0);
rotVer = rotPrev(1);
}
void MainWindow::drawModelOpenGL(Eigen::MatrixXd &V, Eigen::MatrixXd &Vr,
Eigen::MatrixXi &F, Eigen::MatrixXd &N) {
auto *templateImg = &this->templateImg;
MatrixXd colors;
MatrixXd textureCoords;
MatrixXi PARTID;
GLuint activeShader;
glActiveTexture(GL_TEXTURE0);
if (shadingOpts.showTexture && !templateImg->isNull()) {
activeShader = glData.shaderTexture;
glUseProgram(activeShader);
glUniform1i(glGetUniformLocation(activeShader, "tex"), 0);
glUniform1f(glGetUniformLocation(activeShader, "useShading"),
shadingOpts.showTextureUseMatcapShading ? 1 : 0);
// texture coords
const Imguc &I = *templateImg;
textureCoords = (Vr.array().rowwise() / Array3d(I.w, I.h, 1).transpose());
textureCoords.col(2).fill(-1);
glBindTexture(GL_TEXTURE_2D, glData.templateImgTexName);
} else if (shadingOpts.matcapImg != -1) {
activeShader = glData.shaderMatcap;
glUseProgram(activeShader);
glBindTexture(GL_TEXTURE_2D, glData.textureNames[shadingOpts.matcapImg]);
}
MatrixXd C;
uploadCameraMatrices(activeShader, glData.P, glData.M,
glData.M.inverse().transpose());
GLMeshFillBuffers(activeShader, glData.meshData, V, F, N, textureCoords, C,
PARTID);
GLMeshDraw(glData.meshData, GL_TRIANGLES);
}
void MainWindow::cpVisualize2D(MyPainter &screenPainter) {
auto *cpData = &this->cpData;
auto *defData = &this->defData;
auto &selectedPoints = cpData->selectedPoints;
auto &cpAnimSync = cpData->cpAnimSync;
auto cpsAnimSyncId = cpData->cpsAnimSyncId;
auto *defCurr = &def;
if (manipulationMode.mode == DEFORM_MODE) {
return;
}
Cu colorBlack{0, 0, 0, 255};
Cu colorGreen{0, 255, 0, 255};
Cu colorRed{255, 0, 0, 255};
if (rotationModeActive) {
colorBlack = Cu{128, 128, 128, 255};
colorGreen = Cu{192, 192, 192, 255};
colorRed = Cu{192, 192, 192, 255};
}
// show handles
drawControlPoints(*defCurr, screenPainter, 7, proj3DView, 1, colorBlack,
colorRed); // 3D view
if (!displaySyncCPAnim && cpsAnimSyncId != -1) {
try {
const Vector3d p = defCurr->getCP(cpsAnimSyncId).pos;
drawControlPoint(p, screenPainter, 7, proj3DView, 1, colorBlack,
colorGreen);
} catch (out_of_range &e) {
cerr << e.what() << endl;
}
}
for (int cpId : selectedPoints) {
try {
Cu colorFg = colorRed;
if (!displaySyncCPAnim && cpId == cpsAnimSyncId) colorFg = colorGreen;
const Eigen::VectorXd &p = defCurr->getCP(cpId).pos;
drawControlPoint(p, screenPainter, 7, proj3DView, 4, colorBlack, colorFg);
} catch (out_of_range &e) {
cerr << e.what() << endl;
}
}
}
void MainWindow::visualizeCPAnimTrajectories2D(MyPainter &screenPainter) {
auto *cpData = &this->cpData;
auto &cpsAnim = cpData->cpsAnim;
auto &selectedPoints = cpData->selectedPoints;
auto &cpAnimSync = cpData->cpAnimSync;
// visualize animations of control points
auto drawTrajectoriesAndKeyframes = [&](CPAnim &a,
float beginningThicknessMult) {
a.drawTrajectory(screenPainter, proj3DView,
beginningThicknessMult); // 3D view
if (displayKeyframes) {
screenPainter.setThickness(1);
a.drawKeyframes(screenPainter, 1, proj3DView);
}
};
for (auto &el : cpsAnim) {
// draw control points trajectory
const int cpId = el.first;
CPAnim &cpAnim = el.second;
Cu black{0, 0, 0, 255};
if (rotationModeActive) black = Cu{128, 128, 128, 255};
screenPainter.setColor(black);
float beginningThicknessMult = 2;
if (selectedPoints.find(cpId) != selectedPoints.end()) {
screenPainter.setThickness(3);
} else {
screenPainter.setThickness(1);
beginningThicknessMult = 4;
}
drawTrajectoriesAndKeyframes(cpAnim, beginningThicknessMult);
}
// draw control points trajectory of sync anim
if (displaySyncCPAnim) {
screenPainter.setColor(0, 255, 0, 255);
screenPainter.setThickness(1);
drawTrajectoriesAndKeyframes(cpAnimSync, 2);
}
}
void MainWindow::drawMessages(MyPainter &painter) {}
void MainWindow::pauseOrResumeZDeformation(bool pause) {}
void MainWindow::fingerEvent(const MyFingerEvent &event) {}
void MainWindow::fingerMoveEvent(const MyFingerEvent &event) {
if (manipulationMode.isGeometryModeActive()) {
defEng.solveForZ = false; // pause z-deformation
autoRotateDir = -1;
}
}
void MainWindow::fingerPressEvent(const MyFingerEvent &event) {
fingerMoveEvent(event);
}
void MainWindow::fingerReleaseEvent(const MyFingerEvent &event) {
if (touchPointId2CP.find(event.fingerId) != touchPointId2CP.end())
touchPointId2CP.erase(event.fingerId);
if (manipulationMode.isGeometryModeActive()) {
defEng.solveForZ = true; // resume z-deformation
autoRotateDir = 0;
}
}
void MainWindow::mouseEvent(const MyMouseEvent &event) {
if (event.leftButton || event.middleButton || event.rightButton)
repaint = true;
}
void MainWindow::mouseMoveEvent(const MyMouseEvent &event) {
mousePrevPos = mouseCurrPos;
mouseCurrPos = Vector2d(event.pos.x(), event.pos.y());
if (manipulationMode.isGeometryModeActive()) {
if (event.leftButton || event.middleButton || event.rightButton) {
defEng.solveForZ = false; // pause z-deformation
autoRotateDir = -1;
}
handleMouseMoveEventGeometryMode(event);
} else {
handleMouseMoveEventImageMode(event);
}
}
void MainWindow::mousePressEvent(const MyMouseEvent &event) {
mousePressStart = mousePrevPos = mouseCurrPos =
Vector2d(event.pos.x(), event.pos.y());
mousePressed = true;
if (manipulationMode.isGeometryModeActive()) {
defEng.solveForZ = false; // pause z-deformation
autoRotateDir = -1;
handleMousePressEventGeometryMode(event);
} else {
handleMousePressEventImageMode(event);
}
}
void MainWindow::mouseReleaseEvent(const MyMouseEvent &event) {
mousePrevPos = mouseCurrPos;
mouseReleaseEnd = mouseCurrPos = Vector2d(event.pos.x(), event.pos.y());
mousePressed = false;
if (manipulationMode.isGeometryModeActive()) {
defEng.solveForZ = true; // resume z-deformation
autoRotateDir = 0;
handleMouseReleaseEventGeometryMode(event);
} else {
handleMouseReleaseEventImageMode(event);
}
}
void MainWindow::keyEvent(const MyKeyEvent &keyEvent) { repaint = true; }
void MainWindow::keyPressEvent(const MyKeyEvent &keyEvent) {
#ifndef __EMSCRIPTEN__
if (keyEvent.key == SDLK_0) {
if (getAnimRecMode() == ANIM_MODE_TIME_SCALED) {
setAnimRecMode(ANIM_MODE_OVERWRITE);
} else {
setAnimRecMode(ANIM_MODE_TIME_SCALED);
}
}
if (keyEvent.key == SDLK_F1) {
showSegmentation = !showSegmentation;
}
if (keyEvent.key == SDLK_1) {
changeManipulationMode(DRAW_OUTLINE);
}
if (keyEvent.key == SDLK_2) {
changeManipulationMode(DEFORM_MODE);
}
if (keyEvent.key == SDLK_3) {
changeManipulationMode(ANIMATE_MODE);
}
if (keyEvent.key == SDLK_4) {
changeManipulationMode(REGION_SWAP_MODE);
}
if (keyEvent.key == SDLK_5) {
changeManipulationMode(REGION_MOVE_MODE);
}
if (keyEvent.key == SDLK_6) {
changeManipulationMode(REGION_REDRAW_MODE);
}
if (keyEvent.key == SDLK_e) {
cpRecordingRequestOrCancel();
}
if (keyEvent.key == SDLK_SPACE) {
toggleAnimationPlayback();
}
if (keyEvent.key == SDLK_n) {
reset();
}
if (keyEvent.key == SDLK_s) {
saveProject("/tmp/mm_project.zip");
}
if (keyEvent.key == SDLK_l) {
changeManipulationMode(DRAW_REGION);
openProject("/tmp/mm_project.zip");
}
if (keyEvent.key == SDLK_h) {
setCPsVisibility(!getCPsVisibility());
}
if (keyEvent.key == SDLK_j) {
setTemplateImageVisibility(!getTemplateImageVisibility());
}
if (keyEvent.key == SDLK_t) {
loadTemplateImageFromFile();
}
if (keyEvent.key == SDLK_b) {
loadBackgroundImageFromFile();
}
if (keyEvent.key == SDLK_o) {
defEng.solveForZ = !defEng.solveForZ;
}
if (keyEvent.key == SDLK_p) {
recData.armpitsStitching = !recData.armpitsStitching;
DEBUG_CMD_MM(cout << "recData.armpitsStitching: "
<< recData.armpitsStitching << endl;);
}
if (keyEvent.key == SDLK_w) {
// exportAsOBJ("/tmp", "mm_frame", true);
// writeOBJ("/tmp/mm_frame.obj", defData.VCurr, defData.Faces,
// defData.normals,
// defData.Faces, MatrixXd(), defData.Faces);
if (!exportAnimationRunning())
exportAnimationStart(0, false, false);
else
exportAnimationStop();
}
if (keyEvent.ctrlModifier) {
if (keyEvent.key == SDLK_c) {
// CTRL+C
copySelectedAnim();
}
if (keyEvent.key == SDLK_v) {
// CTRL+V
pasteSelectedAnim();
}
if (keyEvent.key == SDLK_a) {
// CTRL+A
selectAll();
}
}
if (keyEvent.key == SDLK_ESCAPE) {
deselectAll();
}
if (keyEvent.key == SDLK_PLUS || keyEvent.key == SDLK_EQUALS ||
keyEvent.key == SDLK_KP_PLUS) {
offsetSelectedCpAnimsByFrames(1);
}
if (keyEvent.key == SDLK_MINUS || keyEvent.key == SDLK_KP_MINUS) {
offsetSelectedCpAnimsByFrames(-1);
}
if (keyEvent.key == SDLK_DELETE || keyEvent.key == SDLK_BACKSPACE) {
removeControlPointOrRegion();
}
#endif
}
int MainWindow::selectLayerUnderCoords(int x, int y, bool nearest) {
// select the farthest/nearest region
int currSelectedLayer = -1;
const int layerGrayId =
nearest ? mergedRegionsImg(x, y, 0) : minRegionsImg(x, y, 0);
if (layerGrayId > 0) {
forlist(i, layerGrayIds) if (layerGrayIds[i] == layerGrayId)
currSelectedLayer = i;
DEBUG_CMD_MM(cout << "selected the " << (nearest ? "nearest" : "farthest")
<< " layer: selectedLayer=" << currSelectedLayer << endl;)
}
return currSelectedLayer;
}
void MainWindow::handleMousePressEventImageMode(const MyMouseEvent &event) {
auto &rightMouseButtonSimulation = *this->rightMouseButtonSimulation;
if (event.leftButton || event.rightButton || event.middleButton) {
drawLine(event, mousePrevPos(0), mousePrevPos(1), mouseCurrPos(0),
mouseCurrPos(1), 2 * circleRadius, paintColor);
}
if ((event.leftButton || event.rightButton) &&
(manipulationMode.mode == REGION_SWAP_MODE ||
manipulationMode.mode == REGION_MOVE_MODE)) {
const bool leftMouseButtonActive =
event.leftButton && !rightMouseButtonSimulation;
selectedLayer = selectLayerUnderCoords(mouseCurrPos.x(), mouseCurrPos.y(),
leftMouseButtonActive);
}
}
void MainWindow::handleMouseMoveEventImageMode(const MyMouseEvent &event) {
if (event.leftButton || event.rightButton || event.middleButton) {
// disable region modification (except in region redraw mode)
if (manipulationMode.mode != REGION_REDRAW_MODE &&
manipulationMode.mode != REGION_SWAP_MODE &&
manipulationMode.mode != REGION_MOVE_MODE && selectedLayer != -1) {
selectedLayers.clear();
selectedLayer = -1;
recreateMergedImgs();
}
drawLine(event, mousePrevPos(0), mousePrevPos(1), mouseCurrPos(0),
mouseCurrPos(1), 2 * circleRadius, paintColor);
}
}
void MainWindow::handleMouseReleaseEventImageMode(const MyMouseEvent &event) {
auto *imgData = &this->imgData;
auto ®ionImgs = imgData->regionImgs;
auto &outlineImgs = imgData->outlineImgs;
auto &layers = imgData->layers;
auto &currOutlineImg = imgData->currOutlineImg;
auto &selectedLayer = this->selectedLayer;
auto &layerGrayIds = imgData->layerGrayIds;
auto &rightMouseButtonSimulation = *this->rightMouseButtonSimulation;
const int selectedRegion = selectedLayer != -1 ? layers[selectedLayer] : -1;
const bool leftMouseButtonActive =
event.leftButton && !rightMouseButtonSimulation;
const bool rightMouseButtonActive =
event.rightButton || (event.leftButton && rightMouseButtonSimulation);
if (event.rightButton) {
drawLine(event, mousePrevPos(0), mousePrevPos(1), mouseCurrPos(0),
mouseCurrPos(1), 2 * circleRadius, paintColor);
}
bool finishedDrawing = true;
if (manipulationMode.isGeometryModeActive()) finishedDrawing = false;
// compute stroke length
const int minLength = 50;
int length = 0;
Imguc &Io = currOutlineImg;
fora(y, 0, Io.h) fora(x, 0, Io.w) {
if (Io(x, y, 0) != 255) length++;
if (length > minLength) break;
}
const bool shortClick =
event.pressReleaseDurationMs < minPressReleaseDurationMs;
const bool doubleClick = event.numClicks >= 2;
const bool shortStroke = length <= minLength;
// perform region move or swap
if (manipulationMode.mode == REGION_SWAP_MODE ||
manipulationMode.mode == REGION_MOVE_MODE) {
if (selectedLayer != -1) {
const int currLayer = selectLayerUnderCoords(
mouseReleaseEnd(0), mouseReleaseEnd(1), leftMouseButtonActive);
if (currLayer != -1 && currLayer != selectedLayer) {
if (manipulationMode.mode == REGION_SWAP_MODE) {
// swap regions
swap(layers[currLayer], layers[selectedLayer]);
} else {
// move selectedLayer in front of currLayer - NOT IMPLEMENTED!
}
}
}
selectedLayer = -1;
selectedLayers.clear();
finishedDrawing = false;
} else {
// region selection or duplication
const bool shiftInDrawMode =
manipulationMode.mode == DRAW_OUTLINE && event.shiftModifier;
if (shiftInDrawMode || (shortStroke && shortClick && !doubleClick)) {
// select the farthest/nearest region
if (event.leftButton || event.rightButton) {
const int selectedLayerCurr = selectLayerUnderCoords(
mouseReleaseEnd(0), mouseReleaseEnd(1), leftMouseButtonActive);
auto it = selectedLayers.find(selectedLayerCurr);
if (shiftInDrawMode && (it != selectedLayers.end())) {
// multiple selection active and the selected region is already in
// selection, remove it from the selection
selectedLayers.erase(it);
if (selectedLayers.empty()) {
selectedLayer = -1;
} else {
selectedLayer = *selectedLayers.begin();
}
} else {
selectedLayer = selectedLayerCurr;
// release mouse button outside of any region (or multiple selection
// not active), deselect all layers
if (selectedLayerCurr == -1 || !shiftInDrawMode)
selectedLayers.clear();
if (selectedLayerCurr != -1) selectedLayers.insert(selectedLayer);
}
finishedDrawing = false;
}
} else if (event.ctrlModifier ||
(shortStroke && shortClick && doubleClick)) {
// duplicate region and add it under/above everything drawn so far
if (event.leftButton || event.rightButton) {
const bool under = leftMouseButtonActive;
const int selectedLayerCurr = selectLayerUnderCoords(
mouseReleaseEnd(0), mouseReleaseEnd(1), leftMouseButtonActive);
if (selectedLayerCurr != -1) {
const int regId = layers[selectedLayerCurr];
const Imguc &Ir = regionImgs[regId];
int regIdDup = -1;
forlist(i,
regionImgs) if (i != regId && Ir.equalData(regionImgs[i])) {
regIdDup = i;
break;
}
bool exists = regIdDup != -1;
if (exists) {
// region already has a duplicate, remove the farthest/nearest one
const int regIdErase = regIdDup;
outlineImgs[regIdErase].setNull();
regionImgs[regIdErase].setNull();
for (auto it = layers.begin(); it != layers.end(); it++) {
if (*it == regIdErase) {
layers.erase(it);
break;
}
}
DEBUG_CMD_MM(cout << "duplicate already exists, removing the "
<< (under ? "farthest" : "nearest") << " one"
<< endl;)
} else {
// region does not have a duplicate yet, duplicate it and move it
// under/above everything drawn so far
outlineImgs.push_back(outlineImgs[regId]);
regionImgs.push_back(regionImgs[regId]);
const int lastRegionId = regionImgs.size() - 1;
if (under) {
layers.push_front(lastRegionId);
} else {
layers.push_back(lastRegionId);
}
DEBUG_CMD_MM(cout << "adding a duplicate of region " << regId << " "
<< (under ? "under" : "above")
<< " everything drawn so far" << endl;)
}
}
selectedLayer = -1;
selectedLayers.clear();
}
finishedDrawing = false;
}
}
if (shortClick) finishedDrawing = false;
if (finishedDrawing) {
const bool regionModify = selectedLayer != -1;
const bool eraseMode = regionModify &&
manipulationMode.mode == DRAW_REGION &&
leftMouseButtonActive;
const bool weightsMode = regionModify &&
manipulationMode.mode == DRAW_REGION &&
rightMouseButtonActive;
const bool regionModifyRedraw =
regionModify && manipulationMode.mode == REGION_REDRAW_MODE;
if (event.leftButton || event.rightButton) {
// create a region from the outline image
Imguc *Io = &currOutlineImg;
Imguc *Ir = nullptr;
const int w = Io->w, h = Io->h;
// check if the current outline is long enough to prevent from crashing at
// later steps
if (shortStroke) {
DEBUG_CMD_MM(cout << "length of outline < " << minLength << ", skipping"
<< endl;)
} else {
bool createOutlines = manipulationMode.mode == DRAW_REGION_OUTLINE;
bool createRegions =
manipulationMode.mode == DRAW_OUTLINE || regionModify;
bool closeDrawnShape = false;
if (weightsMode) {
createRegions = createOutlines = false;
} else if (regionModifyRedraw) {
DEBUG_CMD_MM(cout << "region modification (redraw)" << endl;)
// replace the outline of the selected region with the newly drawn one
Ir = ®ionImgs[selectedRegion];
Imguc &I = outlineImgs[selectedRegion];
I = *Io;
*Ir = *Io;
Io = &I;
closeDrawnShape = true;
} else if (regionModify || eraseMode) {
// modifying a selected region
Ir = ®ionImgs[selectedRegion];
// compose drawn outline image with the selected one
Imguc &I = outlineImgs[selectedRegion];
fora(y, 0, I.h) fora(x, 0, I.w) {
if ((*Io)(x, y, 0) == 0)
I(x, y, 0) = 0;
else if ((*Io)(x, y, 0) == ERASE_PIXEL_COLOR) {
if (manipulationMode.mode == OUTLINE_RECOLOR &&
I(x, y, 0) != 255) {
if (leftMouseButtonActive)
I(x, y, 0) = 0;
else if (rightMouseButtonActive)
I(x, y, 0) = NEUMANN_OUTLINE_PIXEL_COLOR;
} else if (eraseMode)
I(x, y, 0) = 255;
}
if ((*Io)(x, y, 0) == NEUMANN_OUTLINE_PIXEL_COLOR) {
(*Ir)(x, y, 0) = 0;
I(x, y, 0) = NEUMANN_OUTLINE_PIXEL_COLOR;
} else {
(*Ir)(x, y, 0) = I(x, y, 0);
}
}
Io = &I;
} else if (createOutlines || createRegions) {
// insert a new layer under the layer specified using
// drawingUnderLayer
regionImgs.push_back(*Io);
outlineImgs.push_back(*Io);
Ir = ®ionImgs.back();
Io = &outlineImgs.back();
const int lastRegionId = regionImgs.size() - 1;
if (drawingUnderLayer != numeric_limits<int>::max()) {
int underId = 0;
forlist(i, layerGrayIds) if (layerGrayIds[i] == drawingUnderLayer)
underId = i;
const auto &pos = layers.begin() + underId;
layers.insert(pos, lastRegionId);
} else {
layers.push_back(lastRegionId);
}
if (createRegions) closeDrawnShape = true;
}
if (closeDrawnShape) {
// close the drawn shape
Imguc tmp;
tmp.initImage(*Io);
tmp.fill(255);
MyPainter painter(tmp);
painter.setColor(NEUMANN_OUTLINE_PIXEL_COLOR,
NEUMANN_OUTLINE_PIXEL_COLOR,
NEUMANN_OUTLINE_PIXEL_COLOR, 255);
painter.drawLine(mousePressStart(0), mousePressStart(1),
mouseReleaseEnd(0), mouseReleaseEnd(1),
defaultThickness);
fora(y, 0, h)
fora(x, 0, w) if ((*Io)(x, y, 0) == 255) (*Io)(x, y, 0) =
tmp(x, y, 0); // put neumann outline behind regular one
*Ir = *Io;
}
if (createRegions) {
// if drawing outlines, fill the drawn shape
// convert the shape to a region by filling the outside and recoloring
// the remaining shape to have the same color (black)
floodFill(*Ir, 0, 0, 255, 128);
fora(y, 0, h) fora(x, 0, w) (*Ir)(x, y, 0) =
(*Ir)(x, y, 0) == 128 ? 0 : 255;
} else if (createOutlines) {
// if drawing regions, create outline image by tracing the drawn black
// region
Io->fill(255);
Imguc M;
M.initImage(*Io);
M.clear();
Ir->invert(255); // convert black regions to white, white background
// to black
// find the first background pixel and use flood fill to add
// background to the mask image
int startX = -1, startY = -1;
fora(y, 0, M.h) fora(x, 0, M.w) if ((*Ir)(x, y, 0) == 0) {
startX = x;
startY = y;
goto EXIT;
}
EXIT:;
floodFill(*Ir, M, startX, startY, 0, 255);
auto bndVis = [&](const int x, const int y) {
const int N = 1;
fora(i, -N, N + 1)
fora(j, -N, N + 1) if (Io->checkBounds(x + i, y + j, 0)) (*Io)(
x + i, y + j, 0) = 0;
};
while (traceRegion(M, bndVis, startX, startY)) {
// if the region is composed of several separated components, find
// one, remove it, repeat
const int &color = (*Ir)(startX, startY, 0);
floodFill(*Ir, M, startX, startY, color, 255);
}
}
}
}
}
// merge all regions into a single image (for displaying it)
recreateMergedImgs();
// clear the outline image
currOutlineImg.fill(255);
}
void MainWindow::handleMousePressEventGeometryMode(const MyMouseEvent &event) {
auto *cpData = &this->cpData;
auto *defData = &this->defData;
auto &selectedPoint = cpData->selectedPoint;
auto &selectedPoints = cpData->selectedPoints;
auto &def = defData->def;
auto &VCurr = defData->VCurr;
auto &Faces = defData->Faces;
auto &rightMouseButtonSimulation = *this->rightMouseButtonSimulation;
const bool leftMouseButtonActive =
event.leftButton && !rightMouseButtonSimulation;
const bool rightMouseButtonActive =
event.rightButton || (event.leftButton && rightMouseButtonSimulation);
if (!(VCurr.size() > 0 && proj3DView.size() > 0)) return;
const int radius = 60;
if (event.middleButton ||
(middleMouseSimulation && (event.leftButton || event.rightButton))) {
rotationModeActive = true;
forceRecomputeCameraCenter = true;
rubberBandActive = false;
return;
}
if (manipulationMode.mode == DEFORM_MODE) {
if (event.leftButton || event.rightButton) {
bool reverse = true;
if (leftMouseButtonActive) reverse = false;
bool added = defDeformMode.addControlPointOnFace(
VCurr, Faces, mouseCurrPos(0), mouseCurrPos(1), radius, reverse,
reverse, selectedPoint, proj3DView);
if (selectedPoint != -1) {
selectedPoints.insert(selectedPoint);
}
}
return;
}
if (transformRelative) {
if (event.leftButton)
transformApply();
else
transformDiscard();
return;
}
if (event.leftButton || event.rightButton) {
bool reverse = true;
if (leftMouseButtonActive) reverse = false;
bool added = def.addControlPointOnFace(VCurr, Faces, mouseCurrPos(0),
mouseCurrPos(1), radius, reverse,
reverse, selectedPoint, proj3DView);
temporaryPoint = false;
if (selectedPoint != -1) {
if (!event.shiftModifier) {
if (selectedPoints.find(selectedPoint) == selectedPoints.end())
selectedPoints.clear();
if (added) {
// temporaryPoint = true;
temporaryPoint = false;
}
} else {
// DISABLED: When adding a new permanent control point (using
// Ctrl+LMB/RMB), add it to the current control point selection, i.e.
// disable this: if (added & selectedPoints.find(selectedPoint) ==
// selectedPoints.end()) selectedPoints.clear();
if (added & selectedPoints.find(selectedPoint) == selectedPoints.end())
selectedPoints.clear();
}
if (!added && event.shiftModifier &&
selectedPoints.find(selectedPoint) != selectedPoints.end()) {
selectedPoints.erase(selectedPoint);
if (selectedPoints.empty()) selectedPoint = -1;
} else {
selectedPoints.insert(selectedPoint);
}
}
if (selectedPoint == -1) {
if (!event.shiftModifier) selectedPoints.clear();
rubberBandActive = true;
}
}
}
void MainWindow::handleMouseMoveEventGeometryMode(const MyMouseEvent &event) {
auto *cpData = &this->cpData;
auto *defData = &this->defData;
auto &selectedPoint = cpData->selectedPoint;
auto &selectedPoints = cpData->selectedPoints;
auto &recordCP = cpData->recordCP;
auto &recordCPActive = cpData->recordCPActive;
auto &cpsAnim = cpData->cpsAnim;
auto &recordCPWaitForClick = cpData->recordCPWaitForClick;
auto *defCurr = &def;
if (manipulationMode.mode == DEFORM_MODE) defCurr = &defDeformMode;
if (event.middleButton ||
(middleMouseSimulation && (event.leftButton || event.rightButton))) {
rotationModeActive = true;
if (!event.shiftModifier) {
const Vector2d r = rotPrev + rotFactor * (mouseCurrPos - mousePressStart);
rotHor = r(0);
rotVer = r(1);
} else {
// Shift+MiddleMouseButton pressed
translateView =
transPrev + translateViewFactor * (mouseCurrPos - mousePressStart);
}
return;
}
// if recording has been requested after clicking on a control point, start
// recording
if ((event.leftButton || event.rightButton) && recordCPWaitForClick &&
!recordCP && selectedPoint != -1) {
setRecordingCP(true);
}
if (!recordCP && recordCPActive) return;
if (transformRelative) {
#if 0
handleRelativeTransformation();
#endif
return;
}
if (selectedPoint == -1) return;
// Translation of selected control points and their animations (by dragging
// only - relative transformation is handled in handleRelativeTransformation).
Vector2d startPos;
if (event.leftButton || event.rightButton) {
startPos = mousePressStart;
} else {
return;
}
// compute translation vector (based on a single control point)
try {
auto &cpFirst = defCurr->getCP(*selectedPoints.begin());
const Vector3d cpProj =
(proj3DView * cpFirst.prevPos.homogeneous()).hnormalized();
const Vector3d mouseCurrProj(mouseCurrPos(0), mouseCurrPos(1), cpProj(2));
const Vector3d startPosProj(startPos(0), startPos(1), cpProj(2));
const Vector3d t =
(proj3DViewInv * mouseCurrProj.homogeneous()).hnormalized() -
(proj3DViewInv * startPosProj.homogeneous()).hnormalized();
// apply the translation vector to all selected control points
for (const int cpId : selectedPoints) {
auto &cp = defCurr->getCP(cpId);
const auto &it = cpsAnim.find(cpId);
if (it != cpsAnim.end() && !recordCP) {
auto &cpAnim = it->second;
Affine3d T((Translation3d(t(0), t(1), t(2))));
cpAnim.setTransform(T.matrix());
cp.pos = cpAnim.peek();
} else {
cp.pos = cp.prevPos + t;
}
}
} catch (out_of_range &e) {
cerr << e.what() << endl;
}
}
void MainWindow::handleMouseReleaseEventGeometryMode(
const MyMouseEvent &event) {
auto *cpData = &this->cpData;
auto *defData = &this->defData;
auto &selectedPoint = cpData->selectedPoint;
auto &selectedPoints = cpData->selectedPoints;
auto &recordCPActive = cpData->recordCPActive;
auto &defEng = defData->defEng;
auto &mesh = defData->mesh;
auto &verticesOfParts = defData->verticesOfParts;
auto &VCurr = defData->VCurr;
auto &Faces = defData->Faces;
auto &rightMouseButtonSimulation = *this->rightMouseButtonSimulation;
auto &recordCPWaitForClick = cpData->recordCPWaitForClick;
const bool leftMouseButtonActive =
event.leftButton && !rightMouseButtonSimulation;
const bool rightMouseButtonActive =
event.rightButton || (event.leftButton && rightMouseButtonSimulation);
if (event.middleButton ||
(middleMouseSimulation && (event.leftButton || event.rightButton))) {
if (!event.shiftModifier) {
rotPrev += rotFactor * (mouseCurrPos - mousePressStart);
} else {
// Shift+MiddleMouseButton pressed
transPrev += translateViewFactor * (mouseCurrPos - mousePressStart);
}
if (!middleMouseSimulation) {
rotationModeActive = false;
}
// middleMouseSimulation = false;
return;
}
if (manipulationMode.mode == DEFORM_MODE) {
defDeformMode.removeControlPoints();
selectedPoints.clear();
selectedPoint = -1;
return;
}
if (recordCPActive) {
recordCPActive = false;
// always stop recording CP after releasing the button
setRecordingCP(false);
recordCPWaitForClick = false; // also stop recording mode
#ifdef __EMSCRIPTEN__
EM_ASM(js_recordingModeStopped(););
#endif
return;
}
if (transformRelative) {
if (event.leftButton)
transformApply();
else
transformDiscard();
return;
}
transformApply();
if (rubberBandActive) {
// select points inside the rubber band
double x1 = mousePressStart(0);
double y1 = mousePressStart(1);
double x2 = mouseReleaseEnd(0);
double y2 = mouseReleaseEnd(1);
if (x1 > x2) swap(x1, x2);
if (y1 > y2) swap(y1, y2);
const vector<int> &sel =
def.getControlPointsInsideRect(x1, y1, x2, y2, proj3DView);
if (!event.shiftModifier) selectedPoints.clear();
for (const int id : sel) selectedPoints.insert(id);
if (!selectedPoints.empty())
selectedPoint = *selectedPoints.begin();
else
selectedPoint = -1;
rubberBandActive = false;
return;
}
if (!event.shiftModifier && (event.leftButton || event.rightButton)) {
if (temporaryPoint) {
def.removeLastControlPoint();
selectedPoints.clear();
selectedPoint = -1;
}
}
}
void MainWindow::drawLine(const MyMouseEvent &event, int x1, int y1, int x2,
int y2, int thickness, const Cu &color) {
auto imgData = &this->imgData;
auto &minRegionsImg = imgData->minRegionsImg;
auto &currOutlineImg = imgData->currOutlineImg;
auto &selectedLayer = this->selectedLayer;
auto &mergedRegionsImg = imgData->mergedRegionsImg;
auto &mergedOutlinesImg = imgData->mergedOutlinesImg;
auto &rightMouseButtonSimulation = *this->rightMouseButtonSimulation;
if (event.shiftModifier) return;
if (event.ctrlModifier) return;
if (manipulationMode.isGeometryModeActive()) return;
if (manipulationMode.mode == REGION_SWAP_MODE ||
manipulationMode.mode == REGION_MOVE_MODE)
return;
if (manipulationMode.mode == REGION_REDRAW_MODE && selectedLayer == -1)
return;
const bool leftMouseButtonActive =
event.leftButton && !rightMouseButtonSimulation;
const bool rightMouseButtonActive =
event.rightButton || (event.leftButton && rightMouseButtonSimulation);
const bool regionModify = false; // disable original region modification
const bool eraseMode = regionModify && manipulationMode.mode == DRAW_REGION &&
leftMouseButtonActive;
const bool neumannOutline = regionModify &&
manipulationMode.mode == DRAW_OUTLINE &&
rightMouseButtonActive;
const bool outlineRecolorMode =
regionModify && manipulationMode.mode == OUTLINE_RECOLOR;
// override the thickness if outline drawing mode is selected
if (manipulationMode.mode == DRAW_OUTLINE ||
manipulationMode.mode == REGION_REDRAW_MODE)
thickness = defaultThickness;
Cu c = color;
if (neumannOutline)
c = Cu{NEUMANN_OUTLINE_PIXEL_COLOR, NEUMANN_OUTLINE_PIXEL_COLOR,
NEUMANN_OUTLINE_PIXEL_COLOR, 255};
else if (eraseMode || outlineRecolorMode)
c = Cu{ERASE_PIXEL_COLOR, ERASE_PIXEL_COLOR, ERASE_PIXEL_COLOR, 255};
MyPainter painter(currOutlineImg);
painter.setColor(c(0), c(1), c(2), c(3));
painter.drawLine(x1, y1, x2, y2, thickness);
drawingUnderLayer = numeric_limits<int>::max();
Imguc &I = currOutlineImg, &MI = mergedOutlinesImg;
if (neumannOutline) {
fora(y, 0, I.h)
fora(x, 0, I.w) if (I(x, y, 0) == NEUMANN_OUTLINE_PIXEL_COLOR) {
MI(x, y, 1) = 255;
MI(x, y, 2) = MI(x, y, 0) = 0;
MI.alpha(x, y) = 255; // green
}
} else if (eraseMode) {
fora(y, 0, I.h) fora(x, 0, I.w) if (I(x, y, 0) == ERASE_PIXEL_COLOR) {
MI.alpha(x, y) = 0;
}
} else if (outlineRecolorMode) {
} else if (leftMouseButtonActive) {
// compose current outline image on top of merged outlines image
fora(y, 0, I.h) fora(x, 0, I.w) if (I(x, y, 0) == 0) {
MI(x, y, 2) = MI(x, y, 1) = MI(x, y, 0) = 0;
MI.alpha(x, y) = 255;
}
} else if (rightMouseButtonActive) {
// When drawing under already drawn regions, change pen color and also
// identify the backmost region.
Imguc &Mr = mergedRegionsImg, &Mm = minRegionsImg;
fora(y, 0, I.h) fora(x, 0, I.w) {
if (I(x, y, 0) == 0) {
if (Mm(x, y, 0) > 0 && Mm(x, y, 0) < drawingUnderLayer)
drawingUnderLayer = Mm(x, y, 0);
MI(x, y, 0) = Mm(x, y, 0) > 0 ? 220 : 0;
MI(x, y, 2) = MI(x, y, 1) = MI(x, y, 0);
MI.alpha(x, y) = 255;
}
}
}
}
void MainWindow::drawImageMode(MyPainter &painter, MyPainter &painterOther,
double alpha) {
auto *imgData = &this->imgData;
auto &mergedRegionsImg = imgData->mergedRegionsImg;
auto &mergedOutlinesImg = imgData->mergedOutlinesImg;
auto &layers = imgData->layers;
auto &selectedLayer = this->selectedLayer;
auto &showTemplateImg = shadingOpts.showTemplateImg;
// rasterize mesh
painter.drawImage(0, 0, mergedRegionsOneColorImg, alpha);
// show template image (used as a guide for tracing)
if (showTemplateImg && !templateImg.isNull()) {
painter.drawImage(0, 0, templateImg, alpha * 0.5);
}
// display segmented (depth) image
if (showSegmentation) {
fora(y, 0, viewportH) fora(x, 0, viewportW) {
unsigned char alpha = 255;
if (mergedRegionsImg(x, y, 0) == 0) alpha = 0;
mergedRegionsImg(x, y, 3) = alpha;
}
painter.drawImage(0, 0, mergedRegionsImg, alpha);
}
// display outlines
painter.drawImage(0, 0, mergedOutlinesImg, alpha);
if ((manipulationMode.mode == REGION_SWAP_MODE ||
manipulationMode.mode == REGION_MOVE_MODE) &&
selectedLayer != -1) {
painterOther.setColor(0, 255, 0, 255);
const bool headStart = manipulationMode.mode == REGION_SWAP_MODE;
painterOther.drawArrow(mousePressStart.x(), mousePressStart.y(),
mouseCurrPos.x(), mouseCurrPos.y(), 10, 30, 3, true,
headStart);
}
}
// START OF IMAGE LAYERS
void MainWindow::initImageLayers() {
currOutlineImg = Imguc(viewportW, viewportH, 1);
mergedRegionsImg = Imguc(viewportW, viewportH, 4, 3);
mergedRegionsOneColorImg = Imguc(viewportW, viewportH, 4, 3);
mergedOutlinesImg = Imguc(viewportW, viewportH, 4, 3);
minRegionsImg.initImage(currOutlineImg);
clearImgs();
}
void MainWindow::clearImgs() {
currOutlineImg.fill(255);
outlineImgs.clear();
regionImgs.clear();
layers.clear();
mergedRegionsImg.fill(Cu{0, 0, 0, 255});
mergedRegionsOneColorImg.fill(0);
mergedOutlinesImg.fill(0);
minRegionsImg.clear();
repaint = true;
}
void MainWindow::recreateMergedImgs() {
Imguc &Mr = mergedRegionsImg, &Mo = mergedOutlinesImg, &Mm = minRegionsImg;
Mr.fill(Cu{0, 0, 0, 255});
/*Mr.clear();*/ Mo.fill(0);
Mm.clear();
const int w = Mr.w, h = Mr.h;
const int N = layers.size();
layerGrayIds.clear();
fora(i, 0, N) {
const int regId = layers[i];
const int n = (i + 1) / (float)N * 255;
layerGrayIds.push_back(n);
Imguc &IrCurr = regionImgs[regId];
Imguc &IoCurr = outlineImgs[regId];
const bool selected = selectedLayers.find(i) != selectedLayers.end();
fora(y, 0, h) fora(x, 0, w) {
if (IrCurr(x, y, 0) == 255) { // we're inside a region
fora(c, 0, 3) Mr(x, y, c) = n;
if (Mo.alpha(x, y) != 0) fora(c, 0, 3) {
// light outlines
int v = Mo(x, y, c);
if (v == 0) v += 220;
Mo(x, y, c) = v;
}
if (Mm(x, y, 0) == 0 || Mm(x, y, 0) > n) Mm(x, y, 0) = n;
}
if (IoCurr(x, y, 0) != 255) { // we're inside a stroke
if (IoCurr(x, y, 0) == NEUMANN_OUTLINE_PIXEL_COLOR) {
if ((showNeumannOutlines || selected)) {
Mo(x, y, 1) = 255;
Mo(x, y, 0) = Mo(x, y, 2) = 0;
Mo.alpha(x, y) = 255;
}
} else {
if (selected) {
Mo(x, y, 2) = 255;
Mo(x, y, 0) = Mo(x, y, 1) = 0;
Mo.alpha(x, y) = 255;
} else if (!showSelectedRegionOnly) {
if (Mo.alpha(x, y) != 0) {
if (!hideRedAnnotations)
Mo(x, y, 0) = 255;
else
Mo(x, y, 0) = 0;
Mo(x, y, 2) = Mo(x, y, 1) = 0;
} else {
Mo(x, y, 0) = Mo(x, y, 2) = Mo(x, y, 1) = 0;
}
Mo.alpha(x, y) = 255;
}
}
}
if (IrCurr(x, y, 0) == 255) { // we're inside a region
}
}
}
// create a one color region layer that will be placed under outline image to
// better convey the regions
mergedRegionsOneColorImg.fill(0);
fora(y, 0, h) fora(x, 0, w) {
if (Mr(x, y, 0) > 0) {
fora(c, 0, 4) mergedRegionsOneColorImg(x, y, c) = 255;
}
}
repaint = true;
}
void MainWindow::reset() {
// reset image data
clearImgs();
selectedLayer = -1;
selectedLayers.clear();
templateImg.setNull();
backgroundImg.setNull();
showModel = false;
// reset reconstruction data
recData = RecData();
// reset shading options
shadingOpts = ShadingOptions();
// reset control points
cpData = CPData();
cpDataBackup = CPData();
// reset deformation
defData = DefData();
// reset camera
camData = CameraData();
translateCam = Eigen::Vector3d::Zero();
rotateCam = Eigen::Vector3d::Zero();
cameraTransforms.clear();
forceRecomputeCameraCenter = true;
enableMiddleMouseSimulation(false);
// change manipulation mode to default
manipulationMode = DRAW_OUTLINE;
repaint = true;
}
void MainWindow::changeManipulationMode(
const ManipulationMode &manipulationMode, bool saveCPs) {
ManipulationMode prevMode = this->manipulationMode;
this->manipulationMode = manipulationMode;
// do not proceed if switching to the same mode
if (prevMode.mode == manipulationMode.mode) {
return;
}
DEBUG_CMD_MM(cout << "changeManipulationMode: " << prevMode.mode << " -> "
<< manipulationMode.mode << endl;);
// going from DEFORM_MODE
if (prevMode.mode == DEFORM_MODE && manipulationMode.mode != DEFORM_MODE) {
DEBUG_CMD_MM(cout << "restoring data from backup" << endl;);
// restore cpData
bool showControlPointsPrev = cpData.showControlPoints;
cpData = cpDataBackup;
cpData.showControlPoints = showControlPointsPrev;
}
// going from image to geometry mode
if (prevMode.isImageModeActive() && manipulationMode.isGeometryModeActive()) {
progressMessage = "Reconstruction running";
if (performReconstruction(recData, defData, cpData, imgData)) {
progressMessage = "";
// reset camera matrix (needed for proper transitions)
proj3DView = proj3DViewInv = Matrix4d::Identity();
} else {
progressMessage = "Reconstruction failed";
changeManipulationMode(DRAW_OUTLINE);
#ifdef __EMSCRIPTEN__
EM_ASM(js_reconstructionFailed(););
#endif
return;
}
#ifdef __EMSCRIPTEN__
EM_ASM(js_reconstructionFinished(););
#endif
}
// going from geometry to image mode
if (prevMode.isGeometryModeActive() && manipulationMode.isImageModeActive()) {
if (saveCPs) {
// save control points and their animations
ostringstream oss;
saveControlPointsToStream(oss, cpData, defData, imgData);
savedCPs = oss.str();
}
recreateMergedImgs();
}
// staying in geometry mode
if (prevMode.isGeometryModeActive() &&
manipulationMode.isGeometryModeActive()) {
}
// going to DEFORM_MODE
if (prevMode.mode != DEFORM_MODE && manipulationMode.mode == DEFORM_MODE) {
DEBUG_CMD_MM(cout << "making data backup" << endl;);
// make backup of cpData and clear it
cpDataBackup = cpData;
bool showControlPointsPrev = cpData.showControlPoints;
cpData = CPData();
cpData.showControlPoints = showControlPointsPrev;
defEng.solveForZ = true; // resume z-deformation
}
// going to REGION_REDRAW_MODE
if (manipulationMode.mode == REGION_REDRAW_MODE) {
if (selectedLayer != -1 && selectedLayers.size() > 1) {
// only single selected region is allowed in REGION_REDRAW_MODE
selectedLayers.clear();
selectedLayers.insert(selectedLayer);
recreateMergedImgs();
}
}
startModeTransition(prevMode, manipulationMode);
repaint = true;
}
void MainWindow::transformEnd(bool apply) {
auto *cpData = &this->cpData;
auto *defData = &this->defData;
auto &selectedPoint = cpData->selectedPoint;
auto &selectedPoints = cpData->selectedPoints;
auto &cpsAnim = cpData->cpsAnim;
auto &def = defData->def;
auto &VCurr = defData->VCurr;
if (selectedPoint == -1) return;
for (int cpId : selectedPoints) {
try {
auto &cp = def.getCP(cpId);
if (apply) {
cp.pos.z() =
VCurr.row(cp.ptId).z(); // don't allow z-translation: update
// z-coordinate of control point by
// z-coordinate of corresponding mesh point
cp.prevPos = cp.pos; // apply
} else
cp.pos = cp.prevPos; // discard
const auto &it = cpsAnim.find(cpId);
if (it != cpsAnim.end()) {
auto &cpAnim = it->second;
if (apply) {
// don't allow z-translation: update z-coordinate of control point by
// z-coordinate of corresponding mesh point
MatrixXd &T = cpAnim.getTransform();
T(2, 3) = 0;
cpAnim.applyTransform(); // apply
} else
cpAnim.setTransform(Matrix4d::Identity()); // discard
}
} catch (out_of_range &e) {
cerr << e.what() << endl;
}
}
transformRelative = false;
repaint = true;
}
void MainWindow::transformApply() { transformEnd(true); }
void MainWindow::transformDiscard() { transformEnd(false); }
void MainWindow::removeControlPointOrRegion() {
if (manipulationMode.isGeometryModeActive()) {
// if there are CP animations, remove them only; remove control points
// otherwise
if (!removeCPAnims()) removeControlPoints();
} else {
if (!removeSelectedLayers()) {
removeLastRegion();
}
recreateMergedImgs();
}
repaint = true;
}
void MainWindow::removeControlPoints() {
auto &selectedPoints = this->cpData.selectedPoints;
auto &selectedPoint = this->cpData.selectedPoint;
auto &cpsAnim = this->cpData.cpsAnim;
auto &cpsAnimSyncId = this->cpData.cpsAnimSyncId;
// remove selected control points and their animations
selectedPoint = -1;
for (auto it = selectedPoints.begin(); it != selectedPoints.end();) {
const int cpId = *it;
it = selectedPoints.erase(it);
def.removeControlPoint(cpId);
cpsAnim.erase(cpId);
if (cpId == cpsAnimSyncId) cpsAnimSyncId = -1;
}
repaint = true;
}
bool MainWindow::removeSelectedLayers() {
if (selectedLayer == -1) return false;
vector<int> regIds;
for (int layerId : selectedLayers) {
const int regId =
layerId >= 0 && layerId < layers.size() ? layers[layerId] : -1;
if (regId != -1) regIds.push_back(regId);
}
for (int regId : regIds) {
removeRegion(regId);
}
selectedLayer = -1;
selectedLayers.clear();
return true;
}
void MainWindow::removeLastRegion() {
// find last region
int regId = -1;
for (int i = outlineImgs.size() - 1; i >= 0; i--) {
if (!outlineImgs[i].isNull()) {
regId = i;
break;
}
}
if (regId == -1) return;
removeRegion(regId);
}
void MainWindow::removeRegion(int regId) {
if (!(regId >= 0 && regId < regionImgs.size())) return;
DEBUG_CMD_MM(cout << "removing region; " << regId << endl;)
outlineImgs[regId].setNull();
regionImgs[regId].setNull();
for (auto it = layers.begin(); it != layers.end(); it++) {
if (*it == regId) {
layers.erase(it);
break;
}
}
}
void MainWindow::selectAllRegions() {
forlist(i, layers) selectedLayers.insert(i);
if (!layers.empty()) selectedLayer = layers[0];
if (manipulationMode.isImageModeActive()) recreateMergedImgs();
repaint = true;
}
void MainWindow::deselectAllRegions() {
selectedLayer = -1;
selectedLayers.clear();
if (manipulationMode.isImageModeActive()) recreateMergedImgs();
repaint = true;
}
void MainWindow::deselectAll() {
deselectAllControlPoints();
deselectAllRegions();
repaint = true;
}
void MainWindow::deselectAllControlPoints() {
if (transformRelative)
transformDiscard();
else
selectedPoints.clear();
repaint = true;
}
void MainWindow::selectAll() {
if (manipulationMode.isImageModeActive()) selectAllRegions();
if (manipulationMode.isGeometryModeActive()) selectAllControlPoints();
repaint = true;
}
void MainWindow::selectAllControlPoints() {
auto &selectedPoints = this->cpData.selectedPoints;
auto &selectedPoint = this->cpData.selectedPoint;
selectedPoints.clear();
for (const auto &it : def.getCPs()) selectedPoints.insert(it.first);
selectedPoint = *selectedPoints.begin();
repaint = true;
}
template <typename T>
void computeScaledImage(const T targetW, const T targetH, T &newW, T &newH,
T &shiftX, T &shiftY) {
const float r = newW / static_cast<float>(newH);
// scale up
newW = targetW;
newH = 1.f / r * newW;
// scale down
if (newH > targetH) {
newH = targetH;
newW = r * newH;
}
shiftX = 0, shiftY = 0;
if (newW < targetW) {
shiftX = 0.5 * (targetW - newW);
}
if (newH < targetH) {
shiftY = 0.5 * (targetH - newH);
}
}
void MainWindow::loadTemplateImageFromFile(bool scale) {
Imguc tmp = Imguc::loadImage("/tmp/template.img", 3, 4);
DEBUG_CMD_MM(cout << "loadTemplateImageFromFile: " << tmp << endl;);
if (!tmp.isNull() && tmp.w > 0 && tmp.h > 0) {
if (scale) {
int newW = tmp.w, newH = tmp.h;
int shiftX = 0, shiftY = 0;
computeScaledImage(viewportW, viewportH, newW, newH, shiftX, shiftY);
templateImg.setNull() =
tmp.scale(newW, newH)
.resize(windowWidth, windowHeight, shiftX, shiftY, Cu{255});
} else {
templateImg.setNull() =
tmp.resize(windowWidth, windowHeight, 0, 0, Cu{255});
}
loadTextureToGPU(templateImg, glData.templateImgTexName);
shadingOpts.showTemplateImg = true;
shadingOpts.showTexture = true;
}
repaint = true;
}
void MainWindow::loadBackgroundImageFromFile(bool scale) {
Imguc tmp = Imguc::loadImage("/tmp/bg.img", 3, 4);
DEBUG_CMD_MM(cout << "loadBackgroundImageFromFile: " << tmp << endl;);
if (!tmp.isNull() && tmp.w > 0 && tmp.h > 0) {
if (scale) {
int newW = tmp.w, newH = tmp.h;
int shiftX = 0, shiftY = 0;
computeScaledImage(viewportW, viewportH, newW, newH, shiftX, shiftY);
backgroundImg.setNull() =
tmp.scale(newW, newH)
.resize(windowWidth, windowHeight, shiftX, shiftY, Cu{255});
} else {
backgroundImg.setNull() =
tmp.resize(windowWidth, windowHeight, 0, 0, Cu{255});
}
loadTextureToGPU(backgroundImg, glData.backgroundImgTexName);
shadingOpts.showBackgroundImg = true;
}
repaint = true;
}
// START OF ANIMATION
void MainWindow::cpRecordingRequestOrCancel() {
cpData.recordCPWaitForClick = !cpData.recordCPWaitForClick;
if (cpData.recordCPWaitForClick) {
DEBUG_CMD_MM(
cout << "CP recording requested, waiting for click on a control point"
<< endl;)
} else {
DEBUG_CMD_MM(cout << "CP recording request canceled" << endl;)
// if recording, stop it
if (cpData.recordCP) {
setRecordingCP(false);
cpData.recordCPWaitForClick = false;
}
}
}
void MainWindow::setRecordingCP(bool active) {
auto &selectedPoints = this->cpData.selectedPoints;
auto &cpsAnim = this->cpData.cpsAnim;
auto &recordCP = this->cpData.recordCP;
auto &recordCPActive = this->cpData.recordCPActive;
auto &animMode = cpData.animMode;
recordCP = active;
for (int i : selectedPoints) {
const auto &it = cpsAnim.find(i);
if (it == cpsAnim.end()) continue;
auto &cpAnim = it->second;
if (recordCP) {
// recording started - clear previously recorded control point animation
// if it exists
cpAnim = CPAnim();
} else {
// recording stopped
cpAnim.setAll(false, true);
if (autoSmoothAnim) {
int from = autoSmoothAnimFrom;
int to = autoSmoothAnimTo;
if (animMode == ANIM_MODE_OVERWRITE || animMode == ANIM_MODE_AVERAGE) {
int syncLength = cpAnimSync.getLength();
int syncT = syncLength > 0
? static_cast<int>(cpAnimSync.lastT) % syncLength
: 0;
from = syncT + autoSmoothAnimFrom;
to = syncT + autoSmoothAnimTo;
}
cpAnim.performSmoothing(from, to, autoSmoothAnimIts);
}
}
}
if (recordCP) {
// recording started
recordCPActive = true;
cpData.timestampStart = chrono::high_resolution_clock::now();
DEBUG_CMD_MM(cout << "CP recording started" << endl;)
} else {
// recording stopped
// Stop relative transformation when animation recording finished.
transformEnd(false);
DEBUG_CMD_MM(cout << "CP recording stopped" << endl;)
}
}
void MainWindow::cpAnimationPlaybackAndRecord() {
auto &selectedPoints = this->cpData.selectedPoints;
auto &selectedPoint = this->cpData.selectedPoint;
auto &cpsAnim = this->cpData.cpsAnim;
auto &cpAnimSync = this->cpData.cpAnimSync;
auto &cpsAnimSyncId = this->cpData.cpsAnimSyncId;
auto &recordCP = this->cpData.recordCP;
auto &animMode = cpData.animMode;
auto &playAnimation = cpData.playAnimation;
auto &playAnimWhenSelected = cpData.playAnimWhenSelected;
// control points animation
// find sync control point
bool cpAnimSyncUpdating = false;
if (!cpsAnim.empty()) {
const auto &it = cpsAnim.find(cpsAnimSyncId);
if (it == cpsAnim.end()) {
// sync anim does not exist anymore - create it from the first cpAnim in
// the list
cpsAnimSyncId = cpsAnim.begin()->first;
cpAnimSync =
CPAnim(cpsAnim.begin()
->second.getKeyposes()); // initialize only with keyposes
// of the first cpAnim
DEBUG_CMD_MM(cout << "cpsanimfirst " << cpsAnimSyncId << endl;)
} else {
if (cpAnimSync.getLength() != it->second.getLength()) {
// Lengths of sync animation and its assigned animations differ:
// update cpAnimSync: only by keyposes of the first cpAnim.
cpAnimSync = CPAnim(it->second.getKeyposes());
}
}
// check if we're updating sync CP anim
if (selectedPoints.find(cpsAnimSyncId) != selectedPoints.end()) {
cpAnimSyncUpdating = true;
}
} else {
cpsAnimSyncId = -1;
cpAnimSync = CPAnim();
}
// sync timepoint hack allowing for animation speed-up/slow-down
if (cpsAnimSyncId != -1 && cpAnimSync.getLength() > 0) {
if (playAnimation || recordCP) {
if (!manualTimepoint) {
cpAnimSync.lastT++;
if (cpAnimSync.lastT >= 100 * cpAnimSync.getLength())
cpAnimSync.lastT = 0;
}
}
}
if (!def.getCPs().empty()) {
// recording
if (recordCP && selectedPoint != -1) {
bool overwriteMode = false;
int syncLength = 0;
int syncT = 0;
if (!cpAnimSyncUpdating &&
(animMode == ANIM_MODE_OVERWRITE || animMode == ANIM_MODE_AVERAGE)) {
if (cpsAnimSyncId != -1 && cpAnimSync.getLength() > 0)
overwriteMode = true;
if (overwriteMode) {
// sync CP exists, get its length and timepoint
syncLength = cpAnimSync.getLength();
syncT = syncLength > 0
? static_cast<int>(cpAnimSync.lastT) % syncLength
: 0;
}
}
for (int cpId : selectedPoints) {
try {
Vector3d p = def.getCP(cpId).pos;
auto &cpAnim = cpsAnim[cpId];
int timestamp =
chrono::duration_cast<chrono::milliseconds>(
chrono::high_resolution_clock::now() - cpData.timestampStart)
.count();
if (!cpAnimSyncUpdating && overwriteMode) {
if (cpAnim.getLength() != syncLength) {
// lengths do not match, recreate, initialize with empty flag
cpAnim = CPAnim(syncLength, p);
}
const auto &kPrev = cpAnim.peekk(syncT);
// If the value at the current timepoint is empty, set it to the
// current position, otherwise compute average of previous and
// current position.
if (animMode == ANIM_MODE_AVERAGE && !kPrev.empty) {
p = 0.75 * p + 0.25 * kPrev.p;
}
cpAnim.record(syncT,
CPAnim::Keypose{p, timestamp, false, true, true});
const int syncTNext = syncLength > 0 ? (syncT + 1) % syncLength : 0;
auto &kNext = cpAnim.peekk(syncTNext);
kNext.display = false;
} else {
if (cpAnim.lastT >= 1) {
auto &k = cpAnim.peekk(static_cast<int>(cpAnim.lastT));
k.display = true;
}
cpAnim.record(CPAnim::Keypose{p, timestamp, true, false, true});
}
} catch (out_of_range &e) {
cerr << e.what() << endl;
}
}
}
// playback
if (playAnimation && !manualTimepoint && !cpsAnim.empty()) {
defEng.solveForZ = false; // pause z-deformation
}
if (playAnimation || recordCP) {
for (auto &it2 : cpsAnim) {
const int cpId = it2.first;
CPAnim &a = it2.second;
// skip selected points
if (selectedPoints.find(cpId) != selectedPoints.end() &&
(!playAnimWhenSelected || recordCP)) {
continue;
}
a.syncSetLength(cpAnimSync.getLength());
try {
auto &cp = def.getCP(cpId);
cp.pos = cp.prevPos = a.replay(cpAnimSync.lastT);
} catch (out_of_range &e) {
cerr << e.what() << endl;
}
}
}
}
}
void MainWindow::setAnimRecMode(AnimMode animMode) {
cpData.animMode = animMode;
}
AnimMode MainWindow::getAnimRecMode() { return cpData.animMode; }
void MainWindow::toggleAnimationPlayback() {
cpData.playAnimation = !cpData.playAnimation;
defEng.solveForZ = !cpData.playAnimation; // pause z-deformation
repaint = true;
}
bool MainWindow::isAnimationPlaying() { return cpData.playAnimation; }
void MainWindow::toggleAnimationSelectedPlayback() {
cpData.playAnimWhenSelected = !cpData.playAnimWhenSelected;
repaint = true;
}
void MainWindow::offsetSelectedCpAnimsByFrames(double offset) {
auto &selectedPoints = this->cpData.selectedPoints;
auto &cpsAnim = this->cpData.cpsAnim;
for (auto &it : cpsAnim) {
const int cpId = it.first;
if (selectedPoints.find(cpId) == selectedPoints.end()) continue;
auto &cpAnim = it.second;
cpAnim.setOffset(cpAnim.getOffset() + offset);
try {
auto &cp = def.getCP(cpId);
cp.pos = cp.prevPos = cpAnim.peek();
} catch (out_of_range &e) {
cerr << e.what() << endl;
}
}
repaint = true;
}
void MainWindow::offsetSelectedCpAnimsByPercentage(double offset) {
// TODO: not implemented
repaint = true;
}
void MainWindow::toggleAutoSmoothAnim() { autoSmoothAnim = !autoSmoothAnim; }
bool MainWindow::copySelectedAnim() {
auto &selectedPoint = this->cpData.selectedPoint;
auto &cpsAnim = this->cpData.cpsAnim;
const auto &it = cpsAnim.find(selectedPoint);
if (it == cpsAnim.end()) {
DEBUG_CMD_MM(cout << "No control point animation selected." << endl;);
return false;
}
copiedAnim = it->second;
return true;
}
bool MainWindow::pasteSelectedAnim() {
auto &selectedPoints = this->cpData.selectedPoints;
auto &selectedPoint = this->cpData.selectedPoint;
auto &cpsAnim = this->cpData.cpsAnim;
if (selectedPoint == -1) {
DEBUG_CMD_MM(cout << "No control point selected." << endl;);
return false;
}
for (int cpId : selectedPoints) {
try {
auto &cp = def.getCP(cpId);
auto &cpAnim = cpsAnim[cpId];
cpAnim = copiedAnim;
Vector3d t = -cpAnim.peek(0) + cp.pos;
Affine3d T((Translation3d(t)));
cpAnim.setTransform(T.matrix());
cpAnim.applyTransform();
} catch (out_of_range &e) {
cerr << e.what() << endl;
}
}
repaint = true;
return true;
}
bool MainWindow::removeCPAnims() {
auto &selectedPoints = this->cpData.selectedPoints;
auto &cpsAnim = this->cpData.cpsAnim;
auto &cpsAnimSyncId = this->cpData.cpsAnimSyncId;
// remove only animations of selected control points
bool cpErased = false;
for (const int cpId : selectedPoints) {
if (cpId == cpsAnimSyncId) cpsAnimSyncId = -1;
if (cpsAnim.erase(cpId) != 0) cpErased = true;
}
repaint = true;
return cpErased;
}
// END OF ANIMATION
void MainWindow::setCPsVisibility(bool visible) {
cpData.showControlPoints = visible;
repaint = true;
}
bool MainWindow::getCPsVisibility() { return cpData.showControlPoints; }
ManipulationMode MainWindow::openProject(const std::string &zipFn,
bool changeMode) {
reset();
ManipulationMode newManipulationMode;
loadAllFromZip(zipFn, viewportW, viewportH, cpData, imgData, recData,
savedCPs, templateImg, backgroundImg, shadingOpts,
newManipulationMode, middleMouseSimulation);
shadingOpts.showTexture = shadingOpts.showTemplateImg;
if (!templateImg.isNull()) {
loadTextureToGPU(templateImg, glData.templateImgTexName);
}
if (!backgroundImg.isNull()) {
loadTextureToGPU(backgroundImg, glData.backgroundImgTexName);
}
if (changeMode) changeManipulationMode(newManipulationMode, false);
if (manipulationMode.isImageModeActive()) recreateMergedImgs();
enableMiddleMouseSimulation(middleMouseSimulation);
repaint = true;
return newManipulationMode;
}
void MainWindow::saveProject(const std::string &zipFn) {
auto *cpDataAnimateMode = &cpData;
if (manipulationMode.mode == DEFORM_MODE) cpDataAnimateMode = &cpDataBackup;
saveAllToZip(zipFn, *cpDataAnimateMode, defData, imgData, recData, savedCPs,
templateImg, backgroundImg, shadingOpts, manipulationMode,
middleMouseSimulation);
}
void MainWindow::setTemplateImageVisibility(bool visible) {
shadingOpts.showTemplateImg = visible;
shadingOpts.showTexture = visible;
repaint = true;
}
bool MainWindow::getTemplateImageVisibility() {
return shadingOpts.showTemplateImg;
}
bool MainWindow::hasTemplateImage() { return !templateImg.isNull(); }
void MainWindow::setBackgroundImageVisibility(bool visible) {
shadingOpts.showBackgroundImg = visible;
repaint = true;
}
bool MainWindow::getBackgroundImageVisibility() {
return shadingOpts.showBackgroundImg;
}
void MainWindow::enableTextureShading(bool enabled) {
shadingOpts.showTextureUseMatcapShading = enabled;
repaint = true;
}
bool MainWindow::isTextureShadingEnabled() {
return shadingOpts.showTextureUseMatcapShading;
}
ManipulationMode &MainWindow::getManipulationMode() { return manipulationMode; }
void MainWindow::recomputeCameraCenter() {
auto &V = defData.VCurr;
if (V.rows() == 0) return;
cameraCenter.fill(0);
cameraCenter =
(V.colwise().sum() / V.rows()).transpose(); // model's centroid
cameraCenter(2) = 0;
cameraCenterViewSpace =
(proj3DView * cameraCenter.homogeneous()).hnormalized() -
Vector3d(translateView.x(), translateView.y(), 0);
repaint = true;
}
void MainWindow::enableArmpitsStitching(bool enabled) {
armpitsStitching = enabled;
repaint = true;
}
bool MainWindow::isArmpitsStitchingEnabled() { return armpitsStitching; }
void MainWindow::enableNormalSmoothing(bool enabled) {
shadingOpts.useNormalSmoothing = enabled;
repaint = true;
}
bool MainWindow::isNormalSmoothingEnabled() {
return shadingOpts.useNormalSmoothing;
}
void MainWindow::exportTextureTemplate(const std::string &fn) {
const Imguc &Io = mergedOutlinesImg;
Imguc I;
I.initImage(mergedOutlinesImg);
I.fill(255);
fora(y, 0, I.h) fora(x, 0, I.w) {
if (Io(x, y, 3) != 0) {
fora(c, 0, 3) I(x, y, c) = (0.75 * 256 - 1) + 0.25 * Io(x, y, c);
}
}
I.savePNG(fn);
}
void MainWindow::enableMiddleMouseSimulation(bool enabled) {
middleMouseSimulation = enabled;
rotationModeActive = enabled;
repaint = true;
}
bool MainWindow::isMiddleMouseSimulationEnabled() {
return middleMouseSimulation;
}
void MainWindow::resetView() {
camData = CameraData();
recomputeCameraCenter();
cameraCenterViewSpace = cameraCenter;
repaint = true;
}
void MainWindow::pauseAll(PauseStatus &status) {
if (manipulationMode.mode != ANIMATE_MODE) return;
status.animPaused = !cpData.playAnimation;
cpData.playAnimation = false;
defPaused = true;
repaint = true;
}
void MainWindow::resumeAll(PauseStatus &status) {
if (manipulationMode.mode != ANIMATE_MODE) return;
cpData.playAnimation = !status.animPaused;
defPaused = false;
repaint = true;
}
void MainWindow::exportAsOBJ(const std::string &outDir,
const std::string &outFnWithoutExtension,
bool saveTexture) {
MatrixXd V = defData.VCurr;
MatrixXd N = defData.normals;
V *= 10.0 / viewportW;
V.array().rowwise() *= RowVector3d(1, -1, -1).array();
N.array().rowwise() *= RowVector3d(1, -1, -1).array();
V.rowwise() += RowVector3d(-5, 5, 0);
MatrixXd textureCoords;
if (!templateImg.isNull() && saveTexture) {
textureCoords = (defData.VRestOrig.array().rowwise() /
Array3d(templateImg.w, -templateImg.h, 1).transpose());
}
string objFn = outDir + "/" + outFnWithoutExtension + ".obj";
writeOBJ(objFn, V, defData.Faces, N, defData.Faces, textureCoords,
defData.Faces);
if (!templateImg.isNull() && saveTexture) {
// write material to a file
{
ofstream stream(objFn, ofstream::out | ofstream::app);
if (stream.is_open()) {
stream << "s 1" << endl;
stream << "mtllib " << outFnWithoutExtension << ".mtl" << endl;
stream << "usemtl Textured" << endl;
stream.close();
}
}
{
ofstream stream(outDir + "/" + outFnWithoutExtension + ".mtl");
if (stream.is_open()) {
stream << "newmtl Textured\nKa 1.000 1.000 1.000\nKd 1.000 1.000 "
"1.000\nKs 0.000 0.000 0.000\nNs 10.000\nd 1.0\nTr "
"0.0\nillum 2\nmap_Ka "
<< outFnWithoutExtension << ".png"
<< "\nmap_Kd " << outFnWithoutExtension << ".png" << endl;
stream.close();
}
}
templateImg.savePNG(outDir + "/" + outFnWithoutExtension + ".png");
}
}
void MainWindow::exportAnimationStart(int preroll, bool solveForZ,
bool perFrameNormals) {
const int nFrames = cpAnimSync.getLength();
manualTimepoint = true;
if (nFrames > 0) {
cpAnimSync.lastT = (100 * nFrames - preroll) % nFrames;
}
cpData.playAnimation = true;
defEng.solveForZ = solveForZ; // resume z-deformation
defPaused = false;
if (gltfExporter != nullptr) delete gltfExporter;
gltfExporter = new exportgltf::ExportGltf;
exportAnimationWaitForBeginning = true;
exportAnimationPreroll = preroll;
exportPerFrameNormals = perFrameNormals;
exportedFrames = 0;
repaint = true;
DEBUG_CMD_MM(cout << "exportAnimationStart" << endl;);
}
void MainWindow::exportAnimationStop(bool exportModel) {
manualTimepoint = false;
defEng.solveForZ = false; // pause z-deformation
cpData.playAnimation = false;
defPaused = true;
if (gltfExporter != nullptr) {
if (exportModel) {
gltfExporter->exportStop("/tmp/mm_project.glb", true);
#ifdef __EMSCRIPTEN__
EM_ASM(js_exportAnimationFinished(););
#endif
}
delete gltfExporter;
gltfExporter = nullptr;
}
repaint = true;
DEBUG_CMD_MM(cout << "exportAnimationStop" << endl;);
}
void MainWindow::exportAnimationFrame() {
if (gltfExporter == nullptr) {
DEBUG_CMD_MM(cerr << "exportAnimationFrame: gltfModel == nullptr" << endl;);
return;
}
const int nFrames = cpAnimSync.getLength();
bool exportSingleFrame = nFrames == 0;
int prerollCurr = 0;
if (!exportSingleFrame) {
const int prerollStart = (100 * nFrames - exportAnimationPreroll) % nFrames;
prerollCurr = static_cast<int>(cpAnimSync.lastT) - prerollStart;
if (exportAnimationWaitForBeginning) {
if (prerollCurr >= exportAnimationPreroll) {
exportAnimationWaitForBeginning = false;
} else {
DEBUG_CMD_MM(cout << "exportAnimationFrame: waiting for beginning ("
<< cpAnimSync.lastT << ")" << endl;);
}
}
} else {
exportAnimationWaitForBeginning = false;
}
if (!exportAnimationWaitForBeginning) {
prerollCurr = exportAnimationPreroll;
DEBUG_CMD_MM(cout << "exportAnimationFrame: " << exportedFrames << endl;);
exportgltf::MatrixXfR V = defData.VCurr.cast<float>();
V *= 10.0 / viewportW;
V.array().rowwise() *= RowVector3f(1, -1, -1).array();
V.rowwise() += RowVector3f(-5, 5, 0);
const int nFrames = cpAnimSync.getLength();
const bool hasTexture = !templateImg.isNull();
exportgltf::MatrixXfR N;
if (exportedFrames == 0 || exportPerFrameNormals) {
N = defData.normals.cast<float>();
N.array().rowwise() *= RowVector3f(1, -1, -1).array();
}
if (exportedFrames == 0) {
exportBaseV = V;
exportBaseN = N;
exportgltf::MatrixXusR F = defData.Faces.cast<unsigned short>();
exportgltf::MatrixXfR TC;
if (hasTexture) {
TC = (defData.VRestOrig.leftCols(2).cast<float>().array().rowwise() /
Array2f(templateImg.w, templateImg.h).transpose());
}
gltfExporter->exportStart(V, N, F, TC, nFrames, exportPerFrameNormals, 24,
templateImg);
gltfExporter->exportFullModel(V, N, F, TC);
} else {
V -= exportBaseV;
if (exportPerFrameNormals) N -= exportBaseN;
gltfExporter->exportMorphTarget(V, N, exportedFrames);
}
exportedFrames++;
}
// update progress bar
int progress = 100;
if (!exportSingleFrame) {
progress = round(100.0 * (prerollCurr + exportedFrames) /
(nFrames + exportAnimationPreroll));
}
#ifdef __EMSCRIPTEN__
EM_ASM({ js_exportAnimationProgress($0); }, progress);
#endif
cpAnimSync.lastT++;
if (cpAnimSync.lastT >= 100 * nFrames) cpAnimSync.lastT = 0;
if (!exportAnimationWaitForBeginning) {
if (exportSingleFrame ||
(nFrames > 0 && (static_cast<int>(cpAnimSync.lastT) % nFrames == 0))) {
// reached the end of animation
exportAnimationStop();
return;
}
}
repaint = true;
}
bool MainWindow::exportAnimationRunning() { return gltfExporter != nullptr; }
void MainWindow::pauseAnimation() { pauseAll(animStatus); }
void MainWindow::resumeAnimation() { resumeAll(animStatus); }
int MainWindow::getNumberOfAnimationFrames() { return cpAnimSync.getLength(); }
| 31.929845 | 80 | 0.630658 | [
"mesh",
"geometry",
"shape",
"vector",
"model",
"3d"
] |
07f579f301e69f2ff38c40ffa50d3e956587e2fd | 2,244 | cpp | C++ | 21.cpp | Alex-Amber/LeetCode | c8d09e86cee52648f84ca2afed8dd0f13e51ab58 | [
"MIT"
] | null | null | null | 21.cpp | Alex-Amber/LeetCode | c8d09e86cee52648f84ca2afed8dd0f13e51ab58 | [
"MIT"
] | null | null | null | 21.cpp | Alex-Amber/LeetCode | c8d09e86cee52648f84ca2afed8dd0f13e51ab58 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using ull = uint64_t;
using ll = int64_t;
using ld = long double;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<ii> vii;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
if (!l1 || !l2) // corner case: at least one list is empty, then we return another list head
return l1 ? l1 : l2;
ListNode *head = NULL, *cur1 = l1, *cur2 = l2; // cur1 and cur2 are the pointers to the next node to be added to the merged list, and the smaller one of them is current tail node
head = cur1->val < cur2->val ? cur1 : cur2;
bool tail_on_l1 = (head == cur1); // the last added node is the tail of the merged list, so tail_on_l1 indicate whether the last node is in l1 when the two current nodes have equal values
while (cur1 != NULL && cur2 != NULL)
{
if (cur1->val < cur2->val) // cur1's value comes before cur2's value, which means that the cur1 is the current tail node
{
ListNode *cur_tail = cur1;
cur1 = cur1->next;
// determine the next tail node
cur_tail->next = cur_tail->next ? (cur_tail->next->val < cur2->val ? cur_tail->next : cur2) : cur2;
tail_on_l1 = false; // when cur_tail->next->value == cur2->value, the next tail node is in l2
}
else if (cur1->val > cur2->val) // cur2's value comes before cur1's value, which means that the cur2 is the current tail node
{
ListNode *cur_tail = cur2;
cur2 = cur2->next;
// determine the next tail node
cur_tail->next = cur_tail->next ? (cur_tail->next->val < cur1->val ? cur_tail->next : cur1) : cur1;
tail_on_l1 = true; // when cur_tail->next->value == cur2->value, the next tail node is in l1
}
else // cur1 andh cur2's values are equal
{
// In this case, we need to link current tail to the other equal node
if (tail_on_l1)
{
ListNode *next = cur1->next;
cur1->next = cur2;
cur1 = next;
}
else
{
ListNode *next = cur2->next;
cur2->next = cur1;
cur2 = next;
}
tail_on_l1 = !tail_on_l1; // the next tail node is in the other list
}
}
return head;
}
};
| 33 | 192 | 0.642157 | [
"vector"
] |
07f631683e4130cc760cbc9c9e7271b8a4468c55 | 14,591 | cpp | C++ | api_bridge_example_backend/src/ex_benchmark.cpp | jlakness-intel/api-bridge | 5287cac775976906abd99e09a113ef70ce9b07df | [
"Apache-2.0"
] | 4 | 2021-10-09T12:41:16.000Z | 2022-03-09T22:08:37.000Z | api_bridge_example_backend/src/ex_benchmark.cpp | jlakness-intel/api-bridge | 5287cac775976906abd99e09a113ef70ce9b07df | [
"Apache-2.0"
] | null | null | null | api_bridge_example_backend/src/ex_benchmark.cpp | jlakness-intel/api-bridge | 5287cac775976906abd99e09a113ef70ce9b07df | [
"Apache-2.0"
] | 1 | 2021-12-14T20:16:58.000Z | 2021-12-14T20:16:58.000Z |
// Copyright (C) 2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include <algorithm>
#include <cstring>
#include <memory>
#include <vector>
#include "../include/ex_benchmark.h"
#include "../include/ex_engine.h"
//-----------------------------------
// class ExampleBenchmarkDescription
//-----------------------------------
ExampleBenchmarkDescription::ExampleBenchmarkDescription()
{
// initialize the descriptor for this benchmark
std::memset(&m_descriptor, 0, sizeof(hebench::APIBridge::BenchmarkDescriptor));
m_descriptor.workload = hebench::APIBridge::Workload::MatrixMultiply;
m_descriptor.data_type = hebench::APIBridge::DataType::Float64;
m_descriptor.category = hebench::APIBridge::Category::Latency;
m_descriptor.cat_params.latency.min_test_time_ms = 2000; // 2s
m_descriptor.cat_params.latency.warmup_iterations_count = 1;
m_descriptor.cipher_param_mask = HEBENCH_HE_PARAM_FLAGS_ALL_PLAIN;
//
m_descriptor.scheme = HEBENCH_HE_SCHEME_PLAIN;
m_descriptor.security = HEBENCH_HE_SECURITY_NONE;
m_descriptor.other = 0; // no extras needed for our purpose:
// Other backends can use this field to differentiate between
// benchmarks for which internal parameters, not specified by
// other fields of this structure, differ.
// specify default arguments for this workload:
// this benchmark will only support matrices of 100x100
hebench::cpp::WorkloadParams::MatrixMultiply default_workload_params;
default_workload_params.rows_M0() = 100;
default_workload_params.cols_M0() = 100;
default_workload_params.cols_M1() = 100;
this->addDefaultParameters(default_workload_params);
}
ExampleBenchmarkDescription::~ExampleBenchmarkDescription()
{
// nothing needed in this example
}
hebench::cpp::BaseBenchmark *ExampleBenchmarkDescription::createBenchmark(hebench::cpp::BaseEngine &engine,
const hebench::APIBridge::WorkloadParams *p_params)
{
if (!p_params)
throw hebench::cpp::HEBenchError(HEBERROR_MSG_CLASS("Invalid empty workload parameters. This workload requires flexible parameters."),
HEBENCH_ECODE_CRITICAL_ERROR);
ExampleEngine &ex_engine = dynamic_cast<ExampleEngine &>(engine);
return new ExampleBenchmark(ex_engine, m_descriptor, *p_params);
}
void ExampleBenchmarkDescription::destroyBenchmark(hebench::cpp::BaseBenchmark *p_bench)
{
// make sure we are destroying a benchmark object we created
if (p_bench)
{
ExampleBenchmark *p_tmp = dynamic_cast<ExampleBenchmark *>(p_bench);
delete p_tmp;
} // end if
}
//------------------------
// class ExampleBenchmark
//------------------------
ExampleBenchmark::ExampleBenchmark(ExampleEngine &engine,
const hebench::APIBridge::BenchmarkDescriptor &bench_desc,
const hebench::APIBridge::WorkloadParams &bench_params) :
hebench::cpp::BaseBenchmark(engine, bench_desc, bench_params)
{
// validate workload parameters
// number of workload parameters (3 for matmul: rows of M0, cols of M0, cols of M1)
if (bench_params.count < ExampleBenchmarkDescription::NumWorkloadParams)
throw hebench::cpp::HEBenchError(HEBERROR_MSG_CLASS("Invalid workload parameters. This workload requires " + std::to_string(ExampleBenchmarkDescription::NumWorkloadParams) + " parameters."),
HEBENCH_ECODE_INVALID_ARGS);
// check values of the workload parameters and make sure they are supported by benchmark:
hebench::cpp::WorkloadParams::MatrixMultiply w_params(bench_params);
if (w_params.rows_M0() != 100
|| w_params.cols_M0() != 100
|| w_params.cols_M1() != 100)
throw hebench::cpp::HEBenchError(HEBERROR_MSG_CLASS("Invalid workload parameters. This workload only supports matrices of dimensions 100 x 100."),
HEBENCH_ECODE_INVALID_ARGS);
// workload-parameter-based initialization would go here, but for this example is
// not necessary because this example supports only matrices that are 100 x 100
}
ExampleBenchmark::~ExampleBenchmark()
{
// nothing needed in this example
}
hebench::APIBridge::Handle ExampleBenchmark::encode(const hebench::APIBridge::PackedData *p_parameters)
{
if (p_parameters->pack_count != ParametersCount)
throw hebench::cpp::HEBenchError(HEBERROR_MSG_CLASS("Invalid number of parameters detected in parameter pack. Expected 2."),
HEBENCH_ECODE_INVALID_ARGS);
// allocate our internal version of the encoded data
// We are using shared_ptr because we want to be able to copy the pointer object later
// and use the reference counter to avoid leaving dangling. If our internal object
// does not need to be copied, shared_ptr is not really needed.
std::shared_ptr<std::vector<Matrix>> p_params =
std::make_shared<std::vector<Matrix>>(p_parameters->pack_count);
std::vector<Matrix> ¶ms = *p_params;
// encode the packed parameters into our internal version
for (std::uint64_t param_i = 0; param_i < p_parameters->pack_count; ++param_i)
{
// find the parameter data pack inside the parameters pack that corresponds
// to this parameter position:
// param_i == p_parameters->p_data_packs[i].param_position
const hebench::APIBridge::DataPack ¶meter = ExampleBenchmark::findDataPack(*p_parameters, param_i);
// take first sample from parameter (because latency test has a single sample per parameter)
if (!parameter.p_buffers || !parameter.p_buffers[0].p)
throw hebench::cpp::HEBenchError(HEBERROR_MSG_CLASS("Invalid empty samples detected in parameter pack."),
HEBENCH_ECODE_INVALID_ARGS);
const hebench::APIBridge::NativeDataBuffer &sample = parameter.p_buffers[0];
// convert the native data to pointer to double as per specification of workload
const double *p_row = reinterpret_cast<const double *>(sample.p);
// copy every 100 doubles (full row) to each row of the matrix representation
// We cannot just simply maintain pointers to the parameter data because, as per specification,
// the resulting handle must be valid regardless whether the native data is valid after
// this method completes. Thus, deep copy is needed.
for (std::size_t row_i = 0; row_i < params[param_i].rows.size(); ++row_i)
{
std::copy(p_row, p_row + params[param_i].rows[row_i].size(),
params[param_i].rows[row_i].data());
p_row += params[param_i].rows[row_i].size();
} // end for
} // end for
// wrap our internal object into a handle to cross the boundary of the API Bridge
return this->getEngine().template createHandle<decltype(p_params)>(sizeof(Matrix) * params.size(), 0,
p_params);
}
void ExampleBenchmark::decode(hebench::APIBridge::Handle encoded_data, hebench::APIBridge::PackedData *p_native)
{
// This method should handle decoding of data encoded using encode(), due to
// specification stating that encode() and decode() are inverses; as well as
// handle data decrypted from operation() results.
// retrieve our internal format object from the handle
const std::vector<Matrix> ¶ms =
*this->getEngine().template retrieveFromHandle<std::shared_ptr<std::vector<Matrix>>>(encoded_data);
// according to specification, we must decode as much data as possible, where
// any excess encoded data that won't fit into the pre-allocated native buffer
// shall be ignored
std::uint64_t min_param_count = std::min(p_native->pack_count, params.size());
for (std::size_t param_i = 0; param_i < min_param_count; ++param_i)
{
hebench::APIBridge::DataPack *p_native_param = &p_native->p_data_packs[param_i];
if (p_native_param && p_native_param->buffer_count > 0)
{
// for latency, we have only one sample, so, decode the sample into the first buffer
hebench::APIBridge::NativeDataBuffer &native_sample = p_native_param->p_buffers[0];
// copy each row for the current parameter matrix into the corresponding
// decoded buffer
const Matrix &mat = params[param_i]; // alias for clarity
std::uint64_t sample_elem_count = // number of doubles in decoded buffer
native_sample.size / sizeof(double);
std::uint64_t offset = 0;
for (std::size_t row_i = 0;
offset < sample_elem_count
&& row_i < mat.rows.size();
++row_i)
{
// point to next row in target
double *p_decoded_row = reinterpret_cast<double *>(native_sample.p) + offset;
// copy as much as we can into the row
std::uint64_t num_elems_to_copy =
std::min(mat.rows[row_i].size(), sample_elem_count - offset);
std::copy(mat.rows[row_i].data(), mat.rows[row_i].data() + num_elems_to_copy,
p_decoded_row);
offset += num_elems_to_copy; // advance the target row pointer
} // end for
} // end if
} // end for
}
hebench::APIBridge::Handle ExampleBenchmark::encrypt(hebench::APIBridge::Handle encoded_data)
{
// we only do plain text in this example, so, just return a copy of our internal data
std::shared_ptr<void> p_encoded_data =
this->getEngine().template retrieveFromHandle<std::shared_ptr<void>>(encoded_data);
// the copy is shallow, but shared_ptr ensures correct destruction using reference counting
return this->getEngine().template createHandle<decltype(p_encoded_data)>(encoded_data.size, 0,
p_encoded_data);
}
hebench::APIBridge::Handle ExampleBenchmark::decrypt(hebench::APIBridge::Handle encrypted_data)
{
// we only do plain text in this example, so, just return a copy of our internal data
std::shared_ptr<void> p_encrypted_data =
this->getEngine().template retrieveFromHandle<std::shared_ptr<void>>(encrypted_data);
// the copy is shallow, but shared_ptr ensures correct destruction using reference counting
return this->getEngine().template createHandle<decltype(p_encrypted_data)>(encrypted_data.size, 0,
p_encrypted_data);
}
hebench::APIBridge::Handle ExampleBenchmark::load(const hebench::APIBridge::Handle *p_local_data, uint64_t count)
{
if (count != 1)
// we do all ops in plain text, so, we should get only one pack of data
throw hebench::cpp::HEBenchError(HEBERROR_MSG_CLASS("Invalid number of handles. Expected 1."),
HEBENCH_ECODE_INVALID_ARGS);
if (!p_local_data)
throw hebench::cpp::HEBenchError(HEBERROR_MSG_CLASS("Invalid null array of handles: \"p_local_data\""),
HEBENCH_ECODE_INVALID_ARGS);
// since remote and host are the same for this example, we just need to return a copy
// of the local data as remote.
return this->getEngine().duplicateHandle(p_local_data[0]);
}
void ExampleBenchmark::store(hebench::APIBridge::Handle remote_data,
hebench::APIBridge::Handle *p_local_data, std::uint64_t count)
{
if (count > 0 && !p_local_data)
throw hebench::cpp::HEBenchError(HEBERROR_MSG_CLASS("Invalid null array of handles: \"p_local_data\""),
HEBENCH_ECODE_INVALID_ARGS);
if (count > 0)
{
// pad with zeros any remaining local handles as per specifications
std::memset(p_local_data, 0, sizeof(hebench::APIBridge::Handle) * count);
// since remote and host are the same for this example, we just need to return a copy
// of the remote as local data.
p_local_data[0] = this->getEngine().duplicateHandle(remote_data);
} // end if
}
hebench::APIBridge::Handle ExampleBenchmark::operate(hebench::APIBridge::Handle h_remote_packed,
const hebench::APIBridge::ParameterIndexer *p_param_indexers)
{
// This method should perform as fast as possible since it is the
// method benchmarked by Test Harness.
for (std::size_t i = 0; i < 2; ++i)
// normally, a robust backend will use the indexers as appropriate,
// but for the sake of the example, we just validate them
if (p_param_indexers[i].value_index != 0 || p_param_indexers[i].batch_size != 1)
throw hebench::cpp::HEBenchError(HEBERROR_MSG_CLASS("Invalid parameter indexer. Expected index 0 and batch size of 1."),
HEBENCH_ECODE_INVALID_ARGS);
// retrieve our internal format object from the handle
const std::vector<Matrix> ¶ms =
*this->getEngine().template retrieveFromHandle<std::shared_ptr<std::vector<Matrix>>>(h_remote_packed);
// create a new internal object for result
std::uint64_t components_count = ResultComponentsCount;
std::shared_ptr<std::vector<Matrix>> p_result = std::make_shared<std::vector<Matrix>>(components_count);
// perform the actual operation
Matrix &result = p_result->front(); // alias the pointer for clarity
for (std::size_t row_0_i = 0; row_0_i < params[0].rows.size(); ++row_0_i)
{
for (std::size_t col_0_i = 0; col_0_i < params[0].rows[row_0_i].size(); ++col_0_i)
{
double val = 0;
for (int i = 0; i < 100; i++)
val += params[0].rows[row_0_i][i] * params[1].rows[i][col_0_i];
result.rows[row_0_i][col_0_i] = val;
} // end for
} // end for
// send our internal result across the boundary of the API Bridge as a handle
return this->getEngine().template createHandle<decltype(p_result)>(sizeof(Matrix) * p_result->size(), 0,
p_result);
}
| 48.799331 | 198 | 0.647111 | [
"object",
"vector"
] |
07f95964f089f0f2086822adb16f7e5f6f630473 | 723 | hpp | C++ | game.hpp | OneMoreCookiePlease/asteroids | b0aaeab8efe87b8269108848e5efc44f1bdaceb0 | [
"MIT"
] | null | null | null | game.hpp | OneMoreCookiePlease/asteroids | b0aaeab8efe87b8269108848e5efc44f1bdaceb0 | [
"MIT"
] | null | null | null | game.hpp | OneMoreCookiePlease/asteroids | b0aaeab8efe87b8269108848e5efc44f1bdaceb0 | [
"MIT"
] | null | null | null | #pragma once
#include "SFML/Graphics.hpp"
#include "SFML/Window.hpp"
#include "utils.hpp"
#include "object.hpp"
class Game final
{
private:
bool m_is_running = true;
int m_exit_code;
float m_minimum_d_time = 0;
std::vector<Object>objects;
sf::RenderWindow m_window;
public:
Game();
~Game();
int run();
void draw();
void quit(int exit_code = 0);
void create_main_window();
struct options
{
int width = 640;
int heigth = 400;
int bpp = 32;
int font_size = 21;
const char *game_title = "Asteroids";
bool vsync = false;
float max_fps = 60.f;
const char*font_name = "static/WinterCat.ttf";
};
};
| 18.075 | 54 | 0.589212 | [
"object",
"vector"
] |
07fec19344b1d1025ddd15955ef711a4b4f61cd1 | 799 | cpp | C++ | STL/Sequence Containers/10 emplace in stl.cpp | arvindr19/cppnuts | 3814a00348e0eb8588711bab751d3db1b6af6a25 | [
"MIT"
] | null | null | null | STL/Sequence Containers/10 emplace in stl.cpp | arvindr19/cppnuts | 3814a00348e0eb8588711bab751d3db1b6af6a25 | [
"MIT"
] | null | null | null | STL/Sequence Containers/10 emplace in stl.cpp | arvindr19/cppnuts | 3814a00348e0eb8588711bab751d3db1b6af6a25 | [
"MIT"
] | null | null | null | // TOPIC: Emplace In STL
// 1. All the containers supports insert and emplace operation to store data.
// 2. Emplace is used to construct object in-place and avoids unnecessary copy of objects.
// 3. Insert and Emplace is equal for premetive data types but when we deal with heavy objects
// we should use emplace if we can for efficiency.
#include <iostream>
#include <set>
using namespace std;
class A {
public:
int x;
A(int x=0): x{x} { cout << "Construct" << endl; };
A(const A& rhs) { x = rhs.x; cout << "Copy" << endl; }
};
bool operator < (const A& lhs, const A& rhs) { return lhs.x < rhs.x; }
int main() {
set<A> Set;
// A a(10);
//Set.insert(A(10));
//Set.emplace(10);
for ( auto & elm: Set){
cout << elm.x << endl;
}
return 0;
} | 26.633333 | 94 | 0.612015 | [
"object"
] |
580874936588a0f53e31daf6ec0a98ba02d50128 | 7,735 | cc | C++ | plugins/GravityCompensationPlugin.cc | apiyap/gazebo | adb08340fe71488045dd79a6465db7d58e3ae06f | [
"ECL-2.0",
"Apache-2.0"
] | 887 | 2020-04-18T08:43:06.000Z | 2022-03-31T11:58:50.000Z | plugins/GravityCompensationPlugin.cc | apiyap/gazebo | adb08340fe71488045dd79a6465db7d58e3ae06f | [
"ECL-2.0",
"Apache-2.0"
] | 462 | 2020-04-21T21:59:19.000Z | 2022-03-31T23:23:21.000Z | plugins/GravityCompensationPlugin.cc | apiyap/gazebo | adb08340fe71488045dd79a6465db7d58e3ae06f | [
"ECL-2.0",
"Apache-2.0"
] | 421 | 2020-04-21T09:13:03.000Z | 2022-03-30T02:22:01.000Z | /*
* Copyright (C) 2017 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.
*
*/
#include <functional>
#include <boost/filesystem.hpp>
#include <ignition/common/Profiler.hh>
#include <gazebo/transport/Node.hh>
#include <gazebo/transport/Subscriber.hh>
#include <gazebo/common/Events.hh>
#include <gazebo/common/Assert.hh>
#include <gazebo/physics/World.hh>
#include <gazebo/physics/Model.hh>
#include <gazebo/physics/Link.hh>
#include <gazebo/physics/dart/DARTTypes.hh>
#include <dart/dart.hpp>
#include <dart/utils/utils.hpp>
#include <dart/utils/sdf/sdf.hpp>
#include <Eigen/Core>
#include <ignition/math/Pose3.hh>
#include <ignition/math/Vector3.hh>
#include <sdf/sdf.hh>
#include "GravityCompensationPlugin.hh"
using namespace gazebo;
GZ_REGISTER_MODEL_PLUGIN(GravityCompensationPlugin)
namespace gazebo
{
/// \internal
/// \brief Private data for the GravityCompensationPlugin.
class GravityCompensationPluginPrivate
{
public: GravityCompensationPluginPrivate()
{
}
/// \brief The gazebo model.
public: physics::ModelPtr model;
/// \brief A DART skeleton for the model.
public: dart::dynamics::SkeletonPtr skel;
/// \brief Connects to world update event.
public: event::ConnectionPtr updateConnection;
/// \brief Node for communication.
public: transport::NodePtr node;
/// \brief Subscribe to the "~/physics" topic.
public: transport::SubscriberPtr physicsSub;
};
}
/////////////////////////////////////////////////
bool ModelResourceRetriever::exists(const dart::common::Uri &_uri)
{
return LocalResourceRetriever::exists(this->resolve(_uri));
}
/////////////////////////////////////////////////
dart::common::ResourcePtr ModelResourceRetriever::retrieve(
const dart::common::Uri &_uri)
{
return LocalResourceRetriever::retrieve(this->resolve(_uri));
}
/////////////////////////////////////////////////
dart::common::Uri ModelResourceRetriever::resolve(const dart::common::Uri &_uri)
{
dart::common::Uri uri;
if (_uri.mScheme.get_value_or("model") == "model")
{
uri.mScheme.assign("file");
std::string modelPath
= sdf::findFile("model://" + _uri.mAuthority.get() + _uri.mPath.get());
if (boost::filesystem::exists(modelPath))
{
if (boost::filesystem::is_directory(modelPath))
{
modelPath = sdf::getModelFilePath(modelPath);
}
uri.mPath.assign(modelPath);
}
}
return uri;
}
/////////////////////////////////////////////////
GravityCompensationPlugin::GravityCompensationPlugin()
: dataPtr(new GravityCompensationPluginPrivate)
{
}
/////////////////////////////////////////////////
GravityCompensationPlugin::~GravityCompensationPlugin()
{
}
/////////////////////////////////////////////////
void GravityCompensationPlugin::Load(physics::ModelPtr _model,
sdf::ElementPtr _sdf)
{
GZ_ASSERT(_model, "Model pointer is null");
GZ_ASSERT(_sdf, "SDF pointer is null");
this->dataPtr->model = _model;
// Load a DART skeleton model
if (_sdf->HasElement("uri"))
{
this->dataPtr->skel = dart::utils::SdfParser::readSkeleton(
_sdf->Get<std::string>("uri"),
std::make_shared<ModelResourceRetriever>());
if (this->dataPtr->skel == nullptr)
{
gzerr << "Error parsing " << _sdf->Get<std::string>("uri") << "\n";
return;
}
}
else
{
gzerr << "Must specify a model URI\n";
return;
}
if (this->dataPtr->model->GetWorld())
{
// Set gravity
ignition::math::Vector3d g = this->dataPtr->model->GetWorld()->Gravity();
this->dataPtr->skel->setGravity(Eigen::Vector3d(g.X(), g.Y(), g.Z()));
// Subscribe to physics messages in case gravity changes
this->dataPtr->node = transport::NodePtr(new transport::Node());
this->dataPtr->node->Init(this->dataPtr->model->GetWorld()->Name());
this->dataPtr->physicsSub = this->dataPtr->node->Subscribe("~/physics",
&GravityCompensationPlugin::OnPhysicsMsg, this);
}
else
{
gzwarn << "Unable to get world name. "
<< "GravityCompensationPlugin will not receive physics messages\n";
}
// Check that for each joint in the model the skeleton has a matching one.
physics::Joint_V joints = this->dataPtr->model->GetJoints();
for (auto joint : joints)
{
dart::dynamics::Joint *dtJoint =
this->dataPtr->skel->getJoint(joint->GetName());
if (dtJoint == nullptr)
{
gzerr << "Missing joint \"" << joint->GetName()
<< "\" in DART skeleton.\n";
return;
}
else if (dtJoint->getNumDofs() != joint->DOF())
{
gzerr << "Inconsistent number of DOF for joint \"" << joint->GetName()
<< ".\" The Gazebo joint has " << joint->DOF() << " DOF while"
<< " the DART joint has " << dtJoint->getNumDofs() << " DOF\n";
return;
}
}
// Connect to the world update signal
this->dataPtr->updateConnection = event::Events::ConnectWorldUpdateBegin(
std::bind(&GravityCompensationPlugin::Update, this,
std::placeholders::_1));
}
/////////////////////////////////////////////////
void GravityCompensationPlugin::Update(const common::UpdateInfo &/*_info*/)
{
IGN_PROFILE("GravityCompensationPlugin::Update");
IGN_PROFILE_BEGIN("Update");
dart::dynamics::Joint *dtJoint = this->dataPtr->skel->getRootJoint();
if (dtJoint == nullptr)
{
gzerr << "Failed to find root joint of DART skeleton\n";
}
// A free (root) joint won't be in the Gazebo model, so handle it seperately.
auto dtFreeJoint = dynamic_cast<dart::dynamics::FreeJoint *>(dtJoint);
if (dtFreeJoint != nullptr)
{
// Set skeleton pose
dtFreeJoint->setTransform(
physics::DARTTypes::ConvPose(this->dataPtr->model->WorldPose()));
// Get model velocity
ignition::math::Vector3d linVel = this->dataPtr->model->WorldLinearVel();
ignition::math::Vector3d angVel = this->dataPtr->model->WorldAngularVel();
// Set skeleton velocity
dtFreeJoint->setLinearVelocity(
Eigen::Vector3d(linVel.X(), linVel.Y(), linVel.Z()));
dtFreeJoint->setAngularVelocity(
Eigen::Vector3d(angVel.X(), angVel.Y(), angVel.Z()));
}
// Set skeleton joint positions and velocities
physics::Joint_V joints = this->dataPtr->model->GetJoints();
for (auto joint : joints)
{
dtJoint = this->dataPtr->skel->getJoint(joint->GetName());
for (size_t i = 0; i < joint->DOF(); ++i)
{
dtJoint->setPosition(i, joint->Position(i));
dtJoint->setVelocity(i, joint->GetVelocity(i));
}
}
// Gravity compensation
Eigen::VectorXd forces = this->dataPtr->skel->getCoriolisAndGravityForces();
for (auto joint : joints)
{
dtJoint = this->dataPtr->skel->getJoint(joint->GetName());
for (size_t i = 0; i < joint->DOF(); ++i)
{
joint->SetForce(i, forces[dtJoint->getIndexInSkeleton(i)]);
}
}
IGN_PROFILE_END();
}
/////////////////////////////////////////////////
void GravityCompensationPlugin::OnPhysicsMsg(ConstPhysicsPtr &_msg)
{
if (_msg->has_gravity())
{
ignition::math::Vector3d g = msgs::ConvertIgn(_msg->gravity());
this->dataPtr->skel->setGravity(Eigen::Vector3d(g.X(), g.Y(), g.Z()));
}
}
| 29.98062 | 80 | 0.634777 | [
"model"
] |
580d2b29842328ca158d8f72dbbc94546e8f83fd | 3,554 | cpp | C++ | example_objectDetection/src/ofApp.cpp | natxopedreira/ofxTensorFlow2 | a8ef10fa3380e2d55bbd3c7cccaa363d9c7ba9ad | [
"BSD-2-Clause"
] | null | null | null | example_objectDetection/src/ofApp.cpp | natxopedreira/ofxTensorFlow2 | a8ef10fa3380e2d55bbd3c7cccaa363d9c7ba9ad | [
"BSD-2-Clause"
] | null | null | null | example_objectDetection/src/ofApp.cpp | natxopedreira/ofxTensorFlow2 | a8ef10fa3380e2d55bbd3c7cccaa363d9c7ba9ad | [
"BSD-2-Clause"
] | null | null | null | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
model.load("model");
img_dog.load(ofToDataPath("dog.jpg"));
vector<string> inputs{"serving_default_input_tensor:0"};
vector<string> outputs{"StatefulPartitionedCall:0",
"StatefulPartitionedCall:1",
"StatefulPartitionedCall:2",
"StatefulPartitionedCall:3"};
model.setup(inputs,outputs);
//std::string path(ofToDataPath("dog.jpg"));
//auto input = cppflow::decode_jpeg(cppflow::read_file(path));
auto input = ofxTF2::pixelsToTensor(img_dog.getPixels());
input = cppflow::expand_dims(input, 0);
auto output = model.runMultiModel({input});
cout << output.size() << endl;
auto detection_boxes = output[0];
auto detection_classes = output[1];
auto detection_scores = output[2];
auto num_detections = output[3];
ofxTF2::tensorToVector(detection_boxes, detection_boxes_vector);
ofxTF2::tensorToVector(detection_classes, detection_classes_vector);
ofxTF2::tensorToVector(detection_scores, detection_scores_vector);
ofxTF2::tensorToVector(num_detections, num_detections_vector);
cout << "detection_boxes " << detection_boxes << endl;
cout << "detection_classes " << detection_classes << endl;
cout << "detection_scores " << detection_scores << endl;
cout << "num_detections " << num_detections << endl;
}
//--------------------------------------------------------------
void ofApp::update(){
// start & stop the model
}
//--------------------------------------------------------------
void ofApp::draw(){
img_dog.draw(0,0);
ofPushStyle();
ofSetColor(ofColor::red);
for(int i = 0; i < detection_scores_vector.size(); i++){
ofNoFill();
if(detection_scores_vector[i]>0.5){
int py = detection_boxes_vector[i*4] * img_dog.getHeight();
int px = detection_boxes_vector[i*4+1] * img_dog.getWidth();
int pheight = detection_boxes_vector[i*4+2] * img_dog.getHeight() - py;
int pwidth = detection_boxes_vector[i*4+3] * img_dog.getWidth() - px;
ofDrawRectangle(px, py, pwidth, pheight);
}
}
ofPopStyle();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 27.338462 | 83 | 0.47749 | [
"vector",
"model"
] |
5812b5bb3275bc9001ab6cf7d1af9380c70aa8e6 | 151 | cpp | C++ | shape_wrapper.cpp | DreamingNight/ModernCppPractice | 97a1496537ff2ba7df060f5351f87a815e203161 | [
"MIT"
] | null | null | null | shape_wrapper.cpp | DreamingNight/ModernCppPractice | 97a1496537ff2ba7df060f5351f87a815e203161 | [
"MIT"
] | null | null | null | shape_wrapper.cpp | DreamingNight/ModernCppPractice | 97a1496537ff2ba7df060f5351f87a815e203161 | [
"MIT"
] | null | null | null | class shape {};
class circle : public shape {};
class triangle : public shape {};
class shape_wrapper {
public:
explicit shape_wrapper(shape *ptr)
} | 18.875 | 36 | 0.721854 | [
"shape"
] |
58140dd89651c76fd9a74f92a5830187bc1fe40c | 3,888 | cpp | C++ | Engine/source/EtRendering/MaterialSystem/MaterialData.cpp | NeroBurner/ETEngine | 3fe039ff65cd1355957bcfce3f851fa411a86d94 | [
"MIT"
] | null | null | null | Engine/source/EtRendering/MaterialSystem/MaterialData.cpp | NeroBurner/ETEngine | 3fe039ff65cd1355957bcfce3f851fa411a86d94 | [
"MIT"
] | null | null | null | Engine/source/EtRendering/MaterialSystem/MaterialData.cpp | NeroBurner/ETEngine | 3fe039ff65cd1355957bcfce3f851fa411a86d94 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "MaterialData.h"
#include "MaterialDescriptor.h"
#include <EtCore/Reflection/Serialization.h>
#include <EtCore/FileSystem/FileUtil.h>
namespace et {
namespace render {
//==========
// Material
//==========
// reflection
//////////////
RTTR_REGISTRATION
{
rttr::registration::enumeration<Material::E_DrawType>("E_DrawType") (
rttr::value("Opaque", Material::E_DrawType::Opaque),
rttr::value("AlphaBlend", Material::E_DrawType::AlphaBlend),
rttr::value("Custom", Material::E_DrawType::Custom));
BEGIN_REGISTER_POLYMORPHIC_CLASS(MaterialAsset, "material asset")
.property("draw type", &MaterialAsset::m_DrawType)
END_REGISTER_POLYMORPHIC_CLASS(MaterialAsset, core::I_Asset);
}
DEFINE_FORCED_LINKING(MaterialAsset) // force the material asset class to be linked
//--------------------------
// Material::c-tor
//
// Construct material, set up vertex info etc
//
Material::Material(AssetPtr<ShaderData> const shader,
E_DrawType const drawType,
T_ParameterBlock const defaultParameters,
std::vector<AssetPtr<TextureData>> const& textureReferences
)
: I_Material()
, m_Shader(shader)
, m_DrawType(drawType)
, m_DefaultParameters(defaultParameters)
, m_TextureReferences(textureReferences)
{
ET_ASSERT(m_Shader != nullptr);
// determine layout flags and locations
std::vector<ShaderData::T_AttributeLocation> const& attributes = m_Shader->GetAttributes();
for (auto it = AttributeDescriptor::s_VertexAttributes.begin(); it != AttributeDescriptor::s_VertexAttributes.end(); ++it)
{
auto const attribIt = std::find_if(attributes.cbegin(), attributes.cend(), [it](ShaderData::T_AttributeLocation const& loc)
{
return it->second.name == loc.second.name;
});
if (attribIt != attributes.cend())
{
m_AttributeLocations.emplace_back(attribIt->first);
m_LayoutFlags |= it->first;
}
}
}
//--------------------------
// Material::d-tor
//
Material::~Material()
{
if (m_DefaultParameters != nullptr)
{
parameters::DestroyBlock(m_DefaultParameters);
}
}
//================
// Material Asset
//================
//---------------------------------
// MaterialAsset::LoadFromMemory
//
// Load shader data from binary asset content
//
bool MaterialAsset::LoadFromMemory(std::vector<uint8> const& data)
{
MaterialDescriptor descriptor;
if (!(core::serialization::DeserializeFromJsonString(core::FileUtil::AsText(data), descriptor)))
{
LOG("MaterialAsset::LoadFromMemory > Failed to deserialize data from a JSON format into a material descriptor", core::LogLevel::Warning);
return false;
}
// extract the shader and texture references
std::vector<AssetPtr<TextureData>> textureRefs;
AssetPtr<ShaderData> shaderRef;
for (I_Asset::Reference const& reference : GetReferences())
{
I_AssetPtr const* const rawAssetPtr = reference.GetAsset();
if (rawAssetPtr->GetType() == typeid(ShaderData))
{
ET_ASSERT(shaderRef == nullptr, "Materials cannot reference more than one shader!");
shaderRef = *static_cast<AssetPtr<ShaderData> const*>(rawAssetPtr);
}
else if (rawAssetPtr->GetType() == typeid(TextureData))
{
textureRefs.push_back(*static_cast<AssetPtr<TextureData> const*>(rawAssetPtr));
}
else
{
ET_ASSERT(false, "unhandled reference type!");
}
}
if (shaderRef == nullptr)
{
LOG("MaterialAsset::LoadFromMemory > Materials must reference a shader!", core::LogLevel::Warning);
return false;
}
// convert to a parameter block
// ideally this should be done before any uniforms are set in the shader
T_ParameterBlock const params = shaderRef->CopyParameterBlock(shaderRef->GetCurrentUniforms());
if (params != nullptr)
{
parameters::ConvertDescriptor(params, descriptor, shaderRef.get(), textureRefs);
}
// Create the material
m_Data = new Material(shaderRef, m_DrawType, params, textureRefs);
return true;
}
} // namespace render
} // namespace et
| 26.44898 | 139 | 0.708848 | [
"render",
"vector"
] |
5814d0904fa27ad851d6b909e1e1a18e7019c280 | 18,889 | cpp | C++ | contracts/eosio.system/voting.cpp | payb-foundation/PayB | 00fa1d6f498c19bb2307ea97ab277de514051b4c | [
"MIT"
] | null | null | null | contracts/eosio.system/voting.cpp | payb-foundation/PayB | 00fa1d6f498c19bb2307ea97ab277de514051b4c | [
"MIT"
] | null | null | null | contracts/eosio.system/voting.cpp | payb-foundation/PayB | 00fa1d6f498c19bb2307ea97ab277de514051b4c | [
"MIT"
] | null | null | null | /**
* @file
* @copyright defined in eos/LICENSE.txt
*/
#include "eosio.system.hpp"
#include <eosiolib/eosio.hpp>
#include <eosiolib/crypto.h>
#include <eosiolib/print.hpp>
#include <eosiolib/datastream.hpp>
#include <eosiolib/serialize.hpp>
#include <eosiolib/multi_index.hpp>
#include <eosiolib/privileged.hpp>
#include <eosiolib/singleton.hpp>
#include <eosiolib/transaction.hpp>
#include <eosio.token/eosio.token.hpp>
#include <algorithm>
#include <cmath>
#define TWELVE_HOURS_US 43200000000
#define SIX_HOURS_US 21600000000
#define ONE_HOUR_US 900000000 // 15 min ***quick test
#define SIX_MINUTES_US 360000000 // debug version
#define TWELVE_MINUTES_US 720000000
#define MAX_PRODUCERS 51
#define TOP_PRODUCERS 21
#define MAX_VOTE_PRODUCERS 30
namespace eosiosystem {
using namespace eosio;
using eosio::indexed_by;
using eosio::const_mem_fun;
using eosio::bytes;
using eosio::print;
using eosio::singleton;
using eosio::transaction;
/**
* This method will create a producer_config and producer_info object for 'producer'
*
* @pre producer is not already registered
* @pre producer to register is an account
* @pre authority of producer to register
*
*/
void system_contract::regproducer( const account_name producer, const eosio::public_key& producer_key, const std::string& url, uint16_t location ) {
eosio_assert( url.size() < 512, "url too long" );
eosio_assert( producer_key != eosio::public_key(), "public key should not be the default value" );
require_auth( producer );
auto prod = _producers.find( producer );
if ( prod != _producers.end() ) {
_producers.modify(prod, producer, [&](producer_info &info) {
auto now = block_timestamp(eosio::time_point(eosio::microseconds(int64_t(current_time()))));
block_timestamp penalty_expiration_time = block_timestamp(info.last_time_kicked.to_time_point() + time_point(hours(int64_t(info.kick_penalty_hours))));
eosio_assert(now.slot > penalty_expiration_time.slot,
std::string("Producer is not allowed to register at this time. Please fix your node and try again later in: "
+ std::to_string( uint32_t((penalty_expiration_time.slot - now.slot) / 2 ))
+ " seconds").c_str());
info.producer_key = producer_key;
info.url = url;
info.location = location;
info.is_active = true;
});
} else {
_producers.emplace(producer, [&](producer_info &info) {
info.owner = producer;
info.total_votes = 0;
info.producer_key = producer_key;
info.is_active = true;
info.url = url;
info.location = location;
});
}
}
void system_contract::unregprod( const account_name producer ) {
require_auth( producer );
const auto& prod = _producers.get( producer, "producer not found" );
_producers.modify( prod, 0, [&]( producer_info& info ) {
info.deactivate();
});
}
void system_contract::set_bps_rotation(account_name bpOut, account_name sbpIn) {
_grotations.bp_currently_out = bpOut;
_grotations.sbp_currently_in = sbpIn;
}
void system_contract::update_rotation_time(block_timestamp block_time) {
_grotations.last_rotation_time = block_time;
_grotations.next_rotation_time = block_timestamp(block_time.to_time_point() + time_point(microseconds(TWELVE_HOURS_US)));
}
void system_contract::restart_missed_blocks_per_rotation(std::vector<eosio::producer_key> prods) {
// restart all missed blocks to bps and sbps
for (size_t i = 0; i < prods.size(); i++) {
auto bp_name = prods[i].producer_name;
auto pitr = _producers.find(bp_name);
if (pitr != _producers.end()) {
_producers.modify(pitr, 0, [&](auto &p) {
if (p.times_kicked > 0 && p.missed_blocks_per_rotation == 0) {
p.times_kicked--;
}
p.lifetime_missed_blocks += p.missed_blocks_per_rotation;
p.missed_blocks_per_rotation = 0;
});
}
}
}
//TODO: Add _grotations.is_rotation_active, that way this feature can be toggled.
void system_contract::update_elected_producers( block_timestamp block_time ) {
_gstate.last_producer_schedule_update = block_time;
auto idx = _producers.get_index<N(prototalvote)>();
uint32_t totalActiveVotedProds = uint32_t(std::distance(idx.begin(), idx.end()));
totalActiveVotedProds = totalActiveVotedProds > MAX_PRODUCERS ? MAX_PRODUCERS : totalActiveVotedProds;
std::vector<eosio::producer_key> prods;
prods.reserve(size_t(totalActiveVotedProds));
//add active producers with vote > 0
for ( auto it = idx.cbegin(); it != idx.cend() && prods.size() < totalActiveVotedProds && it->total_votes > 0 && it->active(); ++it ) {
prods.emplace_back( eosio::producer_key{it->owner, it->producer_key} );
}
totalActiveVotedProds = prods.size();
vector<eosio::producer_key>::iterator it_bp = prods.end();
vector<eosio::producer_key>::iterator it_sbp = prods.end();
if (_grotations.next_rotation_time <= block_time) {
if (totalActiveVotedProds > TOP_PRODUCERS) {
_grotations.bp_out_index = _grotations.bp_out_index >= TOP_PRODUCERS - 1 ? 0 : _grotations.bp_out_index + 1;
_grotations.sbp_in_index = _grotations.sbp_in_index >= totalActiveVotedProds - 1 ? TOP_PRODUCERS : _grotations.sbp_in_index + 1;
account_name bp_name = prods[_grotations.bp_out_index].producer_name;
account_name sbp_name = prods[_grotations.sbp_in_index].producer_name;
it_bp = prods.begin() + int32_t(_grotations.bp_out_index);
it_sbp = prods.begin() + int32_t(_grotations.sbp_in_index);
set_bps_rotation(bp_name, sbp_name);
}
update_rotation_time(block_time);
restart_missed_blocks_per_rotation(prods);
}
else {
if(_grotations.bp_currently_out != 0 && _grotations.sbp_currently_in != 0) {
auto bp_name = _grotations.bp_currently_out;
it_bp = std::find_if(prods.begin(), prods.end(), [&bp_name](const eosio::producer_key &g) {
return g.producer_name == bp_name;
});
auto sbp_name = _grotations.sbp_currently_in;
it_sbp = std::find_if(prods.begin(), prods.end(), [&sbp_name](const eosio::producer_key &g) {
return g.producer_name == sbp_name;
});
auto _bp_index = std::distance(prods.begin(), it_bp);
auto _sbp_index = std::distance(prods.begin(), it_sbp);
if(it_bp == prods.end() || it_sbp == prods.end()) {
set_bps_rotation(0, 0);
if(totalActiveVotedProds < TOP_PRODUCERS) {
_grotations.bp_out_index = TOP_PRODUCERS;
_grotations.sbp_in_index = MAX_PRODUCERS+1;
}
} else if (totalActiveVotedProds > TOP_PRODUCERS && (!is_in_range(_bp_index, 0, TOP_PRODUCERS) || !is_in_range(_sbp_index, TOP_PRODUCERS, MAX_PRODUCERS))) {
set_bps_rotation(0, 0);
it_bp = prods.end();
it_sbp = prods.end();
}
}
}
std::vector<eosio::producer_key> top_producers;
//Rotation
if(it_bp != prods.end() && it_sbp != prods.end()) {
for ( auto pIt = prods.begin(); pIt != prods.end(); ++pIt) {
auto i = std::distance(prods.begin(), pIt);
// print("\ni-> ", i);
if(i > TOP_PRODUCERS - 1) break;
if(pIt->producer_name == it_bp->producer_name) {
// print("\nprod sbp added to schedule -> ", name{it_sbp->producer_name});
top_producers.emplace_back(*it_sbp);
} else {
// print("\nprod bp added to schedule -> ", name{pIt->producer_name});
top_producers.emplace_back(*pIt);
}
}
}
else {
top_producers = prods;
if(prods.size() > TOP_PRODUCERS) top_producers.resize(TOP_PRODUCERS);
else top_producers.resize(prods.size());
}
// if ( top_producers.size() < _gstate.last_producer_schedule_size ) {
// return;
// }
// sort by producer name
std::sort( top_producers.begin(), top_producers.end() );
bytes packed_schedule = pack(top_producers);
auto schedule_version = set_proposed_producers( packed_schedule.data(), packed_schedule.size());
if (schedule_version >= 0) {
_gstate.last_proposed_schedule_update = block_time;
_gschedule_metrics.producers_metric.erase(_gschedule_metrics.producers_metric.begin(), _gschedule_metrics.producers_metric.end());
print("\n**new schedule was proposed**");
std::vector<producer_metric> psm;
std::for_each(top_producers.begin(), top_producers.end(), [&psm](auto &tp) {
auto bp_name = tp.producer_name;
psm.emplace_back(producer_metric{ bp_name, 12 });
});
_gschedule_metrics.producers_metric = psm;
_gstate.last_producer_schedule_size = static_cast<decltype(_gstate.last_producer_schedule_size)>(top_producers.size());
}
}
/*
* This function caculates the inverse weight voting.
* The maximum weighted vote will be reached if an account votes for the maximum number of registered producers (up to 30 in total).
*/
double system_contract::inverse_vote_weight(double staked, double amountVotedProducers) {
if (amountVotedProducers == 0.0) {
return 0;
}
double percentVoted = amountVotedProducers / MAX_VOTE_PRODUCERS;
double voteWeight = (sin(M_PI * percentVoted - M_PI_2) + 1.0) / 2.0;
return (voteWeight * staked);
}
bool system_contract::is_in_range(int32_t index, int32_t low_bound, int32_t up_bound) {
return index >= low_bound && index < up_bound;
}
/**
* @pre producers must be sorted from lowest to highest and must be registered and active
* @pre if proxy is set then no producers can be voted for
* @pre if proxy is set then proxy account must exist and be registered as a proxy
* @pre every listed producer or proxy must have been previously registered
* @pre voter must authorize this action
* @pre voter must have previously staked some EOS for voting
* @pre voter->staked must be up to date
*
* @post every producer previously voted for will have vote reduced by previous vote weight
* @post every producer newly voted for will have vote increased by new vote amount
* @post prior proxy will proxied_vote_weight decremented by previous vote weight
* @post new proxy will proxied_vote_weight incremented by new vote weight
*
* If voting for a proxy, the producer votes will not change until the proxy updates their own vote.
*/
void system_contract::voteproducer(const account_name voter_name, const account_name proxy, const std::vector<account_name> &producers) {
require_auth(voter_name);
update_votes(voter_name, proxy, producers, true);
}
void system_contract::update_votes( const account_name voter_name, const account_name proxy, const std::vector<account_name>& producers, bool voting ) {
//validate input
if ( proxy ) {
eosio_assert( producers.size() == 0, "cannot vote for producers and proxy at same time" );
eosio_assert( voter_name != proxy, "cannot proxy to self" );
require_recipient( proxy );
} else {
eosio_assert( producers.size() <= MAX_VOTE_PRODUCERS, "attempt to vote for too many producers" );
for( size_t i = 1; i < producers.size(); ++i ) {
eosio_assert( producers[i-1] < producers[i], "producer votes must be unique and sorted" );
}
}
auto voter = _voters.find(voter_name);
eosio_assert( voter != _voters.end(), "user must stake before they can vote" ); /// staking creates voter object
eosio_assert( !proxy || !voter->is_proxy, "account registered as a proxy is not allowed to use a proxy" );
auto totalStaked = voter->staked;
if(voter->is_proxy){
totalStaked += voter->proxied_vote_weight;
}
// when unvoting, set the stake used for calculations to 0
// since it is the equivalent to retracting your stake
if(voting && !proxy && producers.size() == 0){
totalStaked = 0;
}
// when a voter or a proxy votes or changes stake, the total_activated stake should be re-calculated
// any proxy stake handling should be done when the proxy votes or on weight propagation
// if(_gstate.thresh_activated_stake_time == 0 && !proxy && !voter->proxy){
if(!proxy && !voter->proxy){
_gstate.total_activated_stake += totalStaked - voter->last_stake;
}
auto new_vote_weight = inverse_vote_weight((double )totalStaked, (double) producers.size());
boost::container::flat_map<account_name, pair<double, bool /*new*/> > producer_deltas;
// print("\n Voter : ", voter->last_stake, " = ", voter->last_vote_weight, " = ", proxy, " = ", producers.size(), " = ", totalStaked, " = ", new_vote_weight);
//Voter from second vote
if ( voter->last_stake > 0 ) {
//if voter account has set proxy to another voter account
if( voter->proxy ) {
auto old_proxy = _voters.find( voter->proxy );
eosio_assert( old_proxy != _voters.end(), "old proxy not found" ); //data corruption
_voters.modify( old_proxy, 0, [&]( auto& vp ) {
vp.proxied_vote_weight -= voter->last_stake;
});
// propagate weight here only when switching proxies
// otherwise propagate happens in the case below
if( proxy != voter->proxy ) {
_gstate.total_activated_stake += totalStaked - voter->last_stake;
propagate_weight_change( *old_proxy );
}
} else {
for( const auto& p : voter->producers ) {
auto& d = producer_deltas[p];
d.first -= voter->last_vote_weight;
d.second = false;
}
}
}
if( proxy ) {
auto new_proxy = _voters.find( proxy );
eosio_assert( new_proxy != _voters.end(), "invalid proxy specified" ); //if ( !voting ) { data corruption } else { wrong vote }
eosio_assert( !voting || new_proxy->is_proxy, "proxy not found" );
_voters.modify( new_proxy, 0, [&]( auto& vp ) {
vp.proxied_vote_weight += voter->staked;
});
if((*new_proxy).last_vote_weight > 0){
_gstate.total_activated_stake += totalStaked - voter->last_stake;
propagate_weight_change( *new_proxy );
}
} else {
if( new_vote_weight >= 0 ) {
for( const auto& p : producers ) {
auto& d = producer_deltas[p];
d.first += new_vote_weight;
d.second = true;
}
}
}
for( const auto& pd : producer_deltas ) {
auto pitr = _producers.find( pd.first );
if( pitr != _producers.end() ) {
eosio_assert( !voting || pitr->active() || !pd.second.second /* not from new set */, "producer is not currently registered" );
_producers.modify( pitr, 0, [&]( auto& p ) {
p.total_votes += pd.second.first;
if ( p.total_votes < 0 ) { // floating point arithmetics can give small negative numbers
p.total_votes = 0;
}
_gstate.total_producer_vote_weight += pd.second.first;
});
} else {
eosio_assert( !pd.second.second /* not from new set */, "producer is not registered" ); //data corruption
}
}
_voters.modify( voter, 0, [&]( auto& av ) {
av.last_vote_weight = new_vote_weight;
av.last_stake = int64_t(totalStaked);
av.producers = producers;
av.proxy = proxy;
});
}
/**
* An account marked as a proxy can vote with the weight of other accounts which
* have selected it as a proxy. Other accounts must refresh their voteproducer to
* update the proxy's weight.
*
* @param isproxy - true if proxy wishes to vote on behalf of others, false otherwise
* @pre proxy must have something staked (existing row in voters table)
* @pre new state must be different than current state
*/
void system_contract::regproxy( const account_name proxy, bool isproxy ) {
require_auth( proxy );
auto pitr = _voters.find(proxy);
if ( pitr != _voters.end() ) {
eosio_assert( isproxy != pitr->is_proxy, "action has no effect" );
eosio_assert( !isproxy || !pitr->proxy, "account that uses a proxy is not allowed to become a proxy" );
_voters.modify( pitr, 0, [&]( auto& p ) {
p.is_proxy = isproxy;
});
update_votes(pitr->owner, pitr->proxy, pitr->producers, true);
} else {
_voters.emplace( proxy, [&]( auto& p ) {
p.owner = proxy;
p.is_proxy = isproxy;
});
}
}
void system_contract::propagate_weight_change(const voter_info &voter) {
eosio_assert( voter.proxy == 0 || !voter.is_proxy, "account registered as a proxy is not allowed to use a proxy");
auto totalStake = voter.staked;
if(voter.is_proxy){
totalStake += voter.proxied_vote_weight;
}
double new_weight = inverse_vote_weight((double)totalStake, voter.producers.size());
double delta = new_weight - voter.last_vote_weight;
if (voter.proxy) { // this part should never happen since the function is called only on proxies
if(voter.last_stake != totalStake){
auto &proxy = _voters.get(voter.proxy, "proxy not found"); // data corruption
_voters.modify(proxy, 0, [&](auto &p) {
p.proxied_vote_weight += totalStake - voter.last_stake;
});
propagate_weight_change(proxy);
}
} else {
for (auto acnt : voter.producers) {
auto &pitr = _producers.get(acnt, "producer not found"); // data corruption
_producers.modify(pitr, 0, [&](auto &p) {
p.total_votes += delta;
_gstate.total_producer_vote_weight += delta;
});
}
}
_voters.modify(voter, 0, [&](auto &v) {
v.last_vote_weight = new_weight;
v.last_stake = totalStake;
});
}
} /// namespace eosiosystem
| 41.423246 | 166 | 0.622214 | [
"object",
"vector"
] |
58184cd7cd718915428b9bbad784121b5711c4c9 | 34,041 | cpp | C++ | clicache/src/DataInput.cpp | mcmellawatt/geode-native | 53315985c4386e6781473c5713d638c8139e3e8e | [
"Apache-2.0"
] | null | null | null | clicache/src/DataInput.cpp | mcmellawatt/geode-native | 53315985c4386e6781473c5713d638c8139e3e8e | [
"Apache-2.0"
] | null | null | null | clicache/src/DataInput.cpp | mcmellawatt/geode-native | 53315985c4386e6781473c5713d638c8139e3e8e | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "begin_native.hpp"
#include <geode/Cache.hpp>
#include <GeodeTypeIdsImpl.hpp>
#include "SerializationRegistry.hpp"
#include "CacheRegionHelper.hpp"
#include "CacheImpl.hpp"
#include "DataInputInternal.hpp"
#include "end_native.hpp"
#include "DataInput.hpp"
#include "Cache.hpp"
#include "CacheableString.hpp"
#include "CacheableHashMap.hpp"
#include "CacheableStack.hpp"
#include "CacheableVector.hpp"
#include "CacheableArrayList.hpp"
#include "CacheableIDentityHashMap.hpp"
#include "CacheableDate.hpp"
#include "CacheableObjectArray.hpp"
#include "Serializable.hpp"
#include "impl/PdxHelper.hpp"
#include "impl/PdxWrapper.hpp"
using namespace System;
using namespace System::IO;
using namespace apache::geode::client;
namespace Apache
{
namespace Geode
{
namespace Client
{
using namespace msclr::interop;
namespace native = apache::geode::client;
DataInput::DataInput(System::Byte* buffer, size_t size, Apache::Geode::Client::Cache^ cache)
{
m_ispdxDesrialization = false;
m_isRootObjectPdx = false;
m_cache = cache;
if (buffer != nullptr && size > 0) {
_GF_MG_EXCEPTION_TRY2
m_nativeptr = gcnew native_conditional_unique_ptr<native::DataInput>(cache->GetNative()->createDataInput(buffer, size));
m_cursor = 0;
m_isManagedObject = false;
m_forStringDecode = gcnew array<Char>(100);
try
{
m_buffer = const_cast<System::Byte*>(m_nativeptr->get()->currentBufferPosition());
m_bufferLength = m_nativeptr->get()->getBytesRemaining();
}
finally
{
GC::KeepAlive(m_nativeptr);
}
_GF_MG_EXCEPTION_CATCH_ALL2
}
else {
throw gcnew IllegalArgumentException("DataInput.ctor(): "
"provided buffer is null or empty");
}
}
DataInput::DataInput(array<Byte>^ buffer, Apache::Geode::Client::Cache^ cache)
{
m_ispdxDesrialization = false;
m_isRootObjectPdx = false;
m_cache = cache;
if (buffer != nullptr && buffer->Length > 0) {
_GF_MG_EXCEPTION_TRY2
System::Int32 len = buffer->Length;
_GEODE_NEW(m_buffer, System::Byte[len]);
pin_ptr<const Byte> pin_buffer = &buffer[0];
memcpy(m_buffer, (void*)pin_buffer, len);
m_nativeptr = gcnew native_conditional_unique_ptr<native::DataInput>(m_cache->GetNative()->createDataInput(m_buffer, len));
m_cursor = 0;
m_isManagedObject = false;
m_forStringDecode = gcnew array<Char>(100);
try
{
m_buffer = const_cast<System::Byte*>(m_nativeptr->get()->currentBufferPosition());
m_bufferLength = m_nativeptr->get()->getBytesRemaining();
}
finally
{
GC::KeepAlive(m_nativeptr);
}
_GF_MG_EXCEPTION_CATCH_ALL2
}
else {
throw gcnew IllegalArgumentException("DataInput.ctor(): "
"provided buffer is null or empty");
}
}
DataInput::DataInput(array<Byte>^ buffer, size_t len, Apache::Geode::Client::Cache^ cache)
{
m_ispdxDesrialization = false;
m_isRootObjectPdx = false;
m_cache = cache;
if (buffer != nullptr) {
if (len == 0 || (System::Int32)len > buffer->Length) {
throw gcnew IllegalArgumentException(String::Format(
"DataInput.ctor(): given length {0} is zero or greater than "
"size of buffer {1}", len, buffer->Length));
}
//m_bytes = gcnew array<Byte>(len);
//System::Array::Copy(buffer, 0, m_bytes, 0, len);
_GF_MG_EXCEPTION_TRY2
_GEODE_NEW(m_buffer, System::Byte[len]);
pin_ptr<const Byte> pin_buffer = &buffer[0];
memcpy(m_buffer, (void*)pin_buffer, len);
m_nativeptr = gcnew native_conditional_unique_ptr<native::DataInput>(m_cache->GetNative()->createDataInput(m_buffer, len));
try
{
m_buffer = const_cast<System::Byte*>(m_nativeptr->get()->currentBufferPosition());
m_bufferLength = m_nativeptr->get()->getBytesRemaining();
}
finally
{
GC::KeepAlive(m_nativeptr);
}
_GF_MG_EXCEPTION_CATCH_ALL2
}
else {
throw gcnew IllegalArgumentException("DataInput.ctor(): "
"provided buffer is null");
}
}
void DataInput::CheckBufferSize(int size)
{
if ((unsigned int)(m_cursor + size) > m_bufferLength)
{
Log::Debug("DataInput::CheckBufferSize m_cursor:" + m_cursor + " size:" + size + " m_bufferLength:" + m_bufferLength);
throw gcnew OutOfRangeException("DataInput: attempt to read beyond buffer");
}
}
DataInput^ DataInput::GetClone()
{
return gcnew DataInput(m_buffer, m_bufferLength, m_cache);
}
Byte DataInput::ReadByte()
{
CheckBufferSize(1);
return m_buffer[m_cursor++];
}
SByte DataInput::ReadSByte()
{
CheckBufferSize(1);
return m_buffer[m_cursor++];
}
bool DataInput::ReadBoolean()
{
CheckBufferSize(1);
Byte val = m_buffer[m_cursor++];
if (val == 1)
return true;
else
return false;
}
Char DataInput::ReadChar()
{
CheckBufferSize(2);
Char data = m_buffer[m_cursor++];
data = (data << 8) | m_buffer[m_cursor++];
return data;
}
array<Byte>^ DataInput::ReadBytes()
{
System::Int32 length;
length = ReadArrayLen();
if (length >= 0) {
if (length == 0)
return gcnew array<Byte>(0);
else {
array<Byte>^ bytes = ReadBytesOnly(length);
return bytes;
}
}
return nullptr;
}
int DataInput::ReadArrayLen()
{
int code;
int len;
code = Convert::ToInt32(ReadByte());
if (code == 0xFF) {
len = -1;
}
else {
unsigned int result = code;
if (result > 252) { // 252 is java's ((byte)-4 && 0xFF)
if (code == 0xFE) {
result = ReadUInt16();
}
else if (code == 0xFD) {
result = ReadUInt32();
}
else {
throw gcnew IllegalStateException("unexpected array length code");
}
//TODO:: illegal length
}
len = (int)result;
}
return len;
}
array<SByte>^ DataInput::ReadSBytes()
{
System::Int32 length;
length = ReadArrayLen();
if (length > -1) {
if (length == 0)
return gcnew array<SByte>(0);
else {
array<SByte>^ bytes = ReadSBytesOnly(length);
return bytes;
}
}
return nullptr;
}
array<Byte>^ DataInput::ReadBytesOnly(System::UInt32 len)
{
if (len > 0) {
CheckBufferSize(len);
array<Byte>^ bytes = gcnew array<Byte>(len);
for (unsigned int i = 0; i < len; i++)
bytes[i] = m_buffer[m_cursor++];
return bytes;
}
return nullptr;
}
void DataInput::ReadBytesOnly(array<Byte> ^ buffer, int offset, int count)
{
if (count > 0) {
CheckBufferSize((System::UInt32)count);
for (int i = 0; i < count; i++)
buffer[offset + i] = m_buffer[m_cursor++];
}
}
array<SByte>^ DataInput::ReadSBytesOnly(System::UInt32 len)
{
if (len > 0) {
CheckBufferSize(len);
array<SByte>^ bytes = gcnew array<SByte>(len);
for (unsigned int i = 0; i < len; i++)
bytes[i] = (SByte)m_buffer[m_cursor++];
return bytes;
}
return nullptr;
}
System::UInt16 DataInput::ReadUInt16()
{
CheckBufferSize(2);
System::UInt16 data = m_buffer[m_cursor++];
data = (data << 8) | m_buffer[m_cursor++];
return data;
}
System::UInt32 DataInput::ReadUInt32()
{
CheckBufferSize(4);
System::UInt32 data = m_buffer[m_cursor++];
data = (data << 8) | m_buffer[m_cursor++];
data = (data << 8) | m_buffer[m_cursor++];
data = (data << 8) | m_buffer[m_cursor++];
return data;
}
System::UInt64 DataInput::ReadUInt64()
{
System::UInt64 data;
CheckBufferSize(8);
data = m_buffer[m_cursor++];
data = (data << 8) | m_buffer[m_cursor++];
data = (data << 8) | m_buffer[m_cursor++];
data = (data << 8) | m_buffer[m_cursor++];
data = (data << 8) | m_buffer[m_cursor++];
data = (data << 8) | m_buffer[m_cursor++];
data = (data << 8) | m_buffer[m_cursor++];
data = (data << 8) | m_buffer[m_cursor++];
return data;
}
System::Int16 DataInput::ReadInt16()
{
return ReadUInt16();
}
System::Int32 DataInput::ReadInt32()
{
return ReadUInt32();
}
System::Int64 DataInput::ReadInt64()
{
return ReadUInt64();
}
array<Byte>^ DataInput::ReadReverseBytesOnly(int len)
{
CheckBufferSize(len);
int i = 0;
auto j = m_cursor + len - 1;
array<Byte>^ bytes = gcnew array<Byte>(len);
while (i < len)
{
bytes[i++] = m_buffer[j--];
}
m_cursor += len;
return bytes;
}
float DataInput::ReadFloat()
{
float data;
array<Byte>^ bytes = nullptr;
if (BitConverter::IsLittleEndian)
bytes = ReadReverseBytesOnly(4);
else
bytes = ReadBytesOnly(4);
data = BitConverter::ToSingle(bytes, 0);
return data;
}
double DataInput::ReadDouble()
{
double data;
array<Byte>^ bytes = nullptr;
if (BitConverter::IsLittleEndian)
bytes = ReadReverseBytesOnly(8);
else
bytes = ReadBytesOnly(8);
data = BitConverter::ToDouble(bytes, 0);
return data;
}
String^ DataInput::ReadUTF()
{
int length = ReadUInt16();
CheckBufferSize(length);
String^ str = DecodeBytes(length);
return str;
}
String^ DataInput::ReadUTFHuge()
{
int length = ReadUInt32();
CheckBufferSize(length);
array<Char>^ chArray = gcnew array<Char>(length);
for (int i = 0; i < length; i++)
{
Char ch = ReadByte();
ch = ((ch << 8) | ReadByte());
chArray[i] = ch;
}
String^ str = gcnew String(chArray);
return str;
}
String^ DataInput::ReadASCIIHuge()
{
int length = ReadInt32();
CheckBufferSize(length);
String^ str = DecodeBytes(length);
return str;
}
Object^ DataInput::ReadObject()
{
return ReadInternalObject();
}
/* Object^ DataInput::ReadGenericObject( )
{
return ReadInternalGenericObject();
}*/
Object^ DataInput::ReadDotNetTypes(int8_t typeId)
{
switch (typeId)
{
case apache::geode::client::GeodeTypeIds::CacheableByte:
{
return ReadSByte();
}
case apache::geode::client::GeodeTypeIds::CacheableBoolean:
{
bool obj;
ReadObject(obj);
return obj;
}
case apache::geode::client::GeodeTypeIds::CacheableCharacter:
{
Char obj;
ReadObject(obj);
return obj;
}
case apache::geode::client::GeodeTypeIds::CacheableDouble:
{
Double obj;
ReadObject(obj);
return obj;
}
case apache::geode::client::GeodeTypeIds::CacheableASCIIString:
{
/* CacheableString^ cs = static_cast<CacheableString^>(CacheableString::CreateDeserializable());
cs->FromData(this);
return cs->Value;*/
return ReadUTF();
}
case apache::geode::client::GeodeTypeIds::CacheableASCIIStringHuge:
{
/*CacheableString^ cs = static_cast<CacheableString^>(CacheableString::createDeserializableHuge());
cs->FromData(this);
return cs->Value;*/
return ReadASCIIHuge();
}
case apache::geode::client::GeodeTypeIds::CacheableString:
{
/*CacheableString^ cs = static_cast<CacheableString^>(CacheableString::createUTFDeserializable());
cs->FromData(this);
return cs->Value;*/
return ReadUTF();
}
case apache::geode::client::GeodeTypeIds::CacheableStringHuge:
{
//TODO: need to look all strings types
/*CacheableString^ cs = static_cast<CacheableString^>(CacheableString::createUTFDeserializableHuge());
cs->FromData(this);
return cs->Value;*/
return ReadUTFHuge();
}
case apache::geode::client::GeodeTypeIds::CacheableFloat:
{
float obj;
ReadObject(obj);
return obj;
}
case apache::geode::client::GeodeTypeIds::CacheableInt16:
{
Int16 obj;
ReadObject(obj);
return obj;
}
case apache::geode::client::GeodeTypeIds::CacheableInt32:
{
Int32 obj;
ReadObject(obj);
return obj;
}
case apache::geode::client::GeodeTypeIds::CacheableInt64:
{
Int64 obj;
ReadObject(obj);
return obj;
}
case apache::geode::client::GeodeTypeIds::CacheableDate:
{
CacheableDate^ cd = CacheableDate::Create();
cd->FromData(this);
return cd->Value;
}
case apache::geode::client::GeodeTypeIds::CacheableBytes:
{
return ReadBytes();
}
case apache::geode::client::GeodeTypeIds::CacheableDoubleArray:
{
array<Double>^ obj;
ReadObject(obj);
return obj;
}
case apache::geode::client::GeodeTypeIds::CacheableFloatArray:
{
array<float>^ obj;
ReadObject(obj);
return obj;
}
case apache::geode::client::GeodeTypeIds::CacheableInt16Array:
{
array<Int16>^ obj;
ReadObject(obj);
return obj;
}
case apache::geode::client::GeodeTypeIds::CacheableInt32Array:
{
array<Int32>^ obj;
ReadObject(obj);
return obj;
}
case apache::geode::client::GeodeTypeIds::BooleanArray:
{
array<bool>^ obj;
ReadObject(obj);
return obj;
}
case apache::geode::client::GeodeTypeIds::CharArray:
{
array<Char>^ obj;
ReadObject(obj);
return obj;
}
case apache::geode::client::GeodeTypeIds::CacheableInt64Array:
{
array<Int64>^ obj;
ReadObject(obj);
return obj;
}
case apache::geode::client::GeodeTypeIds::CacheableStringArray:
{
return ReadStringArray();
}
case apache::geode::client::GeodeTypeIds::CacheableHashTable:
{
return ReadHashtable();
}
case apache::geode::client::GeodeTypeIds::CacheableHashMap:
{
CacheableHashMap^ chm = static_cast<CacheableHashMap^>(CacheableHashMap::CreateDeserializable());
chm->FromData(this);
return chm->Value;
}
case apache::geode::client::GeodeTypeIds::CacheableIdentityHashMap:
{
CacheableIdentityHashMap^ chm = static_cast<CacheableIdentityHashMap^>(CacheableIdentityHashMap::CreateDeserializable());
chm->FromData(this);
return chm->Value;
}
case apache::geode::client::GeodeTypeIds::CacheableVector:
{
/*CacheableVector^ cv = static_cast<CacheableVector^>(CacheableVector::CreateDeserializable());
cv->FromData(this);
return cv->Value;*/
int len = ReadArrayLen();
System::Collections::ArrayList^ retA = gcnew System::Collections::ArrayList(len);
for (int i = 0; i < len; i++)
{
retA->Add(this->ReadObject());
}
return retA;
}
case apache::geode::client::GeodeTypeIds::CacheableArrayList:
{
/*CacheableArrayList^ cv = static_cast<CacheableArrayList^>(CacheableArrayList::CreateDeserializable());
cv->FromData(this);
return cv->Value;*/
int len = ReadArrayLen();
System::Collections::Generic::List<Object^>^ retA = gcnew System::Collections::Generic::List<Object^>(len);
for (int i = 0; i < len; i++)
{
retA->Add(this->ReadObject());
}
return retA;
}
case apache::geode::client::GeodeTypeIds::CacheableLinkedList:
{
/*CacheableArrayList^ cv = static_cast<CacheableArrayList^>(CacheableArrayList::CreateDeserializable());
cv->FromData(this);
return cv->Value;*/
int len = ReadArrayLen();
System::Collections::Generic::LinkedList<Object^>^ retA = gcnew System::Collections::Generic::LinkedList<Object^>();
for (int i = 0; i < len; i++)
{
retA->AddLast(this->ReadObject());
}
return retA;
}
case apache::geode::client::GeodeTypeIds::CacheableStack:
{
CacheableStack^ cv = static_cast<CacheableStack^>(CacheableStack::CreateDeserializable());
cv->FromData(this);
return cv->Value;
}
default:
return nullptr;
}
}
Object^ DataInput::ReadInternalObject()
{
try
{
//Log::Debug("DataInput::ReadInternalObject m_cursor " + m_cursor);
bool findinternal = false;
int8_t typeId = ReadByte();
System::Int64 compId = typeId;
TypeFactoryMethodGeneric^ createType = nullptr;
if (compId == GeodeTypeIds::NullObj) {
return nullptr;
}
else if (compId == GeodeClassIds::PDX)
{
//cache current state and reset after reading pdx object
auto cacheCursor = m_cursor;
System::Byte* cacheBuffer = m_buffer;
auto cacheBufferLength = m_bufferLength;
Object^ ret = Internal::PdxHelper::DeserializePdx(this, false, CacheRegionHelper::getCacheImpl(m_cache->GetNative().get())->getSerializationRegistry().get());
auto tmp = m_nativeptr->get()->getBytesRemaining();
m_cursor = cacheBufferLength - tmp;
m_buffer = cacheBuffer;
m_bufferLength = cacheBufferLength;
m_nativeptr->get()->rewindCursor(m_cursor);
if (ret != nullptr)
{
Apache::Geode::Client::PdxWrapper^ pdxWrapper = dynamic_cast<Apache::Geode::Client::PdxWrapper^>(ret);
if (pdxWrapper != nullptr)
{
return pdxWrapper->GetObject();
}
}
return ret;
}
else if (compId == GeodeClassIds::PDX_ENUM)
{
int8_t dsId = ReadByte();
int tmp = ReadArrayLen();
int enumId = (dsId << 24) | (tmp & 0xFFFFFF);
Object^ enumVal = Internal::PdxHelper::GetEnum(enumId, m_cache);
return enumVal;
}
else if (compId == GeodeTypeIds::CacheableNullString) {
//return SerializablePtr(CacheableString::createDeserializable());
//TODO::
return nullptr;
}
else if (compId == GeodeTypeIdsImpl::CacheableUserData) {
int8_t classId = ReadByte();
//compId |= ( ( (System::Int64)classId ) << 32 );
compId = (System::Int64)classId;
}
else if (compId == GeodeTypeIdsImpl::CacheableUserData2) {
System::Int16 classId = ReadInt16();
//compId |= ( ( (System::Int64)classId ) << 32 );
compId = (System::Int64)classId;
}
else if (compId == GeodeTypeIdsImpl::CacheableUserData4) {
System::Int32 classId = ReadInt32();
//compId |= ( ( (System::Int64)classId ) << 32 );
compId = (System::Int64)classId;
}
else if (compId == GeodeTypeIdsImpl::FixedIDByte) {//TODO: need to verify again
int8_t fixedId = ReadByte();
compId = fixedId;
findinternal = true;
}
else if (compId == GeodeTypeIdsImpl::FixedIDShort) {
System::Int16 fixedId = ReadInt16();
compId = fixedId;
findinternal = true;
}
else if (compId == GeodeTypeIdsImpl::FixedIDInt) {
System::Int32 fixedId = ReadInt32();
compId = fixedId;
findinternal = true;
}
if (findinternal) {
compId += 0x80000000;
createType = m_cache->TypeRegistry->GetManagedDelegateGeneric((System::Int64)compId);
}
else {
createType = m_cache->TypeRegistry->GetManagedDelegateGeneric(compId);
if (createType == nullptr)
{
Object^ retVal = ReadDotNetTypes(typeId);
if (retVal != nullptr)
return retVal;
if (m_ispdxDesrialization && typeId == apache::geode::client::GeodeTypeIds::CacheableObjectArray)
{//object array and pdxSerialization
return readDotNetObjectArray();
}
compId += 0x80000000;
createType = m_cache->TypeRegistry->GetManagedDelegateGeneric(compId);
/*if (createType == nullptr)
{
//TODO:: final check for user type if its not in cache
compId -= 0x80000000;
createType = Serializable::GetManagedDelegate(compId);
}*/
}
}
if (createType == nullptr) {
throw gcnew IllegalStateException("Unregistered typeId " + typeId + " in deserialization, aborting.");
}
bool isPdxDeserialization = m_ispdxDesrialization;
m_ispdxDesrialization = false;//for nested objects
IGeodeSerializable^ newObj = createType();
newObj->FromData(this);
m_ispdxDesrialization = isPdxDeserialization;
return newObj;
}
finally
{
GC::KeepAlive(m_nativeptr);
}
}
Object^ DataInput::readDotNetObjectArray()
{
int len = ReadArrayLen();
String^ className = nullptr;
if (len >= 0)
{
ReadByte(); // ignore CLASS typeid
className = (String^)ReadObject();
className = m_cache->TypeRegistry->GetLocalTypeName(className);
System::Collections::IList^ list = nullptr;
if (len == 0)
{
list = (System::Collections::IList^)m_cache->TypeRegistry->GetArrayObject(className, len);
return list;
}
//read first object
Object^ ret = ReadObject();//in case it returns pdxinstance or java.lang.object
list = (System::Collections::IList^)m_cache->TypeRegistry->GetArrayObject(ret->GetType()->FullName, len);
list[0] = ret;
for (System::Int32 index = 1; index < list->Count; ++index)
{
list[index] = ReadObject();
}
return list;
}
return nullptr;
}
Object^ DataInput::ReadInternalGenericObject()
{
bool findinternal = false;
int8_t typeId = ReadByte();
System::Int64 compId = typeId;
TypeFactoryMethodGeneric^ createType = nullptr;
if (compId == GeodeTypeIds::NullObj) {
return nullptr;
}
else if (compId == GeodeClassIds::PDX)
{
return Internal::PdxHelper::DeserializePdx(this, false, CacheRegionHelper::getCacheImpl(m_cache->GetNative().get())->getSerializationRegistry().get());
}
else if (compId == GeodeTypeIds::CacheableNullString) {
//return SerializablePtr(CacheableString::createDeserializable());
//TODO::
return nullptr;
}
else if (compId == GeodeTypeIdsImpl::CacheableUserData) {
int8_t classId = ReadByte();
//compId |= ( ( (System::Int64)classId ) << 32 );
compId = (System::Int64)classId;
}
else if (compId == GeodeTypeIdsImpl::CacheableUserData2) {
System::Int16 classId = ReadInt16();
//compId |= ( ( (System::Int64)classId ) << 32 );
compId = (System::Int64)classId;
}
else if (compId == GeodeTypeIdsImpl::CacheableUserData4) {
System::Int32 classId = ReadInt32();
//compId |= ( ( (System::Int64)classId ) << 32 );
compId = (System::Int64)classId;
}
else if (compId == GeodeTypeIdsImpl::FixedIDByte) {//TODO: need to verify again
int8_t fixedId = ReadByte();
compId = fixedId;
findinternal = true;
}
else if (compId == GeodeTypeIdsImpl::FixedIDShort) {
System::Int16 fixedId = ReadInt16();
compId = fixedId;
findinternal = true;
}
else if (compId == GeodeTypeIdsImpl::FixedIDInt) {
System::Int32 fixedId = ReadInt32();
compId = fixedId;
findinternal = true;
}
if (findinternal) {
compId += 0x80000000;
createType = m_cache->TypeRegistry->GetManagedDelegateGeneric((System::Int64)compId);
}
else {
createType = m_cache->TypeRegistry->GetManagedDelegateGeneric(compId);
if (createType == nullptr)
{
Object^ retVal = ReadDotNetTypes(typeId);
if (retVal != nullptr)
return retVal;
compId += 0x80000000;
createType = m_cache->TypeRegistry->GetManagedDelegateGeneric(compId);
}
}
if (createType != nullptr)
{
IGeodeSerializable^ newObj = createType();
newObj->FromData(this);
return newObj;
}
throw gcnew IllegalStateException("Unregistered typeId in deserialization, aborting.");
}
size_t DataInput::BytesRead::get()
{
AdvanceUMCursor();
SetBuffer();
try
{
return m_nativeptr->get()->getBytesRead();
}
finally
{
GC::KeepAlive(m_nativeptr);
}
}
size_t DataInput::BytesReadInternally::get()
{
return m_cursor;
}
size_t DataInput::BytesRemaining::get()
{
AdvanceUMCursor();
SetBuffer();
try
{
return m_nativeptr->get()->getBytesRemaining();
}
finally
{
GC::KeepAlive(m_nativeptr);
}
}
void DataInput::AdvanceCursor(size_t offset)
{
m_cursor += offset;
}
void DataInput::RewindCursor(size_t offset)
{
AdvanceUMCursor();
try
{
m_nativeptr->get()->rewindCursor(offset);
}
finally
{
GC::KeepAlive(m_nativeptr);
}
SetBuffer();
}
void DataInput::Reset()
{
AdvanceUMCursor();
try
{
m_nativeptr->get()->reset();
}
finally
{
GC::KeepAlive(m_nativeptr);
}
SetBuffer();
}
void DataInput::Cleanup()
{
//TODO:
//GF_SAFE_DELETE_ARRAY(m_buffer);
}
void DataInput::ReadDictionary(System::Collections::IDictionary^ dict)
{
int len = this->ReadArrayLen();
if (len > 0)
{
for (int i = 0; i < len; i++)
{
Object^ key = this->ReadObject();
Object^ val = this->ReadObject();
dict->Add(key, val);
}
}
}
IDictionary<Object^, Object^>^ DataInput::ReadDictionary()
{
int len = this->ReadArrayLen();
if (len == -1)
return nullptr;
else
{
IDictionary<Object^, Object^>^ dict = gcnew Dictionary<Object^, Object^>();
for (int i = 0; i < len; i++)
{
Object^ key = this->ReadObject();
Object^ val = this->ReadObject();
dict->Add(key, val);
}
return dict;
}
}
System::DateTime DataInput::ReadDate()
{
long ticks = (long)ReadInt64();
if (ticks != -1L)
{
m_cursor -= 8;//for above
CacheableDate^ cd = CacheableDate::Create();
cd->FromData(this);
return cd->Value;
}
else
{
DateTime dt(0);
return dt;
}
}
void DataInput::ReadCollection(System::Collections::IList^ coll)
{
int len = ReadArrayLen();
for (int i = 0; i < len; i++)
{
coll->Add(ReadObject());
}
}
array<Char>^ DataInput::ReadCharArray()
{
array<Char>^ arr;
this->ReadObject(arr);
return arr;
}
array<bool>^ DataInput::ReadBooleanArray()
{
array<bool>^ arr;
this->ReadObject(arr);
return arr;
}
array<Int16>^ DataInput::ReadShortArray()
{
array<Int16>^ arr;
this->ReadObject(arr);
return arr;
}
array<Int32>^ DataInput::ReadIntArray()
{
array<Int32>^ arr;
this->ReadObject(arr);
return arr;
}
array<Int64>^ DataInput::ReadLongArray()
{
array<Int64>^ arr;
this->ReadObject(arr);
return arr;
}
array<float>^ DataInput::ReadFloatArray()
{
array<float>^ arr;
this->ReadObject(arr);
return arr;
}
array<double>^ DataInput::ReadDoubleArray()
{
array<double>^ arr;
this->ReadObject(arr);
return arr;
}
List<Object^>^ DataInput::ReadObjectArray()
{
//this to know whether it is null or it is empty
auto storeCursor = m_cursor;
auto len = this->ReadArrayLen();
if (len == -1)
return nullptr;
//this will be read further by fromdata
m_cursor = m_cursor - (m_cursor - storeCursor);
CacheableObjectArray^ coa = CacheableObjectArray::Create();
coa->FromData(this);
List<Object^>^ retObj = (List<Object^>^)coa;
if (retObj->Count >= 0)
return retObj;
return nullptr;
}
array<array<Byte>^>^ DataInput::ReadArrayOfByteArrays()
{
int len = ReadArrayLen();
if (len >= 0)
{
array<array<Byte>^>^ retVal = gcnew array<array<Byte>^>(len);
for (int i = 0; i < len; i++)
{
retVal[i] = this->ReadBytes();
}
return retVal;
}
else
return nullptr;
}
void DataInput::ReadObject(array<UInt16>^% obj)
{
int len = ReadArrayLen();
if (len >= 0)
{
obj = gcnew array<UInt16>(len);
for (int i = 0; i < len; i++)
{
obj[i] = this->ReadUInt16();
}
}
}
void DataInput::ReadObject(array<UInt32>^% obj)
{
int len = ReadArrayLen();
if (len >= 0)
{
obj = gcnew array<UInt32>(len);
for (int i = 0; i < len; i++)
{
obj[i] = this->ReadUInt32();
}
}
}
void DataInput::ReadObject(array<UInt64>^% obj)
{
int len = ReadArrayLen();
if (len >= 0)
{
obj = gcnew array<UInt64>(len);
for (int i = 0; i < len; i++)
{
obj[i] = this->ReadUInt64();
}
}
}
String^ DataInput::ReadString()
{
UInt32 typeId = (Int32)ReadByte();
if (typeId == GeodeTypeIds::CacheableNullString)
return nullptr;
if (typeId == GeodeTypeIds::CacheableASCIIString ||
typeId == GeodeTypeIds::CacheableString)
{
return ReadUTF();
}
else if (typeId == GeodeTypeIds::CacheableASCIIStringHuge)
{
return ReadASCIIHuge();
}
else
{
return ReadUTFHuge();
}
}
native::Pool* DataInput::GetPool()
{
try
{
return native::DataInputInternal::getPool(*m_nativeptr);
}
finally {
GC::KeepAlive(m_nativeptr);
}
}
} // namespace Client
} // namespace Geode
} // namespace Apache
| 28.799492 | 168 | 0.538263 | [
"object"
] |
581e6ae08a33f22d4fd391978dbff902e925fcb4 | 1,322 | cpp | C++ | main_pearce.cpp | phisco/advance_algorithms_project | 2961959cf6036ed4c85d479dd14389315df55ee1 | [
"MIT"
] | 3 | 2018-07-04T13:46:31.000Z | 2018-11-28T16:42:31.000Z | main_pearce.cpp | phisco/advance_algorithms_project | 2961959cf6036ed4c85d479dd14389315df55ee1 | [
"MIT"
] | null | null | null | main_pearce.cpp | phisco/advance_algorithms_project | 2961959cf6036ed4c85d479dd14389315df55ee1 | [
"MIT"
] | null | null | null | #include "my_pearce.cpp"
#include <boost/graph/erdos_renyi_generator.hpp>
#include <boost/random/linear_congruential.hpp>
#include <boost/graph/graphml.hpp>
#include <boost/property_map/dynamic_property_map.hpp>
#include <boost/graph/transitive_closure.hpp>
using namespace boost;
#ifndef TYPEDEF
#define TYPEDEF
typedef adjacency_list <vecS, vecS, directedS> Graph;
typedef typename graph_traits<Graph>::vertex_descriptor Vertex;
typedef typename graph_traits<Graph>::vertex_iterator vertex_iter;
typedef graph_traits<adjacency_list<vecS, vecS, directedS> >::vertex_descriptor Vertex;
typedef typename property_map<Graph, vertex_index_t>::type IndexMap;
#endif
int main(int, char*[])
{
//This function takes a graph formatted by graphml fashion from the stdin
Graph g;
dynamic_properties dp;
read_graphml(std::cin, g, dp);
//Printing the graph
std::cout << "A directed graph:" << std::endl;
print_graph(g, get(vertex_index,g));
std::cout << std::endl;
//PearceClass object
PearceClass<typeInt> pearce(&g);
std::vector<int>* rindex = pearce.pearce_scc();
//Printing the result
IndexMap index=get(vertex_index,g);
for (int i = 0; i != num_vertices(g); ++i){
std::cout << index[i] << " -> " << (*rindex)[i] << std::endl;
}
return 0;
}
| 29.377778 | 87 | 0.707262 | [
"object",
"vector"
] |
581ffe5839c345e645811108327a587701b94a66 | 2,603 | cc | C++ | smartag/src/model/DescribeQosesResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | smartag/src/model/DescribeQosesResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | smartag/src/model/DescribeQosesResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/smartag/model/DescribeQosesResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Smartag;
using namespace AlibabaCloud::Smartag::Model;
DescribeQosesResult::DescribeQosesResult() :
ServiceResult()
{}
DescribeQosesResult::DescribeQosesResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
DescribeQosesResult::~DescribeQosesResult()
{}
void DescribeQosesResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allQosesNode = value["Qoses"]["Qos"];
for (auto valueQosesQos : allQosesNode)
{
Qos qosesObject;
if(!valueQosesQos["QosDescription"].isNull())
qosesObject.qosDescription = valueQosesQos["QosDescription"].asString();
if(!valueQosesQos["SagCount"].isNull())
qosesObject.sagCount = valueQosesQos["SagCount"].asString();
if(!valueQosesQos["SmartAGIds"].isNull())
qosesObject.smartAGIds = valueQosesQos["SmartAGIds"].asString();
if(!valueQosesQos["QosId"].isNull())
qosesObject.qosId = valueQosesQos["QosId"].asString();
if(!valueQosesQos["QosName"].isNull())
qosesObject.qosName = valueQosesQos["QosName"].asString();
if(!valueQosesQos["ResourceGroupId"].isNull())
qosesObject.resourceGroupId = valueQosesQos["ResourceGroupId"].asString();
qoses_.push_back(qosesObject);
}
if(!value["TotalCount"].isNull())
totalCount_ = std::stoi(value["TotalCount"].asString());
if(!value["PageSize"].isNull())
pageSize_ = std::stoi(value["PageSize"].asString());
if(!value["PageNumber"].isNull())
pageNumber_ = std::stoi(value["PageNumber"].asString());
}
int DescribeQosesResult::getTotalCount()const
{
return totalCount_;
}
int DescribeQosesResult::getPageSize()const
{
return pageSize_;
}
int DescribeQosesResult::getPageNumber()const
{
return pageNumber_;
}
std::vector<DescribeQosesResult::Qos> DescribeQosesResult::getQoses()const
{
return qoses_;
}
| 29.247191 | 77 | 0.742605 | [
"vector",
"model"
] |
582328a312489eb60c7e5203c0e337a08f856b4d | 881 | cpp | C++ | game/world/objects/itemtorchburning.cpp | houkama/OpenGothic | 0a5e429bc1fd370259abe8664f19dc9e365ecac5 | [
"MIT"
] | 576 | 2019-07-22T19:14:33.000Z | 2022-03-31T22:27:28.000Z | game/world/objects/itemtorchburning.cpp | houkama/OpenGothic | 0a5e429bc1fd370259abe8664f19dc9e365ecac5 | [
"MIT"
] | 208 | 2019-07-22T17:25:30.000Z | 2022-03-14T18:53:06.000Z | game/world/objects/itemtorchburning.cpp | houkama/OpenGothic | 0a5e429bc1fd370259abe8664f19dc9e365ecac5 | [
"MIT"
] | 67 | 2019-10-14T19:39:38.000Z | 2022-01-27T13:58:03.000Z | #include "itemtorchburning.h"
#include "world/world.h"
ItemTorchBurning::ItemTorchBurning(World& owner, size_t inst, Item::Type type)
:Item(owner,inst,type) {
auto& sc = owner.script();
Daedalus::GEngineClasses::C_Item hitem={};
sc.initializeInstance(hitem,inst);
sc.clearReferences(hitem);
view.setVisual(hitem,owner);
size_t torchId = sc.getSymbolIndex("ItLsTorchburned");
if(torchId!=size_t(-1)) {
Daedalus::GEngineClasses::C_Item hitem={};
sc.initializeInstance(hitem,torchId);
sc.clearReferences(hitem);
auto m = Resources::loadMesh(hitem.visual.c_str());
setPhysicsEnable(m);
}
}
void ItemTorchBurning::clearView() {
Item::clearView();
view = ObjVisual();
}
bool ItemTorchBurning::isTorchBurn() const {
return true;
}
void ItemTorchBurning::moveEvent() {
Item::moveEvent();
view.setObjMatrix(transform());
}
| 23.810811 | 78 | 0.700341 | [
"transform"
] |
5832905b9f64842a7f05800c899b539546f914b7 | 22,630 | cc | C++ | src/compiler/pipeline.cc | ttyangf/v8 | cb1b554a837bb47ec718c1542d462cb2ac2aa0fd | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null | src/compiler/pipeline.cc | ttyangf/v8 | cb1b554a837bb47ec718c1542d462cb2ac2aa0fd | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 1 | 2019-01-16T13:06:04.000Z | 2019-01-16T13:06:04.000Z | src/compiler/pipeline.cc | ttyangf/v8 | cb1b554a837bb47ec718c1542d462cb2ac2aa0fd | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 2 | 2020-05-05T12:11:43.000Z | 2022-03-22T20:36:04.000Z | // Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/compiler/pipeline.h"
#include <fstream> // NOLINT(readability/streams)
#include <sstream>
#include "src/base/platform/elapsed-timer.h"
#include "src/compiler/ast-graph-builder.h"
#include "src/compiler/basic-block-instrumentor.h"
#include "src/compiler/change-lowering.h"
#include "src/compiler/code-generator.h"
#include "src/compiler/control-reducer.h"
#include "src/compiler/graph-replay.h"
#include "src/compiler/graph-visualizer.h"
#include "src/compiler/instruction.h"
#include "src/compiler/instruction-selector.h"
#include "src/compiler/js-context-specialization.h"
#include "src/compiler/js-generic-lowering.h"
#include "src/compiler/js-inlining.h"
#include "src/compiler/js-typed-lowering.h"
#include "src/compiler/machine-operator-reducer.h"
#include "src/compiler/pipeline-statistics.h"
#include "src/compiler/register-allocator.h"
#include "src/compiler/schedule.h"
#include "src/compiler/scheduler.h"
#include "src/compiler/select-lowering.h"
#include "src/compiler/simplified-lowering.h"
#include "src/compiler/simplified-operator-reducer.h"
#include "src/compiler/typer.h"
#include "src/compiler/value-numbering-reducer.h"
#include "src/compiler/verifier.h"
#include "src/compiler/zone-pool.h"
#include "src/ostreams.h"
#include "src/utils.h"
namespace v8 {
namespace internal {
namespace compiler {
class PipelineData {
public:
explicit PipelineData(CompilationInfo* info, ZonePool* zone_pool,
PipelineStatistics* pipeline_statistics)
: isolate_(info->zone()->isolate()),
outer_zone_(info->zone()),
zone_pool_(zone_pool),
pipeline_statistics_(pipeline_statistics),
graph_zone_scope_(zone_pool_),
graph_zone_(graph_zone_scope_.zone()),
graph_(new (graph_zone()) Graph(graph_zone())),
source_positions_(new SourcePositionTable(graph())),
machine_(new (graph_zone()) MachineOperatorBuilder(
graph_zone(), kMachPtr,
InstructionSelector::SupportedMachineOperatorFlags())),
common_(new (graph_zone()) CommonOperatorBuilder(graph_zone())),
javascript_(new (graph_zone()) JSOperatorBuilder(graph_zone())),
jsgraph_(new (graph_zone())
JSGraph(graph(), common(), javascript(), machine())),
typer_(new Typer(graph(), info->context())),
schedule_(NULL),
instruction_zone_scope_(zone_pool_),
instruction_zone_(instruction_zone_scope_.zone()) {}
// For machine graph testing only.
PipelineData(Graph* graph, Schedule* schedule, ZonePool* zone_pool)
: isolate_(graph->zone()->isolate()),
outer_zone_(NULL),
zone_pool_(zone_pool),
pipeline_statistics_(NULL),
graph_zone_scope_(zone_pool_),
graph_zone_(NULL),
graph_(graph),
source_positions_(new SourcePositionTable(graph)),
machine_(NULL),
common_(NULL),
javascript_(NULL),
jsgraph_(NULL),
typer_(NULL),
schedule_(schedule),
instruction_zone_scope_(zone_pool_),
instruction_zone_(instruction_zone_scope_.zone()) {}
~PipelineData() {
DeleteInstructionZone();
DeleteGraphZone();
}
Isolate* isolate() const { return isolate_; }
ZonePool* zone_pool() const { return zone_pool_; }
PipelineStatistics* pipeline_statistics() { return pipeline_statistics_; }
Zone* graph_zone() const { return graph_zone_; }
Graph* graph() const { return graph_; }
SourcePositionTable* source_positions() const {
return source_positions_.get();
}
MachineOperatorBuilder* machine() const { return machine_; }
CommonOperatorBuilder* common() const { return common_; }
JSOperatorBuilder* javascript() const { return javascript_; }
JSGraph* jsgraph() const { return jsgraph_; }
Typer* typer() const { return typer_.get(); }
Schedule* schedule() const { return schedule_; }
void set_schedule(Schedule* schedule) {
DCHECK_EQ(NULL, schedule_);
schedule_ = schedule;
}
Zone* instruction_zone() const { return instruction_zone_; }
void DeleteGraphZone() {
// Destroy objects with destructors first.
source_positions_.Reset(NULL);
typer_.Reset(NULL);
if (graph_zone_ == NULL) return;
// Destroy zone and clear pointers.
graph_zone_scope_.Destroy();
graph_zone_ = NULL;
graph_ = NULL;
machine_ = NULL;
common_ = NULL;
javascript_ = NULL;
jsgraph_ = NULL;
schedule_ = NULL;
}
void DeleteInstructionZone() {
if (instruction_zone_ == NULL) return;
instruction_zone_scope_.Destroy();
instruction_zone_ = NULL;
}
private:
Isolate* isolate_;
Zone* outer_zone_;
ZonePool* zone_pool_;
PipelineStatistics* pipeline_statistics_;
ZonePool::Scope graph_zone_scope_;
Zone* graph_zone_;
// All objects in the following group of fields are allocated in graph_zone_.
// They are all set to NULL when the graph_zone_ is destroyed.
Graph* graph_;
// TODO(dcarney): make this into a ZoneObject.
SmartPointer<SourcePositionTable> source_positions_;
MachineOperatorBuilder* machine_;
CommonOperatorBuilder* common_;
JSOperatorBuilder* javascript_;
JSGraph* jsgraph_;
// TODO(dcarney): make this into a ZoneObject.
SmartPointer<Typer> typer_;
Schedule* schedule_;
// All objects in the following group of fields are allocated in
// instruction_zone_. They are all set to NULL when the instruction_zone_ is
// destroyed.
ZonePool::Scope instruction_zone_scope_;
Zone* instruction_zone_;
DISALLOW_COPY_AND_ASSIGN(PipelineData);
};
static inline bool VerifyGraphs() {
#ifdef DEBUG
return true;
#else
return FLAG_turbo_verify;
#endif
}
struct TurboCfgFile : public std::ofstream {
explicit TurboCfgFile(Isolate* isolate)
: std::ofstream(isolate->GetTurboCfgFileName().c_str(),
std::ios_base::app) {}
};
void Pipeline::VerifyAndPrintGraph(
Graph* graph, const char* phase, bool untyped) {
if (FLAG_trace_turbo) {
char buffer[256];
Vector<char> filename(buffer, sizeof(buffer));
SmartArrayPointer<char> functionname;
if (!info_->shared_info().is_null()) {
functionname = info_->shared_info()->DebugName()->ToCString();
if (strlen(functionname.get()) > 0) {
SNPrintF(filename, "turbo-%s-%s", functionname.get(), phase);
} else {
SNPrintF(filename, "turbo-%p-%s", static_cast<void*>(info_), phase);
}
} else {
SNPrintF(filename, "turbo-none-%s", phase);
}
std::replace(filename.start(), filename.start() + filename.length(), ' ',
'_');
char dot_buffer[256];
Vector<char> dot_filename(dot_buffer, sizeof(dot_buffer));
SNPrintF(dot_filename, "%s.dot", filename.start());
FILE* dot_file = base::OS::FOpen(dot_filename.start(), "w+");
OFStream dot_of(dot_file);
dot_of << AsDOT(*graph);
fclose(dot_file);
char json_buffer[256];
Vector<char> json_filename(json_buffer, sizeof(json_buffer));
SNPrintF(json_filename, "%s.json", filename.start());
FILE* json_file = base::OS::FOpen(json_filename.start(), "w+");
OFStream json_of(json_file);
json_of << AsJSON(*graph);
fclose(json_file);
OFStream os(stdout);
os << "-- " << phase << " graph printed to file " << filename.start()
<< "\n";
}
if (VerifyGraphs()) {
Verifier::Run(graph,
FLAG_turbo_types && !untyped ? Verifier::TYPED : Verifier::UNTYPED);
}
}
class AstGraphBuilderWithPositions : public AstGraphBuilder {
public:
explicit AstGraphBuilderWithPositions(Zone* local_zone, CompilationInfo* info,
JSGraph* jsgraph,
SourcePositionTable* source_positions)
: AstGraphBuilder(local_zone, info, jsgraph),
source_positions_(source_positions) {}
bool CreateGraph() {
SourcePositionTable::Scope pos(source_positions_,
SourcePosition::Unknown());
return AstGraphBuilder::CreateGraph();
}
#define DEF_VISIT(type) \
virtual void Visit##type(type* node) OVERRIDE { \
SourcePositionTable::Scope pos(source_positions_, \
SourcePosition(node->position())); \
AstGraphBuilder::Visit##type(node); \
}
AST_NODE_LIST(DEF_VISIT)
#undef DEF_VISIT
private:
SourcePositionTable* source_positions_;
};
static void TraceSchedule(Schedule* schedule) {
if (!FLAG_trace_turbo) return;
OFStream os(stdout);
os << "-- Schedule --------------------------------------\n" << *schedule;
}
static SmartArrayPointer<char> GetDebugName(CompilationInfo* info) {
SmartArrayPointer<char> name;
if (info->IsStub()) {
if (info->code_stub() != NULL) {
CodeStub::Major major_key = info->code_stub()->MajorKey();
const char* major_name = CodeStub::MajorName(major_key, false);
size_t len = strlen(major_name);
name.Reset(new char[len]);
memcpy(name.get(), major_name, len);
}
} else {
AllowHandleDereference allow_deref;
name = info->function()->debug_name()->ToCString();
}
return name;
}
Handle<Code> Pipeline::GenerateCode() {
// This list must be kept in sync with DONT_TURBOFAN_NODE in ast.cc.
if (info()->function()->dont_optimize_reason() == kTryCatchStatement ||
info()->function()->dont_optimize_reason() == kTryFinallyStatement ||
// TODO(turbofan): Make ES6 for-of work and remove this bailout.
info()->function()->dont_optimize_reason() == kForOfStatement ||
// TODO(turbofan): Make super work and remove this bailout.
info()->function()->dont_optimize_reason() == kSuperReference ||
// TODO(turbofan): Make class literals work and remove this bailout.
info()->function()->dont_optimize_reason() == kClassLiteral ||
// TODO(turbofan): Make OSR work and remove this bailout.
info()->is_osr()) {
return Handle<Code>::null();
}
ZonePool zone_pool(isolate());
SmartPointer<PipelineStatistics> pipeline_statistics;
if (FLAG_turbo_stats) {
pipeline_statistics.Reset(new PipelineStatistics(info(), &zone_pool));
pipeline_statistics->BeginPhaseKind("graph creation");
}
if (FLAG_trace_turbo) {
OFStream os(stdout);
os << "---------------------------------------------------\n"
<< "Begin compiling method " << GetDebugName(info()).get()
<< " using Turbofan" << std::endl;
TurboCfgFile tcf(isolate());
tcf << AsC1VCompilation(info());
}
// Initialize the graph and builders.
PipelineData data(info(), &zone_pool, pipeline_statistics.get());
data.source_positions()->AddDecorator();
Node* context_node;
{
PhaseScope phase_scope(pipeline_statistics.get(), "graph builder");
ZonePool::Scope zone_scope(data.zone_pool());
AstGraphBuilderWithPositions graph_builder(
zone_scope.zone(), info(), data.jsgraph(), data.source_positions());
if (!graph_builder.CreateGraph()) return Handle<Code>::null();
context_node = graph_builder.GetFunctionContext();
}
VerifyAndPrintGraph(data.graph(), "Initial untyped", true);
{
PhaseScope phase_scope(pipeline_statistics.get(),
"early control reduction");
SourcePositionTable::Scope pos(data.source_positions(),
SourcePosition::Unknown());
ZonePool::Scope zone_scope(data.zone_pool());
ControlReducer::ReduceGraph(zone_scope.zone(), data.jsgraph(),
data.common());
VerifyAndPrintGraph(data.graph(), "Early Control reduced", true);
}
if (info()->is_context_specializing()) {
SourcePositionTable::Scope pos(data.source_positions(),
SourcePosition::Unknown());
// Specialize the code to the context as aggressively as possible.
JSContextSpecializer spec(info(), data.jsgraph(), context_node);
spec.SpecializeToContext();
VerifyAndPrintGraph(data.graph(), "Context specialized", true);
}
if (info()->is_inlining_enabled()) {
PhaseScope phase_scope(pipeline_statistics.get(), "inlining");
SourcePositionTable::Scope pos(data.source_positions(),
SourcePosition::Unknown());
ZonePool::Scope zone_scope(data.zone_pool());
JSInliner inliner(zone_scope.zone(), info(), data.jsgraph());
inliner.Inline();
VerifyAndPrintGraph(data.graph(), "Inlined", true);
}
// Print a replay of the initial graph.
if (FLAG_print_turbo_replay) {
GraphReplayPrinter::PrintReplay(data.graph());
}
// Bailout here in case target architecture is not supported.
if (!SupportedTarget()) return Handle<Code>::null();
if (info()->is_typing_enabled()) {
{
// Type the graph.
PhaseScope phase_scope(pipeline_statistics.get(), "typer");
data.typer()->Run();
VerifyAndPrintGraph(data.graph(), "Typed");
}
}
if (!pipeline_statistics.is_empty()) {
pipeline_statistics->BeginPhaseKind("lowering");
}
if (info()->is_typing_enabled()) {
{
// Lower JSOperators where we can determine types.
PhaseScope phase_scope(pipeline_statistics.get(), "typed lowering");
SourcePositionTable::Scope pos(data.source_positions(),
SourcePosition::Unknown());
ValueNumberingReducer vn_reducer(data.graph_zone());
JSTypedLowering lowering(data.jsgraph());
SimplifiedOperatorReducer simple_reducer(data.jsgraph());
GraphReducer graph_reducer(data.graph());
graph_reducer.AddReducer(&vn_reducer);
graph_reducer.AddReducer(&lowering);
graph_reducer.AddReducer(&simple_reducer);
graph_reducer.ReduceGraph();
VerifyAndPrintGraph(data.graph(), "Lowered typed");
}
{
// Lower simplified operators and insert changes.
PhaseScope phase_scope(pipeline_statistics.get(), "simplified lowering");
SourcePositionTable::Scope pos(data.source_positions(),
SourcePosition::Unknown());
SimplifiedLowering lowering(data.jsgraph());
lowering.LowerAllNodes();
ValueNumberingReducer vn_reducer(data.graph_zone());
SimplifiedOperatorReducer simple_reducer(data.jsgraph());
GraphReducer graph_reducer(data.graph());
graph_reducer.AddReducer(&vn_reducer);
graph_reducer.AddReducer(&simple_reducer);
graph_reducer.ReduceGraph();
VerifyAndPrintGraph(data.graph(), "Lowered simplified");
}
{
// Lower changes that have been inserted before.
PhaseScope phase_scope(pipeline_statistics.get(), "change lowering");
SourcePositionTable::Scope pos(data.source_positions(),
SourcePosition::Unknown());
Linkage linkage(data.graph_zone(), info());
ValueNumberingReducer vn_reducer(data.graph_zone());
SimplifiedOperatorReducer simple_reducer(data.jsgraph());
ChangeLowering lowering(data.jsgraph(), &linkage);
MachineOperatorReducer mach_reducer(data.jsgraph());
GraphReducer graph_reducer(data.graph());
// TODO(titzer): Figure out if we should run all reducers at once here.
graph_reducer.AddReducer(&vn_reducer);
graph_reducer.AddReducer(&simple_reducer);
graph_reducer.AddReducer(&lowering);
graph_reducer.AddReducer(&mach_reducer);
graph_reducer.ReduceGraph();
// TODO(jarin, rossberg): Remove UNTYPED once machine typing works.
VerifyAndPrintGraph(data.graph(), "Lowered changes", true);
}
{
PhaseScope phase_scope(pipeline_statistics.get(),
"late control reduction");
SourcePositionTable::Scope pos(data.source_positions(),
SourcePosition::Unknown());
ZonePool::Scope zone_scope(data.zone_pool());
ControlReducer::ReduceGraph(zone_scope.zone(), data.jsgraph(),
data.common());
VerifyAndPrintGraph(data.graph(), "Late Control reduced");
}
}
{
// Lower any remaining generic JSOperators.
PhaseScope phase_scope(pipeline_statistics.get(), "generic lowering");
SourcePositionTable::Scope pos(data.source_positions(),
SourcePosition::Unknown());
JSGenericLowering generic(info(), data.jsgraph());
SelectLowering select(data.jsgraph()->graph(), data.jsgraph()->common());
GraphReducer graph_reducer(data.graph());
graph_reducer.AddReducer(&generic);
graph_reducer.AddReducer(&select);
graph_reducer.ReduceGraph();
// TODO(jarin, rossberg): Remove UNTYPED once machine typing works.
VerifyAndPrintGraph(data.graph(), "Lowered generic", true);
}
if (!pipeline_statistics.is_empty()) {
pipeline_statistics->BeginPhaseKind("block building");
}
data.source_positions()->RemoveDecorator();
// Compute a schedule.
ComputeSchedule(&data);
Handle<Code> code = Handle<Code>::null();
{
// Generate optimized code.
Linkage linkage(data.instruction_zone(), info());
code = GenerateCode(&linkage, &data);
info()->SetCode(code);
}
// Print optimized code.
v8::internal::CodeGenerator::PrintCode(code, info());
if (FLAG_trace_turbo) {
OFStream os(stdout);
os << "--------------------------------------------------\n"
<< "Finished compiling method " << GetDebugName(info()).get()
<< " using Turbofan" << std::endl;
}
return code;
}
void Pipeline::ComputeSchedule(PipelineData* data) {
PhaseScope phase_scope(data->pipeline_statistics(), "scheduling");
Schedule* schedule =
Scheduler::ComputeSchedule(data->zone_pool(), data->graph());
TraceSchedule(schedule);
if (VerifyGraphs()) ScheduleVerifier::Run(schedule);
data->set_schedule(schedule);
}
Handle<Code> Pipeline::GenerateCodeForMachineGraph(Linkage* linkage,
Graph* graph,
Schedule* schedule) {
ZonePool zone_pool(isolate());
CHECK(SupportedBackend());
PipelineData data(graph, schedule, &zone_pool);
if (schedule == NULL) {
// TODO(rossberg): Should this really be untyped?
VerifyAndPrintGraph(graph, "Machine", true);
ComputeSchedule(&data);
} else {
TraceSchedule(schedule);
}
Handle<Code> code = GenerateCode(linkage, &data);
#if ENABLE_DISASSEMBLER
if (!code.is_null() && FLAG_print_opt_code) {
CodeTracer::Scope tracing_scope(isolate()->GetCodeTracer());
OFStream os(tracing_scope.file());
code->Disassemble("test code", os);
}
#endif
return code;
}
Handle<Code> Pipeline::GenerateCode(Linkage* linkage, PipelineData* data) {
DCHECK_NOT_NULL(linkage);
DCHECK_NOT_NULL(data->graph());
DCHECK_NOT_NULL(data->schedule());
CHECK(SupportedBackend());
BasicBlockProfiler::Data* profiler_data = NULL;
if (FLAG_turbo_profiling) {
profiler_data = BasicBlockInstrumentor::Instrument(info(), data->graph(),
data->schedule());
}
InstructionBlocks* instruction_blocks =
InstructionSequence::InstructionBlocksFor(data->instruction_zone(),
data->schedule());
InstructionSequence sequence(data->instruction_zone(), instruction_blocks);
// Select and schedule instructions covering the scheduled graph.
{
PhaseScope phase_scope(data->pipeline_statistics(), "select instructions");
ZonePool::Scope zone_scope(data->zone_pool());
InstructionSelector selector(zone_scope.zone(), data->graph(), linkage,
&sequence, data->schedule(),
data->source_positions());
selector.SelectInstructions();
}
if (FLAG_trace_turbo) {
OFStream os(stdout);
PrintableInstructionSequence printable = {
RegisterConfiguration::ArchDefault(), &sequence};
os << "----- Instruction sequence before register allocation -----\n"
<< printable;
TurboCfgFile tcf(isolate());
tcf << AsC1V("CodeGen", data->schedule(), data->source_positions(),
&sequence);
}
data->DeleteGraphZone();
if (data->pipeline_statistics() != NULL) {
data->pipeline_statistics()->BeginPhaseKind("register allocation");
}
// Allocate registers.
Frame frame;
{
int node_count = sequence.VirtualRegisterCount();
if (node_count > UnallocatedOperand::kMaxVirtualRegisters) {
info()->AbortOptimization(kNotEnoughVirtualRegistersForValues);
return Handle<Code>::null();
}
ZonePool::Scope zone_scope(data->zone_pool());
SmartArrayPointer<char> debug_name;
RegisterAllocator::VerificationType verification_type =
RegisterAllocator::kNoVerify;
#ifdef DEBUG
debug_name = GetDebugName(info());
verification_type = RegisterAllocator::kVerifyAssignment;
#endif
RegisterAllocator allocator(RegisterConfiguration::ArchDefault(),
zone_scope.zone(), &frame, &sequence,
debug_name.get());
if (!allocator.Allocate(data->pipeline_statistics(), verification_type)) {
info()->AbortOptimization(kNotEnoughVirtualRegistersRegalloc);
return Handle<Code>::null();
}
if (FLAG_trace_turbo) {
TurboCfgFile tcf(isolate());
tcf << AsC1VAllocator("CodeGen", &allocator);
}
}
if (FLAG_trace_turbo) {
OFStream os(stdout);
PrintableInstructionSequence printable = {
RegisterConfiguration::ArchDefault(), &sequence};
os << "----- Instruction sequence after register allocation -----\n"
<< printable;
}
if (data->pipeline_statistics() != NULL) {
data->pipeline_statistics()->BeginPhaseKind("code generation");
}
// Generate native sequence.
Handle<Code> code;
{
PhaseScope phase_scope(data->pipeline_statistics(), "generate code");
CodeGenerator generator(&frame, linkage, &sequence, info());
code = generator.GenerateCode();
}
if (profiler_data != NULL) {
#if ENABLE_DISASSEMBLER
std::ostringstream os;
code->Disassemble(NULL, os);
profiler_data->SetCode(&os);
#endif
}
return code;
}
void Pipeline::SetUp() {
InstructionOperand::SetUpCaches();
}
void Pipeline::TearDown() {
InstructionOperand::TearDownCaches();
}
} // namespace compiler
} // namespace internal
} // namespace v8
| 34.815385 | 80 | 0.662262 | [
"vector"
] |
5837c4e235d7cc67235a4425d935ae550166b534 | 6,563 | cpp | C++ | Geolocalizacion/sourcewidget.cpp | ZoraDomain/-Garbanzo | 1a3004ed3a269d418a407ca637b76b8891e9e5fb | [
"Apache-2.0"
] | null | null | null | Geolocalizacion/sourcewidget.cpp | ZoraDomain/-Garbanzo | 1a3004ed3a269d418a407ca637b76b8891e9e5fb | [
"Apache-2.0"
] | null | null | null | Geolocalizacion/sourcewidget.cpp | ZoraDomain/-Garbanzo | 1a3004ed3a269d418a407ca637b76b8891e9e5fb | [
"Apache-2.0"
] | null | null | null | #include "sourcewidget.h"
#include "marker.h"
#include "logfilepositionsource.h"
#include "bus.h"
#include <QPushButton>
#include <QPlainTextEdit>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QFileDialog>
#include <QDebug>
SourceWidget::SourceWidget(QWidget *parent) : QWidget(parent) {
setupNmeaLog();
///this set up the corps object
corps.bus = 0;
corps.marker = 0;
QVBoxLayout *mainLayout = new QVBoxLayout(this);
mainLayout->addWidget(nmeaLog);
thereAre = false;
QObject::connect(this, SIGNAL(currentObjectChanged()), this, SLOT(clearAll()));
QObject::connect(addSourceButton, SIGNAL(clicked()), this, SLOT(addSourceButtonSlot()));
QObject::connect(removeSourceButton, SIGNAL(clicked()), this, SLOT(removeSourceButtonSlot()));
clearAll();
}
void SourceWidget::setupNmeaLog() {
nmeaLog = new QGroupBox("Nmea Log", this);
addSourceButton = new QPushButton("Add Source", this);
removeSourceButton = new QPushButton("Remove Source", this);;
nmeaLogText = new QPlainTextEdit(); nmeaLogText->setReadOnly(true);
nmeaLogText->setFont(QFont("Courier New", 5, 1));
QHBoxLayout *nmeaLayout = new QHBoxLayout(this);
QVBoxLayout *buttonLayout = new QVBoxLayout(this);
buttonLayout->addWidget(addSourceButton);
buttonLayout->addWidget(removeSourceButton);
nmeaLayout->addLayout(buttonLayout);
nmeaLayout->addWidget(nmeaLogText);
nmeaLog->setLayout(nmeaLayout);
nmeaLog->setFont(QFont("Courier New", 12, 1));
}
void SourceWidget::setCurrentCorps(Marker *newMarker) {
if (newMarker->getClassName() == "Marker") {
if (corps.marker != newMarker) {
corps.marker = newMarker;
corps.bus = 0;
nmeaLog->setTitle("Nmea Log " + getCurrentCorps().marker->text());
clearAll();
}
else return;
} else
return;
}
void SourceWidget::setCurrentCorps(Bus *newBus) {
if (newBus->getClassName() == "Bus") {
if (corps.bus != newBus) {
corps.bus = newBus;
corps.marker = 0;
nmeaLog->setTitle("Nmea Log " + getCurrentCorps().bus->text());
clearAll();
}
else return;
} else
return;
}
void SourceWidget::updateName(int index, QString name) {
if (whatWeHave() == "Marker") {
if (getCurrentCorps().marker->getIndex() == index)
nmeaLog->setTitle("Nmea Log " + name);
else
return;
} else if (whatWeHave() == "Bus") {
if (getCurrentCorps().bus->getIndex() == index)
nmeaLog->setTitle("Nmea Log " + name);
else
return;
}
}
void SourceWidget::checkRemoved(int index) {
emit currentObjectChanged();
}
void SourceWidget::addSource(QString fileName) {
if(!fileName.isEmpty()) {
if (whatWeHave() == "Marker")
getCurrentCorps().marker->getLogFileSource()->setPath(fileName);
else if (whatWeHave() == "Bus")
getCurrentCorps().bus->getLogFileSource()->setPath(fileName);
}
}
QString SourceWidget::whatWeHave() const {
if (getCurrentCorps().bus == 0)
return getCurrentCorps().marker->getClassName();
else if (getCurrentCorps().marker == 0)
return getCurrentCorps().bus->getClassName();
}
void SourceWidget::addSourceButtonSlot() {
if (whatWeHave() == "Marker") {
if (getCurrentCorps().marker->getSet() == 1) {
emit showInfomationMessageBox(tr("Marker"),
tr("Remeber that the marker is a fixed object /n "
"if you want to make it movable unselect set option in status widget"));
emit requestFileName();
} else
emit requestFileName();
} else if (whatWeHave() == "Bus") {
emit requestFileName();
}
}
void SourceWidget::removeSourceButtonSlot() {
if (whatWeHave() == "Marker") {
if (getCurrentCorps().marker->getLogFileSource()->isRunning()) {
const QString message("Has been remove the log file of the marker: " + getCurrentCorps().marker->text() + "\n" +
"and path" + getCurrentCorps().marker->getLogFileSource()->getPath());
emit showInfomationMessageBox(tr("Marker"),
message);
removeSource();
}
return;
} else if (whatWeHave() == "Bus") {
if (getCurrentCorps().bus->getLogFileSource()->isRunning()) {
const QString message("Has been remove the log file of the bus: " + getCurrentCorps().bus->text() + "\n" +
"and path" + getCurrentCorps().bus->getLogFileSource()->getPath());
emit showInfomationMessageBox(tr("Bus"),
message);
removeSource();
}
}
}
void SourceWidget::updateNmeaLogText(int index, double latitude, double longitude) {
//qDebug("in the source widget the marker has the index: %d and the index recive is: %d", getCurrentMarker()->getIndex(),index );
if (whatWeHave() == "Marker") {
if (getCurrentCorps().marker->getIndex() == index)
nmeaLogText->insertPlainText(QString::number(latitude) + " " + QString::number(longitude));
else return;
} else if (whatWeHave() == "Bus") {
if (getCurrentCorps().bus->getIndex() == index)
nmeaLogText->insertPlainText(QString::number(latitude) + " " + QString::number(longitude));
else return;
}
}
void SourceWidget::removeSource() {
if (whatWeHave() == "Marker") {
getCurrentCorps().marker->getLogFileSource()->finish();
return;
} else if (whatWeHave() == "Bus") {
getCurrentCorps().bus->getLogFileSource()->finish();
return;
}
}
void SourceWidget::setThereAre(bool newThereAre) {
if (thereAre != newThereAre) {
thereAre = newThereAre;
clearAll();
} else return;
}
void SourceWidget::clearAll() {
if (thereAre == false) {
nmeaLog->setTitle("Nmea Log");
addSourceButton->setDisabled(true);
removeSourceButton->setDisabled(true);
nmeaLogText->setDisabled(true);
nmeaLogText->clear();
} else {
addSourceButton->setDisabled(false);
removeSourceButton->setDisabled(false);
nmeaLogText->setDisabled(false);
nmeaLogText->clear();
nmeaLogText->insertPlainText(tr("<LATITUDE>, <LONGITUDE>"));
}
}
| 34.005181 | 133 | 0.599116 | [
"object"
] |
583c2d5c220655f0aac6633cf6590e40709bf401 | 1,805 | cpp | C++ | potw/deck-of-cards/src/main.cpp | tehwalris/algolab | 489e0f6dd137336fa32b8002fc6eed8a7d35d87a | [
"MIT"
] | 1 | 2021-01-17T08:21:32.000Z | 2021-01-17T08:21:32.000Z | potw/deck-of-cards/src/main.cpp | tehwalris/algolab | 489e0f6dd137336fa32b8002fc6eed8a7d35d87a | [
"MIT"
] | null | null | null | potw/deck-of-cards/src/main.cpp | tehwalris/algolab | 489e0f6dd137336fa32b8002fc6eed8a7d35d87a | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <cmath>
#include <limits>
#include <assert.h>
#include <algorithm>
void testcase()
{
int n, k;
std::cin >> n >> k;
assert(n > 0);
std::vector<int> cardValuesCum;
int cumSum = 0;
for (int i = 0; i < n; i++)
{
int v;
std::cin >> v;
cumSum += v;
cardValuesCum.push_back(cumSum);
}
int bestValue = std::numeric_limits<int>::max(), bestI = -1, bestJ = -1;
for (int i = 0; i < n; i++)
{
auto target = k;
if (i > 0)
{
target += cardValuesCum[i - 1];
}
if (target < 0)
{
// HACK there was overflow, ignore it just in case
continue;
}
auto closestHigh = std::lower_bound(cardValuesCum.begin() + i, cardValuesCum.end(), target);
std::vector<std::vector<int>::iterator> candidates;
if (closestHigh != cardValuesCum.begin() + i)
{
auto closest = closestHigh - 1;
int solutionValue = *closest;
if (i > 0)
{
solutionValue -= cardValuesCum[i - 1];
}
solutionValue = abs(k - solutionValue);
if (solutionValue < bestValue)
{
bestValue = solutionValue;
bestI = i;
bestJ = closest - cardValuesCum.begin();
}
}
{
auto closest = closestHigh;
int solutionValue = *closest;
if (i > 0)
{
solutionValue -= cardValuesCum[i - 1];
}
solutionValue = abs(k - solutionValue);
if (solutionValue < bestValue)
{
bestValue = solutionValue;
bestI = i;
bestJ = closest - cardValuesCum.begin();
}
}
}
std::cout << bestI << ' ' << bestJ << '\n';
}
int main()
{
std::ios_base::sync_with_stdio(false);
int n;
std::cin >> n;
for (int i = 0; i < n; i++)
{
testcase();
}
return 0;
} | 19.202128 | 96 | 0.537396 | [
"vector"
] |
58468b23267e9abb47a831e307e99b8232a25792 | 13,349 | cc | C++ | modules/video_coding/main/test/test_callbacks.cc | yuxw75/temp | ab2fd478821e6c98ff10f2976ce43f617250cff6 | [
"DOC",
"BSD-3-Clause"
] | null | null | null | modules/video_coding/main/test/test_callbacks.cc | yuxw75/temp | ab2fd478821e6c98ff10f2976ce43f617250cff6 | [
"DOC",
"BSD-3-Clause"
] | null | null | null | modules/video_coding/main/test/test_callbacks.cc | yuxw75/temp | ab2fd478821e6c98ff10f2976ce43f617250cff6 | [
"DOC",
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/video_coding/main/test/test_callbacks.h"
#include <math.h>
#include "webrtc/common_video/libyuv/include/webrtc_libyuv.h"
#include "webrtc/modules/rtp_rtcp/interface/rtp_header_parser.h"
#include "webrtc/modules/rtp_rtcp/interface/rtp_payload_registry.h"
#include "webrtc/modules/rtp_rtcp/interface/rtp_receiver.h"
#include "webrtc/modules/utility/interface/rtp_dump.h"
#include "webrtc/modules/video_coding/main/source/encoded_frame.h"
#include "webrtc/modules/video_coding/main/test/test_macros.h"
#include "webrtc/system_wrappers/interface/clock.h"
namespace webrtc {
/******************************
* VCMEncodeCompleteCallback
*****************************/
// Basic callback implementation
// passes the encoded frame directly to the encoder
// Packetization callback implementation
VCMEncodeCompleteCallback::VCMEncodeCompleteCallback(FILE* encodedFile):
_encodedFile(encodedFile),
_encodedBytes(0),
_VCMReceiver(NULL),
_seqNo(0),
_encodeComplete(false),
_width(0),
_height(0),
_codecType(kRtpVideoNone)
{
//
}
VCMEncodeCompleteCallback::~VCMEncodeCompleteCallback()
{
}
void VCMEncodeCompleteCallback::RegisterTransportCallback(
VCMPacketizationCallback* transport) {
}
int32_t
VCMEncodeCompleteCallback::SendData(
const uint8_t payloadType,
const EncodedImage& encoded_image,
const RTPFragmentationHeader& fragmentationHeader,
const RTPVideoHeader* videoHdr)
{
// will call the VCMReceiver input packet
_frameType = VCMEncodedFrame::ConvertFrameType(encoded_image._frameType);
// writing encodedData into file
if (fwrite(encoded_image._buffer, 1, encoded_image._length, _encodedFile) !=
encoded_image._length) {
return -1;
}
WebRtcRTPHeader rtpInfo;
rtpInfo.header.markerBit = true; // end of frame
rtpInfo.type.Video.isFirstPacket = true;
rtpInfo.type.Video.codec = _codecType;
rtpInfo.type.Video.height = (uint16_t)_height;
rtpInfo.type.Video.width = (uint16_t)_width;
switch (_codecType)
{
case webrtc::kRtpVideoVp8:
rtpInfo.type.Video.codecHeader.VP8.InitRTPVideoHeaderVP8();
rtpInfo.type.Video.codecHeader.VP8.nonReference =
videoHdr->codecHeader.VP8.nonReference;
rtpInfo.type.Video.codecHeader.VP8.pictureId =
videoHdr->codecHeader.VP8.pictureId;
break;
case webrtc::kRtpVideoGeneric:
// Leave for now, until we add kRtpVideoVp9 to RTP.
break;
default:
assert(false);
return -1;
}
rtpInfo.header.payloadType = payloadType;
rtpInfo.header.sequenceNumber = _seqNo++;
rtpInfo.header.ssrc = 0;
rtpInfo.header.timestamp = encoded_image._timeStamp;
rtpInfo.frameType = _frameType;
// Size should also be received from that table, since the payload type
// defines the size.
_encodedBytes += encoded_image._length;
// directly to receiver
int ret = _VCMReceiver->IncomingPacket(encoded_image._buffer,
encoded_image._length, rtpInfo);
_encodeComplete = true;
return ret;
}
size_t
VCMEncodeCompleteCallback::EncodedBytes()
{
return _encodedBytes;
}
bool
VCMEncodeCompleteCallback::EncodeComplete()
{
if (_encodeComplete)
{
_encodeComplete = false;
return true;
}
return false;
}
void
VCMEncodeCompleteCallback::Initialize()
{
_encodeComplete = false;
_encodedBytes = 0;
_seqNo = 0;
return;
}
void
VCMEncodeCompleteCallback::ResetByteCount()
{
_encodedBytes = 0;
}
/***********************************/
/* VCMRTPEncodeCompleteCallback */
/***********************************/
// Encode Complete callback implementation
// passes the encoded frame via the RTP module to the decoder
// Packetization callback implementation
int32_t
VCMRTPEncodeCompleteCallback::SendData(
uint8_t payloadType,
const EncodedImage& encoded_image,
const RTPFragmentationHeader& fragmentationHeader,
const RTPVideoHeader* videoHdr)
{
_frameType = VCMEncodedFrame::ConvertFrameType(encoded_image._frameType);
_encodedBytes+= encoded_image._length;
_encodeComplete = true;
return _RTPModule->SendOutgoingData(_frameType,
payloadType,
encoded_image._timeStamp,
encoded_image.capture_time_ms_,
encoded_image._buffer,
encoded_image._length,
&fragmentationHeader,
videoHdr);
}
size_t
VCMRTPEncodeCompleteCallback::EncodedBytes()
{
// only good for one call - after which will reset value;
size_t tmp = _encodedBytes;
_encodedBytes = 0;
return tmp;
}
bool
VCMRTPEncodeCompleteCallback::EncodeComplete()
{
if (_encodeComplete)
{
_encodeComplete = false;
return true;
}
return false;
}
// Decoded Frame Callback Implementation
int32_t
VCMDecodeCompleteCallback::FrameToRender(I420VideoFrame& videoFrame)
{
if (PrintI420VideoFrame(videoFrame, _decodedFile) < 0) {
return -1;
}
_decodedBytes += CalcBufferSize(kI420, videoFrame.width(),
videoFrame.height());
return VCM_OK;
}
size_t
VCMDecodeCompleteCallback::DecodedBytes()
{
return _decodedBytes;
}
RTPSendCompleteCallback::RTPSendCompleteCallback(Clock* clock,
const char* filename):
_clock(clock),
_sendCount(0),
rtp_payload_registry_(NULL),
rtp_receiver_(NULL),
_rtp(NULL),
_lossPct(0),
_burstLength(0),
_networkDelayMs(0),
_jitterVar(0),
_prevLossState(0),
_totalSentLength(0),
_rtpPackets(),
_rtpDump(NULL)
{
if (filename != NULL)
{
_rtpDump = RtpDump::CreateRtpDump();
_rtpDump->Start(filename);
}
}
RTPSendCompleteCallback::~RTPSendCompleteCallback()
{
if (_rtpDump != NULL)
{
_rtpDump->Stop();
RtpDump::DestroyRtpDump(_rtpDump);
}
// Delete remaining packets
while (!_rtpPackets.empty())
{
// Take first packet in list
delete _rtpPackets.front();
_rtpPackets.pop_front();
}
}
int
RTPSendCompleteCallback::SendPacket(int channel, const void *data, size_t len)
{
_sendCount++;
_totalSentLength += len;
if (_rtpDump != NULL)
{
if (_rtpDump->DumpPacket((const uint8_t*)data, len) != 0)
{
return -1;
}
}
bool transmitPacket = true;
transmitPacket = PacketLoss();
int64_t now = _clock->TimeInMilliseconds();
// Insert outgoing packet into list
if (transmitPacket)
{
RtpPacket* newPacket = new RtpPacket();
memcpy(newPacket->data, data, len);
newPacket->length = len;
// Simulate receive time = network delay + packet jitter
// simulated as a Normal distribution random variable with
// mean = networkDelay and variance = jitterVar
int32_t
simulatedDelay = (int32_t)NormalDist(_networkDelayMs,
sqrt(_jitterVar));
newPacket->receiveTime = now + simulatedDelay;
_rtpPackets.push_back(newPacket);
}
// Are we ready to send packets to the receiver?
RtpPacket* packet = NULL;
while (!_rtpPackets.empty())
{
// Take first packet in list
packet = _rtpPackets.front();
int64_t timeToReceive = packet->receiveTime - now;
if (timeToReceive > 0)
{
// No available packets to send
break;
}
_rtpPackets.pop_front();
assert(_rtp); // We must have a configured RTP module for this test.
// Send to receive side
RTPHeader header;
scoped_ptr<RtpHeaderParser> parser(RtpHeaderParser::Create());
if (!parser->Parse(packet->data, packet->length, &header)) {
delete packet;
return -1;
}
PayloadUnion payload_specific;
if (!rtp_payload_registry_->GetPayloadSpecifics(
header.payloadType, &payload_specific)) {
return -1;
}
if (!rtp_receiver_->IncomingRtpPacket(header, packet->data,
packet->length, payload_specific,
true))
{
delete packet;
return -1;
}
delete packet;
packet = NULL;
}
return static_cast<int>(len); // OK
}
int
RTPSendCompleteCallback::SendRTCPPacket(int channel,
const void *data,
size_t len)
{
// Incorporate network conditions
return SendPacket(channel, data, len);
}
void
RTPSendCompleteCallback::SetLossPct(double lossPct)
{
_lossPct = lossPct;
return;
}
void
RTPSendCompleteCallback::SetBurstLength(double burstLength)
{
_burstLength = burstLength;
return;
}
bool
RTPSendCompleteCallback::PacketLoss()
{
bool transmitPacket = true;
if (_burstLength <= 1.0)
{
// Random loss: if _burstLength parameter is not set, or <=1
if (UnifomLoss(_lossPct))
{
// drop
transmitPacket = false;
}
}
else
{
// Simulate bursty channel (Gilbert model)
// (1st order) Markov chain model with memory of the previous/last
// packet state (loss or received)
// 0 = received state
// 1 = loss state
// probTrans10: if previous packet is lost, prob. to -> received state
// probTrans11: if previous packet is lost, prob. to -> loss state
// probTrans01: if previous packet is received, prob. to -> loss state
// probTrans00: if previous packet is received, prob. to -> received
// Map the two channel parameters (average loss rate and burst length)
// to the transition probabilities:
double probTrans10 = 100 * (1.0 / _burstLength);
double probTrans11 = (100.0 - probTrans10);
double probTrans01 = (probTrans10 * ( _lossPct / (100.0 - _lossPct)));
// Note: Random loss (Bernoulli) model is a special case where:
// burstLength = 100.0 / (100.0 - _lossPct) (i.e., p10 + p01 = 100)
if (_prevLossState == 0 )
{
// previous packet was received
if (UnifomLoss(probTrans01))
{
// drop, update previous state to loss
_prevLossState = 1;
transmitPacket = false;
}
}
else if (_prevLossState == 1)
{
_prevLossState = 0;
// previous packet was lost
if (UnifomLoss(probTrans11))
{
// drop, update previous state to loss
_prevLossState = 1;
transmitPacket = false;
}
}
}
return transmitPacket;
}
bool
RTPSendCompleteCallback::UnifomLoss(double lossPct)
{
double randVal = (rand() + 1.0) / (RAND_MAX + 1.0);
return randVal < lossPct/100;
}
int32_t
PacketRequester::ResendPackets(const uint16_t* sequenceNumbers,
uint16_t length)
{
return _rtp.SendNACK(sequenceNumbers, length);
}
int32_t
SendStatsTest::SendStatistics(const uint32_t bitRate,
const uint32_t frameRate)
{
TEST(frameRate <= _framerate);
TEST(bitRate > _bitrate / 2 && bitRate < 3 * _bitrate / 2);
printf("VCM 1 sec: Bit rate: %u\tFrame rate: %u\n", bitRate, frameRate);
return 0;
}
int32_t KeyFrameReqTest::RequestKeyFrame() {
printf("Key frame requested\n");
return 0;
}
VideoProtectionCallback::VideoProtectionCallback():
delta_fec_params_(),
key_fec_params_()
{
memset(&delta_fec_params_, 0, sizeof(delta_fec_params_));
memset(&key_fec_params_, 0, sizeof(key_fec_params_));
}
VideoProtectionCallback::~VideoProtectionCallback()
{
//
}
int32_t
VideoProtectionCallback::ProtectionRequest(
const FecProtectionParams* delta_fec_params,
const FecProtectionParams* key_fec_params,
uint32_t* sent_video_rate_bps,
uint32_t* sent_nack_rate_bps,
uint32_t* sent_fec_rate_bps)
{
key_fec_params_ = *key_fec_params;
delta_fec_params_ = *delta_fec_params;
// Update RTP
if (_rtp->SetFecParameters(&delta_fec_params_,
&key_fec_params_) != 0)
{
printf("Error in Setting FEC rate\n");
return -1;
}
return 0;
}
FecProtectionParams VideoProtectionCallback::DeltaFecParameters() const
{
return delta_fec_params_;
}
FecProtectionParams VideoProtectionCallback::KeyFecParameters() const
{
return key_fec_params_;
}
} // namespace webrtc
| 27.810417 | 80 | 0.628511 | [
"model"
] |
584aac545cfc6ee8881c80b85c3d92481eff5895 | 1,240 | cpp | C++ | Leetcode/1000-2000/1804. Implement Trie II (Prefix Tree)/1804.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/1000-2000/1804. Implement Trie II (Prefix Tree)/1804.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/1000-2000/1804. Implement Trie II (Prefix Tree)/1804.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | struct TrieNode {
vector<TrieNode*> children;
int prefixCount = 0;
int wordCount = 0;
TrieNode() : children(26) {}
~TrieNode() {
for (TrieNode* child : children)
delete child;
}
};
class Trie {
public:
void insert(string word) {
TrieNode* node = &root;
for (const char c : word) {
const int i = c - 'a';
if (node->children[i] == nullptr)
node->children[i] = new TrieNode();
node = node->children[i];
++node->prefixCount;
}
++node->wordCount;
}
int countWordsEqualTo(string word) {
TrieNode* node = find(word);
return node ? node->wordCount : 0;
}
int countWordsStartingWith(string prefix) {
TrieNode* node = find(prefix);
return node ? node->prefixCount : 0;
}
void erase(string word) {
TrieNode* node = &root;
for (const char c : word) {
const int i = c - 'a';
node = node->children[i];
--node->prefixCount;
}
--node->wordCount;
}
private:
TrieNode root;
TrieNode* find(const string& s) {
TrieNode* node = &root;
for (const char c : s) {
const int i = c - 'a';
if (!node->children[i])
return nullptr;
node = node->children[i];
}
return node;
}
};
| 20.666667 | 45 | 0.565323 | [
"vector"
] |
584ab34a99ffd0cabb8454831432dad0601bc864 | 1,020 | hpp | C++ | applications/robin/cpp/pdepart.hpp | beckerrh/simfemsrc | d857eb6f6f8627412d4f9d89a871834c756537db | [
"MIT"
] | null | null | null | applications/robin/cpp/pdepart.hpp | beckerrh/simfemsrc | d857eb6f6f8627412d4f9d89a871834c756537db | [
"MIT"
] | 1 | 2019-01-31T10:59:11.000Z | 2019-01-31T10:59:11.000Z | applications/robin/cpp/pdepart.hpp | beckerrh/simfemsrc | d857eb6f6f8627412d4f9d89a871834c756537db | [
"MIT"
] | null | null | null | #ifndef ___PdePart_hpp
#define ___PdePart_hpp
#include "Solvers/pdepartwithintegration.hpp"
#include "Solvers/rt0.hpp"
#include "model.hpp"
/*--------------------------------------------------------------------------*/
class PdePart : public solvers::PdePartWithIntegration
{
protected:
mutable alat::armavec _beta;
const Model* _localmodel;
int _ivar, _ncomp, _nlocal;
double _deltasupg;
double _supg(double weight, double beta) const;
const alat::VectorOneVariable* _betavec;
const solvers::RT0* _femrt;
const solvers::InitialConditionInterface* _betafct;
bool _lumpedmass;
double _gamma;
public:
~PdePart();
PdePart(alat::StringList vars);
PdePart( const PdePart& pdepartwithfemtraditional);
PdePart& operator=( const PdePart& pdepartwithfemtraditional);
std::string getClassName() const;
void setData(const alat::Map<std::string, int>& var2index, const solvers::Parameters& parameters);
};
/*--------------------------------------------------------------------------*/
#endif
| 29.142857 | 100 | 0.644118 | [
"model"
] |
584acec313b99cb0335fb9c0e94db48ecd13be33 | 4,180 | hpp | C++ | libraries/chain/include/evt/chain/name.hpp | everitoken/evt | 3fbc2d0fd43421d81e1c88fa91d41ea97477e9ea | [
"Apache-2.0"
] | 1,411 | 2018-04-23T03:57:30.000Z | 2022-02-13T10:34:22.000Z | libraries/chain/include/evt/chain/name.hpp | baby636/evt | 3fbc2d0fd43421d81e1c88fa91d41ea97477e9ea | [
"Apache-2.0"
] | 27 | 2018-06-11T10:34:42.000Z | 2019-07-27T08:50:02.000Z | libraries/chain/include/evt/chain/name.hpp | baby636/evt | 3fbc2d0fd43421d81e1c88fa91d41ea97477e9ea | [
"Apache-2.0"
] | 364 | 2018-06-09T12:11:53.000Z | 2020-12-15T03:26:48.000Z | /**
* @file
* @copyright defined in evt/LICENSE.txt
*/
#pragma once
#include <string.h>
#include <iosfwd>
#include <string>
#include <vector>
#include <fmt/format.h>
#include <fc/reflect/reflect.hpp>
namespace evt { namespace chain {
using std::string;
static constexpr uint64_t
char_to_symbol(char c) {
if(c >= 'a' && c <= 'z')
return (c - 'a') + 1;
if(c >= '1' && c <= '5')
return (c - '1') + 27;
return 0;
}
static constexpr uint64_t
string_to_name(const char* str) {
uint64_t name = 0;
int i = 0;
for(; str[i] && i < 12; ++i) {
// NOTE: char_to_symbol() returns char type, and without this explicit
// expansion to uint64 type, the compilation fails at the point of usage
// of string_to_name(), where the usage requires constant (compile time) expression.
name |= (char_to_symbol(str[i]) & 0x1f) << (64 - 5 * (i + 1));
}
// The for-loop encoded up to 60 high bits into uint64 'name' variable,
// if (strlen(str) > 12) then encode str[12] into the low (remaining)
// 4 bits of 'name'
if(i == 12)
name |= char_to_symbol(str[12]) & 0x0f;
return name;
}
#define N(X) evt::chain::string_to_name(#X)
struct name {
uint64_t value = 0;
bool
empty() const {
return 0 == value;
}
bool
good() const {
return !empty();
}
bool
reserved() const {
constexpr auto flag = ((uint64_t)0x1f << (64-5));
return !(value & flag);
}
name(const char* str) { set(str); }
name(const string& str) { set(str.c_str()); }
void set(const char* str);
constexpr name(uint64_t v) : value(v) {}
constexpr name() {}
explicit operator string() const;
explicit operator bool() const { return value; }
explicit operator uint64_t() const { return value; }
string
to_string() const {
return string(*this);
}
name&
operator=(uint64_t v) {
value = v;
return *this;
}
name&
operator=(const string& n) {
value = name(n).value;
return *this;
}
name&
operator=(const char* n) {
value = name(n).value;
return *this;
}
friend std::ostream&
operator<<(std::ostream& out, const name& n) {
return out << string(n);
}
friend bool
operator<(const name& a, const name& b) {
return a.value < b.value;
}
friend bool
operator<=(const name& a, const name& b) {
return a.value <= b.value;
}
friend bool
operator>(const name& a, const name& b) {
return a.value > b.value;
}
friend bool
operator>=(const name& a, const name& b) {
return a.value >= b.value;
}
friend bool
operator==(const name& a, const name& b) {
return a.value == b.value;
}
friend bool
operator==(const name& a, uint64_t b) {
return a.value == b;
}
friend bool
operator!=(const name& a, uint64_t b) {
return a.value != b;
}
friend bool
operator!=(const name& a, const name& b) {
return a.value != b.value;
}
};
inline std::vector<name>
sort_names(std::vector<name>&& names) {
fc::deduplicate(names);
return std::move(names);
}
}} // namespace evt::chain
namespace std {
template <>
struct hash<evt::chain::name> : private hash<uint64_t> {
using argument_type = evt::chain::name;
std::size_t
operator()(const argument_type& name) const noexcept {
return hash<uint64_t>::operator()(name.value);
}
};
}; // namespace std
namespace fc {
class variant;
void to_variant(const evt::chain::name& name, fc::variant& v);
void from_variant(const fc::variant& v, evt::chain::name& name);
} // namespace fc
namespace fmt {
template <>
struct formatter<evt::chain::name> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) { return ctx.begin(); }
template <typename FormatContext>
auto format(const evt::chain::name& n, FormatContext &ctx) {
return format_to(ctx.begin(), n.to_string());
}
};
} // namespace fmt
FC_REFLECT(evt::chain::name, (value));
| 21.770833 | 92 | 0.582536 | [
"vector"
] |
585b6562375eed2762d12039c1d89cfdf507fadb | 3,733 | cpp | C++ | NetworkFlow24/codes/P3356.cpp | Tony031218/OI | 562f5f45d0448f4eab77643b99b825405a123d92 | [
"MIT"
] | 1 | 2021-02-22T03:39:24.000Z | 2021-02-22T03:39:24.000Z | NetworkFlow24/codes/P3356.cpp | Tony031218/OI | 562f5f45d0448f4eab77643b99b825405a123d92 | [
"MIT"
] | null | null | null | NetworkFlow24/codes/P3356.cpp | Tony031218/OI | 562f5f45d0448f4eab77643b99b825405a123d92 | [
"MIT"
] | null | null | null | /*************************************************************
* > File Name : P3356.cpp
* > Author : Tony
* > Created Time : 2020/04/20 14:55:29
* > Algorithm : 费用流
**************************************************************/
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0; int f = 1; char ch = getchar();
while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();}
while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();}
return x * f;
}
const int maxn = 4010;
const int inf = 0x3f3f3f3f;
const int ninf = 0xc0c0c0c0;
int n, m, s, t, ansflow;
int vis[maxn], d[maxn], pre[maxn], a[maxn];
long long anscost;
struct Edge {
int from, to, cap, flow, cost;
Edge(int u, int v, int c, int f, int w): from(u), to(v), cap(c), flow(f), cost(w){}
};
vector<Edge> edges;
vector<int> G[maxn];
void add(int u, int v, int c, int w) {
edges.push_back(Edge(u, v, c, 0, w));
edges.push_back(Edge(v, u, 0, 0,-w));
int mm = edges.size();
G[u].push_back(mm - 2);
G[v].push_back(mm - 1);
}
bool BellmanFord(int& flow, long long& cost) {
memset(d, 0xc0, sizeof(d));
memset(vis, 0, sizeof(vis));
d[s] = 0; vis[s] = 1; pre[s] = 0; a[s] = inf;
queue<int> Q;
Q.push(s);
while (!Q.empty()) {
int x = Q.front(); Q.pop();
vis[x] = 0;
for (int i = 0; i < G[x].size(); ++i) {
Edge& e = edges[G[x][i]];
if (e.cap > e.flow && d[e.to] < d[x] + e.cost) {
d[e.to] = d[x] + e.cost;
pre[e.to] = G[x][i];
a[e.to] = min(a[x], e.cap - e.flow);
if (!vis[e.to]) {
Q.push(e.to);
vis[e.to] = 1;
}
}
}
}
if (d[t] == ninf) return false;
flow += a[t];
cost += (long long)d[t] * (long long)a[t];
for (int u = t; u != s; u = edges[pre[u]].from) {
edges[pre[u]].flow += a[t];
edges[pre[u] ^ 1].flow -= a[t];
}
return true;
}
int MaxCostMaxFlow(long long& cost) {
int flow = 0; cost = 0;
while (BellmanFord(flow, cost));
return flow;
}
int p, q;
int in[40][40];
int point(int x, int y) {
return (x - 1) * p + y;
}
void dfs(int x, int y, int u, int id) {
for (int i = 0; i < G[u].size(); ++i) {
Edge& e = edges[G[u][i]];
Edge& ne = edges[G[u][i] ^ 1];
if (e.to == s || e.to == t || e.to == u - n) continue;
if (!e.flow) continue;
e.flow--;
if (e.to > n) {
dfs(x, y, e.to, id);
return;
}
int nx, ny, dir;
if (e.to == point(x, y) + 1) {
nx = x; ny = y + 1;
dir = 1;
} else {
nx = x + 1; ny = y;
dir = 0;
}
printf("%d %d\n", id, dir);
dfs(nx, ny, e.to + n, id);
return;
}
}
int main() {
int c = read(); p = read(); q = read();
n = p * q; s = 0; t = 2 * n + 1;
for (int i = 1; i <= q; ++i) {
for (int j = 1; j <= p; ++j) {
in[i][j] = read();
if (in[i][j] == 0) add(point(i, j), point(i, j) + n, inf, 0);
if (in[i][j] == 2) {
add(point(i, j), point(i, j) + n, inf, 0);
add(point(i, j), point(i, j) + n, 1, 1);
}
}
}
if (in[1][1] != 1) add(s, 1, c, 0);
for (int i = 1; i <= q; ++i) {
for (int j = 1; j <= p; ++j) {
if (in[i][j] == 1) continue;
if (in[i][j + 1] != 1 && j + 1 <= p) add(point(i, j) + n, point(i, j + 1), inf, 0);
if (in[i + 1][j] != 1 && i + 1 <= q) add(point(i, j) + n, point(i + 1, j), inf, 0);
}
}
if (in[q][p] != 1) add(point(q, p) + n, t, c, 0);
ansflow = MaxCostMaxFlow(anscost);
// printf("%d %d\n", ansflow, anscost);
for (int i = 1; i <= ansflow; ++i) {
dfs(1, 1, 1, i);
}
return 0;
} | 26.856115 | 95 | 0.424859 | [
"vector"
] |
585c51582b1fb4794f3a18d208e66afe90ef5bd6 | 2,152 | cpp | C++ | source/json/h2_select.cpp | lingjf/jp | e7fa2c97c3e1906bfb77afc1b07f0d51b53693d8 | [
"Apache-2.0"
] | null | null | null | source/json/h2_select.cpp | lingjf/jp | e7fa2c97c3e1906bfb77afc1b07f0d51b53693d8 | [
"Apache-2.0"
] | null | null | null | source/json/h2_select.cpp | lingjf/jp | e7fa2c97c3e1906bfb77afc1b07f0d51b53693d8 | [
"Apache-2.0"
] | null | null | null | struct h2_json_select {
struct value {
int index;
h2_string key;
};
std::vector<value> values;
h2_json_select(const char* selector)
{
const int st_idle = 0;
const int st_in_dot = 1;
const int st_in_bracket = 2;
int state = 0;
const char *s = nullptr, *p = selector;
do {
switch (state) {
case st_idle:
if (*p == '.') {
state = st_in_dot;
s = p + 1;
} else if (*p == '[') {
state = st_in_bracket;
s = p + 1;
}
break;
case st_in_dot:
if (*p == '.') { // end a part
if (s < p) add(s, p - 1, true);
// restart a new part
state = st_in_dot;
s = p + 1;
} else if (*p == '[') { // end a part
if (s < p) add(s, p - 1, true);
// restart a new part
state = st_in_bracket;
s = p + 1;
} else if (*p == '\0') {
if (s < p) add(s, p - 1, true);
state = st_idle;
}
break;
case st_in_bracket:
if (*p == ']') {
if (s < p) add(s, p - 1, false);
state = st_idle;
}
break;
}
} while (*p++);
}
void add(const char* start, const char* end, bool only_key)
{
for (; start <= end && ::isspace(*start);) start++; //strip left space
for (; start <= end && ::isspace(*end);) end--; //strip right space
if (start <= end) {
if (!only_key) {
if (strspn(start, "-0123456789") == (size_t)(end - start + 1)) {
values.push_back({atoi(start), ""});
return;
} else if ((*start == '\"' && *end == '\"') || (*start == '\'' && *end == '\'')) {
start++, end--;
}
}
if (start <= end) values.push_back({0, h2_string(end - start + 1, start)});
}
}
};
| 30.742857 | 94 | 0.369424 | [
"vector"
] |
5860eb20660ff4af7a201b25e616cc75fc9d42db | 4,032 | cpp | C++ | src/imu-frontend/ImuFrontendParams.cpp | AllMySlam1/Kimera-VIO | 53621cd3d39b0facf81eb056e92ebd9037560c5b | [
"BSD-2-Clause"
] | null | null | null | src/imu-frontend/ImuFrontendParams.cpp | AllMySlam1/Kimera-VIO | 53621cd3d39b0facf81eb056e92ebd9037560c5b | [
"BSD-2-Clause"
] | null | null | null | src/imu-frontend/ImuFrontendParams.cpp | AllMySlam1/Kimera-VIO | 53621cd3d39b0facf81eb056e92ebd9037560c5b | [
"BSD-2-Clause"
] | null | null | null | /* ----------------------------------------------------------------------------
* Copyright 2017, Massachusetts Institute of Technology,
* Cambridge, MA 02139
* All Rights Reserved
* Authors: Luca Carlone, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file ImuFrontendParams.cpp
* @brief Params for ImuFrontend.
* @author Antoni Rosinol
*/
#include "kimera-vio/imu-frontend/ImuFrontendParams.h"
#include <glog/logging.h>
#include <gtsam/geometry/Pose3.h>
#include "kimera-vio/utils/UtilsOpenCV.h"
#include "kimera-vio/utils/YamlParser.h"
namespace VIO {
ImuParams::ImuParams() : PipelineParams("IMU params") {}
bool ImuParams::parseYAML(const std::string& filepath)
{
YamlParser yaml_parser(filepath);
int imu_preintegration_type;
yaml_parser.getYamlParam("imu_preintegration_type",
&imu_preintegration_type);
imu_preintegration_type_ =
static_cast<ImuPreintegrationType>(imu_preintegration_type);
// Rows and cols are redundant info, since the pose 4x4, but we parse just
// to check we are all on the same page.
// int n_rows = 0;
// yaml_parser.getNestedYamlParam("T_BS", "rows", &n_rows);
// CHECK_EQ(n_rows, 4u);
// int n_cols = 0;
// yaml_parser.getNestedYamlParam("T_BS", "cols", &n_cols);
// CHECK_EQ(n_cols, 4u);
std::vector<double> vector_pose;
yaml_parser.getNestedYamlParam("T_BS", "data", &vector_pose);
const gtsam::Pose3& body_Pose_cam =
UtilsOpenCV::poseVectorToGtsamPose3(vector_pose);
// Sanity check: IMU is usually chosen as the body frame.
LOG_IF(FATAL, !body_Pose_cam.equals(gtsam::Pose3::identity()))
<< "parseImuData: we expected identity body_Pose_cam_: is everything "
"ok?";
double rate_hz = 0.0;
yaml_parser.getYamlParam("rate_hz", &rate_hz);
CHECK_GT(rate_hz, 0.0);
nominal_sampling_time_s_ = 1.0 / rate_hz;
// IMU PARAMS
yaml_parser.getYamlParam("gyroscope_noise_density", &gyro_noise_density_);
yaml_parser.getYamlParam("accelerometer_noise_density",
&acc_noise_density_);
yaml_parser.getYamlParam("gyroscope_random_walk", &gyro_random_walk_);
yaml_parser.getYamlParam("accelerometer_random_walk", &acc_random_walk_);
yaml_parser.getYamlParam("imu_integration_sigma", &imu_integration_sigma_);
yaml_parser.getYamlParam("imu_time_shift", &imu_time_shift_);
std::vector<double> n_gravity;
yaml_parser.getYamlParam("n_gravity", &n_gravity);
CHECK_EQ(n_gravity.size(), 3);
for (int k = 0; k < 3; k++)
n_gravity_(k) = n_gravity[k];
return true;
}
void ImuParams::print() const
{
std::stringstream out;
PipelineParams::print(out, "gyroscope_noise_density: ", gyro_noise_density_,
"gyroscope_random_walk: ", gyro_random_walk_,
"accelerometer_noise_density: ", acc_noise_density_,
"accelerometer_random_walk: ", acc_random_walk_,
"imu_integration_sigma: ", imu_integration_sigma_,
"imu_time_shift: ", imu_time_shift_,
"n_gravity: ", n_gravity_);
LOG(INFO) << out.str();
}
bool ImuParams::equals(const PipelineParams& obj) const
{
const auto& rhs = static_cast<const ImuParams&>(obj);
// clang-format off
return imu_preintegration_type_ == rhs.imu_preintegration_type_ &&
gyro_noise_density_ == rhs.gyro_noise_density_ &&
gyro_random_walk_ == rhs.gyro_random_walk_ &&
acc_noise_density_ == rhs.acc_noise_density_ &&
acc_random_walk_ == rhs.acc_random_walk_ &&
imu_time_shift_ == rhs.imu_time_shift_ &&
nominal_sampling_time_s_ == rhs.nominal_sampling_time_s_ &&
imu_integration_sigma_ == rhs.imu_integration_sigma_ &&
n_gravity_ == rhs.n_gravity_;
// clang-format on
}
} // namespace VIO
| 37.333333 | 80 | 0.655258 | [
"geometry",
"vector"
] |
5864d0f7c8b51ec8f9163e6d386cd28856a9b6a6 | 6,384 | cpp | C++ | Engine/2d/vectorimage.cpp | Sebbestune/MoltenTempest | f77258355dde5648085847da2f4517ffb97b31ff | [
"MIT"
] | null | null | null | Engine/2d/vectorimage.cpp | Sebbestune/MoltenTempest | f77258355dde5648085847da2f4517ffb97b31ff | [
"MIT"
] | null | null | null | Engine/2d/vectorimage.cpp | Sebbestune/MoltenTempest | f77258355dde5648085847da2f4517ffb97b31ff | [
"MIT"
] | null | null | null | #include "vectorimage.h"
#include <Tempest/Device>
#include <Tempest/Builtin>
#include <Tempest/Painter>
#include <Tempest/Event>
#include <Tempest/Encoder>
#define NANOSVG_IMPLEMENTATION
#include "thirdparty/nanosvg.h"
using namespace Tempest;
void VectorImage::beginPaint(bool clr, uint32_t w, uint32_t h) {
if(clr || blocks.size()==0)
clear();
if(clr) {
info.w=w;
info.h=h;
}
paintScope++;
}
void VectorImage::endPaint() {
paintScope--;
if(paintScope!=0)
return;
for(size_t i=0;i<frameCount;++i)
frame[i].outdated=true;
outdatedCount=frameCount;
}
size_t VectorImage::pushState() {
size_t sz=stateStk.size();
stateStk.push_back(blocks.back());
return sz;
}
void VectorImage::popState(size_t id) {
State& s = stateStk[id];
State& b = reinterpret_cast<State&>(blocks.back());
if(b==s)
return;
if(blocks.back().size==0) {
b=s;
} else {
blocks.emplace_back(s);
blocks.back().begin =buf.size();
blocks.back().size =0;
}
stateStk.resize(id);
}
template<class T,T VectorImage::State::*param>
void VectorImage::setState(const T &t) {
// blocks.size()>0, see VectorImage::clear()
if(blocks.back().*param==t)
return;
if(blocks.back().size==0){
blocks.back().*param=t;
return;
}
blocks.push_back(blocks.back());
blocks.back().begin =buf.size();
blocks.back().size =0;
blocks.back().*param=t;
}
void VectorImage::setState(const TexPtr &t,const Color&,TextureFormat frm) {
Texture tex={t,frm,Sprite()};
setState<Texture,&State::tex>(tex);
blocks.back().hasImg=bool(t);
}
void VectorImage::setState(const Sprite &s, const Color&) {
Texture tex={TexPtr(),TextureFormat::Undefined,s};
setState<Texture,&State::tex>(tex);
blocks.back().hasImg=!s.isEmpty();
slock.insert(s);
}
void VectorImage::setTopology(Topology t) {
setState<Topology,&State::tp>(t);
}
void VectorImage::setBlend(const Painter::Blend b) {
setState<Painter::Blend,&State::blend>(b);
}
void VectorImage::clear() {
buf.clear();
blocks.resize(1);
blocks.back()=Block();
stateStk.clear();
slock.clear();
}
void VectorImage::addPoint(const PaintDevice::Point &p) {
buf.push_back(p);
blocks.back().size++;
}
void VectorImage::commitPoints() {
blocks.resize(blocks.size());
while(blocks.size()>1){
if(blocks.back().size!=0)
return;
blocks.pop_back();
}
}
void VectorImage::makeActual(Device &dev,Swapchain& sw) {
if(!frame || frameCount!=dev.maxFramesInFlight()) {
uint8_t count=dev.maxFramesInFlight();
frame.reset(new PerFrame[count]);
frameCount=count;
}
PerFrame& f=frame[sw.frameId()];
if(f.outdated) {
if(f.vbo.size()==buf.size())
f.vbo.update(buf); else
f.vbo=dev.vboDyn(buf);
f.blocksType.resize(blocks.size());
f.blocks .resize(blocks.size());
for(size_t i=0;i<blocks.size();++i){
auto& b =blocks[i];
Uniforms& ux=f.blocks[i];
UboType t =(b.hasImg) ? UT_Img : UT_NoImg;
if(ux.isEmpty() || f.blocksType[i]!=t){
auto& p = pipelineOf(dev,b);
ux = dev.uniforms(p.layout());
f.blocksType[i] = t;
}
if(t==UT_Img) {
if(b.tex.brush) {
if(b.tex.frm==TextureFormat::R8 || b.tex.frm==TextureFormat::R16) {
Sampler2d s;
s.mapping.r = ComponentSwizzle::R;
s.mapping.g = ComponentSwizzle::R;
s.mapping.b = ComponentSwizzle::R;
ux.set(0,b.tex.brush,s);
}
else if(b.tex.frm==TextureFormat::RG8 || b.tex.frm==TextureFormat::RG16) {
Sampler2d s;
s.mapping.r = ComponentSwizzle::R;
s.mapping.g = ComponentSwizzle::R;
s.mapping.b = ComponentSwizzle::R;
s.mapping.a = ComponentSwizzle::G;
ux.set(0,b.tex.brush,s);
}
else {
ux.set(0,b.tex.brush);
}
} else {
ux.set(0,b.tex.sprite.pageRawData(dev)); //TODO: oom
}
}
}
f.outdated=false;
outdatedCount--;
if(outdatedCount==0)
buf.clear();
}
}
const RenderPipeline& VectorImage::pipelineOf(Device& dev, const VectorImage::Block& b) {
const RenderPipeline* p;
if(b.hasImg) {
if(b.tp==Triangles){
if(b.blend==NoBlend)
p=&dev.builtin().texture2d().brush; else
if(b.blend==Alpha)
p=&dev.builtin().texture2d().brushB; else
p=&dev.builtin().texture2d().brushA;
} else {
if(b.blend==NoBlend)
p=&dev.builtin().texture2d().pen; else
if(b.blend==Alpha)
p=&dev.builtin().texture2d().penB; else
p=&dev.builtin().texture2d().penA;
}
} else {
if(b.tp==Triangles) {
if(b.blend==NoBlend)
p=&dev.builtin().empty().brush; else
if(b.blend==Alpha)
p=&dev.builtin().empty().brushB; else
p=&dev.builtin().empty().brushA;
} else {
if(b.blend==NoBlend)
p=&dev.builtin().empty().pen; else
if(b.blend==Alpha)
p=&dev.builtin().empty().penB; else
p=&dev.builtin().empty().penA;
}
}
return *p;
}
void VectorImage::draw(Device& dev, Swapchain& sw, Encoder<CommandBuffer> &cmd) {
makeActual(dev,sw);
PerFrame& f=frame[sw.frameId()];
for(size_t i=0;i<blocks.size();++i){
auto& b=blocks[i];
auto& u=f.blocks[i];
if(b.size==0)
continue;
if(!b.pipeline) {
b.pipeline=PipePtr(pipelineOf(dev,b));
}
if(b.hasImg)
cmd.setUniforms(b.pipeline,u); else
cmd.setUniforms(b.pipeline);
cmd.draw(f.vbo,b.begin,b.size);
}
}
bool VectorImage::load(const char *file) {
NSVGimage* image = nsvgParseFromFile(file,"px",96);
if(image==nullptr)
return false;
try {
VectorImage img;
//PaintEvent event(img,int(image->width),int(image->height));
//Painter p(event);
for(NSVGshape* shape=image->shapes; shape!=nullptr; shape=shape->next) {
for(NSVGpath* path=shape->paths; path!=nullptr; path=path->next) {
for(int i=0; i<path->npts-1; i+=3) {
const float* p = &path->pts[i*2];
//drawCubicBez(p[0],p[1], p[2],p[3], p[4],p[5], p[6],p[7]);
}
}
}
*this=std::move(img);
}
catch(...){
nsvgDelete(image);
return false;
}
nsvgDelete(image);
return true;
}
| 24.45977 | 89 | 0.586936 | [
"shape"
] |
5868813473d80282bad138eb7ff0b20a44442cbd | 1,271 | hpp | C++ | Source/Stdinclude.hpp | MilkywayPwns/ExtendedConsole | 388cb1077d1c9f7a47817807c4ac525fc178fe54 | [
"MIT"
] | 2 | 2019-09-20T21:58:00.000Z | 2021-07-31T01:17:14.000Z | Source/Stdinclude.hpp | RektInator/ExtendedConsole | 388cb1077d1c9f7a47817807c4ac525fc178fe54 | [
"MIT"
] | null | null | null | Source/Stdinclude.hpp | RektInator/ExtendedConsole | 388cb1077d1c9f7a47817807c4ac525fc178fe54 | [
"MIT"
] | 3 | 2019-01-23T19:35:39.000Z | 2020-03-21T16:16:50.000Z | /*
Initial author: Convery (tcn@hedgehogscience.com)
Started: 08-01-2018
License: MIT
Notes:
Provides a single include-file for all modules.
*/
#pragma once
// The configuration settings.
#include "Configuration/Defines.hpp"
#include "Configuration/Macros.hpp"
// Standard libraries.
#include <unordered_map>
#include <string_view>
#include <functional>
#include <assert.h>
#include <cstdint>
#include <cstdarg>
#include <cstring>
#include <cstdio>
#include <vector>
#include <memory>
#include <chrono>
#include <thread>
#include <string>
#include <mutex>
#include <ctime>
// Platformspecific libraries.
#if defined(_WIN32)
#include <Windows.h>
#include <direct.h>
#include <intrin.h>
#undef min
#undef max
#else
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
#include <dirent.h>
#include <dlfcn.h>
#endif
// Utility modules.
#include "Utility/Variadicstring.hpp"
#include "Utility/Patternscan.hpp"
#include "Utility/Filesystem.hpp"
#include "Utility/Memprotect.hpp"
#include "Utility/Bytebuffer.hpp"
#include "Utility/PackageFS.hpp"
#include "Utility/FNV1Hash.hpp"
#include "Utility/Hooking.hpp"
#include "Utility/Logfile.hpp"
#include "Utility/Base64.hpp"
| 21.542373 | 55 | 0.711251 | [
"vector"
] |
586b71b719589c46f431d9d2fad5edc8befd77d8 | 19,720 | cc | C++ | 4_performance_evaluation/src/eval_merci.cc | SNU-ARC/MERCI | cce40ac946e26a328aa1b8d10559c4812f42d0f8 | [
"MIT"
] | 7 | 2021-04-29T13:07:54.000Z | 2022-02-21T04:20:18.000Z | 4_performance_evaluation/src/eval_merci.cc | SNU-ARC/MERCI | cce40ac946e26a328aa1b8d10559c4812f42d0f8 | [
"MIT"
] | 1 | 2021-12-07T01:22:04.000Z | 2021-12-07T01:22:04.000Z | 4_performance_evaluation/src/eval_merci.cc | SNU-ARC/MERCI | cce40ac946e26a328aa1b8d10559c4812f42d0f8 | [
"MIT"
] | 1 | 2021-05-18T02:11:01.000Z | 2021-05-18T02:11:01.000Z | #include "utils.h"
#include "evaluator.h"
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#define INTERVAL 1
// Too Large Buffer size -> Perf Degradation
// Too Small Buffer size -> Perf Degradation
// BUF_SIZE should be set to 1024 in case of dblp dataset
#define BUF_SIZE (512)
#define LBUF_SIZE (512)
#define BUF_FLUSH (0.5f)
// Cond #1 BUF_SIZE * (1-BUF_FLUSH) should be large enough to avoid overflow
struct GroupInfo{
int offset;
int cluster_size;
int memoizationTable_base;
};
class MERCI: public Evaluator {
public:
vector<array<float, EMBEDDING_DIM>> memoizationTable; //not created for baseline
vector<array<float, EMBEDDING_DIM>> oneTable; //not created for baseline
int num_partition;
GroupInfo* groupInfo;
uint8_t groupInfo_size;
vector<int> num_clusters_per_group;
int pcount_accum, lcount_accum;
int emb_table_size;
/* constructors */
MERCI(int np, int emb_table_size_, int core_count, GroupInfo* groupInfo_, vector<int>& num_cluster_per_group_accum) : Evaluator(core_count), num_partition(np) {
groupInfo_size = num_cluster_per_group_accum.size();
groupInfo = new GroupInfo[groupInfo_size];
groupInfo = groupInfo_;
num_clusters_per_group.push_back(num_cluster_per_group_accum[0]);
for(auto i=1; i<int(num_cluster_per_group_accum.size())-1; i++)
num_clusters_per_group.push_back(num_cluster_per_group_accum[i]-num_cluster_per_group_accum[i-1]);
assert(groupInfo_size <= 256);
emb_table_size = emb_table_size_;
}
void build_memoization_table() {
build_embedding_table(emb_table_size);
uint64_t table_size = 0;
int new_size = -1;
if(groupInfo[groupInfo_size-2].cluster_size==1) // if there exist features that only belong to test queries (not in train queries)
new_size = groupInfo_size-2;
else
new_size = groupInfo_size-1;
for(auto i=0; i< new_size; i++) // except for the last group of cluster size one and group with features only in test queries
table_size += (pow(2, groupInfo[i].cluster_size)-1)*num_clusters_per_group[i];
memoizationTable.resize(table_size);
cout << "============================= Memoization Table INFO =============================" << endl;
cout << "Group ID " << "Base Offset " << "First Feature ID " << "Cluster Size " << "# Clusters" << endl;
auto base = 0;
for(int i=0; i<new_size; i++){
const auto cluster_size = int(groupInfo[i].cluster_size);
const auto partition_table_size = pow(2, cluster_size)-1;
printf("%-10d %-15d %-20d %-15d %-10d\n", i, base, groupInfo[i].offset, cluster_size, num_clusters_per_group[i]);
#pragma omp parallel for
for(int j=0; j<num_clusters_per_group[i]; j++){
auto embedding_base = groupInfo[i].offset + j*cluster_size;
for(int k=1; k<partition_table_size+1; k++){
array<float, EMBEDDING_DIM> value;
for(int t=0; t<EMBEDDING_DIM; t++)
value[t] = 0;
for(int idx=0; idx<cluster_size; idx++){
if((k >> idx)&1){
for(auto t=0; t<EMBEDDING_DIM; t++)
value[t] += embedding_table[embedding_base+idx][t];
}
}
assert(base+j*partition_table_size+k-1 < table_size);
for(int l=0; l<EMBEDDING_DIM; l++)
memoizationTable[int(base+j*partition_table_size+k-1)][l] = value[l];
}
}
groupInfo[i].memoizationTable_base = base;
base += partition_table_size*num_clusters_per_group[i];
}
oneTable.resize(emb_table_size-groupInfo[new_size].offset);
for(int i=0; i<(emb_table_size-groupInfo[new_size].offset); i++){
for(int t=0; t<EMBEDDING_DIM; t++){
oneTable[i][t] = embedding_table[groupInfo[new_size].offset+i][t];
}
}
int one = 1;
printf("%-10d %-15d %-20d %-15d %-10d\n", new_size, base, groupInfo[new_size].offset, one, emb_table_size-groupInfo[new_size].offset);
cout << "=================================================================================" << endl;
cout << "Memoization Table Generation Done, total " << table_size+emb_table_size-groupInfo[new_size].offset << " entries\n\n" << endl;
}
// TODO: Does not support groups more than 32
struct LocalGroupInfo {
int offsets[32];
int bases[32];
int cluster_sizes[32];
};
struct ProcessingInfo {
int query_base;
int lcount;
int pcount;
size_t curqlen;
size_t i;
int next_offset;
int cur_cluster_id;
int cluster_table_size;
int cur_offset;
int memoizationTable_base;
int cluster_size;
int section_id;
int qbit;
int pad[3];
};
void inline setvals(struct ProcessingInfo &p, struct LocalGroupInfo &lgi, int id, int feature_id, int cluster_size) {
int diff = feature_id - lgi.offsets[id];
p.cur_cluster_id = diff / cluster_size;
p.qbit = 1 << (diff % cluster_size);
p.cluster_size = cluster_size;
p.cluster_table_size = (1 << cluster_size) -1;
p.cur_offset = lgi.offsets[id];
p.next_offset = lgi.offsets[id+1];
p.memoizationTable_base = lgi.bases[id];
p.section_id = id;
}
void inline processKeys(const int *qarr, const int *karr, int count, int qbase) {
for(int j=0; j<count; j++) {
__builtin_prefetch(&memoizationTable[karr[j+2]][0], 0, 3);
__builtin_prefetch(&memoizationTable[karr[j+2]][16], 0, 3);
__builtin_prefetch(&memoizationTable[karr[j+2]][32], 0, 3);
__builtin_prefetch(&memoizationTable[karr[j+2]][48], 0, 3);
for(int k = 0; k < EMBEDDING_DIM; k++) {
qres[qarr[j] + qbase][k] += memoizationTable[karr[j]][k];
}
}
}
void inline processKeys_one(const int *qarr, const int *karr, int count, int qbase) {
for(int j=0; j<count; j++) {
__builtin_prefetch(&oneTable[karr[j+2]][0], 0, 3);
__builtin_prefetch(&oneTable[karr[j+2]][16], 0, 3);
__builtin_prefetch(&oneTable[karr[j+2]][32], 0, 3);
__builtin_prefetch(&oneTable[karr[j+2]][48], 0, 3);
for(int k = 0; k < EMBEDDING_DIM; k++) {
qres[qarr[j] + qbase][k] += oneTable[karr[j]][k];
}
}
}
void process(vector< vector<int> > &query, const int core_id) {
// Prologue
//ready += 1;
int *loads = new int[LBUF_SIZE];
int *qloads = new int[LBUF_SIZE];
int *eloads = new int[LBUF_SIZE];
int *pkeys = new int[BUF_SIZE];
int *qkeys = new int[BUF_SIZE];
int *eqkeys = new int[BUF_SIZE];
memset(loads, 0, LBUF_SIZE*4);
memset(qloads, 0, LBUF_SIZE*4);
memset(pkeys, 0, BUF_SIZE*4);
memset(qkeys, 0, BUF_SIZE*4);
memset(eqkeys, 0, LBUF_SIZE*4);
memset(eloads, 0, LBUF_SIZE*4);
int SECTION_COUNT;
int one_offset;
if(groupInfo[groupInfo_size-2].cluster_size==1){
SECTION_COUNT = groupInfo_size-2;
one_offset = groupInfo[groupInfo_size-2].offset;
}
else{
SECTION_COUNT = groupInfo_size-1;
one_offset = groupInfo[groupInfo_size-1].offset;
}
// cout << "here" << core_id << endl;
ProcessingInfo p={thrinfo[core_id].qbase, 0, 0,// query_base, lcount, pcount
0, 0, // curqlen, i
-1, // next_offset
-1, // cur_cluster_id
-1, // cluster_table_size
-1, -1, -1, -1, 0, 0, 0}; // cur_offset, memoizationTable_base, cluster_size
LocalGroupInfo localGroupInfo;
assert((INTERVAL==1 && sizeof(localGroupInfo.offsets)==32*4) || (INTERVAL==4 && sizeof(localGroupInfo.offsets)==16*4));
for(auto i=0; i<groupInfo_size; i++){
localGroupInfo.offsets[i] = groupInfo[i].offset;
localGroupInfo.bases[i] = groupInfo[i].memoizationTable_base;
localGroupInfo.cluster_sizes[i] = groupInfo[i].cluster_size;
}
cstart.barrier_wait(core_count);
if(core_id == 0) {
start = steady_clock::now();
}
size_t qlen = query.size();
thrinfo[core_id].tstart = steady_clock::now();
for (p.i=0; p.i < qlen; p.i++) {
p.curqlen = query[p.i].size();
if(unlikely(p.curqlen == 1)){
for(int k = 0; k < EMBEDDING_DIM; k++) {
qres[p.i][k] += embedding_table[query[p.i][0]][k];
}
}
else{
p.qbit = 0;
int first_query = query[p.i][0];
for(int k=0; k<SECTION_COUNT; k++) {
if(first_query < localGroupInfo.offsets[k+1]) {
setvals(p, localGroupInfo, k, first_query, localGroupInfo.cluster_sizes[k]);
break;
}
}
if (unlikely(p.qbit == 0)) {
int diff = first_query - one_offset;
qloads[p.lcount] = p.i;
loads[p.lcount++] = diff;
for(size_t k=1; k<p.curqlen; k++) {
int diff = query[p.i][k] - one_offset;
qloads[p.lcount] = p.i;
loads[p.lcount++] = diff;
}
}
else {
for (size_t j = 1; j < p.curqlen; j++) {
int current_query = query[p.i][j];
if(current_query >= one_offset) {
if(p.qbit != 0) {
qkeys[p.pcount] = p.i;
pkeys[p.pcount++] = p.memoizationTable_base + p.cur_cluster_id * p.cluster_table_size + p.qbit-1;
p.qbit = 0;
}
int diff = current_query - one_offset;
qloads[p.lcount] = p.i;
loads[p.lcount++] = diff;
}
else if(current_query < p.next_offset){
int diff = (current_query-p.cur_offset);
int c_id = diff / p.cluster_size;
int c_rem = diff % p.cluster_size;
if(c_id == p.cur_cluster_id){ // if cluster id is same, just update qbit
p.qbit |= (1<<c_rem);
// change = false;
}
else{ // if cluster id is not the same, update pkeys
qkeys[p.pcount] = p.i;
pkeys[p.pcount++] = p.memoizationTable_base+p.cur_cluster_id*p.cluster_table_size+p.qbit-1;
p.qbit = 1 << c_rem;
p.cur_cluster_id = c_id;
}
}
else{ // if query belongs to the set of different size of cluster
qkeys[p.pcount] = p.i;
pkeys[p.pcount++] = p.memoizationTable_base + p.cur_cluster_id * p.cluster_table_size + p.qbit-1;
p.qbit = 0;
for(int k=p.section_id+1; k<SECTION_COUNT; k++) {
if(current_query < localGroupInfo.offsets[k+1]) {
setvals(p, localGroupInfo, k, current_query, localGroupInfo.cluster_sizes[k]);
break;
}
}
}
}
if(p.qbit != 0){
qkeys[p.pcount] = p.i;
pkeys[p.pcount++] = p.memoizationTable_base+p.cur_cluster_id*p.cluster_table_size + p.qbit-1;
}
}
if(unlikely(p.pcount > (BUF_SIZE * BUF_FLUSH))) {
processKeys(qkeys, pkeys, p.pcount, p.query_base);
p.pcount = 0;
}
if(unlikely(p.lcount > (LBUF_SIZE * BUF_FLUSH))) {
processKeys_one(qloads, loads, p.lcount, p.query_base);
p.lcount = 0;
}
}
}
processKeys(qkeys, pkeys, p.pcount, p.query_base);
processKeys_one(qloads, loads,p.lcount, p.query_base);
thrinfo[core_id].tend = steady_clock::now();
cend.barrier_wait(core_count);
if(core_id == 0) {
end = steady_clock::now();
}
}
int inline getKey(int i1, int i2) {
return i1 * PARTITION_SIZE + (i2 - i1 - 1) - i1 * (i1+1)/2;
}
bitset<PARTITION_SIZE> getBitSet(vector<int> &query, int sid, int eid, int pid) {
int base = pid * PARTITION_SIZE;
bitset<PARTITION_SIZE> key;
for (int i=sid; i <= eid; i++) {
key.set(query[i] - base);
}
return key;
}
};
int main(int argc, const char *argv[]) {
if (argc % 2 == 0) {
cout << "Usage: ./bin/eval_merci -d <dataset name> -p <# of partitions> --memory_ratio <ratio with regard to emb table> -c <core count> -r <repeat>" << endl;
return -1;
}
/* static file I/O variables */
string homeDir = getenv("HOME"); // home directory
string merciDir = homeDir + "/MERCI/data/"; // MERCI directory (located in $HOME/MERCI)
string datasetDir = merciDir + "6_evaluation_input/"; // input dataset directory
/*file I/O variables */
string datasetName;
string testFileName;
ifstream testFile;
/* counter variables */
int num_features = 0; // total number of features (train + test)
size_t core_count = thread::hardware_concurrency();
int repeat = 5;
int num_partition = -1; // total number of partitions
float memory_ratio = 0;
int emb_table_size = 0; //total length of embedding table
/* helper variables */
char read_sharp; // read #
int num_groups; // number of group with different sizes
/////////////////////////////////////////////////////////////////////////////
cout << "Eval Phase 0: Reading Command Line Arguments..." << endl << endl;
/////////////////////////////////////////////////////////////////////////////
/* parsing command line arguments */
for (int i = 0; i < argc; i++) {
string arg(argv[i]);
if (arg.compare("--dataset") == 0 || arg.compare("-d") == 0) {
datasetName = string(argv[i+1]);
++i; //skip next iteration
}
else if (arg.compare("--num_partition") == 0 || arg.compare("-p") == 0) {
num_partition = stoi(argv[i+1]);
++i;
}
else if (arg.compare("--memory_ratio") == 0) {
memory_ratio = stof(argv[i+1]);
++i;
}
else if (arg.compare("-c") == 0) {
core_count = stoi(argv[i+1]);
++i;
}
else if (arg.compare("-r") == 0) {
repeat = stoi(argv[i+1]);
++i;
}
}
/* Error Checking */
if (num_partition < 1) {
cout << "ARG ERROR: Insufficient options, please check parameters" << endl;
return -1;
}
cout << "=================== EVAL INFO ==================" << endl;
cout << "Embedding Dimension : " << EMBEDDING_DIM << endl;
cout << "Partition Size : " << PARTITION_SIZE << endl;
cout << "Debug : " << DEBUG << endl;
cout << "Number of Cores Supported by Hardware : " << thread::hardware_concurrency() << endl;
cout << "Number of Cores : " << core_count << endl;
cout << "===============================================" << endl << endl;
/////////////////////////////////////////////////////////////////////////////
cout << "Eval Phase 1: Retrieving Test Queries..." << endl << endl;
/////////////////////////////////////////////////////////////////////////////
//Step 1: Open test.dat file
testFileName = datasetDir + datasetName + "/partition_" + to_string(num_partition) + "/" + "test_" + to_string(memory_ratio) + "X_" + to_string(EMBEDDING_DIM) + "dim_" + to_string(PARTITION_SIZE) + ".dat";
cout << "Reading test file from " << testFileName << endl << endl;
testFile.open(testFileName, ifstream::in);
if (testFile.fail()) {
cout << "FILE ERROR: Could not open test.dat file" << endl;
return -1;
}
GroupInfo* groupInfo;
//Step 2: Read meta data
testFile >> read_sharp;
testFile >> num_features;
testFile >> emb_table_size;
testFile >> read_sharp;
testFile >> num_groups;
groupInfo = new GroupInfo[num_groups];
vector<int> num_cluster_per_group_accum(num_groups, -1);
for(auto i=0; i<num_groups; i++){
testFile >> groupInfo[i].offset;
testFile >> groupInfo[i].cluster_size;
testFile >> num_cluster_per_group_accum[i];
}
cout << "============= PARTITION META INFO =============" << endl;
cout << "# of Features (train + test) : " << num_features << endl;
cout << "# of Partitions : " << num_partition << endl;
cout << "Partition Size : " << PARTITION_SIZE << endl;
cout << "# of Embedding Table entries : " << emb_table_size << endl;
cout << "===============================================" << endl << endl;
if(num_partition * PARTITION_SIZE < 0.75 * emb_table_size || num_partition * PARTITION_SIZE > 1.25 * emb_table_size) {
cout << "Total # of items in the partition : " << num_partition * PARTITION_SIZE << endl;
cout << "# of Embedding Table Entries : " << emb_table_size << endl;
cout << "Shouldn't partition size be " << emb_table_size / num_partition << "? \n";
assert(false);
}
//Step 3: Read and store query(test) transactions
QueryData qd(testFile);
testFile.close(); //close file
vector<thread> t;
t.resize(core_count);
qd.partition(core_count);
cout << endl;
/////////////////////////////////////////////////////////////////////////////
cout << "Eval Phase 2: Generating Memoization Table..." << endl << endl;
/////////////////////////////////////////////////////////////////////////////
MERCI merci(num_partition, emb_table_size, core_count, groupInfo, num_cluster_per_group_accum);
merci.build_memoization_table();
cout << "Eval Phase 3: Running MERCI..." << endl << endl;
eval<MERCI>(merci, qd, core_count, t, repeat, "MERCI");
cout << endl;
#if DEBUG
double rsum = 0.0f;
size_t qlen = qd.query.size();
for(size_t i=0; i < qlen; i++) {
size_t curqlen = qd.query[i].size();
for(size_t j=0; j< curqlen; j++) {
for(size_t l=0; l < EMBEDDING_DIM; l++)
rsum += merci.embedding_table[qd.query[i][j]][l];
}
}
cout << "Correct Value : " << rsum << "\n";
#endif
return 0;
}
| 42.683983 | 209 | 0.509229 | [
"vector"
] |
586fa32837d6b238adebc95ad7f7a2bffd7b1c06 | 18,586 | cpp | C++ | modules/gdscript_transpiler/languages/gdscript_transpiler_cxx.cpp | orgrinrt/goost | 9dd3cd7f723115939a4590a637c35b05314e6b07 | [
"Apache-2.0",
"CC-BY-4.0",
"MIT"
] | 323 | 2020-07-14T09:57:03.000Z | 2022-03-26T07:04:03.000Z | modules/gdscript_transpiler/languages/gdscript_transpiler_cxx.cpp | TREVO786/goost | babbeb7583b603a59577cac3bf34c6e136ea7396 | [
"CC-BY-3.0",
"MIT"
] | 57 | 2020-08-21T08:20:47.000Z | 2022-03-31T23:46:17.000Z | modules/gdscript_transpiler/languages/gdscript_transpiler_cxx.cpp | TREVO786/goost | babbeb7583b603a59577cac3bf34c6e136ea7396 | [
"CC-BY-3.0",
"MIT"
] | 18 | 2020-09-07T14:53:24.000Z | 2022-02-19T10:41:22.000Z | #include "core/string_builder.h"
#include "gdscript_transpiler_cxx.h"
#include "gdscript_transpiler_utils.h"
String GDScriptTranspilerCpp::get_name() const {
return "C++";
}
Variant GDScriptTranspilerCpp::transpile(const Ref<GDScript> &p_script) {
ERR_FAIL_COND_V_MSG(p_script.is_null(), Dictionary(), "Invalid script.")
GDScriptParser parser;
script_path = p_script->get_path();
parser.parse(p_script->get_source_code(), script_path.get_base_dir(), false, script_path, false, nullptr, false);
const GDScriptParser::Node *gd_tree = parser.get_parse_tree();
ERR_FAIL_COND_V(gd_tree->type != GDScriptParser::Node::TYPE_CLASS, Variant());
const Node *cpp_tree = translate_node(gd_tree);
code["header"] = GDScriptTranspilerUtils::CodeBuilder();
code["source"] = GDScriptTranspilerUtils::CodeBuilder();
transpile_node(cpp_tree);
Dictionary ret;
for (Map<String, GDScriptTranspilerUtils::CodeBuilder>::Element *E = code.front(); E; E = E->next()) {
ret[E->key()] = E->get().get_code();
}
clear();
return ret;
}
template <class T>
T *GDScriptTranspilerCpp::new_node() {
T *node = memnew(T);
node->next = list;
list = node;
if (!head) {
head = node;
}
return node;
}
String GDScriptTranspilerCpp::to_string(const GDScriptParser::DataType &p_datatype) {
String type = p_datatype.to_string();
if (!p_datatype.has_type) {
type = "Variant";
} else if (p_datatype.builtin_type == Variant::NIL) {
type = "void";
}
return type;
}
void GDScriptTranspilerCpp::clear() {
while (list) {
Node *l = list;
list = list->next;
memdelete(l);
}
head = nullptr;
list = nullptr;
code.clear();
parsed_expression.clear();
}
GDScriptTranspilerCpp::Node *GDScriptTranspilerCpp::translate_node(const GDScriptParser::Node *p_node) {
if (!p_node) {
return nullptr;
}
switch (p_node->type) {
case GDScriptParser::Node::TYPE_CLASS: {
auto class_node = static_cast<const GDScriptParser::ClassNode *>(p_node);
return translate_class(class_node);
} break;
case GDScriptParser::Node::TYPE_FUNCTION: {
auto func_node = static_cast<const GDScriptParser::FunctionNode *>(p_node);
return translate_function(func_node);
} break;
case GDScriptParser::Node::TYPE_BUILT_IN_FUNCTION: {
ERR_FAIL_V_MSG(nullptr, "Type not implemented yet.");
} break;
case GDScriptParser::Node::TYPE_BLOCK: {
auto block_node = static_cast<const GDScriptParser::BlockNode *>(p_node);
return translate_block(block_node);
} break;
case GDScriptParser::Node::TYPE_IDENTIFIER: {
auto gd_id = static_cast<const GDScriptParser::IdentifierNode *>(p_node);
auto id = new_node<IdentifierNode>();
id->name = String(gd_id->name);
id->datatype = to_string(gd_id->datatype);
return id;
} break;
case GDScriptParser::Node::TYPE_TYPE: {
ERR_FAIL_V_MSG(nullptr, "Type not implemented yet.");
} break;
case GDScriptParser::Node::TYPE_CONSTANT: {
auto gd_cnode = static_cast<const GDScriptParser::ConstantNode *>(p_node);
auto cpp_cnode = new_node<ConstantNode>();
cpp_cnode->value = gd_cnode->value;
cpp_cnode->datatype = to_string(gd_cnode->datatype);
cpp_cnode->is_enum = gd_cnode->datatype.builtin_type == Variant::DICTIONARY;
return cpp_cnode;
} break;
case GDScriptParser::Node::TYPE_ARRAY: {
ERR_FAIL_V_MSG(nullptr, "Type not implemented yet.");
} break;
case GDScriptParser::Node::TYPE_DICTIONARY: {
ERR_FAIL_V_MSG(nullptr, "Type not implemented yet.");
} break;
case GDScriptParser::Node::TYPE_SELF: {
ERR_FAIL_V_MSG(nullptr, "Type not implemented yet.");
} break;
case GDScriptParser::Node::TYPE_OPERATOR: {
auto op_node = static_cast<const GDScriptParser::OperatorNode *>(p_node);
auto cpp_op_node = new_node<OperatorNode>();
cpp_op_node->op = OperatorNode::Operator(op_node->op);
Vector<Node *> arguments;
for (int i = 0; i < op_node->arguments.size(); i++) {
arguments.push_back(translate_node(op_node->arguments[i]));
}
cpp_op_node->arguments = arguments;
cpp_op_node->datatype = to_string(op_node->datatype);
return cpp_op_node;
} break;
case GDScriptParser::Node::TYPE_CONTROL_FLOW: {
ERR_FAIL_V_MSG(nullptr, "Type not implemented yet.");
} break;
case GDScriptParser::Node::TYPE_LOCAL_VAR: {
auto gd_lvar = static_cast<const GDScriptParser::LocalVarNode *>(p_node);
auto lvar = new_node<LocalVarNode>();
lvar->name = String(gd_lvar->name);
lvar->assign = translate_node(gd_lvar->assign);
lvar->assign_op = static_cast<OperatorNode *>(translate_node(gd_lvar->assign_op));
lvar->datatype = to_string(gd_lvar->datatype);
return lvar;
} break;
case GDScriptParser::Node::TYPE_CAST: {
ERR_FAIL_V_MSG(nullptr, "Type not implemented yet.");
} break;
case GDScriptParser::Node::TYPE_ASSERT: {
ERR_FAIL_V_MSG(nullptr, "Type not implemented yet.");
} break;
case GDScriptParser::Node::TYPE_BREAKPOINT: {
ERR_FAIL_V_MSG(nullptr, "Type not implemented yet.");
} break;
case GDScriptParser::Node::TYPE_NEWLINE: {
return nullptr; // skip
} break;
default: {
ERR_FAIL_V_MSG(nullptr, "Type not implemented yet.");
}
}
}
GDScriptTranspilerCpp::ClassNode *GDScriptTranspilerCpp::translate_class(const GDScriptParser::ClassNode *p_class) {
const GDScriptParser::ClassNode *gd_class = p_class;
auto cpp_class = new_node<ClassNode>();
// Class
if (gd_class->classname_used) {
cpp_class->class_name = gd_class->name;
} else {
cpp_class->class_name = GDScriptTranspilerUtils::filepath_to_pascal_case(script_path);
}
cpp_class->inherits = "Reference"; // by default
if (gd_class->extends_used) {
if (gd_class->extends_file != String()) {
cpp_class->inherits = GDScriptTranspilerUtils::filepath_to_pascal_case(String(gd_class->extends_file));
} else if (!gd_class->extends_class.empty()) {
cpp_class->inherits = gd_class->extends_class[0];
}
}
// Members
for (int i = 0; i < gd_class->variables.size(); ++i) {
const GDScriptParser::ClassNode::Member &gd_member = gd_class->variables[i];
ClassNode::Member cpp_member;
cpp_member.info = gd_member._export;
cpp_member.identifier = gd_member.identifier;
cpp_member.setter = gd_member.setter;
cpp_member.getter = gd_member.getter;
if (cpp_member.identifier.begins_with("_")) {
// A convention used to separate private from public members in GDScript.
cpp_member.access = AccessSpecifier::ACCESS_PRIVATE;
}
cpp_member.type = to_string(gd_member.data_type);
if (!gd_member.data_type.has_type) {
if (cpp_member.info.hint == PROPERTY_HINT_ENUM) {
cpp_member.type = "int";
}
}
cpp_member.expression = translate_node(gd_member.expression);
cpp_class->variables.push_back(cpp_member);
}
// Constants
for (auto E = gd_class->constant_expressions.front(); E; E = E->next()) {
ClassNode::Constant cpp_const;
cpp_const.expression = translate_node(E->get().expression);
cpp_const.datatype = to_string(E->get().type);
cpp_const.is_enum = E->get().type.builtin_type == Variant::DICTIONARY;
cpp_class->constant_expressions.insert(E->key(), cpp_const);
}
// Functions
for (int i = 0; i < gd_class->functions.size(); ++i) {
const GDScriptParser::FunctionNode *gd_func = gd_class->functions[i];
auto cpp_func = static_cast<FunctionNode *>(translate_node(gd_func));
cpp_class->functions.push_back(cpp_func);
}
return cpp_class;
}
GDScriptTranspilerCpp::FunctionNode *GDScriptTranspilerCpp::translate_function(const GDScriptParser::FunctionNode *p_function) {
auto gd_func = p_function;
auto cpp_func = new_node<FunctionNode>();
cpp_func->name = gd_func->name;
if (cpp_func->name.begins_with("_")) {
// A convention used to separate private from public methods in GDScript.
cpp_func->access = AccessSpecifier::ACCESS_PRIVATE;
}
cpp_func->return_type = to_string(gd_func->return_type);
Vector<String> arguments;
Vector<String> argument_types;
// We can assume that arguments and types have the same size.
for (int j = 0; j < gd_func->arguments.size(); ++j) {
String arg = gd_func->arguments[j];
arguments.push_back(arg);
const GDScriptParser::DataType &gd_arg_type = gd_func->argument_types[j];
String type = to_string(gd_arg_type);
if (gd_arg_type.kind == GDScriptParser::DataType::BUILTIN) {
if (cpp_func->name.begins_with("set")) {
type = vformat("const %s &", type);
}
}
argument_types.push_back(type);
}
cpp_func->arguments = arguments;
cpp_func->argument_types = argument_types;
Vector<Node *> default_values;
for (int j = 0; j < gd_func->default_values.size(); ++j) {
Node *expression = translate_node(gd_func->default_values[j]);
default_values.push_back(expression);
}
cpp_func->body = static_cast<BlockNode *>(translate_node(gd_func->body));
return cpp_func;
}
GDScriptTranspilerCpp::BlockNode *GDScriptTranspilerCpp::translate_block(const GDScriptParser::BlockNode *p_block) {
auto cpp_block = new_node<BlockNode>();
List<Node *> statements;
for (auto E = p_block->statements.front(); E; E = E->next()) {
auto s = translate_node(E->get());
statements.push_back(s);
}
cpp_block->statements = statements;
Map<StringName, LocalVarNode *> variables;
for (auto E = p_block->variables.front(); E; E = E->next()) {
auto cpp_lvar = new_node<LocalVarNode>();
cpp_lvar->name = String(E->get()->name);
cpp_lvar->assign = translate_node(E->get()->assign);
cpp_lvar->assign_op = static_cast<OperatorNode *>(translate_node(E->get()->assign_op));
cpp_lvar->datatype = to_string(E->get()->datatype);
variables.insert(cpp_lvar->name, cpp_lvar);
}
cpp_block->variables = variables;
cpp_block->has_return = p_block->has_return;
return cpp_block;
}
void GDScriptTranspilerCpp::transpile_node(const Node *p_node) {
if (!p_node) {
return;
}
GDScriptTranspilerUtils::CodeBuilder &hpp = code["header"];
GDScriptTranspilerUtils::CodeBuilder &cpp = code["source"];
switch (p_node->type) {
case Node::TYPE_CLASS: {
auto class_node = static_cast<const ClassNode *>(p_node);
transpile_class(class_node);
} break;
case Node::TYPE_FUNCTION: {
} break;
case Node::TYPE_BUILT_IN_FUNCTION: {
} break;
case Node::TYPE_BLOCK: {
} break;
case Node::TYPE_IDENTIFIER: {
} break;
case Node::TYPE_TYPE: {
} break;
case Node::TYPE_CONSTANT: {
auto cnode = static_cast<const ConstantNode *>(p_node);
if (cnode->is_enum) {
ERR_FAIL_COND(cnode->value.get_type() != Variant::DICTIONARY);
const Dictionary &d = cnode->value;
List<Variant> keys;
d.get_key_list(&keys);
String enum_indent = hpp.get_indent_string();
String const_indent = enum_indent + hpp.get_indent_sequence();
String str("{\n");
for (List<Variant>::Element *E = keys.front(); E; E = E->next()) {
str += const_indent;
str += vformat("%s = %s,\n", E->get(), d[E->get()]);
}
str += enum_indent;
str += "};";
parsed_expression = str;
} else {
switch (cnode->value.get_type()) {
case Variant::STRING: {
parsed_expression = "\"" + String(cnode->value) + "\"";
} break;
case Variant::BOOL: {
bool v = cnode->value;
parsed_expression = v ? "true" : "false";
} break;
case Variant::NIL: {
parsed_expression = "nullptr";
}
default: {
parsed_expression = cnode->value;
}
}
}
} break;
case Node::TYPE_ARRAY: {
} break;
case Node::TYPE_DICTIONARY: {
} break;
case Node::TYPE_SELF: {
} break;
case Node::TYPE_OPERATOR: {
auto op_node = static_cast<const OperatorNode *>(p_node);
switch (op_node->op) {
case OperatorNode::OP_CALL: {
// parsed_expression =
} break;
case OperatorNode::OP_PARENT_CALL: {
// parsed_expression =
} break;
case OperatorNode::OP_YIELD: {
// parsed_expression =
} break;
case OperatorNode::OP_IS: {
// parsed_expression =
} break;
case OperatorNode::OP_IS_BUILTIN: {
// parsed_expression =
} break;
case OperatorNode::OP_INDEX: {
// parsed_expression =
} break;
case OperatorNode::OP_INDEX_NAMED: {
// parsed_expression =
} break;
case OperatorNode::OP_NEG: {
// parsed_expression =
} break;
case OperatorNode::OP_POS: {
// parsed_expression =
} break;
case OperatorNode::OP_NOT: {
// parsed_expression =
} break;
case OperatorNode::OP_BIT_INVERT: {
// parsed_expression =
} break;
case OperatorNode::OP_IN: {
// parsed_expression =
} break;
case OperatorNode::OP_EQUAL: {
// parsed_expression =
} break;
case OperatorNode::OP_NOT_EQUAL: {
// parsed_expression =
} break;
case OperatorNode::OP_LESS: {
// parsed_expression =
} break;
case OperatorNode::OP_LESS_EQUAL: {
// parsed_expression =
} break;
case OperatorNode::OP_GREATER: {
// parsed_expression =
} break;
case OperatorNode::OP_GREATER_EQUAL: {
// parsed_expression =
} break;
case OperatorNode::OP_AND: {
// parsed_expression =
} break;
case OperatorNode::OP_OR: {
// parsed_expression =
} break;
case OperatorNode::OP_ADD: {
// parsed_expression =
} break;
case OperatorNode::OP_SUB: {
// parsed_expression =
} break;
case OperatorNode::OP_MUL: {
// parsed_expression =
} break;
case OperatorNode::OP_DIV: {
// parsed_expression =
} break;
case OperatorNode::OP_MOD: {
// parsed_expression =
} break;
case OperatorNode::OP_SHIFT_LEFT: {
// parsed_expression =
} break;
case OperatorNode::OP_SHIFT_RIGHT: {
// parsed_expression =
} break;
case OperatorNode::OP_INIT_ASSIGN: {
// transpile_node(op_node->arguments[0]);
// String a = parsed_expression;
// transpile_node(op_node->arguments[1]);
// String b = parsed_expression;
// parsed_expression = vformat("%s = %s", a, b);
} break;
case OperatorNode::OP_ASSIGN: {
transpile_node(op_node->arguments[0]);
String a = parsed_expression;
transpile_node(op_node->arguments[1]);
String b = parsed_expression;
if (!a.empty()) {
parsed_expression = vformat("%s = %s", a, b);
} else {
parsed_expression = vformat(" = %s", b);
}
} break;
case OperatorNode::OP_ASSIGN_ADD: {
// parsed_expression =
} break;
case OperatorNode::OP_ASSIGN_SUB: {
// parsed_expression =
} break;
case OperatorNode::OP_ASSIGN_MUL: {
// parsed_expression =
} break;
case OperatorNode::OP_ASSIGN_DIV: {
// parsed_expression =
} break;
case OperatorNode::OP_ASSIGN_MOD: {
// parsed_expression =
} break;
case OperatorNode::OP_ASSIGN_SHIFT_LEFT: {
// parsed_expression =
} break;
case OperatorNode::OP_ASSIGN_SHIFT_RIGHT: {
// parsed_expression =
} break;
case OperatorNode::OP_ASSIGN_BIT_AND: {
// parsed_expression =
} break;
case OperatorNode::OP_ASSIGN_BIT_OR: {
// parsed_expression =
} break;
case OperatorNode::OP_ASSIGN_BIT_XOR: {
// parsed_expression =
} break;
case OperatorNode::OP_BIT_AND: {
// parsed_expression =
} break;
case OperatorNode::OP_BIT_OR: {
// parsed_expression =
} break;
case OperatorNode::OP_BIT_XOR: {
// parsed_expression =
} break;
case OperatorNode::OP_TERNARY_IF: {
// parsed_expression =
} break;
case OperatorNode::OP_TERNARY_ELSE: {
// parsed_expression =
} break;
}
} break;
case Node::TYPE_CONTROL_FLOW: {
} break;
case Node::TYPE_LOCAL_VAR: {
auto lvar = static_cast<const LocalVarNode *>(p_node);
transpile_node(lvar->assign_op);
cpp += vformat("%s %s%s;", lvar->datatype, lvar->name, parsed_expression);
} break;
case Node::TYPE_CAST: {
} break;
case Node::TYPE_ASSERT: {
} break;
case Node::TYPE_BREAKPOINT: {
} break;
case Node::TYPE_NEWLINE: {
} break;
}
}
void GDScriptTranspilerCpp::transpile_class(const ClassNode *p_class) {
// Header
GDScriptTranspilerUtils::CodeBuilder &hpp = code["header"];
hpp.map["class_name"] = p_class->class_name;
hpp.map["inherits"] = p_class->inherits;
hpp.map["include_guard"] = vformat("%s_H", p_class->class_name.to_upper());
hpp += "#ifndef {include_guard}";
hpp += "#define {include_guard}";
hpp += "\n";
hpp += "class {class_name} : public {inherits} {";
hpp.indent();
hpp += "GDCLASS({class_name}, {inherits});";
hpp.dedent();
hpp += "\n";
hpp += "public:";
hpp.indent();
for (auto E = p_class->constant_expressions.front(); E; E = E->next()) {
const ClassNode::Constant &c = E->get();
transpile_node(c.expression);
String value = parsed_expression;
if (c.is_enum) {
hpp += vformat("enum %s %s", E->key(), value);
} else {
hpp += vformat("const %s %s = %s;", c.datatype, E->key(), value);
}
}
for (int i = 0; i < p_class->variables.size(); ++i) {
const ClassNode::Member &m = p_class->variables[i];
hpp += vformat("%s %s;", m.type, m.identifier);
}
hpp += "\n";
for (int i = 0; i < p_class->functions.size(); ++i) {
const FunctionNode *func = p_class->functions[i];
String signature;
for (int j = 0; j < func->arguments.size(); ++j) {
String type = func->argument_types[j];
String arg = func->arguments[j];
signature += vformat("%s %s", type, arg);
if (j < func->arguments.size() - 1) {
signature += ", ";
}
}
hpp += vformat("%s %s(%s);", func->return_type, func->name, signature);
}
hpp.dedent();
hpp += "};";
hpp += "\n";
hpp += "#endif // {include_guard}";
// Source
GDScriptTranspilerUtils::CodeBuilder &cpp = code["source"];
cpp.map["class_name"] = p_class->class_name;
String include_header = script_path.get_basename().get_file() + ".h";
cpp += vformat("#include \"%s\"", include_header);
cpp += "\n";
for (int i = 0; i < p_class->functions.size(); ++i) {
const FunctionNode *func = p_class->functions[i];
String signature;
for (int j = 0; j < func->arguments.size(); ++j) {
String type = func->argument_types[j];
String arg = func->arguments[j];
signature += vformat("%s %s", type, arg);
if (j < func->arguments.size() - 1) {
signature += ", ";
}
}
cpp += vformat("%s {class_name}::%s(%s) {", func->return_type, func->name, signature);
cpp.indent();
for (List<Node *>::Element *E = func->body->statements.front(); E; E = E->next()) {
transpile_node(E->get());
}
cpp.dedent();
cpp += "}\n";
}
}
GDScriptTranspilerCpp::GDScriptTranspilerCpp() {
head = nullptr;
list = nullptr;
clear();
}
GDScriptTranspilerCpp::~GDScriptTranspilerCpp() {
clear();
}
| 30.074434 | 128 | 0.671258 | [
"vector"
] |
58762b8a26339b4623f50c6fb0f2abcfceece4d3 | 3,883 | cpp | C++ | src/ornrepomodel.cpp | Acidburn0zzz/harbour-storeman | beda8d3aa7b580b35200816a5494532102eff7ba | [
"MIT"
] | 1 | 2019-08-26T04:02:24.000Z | 2019-08-26T04:02:24.000Z | src/ornrepomodel.cpp | Acidburn0zzz/harbour-storeman | beda8d3aa7b580b35200816a5494532102eff7ba | [
"MIT"
] | null | null | null | src/ornrepomodel.cpp | Acidburn0zzz/harbour-storeman | beda8d3aa7b580b35200816a5494532102eff7ba | [
"MIT"
] | null | null | null | #include "ornrepomodel.h"
#include "ornpm.h"
#include <QTimer>
#include <QDebug>
OrnRepoModel::OrnRepoModel(QObject *parent)
: QAbstractListModel(parent)
, mEnabledRepos(0)
{
auto ornPm = OrnPm::instance();
connect(ornPm, &OrnPm::initialisedChanged, this, &OrnRepoModel::reset);
connect(ornPm, &OrnPm::enableReposFinished, this, &OrnRepoModel::reset);
connect(ornPm, &OrnPm::removeAllReposFinished, this, &OrnRepoModel::reset);
connect(ornPm, &OrnPm::repoModified, this, &OrnRepoModel::onRepoModified);
connect(this, &OrnRepoModel::modelReset, this, &OrnRepoModel::enabledReposChanged);
// Delay reset to ensure that modelReset signal is received in qml
QTimer::singleShot(500, this, &OrnRepoModel::reset);
}
bool OrnRepoModel::hasEnabledRepos() const
{
return mEnabledRepos;
}
bool OrnRepoModel::hasDisabledRepos() const
{
return mEnabledRepos != mData.size();
}
void OrnRepoModel::reset()
{
qDebug() << "Resetting model";
this->beginResetModel();
mData.clear();
auto repos = OrnPm::instance()->repoList();
auto size = repos.size();
int enabledRepos = 0;
if (size)
{
mData.append(repos);
for (const auto &repo : repos)
{
enabledRepos += repo.enabled;
}
}
if (mEnabledRepos != enabledRepos)
{
mEnabledRepos = enabledRepos;
emit this->enabledReposChanged();
}
this->endResetModel();
}
void OrnRepoModel::onRepoModified(const QString &alias, int action)
{
QModelIndex parentIndex;
if (action == OrnPm::AddRepo)
{
auto row = mData.size();
this->beginInsertRows(parentIndex, row, row);
mData << OrnRepo{ true, alias, alias.mid(OrnPm::repoNamePrefix.size()) };
++mEnabledRepos;
emit this->enabledReposChanged();
this->endInsertRows();
return;
}
int row = 0;
for (auto &repo : mData)
{
if (repo.alias == alias)
{
switch (action)
{
case OrnPm::RemoveRepo:
this->beginRemoveRows(parentIndex, row, row);
mData.removeAt(row);
--mEnabledRepos;
emit this->enabledReposChanged();
this->endRemoveRows();
break;
case OrnPm::DisableRepo:
case OrnPm::EnableRepo:
{
bool enable = action == OrnPm::EnableRepo;
if (repo.enabled != enable)
{
repo.enabled = enable;
auto index = this->createIndex(row, 0);
emit this->dataChanged(index, index, { RepoEnabledRole });
mEnabledRepos += enable ? 1 : -1;
emit this->enabledReposChanged();
}
}
break;
default:
break;
}
return;
}
++row;
}
}
int OrnRepoModel::rowCount(const QModelIndex &parent) const
{
return !parent.isValid() ? mData.size() : 0;
}
QVariant OrnRepoModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
{
return QVariant();
}
auto &repo = mData[index.row()];
switch (role)
{
case RepoAuthorRole:
return repo.author;
case RepoAliasRole:
return repo.alias;
case RepoEnabledRole:
return repo.enabled;
case SortRole:
// Place enabled first and then sort by author
return QString::number(!repo.enabled).append(repo.author);
default:
return QVariant();
}
}
QHash<int, QByteArray> OrnRepoModel::roleNames() const
{
return {
{ RepoAuthorRole, "repoAuthor" },
{ RepoAliasRole, "repoAlias" },
{ RepoEnabledRole, "repoEnabled" }
};
}
| 26.060403 | 87 | 0.566315 | [
"model"
] |
587d7d06e00dbddff93082f53c1f5812b30ff19f | 2,461 | cpp | C++ | Ball/Ball Instantiation.cpp | pixelsquare/ball-instantiation | 6929f18e2051b5efe63c9030c20f1b041590cbdf | [
"MIT"
] | null | null | null | Ball/Ball Instantiation.cpp | pixelsquare/ball-instantiation | 6929f18e2051b5efe63c9030c20f1b041590cbdf | [
"MIT"
] | null | null | null | Ball/Ball Instantiation.cpp | pixelsquare/ball-instantiation | 6929f18e2051b5efe63c9030c20f1b041590cbdf | [
"MIT"
] | null | null | null | #include "glutSetup.h"
#include <iostream>
#include <vector>
using namespace std;
class Ball { // Create a class "Implementation[class <any name> { }; ]"
public: // Specify its referencing make it public so it can be accessed outside the class
float posX, posY, posZ;
vector<Ball> vectorBall;
Ball() { posX = 0; posY = 0; posZ = 0; }
Ball(float positionX, float positionY, float positionZ) {
posX = positionX; posY = positionY; posZ = positionZ;
}
// Class Function "Draw"
// This will render the objectS
void Draw() {
for(int i = 0; i < vectorBall.size(); i++) {
glPushMatrix();
glTranslatef(vectorBall.at(i).posX, vectorBall.at(i).posY, vectorBall.at(i).posZ);
glutSolidSphere(0.6f, 50, 50);
glPopMatrix();
}
}
private:
protected:
}; // << ---- Don't forget this ";" in the class :)
// Object "Implementation[<Class Name> <Any Name>( <positionX>, <positionY>, <positionZ> ); ]"
// I used my Overloaded Constructor to set my object to x = -20, y = 0, z = 0
Ball ball(-20.0f, 0.0f, 0.0f);
// This variable will add 1 to the x position of the object
float increment = 0;
void GamePlay()
{
// Used in drawing Objects on game screen
ball.Draw();
}
void Scene()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(LookX, LookY, LookZ, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
glRotatef(AngleX, 1.0, 0.0, 0.0);
glRotatef(AngleY, 0.0, 1.0, 0.0);
/* Display Object on GLUT Window */
glPushMatrix();
GamePlay();
glPopMatrix();
glutSwapBuffers();
}
void Keys(unsigned char key, int x, int y)
{
KeyDown[key] = true;
switch(key)
{
case ' ': // Space bar keypress
increment += 1.3f; // Add + 1.3f in my variable "increment"
// Store another ball to the vector
// Implementation [<CLASS VARIABLE name>.<VECTOR variable>.<push_back>( <CLASS NAME> ( <positionX>, <positionY>, <positionZ> ));
ball.vectorBall.push_back(Ball(ball.posX + increment, ball.posY, ball.posZ));
break;
case 'e':
ball.vectorBall.erase(ball.vectorBall.begin());
break;
/* ZOOM FUNCTION */
case 'z':
LookZ += 1.0;
break;
case 'x':
LookZ -= 1.0;
break;
// Normal Camera origin
case 'c':
LookX = 0.0f;
LookY = 0.0f;
LookZ = 8.0f;
break;
// Others
case 27:
exit(0);
}
}
void main(int argc, char **argv)
{
GLUTmain(argc, argv, "Ball Instantiation");
} | 23 | 131 | 0.625762 | [
"render",
"object",
"vector"
] |
58834bd6121ea2da97269b62d665b66c383e5b6b | 422,593 | cc | C++ | MELA/src/TUtil.cc | mostafa1993/JHUGenMELA | a28f39043d98319f1f27493cf899a13646221eda | [
"Apache-2.0"
] | null | null | null | MELA/src/TUtil.cc | mostafa1993/JHUGenMELA | a28f39043d98319f1f27493cf899a13646221eda | [
"Apache-2.0"
] | 8 | 2020-10-02T20:02:44.000Z | 2022-01-19T15:41:05.000Z | MELA/src/TUtil.cc | mostafa1993/JHUGenMELA | a28f39043d98319f1f27493cf899a13646221eda | [
"Apache-2.0"
] | 11 | 2020-10-07T17:15:30.000Z | 2022-03-19T10:41:52.000Z | #include <iostream>
#include <cstdio>
#include <cmath>
#include <iterator>
#include <utility>
#include <algorithm>
#include <cassert>
#include "MELAStreamHelpers.hh"
#include "TJHUGenUtils.hh"
#include "TUtilHelpers.hh"
#include "TUtil.hh"
#include "TMath.h"
#include "TLorentzRotation.h"
using namespace std;
using TVar::event_scales_type;
using TVar::simple_event_record;
using MELAStreamHelpers::MELAout;
using MELAStreamHelpers::MELAerr;
using namespace TJHUGenUtils;
namespace TUtil{
bool forbidMassiveLeptons = true;
bool forbidMassiveJets = true;
TVar::FermionMassRemoval LeptonMassScheme = TVar::ConserveDifermionMass;
TVar::FermionMassRemoval JetMassScheme = TVar::ConserveDifermionMass;
}
/***************************************************/
/***** Scripts for decay and production angles *****/
/***************************************************/
void TUtil::applyLeptonMassCorrection(bool flag){ TUtil::forbidMassiveLeptons = flag; }
void TUtil::applyJetMassCorrection(bool flag){ TUtil::forbidMassiveJets = flag; }
void TUtil::setLeptonMassScheme(TVar::FermionMassRemoval scheme){ LeptonMassScheme=scheme; }
void TUtil::setJetMassScheme(TVar::FermionMassRemoval scheme){ JetMassScheme=scheme; }
void TUtil::constrainedRemovePairMass(TLorentzVector& p1, TLorentzVector& p2, double m1, double m2){
TLorentzVector const nullFourVector(0, 0, 0, 0);
TLorentzVector p1hat, p2hat;
if (p1==nullFourVector || p2==nullFourVector) return;
/***** shiftMass in C++ *****/
TLorentzVector p12=p1+p2;
TLorentzVector diffp2p1=p2-p1;
double p1sq = p1.M2();
double p2sq = p2.M2();
double p1p2 = p1.Dot(p2);
double m1sq = m1*fabs(m1);
double m2sq = m2*fabs(m2);
double p12sq = p12.M2();
TLorentzVector avec=(p1sq*p2 - p2sq*p1 + p1p2*diffp2p1);
double a = avec.M2();
double b = (p12sq + m2sq - m1sq) * (pow(p1p2, 2) - p1sq*p2sq);
double c = pow((p12sq + m2sq - m1sq), 2)*p1sq/4. - pow((p1sq + p1p2), 2)*m2sq;
double eta = (-b - sqrt(fabs(b*b -4.*a*c)))/(2.*a);
double xi = (p12sq + m2sq - m1sq - 2.*eta*(p2sq + p1p2))/(2.*(p1sq + p1p2));
p1hat = (1.-xi)*p1 + (1.-eta)*p2;
p2hat = xi*p1 + eta*p2;
p1=p1hat;
p2=p2hat;
}
void TUtil::scaleMomentumToEnergy(const TLorentzVector& massiveJet, TLorentzVector& masslessJet, double mass){
double energy, p3, newp3, ratio;
energy = massiveJet.T();
p3 = massiveJet.P();
newp3 = sqrt(max(pow(energy, 2)-mass*fabs(mass), 0.));
ratio = (p3>0. ? (newp3/p3) : 1.);
masslessJet.SetXYZT(massiveJet.X()*ratio, massiveJet.Y()*ratio, massiveJet.Z()*ratio, energy);
}
std::pair<TLorentzVector, TLorentzVector> TUtil::removeMassFromPair(
TLorentzVector const& jet1, int const& jet1Id,
TLorentzVector const& jet2, int const& jet2Id,
double m1, double m2
){
TLorentzVector const nullFourVector(0, 0, 0, 0);
TLorentzVector jet1massless(0, 0, 0, 0), jet2massless(0, 0, 0, 0);
if (
TUtil::forbidMassiveJets
&&
((PDGHelpers::isAJet(jet1Id) && !PDGHelpers::isATopQuark(jet1Id)) || (PDGHelpers::isAJet(jet2Id) && !PDGHelpers::isATopQuark(jet2Id)))
){
if (JetMassScheme==TVar::NoRemoval){
jet1massless=jet1;
jet2massless=jet2;
}
else if (jet1==nullFourVector || jet2==nullFourVector || jet1==jet2 || JetMassScheme==TVar::MomentumToEnergy){
TUtil::scaleMomentumToEnergy(jet1, jet1massless, m1);
TUtil::scaleMomentumToEnergy(jet2, jet2massless, m2);
}
else if (JetMassScheme==TVar::ConserveDifermionMass){
jet1massless=jet1;
jet2massless=jet2;
TUtil::constrainedRemovePairMass(jet1massless, jet2massless, m1, m2);
}
else{
jet1massless=jet1;
jet2massless=jet2;
}
}
else if (TUtil::forbidMassiveLeptons && (PDGHelpers::isALepton(jet1Id) || PDGHelpers::isANeutrino(jet1Id) || PDGHelpers::isALepton(jet2Id) || PDGHelpers::isANeutrino(jet2Id))){
if (LeptonMassScheme==TVar::NoRemoval){
jet1massless=jet1;
jet2massless=jet2;
}
else if (jet1==nullFourVector || jet2==nullFourVector || jet1==jet2 || LeptonMassScheme==TVar::MomentumToEnergy){
TUtil::scaleMomentumToEnergy(jet1, jet1massless, m1);
TUtil::scaleMomentumToEnergy(jet2, jet2massless, m2);
}
else if (LeptonMassScheme==TVar::ConserveDifermionMass){
jet1massless=jet1;
jet2massless=jet2;
TUtil::constrainedRemovePairMass(jet1massless, jet2massless, m1, m2);
}
else{
jet1massless=jet1;
jet2massless=jet2;
}
}
else{
jet1massless=jet1;
jet2massless=jet2;
}
pair<TLorentzVector, TLorentzVector> result(jet1massless, jet2massless);
return result;
}
void TUtil::adjustTopDaughters(SimpleParticleCollection_t& daughters){ // Daughters are arranged as b, Wf, Wfb
if (daughters.size()!=3) return; // Cannot work if the number of daughters is not exactly 3.
pair<TLorentzVector, TLorentzVector> corrWpair = TUtil::removeMassFromPair(
daughters.at(1).second, daughters.at(1).first,
daughters.at(2).second, daughters.at(2).first
);
daughters.at(1).second = corrWpair.first;
daughters.at(2).second = corrWpair.second;
TLorentzVector pW = daughters.at(1).second+daughters.at(2).second;
TVector3 pW_boost_old = -pW.BoostVector();
pair<TLorentzVector, TLorentzVector> corrbW = TUtil::removeMassFromPair(
daughters.at(0).second, daughters.at(0).first,
pW, -daughters.at(0).first, // Trick the function
0., pW.M() // Conserve W mass, ensures Wf+Wfb=W after re-boosting Wf and Wfb to the new W frame.
);
daughters.at(0).second=corrbW.first;
pW=corrbW.second;
TVector3 pW_boost_new = pW.BoostVector();
for (unsigned int idau=1; idau<daughters.size(); idau++){
daughters.at(idau).second.Boost(pW_boost_old);
daughters.at(idau).second.Boost(pW_boost_new);
}
}
// Compute a fake jet
void TUtil::computeFakeJet(TLorentzVector const& realJet, TLorentzVector const& others, TLorentzVector& fakeJet){
TLorentzVector masslessRealJet(0, 0, 0, 0);
if (TUtil::forbidMassiveJets) TUtil::scaleMomentumToEnergy(realJet, masslessRealJet);
else masslessRealJet = realJet;
fakeJet = others + masslessRealJet;
fakeJet.SetVect(-fakeJet.Vect());
fakeJet.SetE(fakeJet.P());
}
/***** Complex Boost *****/
std::pair<TLorentzVector, TLorentzVector> TUtil::ComplexBoost(TVector3 const& beta, TLorentzVector const& p4){
double bx=beta.X();
double by=beta.Y();
double bz=beta.Z();
double b2 = bx*bx + by*by + bz*bz;
double gammasqinv = 1.-b2;
double gamma=0.;
double bp = bx*p4.X() + by*p4.Y() + bz*p4.Z();
double gammap_real=0;
double gammap_imag=0;
TLorentzVector p4new_real(0, 0, 0, 0), p4new_imag(0, 0, 0, 0);
if (gammasqinv>0.){
gamma = 1./sqrt(gammasqinv);
if (b2>0.) gammap_real = (gamma-1.)/b2;
p4new_real.SetX(p4.X() + gammap_real*bp*bx + gamma*bx*p4.T());
p4new_real.SetY(p4.Y() + gammap_real*bp*by + gamma*by*p4.T());
p4new_real.SetZ(p4.Z() + gammap_real*bp*bz + gamma*bz*p4.T());
p4new_real.SetT(gamma*(p4.T() + bp));
}
else if (gammasqinv<0.){
gamma = -1./sqrt(-gammasqinv);
if (b2>0.){
gammap_real = -1./b2;
gammap_imag = gamma/b2;
}
p4new_real.SetX(p4.X() + gammap_real*bp*bx);
p4new_real.SetY(p4.Y() + gammap_real*bp*by);
p4new_real.SetZ(p4.Z() + gammap_real*bp*bz);
p4new_real.SetT(0.);
p4new_imag.SetX(gammap_imag*bp*bx + gamma*bx*p4.T());
p4new_imag.SetY(gammap_imag*bp*by + gamma*by*p4.T());
p4new_imag.SetZ(gammap_imag*bp*bz + gamma*bz*p4.T());
p4new_imag.SetT(gamma*(p4.T() + bp));
}
return (pair<TLorentzVector, TLorentzVector>(p4new_real, p4new_imag));
}
/***** Decay angles *****/
void TUtil::computeAngles(
float& costhetastar,
float& costheta1,
float& costheta2,
float& Phi,
float& Phi1,
TLorentzVector p4M11, int Z1_lept1Id,
TLorentzVector p4M12, int Z1_lept2Id,
TLorentzVector p4M21, int Z2_lept1Id,
TLorentzVector p4M22, int Z2_lept2Id
){
TLorentzVector const nullFourVector(0, 0, 0, 0);
if (p4M12==nullFourVector || p4M22==nullFourVector){
pair<TLorentzVector, TLorentzVector> f13Pair = TUtil::removeMassFromPair(p4M11, Z1_lept1Id, p4M21, Z2_lept1Id);
p4M11 = f13Pair.first;
p4M21 = f13Pair.second;
}
else if (p4M11==nullFourVector || p4M21==nullFourVector){
pair<TLorentzVector, TLorentzVector> f24Pair = TUtil::removeMassFromPair(p4M12, Z1_lept2Id, p4M22, Z2_lept2Id);
p4M12 = f24Pair.first;
p4M22 = f24Pair.second;
}
else{
pair<TLorentzVector, TLorentzVector> f12Pair = TUtil::removeMassFromPair(p4M11, Z1_lept1Id, p4M12, Z1_lept2Id);
pair<TLorentzVector, TLorentzVector> f34Pair = TUtil::removeMassFromPair(p4M21, Z2_lept1Id, p4M22, Z2_lept2Id);
p4M11 = f12Pair.first;
p4M12 = f12Pair.second;
p4M21 = f34Pair.first;
p4M22 = f34Pair.second;
}
//build Z 4-vectors
TLorentzVector p4Z1 = p4M11 + p4M12;
TLorentzVector p4Z2 = p4M21 + p4M22;
// Sort Z1 leptons so that...
if (
Z1_lept2Id!=-9000
&&
(
(Z1_lept1Id*Z1_lept2Id<0 && Z1_lept1Id<0) // ...for OS pairs, lep1 is the particle.
||
((Z1_lept1Id*Z1_lept2Id>0 || (Z1_lept1Id==0 && Z1_lept2Id==0)) && p4M11.Phi()<=p4M12.Phi()) // ...for SS pairs, a random deterministic convention is used.
)
) swap(p4M11, p4M12);
// Same for Z2 leptons
if (
Z2_lept2Id!=-9000
&&
(
(Z2_lept1Id*Z2_lept2Id<0 && Z2_lept1Id<0)
||
((Z2_lept1Id*Z2_lept2Id>0 || (Z2_lept1Id==0 && Z2_lept2Id==0)) && p4M21.Phi()<=p4M22.Phi())
)
) swap(p4M21, p4M22);
// BEGIN THE CALCULATION
// build H 4-vectors
TLorentzVector p4H = p4Z1 + p4Z2;
// -----------------------------------
//// costhetastar
TVector3 boostX = -(p4H.BoostVector());
TLorentzVector thep4Z1inXFrame(p4Z1);
TLorentzVector thep4Z2inXFrame(p4Z2);
thep4Z1inXFrame.Boost(boostX);
thep4Z2inXFrame.Boost(boostX);
TVector3 theZ1X_p3 = thep4Z1inXFrame.Vect();
TVector3 theZ2X_p3 = thep4Z2inXFrame.Vect();
costhetastar = theZ1X_p3.CosTheta();
TVector3 boostV1(0, 0, 0);
TVector3 boostV2(0, 0, 0);
//// --------------------------- costheta1
if (!(fabs(Z1_lept1Id)==21 || fabs(Z1_lept1Id)==22 || fabs(Z1_lept2Id)==21 || fabs(Z1_lept2Id)==22)){
boostV1 = -(p4Z1.BoostVector());
if (boostV1.Mag()>=1.) {
MELAout << "Warning: Mela::computeAngles: Z1 boost with beta=1, scaling down" << endl;
boostV1*=0.9999/boostV1.Mag();
}
TLorentzVector p4M11_BV1(p4M11);
TLorentzVector p4M12_BV1(p4M12);
TLorentzVector p4M21_BV1(p4M21);
TLorentzVector p4M22_BV1(p4M22);
p4M11_BV1.Boost(boostV1);
p4M12_BV1.Boost(boostV1);
p4M21_BV1.Boost(boostV1);
p4M22_BV1.Boost(boostV1);
TLorentzVector p4V2_BV1 = p4M21_BV1 + p4M22_BV1;
//// costheta1
costheta1 = -p4V2_BV1.Vect().Unit().Dot(p4M11_BV1.Vect().Unit());
}
else costheta1 = 0;
//// --------------------------- costheta2
if (!(fabs(Z2_lept1Id)==21 || fabs(Z2_lept1Id)==22 || fabs(Z2_lept2Id)==21 || fabs(Z2_lept2Id)==22)){
boostV2 = -(p4Z2.BoostVector());
if (boostV2.Mag()>=1.) {
MELAout << "Warning: Mela::computeAngles: Z2 boost with beta=1, scaling down" << endl;
boostV2*=0.9999/boostV2.Mag();
}
TLorentzVector p4M11_BV2(p4M11);
TLorentzVector p4M12_BV2(p4M12);
TLorentzVector p4M21_BV2(p4M21);
TLorentzVector p4M22_BV2(p4M22);
p4M11_BV2.Boost(boostV2);
p4M12_BV2.Boost(boostV2);
p4M21_BV2.Boost(boostV2);
p4M22_BV2.Boost(boostV2);
TLorentzVector p4V1_BV2 = p4M11_BV2 + p4M12_BV2;
//// costheta2
costheta2 = -p4V1_BV2.Vect().Unit().Dot(p4M21_BV2.Vect().Unit());
}
else costheta2 = 0;
//// --------------------------- Phi and Phi1 (old phistar1 - azimuthal production angle)
TLorentzVector p4M11_BX(p4M11);
TLorentzVector p4M12_BX(p4M12);
TLorentzVector p4M21_BX(p4M21);
TLorentzVector p4M22_BX(p4M22);
p4M11_BX.Boost(boostX);
p4M12_BX.Boost(boostX);
p4M21_BX.Boost(boostX);
p4M22_BX.Boost(boostX);
TLorentzVector p4V1_BX = p4M11_BX + p4M12_BX;
TVector3 const beamAxis(0, 0, 1);
TVector3 p3V1_BX = p4V1_BX.Vect().Unit();
TVector3 normal1_BX = (p4M11_BX.Vect().Cross(p4M12_BX.Vect())).Unit();
TVector3 normal2_BX = (p4M21_BX.Vect().Cross(p4M22_BX.Vect())).Unit();
TVector3 normalSC_BX = (beamAxis.Cross(p3V1_BX)).Unit();
//// Phi
float tmpSgnPhi = p3V1_BX.Dot(normal1_BX.Cross(normal2_BX));
float sgnPhi = 0;
if (fabs(tmpSgnPhi)>0.) sgnPhi = tmpSgnPhi/fabs(tmpSgnPhi);
float dot_BX12 = normal1_BX.Dot(normal2_BX);
if (fabs(dot_BX12)>=1.) dot_BX12 *= 1./fabs(dot_BX12);
Phi = sgnPhi * acos(-1.*dot_BX12);
//// Phi1
float tmpSgnPhi1 = p3V1_BX.Dot(normal1_BX.Cross(normalSC_BX));
float sgnPhi1 = 0;
if (fabs(tmpSgnPhi1)>0.) sgnPhi1 = tmpSgnPhi1/fabs(tmpSgnPhi1);
float dot_BX1SC = normal1_BX.Dot(normalSC_BX);
if (fabs(dot_BX1SC)>=1.) dot_BX1SC *= 1./fabs(dot_BX1SC);
Phi1 = sgnPhi1 * acos(dot_BX1SC);
if (isnan(costhetastar) || isnan(costheta1) || isnan(costheta2) || isnan(Phi) || isnan(Phi1)){
MELAout << "WARNING: NaN in computeAngles: "
<< costhetastar << " "
<< costheta1 << " "
<< costheta2 << " "
<< Phi << " "
<< Phi1 << " " << endl;
MELAout << " boostV1: " <<boostV1.Pt() << " " << boostV1.Eta() << " " << boostV1.Phi() << " " << boostV1.Mag() << endl;
MELAout << " boostV2: " <<boostV2.Pt() << " " << boostV2.Eta() << " " << boostV2.Phi() << " " << boostV2.Mag() << endl;
}
}
void TUtil::computeAnglesCS(
float const& pbeam,
float& costhetastar,
float& costheta1,
float& costheta2,
float& Phi,
float& Phi1,
TLorentzVector p4M11, int Z1_lept1Id,
TLorentzVector p4M12, int Z1_lept2Id,
TLorentzVector p4M21, int Z2_lept1Id,
TLorentzVector p4M22, int Z2_lept2Id
){
TLorentzVector const nullFourVector(0, 0, 0, 0);
if (p4M12==nullFourVector || p4M22==nullFourVector){
pair<TLorentzVector, TLorentzVector> f13Pair = TUtil::removeMassFromPair(p4M11, Z1_lept1Id, p4M21, Z2_lept1Id);
p4M11 = f13Pair.first;
p4M21 = f13Pair.second;
}
else if (p4M11==nullFourVector || p4M21==nullFourVector){
pair<TLorentzVector, TLorentzVector> f24Pair = TUtil::removeMassFromPair(p4M12, Z1_lept2Id, p4M22, Z2_lept2Id);
p4M12 = f24Pair.first;
p4M22 = f24Pair.second;
}
else{
pair<TLorentzVector, TLorentzVector> f12Pair = TUtil::removeMassFromPair(p4M11, Z1_lept1Id, p4M12, Z1_lept2Id);
pair<TLorentzVector, TLorentzVector> f34Pair = TUtil::removeMassFromPair(p4M21, Z2_lept1Id, p4M22, Z2_lept2Id);
p4M11 = f12Pair.first;
p4M12 = f12Pair.second;
p4M21 = f34Pair.first;
p4M22 = f34Pair.second;
}
TVector3 LabXaxis(1.0, 0.0, 0.0);
TVector3 LabYaxis(0.0, 1.0, 0.0);
TVector3 LabZaxis(0.0, 0.0, 1.0);
float Mprot = 0.938;
float Ebeam = sqrt(pbeam*pbeam + Mprot*Mprot);
TLorentzVector targ(0., 0., -pbeam, Ebeam);
TLorentzVector beam(0., 0., pbeam, Ebeam);
//build Z 4-vectors
TLorentzVector p4Z1 = p4M11 + p4M12;
TLorentzVector p4Z2 = p4M21 + p4M22;
// Sort Z1 leptons so that:
if (
Z1_lept2Id!=9000
&&
(
(Z1_lept1Id*Z1_lept2Id<0 && Z1_lept1Id<0) // for OS pairs: lep1 must be the negative one
||
((Z1_lept1Id*Z1_lept2Id>0 || (Z1_lept1Id==0 && Z1_lept2Id==0)) && p4M11.Phi()<=p4M12.Phi()) //for SS pairs: use random deterministic convention
)
) swap(p4M11, p4M12);
// Same for Z2 leptons
if (
Z2_lept2Id!=9000
&&
(
(Z2_lept1Id*Z2_lept2Id<0 && Z2_lept1Id<0)
||
((Z2_lept1Id*Z2_lept2Id>0 || (Z2_lept1Id==0 && Z2_lept2Id==0)) && p4M21.Phi()<=p4M22.Phi())
)
) swap(p4M21, p4M22);
//build H 4-vectors
TLorentzVector p4H = p4Z1 + p4Z2;
TVector3 boostX = -(p4H.BoostVector());
/////////////////////////////
// Collin-Sopper calculation:
// in the CS frame, the z-axis is along the bisectrice of one beam and the opposite of the other beam,
// after their boost in X
///////////////////////////////
// Rotation for the CS Frame
TRotation rotationCS;
TLorentzVector beaminX(beam);
TLorentzVector targinX(targ);
targinX.Boost(boostX);
beaminX.Boost(boostX);
//Bisectrice: sum of unit vectors (remember: you need to invert one beam vector)
TVector3 beam_targ_bisecinX((beaminX.Vect().Unit() - targinX.Vect().Unit()).Unit());
// Define a rotationCS Matrix, with Z along the bisectric,
TVector3 newZaxisCS(beam_targ_bisecinX.Unit());
TVector3 newYaxisCS(beaminX.Vect().Unit().Cross(newZaxisCS).Unit());
TVector3 newXaxisCS(newYaxisCS.Unit().Cross(newZaxisCS).Unit());
rotationCS.RotateAxes(newXaxisCS, newYaxisCS, newZaxisCS);
rotationCS.Invert();
//// costhetastar
TLorentzVector thep4Z1inXFrame_rotCS(p4Z1);
TLorentzVector thep4Z2inXFrame_rotCS(p4Z2);
thep4Z1inXFrame_rotCS.Transform(rotationCS);
thep4Z2inXFrame_rotCS.Transform(rotationCS);
thep4Z1inXFrame_rotCS.Boost(boostX);
thep4Z2inXFrame_rotCS.Boost(boostX);
TVector3 theZ1XrotCS_p3 = TVector3(thep4Z1inXFrame_rotCS.X(), thep4Z1inXFrame_rotCS.Y(), thep4Z1inXFrame_rotCS.Z());
costhetastar = theZ1XrotCS_p3.CosTheta();
//// --------------------------- Phi and Phi1 (old phistar1 - azimuthal production angle)
// TVector3 boostX = -(thep4H.BoostVector());
TLorentzVector p4M11_BX_rotCS(p4M11);
TLorentzVector p4M12_BX_rotCS(p4M12);
TLorentzVector p4M21_BX_rotCS(p4M21);
TLorentzVector p4M22_BX_rotCS(p4M22);
p4M11_BX_rotCS.Transform(rotationCS);
p4M12_BX_rotCS.Transform(rotationCS);
p4M21_BX_rotCS.Transform(rotationCS);
p4M22_BX_rotCS.Transform(rotationCS);
p4M11_BX_rotCS.Boost(boostX);
p4M12_BX_rotCS.Boost(boostX);
p4M21_BX_rotCS.Boost(boostX);
p4M22_BX_rotCS.Boost(boostX);
TLorentzVector p4Z1_BX_rotCS = p4M11_BX_rotCS + p4M12_BX_rotCS;
TVector3 p3V1_BX_rotCS = (p4Z1_BX_rotCS.Vect()).Unit();
TVector3 const beamAxis(0, 0, 1);
TVector3 normal1_BX_rotCS = (p4M11_BX_rotCS.Vect().Cross(p4M12_BX_rotCS.Vect())).Unit();
TVector3 normal2_BX_rotCS = (p4M21_BX_rotCS.Vect().Cross(p4M22_BX_rotCS.Vect())).Unit();
TVector3 normalSC_BX_rotCS = (beamAxis.Cross(p3V1_BX_rotCS)).Unit();
//// Phi
float tmpSgnPhi = p3V1_BX_rotCS.Dot(normal1_BX_rotCS.Cross(normal2_BX_rotCS));
float sgnPhi = 0;
if (fabs(tmpSgnPhi)>0.) sgnPhi = tmpSgnPhi/fabs(tmpSgnPhi);
float dot_BX12 = normal1_BX_rotCS.Dot(normal2_BX_rotCS);
if (fabs(dot_BX12)>=1.) dot_BX12 *= 1./fabs(dot_BX12);
Phi = sgnPhi * acos(-1.*dot_BX12);
//// Phi1
float tmpSgnPhi1 = p3V1_BX_rotCS.Dot(normal1_BX_rotCS.Cross(normalSC_BX_rotCS));
float sgnPhi1 = 0;
if (fabs(tmpSgnPhi1)>0.) sgnPhi1 = tmpSgnPhi1/fabs(tmpSgnPhi1);
float dot_BX1SC = normal1_BX_rotCS.Dot(normalSC_BX_rotCS);
if (fabs(dot_BX1SC)>=1.) dot_BX1SC *= 1./fabs(dot_BX1SC);
Phi1 = sgnPhi1 * acos(dot_BX1SC);
//// --------------------------- costheta1
if (!(fabs(Z1_lept1Id)==21 || fabs(Z1_lept1Id)==22 || fabs(Z1_lept2Id)==21 || fabs(Z1_lept2Id)==22)){
//define Z1 rotation
TRotation rotationZ1;
TVector3 newZaxisZ1(thep4Z1inXFrame_rotCS.Vect().Unit());
TVector3 newXaxisZ1(newYaxisCS.Cross(newZaxisZ1).Unit());
TVector3 newYaxisZ1(newZaxisZ1.Cross(newXaxisZ1).Unit());
rotationZ1.RotateAxes(newXaxisZ1, newYaxisZ1, newZaxisZ1);
rotationZ1.Invert();
TLorentzVector thep4Z1inXFrame_rotCS_rotZ1(thep4Z1inXFrame_rotCS);
thep4Z1inXFrame_rotCS_rotZ1.Transform(rotationZ1);
TVector3 boostZ1inX_rotCS_rotZ1= -(thep4Z1inXFrame_rotCS_rotZ1.BoostVector());
TLorentzVector p4M11_BX_rotCS_rotZ1(p4M11_BX_rotCS);
TLorentzVector p4M12_BX_rotCS_rotZ1(p4M12_BX_rotCS);
TLorentzVector p4M21_BX_rotCS_rotZ1(p4M21_BX_rotCS);
TLorentzVector p4M22_BX_rotCS_rotZ1(p4M22_BX_rotCS);
p4M11_BX_rotCS_rotZ1.Transform(rotationZ1);
p4M12_BX_rotCS_rotZ1.Transform(rotationZ1);
p4M21_BX_rotCS_rotZ1.Transform(rotationZ1);
p4M22_BX_rotCS_rotZ1.Transform(rotationZ1);
p4M11_BX_rotCS_rotZ1.Boost(boostZ1inX_rotCS_rotZ1);
p4M12_BX_rotCS_rotZ1.Boost(boostZ1inX_rotCS_rotZ1);
p4M21_BX_rotCS_rotZ1.Boost(boostZ1inX_rotCS_rotZ1);
p4M22_BX_rotCS_rotZ1.Boost(boostZ1inX_rotCS_rotZ1);
TLorentzVector p4V2_BX_rotCS_rotZ1 = p4M21_BX_rotCS_rotZ1 + p4M22_BX_rotCS_rotZ1;
//// costheta1
costheta1 = -p4V2_BX_rotCS_rotZ1.Vect().Dot(p4M11_BX_rotCS_rotZ1.Vect())/p4V2_BX_rotCS_rotZ1.Vect().Mag()/p4M11_BX_rotCS_rotZ1.Vect().Mag();
}
else costheta1=0;
//// --------------------------- costheta2
if (!(fabs(Z2_lept1Id)==21 || fabs(Z2_lept1Id)==22 || fabs(Z2_lept2Id)==21 || fabs(Z2_lept2Id)==22)){
//define Z2 rotation
TRotation rotationZ2;
TVector3 newZaxisZ2(thep4Z2inXFrame_rotCS.Vect().Unit());
TVector3 newXaxisZ2(newYaxisCS.Cross(newZaxisZ2).Unit());
TVector3 newYaxisZ2(newZaxisZ2.Cross(newXaxisZ2).Unit());
rotationZ2.RotateAxes(newXaxisZ2, newYaxisZ2, newZaxisZ2);
rotationZ2.Invert();
TLorentzVector thep4Z2inXFrame_rotCS_rotZ2(thep4Z2inXFrame_rotCS);
thep4Z2inXFrame_rotCS_rotZ2.Transform(rotationZ2);
TVector3 boostZ2inX_rotCS_rotZ2= -(thep4Z2inXFrame_rotCS_rotZ2.BoostVector());
TLorentzVector p4M11_BX_rotCS_rotZ2(p4M11_BX_rotCS);
TLorentzVector p4M12_BX_rotCS_rotZ2(p4M12_BX_rotCS);
TLorentzVector p4M21_BX_rotCS_rotZ2(p4M21_BX_rotCS);
TLorentzVector p4M22_BX_rotCS_rotZ2(p4M22_BX_rotCS);
p4M11_BX_rotCS_rotZ2.Transform(rotationZ2);
p4M12_BX_rotCS_rotZ2.Transform(rotationZ2);
p4M21_BX_rotCS_rotZ2.Transform(rotationZ2);
p4M22_BX_rotCS_rotZ2.Transform(rotationZ2);
p4M11_BX_rotCS_rotZ2.Boost(boostZ2inX_rotCS_rotZ2);
p4M12_BX_rotCS_rotZ2.Boost(boostZ2inX_rotCS_rotZ2);
p4M21_BX_rotCS_rotZ2.Boost(boostZ2inX_rotCS_rotZ2);
p4M22_BX_rotCS_rotZ2.Boost(boostZ2inX_rotCS_rotZ2);
TLorentzVector p4V1_BX_rotCS_rotZ2= p4M11_BX_rotCS_rotZ2 + p4M12_BX_rotCS_rotZ2;
//// costheta2
costheta2 = -p4V1_BX_rotCS_rotZ2.Vect().Dot(p4M21_BX_rotCS_rotZ2.Vect())/p4V1_BX_rotCS_rotZ2.Vect().Mag()/p4M21_BX_rotCS_rotZ2.Vect().Mag();
}
else costheta2=0;
if (isnan(costhetastar) || isnan(costheta1) || isnan(costheta2) || isnan(Phi) || isnan(Phi1)){
MELAout << "WARNING: NaN in computeAngles: "
<< costhetastar << " "
<< costheta1 << " "
<< costheta2 << " "
<< Phi << " "
<< Phi1 << " " << endl;
}
}
/***** Associated production angles *****/
void TUtil::computeVBFAngles(
float& costhetastar,
float& costheta1,
float& costheta2,
float& Phi,
float& Phi1,
float& Q2V1,
float& Q2V2,
TLorentzVector p4M11, int Z1_lept1Id,
TLorentzVector p4M12, int Z1_lept2Id,
TLorentzVector p4M21, int Z2_lept1Id,
TLorentzVector p4M22, int Z2_lept2Id,
TLorentzVector jet1, int jet1Id,
TLorentzVector jet2, int jet2Id,
TLorentzVector* injet1, int injet1Id, // Gen. partons in the lab frame
TLorentzVector* injet2, int injet2Id
){
TLorentzVector const nullFourVector(0, 0, 0, 0);
TLorentzVector jet1massless, jet2massless;
pair<TLorentzVector, TLorentzVector> jetPair = TUtil::removeMassFromPair(jet1, jet1Id, jet2, jet2Id);
jet1massless = jetPair.first;
jet2massless = jetPair.second;
//build Z 4-vectors
TLorentzVector p4Z1 = p4M11 + p4M12;
TLorentzVector p4Z2 = p4M21 + p4M22;
TLorentzVector pH = p4Z1+p4Z2;
//jet1 is defined as going forwards (bigger pz), jet2 going backwards (smaller pz)
if (jet1massless.Z() < jet2massless.Z()) { swap(jet1massless, jet2massless); swap(jet1Id, jet2Id); }
//Find the incoming partons - first boost so the pT(HJJ) = 0, then boost away the pz.
//This preserves the z direction. Then assume that the partons come in this z direction.
//This is exactly correct at LO (since pT=0 anyway).
//Then associate the one going forwards with jet1 and the one going backwards with jet2
TLorentzRotation movingframe;
TLorentzVector pHJJ = pH+jet1massless+jet2massless;
TLorentzVector pHJJ_perp(pHJJ.X(), pHJJ.Y(), 0, pHJJ.T());
movingframe.Boost(-pHJJ_perp.BoostVector());
pHJJ.Boost(-pHJJ_perp.BoostVector());
movingframe.Boost(-pHJJ.BoostVector());
pHJJ.Boost(-pHJJ.BoostVector()); //make sure to boost HJJ AFTER boosting movingframe
TLorentzVector P1(0, 0, pHJJ.T()/2, pHJJ.T()/2);
TLorentzVector P2(0, 0, -pHJJ.T()/2, pHJJ.T()/2);
// Transform incoming partons back to original frame
P1.Transform(movingframe.Inverse());
P2.Transform(movingframe.Inverse());
pHJJ.Transform(movingframe.Inverse());
// movingframe and HJJ_T will not be used anymore
// Handle gen. partons if they are available
if (injet1 && injet2 && fabs((*injet1+*injet2).P()-pHJJ.P())<pHJJ.P()*1e-4){
P1=*injet1;
P2=*injet2;
if (P1.Z() < P2.Z()){
swap(P1, P2);
swap(injet1Id, injet2Id);
}
// In the case of gen. partons, check if the intermediates are a Z or a W.
int diff1Id = jet1Id-injet1Id;
int diff2Id = jet2Id-injet2Id;
if (
!( // THIS IS A NOT-IF!
(diff1Id==0 && diff2Id==0 && !(injet1Id==21 || injet2Id==21)) // Two Z bosons
||
((fabs(diff1Id)==1 || fabs(diff1Id)==3 || fabs(diff1Id)==5) && (fabs(diff2Id)==1 || fabs(diff2Id)==3 || fabs(diff2Id)==5)) // Two W bosons, do not check W+ vs W-
)
){
int diff12Id = jet1Id-injet2Id;
int diff21Id = jet2Id-injet1Id;
if (
((diff12Id==0 || diff21Id==0) && !(injet1Id==21 || injet2Id==21)) // At least one Z boson
||
((fabs(diff12Id)==1 || fabs(diff12Id)==3 || fabs(diff12Id)==5) || (fabs(diff21Id)==1 || fabs(diff21Id)==3 || fabs(diff21Id)==5)) // At least one W boson
){
swap(P1, P2);
swap(injet1Id, injet2Id);
}
}
}
TLorentzRotation ZZframe;
ZZframe.Boost(-pH.BoostVector());
P1.Transform(ZZframe);
P2.Transform(ZZframe);
p4Z1.Transform(ZZframe);
p4Z2.Transform(ZZframe);
jet1massless.Transform(ZZframe);
jet2massless.Transform(ZZframe);
TLorentzVector fermion1, fermion2, antifermion1, antifermion2;
// Consider cases with gen. partons
// By default, fermion1/2 are jet1/2 unless incoming partons are specifically anti-quarks!
if (injet1 && injet1Id<0){
fermion1=-P1;
antifermion1 = jet1massless;
}
else{
fermion1 = jet1massless;
antifermion1=-P1;
}
if (injet2 && injet2Id<0){
fermion2=-P2;
antifermion2 = jet2massless;
}
else{
fermion2 = jet2massless;
antifermion2=-P2;
}
// Computations in the frame of X
TLorentzVector V1 = fermion1 + antifermion1; // Outgoing V1
TLorentzVector V2 = fermion2 + antifermion2; // Outgoing V2
TVector3 normvec1 = fermion1.Vect().Cross(antifermion1.Vect()).Unit(); // p11 x p12
TVector3 normvec2 = fermion2.Vect().Cross(antifermion2.Vect()).Unit(); // p21 x p22
TVector3 normvec3 = p4Z2.Vect().Cross(V1.Vect()).Unit(); // z x V1
double cosPhi = normvec1.Dot(normvec2);
double sgnPhi = normvec1.Cross(normvec2).Dot(V1.Vect());
if (fabs(sgnPhi)>0.) sgnPhi = sgnPhi/fabs(sgnPhi);
double cosPhi1 = normvec1.Dot(normvec3);
double sgnPhi1 = normvec1.Cross(normvec3).Dot(V1.Vect());
if (fabs(sgnPhi1)>0.) sgnPhi1 = sgnPhi1/fabs(sgnPhi1);
if (fabs(cosPhi)>1) cosPhi *= 1./fabs(cosPhi);
if (fabs(cosPhi1)>1) cosPhi1 *= 1./fabs(cosPhi1);
Phi = acos(-cosPhi)*sgnPhi;
Phi1 = acos(cosPhi1)*sgnPhi1;
costhetastar = V1.Vect().Unit().Dot(p4Z2.Vect().Unit()); // Note that p4Z2 is still in outgoing convention, so in incoming terms, this is equivalent to putting p4Z1.
Q2V1 = -(V1.M2());
Q2V2 = -(V2.M2());
// Computations that would have been in the frame of X had V1 and V2 not been virtual
costheta1 = V1.Vect().Unit().Dot(fermion1.Vect().Unit());
costheta2 = V2.Vect().Unit().Dot(fermion2.Vect().Unit());
}
void TUtil::computeVBFAngles_ComplexBoost(
float& costhetastar,
float& costheta1_real, float& costheta1_imag,
float& costheta2_real, float& costheta2_imag,
float& Phi,
float& Phi1,
float& Q2V1,
float& Q2V2,
TLorentzVector p4M11, int Z1_lept1Id,
TLorentzVector p4M12, int Z1_lept2Id,
TLorentzVector p4M21, int Z2_lept1Id,
TLorentzVector p4M22, int Z2_lept2Id,
TLorentzVector jet1, int jet1Id,
TLorentzVector jet2, int jet2Id,
TLorentzVector* injet1, int injet1Id, // Gen. partons in the lab frame
TLorentzVector* injet2, int injet2Id
){
TLorentzVector const nullFourVector(0, 0, 0, 0);
TLorentzVector jet1massless, jet2massless;
pair<TLorentzVector, TLorentzVector> jetPair = TUtil::removeMassFromPair(jet1, jet1Id, jet2, jet2Id);
jet1massless = jetPair.first;
jet2massless = jetPair.second;
//build Z 4-vectors
TLorentzVector p4Z1 = p4M11 + p4M12;
TLorentzVector p4Z2 = p4M21 + p4M22;
TLorentzVector pH = p4Z1+p4Z2;
//jet1 is defined as going forwards (bigger pz), jet2 going backwards (smaller pz)
if (jet1massless.Z() < jet2massless.Z()) { swap(jet1massless, jet2massless); swap(jet1Id, jet2Id); }
//Find the incoming partons - first boost so the pT(HJJ) = 0, then boost away the pz.
//This preserves the z direction. Then assume that the partons come in this z direction.
//This is exactly correct at LO (since pT=0 anyway).
//Then associate the one going forwards with jet1 and the one going backwards with jet2
TLorentzRotation movingframe;
TLorentzVector pHJJ = pH+jet1massless+jet2massless;
TLorentzVector pHJJ_perp(pHJJ.X(), pHJJ.Y(), 0, pHJJ.T());
movingframe.Boost(-pHJJ_perp.BoostVector());
pHJJ.Boost(-pHJJ_perp.BoostVector());
movingframe.Boost(-pHJJ.BoostVector());
pHJJ.Boost(-pHJJ.BoostVector()); //make sure to boost HJJ AFTER boosting movingframe
TLorentzVector P1(0, 0, pHJJ.T()/2, pHJJ.T()/2);
TLorentzVector P2(0, 0, -pHJJ.T()/2, pHJJ.T()/2);
// Transform incoming partons back to original frame
P1.Transform(movingframe.Inverse());
P2.Transform(movingframe.Inverse());
pHJJ.Transform(movingframe.Inverse());
// movingframe and HJJ_T will not be used anymore
// Handle gen. partons if they are available
if (injet1 && injet2 && fabs((*injet1+*injet2).P()-pHJJ.P())<pHJJ.P()*1e-4){
P1=*injet1;
P2=*injet2;
if (P1.Z() < P2.Z()){
swap(P1, P2);
swap(injet1Id, injet2Id);
}
// In the case of gen. partons, check if the intermediates are a Z or a W.
int diff1Id = jet1Id-injet1Id;
int diff2Id = jet2Id-injet2Id;
if (
!( // THIS IS A NOT-IF!
(diff1Id==0 && diff2Id==0 && !(injet1Id==21 || injet2Id==21)) // Two Z bosons
||
((fabs(diff1Id)==1 || fabs(diff1Id)==3 || fabs(diff1Id)==5) && (fabs(diff2Id)==1 || fabs(diff2Id)==3 || fabs(diff2Id)==5)) // Two W bosons, do not check W+ vs W-
)
){
int diff12Id = jet1Id-injet2Id;
int diff21Id = jet2Id-injet1Id;
if (
((diff12Id==0 || diff21Id==0) && !(injet1Id==21 || injet2Id==21)) // At least one Z boson
||
((fabs(diff12Id)==1 || fabs(diff12Id)==3 || fabs(diff12Id)==5) || (fabs(diff21Id)==1 || fabs(diff21Id)==3 || fabs(diff21Id)==5)) // At least one W boson
){
swap(P1, P2);
swap(injet1Id, injet2Id);
}
}
}
TLorentzRotation ZZframe;
ZZframe.Boost(-pH.BoostVector());
P1.Transform(ZZframe);
P2.Transform(ZZframe);
p4Z1.Transform(ZZframe);
p4Z2.Transform(ZZframe);
jet1massless.Transform(ZZframe);
jet2massless.Transform(ZZframe);
TLorentzVector fermion1, fermion2, antifermion1, antifermion2;
// Consider cases with gen. partons
// By default, fermion1/2 are jet1/2 unless incoming partons are specifically anti-quarks!
if (injet1 && injet1Id<0){
fermion1=-P1;
antifermion1 = jet1massless;
}
else{
fermion1 = jet1massless;
antifermion1=-P1;
}
if (injet2 && injet2Id<0){
fermion2=-P2;
antifermion2 = jet2massless;
}
else{
fermion2 = jet2massless;
antifermion2=-P2;
}
// Computations in the frame of X
TLorentzVector V1 = fermion1 + antifermion1; // Outgoing V1
TLorentzVector V2 = fermion2 + antifermion2; // Outgoing V2
TVector3 normvec1 = fermion1.Vect().Cross(antifermion1.Vect()).Unit(); // p11 x p12
TVector3 normvec2 = fermion2.Vect().Cross(antifermion2.Vect()).Unit(); // p21 x p22
TVector3 normvec3 = p4Z2.Vect().Cross(V1.Vect()).Unit(); // z x V1
double cosPhi = normvec1.Dot(normvec2);
double sgnPhi = normvec1.Cross(normvec2).Dot(V1.Vect());
if (fabs(sgnPhi)>0.) sgnPhi = sgnPhi/fabs(sgnPhi);
double cosPhi1 = normvec1.Dot(normvec3);
double sgnPhi1 = normvec1.Cross(normvec3).Dot(V1.Vect());
if (fabs(sgnPhi1)>0.) sgnPhi1 = sgnPhi1/fabs(sgnPhi1);
if (fabs(cosPhi)>1) cosPhi *= 1./fabs(cosPhi);
if (fabs(cosPhi1)>1) cosPhi1 *= 1./fabs(cosPhi1);
Phi = acos(-cosPhi)*sgnPhi;
Phi1 = acos(cosPhi1)*sgnPhi1;
costhetastar = V1.Vect().Unit().Dot(p4Z2.Vect().Unit()); // Note that p4Z2 is still in outgoing convention, so in incoming terms, this is equivalent to putting p4Z1.
Q2V1 = -(V1.M2());
Q2V2 = -(V2.M2());
// Up to here, everything has to be the same as TUtil::computeVBFAngles
// Computations that would have been truly in the frame of X had V1 and V2 not been virtual:
// Use TUtil::ComplexBoost to evade imaginary gamma problems when beta**2<0
pair<TLorentzVector, TLorentzVector> V2_BV1 = TUtil::ComplexBoost(V1.BoostVector(), V2);
pair<TLorentzVector, TLorentzVector> fermion1_BV1 = TUtil::ComplexBoost(V1.BoostVector(), fermion1);
costheta1_real = -(V2_BV1.first.Vect().Unit().Dot(fermion1_BV1.first.Vect().Unit()) - V2_BV1.second.Vect().Unit().Dot(fermion1_BV1.second.Vect().Unit()));
costheta1_imag = -(V2_BV1.first.Vect().Unit().Dot(fermion1_BV1.second.Vect().Unit()) + V2_BV1.second.Vect().Unit().Dot(fermion1_BV1.first.Vect().Unit()));
pair<TLorentzVector, TLorentzVector> V1_BV2 = TUtil::ComplexBoost(V2.BoostVector(), V1);
pair<TLorentzVector, TLorentzVector> fermion2_BV2 = TUtil::ComplexBoost(V2.BoostVector(), fermion2);
costheta2_real = -(V1_BV2.first.Vect().Unit().Dot(fermion2_BV2.first.Vect().Unit()) - V1_BV2.second.Vect().Unit().Dot(fermion2_BV2.second.Vect().Unit()));
costheta2_imag = -(V1_BV2.first.Vect().Unit().Dot(fermion2_BV2.second.Vect().Unit()) + V1_BV2.second.Vect().Unit().Dot(fermion2_BV2.first.Vect().Unit()));
}
void TUtil::computeVHAngles(
float& costhetastar,
float& costheta1,
float& costheta2,
float& Phi,
float& Phi1,
float& m1,
float& m2,
TLorentzVector p4M11, int Z1_lept1Id,
TLorentzVector p4M12, int Z1_lept2Id,
TLorentzVector p4M21, int Z2_lept1Id,
TLorentzVector p4M22, int Z2_lept2Id,
TLorentzVector jet1, int jet1Id,
TLorentzVector jet2, int jet2Id,
TLorentzVector* injet1, int injet1Id, // Gen. partons in the lab frame
TLorentzVector* injet2, int injet2Id
){
TLorentzVector const nullFourVector(0, 0, 0, 0);
TLorentzVector jet1massless, jet2massless;
pair<TLorentzVector, TLorentzVector> jetPair = TUtil::removeMassFromPair(jet1, jet1Id, jet2, jet2Id);
jet1massless = jetPair.first;
jet2massless = jetPair.second;
// Build Z 4-vectors
TLorentzVector p4Z1 = p4M11 + p4M12;
TLorentzVector p4Z2 = p4M21 + p4M22;
TLorentzVector pH = p4Z1 + p4Z2;
// Apply convention for outgoing particles
if (
(jet1Id*jet2Id<0 && jet1Id<0) // for OS pairs: jet1 must be the particle
||
((jet1Id*jet2Id>0 || (jet1Id==0 && jet2Id==0)) && jet1massless.Phi()<=jet2massless.Phi()) // for SS pairs: use random deterministic convention
){
swap(jet1massless, jet2massless);
swap(jet1Id, jet2Id);
}
//Find the incoming partons - first boost so the pT(HJJ) = 0, then boost away the pz.
//This preserves the z direction.
//Then, assume that the partons come in this z direction.
//This is exactly correct at LO (since pT=0 anyway).
//Then associate the one going forwards with jet1 and the one going backwards with jet2
TLorentzRotation movingframe;
TLorentzVector pHJJ = pH+jet1massless+jet2massless;
TLorentzVector pHJJ_perp(pHJJ.X(), pHJJ.Y(), 0, pHJJ.T());
movingframe.Boost(-pHJJ_perp.BoostVector());
pHJJ.Boost(-pHJJ_perp.BoostVector());
movingframe.Boost(-pHJJ.BoostVector());
pHJJ.Boost(-pHJJ.BoostVector()); //make sure to boost HJJ AFTER boosting movingframe
TLorentzVector P1(0, 0, -pHJJ.T()/2, pHJJ.T()/2);
TLorentzVector P2(0, 0, pHJJ.T()/2, pHJJ.T()/2);
// Transform incoming partons back to the original frame
P1.Transform(movingframe.Inverse());
P2.Transform(movingframe.Inverse());
pHJJ.Transform(movingframe.Inverse());
// movingframe and HJJ_T will not be used anymore
// Handle gen. partons if they are available
if (injet1 && injet2 && fabs((*injet1+*injet2).P()-pHJJ.P())<pHJJ.P()*1e-4){
P1=*injet1;
P2=*injet2;
// Apply convention for incoming (!) particles
if (
(injet1Id*injet2Id<0 && injet1Id>0) // for OS pairs: parton 2 must be the particle
||
(injet1Id*injet2Id>0 && P1.Z()>=P2.Z()) //for SS pairs: use random deterministic convention
){
swap(P1, P2);
swap(injet1Id, injet2Id);
}
}
// Rotate every vector such that Z1 - Z2 axis is the "beam axis" analogue of decay
TLorentzRotation ZZframe;
TVector3 const beamAxis(0, 0, 1);
if (p4Z1==nullFourVector || p4Z2==nullFourVector){
TVector3 pNewAxis = (p4Z2-p4Z1).Vect().Unit(); // Let Z2 be in the z direction so that once the direction of H is reversed, Z1 is in the z direction
if (pNewAxis != nullFourVector.Vect()){
TVector3 pNewAxisPerp = pNewAxis.Cross(beamAxis);
ZZframe.Rotate(acos(pNewAxis.Dot(beamAxis)), pNewAxisPerp);
P1.Transform(ZZframe);
P2.Transform(ZZframe);
jet1massless = -jet1massless; jet1massless.Transform(ZZframe); jet1massless = -jet1massless;
jet2massless = -jet2massless; jet2massless.Transform(ZZframe); jet2massless = -jet2massless;
}
}
else{
ZZframe.Boost(-pH.BoostVector());
p4Z1.Boost(-pH.BoostVector());
p4Z2.Boost(-pH.BoostVector());
TVector3 pNewAxis = (p4Z2-p4Z1).Vect().Unit(); // Let Z2 be in the z direction so that once the direction of H is reversed, Z1 is in the z direction
TVector3 pNewAxisPerp = pNewAxis.Cross(beamAxis);
ZZframe.Rotate(acos(pNewAxis.Dot(beamAxis)), pNewAxisPerp);
P1.Transform(ZZframe);
P2.Transform(ZZframe);
jet1massless = -jet1massless; jet1massless.Transform(ZZframe); jet1massless = -jet1massless;
jet2massless = -jet2massless; jet2massless.Transform(ZZframe); jet2massless = -jet2massless;
}
TUtil::computeAngles(
costhetastar,
costheta1,
costheta2,
Phi,
Phi1,
-P1, 23, // Id is 23 to avoid an attempt to remove quark mass
-P2, 0, // Id is 0 to avoid swapping
jet1massless, 23,
jet2massless, 0
);
m1 = (P1 + P2).M();
m2 = (jet1massless + jet2massless).M();
}
void TUtil::computeTTHAngles(
// ttH system
float& hs,
float& hincoming,
float& hTT,
float& PhiTT,
float& Phi1,
// tt system
float& hbb,
float& hWW,
float& Phibb,
float& Phi1bb,
// Wplus system
float& hWplusf,
float& PhiWplusf,
// Wminus system
float& hWminusf,
float& PhiWminusf,
TLorentzVector p4M11, int Z1_lept1Id,
TLorentzVector p4M12, int Z1_lept2Id,
TLorentzVector p4M21, int Z2_lept1Id,
TLorentzVector p4M22, int Z2_lept2Id,
TLorentzVector b, int bId,
TLorentzVector Wplusf, int WplusfId,
TLorentzVector Wplusfb, int WplusfbId,
TLorentzVector bbar, int bbarId,
TLorentzVector Wminusf, int WminusfId,
TLorentzVector Wminusfb, int WminusfbId,
TLorentzVector* injet1, int injet1Id, // Gen. partons in the lab frame
TLorentzVector* injet2, int injet2Id
){
TLorentzVector const nullFourVector(0, 0, 0, 0);
TVector3 const beamAxis(0, 0, 1);
TVector3 const xAxis(1, 0, 0);
// Initialize output values
hs=hincoming=hTT=PhiTT=Phi1
=hbb=hWW=Phibb=Phi1bb
=hWplusf=PhiWplusf
=hWminusf=PhiWminusf=0;
if (
bId!=-9000 && !(PDGHelpers::isATopQuark(bId) || PDGHelpers::isATauLepton(bId)) && WplusfId==-9000 && WplusfbId==-9000
&&
bbarId!=-9000 && !(PDGHelpers::isATopQuark(bbarId) || PDGHelpers::isATauLepton(bbarId)) && WminusfId==-9000 && WminusfbId==-9000
){
float m1_dummy=0, m2_dummy=0;
return TUtil::computeVHAngles(
hs, hincoming, hTT, PhiTT, Phi1,
m1_dummy, m2_dummy,
p4M11, Z1_lept1Id,
p4M12, Z1_lept2Id,
p4M21, Z2_lept1Id,
p4M22, Z2_lept2Id,
b, bId,
bbar, bbarId,
injet1, injet1Id,
injet2, injet2Id
);
}
// Swap Wplus daughters if needed
if (
WplusfId!=-9000 && WplusfbId!=-9000
&&
(
(WplusfId*WplusfbId<0 && WplusfId<0) // for OS pairs: Wplusf must be the particle
||
((WplusfId*WplusfbId>0 || (WplusfId==0 && WplusfbId==0)) && Wplusf.Phi()<=Wplusfb.Phi()) // for SS pairs: use random deterministic convention
)
){
swap(Wplusf, Wplusfb);
swap(WplusfId, WplusfbId);
}
// Swap Wminus daughters if needed
if (
WminusfId!=-9000 && WminusfbId!=-9000
&&
(
(WminusfId*WminusfbId<0 && WminusfId<0) // for OS pairs: Wminusf must be the particle
||
((WminusfId*WminusfbId>0 || (WminusfId==0 && WminusfbId==0)) && Wminusf.Phi()<=Wminusfb.Phi()) // for SS pairs: use random deterministic convention
)
){
swap(Wminusf, Wminusfb);
swap(WminusfId, WminusfbId);
}
// Correct the T daughters
if (bId!=-9000 && WplusfId!=-9000 && WplusfbId!=-9000){
SimpleParticleCollection_t tmp_daus;
tmp_daus.reserve(3);
tmp_daus.emplace_back(bId, b);
tmp_daus.emplace_back(WplusfId, Wplusf);
tmp_daus.emplace_back(WplusfbId, Wplusfb);
TUtil::adjustTopDaughters(tmp_daus);
b = tmp_daus.at(0).second;
Wplusf = tmp_daus.at(1).second;
Wplusfb = tmp_daus.at(2).second;
}
else if (WplusfId!=-9000 && WplusfbId!=-9000){
pair<TLorentzVector, TLorentzVector> Wffb = TUtil::removeMassFromPair(Wplusf, WplusfId, Wplusfb, WplusfbId);
Wplusf = Wffb.first;
Wplusfb = Wffb.second;
}
// Correct the TBar daughters
if (bbarId!=-9000 && WminusfId!=-9000 && WminusfbId!=-9000){
SimpleParticleCollection_t tmp_daus;
tmp_daus.reserve(3);
tmp_daus.emplace_back(bbarId, bbar);
tmp_daus.emplace_back(WminusfId, Wminusf);
tmp_daus.emplace_back(WminusfbId, Wminusfb);
TUtil::adjustTopDaughters(tmp_daus);
bbar = tmp_daus.at(0).second;
Wminusf = tmp_daus.at(1).second;
Wminusfb = tmp_daus.at(2).second;
}
else if (WminusfId!=-9000 && WminusfbId!=-9000){
pair<TLorentzVector, TLorentzVector> Wffb = TUtil::removeMassFromPair(Wminusf, WminusfId, Wminusfb, WminusfbId);
Wminusf = Wffb.first;
Wminusfb = Wffb.second;
}
// If the Ws are not present but the bs are, the masses of the bs should not be removed. This is because the bs are now either tops or taus (based on the similar if-statement above).
// Build Z 4-vectors
TLorentzVector p4Z1 = p4M11 + p4M12;
TLorentzVector p4Z2 = p4M21 + p4M22;
// No longer need to use p4Mxy
TLorentzVector pH = p4Z1 + p4Z2;
TLorentzVector pWplus = Wplusf + Wplusfb;
TLorentzVector pTop = b + pWplus;
TLorentzVector pWminus = Wminusf + Wminusfb;
TLorentzVector pATop = bbar + pWminus;
TLorentzVector pTT = pTop + pATop;
TLorentzVector pTTH = pTT + pH;
//Find the incoming partons - first boost so the pT(TTH) = 0, then boost away the pz.
//This preserves the z direction.
//Then, assume that the partons come in this z direction.
//This is exactly correct at LO (since pT=0 anyway).
//Then associate the one going forwards with jet1 and the one going backwards with jet2
TLorentzRotation movingframe;
TLorentzVector pTTH_perp(pTTH.X(), pTTH.Y(), 0, pTTH.T());
movingframe.Boost(-pTTH_perp.BoostVector());
pTTH.Boost(-pTTH_perp.BoostVector());
movingframe.Boost(-pTTH.BoostVector());
pTTH.Boost(-pTTH.BoostVector()); //make sure to boost TTH AFTER boosting movingframe
TLorentzVector P1(0, 0, -pTTH.T()/2, pTTH.T()/2);
TLorentzVector P2(0, 0, pTTH.T()/2, pTTH.T()/2);
// Transform incoming partons back to the original frame
P1.Transform(movingframe.Inverse());
P2.Transform(movingframe.Inverse());
pTTH.Transform(movingframe.Inverse());
// movingframe and TTH_T will not be used anymore
// Handle gen. partons if they are available
if (injet1 && injet2 && fabs((*injet1+*injet2).P()-pTTH.P())<pTTH.P()*1e-4){
P1=*injet1;
P2=*injet2;
// Apply convention for incoming (!) particles
if (
(injet1Id*injet2Id<0 && injet1Id>0) // for OS pairs: parton 2 must be the particle
||
(injet1Id*injet2Id>0 && P1.Z()>=P2.Z()) //for SS pairs: parton 2 must have the greater pz
){
swap(P1, P2);
swap(injet1Id, injet2Id);
}
}
// Rotate every vector such that Z1 - Z2 axis is the "beam axis" analogue of decay
TLorentzRotation ZZframe;
bool applyZZframe=false;
if (p4Z1==nullFourVector || p4Z2==nullFourVector){ // Higgs is undecayed
TVector3 pNewAxis = (p4Z2-p4Z1).Vect().Unit(); // Let Z2 be in the z direction so that once the direction of H is reversed, Z1 is in the z direction
if (pNewAxis != nullFourVector.Vect()){
TVector3 pNewAxisPerp = pNewAxis.Cross(beamAxis);
ZZframe.Rotate(acos(pNewAxis.Dot(beamAxis)), pNewAxisPerp);
applyZZframe=true;
}
}
else{
TVector3 pHboost = pH.BoostVector();
ZZframe.Boost(-pHboost);
p4Z1.Boost(-pHboost);
p4Z2.Boost(-pHboost);
TVector3 pNewAxis = (p4Z2-p4Z1).Vect().Unit(); // Let Z2 be in the z direction so that once the direction of H is reversed, Z1 is in the z direction
TVector3 pNewAxisPerp = pNewAxis.Cross(beamAxis);
ZZframe.Rotate(acos(pNewAxis.Dot(beamAxis)), pNewAxisPerp);
// Boost p4Z1 and p4Z2 back so that you can apply the transformation separately
p4Z1.Boost(pHboost);
p4Z2.Boost(pHboost);
applyZZframe=true;
}
if (applyZZframe){
P1.Transform(ZZframe); P2.Transform(ZZframe);
p4Z1 = -p4Z1; p4Z1.Transform(ZZframe); p4Z1 = -p4Z1;
p4Z2 = -p4Z2; p4Z2.Transform(ZZframe); p4Z2 = -p4Z2;
b = -b; b.Transform(ZZframe); b = -b;
Wplusf = -Wplusf; Wplusf.Transform(ZZframe); Wplusf = -Wplusf;
Wplusfb = -Wplusfb; Wplusfb.Transform(ZZframe); Wplusfb = -Wplusfb;
bbar = -bbar; bbar.Transform(ZZframe); bbar = -bbar;
Wminusf = -Wminusf; Wminusf.Transform(ZZframe); Wminusf = -Wminusf;
Wminusfb = -Wminusfb; Wminusfb.Transform(ZZframe); Wminusfb = -Wminusfb;
}
// Re-assign derived momenta
pH = p4Z1 + p4Z2;
pWplus = Wplusf + Wplusfb;
pTop = b + pWplus;
pWminus = Wminusf + Wminusfb;
pATop = bbar + pWminus;
pTT = pTop + pATop;
pTTH = pTT + pH;
TUtil::computeAngles(
hs,
hincoming,
hTT,
PhiTT,
Phi1,
-P1, 23, // Id is 23 to avoid an attempt to remove quark mass
-P2, 0, // Id is 0 to avoid swapping
pTop, 23,
pATop, 0
);
// Boost everything to Higgs frame AFTER ttH-frame angle computations
// This is to avoid an undetermined z axis in the above angles when Higgs is undecayed
{
TVector3 pHboost = pH.BoostVector();
P1.Boost(-pHboost);
P2.Boost(-pHboost);
// No need for Z1 and Z2
//p4Z1.Boost(-pHboost);
//p4Z2.Boost(-pHboost);
b.Boost(-pHboost);
Wplusf.Boost(-pHboost);
Wplusfb.Boost(-pHboost);
bbar.Boost(-pHboost);
Wminusf.Boost(-pHboost);
Wminusfb.Boost(-pHboost);
// Re-assign derived momenta
// No need for the Higgs in Higgs frame
//pH = p4Z1 + p4Z2;
pWplus = Wplusf + Wplusfb;
pTop = b + pWplus;
pWminus = Wminusf + Wminusfb;
pATop = bbar + pWminus;
pTT = pTop + pATop;
// No need for the TTH system in Higgs frame
//pTTH = pTT + pH;
}
{
TLorentzRotation TTframe;
// z rotation
TVector3 nNewZAxis = (-P1-P2-pTop-pATop).Vect().Unit(); // Let the z axis be formed by the (-P1-P2)--TT axis in the Higgs frame
if (nNewZAxis != nullFourVector.Vect()){
TVector3 nNewZAxisPerp = nNewZAxis.Cross(beamAxis);
TTframe.Rotate(acos(nNewZAxis.Dot(beamAxis)), nNewZAxisPerp);
}
P1.Transform(TTframe);
P2.Transform(TTframe);
b.Transform(TTframe);
Wplusf.Transform(TTframe);
Wplusfb.Transform(TTframe);
bbar.Transform(TTframe);
Wminusf.Transform(TTframe);
Wminusfb.Transform(TTframe);
// Re-assign derived momenta
pWplus = Wplusf + Wplusfb;
pTop = b + pWplus;
pWminus = Wminusf + Wminusfb;
pATop = bbar + pWminus;
}
// Compute TT angles
{
float hs_dummy;
int id_dummy_Wplus=24;
int id_dummy_Wminus=-24;
if (WplusfId!=-9000 && WplusfbId!=-9000) id_dummy_Wplus=-9000;
if (WminusfId!=-9000 && WminusfbId!=-9000) id_dummy_Wminus=-9000;
TUtil::computeAngles(
hs_dummy,
hbb,
hWW,
Phibb, // -\Phi_b from arxiv:1606.03107
Phi1bb, // This angle is the one between the bb plane and the TT-H plane instead of that between the WW plane and the TT-H plane as defined in arxiv:1606.03107.
b, bId,
bbar, bbarId,
pWplus, id_dummy_Wplus,
pWminus, id_dummy_Wminus
);
}
// Wplus frame
if (WplusfId!=-9000 && WplusfbId!=-9000){
TLorentzVector pATop_tmp = pATop;
TVector3 pWplus_boost = (Wplusf+Wplusfb).BoostVector();
b.Boost(-pWplus_boost);
Wplusf.Boost(-pWplus_boost);
Wplusfb.Boost(-pWplus_boost);
pATop_tmp.Boost(-pWplus_boost);
TLorentzRotation Wplusframe;
// z rotation
TVector3 nNewZAxis = (b+Wplusf+Wplusfb-pATop_tmp).Vect().Unit(); // Let the z axis be formed by the TBar direction
if (nNewZAxis != nullFourVector.Vect()){
TVector3 nNewZAxisPerp = nNewZAxis.Cross(beamAxis);
Wplusframe.Rotate(acos(nNewZAxis.Dot(beamAxis)), nNewZAxisPerp);
}
b.Transform(Wplusframe);
Wplusf.Transform(Wplusframe);
Wplusfb.Transform(Wplusframe);
TVector3 n3_Wb = -b.Vect().Unit();
TVector3 nW = ((Wplusf-Wplusfb).Vect().Cross(n3_Wb)).Unit();
TVector3 nS = (beamAxis.Cross(n3_Wb)).Unit();
// hWplusf
hWplusf = n3_Wb.Dot(Wplusf.Vect().Unit());
// PhiWplusf
float tmpSgnPhiWplusf = n3_Wb.Dot(nW.Cross(nS));
float sgnPhiWplusf = 0;
if (fabs(tmpSgnPhiWplusf)>0.) sgnPhiWplusf = tmpSgnPhiWplusf/fabs(tmpSgnPhiWplusf);
float dot_nWnS = nW.Dot(nS);
if (fabs(dot_nWnS)>=1.) dot_nWnS *= 1./fabs(dot_nWnS);
PhiWplusf = sgnPhiWplusf * acos(dot_nWnS);
/*
b.Transform(Wplusframe.Inverse());
Wplusf.Transform(Wplusframe.Inverse());
Wplusfb.Transform(Wplusframe.Inverse());
*/
}
// Wminus frame
if (WminusfId!=-9000 && WminusfbId!=-9000){
TLorentzVector pTop_tmp = pTop;
TVector3 pWminus_boost = (Wminusf+Wminusfb).BoostVector();
bbar.Boost(-pWminus_boost);
Wminusf.Boost(-pWminus_boost);
Wminusfb.Boost(-pWminus_boost);
pTop_tmp.Boost(-pWminus_boost);
TLorentzRotation Wminusframe;
// z rotation
TVector3 nNewZAxis = (pTop_tmp-bbar-Wminusf-Wminusfb).Vect().Unit(); // Let the z axis be formed by the T direction
if (nNewZAxis != nullFourVector.Vect()){
TVector3 nNewZAxisPerp = nNewZAxis.Cross(beamAxis);
Wminusframe.Rotate(acos(nNewZAxis.Dot(beamAxis)), nNewZAxisPerp);
}
bbar.Transform(Wminusframe);
Wminusf.Transform(Wminusframe);
Wminusfb.Transform(Wminusframe);
TVector3 n3_Wb = -bbar.Vect().Unit();
TVector3 nW = ((Wminusf-Wminusfb).Vect().Cross(n3_Wb)).Unit();
TVector3 nS = (beamAxis.Cross(n3_Wb)).Unit();
// hWminusf
hWminusf = n3_Wb.Dot(Wminusf.Vect().Unit());
// PhiWminusf
float tmpSgnPhiWminusf = n3_Wb.Dot(nW.Cross(nS));
float sgnPhiWminusf = 0;
if (fabs(tmpSgnPhiWminusf)>0.) sgnPhiWminusf = tmpSgnPhiWminusf/fabs(tmpSgnPhiWminusf);
float dot_nWnS = nW.Dot(nS);
if (fabs(dot_nWnS)>=1.) dot_nWnS *= 1./fabs(dot_nWnS);
PhiWminusf = sgnPhiWminusf * acos(dot_nWnS);
/*
bbar.Transform(Wminusframe.Inverse());
Wminusf.Transform(Wminusframe.Inverse());
Wminusfb.Transform(Wminusframe.Inverse());
*/
}
}
/****************************************************/
/***** JHUGen- and MCFM-related ME computations *****/
/****************************************************/
void TUtil::SetEwkCouplingParameters(double ext_Gf, double ext_aemmz, double ext_mW, double ext_mZ, double ext_xW, int ext_ewscheme){
// Set JHUGen couplings
const double GeV=1./100.;
double ext_mZ_jhu = ext_mZ*GeV;
double ext_mW_jhu = ext_mW*GeV;
double ext_Gf_jhu = ext_Gf/pow(GeV, 2);
__modjhugenmela_MOD_setewparameters(&ext_mZ_jhu, &ext_mW_jhu, &ext_Gf_jhu, &ext_aemmz, &ext_xW);
// Set MCFM couplings
if (ext_ewscheme<-1 || ext_ewscheme>3) ext_ewscheme=3;
ewinput_.Gf_inp = ext_Gf;
ewinput_.aemmz_inp = ext_aemmz;
ewinput_.wmass_inp = ext_mW;
ewinput_.zmass_inp = ext_mZ;
ewinput_.xw_inp = ext_xW;
ewscheme_.ewscheme = ext_ewscheme;
coupling_();
// SETTINGS TO MATCH JHUGen ME/generator:
/*
ewscheme_.ewscheme = 3; // Switch ewscheme to full control, default is 1
ewinput_.Gf_inp=1.16639E-05;
ewinput_.aemmz_inp=1./128.;
ewinput_.wmass_inp=80.399;
ewinput_.zmass_inp=91.1876;
ewinput_.xw_inp=0.23119;
*/
// Settings used in Run I MC, un-synchronized to JHUGen and Run II generation
/*
ewinput_.Gf_inp = 1.16639E-05;
ewinput_.wmass_inp = 80.385;
ewinput_.zmass_inp = 91.1876;
//ewinput_.aemmz_inp = 7.81751e-3; // Not used in the compiled new default MCFM ewcheme=1
//ewinput_.xw_inp = 0.23116864; // Not used in the compiled new default MCFM ewcheme=1
ewinput_.aemmz_inp = 7.562468901984759e-3;
ewinput_.xw_inp = 0.2228972225239183;
*/
// INPUT SETTINGS in default MCFM generator:
/*
ewscheme_.ewscheme = 1;
ewinput_.Gf_inp=1.16639E-05;
ewinput_.wmass_inp=80.398;
ewinput_.zmass_inp=91.1876;
ewinput_.aemmz_inp=7.7585538055706e-3;
ewinput_.xw_inp=0.2312;
*/
// ACTUAL SETTINGS in default MCFM generator, gives the same values as above but is more explicit
/*
ewscheme_.ewscheme = 3;
ewinput_.Gf_inp=1.16639E-05;
ewinput_.wmass_inp=80.398;
ewinput_.zmass_inp=91.1876;
ewinput_.aemmz_inp=7.55638390728736e-3;
ewinput_.xw_inp=0.22264585341299625;
*/
}
void TUtil::SetMass(double inmass, int ipart){
const int ipartabs = abs(ipart);
bool runcoupling_mcfm=false;
bool runcoupling_jhugen=false;
// MCFM masses
// Tprime and bprime masses are not defined in masses.f
if (ipartabs==8) spinzerohiggs_anomcoupl_.mt_4gen = inmass;
else if (ipartabs==7) spinzerohiggs_anomcoupl_.mb_4gen = inmass;
else if (ipartabs==6){ masses_mcfm_.mt=inmass; runcoupling_mcfm=true; }
else if (ipartabs==5){ masses_mcfm_.mb=inmass; masses_mcfm_.mbsq = pow(masses_mcfm_.mb, 2); runcoupling_mcfm=true; }
else if (ipartabs==4){ masses_mcfm_.mc=inmass; masses_mcfm_.mcsq = pow(masses_mcfm_.mc, 2); runcoupling_mcfm=true; }
else if (ipartabs==3) masses_mcfm_.ms=inmass;
else if (ipartabs==2) masses_mcfm_.mu=inmass;
else if (ipartabs==1) masses_mcfm_.md=inmass;
else if (ipartabs==11) masses_mcfm_.mel=inmass;
else if (ipartabs==13) masses_mcfm_.mmu=inmass;
else if (ipartabs==15){ masses_mcfm_.mtau=inmass; masses_mcfm_.mtausq = pow(masses_mcfm_.mtau, 2); }
else if (ipartabs==23){ masses_mcfm_.zmass=inmass; ewinput_.zmass_inp = inmass; runcoupling_mcfm=true; }
else if (ipartabs==24){ masses_mcfm_.wmass=inmass; ewinput_.wmass_inp = inmass; runcoupling_mcfm=true; }
else if (ipartabs==25) masses_mcfm_.hmass=inmass;
// JHUGen masses
if (
ipartabs<=6
||
(ipartabs>=11 && ipartabs<=16)
||
ipartabs==23 || ipartabs==24 || ipartabs==25
||
ipartabs==32 || ipartabs==34
){
runcoupling_jhugen=(
ipartabs==23
||
ipartabs==24
);
const double GeV=1./100.;
double jinmass = inmass*GeV;
int jpart = convertLHEreverse(&ipart);
__modparameters_MOD_setmass(&jinmass, &jpart);
}
// Recalculate couplings
if (runcoupling_mcfm || runcoupling_jhugen) SetEwkCouplingParameters(ewcouple_.Gf, em_.aemmz, masses_mcfm_.wmass, masses_mcfm_.zmass, ewcouple_.xw, ewscheme_.ewscheme);
}
void TUtil::SetDecayWidth(double inwidth, int ipart){
const int ipartabs = abs(ipart);
// No need to recalculate couplings
// MCFM masses
if (ipartabs==6) masses_mcfm_.twidth=inwidth;
else if (ipartabs==15) masses_mcfm_.tauwidth=inwidth;
else if (ipartabs==23) masses_mcfm_.zwidth=inwidth;
else if (ipartabs==24) masses_mcfm_.wwidth=inwidth;
else if (ipartabs==25) masses_mcfm_.hwidth=inwidth;
// JHUGen masses
const double GeV=1./100.;
double jinwidth = inwidth*GeV;
int jpart = convertLHEreverse(&ipart);
__modparameters_MOD_setdecaywidth(&jinwidth, &jpart);
}
void TUtil::SetCKMElements(double* invckm_ud, double* invckm_us, double* invckm_cd, double* invckm_cs, double* invckm_ts, double* invckm_tb, double* invckm_ub, double* invckm_cb, double* invckm_td){
__modparameters_MOD_computeckmelements(invckm_ud, invckm_us, invckm_cd, invckm_cs, invckm_ts, invckm_tb, invckm_ub, invckm_cb, invckm_td);
int i, j;
i=2; j=1;
cabib_.Vud = __modparameters_MOD_ckmbare(&i, &j);
i=2; j=3;
cabib_.Vus = __modparameters_MOD_ckmbare(&i, &j);
i=2; j=5;
cabib_.Vub = __modparameters_MOD_ckmbare(&i, &j);
i=4; j=1;
cabib_.Vcd = __modparameters_MOD_ckmbare(&i, &j);
i=4; j=3;
cabib_.Vcs = __modparameters_MOD_ckmbare(&i, &j);
i=4; j=5;
cabib_.Vcb = __modparameters_MOD_ckmbare(&i, &j);
// Do not call ckmfill_(), it is called by MCFM_chooser!
}
double TUtil::GetCKMElement(int iquark, int jquark){
return __modparameters_MOD_ckmbare(&iquark, &jquark);
}
double TUtil::GetMass(int ipart){
const int ipartabs = abs(ipart);
if (ipartabs==8) return spinzerohiggs_anomcoupl_.mt_4gen;
else if (ipartabs==7) return spinzerohiggs_anomcoupl_.mb_4gen;
else if (ipartabs==6) return masses_mcfm_.mt;
else if (ipartabs==5) return masses_mcfm_.mb;
else if (ipartabs==4) return masses_mcfm_.mc;
else if (ipartabs==3) return masses_mcfm_.ms;
else if (ipartabs==2) return masses_mcfm_.mu;
else if (ipartabs==1) return masses_mcfm_.md;
else if (ipartabs==11) return masses_mcfm_.mel;
else if (ipartabs==13) return masses_mcfm_.mmu;
else if (ipartabs==15) return masses_mcfm_.mtau;
else if (ipartabs==23) return masses_mcfm_.zmass;
else if (ipartabs==24) return masses_mcfm_.wmass;
else if (ipartabs==25) return masses_mcfm_.hmass;
else{
// JHUGen masses
if (
ipartabs<=6 // (d, u, s, c, b, t)
||
(ipartabs>=11 && ipartabs<=16) // (l, nu) x (e, mu, tau)
||
ipartabs==23 || ipartabs==24 || ipartabs==25 // Z, W, H
||
ipartabs==32 || ipartabs==34 // Z', W+-'
){
const double GeV=1./100.;
int jpart = convertLHEreverse(&ipart);
double joutmass = __modparameters_MOD_getmass(&jpart);
double outmass = joutmass/GeV;
return outmass;
}
else return 0;
}
}
double TUtil::GetDecayWidth(int ipart){
const int ipartabs = abs(ipart);
// MCFM widths
if (ipartabs==6) return masses_mcfm_.twidth;
else if (ipartabs==15) return masses_mcfm_.tauwidth;
else if (ipartabs==23) return masses_mcfm_.zwidth;
else if (ipartabs==24) return masses_mcfm_.wwidth;
else if (ipartabs==25) return masses_mcfm_.hwidth;
else{
// JHUGen widths
const double GeV=1./100.;
int jpart = convertLHEreverse(&ipart);
double joutwidth = __modparameters_MOD_getdecaywidth(&jpart);
double outwidth = joutwidth/GeV;
return outwidth;
}
}
double TUtil::GetMass(const MELAParticle* part){
if (part==nullptr) return GetMass(-9000);
return GetMass(part->id);
}
double TUtil::GetDecayWidth(const MELAParticle* part){
if (part==nullptr) return GetDecayWidth(-9000);
return GetDecayWidth(part->id);
}
void TUtil::GetMassWidth(int ipart, double& m, double& ga){
m=TUtil::GetMass(ipart);
ga=TUtil::GetDecayWidth(ipart);
}
void TUtil::GetMassWidth(const MELAParticle* part, double& m, double& ga){
if (part==nullptr) return GetMassWidth(-9000, m, ga);
return GetMassWidth(part->id, m, ga);
}
double TUtil::InterpretScaleScheme(const TVar::Production& production, const TVar::MatrixElement& matrixElement, const TVar::EventScaleScheme& scheme, TLorentzVector p[mxpart]){
double Q=0;
TLorentzVector const nullFourVector(0, 0, 0, 0);
if (scheme == TVar::Fixed_mH) Q = masses_mcfm_.hmass;
else if (scheme == TVar::Fixed_mW) Q = masses_mcfm_.wmass;
else if (scheme == TVar::Fixed_mZ) Q = masses_mcfm_.zmass;
else if (scheme == TVar::Fixed_mWPlusmH) Q = (masses_mcfm_.wmass+masses_mcfm_.hmass);
else if (scheme == TVar::Fixed_mZPlusmH) Q = (masses_mcfm_.zmass+masses_mcfm_.hmass);
else if (scheme == TVar::Fixed_TwomtPlusmH) Q = (2.*masses_mcfm_.mt+masses_mcfm_.hmass);
else if (scheme == TVar::Fixed_mtPlusmH) Q = masses_mcfm_.mt+masses_mcfm_.hmass;
else if (scheme == TVar::Dynamic_qH){
TLorentzVector pTotal = p[2]+p[3]+p[4]+p[5];
Q = fabs(pTotal.M());
}
else if (scheme == TVar::Dynamic_qJJH){
TLorentzVector pTotal = p[2]+p[3]+p[4]+p[5]+p[6]+p[7];
Q = fabs(pTotal.M());
}
else if (scheme == TVar::Dynamic_qJJ_qH){
TLorentzVector qH = p[2]+p[3]+p[4]+p[5];
TLorentzVector qJJ = p[6]+p[7];
Q = fabs(qH.M()+qJJ.M());
}
else if (scheme == TVar::Dynamic_qJ_qJ_qH){
TLorentzVector qH = p[2]+p[3]+p[4]+p[5];
Q = fabs(qH.M()+p[6].M()+p[7].M());
}
else if (scheme == TVar::Dynamic_HT){
for (int c=2; c<mxpart; c++) Q += p[c].Pt(); // Scalar sum of all pTs
}
else if (scheme == TVar::Dynamic_Leading_pTJ){
// pT of the hardest jet, should be just p[6].Pt() if jets are already ordered in pT
for (int c=6; c<mxpart; c++) Q = std::max(Q, p[c].Pt());
}
else if (scheme == TVar::Dynamic_Softest_pTJ){
// pT of the softest jet, should be just p[7].Pt() if jets are already ordered in pT
Q = p[6].Pt();
for (int c=7; c<mxpart; c++){ if (p[c].Pt()>0.) Q = std::min(Q, p[c].Pt()); }
if (Q<0.) Q = 0;
}
else if (scheme == TVar::DefaultScaleScheme){
// Defaults are dynamic scales except in ttH and bbH.
if (matrixElement==TVar::JHUGen){
if (
production == TVar::JJQCD
|| production == TVar::JJVBF
|| production == TVar::JQCD
|| production == TVar::ZZGG
|| production == TVar::ZZQQB
|| production == TVar::ZZQQB_STU
|| production == TVar::ZZQQB_S
|| production == TVar::ZZQQB_TU
|| production == TVar::ZZINDEPENDENT
|| production == TVar::Lep_WH || production == TVar::Had_WH
|| production == TVar::Lep_ZH || production == TVar::Had_ZH
|| production == TVar::GammaH
){
TLorentzVector pTotal = p[2]+p[3]+p[4]+p[5];
Q = fabs(pTotal.M());
}
else if (
production == TVar::ttH
||
production == TVar::bbH
) Q = (2.*masses_mcfm_.mt+masses_mcfm_.hmass);
}
else if (matrixElement==TVar::MCFM){
if (
production == TVar::ZZGG
|| production == TVar::ZZINDEPENDENT
|| production == TVar::ZZQQB
|| production == TVar::ZZQQB_STU
|| production == TVar::JQCD
|| production == TVar::JJQCD
|| production == TVar::JJVBF
|| production == TVar::JJEW
|| production == TVar::JJEWQCD
|| production == TVar::Lep_WH || production == TVar::Had_WH
|| production == TVar::Lep_ZH || production == TVar::Had_ZH
|| production == TVar::ZZQQB_S
|| production == TVar::JJQCD_S
|| production == TVar::JJVBF_S
|| production == TVar::JJEW_S
|| production == TVar::JJEWQCD_S
|| production == TVar::Lep_WH_S || production == TVar::Had_WH_S
|| production == TVar::Lep_ZH_S || production == TVar::Had_ZH_S
|| production == TVar::ZZQQB_TU
|| production == TVar::JJQCD_TU
|| production == TVar::JJVBF_TU
|| production == TVar::JJEW_TU
|| production == TVar::JJEWQCD_TU
|| production == TVar::Lep_WH_TU || production == TVar::Had_WH_TU
|| production == TVar::Lep_ZH_TU || production == TVar::Had_ZH_TU
|| production == TVar::GammaH
){
TLorentzVector pTotal = p[2]+p[3]+p[4]+p[5];
Q = fabs(pTotal.M());
}
else if (
production == TVar::ttH
|| production == TVar::bbH
){ // ttH and bbH are not implemented through MCFM, will need revision if they are implemented.
TLorentzVector pTotal = p[2]+p[3]+p[4]+p[5]+p[6]+p[7];
Q = fabs(pTotal.M());
}
}
}
if (Q<=0.){
MELAerr << "Scaling " << scheme << " fails for production " << production << ", defaulting to dynamic scheme m3456 " << endl;
TLorentzVector pTotal = p[2]+p[3]+p[4]+p[5];
Q = fabs(pTotal.M());
}
return Q;
}
void TUtil::SetAlphaS(double& Q_ren, double& Q_fac, double multiplier_ren, double multiplier_fac, int mynloop, int mynflav, string mypartons){
bool hasReset=false;
if (multiplier_ren<=0. || multiplier_fac<=0.){
MELAerr << "TUtil::SetAlphaS: Invalid scale multipliers" << endl;
return;
}
if (Q_ren<=1. || Q_fac<=1. || mynloop<=0 || mypartons.compare("Default")==0){
if (Q_ren<0.) MELAout << "TUtil::SetAlphaS: Invalid QCD scale for alpha_s, setting to mH/2..." << endl;
if (Q_fac<0.) MELAout << "TUtil::SetAlphaS: Invalid factorization scale, setting to mH/2..." << endl;
Q_ren = (masses_mcfm_.hmass)*0.5;
Q_fac = Q_ren;
mynloop = 1;
hasReset=true;
}
if (!hasReset){
Q_ren *= multiplier_ren;
Q_fac *= multiplier_fac;
}
/***** MCFM Alpha_S *****/
bool nflav_is_same = (nflav_.nflav == mynflav);
if (!nflav_is_same) MELAout << "TUtil::SetAlphaS: nflav=" << nflav_.nflav << " is the only one supported." << endl;
scale_.scale = Q_ren;
scale_.musq = Q_ren*Q_ren;
facscale_.facscale = Q_fac;
if (mynloop!=1){
MELAout << "TUtil::SetAlphaS: Only nloop=1 is supported!" << endl;
mynloop=1;
}
nlooprun_.nlooprun = mynloop;
/***** JHUGen Alpha_S *****/
/*
///// Disabling alpha_s computation from MCFM to replace with the JHUGen implementation, allows LHAPDF interface readily /////
// For proper pdfwrapper_linux.f execution (alpha_s computation does not use pdf but examines the pdf name to initialize amz.)
if (mypartons.compare("Default")!=0 && mypartons.compare("cteq6_l")!=0 && mypartons.compare("cteq6l1")!=0){
MELAout << "Only default=cteq6l1 or cteq6_l are supported. Modify mela.cc symlinks, put the pdf table into data/Pdfdata and retry. Setting mypartons to Default..." << endl;
mypartons = "Default";
}
// From pdfwrapper_linux.f:
if (mypartons.compare("cteq6_l")==0) couple_.amz = 0.118;
else if (mypartons.compare("cteq6l1")==0 || mypartons.compare("Default")==0) couple_.amz = 0.130;
else couple_.amz = 0.118; // Add pdf as appropriate
if (!nflav_is_same){
nflav_.nflav = mynflav;
if (mypartons.compare("Default")!=0) sprintf(pdlabel_.pdlabel, "%s", mypartons.c_str());
else sprintf(pdlabel_.pdlabel, "%s", "cteq6l1"); // Default pdf is cteq6l1
coupling2_();
}
else qcdcouple_.as = alphas_(&(scale_.scale), &(couple_.amz), &(nlooprun_.nlooprun));
*/
const double GeV=1./100.;
double muren_jhu = scale_.scale*GeV;
double mufac_jhu = facscale_.facscale*GeV;
__modjhugenmela_MOD_setmurenfac(&muren_jhu, &mufac_jhu);
__modparameters_MOD_evalalphas();
TUtil::GetAlphaS(&(qcdcouple_.as), &(couple_.amz));
qcdcouple_.gsq = 4.0*TMath::Pi()*qcdcouple_.as;
qcdcouple_.ason2pi = qcdcouple_.as/(2.0*TMath::Pi());
qcdcouple_.ason4pi = qcdcouple_.as/(4.0*TMath::Pi());
// TEST RUNNING SCALE PER EVENT:
/*
if(verbosity >= TVar::DEBUG){
MELAout << "My pdf is: " << pdlabel_.pdlabel << endl;
MELAout << "My Q_ren: " << Q_ren << " | My alpha_s: " << qcdcouple_.as << " at order " << nlooprun_.nlooprun << " with a(m_Z): " << couple_.amz << '\t'
<< "Nflav: " << nflav_.nflav << endl;
*/
}
void TUtil::GetAlphaS(double* alphas_, double* alphasmz_){
double alphasVal=0, alphasmzVal=0;
__modjhugenmela_MOD_getalphasalphasmz(&alphasVal, &alphasmzVal);
if (alphas_!=0) *alphas_ = alphasVal;
if (alphasmz_!=0) *alphasmz_ = alphasmzVal;
}
// chooser.f split into 2 different functions
bool TUtil::MCFM_chooser(
const TVar::Process& process, const TVar::Production& production, const TVar::LeptonInterference& leptonInterf,
const TVar::VerbosityLevel& verbosity,
const simple_event_record& mela_event
){
bool result = true;
unsigned int ndau = mela_event.pDaughters.size();
int* pId = new int[ndau];
for (unsigned int ip=0; ip<ndau; ip++){
pId[ip]=mela_event.pDaughters.at(ip).first;
}
bool isWW = (ndau>=4 && PDGHelpers::isAWBoson(mela_event.intermediateVid.at(0)) && PDGHelpers::isAWBoson(mela_event.intermediateVid.at(1)));
bool isZZ = (ndau>=4 && PDGHelpers::isAZBoson(mela_event.intermediateVid.at(0)) && PDGHelpers::isAZBoson(mela_event.intermediateVid.at(1)));
bool hasZZ4fInterf = isZZ && abs(pId[0])==abs(pId[2]) && abs(pId[1])==abs(pId[3]) && !PDGHelpers::isAnUnknownJet(pId[0]) && !PDGHelpers::isAnUnknownJet(pId[3]);
//bool isZJJ = false;
//if (ndau>=4) isZJJ = (PDGHelpers::isAZBoson(mela_event.intermediateVid.at(0)) && PDGHelpers::isAJet(pId[2]) && PDGHelpers::isAJet(pId[3])); // Notice both isZZ and isZJJ could be true
//bool isZG = (ndau>=3 && PDGHelpers::isAZBoson(mela_event.intermediateVid.at(0)) && PDGHelpers::isAPhoton(mela_event.intermediateVid.at(1)));
bool isGG = (ndau>=2 && PDGHelpers::isAPhoton(mela_event.intermediateVid.at(0)) && PDGHelpers::isAPhoton(mela_event.intermediateVid.at(1)));
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::MCFM_chooser: isWW=" << (int)isWW << ", isZZ=" << (int)isZZ << ", hasZZ4fInterf=" << (int)hasZZ4fInterf << endl;
npart_.npart=4; // Default number of particles is just 4, indicating no associated particles
sprintf(runstring_.runstring, "test");
if (
ndau>=4
&&
(
((production == TVar::ZZQQB_STU || production == TVar::ZZQQB_S || production == TVar::ZZQQB_TU) && process == TVar::bkgZZ)
||
((production == TVar::ZZINDEPENDENT || production == TVar::ZZQQB) && process == TVar::bkgZZ)
)
){
//81 ' f(p1)+f(p2) --> Z^0(-->mu^-(p3)+mu^+(p4)) + Z^0(-->e^-(p5)+e^+(p6))'
//86 ' f(p1)+f(p2) --> Z^0(-->e^-(p5)+e^+(p6))+Z^0(-->mu^-(p3)+mu^+(p4)) (NO GAMMA*)'
//90 ' f(p1)+f(p2) --> Z^0(-->e^-(p3)+e^+(p4)) + Z^0(-->e^-(p5)+e^+(p6))' 'L'
nqcdjets_.nqcdjets=0;
srdiags_.srdiags=true;
nwz_.nwz=0; ckmfill_(&(nwz_.nwz));
bveg1_mcfm_.ndim=10;
breit_.n2=1;
breit_.n3=1;
breit_.mass2=masses_mcfm_.zmass;
breit_.width2=masses_mcfm_.zwidth;
breit_.mass3=masses_mcfm_.zmass;
breit_.width3=masses_mcfm_.zwidth;
vsymfact_.vsymfact=1.0;
interference_.interference=false;
if (hasZZ4fInterf && (leptonInterf==TVar::DefaultLeptonInterf || leptonInterf==TVar::InterfOn)){
//90 ' f(p1)+f(p2) --> Z^0(-->e^-(p3)+e^+(p4)) + Z^0(-->e^-(p5)+e^+(p6))' 'L'
vsymfact_.vsymfact=0.5;
interference_.interference=true;
}
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::MCFM_chooser: Setup is (production, process)=(" << TVar::ProductionName(production) << ", " << TVar::ProcessName(process) << ")" << endl;
}
else if (
ndau>=4
&&
((production == TVar::ZZINDEPENDENT || production == TVar::ZZQQB) && process == TVar::bkgWW)
){
// Processes 61 (4l), 62 (2l2q), 64 (2q2l)
nqcdjets_.nqcdjets=0;
nwz_.nwz=1; ckmfill_(&(nwz_.nwz));
bveg1_mcfm_.ndim=10;
breit_.n2=1;
breit_.n3=1;
breit_.mass2=masses_mcfm_.wmass;
breit_.width2=masses_mcfm_.wwidth;
breit_.mass3=masses_mcfm_.wmass;
breit_.width3=masses_mcfm_.wwidth;
srdiags_.srdiags=true;
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::MCFM_chooser: Setup is (production, process)=(" << TVar::ProductionName(production) << ", " << TVar::ProcessName(process) << ")" << endl;
}
else if (
(ndau>=4 || ndau==2)
&&
production == TVar::JJQCD
&&
process == TVar::bkgZJets
){
// -- 44 ' f(p1)+f(p2) --> Z^0(-->e^-(p3)+e^+(p4))+f(p5)+f(p6)'
// these settings are identical to use the chooser_() function
flags_.Gflag=true;
flags_.Qflag=true;
flags_.QandGflag=true; // This is in case NLO is implemented.
bveg1_mcfm_.ndim=10;
breit_.n2=0;
breit_.n3=1;
nqcdjets_.nqcdjets=2;
nwz_.nwz=0; ckmfill_(&(nwz_.nwz));
breit_.mass3=masses_mcfm_.zmass;
breit_.width3=masses_mcfm_.zwidth;
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::MCFM_chooser: Setup is (production, process)=(" << TVar::ProductionName(production) << ", " << TVar::ProcessName(process) << ")" << endl;
}
else if (
ndau==3
&&
(production == TVar::ZZQQB || production == TVar::ZZINDEPENDENT)
&&
process == TVar::bkgZGamma
){
// -- 300 ' f(p1)+f(p2) --> Z^0(-->e^-(p3)+e^+(p4))+gamma(p5)'
// -- 305 ' f(p1)+f(p2) --> Z^0(-->3*(nu(p3)+nu~(p4)))-(sum over 3 nu)+gamma(p5)'
nqcdjets_.nqcdjets=0;
bveg1_mcfm_.ndim=7;
breit_.n2=0;
breit_.n3=1;
breit_.mass3=masses_mcfm_.zmass;
breit_.width3=masses_mcfm_.zwidth;
//lastphot_.lastphot=5; // Done during particle label assignment
nwz_.nwz=0; ckmfill_(&(nwz_.nwz));
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::MCFM_chooser: Setup is (production, process)=(" << TVar::ProductionName(production) << ", " << TVar::ProcessName(process) << ")" << endl;
}
else if (
isGG
&&
(production == TVar::ZZQQB || production == TVar::ZZINDEPENDENT || production == TVar::ZZGG)
&&
process == TVar::bkgGammaGamma
){
// -- 285 ' f(p1)+f(p2) --> gamma(p3)+gamma(p4)'
nqcdjets_.nqcdjets=0;
bveg1_mcfm_.ndim=4;
breit_.n3=0;
lastphot_.lastphot=4;
nwz_.nwz=0; ckmfill_(&(nwz_.nwz));
if (production == TVar::ZZQQB || production == TVar::ZZINDEPENDENT) noglue_.omitgg=true;
else noglue_.omitgg=false;
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::MCFM_chooser: Setup is (production, process)=(" << TVar::ProductionName(production) << ", " << TVar::ProcessName(process) << ")" << endl;
}
else if (
ndau>=4
&&
production == TVar::ZZGG
&&
(isZZ && (process == TVar::bkgZZ || process == TVar::HSMHiggs || process == TVar::bkgZZ_SMHiggs))
){
/*
nprocs:
c--- 128 ' f(p1)+f(p2) --> H(--> Z^0(e^-(p3)+e^+(p4)) + Z^0(mu^-(p5)+mu^+(p6)) [top, bottom loops, exact]' 'L'
c--- 129 ' f(p1)+f(p2) --> H(--> Z^0(e^-(p3)+e^+(p4)) + Z^0(mu^-(p5)+mu^+(p6)) [only H, gg->ZZ intf.]' 'L' -> NOT IMPLEMENTED
c--- 130 ' f(p1)+f(p2) --> H(--> Z^0(e^-(p3)+e^+(p4)) + Z^0(mu^-(p5)+mu^+(p6)) [H squared and H, gg->ZZ intf.]' 'L'
c--- 131 ' f(p1)+f(p2) --> Z^0(e^-(p3)+e^+(p4)) + Z^0(mu^-(p5)+mu^+(p6) [gg only, (H + gg->ZZ) squared]' 'L'
c--- 132 ' f(p1)+f(p2) --> Z^0(e^-(p3)+e^+(p4)) + Z^0(mu^-(p5)+mu^+(p6) [(gg->ZZ) squared]' 'L'
*/
nqcdjets_.nqcdjets=0;
nwz_.nwz=0; ckmfill_(&(nwz_.nwz));
bveg1_mcfm_.ndim=10;
breit_.n2=1;
breit_.n3=1;
breit_.mass2 =masses_mcfm_.zmass;
breit_.width2=masses_mcfm_.zwidth;
breit_.mass3 =masses_mcfm_.zmass;
breit_.width3=masses_mcfm_.zwidth;
vsymfact_.vsymfact=1.0;
interference_.interference=false;
if (hasZZ4fInterf && (leptonInterf==TVar::DefaultLeptonInterf || leptonInterf==TVar::InterfOn)){
vsymfact_.vsymfact=0.5;
interference_.interference=true;
}
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::MCFM_chooser: Setup is (production, process)=(" << TVar::ProductionName(production) << ", " << TVar::ProcessName(process) << ")" << endl;
}
else if (
ndau>=4
&&
production == TVar::ZZGG
&&
(
(
(isWW && (process == TVar::bkgWW || process == TVar::HSMHiggs || process == TVar::bkgWW_SMHiggs))
)
||
(
((isWW || isZZ) && (process == TVar::bkgWWZZ || process == TVar::HSMHiggs_WWZZ || process == TVar::bkgWWZZ_SMHiggs))
)
)
){ // gg->VV
// Processes 1281, 1311, 1321
nwz_.nwz=0; ckmfill_(&(nwz_.nwz));
nqcdjets_.nqcdjets=0;
bveg1_mcfm_.ndim=10;
breit_.n2=1;
breit_.n3=1;
nuflav_.nuflav=1; // Keep this at 1. Mela controls how many flavors in a more exact way.
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::MCFM_chooser: Setup is (production, process)=(" << TVar::ProductionName(production) << ", " << TVar::ProcessName(process) << ")" << endl;
}
// JJ + ZZ->4f
else if ( // Check for support in qq'H+2J
ndau>=4
&&
(
production == TVar::Had_WH || production == TVar::Had_ZH
|| production == TVar::Had_WH_S || production == TVar::Had_ZH_S
|| production == TVar::Had_WH_TU || production == TVar::Had_ZH_TU
|| production == TVar::Lep_WH || production == TVar::Lep_ZH
|| production == TVar::Lep_WH_S || production == TVar::Lep_ZH_S
|| production == TVar::Lep_WH_TU || production == TVar::Lep_ZH_TU
|| production == TVar::JJVBF || production == TVar::JJEW
|| production == TVar::JJVBF_S || production == TVar::JJEW_S
|| production == TVar::JJVBF_TU || production == TVar::JJEW_TU
)
&&
(isZZ && (process == TVar::bkgZZ || process == TVar::HSMHiggs || process == TVar::bkgZZ_SMHiggs))
){
// 220 ' f(p1)+f(p2) --> Z(e-(p3),e^+(p4))Z(mu-(p5),mu+(p6)))+f(p7)+f(p8) [weak]' 'L'
if (process == TVar::bkgZZ) sprintf(runstring_.runstring, "wbfBO");
else if (process == TVar::HSMHiggs) sprintf(runstring_.runstring, "wbfHO");
npart_.npart=6;
nwz_.nwz=2; ckmfill_(&(nwz_.nwz));
bveg1_mcfm_.ndim=16;
nqcdjets_.nqcdjets=2;
breit_.n2=1;
breit_.n3=1;
breit_.mass2 =masses_mcfm_.zmass;
breit_.width2=masses_mcfm_.zwidth;
breit_.mass3 =masses_mcfm_.zmass;
breit_.width3=masses_mcfm_.zwidth;
vsymfact_.vsymfact=1.0;
interference_.interference=false;
if (hasZZ4fInterf && (leptonInterf==TVar::DefaultLeptonInterf || leptonInterf==TVar::InterfOn)){
vsymfact_.vsymfact=0.5;
interference_.interference=true;
}
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::MCFM_chooser: Setup is (production, process)=(" << TVar::ProductionName(production) << ", " << TVar::ProcessName(process) << ")" << endl;
}
// JJ + WW->4f
else if ( // Check for support in qq'H+2J
ndau>=4
&&
(
production == TVar::Had_WH || production == TVar::Had_ZH
|| production == TVar::Had_WH_S || production == TVar::Had_ZH_S
|| production == TVar::Had_WH_TU || production == TVar::Had_ZH_TU
|| production == TVar::Lep_WH || production == TVar::Lep_ZH
|| production == TVar::Lep_WH_S || production == TVar::Lep_ZH_S
|| production == TVar::Lep_WH_TU || production == TVar::Lep_ZH_TU
|| production == TVar::JJVBF || production == TVar::JJEW
|| production == TVar::JJVBF_S || production == TVar::JJEW_S
|| production == TVar::JJVBF_TU || production == TVar::JJEW_TU
)
&&
(isWW && (process == TVar::bkgWW || process == TVar::HSMHiggs || process == TVar::bkgWW_SMHiggs))
){
// Process 224
if (process == TVar::bkgWW) sprintf(runstring_.runstring, "wbfBO");
else if (process == TVar::HSMHiggs) sprintf(runstring_.runstring, "wbfHO");
npart_.npart=6;
nwz_.nwz=2; ckmfill_(&(nwz_.nwz));
bveg1_mcfm_.ndim=16;
nqcdjets_.nqcdjets=2;
breit_.n2=1;
breit_.n3=1;
breit_.mass2 =masses_mcfm_.wmass;
breit_.width2=masses_mcfm_.wwidth;
breit_.mass3 =masses_mcfm_.wmass;
breit_.width3=masses_mcfm_.wwidth;
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::MCFM_chooser: Setup is (production, process)=(" << TVar::ProductionName(production) << ", " << TVar::ProcessName(process) << ")" << endl;
}
// JJ + VV->4f
else if ( // Check for support in qq'H+2J
ndau>=4
&&
(
production == TVar::Had_WH || production == TVar::Had_ZH
|| production == TVar::Had_WH_S || production == TVar::Had_ZH_S
|| production == TVar::Had_WH_TU || production == TVar::Had_ZH_TU
|| production == TVar::Lep_WH || production == TVar::Lep_ZH
|| production == TVar::Lep_WH_S || production == TVar::Lep_ZH_S
|| production == TVar::Lep_WH_TU || production == TVar::Lep_ZH_TU
|| production == TVar::JJVBF || production == TVar::JJEW
|| production == TVar::JJVBF_S || production == TVar::JJEW_S
|| production == TVar::JJVBF_TU || production == TVar::JJEW_TU
)
&&
((isZZ || isWW) && (process == TVar::bkgWWZZ || process == TVar::HSMHiggs_WWZZ || process == TVar::bkgWWZZ_SMHiggs))
){
// Procsss 226
if (process == TVar::bkgWWZZ) sprintf(runstring_.runstring, "wbfBO");
else if (process == TVar::HSMHiggs_WWZZ) sprintf(runstring_.runstring, "wbfHO");
npart_.npart=6;
nwz_.nwz=2; ckmfill_(&(nwz_.nwz));
bveg1_mcfm_.ndim=16;
nqcdjets_.nqcdjets=2;
breit_.n2=1;
breit_.n3=1;
breit_.mass2 =masses_mcfm_.wmass;
breit_.width2=masses_mcfm_.wwidth;
breit_.mass3 =masses_mcfm_.wmass;
breit_.width3=masses_mcfm_.wwidth;
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::MCFM_chooser: Setup is (production, process)=(" << TVar::ProductionName(production) << ", " << TVar::ProcessName(process) << ")" << endl;
}
// JJ + ZZ->4f (QCD)
else if (
ndau>=4
&&
(
production == TVar::JJQCD/* || production == TVar::JJQCD_S || production == TVar::JJQCD_TU*/
|| production == TVar::JJEWQCD || production == TVar::JJEWQCD_S || production == TVar::JJEWQCD_TU
)
&&
(isZZ && process == TVar::bkgZZ) // ME is bkg-only
){
// 2201 ' f(p1)+f(p2) --> Z(e-(p3),e^+(p4))Z(mu-(p5),mu+(p6)))+f(p7)+f(p8) [strong]' 'L'
/*
NOTE TO DEVELOPER
MCFM also sets common/VVstrong/VVstrong (logical) here, but it only controls which ww_ZZqq function is called.
It is irrelevant as long as eventgeneration through lowint is not used directly through MELA.
*/
npart_.npart=6;
nwz_.nwz=2; ckmfill_(&(nwz_.nwz));
bveg1_mcfm_.ndim=16;
nqcdjets_.nqcdjets=2;
breit_.n2=1;
breit_.n3=1;
breit_.mass2 =masses_mcfm_.zmass;
breit_.width2=masses_mcfm_.zwidth;
breit_.mass3 =masses_mcfm_.zmass;
breit_.width3=masses_mcfm_.zwidth;
vsymfact_.vsymfact=1.0;
interference_.interference=false;
if (hasZZ4fInterf && (leptonInterf==TVar::DefaultLeptonInterf || leptonInterf==TVar::InterfOn)){
vsymfact_.vsymfact=0.5;
interference_.interference=true;
}
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::MCFM_chooser: Setup is (production, process)=(" << TVar::ProductionName(production) << ", " << TVar::ProcessName(process) << ")" << endl;
}
// JJ + WW->4f (QCD)
else if (
ndau>=4
&&
(
production == TVar::JJQCD/* || production == TVar::JJQCD_S || production == TVar::JJQCD_TU*/
|| production == TVar::JJEWQCD || production == TVar::JJEWQCD_S || production == TVar::JJEWQCD_TU
)
&&
(isWW && process == TVar::bkgWW) // ME is bkg-only
){
// Process 2241
/*
NOTE TO DEVELOPER
MCFM also sets common/VVstrong/VVstrong (logical) here, but it only controls which ww_ZZqq function is called.
It is irrelevant as long as eventgeneration through lowint is not used directly through MELA.
*/
npart_.npart=6;
nwz_.nwz=2; ckmfill_(&(nwz_.nwz));
bveg1_mcfm_.ndim=16;
nqcdjets_.nqcdjets=2;
breit_.n2=1;
breit_.n3=1;
breit_.mass2 =masses_mcfm_.wmass;
breit_.width2=masses_mcfm_.wwidth;
breit_.mass3 =masses_mcfm_.wmass;
breit_.width3=masses_mcfm_.wwidth;
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::MCFM_chooser: Setup is (production, process)=(" << TVar::ProductionName(production) << ", " << TVar::ProcessName(process) << ")" << endl;
}
// JJ + VV->4f (QCD)
else if (
ndau>=4
&&
(
production == TVar::JJQCD/* || production == TVar::JJQCD_S || production == TVar::JJQCD_TU*/
|| production == TVar::JJEWQCD || production == TVar::JJEWQCD_S || production == TVar::JJEWQCD_TU
)
&&
((isZZ || isWW) && process == TVar::bkgWWZZ)
){
// Procsss 2261 (not supported yet)
MELAerr << "TUtil::MCFM_chooser: MCFM does not support QCD JJ+VV->4f interaction yet. Please contact the MELA authors if you need more information." << endl;
result = false;
}
else{
MELAerr << "TUtil::MCFM_chooser: Can't identify (process, production) = (" << process << ", " << production << ")" << endl;
MELAerr << "TUtil::MCFM_chooser: ndau: " << ndau << '\t';
MELAerr << "TUtil::MCFM_chooser: isZZ: " << isZZ << '\t';
MELAerr << "TUtil::MCFM_chooser: isWW: " << isWW << '\t';
MELAerr << "TUtil::MCFM_chooser: isGG: " << isGG << '\t';
MELAerr << endl;
result = false;
}
delete[] pId;
return result;
}
bool TUtil::MCFM_SetupParticleCouplings(
const TVar::Process& process, const TVar::Production& production,
const TVar::VerbosityLevel& verbosity,
const simple_event_record& mela_event,
std::vector<int>* partOrder, std::vector<int>* apartOrder
){
bool result=true;
// Initialize Z couplings
zcouple_.q1=0;
zcouple_.l1=0;
zcouple_.r1=0;
zcouple_.q2=0;
zcouple_.l2=0;
zcouple_.r2=0;
// Initialize plabels
TString strplabel[mxpart];
for (int ip=0; ip<mxpart; ip++) strplabel[ip]=" ";
// Channel checks
unsigned int ndau = mela_event.pDaughters.size();
if (ndau<1) return false;
unsigned int napart = mela_event.pAssociated.size();
bool isWW = (ndau>=4 && PDGHelpers::isAWBoson(mela_event.intermediateVid.at(0)) && PDGHelpers::isAWBoson(mela_event.intermediateVid.at(1)));
bool isZZ = (ndau>=4 && PDGHelpers::isAZBoson(mela_event.intermediateVid.at(0)) && PDGHelpers::isAZBoson(mela_event.intermediateVid.at(1)));
//bool hasZZ4fInterf = isZZ && abs(pId[0])==abs(pId[2]) && abs(pId[1])==abs(pId[3]) && !PDGHelpers::isAnUnknownJet(pId[0]) && !PDGHelpers::isAnUnknownJet(pId[3]);
bool isZJJ = false;
if (ndau>=4) isZJJ = PDGHelpers::isAZBoson(mela_event.intermediateVid.at(0)); // No check on whether daughters 2 and 3 are jets. Notice both isZZ and isZJJ could be true
else if (ndau==2 && process == TVar::bkgZJets){ // Check whether the two daughters can create a Z
isZJJ = (
PDGHelpers::isAZBoson(PDGHelpers::getCoupledVertex(mela_event.intermediateVid.at(0), mela_event.intermediateVid.at(1)))
||
((PDGHelpers::isAnUnknownJet(mela_event.intermediateVid.at(0)) || PDGHelpers::isAQuark(mela_event.intermediateVid.at(0))) && (PDGHelpers::isAnUnknownJet(mela_event.intermediateVid.at(1)) || PDGHelpers::isAQuark(mela_event.intermediateVid.at(1))))
);
}
bool isZG = (ndau>=3 && PDGHelpers::isAZBoson(mela_event.intermediateVid.at(0)) && PDGHelpers::isAPhoton(mela_event.intermediateVid.at(1)));
bool isGG = (ndau>=2 && PDGHelpers::isAPhoton(mela_event.intermediateVid.at(0)) && PDGHelpers::isAPhoton(mela_event.intermediateVid.at(1)));
bool hasZ1 = (isZZ || isZG || isZJJ);
bool hasZ2 = isZZ;
bool hasW1 = isWW;
bool hasW2 = isWW;
if (verbosity>=TVar::DEBUG){
MELAout << "TUtil::MCFM_SetupParticleCouplings(" << TVar::ProductionName(production) << ", " << TVar::ProcessName(process) << "):\nInitial configuration ";
vector<TString> strcfgs;
if (isGG) strcfgs.push_back(TString("GG"));
if (isZG) strcfgs.push_back(TString("ZG"));
if (isZZ) strcfgs.push_back(TString("ZZ"));
if (isZJJ) strcfgs.push_back(TString("ZJJ"));
if (isWW) strcfgs.push_back(TString("WW"));
if (!strcfgs.empty()){
MELAout << "is ";
for (unsigned int istr=0; istr<strcfgs.size(); istr++){
if (istr==0) MELAout << strcfgs.at(istr);
else MELAout << ", " << strcfgs.at(istr);
}
MELAout << ".";
}
else MELAout << "has no valid decay!";
MELAout << endl;
}
// Setup the ordering arrays
int* pApartOrder = 0;
int* pApartId = 0;
if (napart>0){
pApartOrder = new int[napart];
pApartId = new int[napart];
for (unsigned int ip=0; ip<napart; ip++){
pApartOrder[ip]=ip; // This order USUALLY does not change!
pApartId[ip]=mela_event.pAssociated.at(ip).first; // This order does not change.
}
}
int* pOrder = new int[ndau];
int* pZOrder = new int[ndau];
int* pWOrder = new int[ndau];
int* pId = new int[ndau];
for (unsigned int ip=0; ip<ndau; ip++){
pOrder[ip]=ip; // This order does not change
pZOrder[ip]=ip;
pWOrder[ip]=ip;
pId[ip]=mela_event.pDaughters.at(ip).first; // This order does not change.
}
// Special case checks
bool useQQBZGAM = (isZG && process == TVar::bkgZGamma && (production == TVar::ZZQQB || production == TVar::ZZINDEPENDENT));
bool useQQVVQQ =
(
((isZZ && (process == TVar::bkgZZ || process == TVar::HSMHiggs || process == TVar::bkgZZ_SMHiggs))
|| (isWW && (process == TVar::bkgWW || process == TVar::HSMHiggs || process == TVar::bkgWW_SMHiggs))
|| ((isZZ || isWW) && (process == TVar::bkgWWZZ || process == TVar::HSMHiggs_WWZZ || process == TVar::bkgWWZZ_SMHiggs)))
&&
(production == TVar::Had_WH || production == TVar::Had_ZH
|| production == TVar::Had_WH_S || production == TVar::Had_ZH_S
|| production == TVar::Had_WH_TU || production == TVar::Had_ZH_TU
|| production == TVar::Lep_WH || production == TVar::Lep_ZH
|| production == TVar::Lep_WH_S || production == TVar::Lep_ZH_S
|| production == TVar::Lep_WH_TU || production == TVar::Lep_ZH_TU
|| production == TVar::JJVBF || production == TVar::JJEW
|| production == TVar::JJVBF_S || production == TVar::JJEW_S
|| production == TVar::JJVBF_TU || production == TVar::JJEW_TU)
);
bool useQQVVQQstrong =
(
((isZZ && process == TVar::bkgZZ) || (isWW && process == TVar::bkgWW) || ((isZZ || isWW) && process == TVar::bkgWWZZ))
&&
(production == TVar::JJQCD || production == TVar::JJQCD_S || production == TVar::JJQCD_TU)
);
bool useQQVVQQboth =
(
((isZZ && process == TVar::bkgZZ) || (isWW && process == TVar::bkgWW) || ((isZZ || isWW) && process == TVar::bkgWWZZ))
&&
(production == TVar::JJEWQCD || production == TVar::JJEWQCD_S || production == TVar::JJEWQCD_TU)
);
bool useQQVVQQany = useQQVVQQ || useQQVVQQstrong || useQQVVQQboth;
/**************************/
/* Begin the setup checks */
/**************************/
// Check first if the decay mode is valid and the number of associated particles is consistent with the requested number
if (
!(isWW || isZZ || isZJJ || isZG || isGG) // Only ZZ, WW, ZG or GG supported in MCFM
||
((int)napart<(mela_event.nRequested_AssociatedJets+mela_event.nRequested_AssociatedLeptons)) // Associated particle not found
) result=false;
else{
if (isWW && !hasZ1 && !hasZ2){
// Default swap is 3-5
// For ggVV amplitudes, MCFM generates W+W- and does 3-5 swap inside the ME, so by definition, this is ok.
// For VBFWW amplitudes, MCFM generates W-W+ in the phase space and does a 4-6 swap before passing to the ME. The ordering here is W+W-, so this is equivalent to doing a 3-5 swap to get the corresponding ZZ-like combinations.
swap(pZOrder[0], pZOrder[2]);
int V1id, V2id;
if (!PDGHelpers::isAnUnknownJet(pId[pZOrder[0]]) && !PDGHelpers::isAnUnknownJet(pId[pZOrder[1]])) V1id = PDGHelpers::getCoupledVertex(pId[pZOrder[0]], pId[pZOrder[1]]);
else V1id = 23;
if (!PDGHelpers::isAnUnknownJet(pId[pZOrder[2]]) && !PDGHelpers::isAnUnknownJet(pId[pZOrder[3]])) V2id = PDGHelpers::getCoupledVertex(pId[pZOrder[2]], pId[pZOrder[3]]);
else V2id = 23;
hasZ1=hasZ1 || PDGHelpers::isAZBoson(V1id);
hasZ2=hasZ2 || PDGHelpers::isAZBoson(V2id);
if (!hasZ1 && hasZ2){
swap(pZOrder[0], pZOrder[2]);
swap(pZOrder[1], pZOrder[3]);
swap(hasZ1, hasZ2);
}
if (verbosity>=TVar::DEBUG){
if (hasZ1) MELAout << "TUtil::MCFM_SetupParticleCouplings: Found a Z1";
if (hasZ2) MELAout << " and a Z2";
if (hasZ1 || hasZ2) MELAout << " in WW." << endl;
}
}
if (isZZ && !hasW1 && !hasW2){
swap(pWOrder[0], pWOrder[2]);
int V1id, V2id;
if (!PDGHelpers::isAnUnknownJet(pId[pWOrder[0]]) && !PDGHelpers::isAnUnknownJet(pId[pWOrder[1]])) V1id = PDGHelpers::getCoupledVertex(pId[pWOrder[0]], pId[pWOrder[1]]);
else V1id = 24;
if (!PDGHelpers::isAnUnknownJet(pId[pWOrder[2]]) && !PDGHelpers::isAnUnknownJet(pId[pWOrder[3]])) V2id = PDGHelpers::getCoupledVertex(pId[pWOrder[2]], pId[pWOrder[3]]);
else V2id = -24;
if (PDGHelpers::isAWBoson(V1id) && PDGHelpers::isAWBoson(V2id)){
if (V1id<0 || V2id>0){
swap(pWOrder[0], pWOrder[2]);
swap(pWOrder[1], pWOrder[3]);
}
hasW1=true;
hasW2=true;
}
if (verbosity>=TVar::DEBUG){
if (hasW1) MELAout << "TUtil::MCFM_SetupParticleCouplings: Found a W1(" << V1id << ")";
if (hasW2) MELAout << " and a W2(" << V2id << ")";
if (hasW1 || hasW2) MELAout << " in ZZ." << endl;
}
}
/*******************/
/* Particle labels */
/*******************/
// Mother particles
// Default labels for most processes
strplabel[0]="pp";
strplabel[1]="pp";
if (useQQVVQQany){ // Special case if using qqZZ/VVqq*
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::MCFM_SetupParticleCouplings: Setting up mother labels for MCFM:";
for (int ip=0; ip<min(2, (int)mela_event.pMothers.size()); ip++){
const int& idmot = mela_event.pMothers.at(ip).first;
if (!PDGHelpers::isAnUnknownJet(idmot)) strplabel[ip]=TUtil::GetMCFMParticleLabel(idmot, false, useQQVVQQany);
if (verbosity>=TVar::DEBUG) MELAout << " " << idmot << "=" << strplabel[ip];
// No need to check unknown parton case, already "pp"
}
if (verbosity>=TVar::DEBUG) MELAout << endl;
}
// Decay and associated particles
// 0-jet processes, set only decay labels (and plabel[5/6]=pp due to NLO stuff)
if (isZJJ && production == TVar::JJQCD && process == TVar::bkgZJets){
strplabel[2]="el";
strplabel[3]="ea";
strplabel[4]="pp";
strplabel[5]="pp";
strplabel[6]="pp";
}
else if (production == TVar::ZZGG && (
(isWW && (process == TVar::bkgWW || process == TVar::HSMHiggs || process == TVar::bkgWW_SMHiggs))
||
((isWW || isZZ) && (process == TVar::bkgWWZZ || process == TVar::HSMHiggs_WWZZ || process == TVar::bkgWWZZ_SMHiggs))
)
){
strplabel[2]="el";
strplabel[3]="ea";
strplabel[4]="nl";
strplabel[5]="na";
strplabel[6]="pp";
string strrun = runstring_.runstring;
if (isWW && ((!hasZ1 || !hasZ2) || (process == TVar::bkgWW || process == TVar::HSMHiggs || process == TVar::bkgWW_SMHiggs))) strrun += "_ww";
else if (isZZ && (!hasW1 || !hasW2)) strrun += "_zz";
sprintf(runstring_.runstring, strrun.c_str());
}
else if (isZG && (production == TVar::ZZQQB || production == TVar::ZZINDEPENDENT) && process == TVar::bkgZGamma){
lastphot_.lastphot=5;
strplabel[4]="ga";
strplabel[5]="pp";
}
else if (isGG && (production == TVar::ZZGG || production == TVar::ZZQQB || production == TVar::ZZINDEPENDENT) && process == TVar::bkgGammaGamma){
//lastphot_.lastphot=4; // Done in chooser
strplabel[2]="ga";
strplabel[3]="ga";
strplabel[4]="pp";
}
else if (isWW && (production == TVar::ZZINDEPENDENT || production == TVar::ZZQQB) && process == TVar::bkgWW){
strplabel[6]="pp";
zcouple_.l1=1.;
if (PDGHelpers::isANeutrino(pId[pWOrder[0]])){
strplabel[2]="nl";
strplabel[3]="ea";
}
else if (PDGHelpers::isAJet(pId[pWOrder[1]])){
strplabel[2]="qj";
strplabel[3]="qj";
zcouple_.l1 *= sqrt(6.);
nqcdjets_.nqcdjets += 2;
}
else result = false;
if (PDGHelpers::isANeutrino(pId[pWOrder[3]])){
strplabel[4]="el";
strplabel[5]="na";
}
else if (PDGHelpers::isAJet(pId[pWOrder[3]])){
strplabel[4]="qj";
strplabel[5]="qj";
zcouple_.l1 *= sqrt(6.);
nqcdjets_.nqcdjets += 2;
}
else result = false;
if (PDGHelpers::isAJet(pId[pWOrder[0]]) && PDGHelpers::isAJet(pId[pWOrder[3]])) result = false; // MCFM does not support WW->4q
}
// 2-jet processes
// Most of the associated particle labels are set below
// VH productions loop over all possible associated particles to assign V daughters as the first two particles in particle-antiparticle order
else if ((isWW || isZZ) && napart>=2 && (production == TVar::Lep_ZH || production == TVar::Lep_ZH_S || production == TVar::Lep_ZH_TU)){
spinzerohiggs_anomcoupl_.channeltoggle_stu = int(production == TVar::Lep_ZH)*2 + int(production == TVar::Lep_ZH_TU)*1 + int(production == TVar::Lep_ZH_S)*0;
spinzerohiggs_anomcoupl_.vvhvvtoggle_vbfvh = 1;
if (process == TVar::bkgWWZZ || process == TVar::HSMHiggs_WWZZ || process == TVar::bkgWWZZ_SMHiggs){
string strrun = runstring_.runstring;
if (isWW && (!hasZ1 || !hasZ2)) strrun += "_ww";
else if (isZZ && (!hasW1 || !hasW2)) strrun += "_zz";
sprintf(runstring_.runstring, strrun.c_str());
}
bool hasZll=false;
bool hasZnn=false;
for (unsigned int ix=0; ix<napart; ix++){
if (PDGHelpers::isAJet(pApartId[ix])) continue;
for (unsigned int iy=ix+1; iy<napart; iy++){
if (PDGHelpers::isAJet(pApartId[iy])) continue;
int Vid = PDGHelpers::getCoupledVertex(pApartId[ix], pApartId[iy]);
if (PDGHelpers::isAZBoson(Vid) && PDGHelpers::isALepton(pApartId[ix])){
int i1=ix; int i2=iy;
if (pApartId[ix]<0){ swap(i1, i2); }
int* tmpOrder = new int[napart];
tmpOrder[0] = i1; tmpOrder[1] = i2;
unsigned int ctr=2;
for (unsigned int ipart=0; ipart<napart; ipart++){ if (ctr<napart && pApartOrder[ipart]!=i1 && pApartOrder[ipart]!=i2){ tmpOrder[ctr] = pApartOrder[ipart]; ctr++; } }
delete[] pApartOrder; pApartOrder = tmpOrder;
hasZll=true;
break;
}
else if (PDGHelpers::isAZBoson(Vid) && PDGHelpers::isANeutrino(pApartId[ix])){
int i1=ix; int i2=iy;
if (pApartId[ix]<0){ swap(i1, i2); }
int* tmpOrder = new int[napart];
tmpOrder[0] = i1; tmpOrder[1] = i2;
unsigned int ctr=2;
for (unsigned int ipart=0; ipart<napart; ipart++){ if (ctr<napart && pApartOrder[ipart]!=i1 && pApartOrder[ipart]!=i2){ tmpOrder[ctr] = pApartOrder[ipart]; ctr++; } }
delete[] pApartOrder; pApartOrder = tmpOrder;
hasZnn=true;
break;
}
if (hasZll || hasZnn) break;
}
}
unsigned int iout=6;
unsigned int jout=7;
if (useQQVVQQany){
int qqvvqq_apartordering[2]={ -1, -1 };
TMCFMUtils::AssociatedParticleOrdering_QQVVQQAny(
mela_event.pMothers.at(0).first, mela_event.pMothers.at(1).first,
pApartId[pApartOrder[0]], pApartId[pApartOrder[1]],
qqvvqq_apartordering
);
if (qqvvqq_apartordering[0]==-1 || qqvvqq_apartordering[1]==-1) result=false;
else if (qqvvqq_apartordering[0]>qqvvqq_apartordering[1]){
swap(iout, jout);
swap(pApartOrder[0], pApartOrder[1]);
}
}
if (hasZll){
strplabel[iout]="el";
strplabel[jout]="ea";
}
else if (hasZnn){
strplabel[iout]="nl";
strplabel[jout]="na";
}
else result = false;
}
else if ((isWW || isZZ) && napart>=2 && (production == TVar::Lep_WH || production == TVar::Lep_WH_S || production == TVar::Lep_WH_TU)){
spinzerohiggs_anomcoupl_.channeltoggle_stu = int(production == TVar::Lep_WH)*2 + int(production == TVar::Lep_WH_TU)*1 + int(production == TVar::Lep_WH_S)*0;
spinzerohiggs_anomcoupl_.vvhvvtoggle_vbfvh = 1;
if (process == TVar::bkgWWZZ || process == TVar::HSMHiggs_WWZZ || process == TVar::bkgWWZZ_SMHiggs){
string strrun = runstring_.runstring;
if (isWW && (!hasZ1 || !hasZ2)) strrun += "_ww";
else if (isZZ && (!hasW1 || !hasW2)) strrun += "_zz";
sprintf(runstring_.runstring, strrun.c_str());
}
bool hasWplus=false;
bool hasWminus=false;
for (unsigned int ix=0; ix<napart; ix++){
if (PDGHelpers::isAJet(pApartId[ix])) continue;
for (unsigned int iy=ix+1; iy<napart; iy++){
if (PDGHelpers::isAJet(pApartId[iy])) continue;
int Vid = PDGHelpers::getCoupledVertex(pApartId[ix], pApartId[iy]);
if (
PDGHelpers::isAWBoson(Vid)
&&
(
(PDGHelpers::isALepton(pApartId[ix]) && pApartId[ix]<0)
||
(PDGHelpers::isALepton(pApartId[iy]) && pApartId[iy]<0)
)
){
int i1=ix; int i2=iy;
if (pApartId[ix]<0){ swap(i1, i2); }
int* tmpOrder = new int[napart];
tmpOrder[0] = i1; tmpOrder[1] = i2;
unsigned int ctr=2;
for (unsigned int ipart=0; ipart<napart; ipart++){ if (ctr<napart && pApartOrder[ipart]!=i1 && pApartOrder[ipart]!=i2){ tmpOrder[ctr] = pApartOrder[ipart]; ctr++; } }
delete[] pApartOrder; pApartOrder = tmpOrder;
hasWplus=true;
break;
}
else if (
PDGHelpers::isAWBoson(Vid)
&&
(
(PDGHelpers::isALepton(pApartId[ix]) && pApartId[ix]>0)
||
(PDGHelpers::isALepton(pApartId[iy]) && pApartId[iy]>0)
)
){
int i1=ix; int i2=iy;
if (pApartId[ix]<0){ swap(i1, i2); }
int* tmpOrder = new int[napart];
tmpOrder[0] = i1; tmpOrder[1] = i2;
unsigned int ctr=2;
for (unsigned int ipart=0; ipart<napart; ipart++){ if (ctr<napart && pApartOrder[ipart]!=i1 && pApartOrder[ipart]!=i2){ tmpOrder[ctr] = pApartOrder[ipart]; ctr++; } }
delete[] pApartOrder; pApartOrder = tmpOrder;
hasWminus=true;
break;
}
}
if (hasWplus || hasWminus) break;
}
unsigned int iout=6;
unsigned int jout=7;
if (useQQVVQQany){
int qqvvqq_apartordering[2]={ -1, -1 };
TMCFMUtils::AssociatedParticleOrdering_QQVVQQAny(
mela_event.pMothers.at(0).first, mela_event.pMothers.at(1).first,
pApartId[pApartOrder[0]], pApartId[pApartOrder[1]],
qqvvqq_apartordering
);
if (qqvvqq_apartordering[0]==-1 || qqvvqq_apartordering[1]==-1) result=false;
else if (qqvvqq_apartordering[0]>qqvvqq_apartordering[1]){
swap(iout, jout);
swap(pApartOrder[0], pApartOrder[1]);
}
}
if (hasWplus){ // W+
strplabel[iout]="nl";
strplabel[jout]="ea";
}
else if (hasWminus){ // W-
strplabel[iout]="el";
strplabel[jout]="na";
}
else result = false;
}
else if ((isWW || isZZ) && napart>=2 && (production == TVar::Had_ZH || production == TVar::Had_ZH_S || production == TVar::Had_ZH_TU)){
spinzerohiggs_anomcoupl_.channeltoggle_stu = int(production == TVar::Had_ZH)*2 + int(production == TVar::Had_ZH_TU)*1 + int(production == TVar::Had_ZH_S)*0;
spinzerohiggs_anomcoupl_.vvhvvtoggle_vbfvh = 1;
if (process == TVar::bkgWWZZ || process == TVar::HSMHiggs_WWZZ || process == TVar::bkgWWZZ_SMHiggs){
string strrun = runstring_.runstring;
if (isWW && (!hasZ1 || !hasZ2)) strrun += "_ww";
else if (isZZ && (!hasW1 || !hasW2)) strrun += "_zz";
sprintf(runstring_.runstring, strrun.c_str());
}
bool hasZuu=false;
bool hasZdd=false;
bool hasZjj=false;
for (unsigned int ix=0; ix<napart; ix++){
if (!PDGHelpers::isAJet(pApartId[ix])) continue;
for (unsigned int iy=ix+1; iy<napart; iy++){
if (!PDGHelpers::isAJet(pApartId[iy])) continue;
int Vid;
if (!PDGHelpers::isAnUnknownJet(pApartId[ix]) && !PDGHelpers::isAnUnknownJet(pApartId[iy])) Vid = PDGHelpers::getCoupledVertex(pApartId[ix], pApartId[iy]);
else Vid = 23;
if (PDGHelpers::isAZBoson(Vid) && (PDGHelpers::isUpTypeQuark(pApartId[ix]) || PDGHelpers::isUpTypeQuark(pApartId[iy]))){
int i1=ix; int i2=iy;
if (pApartId[ix]<0 || pApartId[iy]>0){ swap(i1, i2); }
int* tmpOrder = new int[napart];
tmpOrder[0] = i1; tmpOrder[1] = i2;
unsigned int ctr=2;
for (unsigned int ipart=0; ipart<napart; ipart++){ if (ctr<napart && pApartOrder[ipart]!=i1 && pApartOrder[ipart]!=i2){ tmpOrder[ctr] = pApartOrder[ipart]; ctr++; } }
delete[] pApartOrder; pApartOrder = tmpOrder;
hasZuu=true;
break;
}
else if (PDGHelpers::isAZBoson(Vid) && (PDGHelpers::isDownTypeQuark(pApartId[ix]) || PDGHelpers::isDownTypeQuark(pApartId[iy]))){
int i1=ix; int i2=iy;
if (pApartId[ix]<0 || pApartId[iy]>0){ swap(i1, i2); }
int* tmpOrder = new int[napart];
tmpOrder[0] = i1; tmpOrder[1] = i2;
unsigned int ctr=2;
for (unsigned int ipart=0; ipart<napart; ipart++){ if (ctr<napart && pApartOrder[ipart]!=i1 && pApartOrder[ipart]!=i2){ tmpOrder[ctr] = pApartOrder[ipart]; ctr++; } }
delete[] pApartOrder; pApartOrder = tmpOrder;
hasZdd=true;
break;
}
else if (PDGHelpers::isAZBoson(Vid)){
int i1=ix; int i2=iy;
int* tmpOrder = new int[napart];
tmpOrder[0] = i1; tmpOrder[1] = i2;
unsigned int ctr=2;
for (unsigned int ipart=0; ipart<napart; ipart++){ if (ctr<napart && pApartOrder[ipart]!=i1 && pApartOrder[ipart]!=i2){ tmpOrder[ctr] = pApartOrder[ipart]; ctr++; } }
delete[] pApartOrder; pApartOrder = tmpOrder;
hasZjj=true;
break;
}
if (hasZuu || hasZdd || hasZjj) break;
}
}
if (useQQVVQQany){
int qqvvqq_apartordering[2]={ -1, -1 };
TMCFMUtils::AssociatedParticleOrdering_QQVVQQAny(
mela_event.pMothers.at(0).first, mela_event.pMothers.at(1).first,
pApartId[pApartOrder[0]], pApartId[pApartOrder[1]],
qqvvqq_apartordering
);
if (qqvvqq_apartordering[0]==-1 || qqvvqq_apartordering[1]==-1) result=false;
else if (qqvvqq_apartordering[0]>qqvvqq_apartordering[1]) swap(pApartOrder[0], pApartOrder[1]);
}
if (hasZuu || hasZdd){
strplabel[6]=TUtil::GetMCFMParticleLabel(pApartId[pApartOrder[0]], true, useQQVVQQany);
strplabel[7]=TUtil::GetMCFMParticleLabel(pApartId[pApartOrder[1]], true, useQQVVQQany);
}
else if (hasZjj){
strplabel[6]="qj";
strplabel[7]="qj";
}
else result = false;
}
else if ((isWW || isZZ) && napart>=2 && (production == TVar::Had_WH || production == TVar::Had_WH_S || production == TVar::Had_WH_TU)){
spinzerohiggs_anomcoupl_.channeltoggle_stu = int(production == TVar::Had_WH)*2 + int(production == TVar::Had_WH_TU)*1 + int(production == TVar::Had_WH_S)*0;
spinzerohiggs_anomcoupl_.vvhvvtoggle_vbfvh = 1;
if (process == TVar::bkgWWZZ || process == TVar::HSMHiggs_WWZZ || process == TVar::bkgWWZZ_SMHiggs){
string strrun = runstring_.runstring;
if (isWW && (!hasZ1 || !hasZ2)) strrun += "_ww";
else if (isZZ && (!hasW1 || !hasW2)) strrun += "_zz";
sprintf(runstring_.runstring, strrun.c_str());
}
bool hasWplus=false;
bool hasWminus=false;
bool hasWjj=false;
for (unsigned int ix=0; ix<napart; ix++){
if (!PDGHelpers::isAJet(pApartId[ix])) continue;
for (unsigned int iy=ix+1; iy<napart; iy++){
if (!PDGHelpers::isAJet(pApartId[iy])) continue;
int Vid;
if (!PDGHelpers::isAnUnknownJet(pApartId[ix]) && !PDGHelpers::isAnUnknownJet(pApartId[iy])) Vid = PDGHelpers::getCoupledVertex(pApartId[ix], pApartId[iy]);
else if (
(PDGHelpers::isUpTypeQuark(pApartId[ix]) && pApartId[ix]<0) || (PDGHelpers::isUpTypeQuark(pApartId[iy]) && pApartId[iy]<0) ||
(PDGHelpers::isDownTypeQuark(pApartId[ix]) && pApartId[ix]>0) || (PDGHelpers::isDownTypeQuark(pApartId[iy]) && pApartId[iy]>0)
) Vid=-24;
else Vid = 24;
if (
PDGHelpers::isAWBoson(Vid)
&&
(
((PDGHelpers::isDownTypeQuark(pApartId[ix]) && pApartId[ix]<0) || (PDGHelpers::isUpTypeQuark(pApartId[iy]) && pApartId[iy]>0))
||
((PDGHelpers::isDownTypeQuark(pApartId[iy]) && pApartId[iy]<0) || (PDGHelpers::isUpTypeQuark(pApartId[ix]) && pApartId[ix]>0))
)
){
int i1=ix; int i2=iy;
if (pApartId[ix]<0 || pApartId[iy]>0){ swap(i1, i2); }
int* tmpOrder = new int[napart];
tmpOrder[0] = i1; tmpOrder[1] = i2;
unsigned int ctr=2;
for (unsigned int ipart=0; ipart<napart; ipart++){ if (ctr<napart && pApartOrder[ipart]!=i1 && pApartOrder[ipart]!=i2){ tmpOrder[ctr] = pApartOrder[ipart]; ctr++; } }
delete[] pApartOrder; pApartOrder = tmpOrder;
hasWplus=true;
break;
}
else if (
PDGHelpers::isAWBoson(Vid)
&&
(
((PDGHelpers::isDownTypeQuark(pApartId[ix]) && pApartId[ix]>0) || (PDGHelpers::isUpTypeQuark(pApartId[iy]) && pApartId[iy]<0))
||
((PDGHelpers::isDownTypeQuark(pApartId[iy]) && pApartId[iy]>0) || (PDGHelpers::isUpTypeQuark(pApartId[ix]) && pApartId[ix]<0))
)
){
int i1=ix; int i2=iy;
if (pApartId[ix]<0 || pApartId[iy]>0){ swap(i1, i2); }
int* tmpOrder = new int[napart];
tmpOrder[0] = i1; tmpOrder[1] = i2;
unsigned int ctr=2;
for (unsigned int ipart=0; ipart<napart; ipart++){ if (ctr<napart && pApartOrder[ipart]!=i1 && pApartOrder[ipart]!=i2){ tmpOrder[ctr] = pApartOrder[ipart]; ctr++; } }
delete[] pApartOrder; pApartOrder = tmpOrder;
hasWminus=true;
break;
}
else if (PDGHelpers::isAWBoson(Vid)){
int i1=ix; int i2=iy;
int* tmpOrder = new int[napart];
tmpOrder[0] = i1; tmpOrder[1] = i2;
unsigned int ctr=2;
for (unsigned int ipart=0; ipart<napart; ipart++){ if (ctr<napart && pApartOrder[ipart]!=i1 && pApartOrder[ipart]!=i2){ tmpOrder[ctr] = pApartOrder[ipart]; ctr++; } }
delete[] pApartOrder; pApartOrder = tmpOrder;
hasWjj=true;
break;
}
}
if (hasWplus || hasWminus || hasWjj) break;
}
if (useQQVVQQany){
int qqvvqq_apartordering[2]={ -1, -1 };
TMCFMUtils::AssociatedParticleOrdering_QQVVQQAny(
mela_event.pMothers.at(0).first, mela_event.pMothers.at(1).first,
pApartId[pApartOrder[0]], pApartId[pApartOrder[1]],
qqvvqq_apartordering
);
if (qqvvqq_apartordering[0]==-1 || qqvvqq_apartordering[1]==-1) result=false;
else if (qqvvqq_apartordering[0]>qqvvqq_apartordering[1]) swap(pApartOrder[0], pApartOrder[1]);
}
if (hasWplus || hasWminus){ // W+ or W-
strplabel[6]=TUtil::GetMCFMParticleLabel(pApartId[pApartOrder[0]], true, useQQVVQQany);
strplabel[7]=TUtil::GetMCFMParticleLabel(pApartId[pApartOrder[1]], true, useQQVVQQany);
}
else if (hasWjj){ // W+/-
strplabel[6]="qj";
strplabel[7]="qj";
}
else result = false;
}
else if ((isWW || isZZ) && napart>=2 && (production == TVar::JJQCD || production == TVar::JJQCD_S || production == TVar::JJQCD_TU)){
spinzerohiggs_anomcoupl_.channeltoggle_stu = int(production == TVar::JJQCD)*2 + int(production == TVar::JJQCD_TU)*1 + int(production == TVar::JJQCD_S)*0;;
spinzerohiggs_anomcoupl_.vvhvvtoggle_vbfvh = 2; // Doesn't matter, already JJQCD
if (process == TVar::bkgWWZZ/* || process == TVar::HSMHiggs_WWZZ || process == TVar::bkgWWZZ_SMHiggs*/){
string strrun = runstring_.runstring;
if (isWW && (!hasZ1 || !hasZ2)) strrun += "_ww";
else if (isZZ && (!hasW1 || !hasW2)) strrun += "_zz";
sprintf(runstring_.runstring, strrun.c_str());
}
if (useQQVVQQany){
int qqvvqq_apartordering[2]={ -1, -1 };
TMCFMUtils::AssociatedParticleOrdering_QQVVQQAny(
mela_event.pMothers.at(0).first, mela_event.pMothers.at(1).first,
pApartId[pApartOrder[0]], pApartId[pApartOrder[1]],
qqvvqq_apartordering
);
if (qqvvqq_apartordering[0]==-1 || qqvvqq_apartordering[1]==-1) result=false;
else if (qqvvqq_apartordering[0]>qqvvqq_apartordering[1]) swap(pApartOrder[0], pApartOrder[1]);
}
strplabel[6]=TUtil::GetMCFMParticleLabel(pApartId[pApartOrder[0]], false, useQQVVQQany);
strplabel[7]=TUtil::GetMCFMParticleLabel(pApartId[pApartOrder[1]], false, useQQVVQQany);
}
else if ((isWW || isZZ) && napart>=2 && (production == TVar::JJVBF || production == TVar::JJVBF_S || production == TVar::JJVBF_TU)){
spinzerohiggs_anomcoupl_.channeltoggle_stu = int(production == TVar::JJVBF)*2 + int(production == TVar::JJVBF_TU)*1 + int(production == TVar::JJVBF_S)*0;;
spinzerohiggs_anomcoupl_.vvhvvtoggle_vbfvh = 0; // VBF-only process
if (process == TVar::bkgWWZZ || process == TVar::HSMHiggs_WWZZ || process == TVar::bkgWWZZ_SMHiggs){
string strrun = runstring_.runstring;
if (isWW && (!hasZ1 || !hasZ2)) strrun += "_ww";
else if (isZZ && (!hasW1 || !hasW2)) strrun += "_zz";
sprintf(runstring_.runstring, strrun.c_str());
}
if (useQQVVQQany){
int qqvvqq_apartordering[2]={ -1, -1 };
TMCFMUtils::AssociatedParticleOrdering_QQVVQQAny(
mela_event.pMothers.at(0).first, mela_event.pMothers.at(1).first,
pApartId[pApartOrder[0]], pApartId[pApartOrder[1]],
qqvvqq_apartordering
);
if (qqvvqq_apartordering[0]==-1 || qqvvqq_apartordering[1]==-1) result=false;
else if (qqvvqq_apartordering[0]>qqvvqq_apartordering[1]) swap(pApartOrder[0], pApartOrder[1]);
}
strplabel[6]=TUtil::GetMCFMParticleLabel(pApartId[pApartOrder[0]], true, useQQVVQQany);
strplabel[7]=TUtil::GetMCFMParticleLabel(pApartId[pApartOrder[1]], true, useQQVVQQany);
}
else if ((isWW || isZZ) && napart>=2 && (production == TVar::JJEW || production == TVar::JJEWQCD || production == TVar::JJEW_S || production == TVar::JJEWQCD_S || production == TVar::JJEW_TU || production == TVar::JJEWQCD_TU)){
spinzerohiggs_anomcoupl_.channeltoggle_stu = int(production == TVar::JJEWQCD || production == TVar::JJEW)*2 + int(production == TVar::JJEWQCD_TU || production == TVar::JJEW_TU)*1 + int(production == TVar::JJEWQCD_S || production == TVar::JJEW_S)*0;;
spinzerohiggs_anomcoupl_.vvhvvtoggle_vbfvh = 2; // VBF+VH process
if (process == TVar::bkgWWZZ || process == TVar::HSMHiggs_WWZZ || process == TVar::bkgWWZZ_SMHiggs){
string strrun = runstring_.runstring;
if (isWW && (!hasZ1 || !hasZ2)) strrun += "_ww";
else if (isZZ && (!hasW1 || !hasW2)) strrun += "_zz";
sprintf(runstring_.runstring, strrun.c_str());
}
if (useQQVVQQany){
int qqvvqq_apartordering[2]={ -1, -1 };
TMCFMUtils::AssociatedParticleOrdering_QQVVQQAny(
mela_event.pMothers.at(0).first, mela_event.pMothers.at(1).first,
pApartId[pApartOrder[0]], pApartId[pApartOrder[1]],
qqvvqq_apartordering
);
if (qqvvqq_apartordering[0]==-1 || qqvvqq_apartordering[1]==-1) result=false;
else if (qqvvqq_apartordering[0]>qqvvqq_apartordering[1]) swap(pApartOrder[0], pApartOrder[1]);
}
strplabel[6]=TUtil::GetMCFMParticleLabel(pApartId[pApartOrder[0]], false, useQQVVQQany);
strplabel[7]=TUtil::GetMCFMParticleLabel(pApartId[pApartOrder[1]], false, useQQVVQQany);
}
// Couplings for Z1
if (isWW && (production == TVar::ZZINDEPENDENT || production == TVar::ZZQQB) && process == TVar::bkgWW){} // Skip this one, already handled above
else if (hasZ1){
if (PDGHelpers::isALepton(pId[pZOrder[0]]) && PDGHelpers::isALepton(pId[pZOrder[1]])){
if (verbosity>=TVar::DEBUG) MELAout << "- Setting Z1->ll couplings." << endl;
zcouple_.q1=-1.0;
zcouple_.l1=zcouple_.le;
zcouple_.r1=zcouple_.re;
// Special Z1->ll cases
if (useQQBZGAM){
strplabel[2]="el";
strplabel[3]="ea";
}
else if (useQQVVQQany){
strplabel[2]=TUtil::GetMCFMParticleLabel(pId[pZOrder[0]], false, useQQVVQQany);
strplabel[3]=TUtil::GetMCFMParticleLabel(pId[pZOrder[1]], false, useQQVVQQany);
}
// End special Z1->ll cases
}
else if (PDGHelpers::isANeutrino(pId[pZOrder[0]]) && PDGHelpers::isANeutrino(pId[pZOrder[1]])){
if (verbosity>=TVar::DEBUG) MELAout << "- Setting Z1->nn couplings." << endl;
zcouple_.q1=0;
zcouple_.l1=zcouple_.ln;
zcouple_.r1=zcouple_.rn;
// Special Z1->nn cases
if (useQQBZGAM){
strplabel[2]="nl";
strplabel[3]="na";
}
else if (useQQVVQQany){
strplabel[2]=TUtil::GetMCFMParticleLabel(pId[pZOrder[0]], false, useQQVVQQany);
strplabel[3]=TUtil::GetMCFMParticleLabel(pId[pZOrder[1]], false, useQQVVQQany);
}
// End special Z1->nn cases
}
else if (PDGHelpers::isAJet(pId[pZOrder[0]]) && PDGHelpers::isAJet(pId[pZOrder[1]])){
if (verbosity>=TVar::DEBUG) MELAout << "- Setting Z1->jj couplings." << endl;
nqcdjets_.nqcdjets += 2;
int jetid=(PDGHelpers::isAnUnknownJet(pId[pZOrder[0]]) ? abs(pId[pZOrder[1]]) : abs(pId[pZOrder[0]]));
if (!PDGHelpers::isAnUnknownJet(jetid)){
if (jetid==6) jetid = 2;
zcouple_.q1=ewcharge_.Q[5+jetid];
zcouple_.l1=zcouple_.l[-1+jetid];
zcouple_.r1=zcouple_.r[-1+jetid];
// Special Z1->qq cases
if (useQQBZGAM){
strplabel[2]="el";// Trick MCFM, not implemented properly
strplabel[3]="ea";
}
else if (useQQVVQQany){
strplabel[2]=TUtil::GetMCFMParticleLabel(pId[pZOrder[0]], false, useQQVVQQany);
strplabel[3]=TUtil::GetMCFMParticleLabel(pId[pZOrder[1]], false, useQQVVQQany);
}
}
else{
double gV_up = (zcouple_.l[-1+2]+zcouple_.r[-1+2])/2.;
double gV_dn = (zcouple_.l[-1+1]+zcouple_.r[-1+1])/2.;
double gA_up = (zcouple_.l[-1+2]-zcouple_.r[-1+2])/2.;
double gA_dn = (zcouple_.l[-1+1]-zcouple_.r[-1+1])/2.;
double yy_up = pow(gV_up, 2) + pow(gA_up, 2);
double yy_dn = pow(gV_dn, 2) + pow(gA_dn, 2);
double xx_up = gV_up*gA_up;
double xx_dn = gV_dn*gA_dn;
double yy = (2.*yy_up+3.*yy_dn);
double xx = (2.*xx_up+3.*xx_dn);
double discriminant = pow(yy, 2)-4.*pow(xx, 2);
double gVsq = (yy+sqrt(fabs(discriminant)))/2.;
double gAsq = pow(xx, 2)/gVsq;
double gV=-sqrt(gVsq);
double gA=-sqrt(gAsq);
zcouple_.l1 = (gV+gA);
zcouple_.r1 = (gV-gA);
zcouple_.q1=sqrt(pow(ewcharge_.Q[5+1], 2)*3.+pow(ewcharge_.Q[5+2], 2)*2.);
// Special Z1->qq cases
if (useQQBZGAM){
strplabel[2]="el";// Trick MCFM, not implemented properly
strplabel[3]="ea";
}
else if (useQQVVQQany){
strplabel[2]="qj";
strplabel[3]="qj";
}
}
if (!useQQVVQQany){ // colfac34_56 handles all couplings instead of this simple scaling (Reason: WW final states)
zcouple_.l1 *= sqrt(3.);
zcouple_.r1 *= sqrt(3.);
zcouple_.q1 *= sqrt(3.);
}
} // End Z1 daughter id tests
} // End ZZ/ZG/ZJJ Z1 couplings
else if (useQQVVQQany){
strplabel[2]=TUtil::GetMCFMParticleLabel(pId[pZOrder[0]], false, useQQVVQQany);
strplabel[3]=TUtil::GetMCFMParticleLabel(pId[pZOrder[1]], false, useQQVVQQany);
}
// Couplings for Z2
if (
(isWW && (production == TVar::ZZINDEPENDENT || production == TVar::ZZQQB) && process == TVar::bkgWW) // Skip this one, already handled above
||
(isZJJ && production == TVar::JJQCD && process == TVar::bkgZJets) // No need to handle
){}
else if (hasZ2){
if (PDGHelpers::isALepton(pId[pZOrder[2]]) && PDGHelpers::isALepton(pId[pZOrder[3]])){
if (verbosity>=TVar::DEBUG) MELAout << "- Setting Z2->ll couplings." << endl;
zcouple_.q2=-1.0;
zcouple_.l2=zcouple_.le;
zcouple_.r2=zcouple_.re;
// Special Z2->ll cases
if (useQQVVQQany){
strplabel[4]=TUtil::GetMCFMParticleLabel(pId[pZOrder[2]], false, useQQVVQQany);
strplabel[5]=TUtil::GetMCFMParticleLabel(pId[pZOrder[3]], false, useQQVVQQany);
}
// End special Z2->ll cases
}
else if (PDGHelpers::isANeutrino(pId[pZOrder[2]]) && PDGHelpers::isANeutrino(pId[pZOrder[3]])){
if (verbosity>=TVar::DEBUG) MELAout << "- Setting Z2->nn couplings." << endl;
zcouple_.q2=0;
zcouple_.l2=zcouple_.ln;
zcouple_.r2=zcouple_.rn;
// Special Z2->nn cases
if (useQQVVQQany){
strplabel[4]=TUtil::GetMCFMParticleLabel(pId[pZOrder[2]], false, useQQVVQQany);
strplabel[5]=TUtil::GetMCFMParticleLabel(pId[pZOrder[3]], false, useQQVVQQany);
}
// End special Z2->nn cases
}
else if (PDGHelpers::isAJet(pId[pZOrder[2]]) && PDGHelpers::isAJet(pId[pZOrder[3]])){
if (verbosity>=TVar::DEBUG) MELAout << "- Setting Z2->jj couplings." << endl;
nqcdjets_.nqcdjets += 2;
int jetid=(PDGHelpers::isAnUnknownJet(pId[pZOrder[2]]) ? abs(pId[pZOrder[3]]) : abs(pId[pZOrder[2]]));
if (!PDGHelpers::isAnUnknownJet(jetid)){
if (jetid==6) jetid = 2;
zcouple_.q2=ewcharge_.Q[5+jetid];
zcouple_.l2=zcouple_.l[-1+jetid];
zcouple_.r2=zcouple_.r[-1+jetid];
// Special Z2->qq cases
if (useQQVVQQany){
strplabel[4]=TUtil::GetMCFMParticleLabel(pId[pZOrder[2]], false, useQQVVQQany);
strplabel[5]=TUtil::GetMCFMParticleLabel(pId[pZOrder[3]], false, useQQVVQQany);
}
}
else{
double gV_up = (zcouple_.l[-1+2]+zcouple_.r[-1+2])/2.;
double gV_dn = (zcouple_.l[-1+1]+zcouple_.r[-1+1])/2.;
double gA_up = (zcouple_.l[-1+2]-zcouple_.r[-1+2])/2.;
double gA_dn = (zcouple_.l[-1+1]-zcouple_.r[-1+1])/2.;
double yy_up = pow(gV_up, 2) + pow(gA_up, 2);
double yy_dn = pow(gV_dn, 2) + pow(gA_dn, 2);
double xx_up = gV_up*gA_up;
double xx_dn = gV_dn*gA_dn;
double yy = (2.*yy_up+3.*yy_dn);
double xx = (2.*xx_up+3.*xx_dn);
double discriminant = pow(yy, 2)-4.*pow(xx, 2);
double gVsq = (yy+sqrt(fabs(discriminant)))/2.;
double gAsq = pow(xx, 2)/gVsq;
double gV=-sqrt(gVsq);
double gA=-sqrt(gAsq);
zcouple_.l2 = (gV+gA);
zcouple_.r2 = (gV-gA);
zcouple_.q2=sqrt(pow(ewcharge_.Q[5+1], 2)*3.+pow(ewcharge_.Q[5+2], 2)*2.);
// Special Z2->qq cases
if (useQQVVQQany){
strplabel[4]="qj";
strplabel[5]="qj";
}
}
if (!useQQVVQQany){ // colfac34_56 handles all couplings instead of this simple scaling (Reason: WW Final states)
zcouple_.l2 *= sqrt(3.);
zcouple_.r2 *= sqrt(3.);
zcouple_.q2 *= sqrt(3.);
}
} // End Z2 daughter id tests
} // End ZZ Z2 couplings
else if (useQQVVQQany){
strplabel[4]=TUtil::GetMCFMParticleLabel(pId[pZOrder[2]], false, useQQVVQQany);
strplabel[5]=TUtil::GetMCFMParticleLabel(pId[pZOrder[3]], false, useQQVVQQany);
}
} // End check WW, ZZ, ZG etc.
int* ordering=nullptr;
if (ndau<=2){
if (production == TVar::ZZGG){
if (process == TVar::bkgGammaGamma){ ordering = pOrder; if (!isGG) result = false; }
}
else if (production == TVar::ZZINDEPENDENT || production == TVar::ZZQQB){
if (process == TVar::bkgGammaGamma){ ordering = pZOrder; if (!isGG) result = false; }
else if (process == TVar::bkgZGamma){ ordering = pZOrder; if (!hasZ1 || !isZG) result = false; }
}
else if (production == TVar::JJQCD){
if (process == TVar::bkgZJets){ ordering = pZOrder; if (!hasZ1 || !isZJJ) result = false; }
}
}
else if (ndau<=3){
if (production == TVar::ZZINDEPENDENT || production == TVar::ZZQQB){
if (process == TVar::bkgZGamma){ ordering = pZOrder; if (!hasZ1 || !isZG) result = false; }
}
}
else{
if (
(production == TVar::ZZINDEPENDENT || production == TVar::ZZQQB)
||
((production == TVar::ZZQQB_STU || production == TVar::ZZQQB_S || production == TVar::ZZQQB_TU) && process == TVar::bkgZZ)
){
// Just get the default ordering
if (production == TVar::ZZINDEPENDENT || production == TVar::ZZQQB){
if (process == TVar::bkgZGamma){ ordering = pZOrder; if (!hasZ1) result = false; }
else if (process == TVar::bkgZZ){ ordering = pZOrder; if (!hasZ1 || !hasZ2) result = false; }
else if (process == TVar::bkgWW){ ordering = pWOrder; if (!hasW1 || !hasW2) result = false; }
}
// bkgZZ process with S/T+U/STU separation needs ZZ ordering
else{ ordering = pZOrder; if (!hasZ1 || !hasZ2) result = false; }
}
else if (production == TVar::ZZGG){
// ggZZ/WW/VV
// All of these require ZZ ordering since they use either ZZ ME or VV ME
if (process == TVar::HSMHiggs || process == TVar::bkgZZ_SMHiggs || process == TVar::bkgZZ){
ordering = pZOrder;
if (
!(
(hasZ1 && hasZ2)
||
(process == TVar::HSMHiggs && hasW1 && hasW2)
)
) result = false;
}
else if (process == TVar::HSMHiggs_WWZZ || process == TVar::bkgWWZZ_SMHiggs || process == TVar::bkgWWZZ){
ordering = pZOrder;
if (!hasZ1 || !hasZ2 || !hasW1 || !hasW2) result = false;
}
else if (process == TVar::bkgWW_SMHiggs || process == TVar::bkgWW){
ordering = pZOrder;
if (!hasW1 || !hasW2) result = false;
}
}
else if (
production == TVar::Had_WH || production == TVar::Had_ZH
|| production == TVar::Had_WH_S || production == TVar::Had_ZH_S
|| production == TVar::Had_WH_TU || production == TVar::Had_ZH_TU
|| production == TVar::Lep_WH || production == TVar::Lep_ZH
|| production == TVar::Lep_WH_S || production == TVar::Lep_ZH_S
|| production == TVar::Lep_WH_TU || production == TVar::Lep_ZH_TU
|| production == TVar::JJVBF || production == TVar::JJEW || production == TVar::JJEWQCD
|| production == TVar::JJVBF_S || production == TVar::JJEW_S || production == TVar::JJEWQCD_S
|| production == TVar::JJVBF_TU || production == TVar::JJEW_TU || production == TVar::JJEWQCD_TU
|| production == TVar::JJQCD || production == TVar::JJQCD_S || production == TVar::JJQCD_TU
){
// Z+2 jets
// Just get the default ordering
if (process == TVar::bkgZJets){ ordering = pZOrder; if (!hasZ1 || !isZJJ) result = false; }
// VBF or QCD MCFM SBI, S or B
// All of these require ZZ ordering since they use either ZZ ME or VV ME
else if (process == TVar::HSMHiggs || process == TVar::bkgZZ_SMHiggs || process == TVar::bkgZZ){
ordering = pZOrder;
if (
!(
(hasZ1 && hasZ2)
||
(process == TVar::HSMHiggs && hasW1 && hasW2)
)
) result = false;
}
else if (process == TVar::HSMHiggs_WWZZ || process == TVar::bkgWWZZ_SMHiggs || process == TVar::bkgWWZZ){
ordering = pZOrder;
if (!hasZ1 || !hasZ2 || !hasW1 || !hasW2) result = false;
}
else if (process == TVar::bkgWW_SMHiggs || process == TVar::bkgWW){
ordering = pZOrder;
if (!hasW1 || !hasW2) result = false;
}
}
}
if (partOrder && ordering) { for (unsigned int ip=0; ip<ndau; ip++) partOrder->push_back(ordering[ip]); }
if (apartOrder && pApartOrder) { for (unsigned int ip=0; ip<napart; ip++) apartOrder->push_back(pApartOrder[ip]); }
for (int ip=0; ip<mxpart; ip++) sprintf((plabel_.plabel)[ip], strplabel[ip].Data());
if (verbosity>=TVar::DEBUG){
MELAout << "TUtil::MCFM_SetupParticleCouplings: Summary (result=" << (int)result << "):\n";
MELAout << "\trunstring=" << runstring_.runstring << endl;
if (hasZ1) MELAout << "\tProcess found a Z1." << endl;
if (hasZ2) MELAout << "\tProcess found a Z2." << endl;
if (hasW1) MELAout << "\tProcess found a W1." << endl;
if (hasW2) MELAout << "\tProcess found a W2." << endl;
MELAout << "\t(l1, l2) = (" << zcouple_.l1 << ", " << zcouple_.l2 << ")" << endl;
MELAout << "\t(r1, r2) = (" << zcouple_.r1 << ", " << zcouple_.r2 << ")" << endl;
MELAout << "\t(q1, q2) = (" << zcouple_.q1 << ", " << zcouple_.q2 << ")" << endl;
MELAout << "\tplabels:\n";
for (int ip=0; ip<mxpart; ip++) MELAout << "\t[" << ip << "]=" << (plabel_.plabel)[ip] << endl;
if (partOrder){
if (!partOrder->empty()) MELAout << "\tpartOrder[" << partOrder->size() << "]:\n";
for (unsigned int ip=0; ip<partOrder->size(); ip++) MELAout << "\t[" << ip << "] -> " << partOrder->at(ip) << endl;
}
if (apartOrder){
if (!apartOrder->empty()) MELAout << "\tapartOrder[" << apartOrder->size() << "]:\n";
for (unsigned int ip=0; ip<apartOrder->size(); ip++) MELAout << "\t[" << ip << "] -> " << apartOrder->at(ip) << endl;
}
}
delete[] pId;
delete[] pWOrder;
delete[] pZOrder;
delete[] pOrder;
if (pApartOrder) delete[] pApartOrder;
if (pApartId) delete[] pApartId;
return result;
}
TString TUtil::GetMCFMParticleLabel(const int& pid, bool useQJ, bool useExtendedConventions){
if (PDGHelpers::isAnUnknownJet(pid)){
if (useQJ) return TString("qj");
else return TString("pp");
}
else if (PDGHelpers::isAGluon(pid)) return TString("ig");
else if (pid==1) return TString("dq");
else if (pid==2) return TString("uq");
else if (pid==3) return TString("sq");
else if (pid==4) return TString("cq");
else if (pid==5) return TString("bq");
else if (pid==-1) return TString("da");
else if (pid==-2) return TString("ua");
else if (pid==-3) return TString("sa");
else if (pid==-4) return TString("ca");
else if (pid==-5) return TString("ba");
else if (abs(pid)==6) return TString("qj"); // No tops!
else if (pid==11) return TString("el");
else if (pid==13) return TString("ml");
else if (pid==15) return TString("tl");
else if (pid==-11) return TString("ea");
else if (pid==-13) return TString("ma");
else if (pid==-15) return TString("ta");
else if (std::abs(pid)>=12 && std::abs(pid)<=16){
if (!useExtendedConventions){
if (pid>0) return TString("nl");
else return TString("na");
}
else{
if (pid==12) return TString("ne");
else if (pid==14) return TString("nm");
else if (pid==16) return TString("nt");
else if (pid==-12) return TString("ke");
else if (pid==-14) return TString("km");
else/* if (pid==-16)*/ return TString("kt");
}
}
else return TString(" ");
}
bool TUtil::MCFM_masscuts(double s[][mxpart], const TVar::Process& process){
double minZmassSqr=10*10;
if (
process == TVar::bkgZZ
&&
(s[2][3]<minZmassSqr || s[4][5]<minZmassSqr)
) return true;
return false;
}
bool TUtil::MCFM_smalls(double s[][mxpart], int npart){
// Reject event if any s(i,j) is too small
// cutoff is defined in technical.Dat
if (
npart == 3 &&
(
(-s[5-1][1-1]< cutoff_.cutoff) //gamma p1
|| (-s[5-1][2-1]< cutoff_.cutoff) //gamma p2
|| (-s[4-1][1-1]< cutoff_.cutoff) //e+ p1
|| (-s[4-1][2-1]< cutoff_.cutoff) //e- p2
|| (-s[3-1][1-1]< cutoff_.cutoff) //nu p1
|| (-s[3-1][2-1]< cutoff_.cutoff) //nu p2
|| (+s[5-1][4-1]< cutoff_.cutoff) //gamma e+
|| (+s[5-1][3-1]< cutoff_.cutoff) //gamma nu
|| (+s[4-1][3-1]< cutoff_.cutoff) //e+ nu
)
)
return true;
else if (
npart == 4 &&
(
(-s[5-1][1-1]< cutoff_.cutoff) //e- p1
|| (-s[5-1][2-1]< cutoff_.cutoff) //e- p2
|| (-s[6-1][1-1]< cutoff_.cutoff) //nb p1
|| (-s[6-1][2-1]< cutoff_.cutoff) //nb p2
|| (+s[6-1][5-1]< cutoff_.cutoff) //e- nb
)
)
return true;
return false;
}
void TUtil::InitJHUGenMELA(const char* pathtoPDFSet, int PDFMember, double collider_sqrts){
const double GeV = 1./100.;
collider_sqrts *= GeV; // GeV units in JHUGen
char path_pdf_c[200];
sprintf(path_pdf_c, "%s", pathtoPDFSet);
int pathpdfLength = strlen(path_pdf_c);
__modjhugen_MOD_initfirsttime(path_pdf_c, &pathpdfLength, &PDFMember, &collider_sqrts);
}
void TUtil::SetJHUGenHiggsMassWidth(double MReso, double GaReso){
const double GeV = 1./100.;
MReso *= GeV; // GeV units in JHUGen
GaReso *= GeV; // GeV units in JHUGen
__modjhugenmela_MOD_sethiggsmasswidth(&MReso, &GaReso);
}
void TUtil::SetJHUGenDistinguishWWCouplings(bool doAllow){
int iAllow = (doAllow ? 1 : 0);
__modjhugenmela_MOD_setdistinguishwwcouplingsflag(&iAllow);
}
void TUtil::ResetAmplitudeIncludes(){
__modjhugenmela_MOD_resetamplitudeincludes();
}
void TUtil::SetMCFMSpinZeroCouplings(bool useBSM, SpinZeroCouplings const* Hcouplings, bool forceZZ){
if (!useBSM){
spinzerohiggs_anomcoupl_.AllowAnomalousCouplings = 0;
spinzerohiggs_anomcoupl_.distinguish_HWWcouplings = 0;
/***** REGULAR RESONANCE *****/
//
spinzerohiggs_anomcoupl_.cz_q1sq = 0;
spinzerohiggs_anomcoupl_.Lambda_z11 = 100;
spinzerohiggs_anomcoupl_.Lambda_z21 = 100;
spinzerohiggs_anomcoupl_.Lambda_z31 = 100;
spinzerohiggs_anomcoupl_.Lambda_z41 = 100;
spinzerohiggs_anomcoupl_.cz_q2sq = 0;
spinzerohiggs_anomcoupl_.Lambda_z12 = 100;
spinzerohiggs_anomcoupl_.Lambda_z22 = 100;
spinzerohiggs_anomcoupl_.Lambda_z32 = 100;
spinzerohiggs_anomcoupl_.Lambda_z42 = 100;
spinzerohiggs_anomcoupl_.cz_q12sq = 0;
spinzerohiggs_anomcoupl_.Lambda_z10 = 100;
spinzerohiggs_anomcoupl_.Lambda_z20 = 100;
spinzerohiggs_anomcoupl_.Lambda_z30 = 100;
spinzerohiggs_anomcoupl_.Lambda_z40 = 100;
//
spinzerohiggs_anomcoupl_.cw_q1sq = 0;
spinzerohiggs_anomcoupl_.Lambda_w11 = 100;
spinzerohiggs_anomcoupl_.Lambda_w21 = 100;
spinzerohiggs_anomcoupl_.Lambda_w31 = 100;
spinzerohiggs_anomcoupl_.Lambda_w41 = 100;
spinzerohiggs_anomcoupl_.cw_q2sq = 0;
spinzerohiggs_anomcoupl_.Lambda_w12 = 100;
spinzerohiggs_anomcoupl_.Lambda_w22 = 100;
spinzerohiggs_anomcoupl_.Lambda_w32 = 100;
spinzerohiggs_anomcoupl_.Lambda_w42 = 100;
spinzerohiggs_anomcoupl_.cw_q12sq = 0;
spinzerohiggs_anomcoupl_.Lambda_w10 = 100;
spinzerohiggs_anomcoupl_.Lambda_w20 = 100;
spinzerohiggs_anomcoupl_.Lambda_w30 = 100;
spinzerohiggs_anomcoupl_.Lambda_w40 = 100;
//
// Just in case, not really needed to set to the default value
spinzerohiggs_anomcoupl_.kappa_top[0] = 1; spinzerohiggs_anomcoupl_.kappa_top[1] = 0;
spinzerohiggs_anomcoupl_.kappa_bot[0] = 1; spinzerohiggs_anomcoupl_.kappa_bot[1] = 0;
spinzerohiggs_anomcoupl_.ghz1[0] = 1; spinzerohiggs_anomcoupl_.ghz1[1] = 0;
spinzerohiggs_anomcoupl_.ghw1[0] = 1; spinzerohiggs_anomcoupl_.ghw1[1] = 0;
for (int im=0; im<2; im++){
spinzerohiggs_anomcoupl_.kappa_tilde_top[im] = 0;
spinzerohiggs_anomcoupl_.kappa_tilde_bot[im] = 0;
spinzerohiggs_anomcoupl_.ghg2[im] = 0;
spinzerohiggs_anomcoupl_.ghg3[im] = 0;
spinzerohiggs_anomcoupl_.ghg4[im] = 0;
spinzerohiggs_anomcoupl_.kappa_4gen_top[im] = 0;
spinzerohiggs_anomcoupl_.kappa_4gen_bot[im] = 0;
spinzerohiggs_anomcoupl_.kappa_tilde_4gen_top[im] = 0;
spinzerohiggs_anomcoupl_.kappa_tilde_4gen_bot[im] = 0;
spinzerohiggs_anomcoupl_.ghg2_4gen[im] = 0;
spinzerohiggs_anomcoupl_.ghg3_4gen[im] = 0;
spinzerohiggs_anomcoupl_.ghg4_4gen[im] = 0;
//
spinzerohiggs_anomcoupl_.ghz2[im] = 0;
spinzerohiggs_anomcoupl_.ghz3[im] = 0;
spinzerohiggs_anomcoupl_.ghz4[im] = 0;
spinzerohiggs_anomcoupl_.ghz1_prime[im] = 0;
spinzerohiggs_anomcoupl_.ghz1_prime2[im] = 0;
spinzerohiggs_anomcoupl_.ghz1_prime3[im] = 0;
spinzerohiggs_anomcoupl_.ghz1_prime4[im] = 0;
spinzerohiggs_anomcoupl_.ghz1_prime5[im] = 0;
spinzerohiggs_anomcoupl_.ghz1_prime6[im] = 0;
spinzerohiggs_anomcoupl_.ghz1_prime7[im] = 0;
spinzerohiggs_anomcoupl_.ghz2_prime[im] = 0;
spinzerohiggs_anomcoupl_.ghz2_prime2[im] = 0;
spinzerohiggs_anomcoupl_.ghz2_prime3[im] = 0;
spinzerohiggs_anomcoupl_.ghz2_prime4[im] = 0;
spinzerohiggs_anomcoupl_.ghz2_prime5[im] = 0;
spinzerohiggs_anomcoupl_.ghz2_prime6[im] = 0;
spinzerohiggs_anomcoupl_.ghz2_prime7[im] = 0;
spinzerohiggs_anomcoupl_.ghz3_prime[im] = 0;
spinzerohiggs_anomcoupl_.ghz3_prime2[im] = 0;
spinzerohiggs_anomcoupl_.ghz3_prime3[im] = 0;
spinzerohiggs_anomcoupl_.ghz3_prime4[im] = 0;
spinzerohiggs_anomcoupl_.ghz3_prime5[im] = 0;
spinzerohiggs_anomcoupl_.ghz3_prime6[im] = 0;
spinzerohiggs_anomcoupl_.ghz3_prime7[im] = 0;
spinzerohiggs_anomcoupl_.ghz4_prime[im] = 0;
spinzerohiggs_anomcoupl_.ghz4_prime2[im] = 0;
spinzerohiggs_anomcoupl_.ghz4_prime3[im] = 0;
spinzerohiggs_anomcoupl_.ghz4_prime4[im] = 0;
spinzerohiggs_anomcoupl_.ghz4_prime5[im] = 0;
spinzerohiggs_anomcoupl_.ghz4_prime6[im] = 0;
spinzerohiggs_anomcoupl_.ghz4_prime7[im] = 0;
//
spinzerohiggs_anomcoupl_.ghzgs1_prime2[im] = 0;
spinzerohiggs_anomcoupl_.ghzgs2[im] = 0;
spinzerohiggs_anomcoupl_.ghzgs3[im] = 0;
spinzerohiggs_anomcoupl_.ghzgs4[im] = 0;
spinzerohiggs_anomcoupl_.ghgsgs2[im] = 0;
spinzerohiggs_anomcoupl_.ghgsgs3[im] = 0;
spinzerohiggs_anomcoupl_.ghgsgs4[im] = 0;
//
spinzerohiggs_anomcoupl_.ghw2[im] = 0;
spinzerohiggs_anomcoupl_.ghw3[im] = 0;
spinzerohiggs_anomcoupl_.ghw4[im] = 0;
spinzerohiggs_anomcoupl_.ghw1_prime[im] = 0;
spinzerohiggs_anomcoupl_.ghw1_prime2[im] = 0;
spinzerohiggs_anomcoupl_.ghw1_prime3[im] = 0;
spinzerohiggs_anomcoupl_.ghw1_prime4[im] = 0;
spinzerohiggs_anomcoupl_.ghw1_prime5[im] = 0;
spinzerohiggs_anomcoupl_.ghw1_prime6[im] = 0;
spinzerohiggs_anomcoupl_.ghw1_prime7[im] = 0;
spinzerohiggs_anomcoupl_.ghw2_prime[im] = 0;
spinzerohiggs_anomcoupl_.ghw2_prime2[im] = 0;
spinzerohiggs_anomcoupl_.ghw2_prime3[im] = 0;
spinzerohiggs_anomcoupl_.ghw2_prime4[im] = 0;
spinzerohiggs_anomcoupl_.ghw2_prime5[im] = 0;
spinzerohiggs_anomcoupl_.ghw2_prime6[im] = 0;
spinzerohiggs_anomcoupl_.ghw2_prime7[im] = 0;
spinzerohiggs_anomcoupl_.ghw3_prime[im] = 0;
spinzerohiggs_anomcoupl_.ghw3_prime2[im] = 0;
spinzerohiggs_anomcoupl_.ghw3_prime3[im] = 0;
spinzerohiggs_anomcoupl_.ghw3_prime4[im] = 0;
spinzerohiggs_anomcoupl_.ghw3_prime5[im] = 0;
spinzerohiggs_anomcoupl_.ghw3_prime6[im] = 0;
spinzerohiggs_anomcoupl_.ghw3_prime7[im] = 0;
spinzerohiggs_anomcoupl_.ghw4_prime[im] = 0;
spinzerohiggs_anomcoupl_.ghw4_prime2[im] = 0;
spinzerohiggs_anomcoupl_.ghw4_prime3[im] = 0;
spinzerohiggs_anomcoupl_.ghw4_prime4[im] = 0;
spinzerohiggs_anomcoupl_.ghw4_prime5[im] = 0;
spinzerohiggs_anomcoupl_.ghw4_prime6[im] = 0;
spinzerohiggs_anomcoupl_.ghw4_prime7[im] = 0;
}
/***** END REGULAR RESONANCE *****/
//
/***** SECOND RESONANCE *****/
//
spinzerohiggs_anomcoupl_.c2z_q1sq = 0;
spinzerohiggs_anomcoupl_.Lambda2_z11 = 100;
spinzerohiggs_anomcoupl_.Lambda2_z21 = 100;
spinzerohiggs_anomcoupl_.Lambda2_z31 = 100;
spinzerohiggs_anomcoupl_.Lambda2_z41 = 100;
spinzerohiggs_anomcoupl_.c2z_q2sq = 0;
spinzerohiggs_anomcoupl_.Lambda2_z12 = 100;
spinzerohiggs_anomcoupl_.Lambda2_z22 = 100;
spinzerohiggs_anomcoupl_.Lambda2_z32 = 100;
spinzerohiggs_anomcoupl_.Lambda2_z42 = 100;
spinzerohiggs_anomcoupl_.c2z_q12sq = 0;
spinzerohiggs_anomcoupl_.Lambda2_z10 = 100;
spinzerohiggs_anomcoupl_.Lambda2_z20 = 100;
spinzerohiggs_anomcoupl_.Lambda2_z30 = 100;
spinzerohiggs_anomcoupl_.Lambda2_z40 = 100;
//
spinzerohiggs_anomcoupl_.c2w_q1sq = 0;
spinzerohiggs_anomcoupl_.Lambda2_w11 = 100;
spinzerohiggs_anomcoupl_.Lambda2_w21 = 100;
spinzerohiggs_anomcoupl_.Lambda2_w31 = 100;
spinzerohiggs_anomcoupl_.Lambda2_w41 = 100;
spinzerohiggs_anomcoupl_.c2w_q2sq = 0;
spinzerohiggs_anomcoupl_.Lambda2_w12 = 100;
spinzerohiggs_anomcoupl_.Lambda2_w22 = 100;
spinzerohiggs_anomcoupl_.Lambda2_w32 = 100;
spinzerohiggs_anomcoupl_.Lambda2_w42 = 100;
spinzerohiggs_anomcoupl_.c2w_q12sq = 0;
spinzerohiggs_anomcoupl_.Lambda2_w10 = 100;
spinzerohiggs_anomcoupl_.Lambda2_w20 = 100;
spinzerohiggs_anomcoupl_.Lambda2_w30 = 100;
spinzerohiggs_anomcoupl_.Lambda2_w40 = 100;
//
// AllowAnomalousCouplings==0, so these are still treated as 1 when h2mass>=0
spinzerohiggs_anomcoupl_.kappa2_top[0] = 0; spinzerohiggs_anomcoupl_.kappa2_top[1] = 0;
spinzerohiggs_anomcoupl_.kappa2_bot[0] = 0; spinzerohiggs_anomcoupl_.kappa2_bot[1] = 0;
spinzerohiggs_anomcoupl_.gh2z1[0] = 0; spinzerohiggs_anomcoupl_.gh2z1[1] = 0;
spinzerohiggs_anomcoupl_.gh2w1[0] = 0; spinzerohiggs_anomcoupl_.gh2w1[1] = 0;
for (int im=0; im<2; im++){
spinzerohiggs_anomcoupl_.kappa2_tilde_top[im] = 0;
spinzerohiggs_anomcoupl_.kappa2_tilde_bot[im] = 0;
spinzerohiggs_anomcoupl_.gh2g2[im] = 0;
spinzerohiggs_anomcoupl_.gh2g3[im] = 0;
spinzerohiggs_anomcoupl_.gh2g4[im] = 0;
spinzerohiggs_anomcoupl_.kappa2_4gen_top[im] = 0;
spinzerohiggs_anomcoupl_.kappa2_4gen_bot[im] = 0;
spinzerohiggs_anomcoupl_.kappa2_tilde_4gen_top[im] = 0;
spinzerohiggs_anomcoupl_.kappa2_tilde_4gen_bot[im] = 0;
spinzerohiggs_anomcoupl_.gh2g2_4gen[im] = 0;
spinzerohiggs_anomcoupl_.gh2g3_4gen[im] = 0;
spinzerohiggs_anomcoupl_.gh2g4_4gen[im] = 0;
//
spinzerohiggs_anomcoupl_.gh2z2[im] = 0;
spinzerohiggs_anomcoupl_.gh2z3[im] = 0;
spinzerohiggs_anomcoupl_.gh2z4[im] = 0;
spinzerohiggs_anomcoupl_.gh2z1_prime[im] = 0;
spinzerohiggs_anomcoupl_.gh2z1_prime2[im] = 0;
spinzerohiggs_anomcoupl_.gh2z1_prime3[im] = 0;
spinzerohiggs_anomcoupl_.gh2z1_prime4[im] = 0;
spinzerohiggs_anomcoupl_.gh2z1_prime5[im] = 0;
spinzerohiggs_anomcoupl_.gh2z1_prime6[im] = 0;
spinzerohiggs_anomcoupl_.gh2z1_prime7[im] = 0;
spinzerohiggs_anomcoupl_.gh2z2_prime[im] = 0;
spinzerohiggs_anomcoupl_.gh2z2_prime2[im] = 0;
spinzerohiggs_anomcoupl_.gh2z2_prime3[im] = 0;
spinzerohiggs_anomcoupl_.gh2z2_prime4[im] = 0;
spinzerohiggs_anomcoupl_.gh2z2_prime5[im] = 0;
spinzerohiggs_anomcoupl_.gh2z2_prime6[im] = 0;
spinzerohiggs_anomcoupl_.gh2z2_prime7[im] = 0;
spinzerohiggs_anomcoupl_.gh2z3_prime[im] = 0;
spinzerohiggs_anomcoupl_.gh2z3_prime2[im] = 0;
spinzerohiggs_anomcoupl_.gh2z3_prime3[im] = 0;
spinzerohiggs_anomcoupl_.gh2z3_prime4[im] = 0;
spinzerohiggs_anomcoupl_.gh2z3_prime5[im] = 0;
spinzerohiggs_anomcoupl_.gh2z3_prime6[im] = 0;
spinzerohiggs_anomcoupl_.gh2z3_prime7[im] = 0;
spinzerohiggs_anomcoupl_.gh2z4_prime[im] = 0;
spinzerohiggs_anomcoupl_.gh2z4_prime2[im] = 0;
spinzerohiggs_anomcoupl_.gh2z4_prime3[im] = 0;
spinzerohiggs_anomcoupl_.gh2z4_prime4[im] = 0;
spinzerohiggs_anomcoupl_.gh2z4_prime5[im] = 0;
spinzerohiggs_anomcoupl_.gh2z4_prime6[im] = 0;
spinzerohiggs_anomcoupl_.gh2z4_prime7[im] = 0;
//
spinzerohiggs_anomcoupl_.gh2zgs1_prime2[im] = 0;
spinzerohiggs_anomcoupl_.gh2zgs2[im] = 0;
spinzerohiggs_anomcoupl_.gh2zgs3[im] = 0;
spinzerohiggs_anomcoupl_.gh2zgs4[im] = 0;
spinzerohiggs_anomcoupl_.gh2gsgs2[im] = 0;
spinzerohiggs_anomcoupl_.gh2gsgs3[im] = 0;
spinzerohiggs_anomcoupl_.gh2gsgs4[im] = 0;
//
spinzerohiggs_anomcoupl_.gh2w2[im] = 0;
spinzerohiggs_anomcoupl_.gh2w3[im] = 0;
spinzerohiggs_anomcoupl_.gh2w4[im] = 0;
spinzerohiggs_anomcoupl_.gh2w1_prime[im] = 0;
spinzerohiggs_anomcoupl_.gh2w1_prime2[im] = 0;
spinzerohiggs_anomcoupl_.gh2w1_prime3[im] = 0;
spinzerohiggs_anomcoupl_.gh2w1_prime4[im] = 0;
spinzerohiggs_anomcoupl_.gh2w1_prime5[im] = 0;
spinzerohiggs_anomcoupl_.gh2w1_prime6[im] = 0;
spinzerohiggs_anomcoupl_.gh2w1_prime7[im] = 0;
spinzerohiggs_anomcoupl_.gh2w2_prime[im] = 0;
spinzerohiggs_anomcoupl_.gh2w2_prime2[im] = 0;
spinzerohiggs_anomcoupl_.gh2w2_prime3[im] = 0;
spinzerohiggs_anomcoupl_.gh2w2_prime4[im] = 0;
spinzerohiggs_anomcoupl_.gh2w2_prime5[im] = 0;
spinzerohiggs_anomcoupl_.gh2w2_prime6[im] = 0;
spinzerohiggs_anomcoupl_.gh2w2_prime7[im] = 0;
spinzerohiggs_anomcoupl_.gh2w3_prime[im] = 0;
spinzerohiggs_anomcoupl_.gh2w3_prime2[im] = 0;
spinzerohiggs_anomcoupl_.gh2w3_prime3[im] = 0;
spinzerohiggs_anomcoupl_.gh2w3_prime4[im] = 0;
spinzerohiggs_anomcoupl_.gh2w3_prime5[im] = 0;
spinzerohiggs_anomcoupl_.gh2w3_prime6[im] = 0;
spinzerohiggs_anomcoupl_.gh2w3_prime7[im] = 0;
spinzerohiggs_anomcoupl_.gh2w4_prime[im] = 0;
spinzerohiggs_anomcoupl_.gh2w4_prime2[im] = 0;
spinzerohiggs_anomcoupl_.gh2w4_prime3[im] = 0;
spinzerohiggs_anomcoupl_.gh2w4_prime4[im] = 0;
spinzerohiggs_anomcoupl_.gh2w4_prime5[im] = 0;
spinzerohiggs_anomcoupl_.gh2w4_prime6[im] = 0;
spinzerohiggs_anomcoupl_.gh2w4_prime7[im] = 0;
}
/***** END SECOND RESONANCE *****/
}
else{
spinzerohiggs_anomcoupl_.AllowAnomalousCouplings = 1;
spinzerohiggs_anomcoupl_.distinguish_HWWcouplings = ((Hcouplings->separateWWZZcouplings && !forceZZ) ? 1 : 0);
/***** REGULAR RESONANCE *****/
//
spinzerohiggs_anomcoupl_.cz_q1sq = (Hcouplings->HzzCLambda_qsq)[cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda_z11 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_1][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda_z21 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_2][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda_z31 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_3][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda_z41 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_4][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.cz_q2sq = (Hcouplings->HzzCLambda_qsq)[cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda_z12 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_1][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda_z22 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_2][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda_z32 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_3][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda_z42 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_4][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.cz_q12sq = (Hcouplings->HzzCLambda_qsq)[cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda_z10 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_1][cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda_z20 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_2][cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda_z30 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_3][cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda_z40 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_4][cLambdaHIGGS_VV_QSQ12];
//
for (int im=0; im<2; im++){
spinzerohiggs_anomcoupl_.kappa_top[im] = (Hcouplings->Httcoupl)[gHIGGS_KAPPA][im];
spinzerohiggs_anomcoupl_.kappa_bot[im] = (Hcouplings->Hbbcoupl)[gHIGGS_KAPPA][im];
spinzerohiggs_anomcoupl_.kappa_tilde_top[im] = (Hcouplings->Httcoupl)[gHIGGS_KAPPA_TILDE][im];
spinzerohiggs_anomcoupl_.kappa_tilde_bot[im] = (Hcouplings->Hbbcoupl)[gHIGGS_KAPPA_TILDE][im];
spinzerohiggs_anomcoupl_.ghg2[im] = (Hcouplings->Hggcoupl)[gHIGGS_GG_2][im];
spinzerohiggs_anomcoupl_.ghg3[im] = (Hcouplings->Hggcoupl)[gHIGGS_GG_3][im];
spinzerohiggs_anomcoupl_.ghg4[im] = (Hcouplings->Hggcoupl)[gHIGGS_GG_4][im];
spinzerohiggs_anomcoupl_.kappa_4gen_top[im] = (Hcouplings->Ht4t4coupl)[gHIGGS_KAPPA][im];
spinzerohiggs_anomcoupl_.kappa_4gen_bot[im] = (Hcouplings->Hb4b4coupl)[gHIGGS_KAPPA][im];
spinzerohiggs_anomcoupl_.kappa_tilde_4gen_top[im] = (Hcouplings->Ht4t4coupl)[gHIGGS_KAPPA_TILDE][im];
spinzerohiggs_anomcoupl_.kappa_tilde_4gen_bot[im] = (Hcouplings->Hb4b4coupl)[gHIGGS_KAPPA_TILDE][im];
spinzerohiggs_anomcoupl_.ghg2_4gen[im] = (Hcouplings->Hg4g4coupl)[gHIGGS_GG_2][im];
spinzerohiggs_anomcoupl_.ghg3_4gen[im] = (Hcouplings->Hg4g4coupl)[gHIGGS_GG_3][im];
spinzerohiggs_anomcoupl_.ghg4_4gen[im] = (Hcouplings->Hg4g4coupl)[gHIGGS_GG_4][im];
//
spinzerohiggs_anomcoupl_.ghz1[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_1][im];
spinzerohiggs_anomcoupl_.ghz2[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_2][im];
spinzerohiggs_anomcoupl_.ghz3[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_3][im];
spinzerohiggs_anomcoupl_.ghz4[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_4][im];
spinzerohiggs_anomcoupl_.ghz1_prime[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_1_PRIME][im];
spinzerohiggs_anomcoupl_.ghz1_prime2[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_1_PRIME2][im];
spinzerohiggs_anomcoupl_.ghz1_prime3[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_1_PRIME3][im];
spinzerohiggs_anomcoupl_.ghz1_prime4[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_1_PRIME4][im];
spinzerohiggs_anomcoupl_.ghz1_prime5[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_1_PRIME5][im];
spinzerohiggs_anomcoupl_.ghz1_prime6[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_1_PRIME6][im];
spinzerohiggs_anomcoupl_.ghz1_prime7[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_1_PRIME7][im];
spinzerohiggs_anomcoupl_.ghz2_prime[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_2_PRIME][im];
spinzerohiggs_anomcoupl_.ghz2_prime2[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_2_PRIME2][im];
spinzerohiggs_anomcoupl_.ghz2_prime3[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_2_PRIME3][im];
spinzerohiggs_anomcoupl_.ghz2_prime4[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_2_PRIME4][im];
spinzerohiggs_anomcoupl_.ghz2_prime5[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_2_PRIME5][im];
spinzerohiggs_anomcoupl_.ghz2_prime6[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_2_PRIME6][im];
spinzerohiggs_anomcoupl_.ghz2_prime7[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_2_PRIME7][im];
spinzerohiggs_anomcoupl_.ghz3_prime[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_3_PRIME][im];
spinzerohiggs_anomcoupl_.ghz3_prime2[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_3_PRIME2][im];
spinzerohiggs_anomcoupl_.ghz3_prime3[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_3_PRIME3][im];
spinzerohiggs_anomcoupl_.ghz3_prime4[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_3_PRIME4][im];
spinzerohiggs_anomcoupl_.ghz3_prime5[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_3_PRIME5][im];
spinzerohiggs_anomcoupl_.ghz3_prime6[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_3_PRIME6][im];
spinzerohiggs_anomcoupl_.ghz3_prime7[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_3_PRIME7][im];
spinzerohiggs_anomcoupl_.ghz4_prime[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_4_PRIME][im];
spinzerohiggs_anomcoupl_.ghz4_prime2[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_4_PRIME2][im];
spinzerohiggs_anomcoupl_.ghz4_prime3[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_4_PRIME3][im];
spinzerohiggs_anomcoupl_.ghz4_prime4[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_4_PRIME4][im];
spinzerohiggs_anomcoupl_.ghz4_prime5[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_4_PRIME5][im];
spinzerohiggs_anomcoupl_.ghz4_prime6[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_4_PRIME6][im];
spinzerohiggs_anomcoupl_.ghz4_prime7[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_4_PRIME7][im];
//
spinzerohiggs_anomcoupl_.ghzgs1_prime2[im] = (Hcouplings->Hzzcoupl)[gHIGGS_ZA_1_PRIME2][im];
spinzerohiggs_anomcoupl_.ghzgs2[im] = (Hcouplings->Hzzcoupl)[gHIGGS_ZA_2][im];
spinzerohiggs_anomcoupl_.ghzgs3[im] = (Hcouplings->Hzzcoupl)[gHIGGS_ZA_3][im];
spinzerohiggs_anomcoupl_.ghzgs4[im] = (Hcouplings->Hzzcoupl)[gHIGGS_ZA_4][im];
spinzerohiggs_anomcoupl_.ghgsgs2[im] = (Hcouplings->Hzzcoupl)[gHIGGS_AA_2][im];
spinzerohiggs_anomcoupl_.ghgsgs3[im] = (Hcouplings->Hzzcoupl)[gHIGGS_AA_3][im];
spinzerohiggs_anomcoupl_.ghgsgs4[im] = (Hcouplings->Hzzcoupl)[gHIGGS_AA_4][im];
}
//
if (spinzerohiggs_anomcoupl_.distinguish_HWWcouplings==1){
//
spinzerohiggs_anomcoupl_.cw_q1sq = (Hcouplings->HwwCLambda_qsq)[cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda_w11 = (Hcouplings->HwwLambda_qsq)[LambdaHIGGS_QSQ_VV_1][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda_w21 = (Hcouplings->HwwLambda_qsq)[LambdaHIGGS_QSQ_VV_2][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda_w31 = (Hcouplings->HwwLambda_qsq)[LambdaHIGGS_QSQ_VV_3][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda_w41 = (Hcouplings->HwwLambda_qsq)[LambdaHIGGS_QSQ_VV_4][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.cw_q2sq = (Hcouplings->HwwCLambda_qsq)[cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda_w12 = (Hcouplings->HwwLambda_qsq)[LambdaHIGGS_QSQ_VV_1][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda_w22 = (Hcouplings->HwwLambda_qsq)[LambdaHIGGS_QSQ_VV_2][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda_w32 = (Hcouplings->HwwLambda_qsq)[LambdaHIGGS_QSQ_VV_3][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda_w42 = (Hcouplings->HwwLambda_qsq)[LambdaHIGGS_QSQ_VV_4][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.cw_q12sq = (Hcouplings->HwwCLambda_qsq)[cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda_w10 = (Hcouplings->HwwLambda_qsq)[LambdaHIGGS_QSQ_VV_1][cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda_w20 = (Hcouplings->HwwLambda_qsq)[LambdaHIGGS_QSQ_VV_2][cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda_w30 = (Hcouplings->HwwLambda_qsq)[LambdaHIGGS_QSQ_VV_3][cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda_w40 = (Hcouplings->HwwLambda_qsq)[LambdaHIGGS_QSQ_VV_4][cLambdaHIGGS_VV_QSQ12];
//
for (int im=0; im<2; im++){
spinzerohiggs_anomcoupl_.ghw1[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_1][im];
spinzerohiggs_anomcoupl_.ghw2[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_2][im];
spinzerohiggs_anomcoupl_.ghw3[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_3][im];
spinzerohiggs_anomcoupl_.ghw4[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_4][im];
spinzerohiggs_anomcoupl_.ghw1_prime[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_1_PRIME][im];
spinzerohiggs_anomcoupl_.ghw1_prime2[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_1_PRIME2][im];
spinzerohiggs_anomcoupl_.ghw1_prime3[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_1_PRIME3][im];
spinzerohiggs_anomcoupl_.ghw1_prime4[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_1_PRIME4][im];
spinzerohiggs_anomcoupl_.ghw1_prime5[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_1_PRIME5][im];
spinzerohiggs_anomcoupl_.ghw1_prime6[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_1_PRIME6][im];
spinzerohiggs_anomcoupl_.ghw1_prime7[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_1_PRIME7][im];
spinzerohiggs_anomcoupl_.ghw2_prime[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_2_PRIME][im];
spinzerohiggs_anomcoupl_.ghw2_prime2[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_2_PRIME2][im];
spinzerohiggs_anomcoupl_.ghw2_prime3[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_2_PRIME3][im];
spinzerohiggs_anomcoupl_.ghw2_prime4[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_2_PRIME4][im];
spinzerohiggs_anomcoupl_.ghw2_prime5[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_2_PRIME5][im];
spinzerohiggs_anomcoupl_.ghw2_prime6[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_2_PRIME6][im];
spinzerohiggs_anomcoupl_.ghw2_prime7[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_2_PRIME7][im];
spinzerohiggs_anomcoupl_.ghw3_prime[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_3_PRIME][im];
spinzerohiggs_anomcoupl_.ghw3_prime2[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_3_PRIME2][im];
spinzerohiggs_anomcoupl_.ghw3_prime3[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_3_PRIME3][im];
spinzerohiggs_anomcoupl_.ghw3_prime4[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_3_PRIME4][im];
spinzerohiggs_anomcoupl_.ghw3_prime5[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_3_PRIME5][im];
spinzerohiggs_anomcoupl_.ghw3_prime6[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_3_PRIME6][im];
spinzerohiggs_anomcoupl_.ghw3_prime7[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_3_PRIME7][im];
spinzerohiggs_anomcoupl_.ghw4_prime[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_4_PRIME][im];
spinzerohiggs_anomcoupl_.ghw4_prime2[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_4_PRIME2][im];
spinzerohiggs_anomcoupl_.ghw4_prime3[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_4_PRIME3][im];
spinzerohiggs_anomcoupl_.ghw4_prime4[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_4_PRIME4][im];
spinzerohiggs_anomcoupl_.ghw4_prime5[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_4_PRIME5][im];
spinzerohiggs_anomcoupl_.ghw4_prime6[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_4_PRIME6][im];
spinzerohiggs_anomcoupl_.ghw4_prime7[im] = (Hcouplings->Hwwcoupl)[gHIGGS_VV_4_PRIME7][im];
}
}
else{
//
spinzerohiggs_anomcoupl_.cw_q1sq = (Hcouplings->HzzCLambda_qsq)[cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda_w11 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_1][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda_w21 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_2][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda_w31 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_3][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda_w41 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_4][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.cw_q2sq = (Hcouplings->HzzCLambda_qsq)[cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda_w12 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_1][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda_w22 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_2][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda_w32 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_3][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda_w42 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_4][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.cw_q12sq = (Hcouplings->HzzCLambda_qsq)[cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda_w10 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_1][cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda_w20 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_2][cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda_w30 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_3][cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda_w40 = (Hcouplings->HzzLambda_qsq)[LambdaHIGGS_QSQ_VV_4][cLambdaHIGGS_VV_QSQ12];
//
for (int im=0; im<2; im++){
spinzerohiggs_anomcoupl_.ghw1[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_1][im];
spinzerohiggs_anomcoupl_.ghw2[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_2][im];
spinzerohiggs_anomcoupl_.ghw3[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_3][im];
spinzerohiggs_anomcoupl_.ghw4[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_4][im];
spinzerohiggs_anomcoupl_.ghw1_prime[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_1_PRIME][im];
spinzerohiggs_anomcoupl_.ghw1_prime2[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_1_PRIME2][im];
spinzerohiggs_anomcoupl_.ghw1_prime3[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_1_PRIME3][im];
spinzerohiggs_anomcoupl_.ghw1_prime4[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_1_PRIME4][im];
spinzerohiggs_anomcoupl_.ghw1_prime5[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_1_PRIME5][im];
spinzerohiggs_anomcoupl_.ghw1_prime6[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_1_PRIME6][im];
spinzerohiggs_anomcoupl_.ghw1_prime7[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_1_PRIME7][im];
spinzerohiggs_anomcoupl_.ghw2_prime[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_2_PRIME][im];
spinzerohiggs_anomcoupl_.ghw2_prime2[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_2_PRIME2][im];
spinzerohiggs_anomcoupl_.ghw2_prime3[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_2_PRIME3][im];
spinzerohiggs_anomcoupl_.ghw2_prime4[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_2_PRIME4][im];
spinzerohiggs_anomcoupl_.ghw2_prime5[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_2_PRIME5][im];
spinzerohiggs_anomcoupl_.ghw2_prime6[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_2_PRIME6][im];
spinzerohiggs_anomcoupl_.ghw2_prime7[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_2_PRIME7][im];
spinzerohiggs_anomcoupl_.ghw3_prime[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_3_PRIME][im];
spinzerohiggs_anomcoupl_.ghw3_prime2[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_3_PRIME2][im];
spinzerohiggs_anomcoupl_.ghw3_prime3[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_3_PRIME3][im];
spinzerohiggs_anomcoupl_.ghw3_prime4[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_3_PRIME4][im];
spinzerohiggs_anomcoupl_.ghw3_prime5[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_3_PRIME5][im];
spinzerohiggs_anomcoupl_.ghw3_prime6[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_3_PRIME6][im];
spinzerohiggs_anomcoupl_.ghw3_prime7[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_3_PRIME7][im];
spinzerohiggs_anomcoupl_.ghw4_prime[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_4_PRIME][im];
spinzerohiggs_anomcoupl_.ghw4_prime2[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_4_PRIME2][im];
spinzerohiggs_anomcoupl_.ghw4_prime3[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_4_PRIME3][im];
spinzerohiggs_anomcoupl_.ghw4_prime4[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_4_PRIME4][im];
spinzerohiggs_anomcoupl_.ghw4_prime5[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_4_PRIME5][im];
spinzerohiggs_anomcoupl_.ghw4_prime6[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_4_PRIME6][im];
spinzerohiggs_anomcoupl_.ghw4_prime7[im] = (Hcouplings->Hzzcoupl)[gHIGGS_VV_4_PRIME7][im];
}
}
/***** END REGULAR RESONANCE *****/
//
/***** SECOND RESONANCE *****/
//
spinzerohiggs_anomcoupl_.c2z_q1sq = (Hcouplings->H2zzCLambda_qsq)[cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda2_z11 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_1][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda2_z21 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_2][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda2_z31 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_3][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda2_z41 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_4][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.c2z_q2sq = (Hcouplings->H2zzCLambda_qsq)[cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda2_z12 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_1][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda2_z22 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_2][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda2_z32 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_3][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda2_z42 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_4][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.c2z_q12sq = (Hcouplings->H2zzCLambda_qsq)[cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda2_z10 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_1][cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda2_z20 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_2][cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda2_z30 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_3][cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda2_z40 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_4][cLambdaHIGGS_VV_QSQ12];
//
for (int im=0; im<2; im++){
spinzerohiggs_anomcoupl_.kappa2_top[im] = (Hcouplings->H2ttcoupl)[gHIGGS_KAPPA][im];
spinzerohiggs_anomcoupl_.kappa2_bot[im] = (Hcouplings->H2bbcoupl)[gHIGGS_KAPPA][im];
spinzerohiggs_anomcoupl_.kappa2_tilde_top[im] = (Hcouplings->H2ttcoupl)[gHIGGS_KAPPA_TILDE][im];
spinzerohiggs_anomcoupl_.kappa2_tilde_bot[im] = (Hcouplings->H2bbcoupl)[gHIGGS_KAPPA_TILDE][im];
spinzerohiggs_anomcoupl_.gh2g2[im] = (Hcouplings->H2ggcoupl)[gHIGGS_GG_2][im];
spinzerohiggs_anomcoupl_.gh2g3[im] = (Hcouplings->H2ggcoupl)[gHIGGS_GG_3][im];
spinzerohiggs_anomcoupl_.gh2g4[im] = (Hcouplings->H2ggcoupl)[gHIGGS_GG_4][im];
spinzerohiggs_anomcoupl_.kappa2_4gen_top[im] = (Hcouplings->H2t4t4coupl)[gHIGGS_KAPPA][im];
spinzerohiggs_anomcoupl_.kappa2_4gen_bot[im] = (Hcouplings->H2b4b4coupl)[gHIGGS_KAPPA][im];
spinzerohiggs_anomcoupl_.kappa2_tilde_4gen_top[im] = (Hcouplings->H2t4t4coupl)[gHIGGS_KAPPA_TILDE][im];
spinzerohiggs_anomcoupl_.kappa2_tilde_4gen_bot[im] = (Hcouplings->H2b4b4coupl)[gHIGGS_KAPPA_TILDE][im];
spinzerohiggs_anomcoupl_.gh2g2_4gen[im] = (Hcouplings->H2g4g4coupl)[gHIGGS_GG_2][im];
spinzerohiggs_anomcoupl_.gh2g3_4gen[im] = (Hcouplings->H2g4g4coupl)[gHIGGS_GG_3][im];
spinzerohiggs_anomcoupl_.gh2g4_4gen[im] = (Hcouplings->H2g4g4coupl)[gHIGGS_GG_4][im];
//
spinzerohiggs_anomcoupl_.gh2z1[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_1][im];
spinzerohiggs_anomcoupl_.gh2z2[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_2][im];
spinzerohiggs_anomcoupl_.gh2z3[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_3][im];
spinzerohiggs_anomcoupl_.gh2z4[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_4][im];
spinzerohiggs_anomcoupl_.gh2z1_prime[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_1_PRIME][im];
spinzerohiggs_anomcoupl_.gh2z1_prime2[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_1_PRIME2][im];
spinzerohiggs_anomcoupl_.gh2z1_prime3[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_1_PRIME3][im];
spinzerohiggs_anomcoupl_.gh2z1_prime4[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_1_PRIME4][im];
spinzerohiggs_anomcoupl_.gh2z1_prime5[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_1_PRIME5][im];
spinzerohiggs_anomcoupl_.gh2z1_prime6[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_1_PRIME6][im];
spinzerohiggs_anomcoupl_.gh2z1_prime7[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_1_PRIME7][im];
spinzerohiggs_anomcoupl_.gh2z2_prime[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_2_PRIME][im];
spinzerohiggs_anomcoupl_.gh2z2_prime2[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_2_PRIME2][im];
spinzerohiggs_anomcoupl_.gh2z2_prime3[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_2_PRIME3][im];
spinzerohiggs_anomcoupl_.gh2z2_prime4[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_2_PRIME4][im];
spinzerohiggs_anomcoupl_.gh2z2_prime5[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_2_PRIME5][im];
spinzerohiggs_anomcoupl_.gh2z2_prime6[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_2_PRIME6][im];
spinzerohiggs_anomcoupl_.gh2z2_prime7[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_2_PRIME7][im];
spinzerohiggs_anomcoupl_.gh2z3_prime[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_3_PRIME][im];
spinzerohiggs_anomcoupl_.gh2z3_prime2[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_3_PRIME2][im];
spinzerohiggs_anomcoupl_.gh2z3_prime3[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_3_PRIME3][im];
spinzerohiggs_anomcoupl_.gh2z3_prime4[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_3_PRIME4][im];
spinzerohiggs_anomcoupl_.gh2z3_prime5[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_3_PRIME5][im];
spinzerohiggs_anomcoupl_.gh2z3_prime6[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_3_PRIME6][im];
spinzerohiggs_anomcoupl_.gh2z3_prime7[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_3_PRIME7][im];
spinzerohiggs_anomcoupl_.gh2z4_prime[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_4_PRIME][im];
spinzerohiggs_anomcoupl_.gh2z4_prime2[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_4_PRIME2][im];
spinzerohiggs_anomcoupl_.gh2z4_prime3[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_4_PRIME3][im];
spinzerohiggs_anomcoupl_.gh2z4_prime4[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_4_PRIME4][im];
spinzerohiggs_anomcoupl_.gh2z4_prime5[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_4_PRIME5][im];
spinzerohiggs_anomcoupl_.gh2z4_prime6[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_4_PRIME6][im];
spinzerohiggs_anomcoupl_.gh2z4_prime7[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_4_PRIME7][im];
//
spinzerohiggs_anomcoupl_.gh2zgs1_prime2[im] = (Hcouplings->H2zzcoupl)[gHIGGS_ZA_1_PRIME2][im];
spinzerohiggs_anomcoupl_.gh2zgs2[im] = (Hcouplings->H2zzcoupl)[gHIGGS_ZA_2][im];
spinzerohiggs_anomcoupl_.gh2zgs3[im] = (Hcouplings->H2zzcoupl)[gHIGGS_ZA_3][im];
spinzerohiggs_anomcoupl_.gh2zgs4[im] = (Hcouplings->H2zzcoupl)[gHIGGS_ZA_4][im];
spinzerohiggs_anomcoupl_.gh2gsgs2[im] = (Hcouplings->H2zzcoupl)[gHIGGS_AA_2][im];
spinzerohiggs_anomcoupl_.gh2gsgs3[im] = (Hcouplings->H2zzcoupl)[gHIGGS_AA_3][im];
spinzerohiggs_anomcoupl_.gh2gsgs4[im] = (Hcouplings->H2zzcoupl)[gHIGGS_AA_4][im];
}
//
if (spinzerohiggs_anomcoupl_.distinguish_HWWcouplings==1){
//
spinzerohiggs_anomcoupl_.c2w_q1sq = (Hcouplings->H2wwCLambda_qsq)[cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda2_w11 = (Hcouplings->H2wwLambda_qsq)[LambdaHIGGS_QSQ_VV_1][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda2_w21 = (Hcouplings->H2wwLambda_qsq)[LambdaHIGGS_QSQ_VV_2][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda2_w31 = (Hcouplings->H2wwLambda_qsq)[LambdaHIGGS_QSQ_VV_3][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda2_w41 = (Hcouplings->H2wwLambda_qsq)[LambdaHIGGS_QSQ_VV_4][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.c2w_q2sq = (Hcouplings->H2wwCLambda_qsq)[cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda2_w12 = (Hcouplings->H2wwLambda_qsq)[LambdaHIGGS_QSQ_VV_1][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda2_w22 = (Hcouplings->H2wwLambda_qsq)[LambdaHIGGS_QSQ_VV_2][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda2_w32 = (Hcouplings->H2wwLambda_qsq)[LambdaHIGGS_QSQ_VV_3][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda2_w42 = (Hcouplings->H2wwLambda_qsq)[LambdaHIGGS_QSQ_VV_4][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.c2w_q12sq = (Hcouplings->H2wwCLambda_qsq)[cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda2_w10 = (Hcouplings->H2wwLambda_qsq)[LambdaHIGGS_QSQ_VV_1][cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda2_w20 = (Hcouplings->H2wwLambda_qsq)[LambdaHIGGS_QSQ_VV_2][cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda2_w30 = (Hcouplings->H2wwLambda_qsq)[LambdaHIGGS_QSQ_VV_3][cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda2_w40 = (Hcouplings->H2wwLambda_qsq)[LambdaHIGGS_QSQ_VV_4][cLambdaHIGGS_VV_QSQ12];
//
for (int im=0; im<2; im++){
spinzerohiggs_anomcoupl_.gh2w1[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_1][im];
spinzerohiggs_anomcoupl_.gh2w2[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_2][im];
spinzerohiggs_anomcoupl_.gh2w3[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_3][im];
spinzerohiggs_anomcoupl_.gh2w4[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_4][im];
spinzerohiggs_anomcoupl_.gh2w1_prime[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_1_PRIME][im];
spinzerohiggs_anomcoupl_.gh2w1_prime2[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_1_PRIME2][im];
spinzerohiggs_anomcoupl_.gh2w1_prime3[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_1_PRIME3][im];
spinzerohiggs_anomcoupl_.gh2w1_prime4[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_1_PRIME4][im];
spinzerohiggs_anomcoupl_.gh2w1_prime5[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_1_PRIME5][im];
spinzerohiggs_anomcoupl_.gh2w1_prime6[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_1_PRIME6][im];
spinzerohiggs_anomcoupl_.gh2w1_prime7[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_1_PRIME7][im];
spinzerohiggs_anomcoupl_.gh2w2_prime[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_2_PRIME][im];
spinzerohiggs_anomcoupl_.gh2w2_prime2[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_2_PRIME2][im];
spinzerohiggs_anomcoupl_.gh2w2_prime3[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_2_PRIME3][im];
spinzerohiggs_anomcoupl_.gh2w2_prime4[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_2_PRIME4][im];
spinzerohiggs_anomcoupl_.gh2w2_prime5[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_2_PRIME5][im];
spinzerohiggs_anomcoupl_.gh2w2_prime6[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_2_PRIME6][im];
spinzerohiggs_anomcoupl_.gh2w2_prime7[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_2_PRIME7][im];
spinzerohiggs_anomcoupl_.gh2w3_prime[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_3_PRIME][im];
spinzerohiggs_anomcoupl_.gh2w3_prime2[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_3_PRIME2][im];
spinzerohiggs_anomcoupl_.gh2w3_prime3[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_3_PRIME3][im];
spinzerohiggs_anomcoupl_.gh2w3_prime4[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_3_PRIME4][im];
spinzerohiggs_anomcoupl_.gh2w3_prime5[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_3_PRIME5][im];
spinzerohiggs_anomcoupl_.gh2w3_prime6[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_3_PRIME6][im];
spinzerohiggs_anomcoupl_.gh2w3_prime7[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_3_PRIME7][im];
spinzerohiggs_anomcoupl_.gh2w4_prime[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_4_PRIME][im];
spinzerohiggs_anomcoupl_.gh2w4_prime2[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_4_PRIME2][im];
spinzerohiggs_anomcoupl_.gh2w4_prime3[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_4_PRIME3][im];
spinzerohiggs_anomcoupl_.gh2w4_prime4[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_4_PRIME4][im];
spinzerohiggs_anomcoupl_.gh2w4_prime5[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_4_PRIME5][im];
spinzerohiggs_anomcoupl_.gh2w4_prime6[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_4_PRIME6][im];
spinzerohiggs_anomcoupl_.gh2w4_prime7[im] = (Hcouplings->H2wwcoupl)[gHIGGS_VV_4_PRIME7][im];
}
}
else{
//
spinzerohiggs_anomcoupl_.c2w_q1sq = (Hcouplings->H2zzCLambda_qsq)[cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda2_w11 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_1][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda2_w21 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_2][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda2_w31 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_3][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.Lambda2_w41 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_4][cLambdaHIGGS_VV_QSQ1];
spinzerohiggs_anomcoupl_.c2w_q2sq = (Hcouplings->H2zzCLambda_qsq)[cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda2_w12 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_1][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda2_w22 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_2][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda2_w32 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_3][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.Lambda2_w42 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_4][cLambdaHIGGS_VV_QSQ2];
spinzerohiggs_anomcoupl_.c2w_q12sq = (Hcouplings->H2zzCLambda_qsq)[cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda2_w10 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_1][cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda2_w20 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_2][cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda2_w30 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_3][cLambdaHIGGS_VV_QSQ12];
spinzerohiggs_anomcoupl_.Lambda2_w40 = (Hcouplings->H2zzLambda_qsq)[LambdaHIGGS_QSQ_VV_4][cLambdaHIGGS_VV_QSQ12];
//
for (int im=0; im<2; im++){
spinzerohiggs_anomcoupl_.gh2w1[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_1][im];
spinzerohiggs_anomcoupl_.gh2w2[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_2][im];
spinzerohiggs_anomcoupl_.gh2w3[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_3][im];
spinzerohiggs_anomcoupl_.gh2w4[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_4][im];
spinzerohiggs_anomcoupl_.gh2w1_prime[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_1_PRIME][im];
spinzerohiggs_anomcoupl_.gh2w1_prime2[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_1_PRIME2][im];
spinzerohiggs_anomcoupl_.gh2w1_prime3[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_1_PRIME3][im];
spinzerohiggs_anomcoupl_.gh2w1_prime4[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_1_PRIME4][im];
spinzerohiggs_anomcoupl_.gh2w1_prime5[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_1_PRIME5][im];
spinzerohiggs_anomcoupl_.gh2w1_prime6[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_1_PRIME6][im];
spinzerohiggs_anomcoupl_.gh2w1_prime7[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_1_PRIME7][im];
spinzerohiggs_anomcoupl_.gh2w2_prime[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_2_PRIME][im];
spinzerohiggs_anomcoupl_.gh2w2_prime2[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_2_PRIME2][im];
spinzerohiggs_anomcoupl_.gh2w2_prime3[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_2_PRIME3][im];
spinzerohiggs_anomcoupl_.gh2w2_prime4[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_2_PRIME4][im];
spinzerohiggs_anomcoupl_.gh2w2_prime5[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_2_PRIME5][im];
spinzerohiggs_anomcoupl_.gh2w2_prime6[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_2_PRIME6][im];
spinzerohiggs_anomcoupl_.gh2w2_prime7[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_2_PRIME7][im];
spinzerohiggs_anomcoupl_.gh2w3_prime[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_3_PRIME][im];
spinzerohiggs_anomcoupl_.gh2w3_prime2[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_3_PRIME2][im];
spinzerohiggs_anomcoupl_.gh2w3_prime3[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_3_PRIME3][im];
spinzerohiggs_anomcoupl_.gh2w3_prime4[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_3_PRIME4][im];
spinzerohiggs_anomcoupl_.gh2w3_prime5[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_3_PRIME5][im];
spinzerohiggs_anomcoupl_.gh2w3_prime6[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_3_PRIME6][im];
spinzerohiggs_anomcoupl_.gh2w3_prime7[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_3_PRIME7][im];
spinzerohiggs_anomcoupl_.gh2w4_prime[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_4_PRIME][im];
spinzerohiggs_anomcoupl_.gh2w4_prime2[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_4_PRIME2][im];
spinzerohiggs_anomcoupl_.gh2w4_prime3[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_4_PRIME3][im];
spinzerohiggs_anomcoupl_.gh2w4_prime4[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_4_PRIME4][im];
spinzerohiggs_anomcoupl_.gh2w4_prime5[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_4_PRIME5][im];
spinzerohiggs_anomcoupl_.gh2w4_prime6[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_4_PRIME6][im];
spinzerohiggs_anomcoupl_.gh2w4_prime7[im] = (Hcouplings->H2zzcoupl)[gHIGGS_VV_4_PRIME7][im];
}
}
/***** END SECOND RESONANCE *****/
}
}
void TUtil::SetMCFMaTQGCCouplings(bool useBSM, aTQGCCouplings const* couplings){
if (!useBSM){
for (int im=0; im<2; im++){
if (im==0){
spinzerohiggs_anomcoupl_.dV_A[im] = 1;
spinzerohiggs_anomcoupl_.dP_A[im] = 1;
spinzerohiggs_anomcoupl_.dM_A[im] = 1;
spinzerohiggs_anomcoupl_.dV_Z[im] = 1;
spinzerohiggs_anomcoupl_.dP_Z[im] = 1;
spinzerohiggs_anomcoupl_.dM_Z[im] = 1;
spinzerohiggs_anomcoupl_.dZZWpWm[im] = 1;
spinzerohiggs_anomcoupl_.dZAWpWm[im] = 1;
spinzerohiggs_anomcoupl_.dAAWpWm[im] = 1;
}
else{
spinzerohiggs_anomcoupl_.dV_A[im] = 0;
spinzerohiggs_anomcoupl_.dP_A[im] = 0;
spinzerohiggs_anomcoupl_.dM_A[im] = 0;
spinzerohiggs_anomcoupl_.dV_Z[im] = 0;
spinzerohiggs_anomcoupl_.dP_Z[im] = 0;
spinzerohiggs_anomcoupl_.dM_Z[im] = 0;
spinzerohiggs_anomcoupl_.dZZWpWm[im] = 0;
spinzerohiggs_anomcoupl_.dZAWpWm[im] = 0;
spinzerohiggs_anomcoupl_.dAAWpWm[im] = 0;
}
spinzerohiggs_anomcoupl_.dFour_A[im] = 0;
spinzerohiggs_anomcoupl_.dFour_Z[im] = 0;
}
}
else{
for (int im=0; im<2; im++){
spinzerohiggs_anomcoupl_.dV_A[im] = (couplings->aTQGCcoupl)[gATQGC_dVA][im];
spinzerohiggs_anomcoupl_.dP_A[im] = (couplings->aTQGCcoupl)[gATQGC_dPA][im];
spinzerohiggs_anomcoupl_.dM_A[im] = (couplings->aTQGCcoupl)[gATQGC_dMA][im];
spinzerohiggs_anomcoupl_.dFour_A[im] = (couplings->aTQGCcoupl)[gATQGC_dFourA][im];
spinzerohiggs_anomcoupl_.dV_Z[im] = (couplings->aTQGCcoupl)[gATQGC_dVZ][im];
spinzerohiggs_anomcoupl_.dP_Z[im] = (couplings->aTQGCcoupl)[gATQGC_dPZ][im];
spinzerohiggs_anomcoupl_.dM_Z[im] = (couplings->aTQGCcoupl)[gATQGC_dMZ][im];
spinzerohiggs_anomcoupl_.dFour_Z[im] = (couplings->aTQGCcoupl)[gATQGC_dFourZ][im];
spinzerohiggs_anomcoupl_.dAAWpWm[im] = (couplings->aTQGCcoupl)[gATQGC_dAAWpWm][im];
spinzerohiggs_anomcoupl_.dZAWpWm[im] = (couplings->aTQGCcoupl)[gATQGC_dZAWpWm][im];
spinzerohiggs_anomcoupl_.dZZWpWm[im] = (couplings->aTQGCcoupl)[gATQGC_dZZWpWm][im];
}
}
}
void TUtil::SetJHUGenSpinZeroVVCouplings(double Hvvcoupl[SIZE_HVV][2], double Hvvpcoupl[SIZE_HVV][2], double Hvpvpcoupl[SIZE_HVV][2], int Hvvcoupl_cqsq[SIZE_HVV_CQSQ], double HvvLambda_qsq[SIZE_HVV_LAMBDAQSQ][SIZE_HVV_CQSQ], bool useWWcoupl){
const double GeV = 1./100.;
int iWWcoupl = (useWWcoupl ? 1 : 0);
for (int c=0; c<SIZE_HVV_LAMBDAQSQ; c++){ for (int k=0; k<SIZE_HVV_CQSQ; k++) HvvLambda_qsq[c][k] *= GeV; } // GeV units in JHUGen
__modjhugenmela_MOD_setspinzerovvcouplings(Hvvcoupl, Hvvpcoupl, Hvpvpcoupl, Hvvcoupl_cqsq, HvvLambda_qsq, &iWWcoupl);
}
void TUtil::SetJHUGenSpinZeroGGCouplings(double Hggcoupl[SIZE_HGG][2]){ __modjhugenmela_MOD_setspinzeroggcouplings(Hggcoupl); }
void TUtil::SetJHUGenSpinZeroQQCouplings(double Hqqcoupl[SIZE_HQQ][2]){ __modjhugenmela_MOD_setspinzeroqqcouplings(Hqqcoupl); }
void TUtil::SetJHUGenSpinOneCouplings(double Zqqcoupl[SIZE_ZQQ][2], double Zvvcoupl[SIZE_ZVV][2]){ __modjhugenmela_MOD_setspinonecouplings(Zqqcoupl, Zvvcoupl); }
void TUtil::SetJHUGenSpinTwoCouplings(double Gacoupl[SIZE_GGG][2], double Gvvcoupl[SIZE_GVV][2], double Gvvpcoupl[SIZE_GVV][2], double Gvpvpcoupl[SIZE_GVV][2], double qLeftRightcoupl[SIZE_GQQ][2]){
__modjhugenmela_MOD_setspintwocouplings(Gacoupl, Gvvcoupl, Gvvpcoupl, Gvpvpcoupl, qLeftRightcoupl);
}
void TUtil::SetJHUGenVprimeContactCouplings(double Zpffcoupl[SIZE_Vpff][2], double Wpffcoupl[SIZE_Vpff][2]){
__modjhugenmela_MOD_setvprimecontactcouplings(Zpffcoupl, Wpffcoupl);
}
//Make sure
// 1. tot Energy Sum < 2EBEAM
// 2. PartonEnergy Fraction minimum<x0,x1<1
// 3. number of final state particle is defined
//
double TUtil::SumMatrixElementPDF(
const TVar::Process& process, const TVar::Production& production, const TVar::MatrixElement& matrixElement, const TVar::LeptonInterference& leptonInterf,
event_scales_type* event_scales, MelaIO* RcdME,
const double& EBEAM,
TVar::VerbosityLevel verbosity
){
if (verbosity>=TVar::DEBUG) MELAout << "Begin SumMatrixElementPDF" << endl;
double msqjk=0;
int nRequested_AssociatedJets=0;
int nRequested_AssociatedLeptons=0;
int AssociationVCompatibility=0;
int partIncCode=TVar::kNoAssociated; // Do not use associated particles in the pT=0 frame boost
if (production == TVar::JQCD){ // Use asociated jets in the pT=0 frame boost
partIncCode=TVar::kUseAssociated_Jets;
nRequested_AssociatedJets = 1;
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::SumMatrixElementPDF: Requesting " << nRequested_AssociatedJets << " jets" << endl;
}
else if (
production == TVar::Had_WH || production == TVar::Had_ZH
|| production == TVar::JJVBF || production == TVar::JJEW || production == TVar::JJEWQCD
|| production == TVar::Had_WH_S || production == TVar::Had_ZH_S
|| production == TVar::JJVBF_S || production == TVar::JJEW_S || production == TVar::JJEWQCD_S
|| production == TVar::Had_WH_TU || production == TVar::Had_ZH_TU
|| production == TVar::JJVBF_TU || production == TVar::JJEW_TU || production == TVar::JJEWQCD_TU
|| ((process == TVar::bkgZZ || process == TVar::bkgWW || process == TVar::bkgWWZZ) && (production == TVar::JJQCD || production == TVar::JJQCD_S || production == TVar::JJQCD_TU))
|| (process == TVar::bkgZJets && production == TVar::JJQCD && RcdME->melaCand->getDecayMode()==TVar::CandidateDecay_ff)
){ // Use associated jets in the pT=0 frame boost
partIncCode=TVar::kUseAssociated_Jets;
nRequested_AssociatedJets = 2;
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::SumMatrixElementPDF: Requesting " << nRequested_AssociatedJets << " jets" << endl;
}
else if (
production == TVar::Lep_ZH || production == TVar::Lep_WH
|| production == TVar::Lep_ZH_S || production == TVar::Lep_WH_S
|| production == TVar::Lep_ZH_TU || production == TVar::Lep_WH_TU
){ // Only use associated leptons(+)neutrinos
partIncCode=TVar::kUseAssociated_Leptons;
nRequested_AssociatedLeptons = 2;
}
if (
production == TVar::Had_WH || production == TVar::Lep_WH
|| production == TVar::Had_WH_S || production == TVar::Lep_WH_S
|| production == TVar::Had_WH_TU || production == TVar::Lep_WH_TU
) AssociationVCompatibility=24;
else if (
production == TVar::Had_ZH || production == TVar::Lep_ZH
|| production == TVar::Had_ZH_S || production == TVar::Lep_ZH_S
|| production == TVar::Had_ZH_TU || production == TVar::Lep_ZH_TU
) AssociationVCompatibility=23;
simple_event_record mela_event;
mela_event.AssociationCode=partIncCode;
mela_event.AssociationVCompatibility=AssociationVCompatibility;
mela_event.nRequested_AssociatedJets=nRequested_AssociatedJets;
mela_event.nRequested_AssociatedLeptons=nRequested_AssociatedLeptons;
GetBoostedParticleVectors(
RcdME->melaCand,
mela_event,
verbosity
);
double xx[2]={ 0 };
vector<int> partOrder;
vector<int> apartOrder;
bool doProceed =
CheckPartonMomFraction(mela_event.pMothers.at(0).second, mela_event.pMothers.at(1).second, xx, EBEAM, verbosity) // Check momentum transfers
&&
TUtil::MCFM_chooser(process, production, leptonInterf, verbosity, mela_event); // Set some of the specifics of the process through this function
if (doProceed) doProceed = TUtil::MCFM_SetupParticleCouplings(process, production, verbosity, mela_event, &partOrder, &apartOrder); // Set the specifics of the daughter or associated particle couplings through this function
if (doProceed){
if (partOrder.size()!=mela_event.pDaughters.size()){
if (verbosity >= TVar::ERROR){
MELAerr << "TUtil::SumMatrixElementPDF: Ordering size " << partOrder.size() << " and number of daughter particles " << mela_event.pDaughters.size() << " are not the same!" << endl;
TUtil::PrintCandidateSummary(&mela_event);
}
doProceed=false;
}
if (apartOrder.size()!=mela_event.pAssociated.size()){
if (verbosity >= TVar::ERROR){
MELAerr << "TUtil::SumMatrixElementPDF: Ordering size " << apartOrder.size() << " and number of associated particles " << mela_event.pAssociated.size() << " are not the same!" << endl;
TUtil::PrintCandidateSummary(&mela_event);
}
doProceed=false;
}
}
if (doProceed){
int NPart=npart_.npart+2; // +2 for mothers
double p4[4][mxpart]={ { 0 } };
double p4_tmp[4][mxpart]={ { 0 } };
int id[mxpart]; for (int ipar=0; ipar<mxpart; ipar++) id[ipar]=-9000;
double msq[nmsq][nmsq]={ { 0 } };
double msq_tmp[nmsq][nmsq]={ { 0 } };
int channeltoggle=0;
TLorentzVector MomStore[mxpart];
for (int i = 0; i < mxpart; i++) MomStore[i].SetXYZT(0, 0, 0, 0);
//Convert TLorentzVector into 4xNPart Matrix
//reverse sign of incident partons
for (int ipar=0; ipar<2; ipar++){
if (mela_event.pMothers.at(ipar).second.T()>0.){
p4[0][ipar] = -mela_event.pMothers.at(ipar).second.X();
p4[1][ipar] = -mela_event.pMothers.at(ipar).second.Y();
p4[2][ipar] = -mela_event.pMothers.at(ipar).second.Z();
p4[3][ipar] = -mela_event.pMothers.at(ipar).second.T();
MomStore[ipar] = mela_event.pMothers.at(ipar).second;
id[ipar] = mela_event.pMothers.at(ipar).first;
}
else{
p4[0][ipar] = mela_event.pMothers.at(ipar).second.X();
p4[1][ipar] = mela_event.pMothers.at(ipar).second.Y();
p4[2][ipar] = mela_event.pMothers.at(ipar).second.Z();
p4[3][ipar] = mela_event.pMothers.at(ipar).second.T();
MomStore[ipar] = -mela_event.pMothers.at(ipar).second;
id[ipar] = mela_event.pMothers.at(ipar).first;
}
}
// Determine if the decay mode involves WW or ZZ, to be used for ZZ or WW-specific signal MEs
//bool isZG = (PDGHelpers::isAZBoson(mela_event.intermediateVid.at(0)) && PDGHelpers::isAPhoton(mela_event.intermediateVid.at(1)));
bool isWW = (PDGHelpers::isAWBoson(mela_event.intermediateVid.at(0)) && PDGHelpers::isAWBoson(mela_event.intermediateVid.at(1)));
bool isZZ = (PDGHelpers::isAZBoson(mela_event.intermediateVid.at(0)) && PDGHelpers::isAZBoson(mela_event.intermediateVid.at(1)));
bool isGG = (PDGHelpers::isAPhoton(mela_event.intermediateVid.at(0)) && PDGHelpers::isAPhoton(mela_event.intermediateVid.at(1)));
//initialize decayed particles
for (int ix=0; ix<(int)partOrder.size(); ix++){
int ipar = min((int)mxpart, min(NPart, 2))+ix;
if (ipar>=mxpart) break;
TLorentzVector* momTmp = &(mela_event.pDaughters.at(partOrder.at(ix)).second);
p4[0][ipar] = momTmp->X();
p4[1][ipar] = momTmp->Y();
p4[2][ipar] = momTmp->Z();
p4[3][ipar] = momTmp->T();
MomStore[ipar]=*momTmp;
id[ipar] = mela_event.pDaughters.at(partOrder.at(ix)).first;
}
for (int ix=0; ix<(int)apartOrder.size(); ix++){
int ipar = min((int)mxpart, min(NPart, (int)(partOrder.size()+2)))+ix;
if (ipar>=mxpart) break;
TLorentzVector* momTmp = &(mela_event.pAssociated.at(apartOrder.at(ix)).second);
p4[0][ipar] = momTmp->X();
p4[1][ipar] = momTmp->Y();
p4[2][ipar] = momTmp->Z();
p4[3][ipar] = momTmp->T();
MomStore[ipar]=*momTmp;
id[ipar] = mela_event.pAssociated.at(apartOrder.at(ix)).first;
}
if (verbosity >= TVar::DEBUG){ for (int i=0; i<NPart; i++) MELAout << "p["<<i<<"] (Px, Py, Pz, E):\t" << p4[0][i] << '\t' << p4[1][i] << '\t' << p4[2][i] << '\t' << p4[3][i] << endl; }
double defaultRenScale = scale_.scale;
double defaultFacScale = facscale_.facscale;
int defaultNloop = nlooprun_.nlooprun;
int defaultNflav = nflav_.nflav;
string defaultPdflabel = pdlabel_.pdlabel;
double renQ = InterpretScaleScheme(production, matrixElement, event_scales->renomalizationScheme, MomStore);
double facQ = InterpretScaleScheme(production, matrixElement, event_scales->factorizationScheme, MomStore);
SetAlphaS(renQ, facQ, event_scales->ren_scale_factor, event_scales->fac_scale_factor, 1, 5, "cteq6_l");
double alphasVal, alphasmzVal;
GetAlphaS(&alphasVal, &alphasmzVal);
RcdME->setRenormalizationScale(renQ);
RcdME->setFactorizationScale(facQ);
RcdME->setAlphaS(alphasVal);
RcdME->setAlphaSatMZ(alphasmzVal);
RcdME->setHiggsMassWidth(masses_mcfm_.hmass, masses_mcfm_.hwidth, 0);
RcdME->setHiggsMassWidth(spinzerohiggs_anomcoupl_.h2mass, spinzerohiggs_anomcoupl_.h2width, 1);
if (verbosity>=TVar::DEBUG){
MELAout
<< "TUtil::SumMatrixElementPDF: Set AlphaS:\n"
<< "\tBefore set, alphas scale: " << defaultRenScale << ", PDF scale: " << defaultFacScale << '\n'
<< "\trenQ: " << renQ << " ( x " << event_scales->ren_scale_factor << "), facQ: " << facQ << " ( x " << event_scales->fac_scale_factor << ")\n"
<< "\tAfter set, alphas scale: " << scale_.scale << ", PDF scale: " << facscale_.facscale << ", alphas(Qren): " << alphasVal << ", alphas(MZ): " << alphasmzVal << endl;
}
int nInstances=0;
if (
(production == TVar::ZZINDEPENDENT || production == TVar::ZZQQB)
||
((production == TVar::ZZQQB_STU || production == TVar::ZZQQB_S || production == TVar::ZZQQB_TU) && process == TVar::bkgZZ)
){
if (production == TVar::ZZINDEPENDENT || production == TVar::ZZQQB){
if (process == TVar::bkgGammaGamma){ qqb_gamgam_(p4[0], msq[0]); msq[5][5]=0; } // This function actually computes qqb/gg -> GG, so need to set msq[g][g]=0
else if (process == TVar::bkgZGamma) qqb_zgam_(p4[0], msq[0]);
else if (process == TVar::bkgZZ) qqb_zz_(p4[0], msq[0]);
else if (process == TVar::bkgWW) qqb_ww_(p4[0], msq[0]);
}
else{
if (production == TVar::ZZQQB_STU) channeltoggle=0;
else if (production == TVar::ZZQQB_S) channeltoggle=1;
else/* if (production == TVar::ZZQQB_TU)*/ channeltoggle=2;
qqb_zz_stu_(p4[0], msq[0], &channeltoggle);
}
nInstances=WipeMEArray(process, production, id, msq, verbosity);
// Sum over valid MEs without PDF weights
// By far the dominant contribution is uub initial state.
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++){
if (
(PDGHelpers::isAnUnknownJet(id[0]) || (PDGHelpers::isAGluon(id[0]) && iquark==0) || iquark==id[0])
&&
(PDGHelpers::isAnUnknownJet(id[1]) || (PDGHelpers::isAGluon(id[1]) && jquark==0) || jquark==id[1])
){
if (
PDGHelpers::isAnUnknownJet(id[0])
&&
PDGHelpers::isAnUnknownJet(id[1])
) msqjk = msq[3][7]+msq[7][3]; // Use only uub initial state
else if (
PDGHelpers::isAnUnknownJet(id[0])
) msqjk = msq[jquark+5][-jquark+5];
else if (
PDGHelpers::isAnUnknownJet(id[1])
) msqjk = msq[-iquark+5][iquark+5];
else msqjk += msq[jquark+5][iquark+5];
}
}
}
SumMEPDF(MomStore[0], MomStore[1], msq, RcdME, EBEAM, verbosity);
}
else if (production == TVar::ZZGG){
if (isZZ){
if (process == TVar::HSMHiggs) gg_hzz_tb_(p4[0], msq[0]); // |ggHZZ|**2
else if (process == TVar::bkgZZ_SMHiggs) gg_zz_all_(p4[0], msq[0]); // |ggZZ + ggHZZ|**2
else if (process == TVar::bkgZZ) gg_zz_(p4[0], &(msq[5][5])); // |ggZZ|**2
// The following WWZZ processes need no swapping because ZZ->4f (same type) is ordered such that 3/5 (C++: 2/4) swap gives W+W-.
else if (process == TVar::HSMHiggs_WWZZ) gg_hvv_tb_(p4[0], msq[0]); // |ggHZZ+WW|**2
else if (process == TVar::bkgWWZZ_SMHiggs) gg_vv_all_(p4[0], msq[0]); // |ggZZ + ggHZZ (+WW)|**2
else if (process == TVar::bkgWWZZ) gg_vv_(p4[0], &(msq[5][5])); // |ggZZ+WW|**2
if (verbosity>=TVar::DEBUG){
MELAout << "\tTUtil::SumMatrixElementPDF: ZZGG && ZZ/WW/ZZ+WW MEs using ZZ (runstring: " << runstring_.runstring << ")" << endl;
for (int i=0; i<NPart; i++) MELAout << "\tp["<<i<<"] (Px, Py, Pz, E):\t" << p4[0][i] << '\t' << p4[1][i] << '\t' << p4[2][i] << '\t' << p4[3][i] << endl;
}
}
else if (isWW){
if (process == TVar::HSMHiggs || process == TVar::HSMHiggs_WWZZ) gg_hvv_tb_(p4[0], msq[0]); // |ggHZZ+WW|**2
else if (process == TVar::bkgWW_SMHiggs || process == TVar::bkgWWZZ_SMHiggs) gg_vv_all_(p4[0], msq[0]); // |ggZZ + ggHZZ (+WW)|**2
else if (process == TVar::bkgWW || process == TVar::bkgWWZZ) gg_vv_(p4[0], &(msq[5][5])); // |ggZZ+WW|**2
if (verbosity>=TVar::DEBUG){
MELAout << "\tTUtil::SumMatrixElementPDF: ZZGG && ZZ/WW/ZZ+WW MEs using WW (runstring: " << runstring_.runstring << ")" << endl;
for (int i=0; i<NPart; i++) MELAout << "\tp["<<i<<"] (Px, Py, Pz, E):\t" << p4[0][i] << '\t' << p4[1][i] << '\t' << p4[2][i] << '\t' << p4[3][i] << endl;
}
}
else if (isGG){
if (process == TVar::bkgGammaGamma){
qqb_gamgam_(p4[0], msq[0]);
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++){
if (iquark==0 && jquark==0) continue;
msq[jquark+5][iquark+5] = 0;
}
}
}
}
nInstances=WipeMEArray(process, production, id, msq, verbosity);
if (
(PDGHelpers::isAnUnknownJet(id[0]) || PDGHelpers::isAGluon(id[0]))
&&
(PDGHelpers::isAnUnknownJet(id[1]) || PDGHelpers::isAGluon(id[1]))
){
msqjk = msq[5][5];
}
SumMEPDF(MomStore[0], MomStore[1], msq, RcdME, EBEAM, verbosity);
}
else if (
production == TVar::Had_WH || production == TVar::Had_ZH
|| production == TVar::Had_WH_S || production == TVar::Had_ZH_S
|| production == TVar::Had_WH_TU || production == TVar::Had_ZH_TU
|| production == TVar::Lep_WH || production == TVar::Lep_ZH
|| production == TVar::Lep_WH_S || production == TVar::Lep_ZH_S
|| production == TVar::Lep_WH_TU || production == TVar::Lep_ZH_TU
|| production == TVar::JJVBF || production == TVar::JJEW || production == TVar::JJEWQCD
|| production == TVar::JJVBF_S || production == TVar::JJEW_S || production == TVar::JJEWQCD_S
|| production == TVar::JJVBF_TU || production == TVar::JJEW_TU || production == TVar::JJEWQCD_TU
|| production == TVar::JJQCD || production == TVar::JJQCD_S || production == TVar::JJQCD_TU
){
// Z+2 jets
if (process == TVar::bkgZJets) qqb_z2jet_(p4[0], msq[0]);
// VBF or QCD MCFM SBI, S or B
else if (isZZ && (process == TVar::bkgZZ_SMHiggs || process == TVar::HSMHiggs || process == TVar::bkgZZ)){
if (
production == TVar::Had_WH || production == TVar::Had_ZH
|| production == TVar::Had_WH_S || production == TVar::Had_ZH_S
|| production == TVar::Had_WH_TU || production == TVar::Had_ZH_TU
|| production == TVar::Lep_WH || production == TVar::Lep_ZH
|| production == TVar::Lep_WH_S || production == TVar::Lep_ZH_S
|| production == TVar::Lep_WH_TU || production == TVar::Lep_ZH_TU
|| production == TVar::JJVBF || production == TVar::JJEW
|| production == TVar::JJVBF_S || production == TVar::JJEW_S
|| production == TVar::JJVBF_TU || production == TVar::JJEW_TU
){
/*
if (process == TVar::bkgZZ){//
qq_zzqq_bkg_(p4[0], msq[0]);
if (PDGHelpers::isAnUnknownJet(id[partOrder.size()+2]) && PDGHelpers::isAnUnknownJet(id[partOrder.size()+3])){
for (unsigned int ix=0; ix<4; ix++){
for (int ip=0; ip<mxpart; ip++) p4_tmp[ix][ip]=p4[ix][ip];
swap(p4_tmp[ix][partOrder.size()+2], p4_tmp[ix][partOrder.size()+3]);
}
qq_zzqq_bkg_(p4_tmp[0], msq_tmp[0]);
for (int iquark=-5; iquark<=5; iquark++){ for (int jquark=-5; jquark<=5; jquark++){ msq[jquark+5][iquark+5] = (msq[jquark+5][iquark+5] + msq_tmp[jquark+5][iquark+5]); if (iquark==jquark) msq[jquark+5][iquark+5]*=0.5; } }
}
}
else{//
*/
qq_zzqq_(p4[0], msq[0]);
if (PDGHelpers::isAnUnknownJet(id[partOrder.size()+2]) && PDGHelpers::isAnUnknownJet(id[partOrder.size()+3])){
for (unsigned int ix=0; ix<4; ix++){
for (int ip=0; ip<mxpart; ip++) p4_tmp[ix][ip]=p4[ix][ip];
swap(p4_tmp[ix][partOrder.size()+2], p4_tmp[ix][partOrder.size()+3]);
}
qq_zzqq_(p4_tmp[0], msq_tmp[0]);
for (int iquark=-5; iquark<=5; iquark++){ for (int jquark=-5; jquark<=5; jquark++){ msq[jquark+5][iquark+5] = (msq[jquark+5][iquark+5] + msq_tmp[jquark+5][iquark+5]); if (iquark==jquark) msq[jquark+5][iquark+5]*=0.5; } }
}
else if (PDGHelpers::isAnUnknownJet(id[partOrder.size()+2]) || PDGHelpers::isAnUnknownJet(id[partOrder.size()+3])){
for (unsigned int ix=0; ix<4; ix++){
for (int ip=0; ip<mxpart; ip++) p4_tmp[ix][ip]=p4[ix][ip];
swap(p4_tmp[ix][partOrder.size()+2], p4_tmp[ix][partOrder.size()+3]);
}
TString strlabel[2] ={ (plabel_.plabel)[7], (plabel_.plabel)[6] }; for (unsigned int il=0; il<2; il++) strlabel[il].Resize(2);
for (int ip=0; ip<mxpart; ip++){
if (ip!=6 && ip!=7) sprintf((plabel_.plabel)[ip], (plabel_.plabel)[ip]);
else sprintf((plabel_.plabel)[ip], strlabel[ip-6].Data());
}
qq_zzqq_(p4_tmp[0], msq_tmp[0]);
if (verbosity>=TVar::DEBUG){
MELAout << "TUtil::SumMatrixElementPDF: Adding missing contributions:\n";
MELAout << "\tplabels:\n";
for (int ip=0; ip<mxpart; ip++) MELAout << "\t[" << ip << "]=" << (plabel_.plabel)[ip] << endl;
MELAout << "\tMEsq initial:" << endl;
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++) MELAout << msq[jquark+5][iquark+5] << '\t';
MELAout << endl;
}
MELAout << "\tMEsq added:" << endl;
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++) MELAout << msq_tmp[jquark+5][iquark+5] << '\t';
MELAout << endl;
}
}
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++){
if (msq[jquark+5][iquark+5]==0.) msq[jquark+5][iquark+5] = msq_tmp[jquark+5][iquark+5];
}
}
}
//}//
}
else if (
production == TVar::JJQCD || production == TVar::JJQCD_S || production == TVar::JJQCD_TU
){
qq_zzqqstrong_(p4[0], msq[0]);
if (PDGHelpers::isAnUnknownJet(id[partOrder.size()+2]) && PDGHelpers::isAnUnknownJet(id[partOrder.size()+3])){
for (unsigned int ix=0; ix<4; ix++){
for (int ip=0; ip<mxpart; ip++) p4_tmp[ix][ip]=p4[ix][ip];
swap(p4_tmp[ix][partOrder.size()+2], p4_tmp[ix][partOrder.size()+3]);
}
qq_zzqqstrong_(p4_tmp[0], msq_tmp[0]);
for (int iquark=-5; iquark<=5; iquark++){ for (int jquark=-5; jquark<=5; jquark++){ msq[jquark+5][iquark+5] = (msq[jquark+5][iquark+5] + msq_tmp[jquark+5][iquark+5]); if (iquark==jquark && iquark!=0) msq[jquark+5][iquark+5]*=0.5; } }
// Subtract qqb/qbq->gg that was counted twice.
TString gglabel = TUtil::GetMCFMParticleLabel(21, false, true);
for (int ip=0; ip<mxpart; ip++){
if (ip!=6 && ip!=7) sprintf((plabel_.plabel)[ip], (plabel_.plabel)[ip]);
else sprintf((plabel_.plabel)[ip], gglabel.Data());
}
qq_zzqqstrong_(p4_tmp[0], msq_tmp[0]);
for (int iquark=-5; iquark<=5; iquark++){ int jquark=-iquark; msq[jquark+5][iquark+5] = (msq[jquark+5][iquark+5] - msq_tmp[jquark+5][iquark+5]); }
if (verbosity>=TVar::DEBUG){
MELAout << "TUtil::SumMatrixElementPDF: Subtracting qqb/qbq->gg double-counted contribution:\n";
MELAout << "\tplabels:\n";
for (int ip=0; ip<mxpart; ip++) MELAout << "\t[" << ip << "]=" << (plabel_.plabel)[ip] << endl;
MELAout << "\tMEsq:" << endl;
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++) MELAout << msq_tmp[jquark+5][iquark+5] << '\t';
MELAout << endl;
}
}
}
else if ((PDGHelpers::isAnUnknownJet(id[partOrder.size()+2]) || PDGHelpers::isAnUnknownJet(id[partOrder.size()+3])) && !(PDGHelpers::isAGluon(id[partOrder.size()+2]) || PDGHelpers::isAGluon(id[partOrder.size()+3]))){
for (unsigned int ix=0; ix<4; ix++){
for (int ip=0; ip<mxpart; ip++) p4_tmp[ix][ip]=p4[ix][ip];
swap(p4_tmp[ix][partOrder.size()+2], p4_tmp[ix][partOrder.size()+3]);
}
TString strlabel[2] ={ (plabel_.plabel)[7], (plabel_.plabel)[6] }; for (unsigned int il=0; il<2; il++) strlabel[il].Resize(2);
for (int ip=0; ip<mxpart; ip++){
if (ip!=6 && ip!=7) sprintf((plabel_.plabel)[ip], (plabel_.plabel)[ip]);
else sprintf((plabel_.plabel)[ip], strlabel[ip-6].Data());
}
qq_zzqqstrong_(p4_tmp[0], msq_tmp[0]);
if (verbosity>=TVar::DEBUG){
MELAout << "TUtil::SumMatrixElementPDF: Adding missing contributions:\n";
MELAout << "\tplabels:\n";
for (int ip=0; ip<mxpart; ip++) MELAout << "\t[" << ip << "]=" << (plabel_.plabel)[ip] << endl;
MELAout << "\tMEsq initial:" << endl;
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++) MELAout << msq[jquark+5][iquark+5] << '\t';
MELAout << endl;
}
MELAout << "\tMEsq added:" << endl;
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++) MELAout << msq_tmp[jquark+5][iquark+5] << '\t';
MELAout << endl;
}
}
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++){
if (msq[jquark+5][iquark+5]==0.) msq[jquark+5][iquark+5] = msq_tmp[jquark+5][iquark+5];
}
}
}
}
}
else if (isWW && (process == TVar::bkgWW_SMHiggs || process == TVar::HSMHiggs || process == TVar::bkgWW)){
if (
production == TVar::Had_WH || production == TVar::Had_ZH
|| production == TVar::Had_WH_S || production == TVar::Had_ZH_S
|| production == TVar::Had_WH_TU || production == TVar::Had_ZH_TU
|| production == TVar::Lep_WH || production == TVar::Lep_ZH
|| production == TVar::Lep_WH_S || production == TVar::Lep_ZH_S
|| production == TVar::Lep_WH_TU || production == TVar::Lep_ZH_TU
|| production == TVar::JJVBF || production == TVar::JJEW
|| production == TVar::JJVBF_S || production == TVar::JJEW_S
|| production == TVar::JJVBF_TU || production == TVar::JJEW_TU
){
qq_wwqq_(p4[0], msq[0]);
if (PDGHelpers::isAnUnknownJet(id[partOrder.size()+2]) && PDGHelpers::isAnUnknownJet(id[partOrder.size()+3])){
for (unsigned int ix=0; ix<4; ix++){
for (int ip=0; ip<mxpart; ip++) p4_tmp[ix][ip]=p4[ix][ip];
swap(p4_tmp[ix][partOrder.size()+2], p4_tmp[ix][partOrder.size()+3]);
}
qq_wwqq_(p4_tmp[0], msq_tmp[0]);
for (int iquark=-5; iquark<=5; iquark++){ for (int jquark=-5; jquark<=5; jquark++){ msq[jquark+5][iquark+5] = (msq[jquark+5][iquark+5] + msq_tmp[jquark+5][iquark+5]); if (iquark==jquark) msq[jquark+5][iquark+5]*=0.5; } }
}
else if (PDGHelpers::isAnUnknownJet(id[partOrder.size()+2]) || PDGHelpers::isAnUnknownJet(id[partOrder.size()+3])){
for (unsigned int ix=0; ix<4; ix++){
for (int ip=0; ip<mxpart; ip++) p4_tmp[ix][ip]=p4[ix][ip];
swap(p4_tmp[ix][partOrder.size()+2], p4_tmp[ix][partOrder.size()+3]);
}
TString strlabel[2] ={ (plabel_.plabel)[7], (plabel_.plabel)[6] }; for (unsigned int il=0; il<2; il++) strlabel[il].Resize(2);
for (int ip=0; ip<mxpart; ip++){
if (ip!=6 && ip!=7) sprintf((plabel_.plabel)[ip], (plabel_.plabel)[ip]);
else sprintf((plabel_.plabel)[ip], strlabel[ip-6].Data());
}
qq_wwqq_(p4_tmp[0], msq_tmp[0]);
if (verbosity>=TVar::DEBUG){
MELAout << "TUtil::SumMatrixElementPDF: Adding missing contributions:\n";
MELAout << "\tplabels:\n";
for (int ip=0; ip<mxpart; ip++) MELAout << "\t[" << ip << "]=" << (plabel_.plabel)[ip] << endl;
MELAout << "\tMEsq initial:" << endl;
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++) MELAout << msq[jquark+5][iquark+5] << '\t';
MELAout << endl;
}
MELAout << "\tMEsq added:" << endl;
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++) MELAout << msq_tmp[jquark+5][iquark+5] << '\t';
MELAout << endl;
}
}
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++){
if (msq[jquark+5][iquark+5]==0.) msq[jquark+5][iquark+5] = msq_tmp[jquark+5][iquark+5];
}
}
}
}
else if (
production == TVar::JJQCD || production == TVar::JJQCD_S || production == TVar::JJQCD_TU
){
qq_wwqqstrong_(p4[0], msq[0]);
if (PDGHelpers::isAnUnknownJet(id[partOrder.size()+2]) && PDGHelpers::isAnUnknownJet(id[partOrder.size()+3])){
for (unsigned int ix=0; ix<4; ix++){
for (int ip=0; ip<mxpart; ip++) p4_tmp[ix][ip]=p4[ix][ip];
swap(p4_tmp[ix][partOrder.size()+2], p4_tmp[ix][partOrder.size()+3]);
}
qq_wwqqstrong_(p4_tmp[0], msq_tmp[0]);
for (int iquark=-5; iquark<=5; iquark++){ for (int jquark=-5; jquark<=5; jquark++){ msq[jquark+5][iquark+5] = (msq[jquark+5][iquark+5] + msq_tmp[jquark+5][iquark+5]); if (iquark==jquark && iquark!=0) msq[jquark+5][iquark+5]*=0.5; } }
// Subtract qqb/qbq->gg that was counted twice.
TString gglabel = TUtil::GetMCFMParticleLabel(21, false, true);
for (int ip=0; ip<mxpart; ip++){
if (ip!=6 && ip!=7) sprintf((plabel_.plabel)[ip], (plabel_.plabel)[ip]);
else sprintf((plabel_.plabel)[ip], gglabel.Data());
}
qq_wwqqstrong_(p4_tmp[0], msq_tmp[0]);
for (int iquark=-5; iquark<=5; iquark++){ int jquark=-iquark; msq[jquark+5][iquark+5] = (msq[jquark+5][iquark+5] - msq_tmp[jquark+5][iquark+5]); }
if (verbosity>=TVar::DEBUG){
MELAout << "TUtil::SumMatrixElementPDF: Subtracting qqb/qbq->gg double-counted contribution:\n";
MELAout << "\tplabels:\n";
for (int ip=0; ip<mxpart; ip++) MELAout << "\t[" << ip << "]=" << (plabel_.plabel)[ip] << endl;
MELAout << "\tMEsq:" << endl;
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++) MELAout << msq_tmp[jquark+5][iquark+5] << '\t';
MELAout << endl;
}
}
}
else if ((PDGHelpers::isAnUnknownJet(id[partOrder.size()+2]) || PDGHelpers::isAnUnknownJet(id[partOrder.size()+3])) && !(PDGHelpers::isAGluon(id[partOrder.size()+2]) || PDGHelpers::isAGluon(id[partOrder.size()+3]))){
for (unsigned int ix=0; ix<4; ix++){
for (int ip=0; ip<mxpart; ip++) p4_tmp[ix][ip]=p4[ix][ip];
swap(p4_tmp[ix][partOrder.size()+2], p4_tmp[ix][partOrder.size()+3]);
}
TString strlabel[2] ={ (plabel_.plabel)[7], (plabel_.plabel)[6] }; for (unsigned int il=0; il<2; il++) strlabel[il].Resize(2);
for (int ip=0; ip<mxpart; ip++){
if (ip!=6 && ip!=7) sprintf((plabel_.plabel)[ip], (plabel_.plabel)[ip]);
else sprintf((plabel_.plabel)[ip], strlabel[ip-6].Data());
}
qq_wwqqstrong_(p4_tmp[0], msq_tmp[0]);
if (verbosity>=TVar::DEBUG){
MELAout << "TUtil::SumMatrixElementPDF: Adding missing contributions:\n";
MELAout << "\tplabels:\n";
for (int ip=0; ip<mxpart; ip++) MELAout << "\t[" << ip << "]=" << (plabel_.plabel)[ip] << endl;
MELAout << "\tMEsq initial:" << endl;
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++) MELAout << msq[jquark+5][iquark+5] << '\t';
MELAout << endl;
}
MELAout << "\tMEsq added:" << endl;
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++) MELAout << msq_tmp[jquark+5][iquark+5] << '\t';
MELAout << endl;
}
}
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++){
if (msq[jquark+5][iquark+5]==0.) msq[jquark+5][iquark+5] = msq_tmp[jquark+5][iquark+5];
}
}
}
}
}
else if ((isWW || isZZ) && (process == TVar::bkgWWZZ_SMHiggs || process == TVar::HSMHiggs_WWZZ || process == TVar::bkgWWZZ)){
if (
production == TVar::Had_WH || production == TVar::Had_ZH
|| production == TVar::Had_WH_S || production == TVar::Had_ZH_S
|| production == TVar::Had_WH_TU || production == TVar::Had_ZH_TU
|| production == TVar::Lep_WH || production == TVar::Lep_ZH
|| production == TVar::Lep_WH_S || production == TVar::Lep_ZH_S
|| production == TVar::Lep_WH_TU || production == TVar::Lep_ZH_TU
|| production == TVar::JJVBF || production == TVar::JJEW
|| production == TVar::JJVBF_S || production == TVar::JJEW_S
|| production == TVar::JJVBF_TU || production == TVar::JJEW_TU
){
qq_vvqq_(p4[0], msq[0]);
if (PDGHelpers::isAnUnknownJet(id[partOrder.size()+2]) && PDGHelpers::isAnUnknownJet(id[partOrder.size()+3])){
for (unsigned int ix=0; ix<4; ix++){
for (int ip=0; ip<mxpart; ip++) p4_tmp[ix][ip]=p4[ix][ip];
swap(p4_tmp[ix][partOrder.size()+2], p4_tmp[ix][partOrder.size()+3]);
}
qq_vvqq_(p4_tmp[0], msq_tmp[0]);
for (int iquark=-5; iquark<=5; iquark++){ for (int jquark=-5; jquark<=5; jquark++){ msq[jquark+5][iquark+5] = (msq[jquark+5][iquark+5] + msq_tmp[jquark+5][iquark+5]); if (iquark==jquark) msq[jquark+5][iquark+5]*=0.5; } }
}
else if (PDGHelpers::isAnUnknownJet(id[partOrder.size()+2]) || PDGHelpers::isAnUnknownJet(id[partOrder.size()+3])){
for (unsigned int ix=0; ix<4; ix++){
for (int ip=0; ip<mxpart; ip++) p4_tmp[ix][ip]=p4[ix][ip];
swap(p4_tmp[ix][partOrder.size()+2], p4_tmp[ix][partOrder.size()+3]);
}
TString strlabel[2] ={ (plabel_.plabel)[7], (plabel_.plabel)[6] }; for (unsigned int il=0; il<2; il++) strlabel[il].Resize(2);
for (int ip=0; ip<mxpart; ip++){
if (ip!=6 && ip!=7) sprintf((plabel_.plabel)[ip], (plabel_.plabel)[ip]);
else sprintf((plabel_.plabel)[ip], strlabel[ip-6].Data());
}
qq_vvqq_(p4_tmp[0], msq_tmp[0]);
if (verbosity>=TVar::DEBUG){
MELAout << "TUtil::SumMatrixElementPDF: Adding missing contributions:\n";
MELAout << "\tplabels:\n";
for (int ip=0; ip<mxpart; ip++) MELAout << "\t[" << ip << "]=" << (plabel_.plabel)[ip] << endl;
MELAout << "\tMEsq initial:" << endl;
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++) MELAout << msq[jquark+5][iquark+5] << '\t';
MELAout << endl;
}
MELAout << "\tMEsq added:" << endl;
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++) MELAout << msq_tmp[jquark+5][iquark+5] << '\t';
MELAout << endl;
}
}
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++){
if (msq[jquark+5][iquark+5]==0.) msq[jquark+5][iquark+5] = msq_tmp[jquark+5][iquark+5];
}
}
}
}
//else if (
// production == TVar::JJQCD || production == TVar::JJQCD_S || production == TVar::JJQCD_TU
// ); // No JJQCD-VV ME in MCFM
}
nInstances=WipeMEArray(process, production, id, msq, verbosity);
msqjk = SumMEPDF(MomStore[0], MomStore[1], msq, RcdME, EBEAM, verbosity);
}
// Set aL/R 1,2 into RcdME
if (PDGHelpers::isAZBoson(mela_event.intermediateVid.at(0))) RcdME->setVDaughterCouplings(zcouple_.l1, zcouple_.r1, 0);
else if (PDGHelpers::isAWBoson(mela_event.intermediateVid.at(0))) RcdME->setVDaughterCouplings(1., 0., 0);
else RcdME->setVDaughterCouplings(0., 0., 0);
if (PDGHelpers::isAZBoson(mela_event.intermediateVid.at(1))) RcdME->setVDaughterCouplings(zcouple_.l2, zcouple_.r2, 1);
else if (PDGHelpers::isAWBoson(mela_event.intermediateVid.at(1))) RcdME->setVDaughterCouplings(1., 0., 1);
else RcdME->setVDaughterCouplings(0., 0., 1);
// Reset some of these couplings if the decay is not actually ZZ or WW.
if (
process == TVar::bkgZJets
||
process == TVar::bkgZGamma
) RcdME->setVDaughterCouplings(0., 0., 1);
if (msqjk != msqjk){
if (verbosity>=TVar::ERROR) MELAout << "TUtil::SumMatrixElementPDF: "<< TVar::ProcessName(process) << " msqjk=" << msqjk << endl;
for (int i=0; i<NPart; i++) MELAout << "p["<<i<<"] (Px, Py, Pz, E):\t" << p4[0][i] << '\t' << p4[1][i] << '\t' << p4[2][i] << '\t' << p4[3][i] << endl;
MELAout << "TUtil::SumMatrixElementPDF: The number of ME instances: " << nInstances << ". MEsq[ip][jp] = " << endl;
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++) MELAout << msq[jquark+5][iquark+5] << '\t';
MELAout << endl;
}
msqjk=0;
}
else if (verbosity>=TVar::DEBUG){
MELAout << "TUtil::SumMatrixElementPDF: The number of ME instances: " << nInstances << ". MEsq[ip][jp] = " << endl;
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++) MELAout << msq[jquark+5][iquark+5] << '\t';
MELAout << endl;
}
}
if (verbosity>=TVar::DEBUG) MELAout
<< "TUtil::SumMatrixElementPDF: Reset AlphaS:\n"
<< "\tBefore reset, alphas scale: " << scale_.scale
<< ", PDF scale: " << facscale_.facscale
<< endl;
SetAlphaS(defaultRenScale, defaultFacScale, 1., 1., defaultNloop, defaultNflav, defaultPdflabel);
if (verbosity>=TVar::DEBUG) MELAout
<< "TUtil::SumMatrixElementPDF: Reset AlphaS result:\n"
<< "\tAfter reset, alphas scale: " << scale_.scale
<< ", PDF scale: " << facscale_.facscale
<< endl;
} // End if doProceed
if (verbosity>=TVar::DEBUG) MELAout << "End TUtil::SumMatrixElementPDF(" << msqjk << ")" << endl;
return msqjk;
}
// ggHdec+0J or Hdec+0J
double TUtil::JHUGenMatEl(
const TVar::Process& process, const TVar::Production& production, const TVar::MatrixElement& matrixElement,
event_scales_type* event_scales, MelaIO* RcdME,
const double& EBEAM,
TVar::VerbosityLevel verbosity
){
const double GeV=1./100.; // JHUGen mom. scale factor
double MatElSq=0; // Return value
if (matrixElement!=TVar::JHUGen){ if (verbosity>=TVar::ERROR) MELAerr << "TUtil::JHUGenMatEl: Non-JHUGen MEs are not supported" << endl; return MatElSq; }
bool isSpinZero = (
process == TVar::HSMHiggs
|| process == TVar::H0minus
|| process == TVar::H0hplus
|| process == TVar::H0_g1prime2
|| process == TVar::H0_Zgs
|| process == TVar::H0_gsgs
|| process == TVar::H0_Zgs_PS
|| process == TVar::H0_gsgs_PS
|| process == TVar::H0_Zgsg1prime2
|| process == TVar::SelfDefine_spin0
);
bool isSpinOne = (
process == TVar::H1minus
|| process == TVar::H1plus
|| process == TVar::SelfDefine_spin1
);
bool isSpinTwo = (
process == TVar::H2_g1g5
|| process == TVar::H2_g1
|| process == TVar::H2_g8
|| process == TVar::H2_g4
|| process == TVar::H2_g5
|| process == TVar::H2_g2
|| process == TVar::H2_g3
|| process == TVar::H2_g6
|| process == TVar::H2_g7
|| process == TVar::H2_g9
|| process == TVar::H2_g10
|| process == TVar::SelfDefine_spin2
);
if (!(isSpinZero || isSpinOne || isSpinTwo)){ if (verbosity>=TVar::ERROR) MELAerr << "TUtil::JHUGenMatEl: Process " << TVar::ProcessName(process) << " (" << process << ")" << " not supported." << endl; return MatElSq; }
if (verbosity>=TVar::DEBUG){
MELAout << "TUtil::JHUGenMatEl: Process " << TVar::ProcessName(process) << " is computing a spin-";
if (isSpinZero) MELAout << "0";
else if (isSpinOne) MELAout << "1";
else if (isSpinTwo) MELAout << "2";
else MELAout << "?";
MELAout << " ME with production " << TVar::ProductionName(production) << "." << endl;
}
double msq[nmsq][nmsq]={ { 0 } }; // ME**2[parton2][parton1] for each incoming parton 1 and 2, used in RcdME
int MYIDUP_tmp[4]={ 0 }; // Initial assignment array, unconverted. 0==Unassigned
vector<pair<int, int>> idarray[2]; // All possible ids for each daughter based on the value of MYIDUP_tmp[0:3] and the desired V ids taken from mela_event.intermediateVid.at(0:1)
int MYIDUP[4]={ 0 }; // "Working" assignment, converted
int idfirst[2]={ 0 }; // Used to set DecayMode1, = MYIDUP[0:1]
int idsecond[2]={ 0 }; // Used to set DecayMode2, = MYIDUP[2:3]
double p4[6][4]={ { 0 } }; // Mom (*GeV) to pass into JHUGen
TLorentzVector MomStore[mxpart]; // Mom (in natural units) to compute alphaS
for (int i = 0; i < mxpart; i++) MomStore[i].SetXYZT(0, 0, 0, 0);
// Notice that partIncCode is specific for this subroutine
int partIncCode=TVar::kNoAssociated; // Do not use associated particles in the pT=0 frame boost
simple_event_record mela_event;
mela_event.AssociationCode=partIncCode;
GetBoostedParticleVectors(
RcdME->melaCand,
mela_event,
verbosity
);
if (mela_event.pDaughters.size()<2 || mela_event.intermediateVid.size()!=2){
if (verbosity>=TVar::ERROR) MELAerr << "TUtil::JHUGenMatEl: Number of daughters " << mela_event.pDaughters.size() << " or number of intermediate Vs " << mela_event.intermediateVid << " not supported!" << endl;
return MatElSq;
}
// p(i,0:3) = (E(i),px(i),py(i),pz(i))
// i=0,1: g1,g2 or q1, qb2 (outgoing convention)
// i=2,3: correspond to MY_IDUP(0),MY_IDUP(1)
// i=4,5: correspond to MY_IDUP(2),MY_IDUP(3)
for (int ipar=0; ipar<2; ipar++){
if (mela_event.pMothers.at(ipar).second.T()>0.){
p4[ipar][0] = -mela_event.pMothers.at(ipar).second.T()*GeV;
p4[ipar][1] = -mela_event.pMothers.at(ipar).second.X()*GeV;
p4[ipar][2] = -mela_event.pMothers.at(ipar).second.Y()*GeV;
p4[ipar][3] = -mela_event.pMothers.at(ipar).second.Z()*GeV;
MomStore[ipar] = mela_event.pMothers.at(ipar).second;
}
else{
p4[ipar][0] = mela_event.pMothers.at(ipar).second.T()*GeV;
p4[ipar][1] = mela_event.pMothers.at(ipar).second.X()*GeV;
p4[ipar][2] = mela_event.pMothers.at(ipar).second.Y()*GeV;
p4[ipar][3] = mela_event.pMothers.at(ipar).second.Z()*GeV;
MomStore[ipar] = -mela_event.pMothers.at(ipar).second;
}
// From Markus:
// Note that the momentum no.2, p(1:4, 2), is a dummy which is not used in case production == TVar::ZZINDEPENDENT.
if (ipar==1 && production == TVar::ZZINDEPENDENT){ for (int ix=0; ix<4; ix++){ p4[0][ix] += p4[ipar][ix]; p4[ipar][ix]=0.; } }
}
//initialize decayed particles
if (mela_event.pDaughters.size()==2){
for (unsigned int ipar=0; ipar<mela_event.pDaughters.size(); ipar++){
TLorentzVector* momTmp = &(mela_event.pDaughters.at(ipar).second);
int* idtmp = &(mela_event.pDaughters.at(ipar).first);
int arrindex = 2*ipar;
if (!PDGHelpers::isAnUnknownJet(*idtmp)) MYIDUP_tmp[arrindex] = *idtmp;
else MYIDUP_tmp[arrindex] = 0;
MYIDUP_tmp[arrindex+1] = -9000;
p4[arrindex+2][0] = momTmp->T()*GeV;
p4[arrindex+2][1] = momTmp->X()*GeV;
p4[arrindex+2][2] = momTmp->Y()*GeV;
p4[arrindex+2][3] = momTmp->Z()*GeV;
MomStore[arrindex+2] = *momTmp;
if (verbosity >= TVar::DEBUG) MELAout << "MYIDUP_tmp[" << arrindex << "(" << ipar << ")" << "]=" << MYIDUP_tmp[arrindex] << endl;
}
}
else{
for (unsigned int ipar=0; ipar<4; ipar++){
if (ipar<mela_event.pDaughters.size()){
TLorentzVector* momTmp = &(mela_event.pDaughters.at(ipar).second);
int* idtmp = &(mela_event.pDaughters.at(ipar).first);
if (!PDGHelpers::isAnUnknownJet(*idtmp)) MYIDUP_tmp[ipar] = *idtmp;
else MYIDUP_tmp[ipar] = 0;
p4[ipar+2][0] = momTmp->T()*GeV;
p4[ipar+2][1] = momTmp->X()*GeV;
p4[ipar+2][2] = momTmp->Y()*GeV;
p4[ipar+2][3] = momTmp->Z()*GeV;
MomStore[ipar+2] = *momTmp;
}
else MYIDUP_tmp[ipar] = -9000; // No need to set p4, which is already 0 by initialization
// __modparameters_MOD_not_a_particle__?
if (verbosity >= TVar::DEBUG) MELAout << "MYIDUP_tmp[" << ipar << "]=" << MYIDUP_tmp[ipar] << endl;
}
}
// Set alphas
double defaultRenScale = scale_.scale;
double defaultFacScale = facscale_.facscale;
int defaultNloop = nlooprun_.nlooprun;
int defaultNflav = nflav_.nflav;
string defaultPdflabel = pdlabel_.pdlabel;
double renQ = InterpretScaleScheme(production, matrixElement, event_scales->renomalizationScheme, MomStore);
double facQ = InterpretScaleScheme(production, matrixElement, event_scales->factorizationScheme, MomStore);
SetAlphaS(renQ, facQ, event_scales->ren_scale_factor, event_scales->fac_scale_factor, 1, 5, "cteq6_l"); // Set AlphaS(|Q|/2, mynloop, mynflav, mypartonPDF)
double alphasVal, alphasmzVal;
GetAlphaS(&alphasVal, &alphasmzVal);
RcdME->setRenormalizationScale(renQ);
RcdME->setFactorizationScale(facQ);
RcdME->setAlphaS(alphasVal);
RcdME->setAlphaSatMZ(alphasmzVal);
RcdME->setHiggsMassWidth(masses_mcfm_.hmass, masses_mcfm_.hwidth, 0);
RcdME->setHiggsMassWidth(spinzerohiggs_anomcoupl_.h2mass, spinzerohiggs_anomcoupl_.h2width, 1);
if (verbosity>=TVar::DEBUG){
MELAout
<< "TUtil::JHUGenMatEl: Set AlphaS:\n"
<< "\tBefore set, alphas scale: " << defaultRenScale << ", PDF scale: " << defaultFacScale << '\n'
<< "\trenQ: " << renQ << " ( x " << event_scales->ren_scale_factor << "), facQ: " << facQ << " ( x " << event_scales->fac_scale_factor << ")\n"
<< "\tAfter set, alphas scale: " << scale_.scale << ", PDF scale: " << facscale_.facscale << ", alphas(Qren): " << alphasVal << ", alphas(MZ): " << alphasmzVal << endl;
}
// Determine te actual ids to compute the ME. Assign ids if any are unknown.
for (int iv=0; iv<2; iv++){ // Max. 2 vector bosons
if (MYIDUP_tmp[2*iv+0]!=0 && MYIDUP_tmp[2*iv+1]!=0){ // Z->2l,2nu,2q, W->lnu,qq', G
// OSSF pairs or just one "V-daughter"
if (
TMath::Sign(1, MYIDUP_tmp[2*iv+0])==TMath::Sign(1, -MYIDUP_tmp[2*iv+1])
||
(MYIDUP_tmp[2*iv+0]==-9000 || MYIDUP_tmp[2*iv+1]==-9000)
) idarray[iv].push_back(pair<int, int>(MYIDUP_tmp[2*iv+0], MYIDUP_tmp[2*iv+1]));
// SSSF pairs, ordered already by phi, so avoid the re-ordering inside the ME
else if (MYIDUP_tmp[2*iv+0]<0) idarray[iv].push_back(pair<int, int>(-MYIDUP_tmp[2*iv+0], MYIDUP_tmp[2*iv+1])); // Reverse sign of first daughter if SS(--)SF pair
else idarray[iv].push_back(pair<int, int>(MYIDUP_tmp[2*iv+0], -MYIDUP_tmp[2*iv+1])); // Reverse sign of daughter if SS(++)SF pair
}
else if (MYIDUP_tmp[2*iv+0]!=0){ // ->f?, one quark is known
if (PDGHelpers::isAWBoson(mela_event.intermediateVid.at(iv))){ // (W+/-)->f?
if (PDGHelpers::isUpTypeQuark(MYIDUP_tmp[2*iv+0])){ // (W+)->u?
int id_dn = TMath::Sign(1, -MYIDUP_tmp[2*iv+0]);
int id_st = TMath::Sign(3, -MYIDUP_tmp[2*iv+0]);
int id_bt = TMath::Sign(5, -MYIDUP_tmp[2*iv+0]);
idarray[iv].push_back(pair<int, int>(MYIDUP_tmp[2*iv+0], id_dn));
idarray[iv].push_back(pair<int, int>(MYIDUP_tmp[2*iv+0], id_st));
idarray[iv].push_back(pair<int, int>(MYIDUP_tmp[2*iv+0], id_bt));
}
else if (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[2*iv+0])){ // (W-)->d?
int id_up = TMath::Sign(2, -MYIDUP_tmp[2*iv+0]);
int id_ch = TMath::Sign(4, -MYIDUP_tmp[2*iv+0]);
idarray[iv].push_back(pair<int, int>(MYIDUP_tmp[2*iv+0], id_up));
idarray[iv].push_back(pair<int, int>(MYIDUP_tmp[2*iv+0], id_ch));
}
}
else if (PDGHelpers::isAZBoson(mela_event.intermediateVid.at(iv))){ // Z->f?
idarray[iv].push_back(pair<int, int>(MYIDUP_tmp[2*iv+0], -MYIDUP_tmp[2*iv+0]));
}
}
else if (MYIDUP_tmp[2*iv+1]!=0){ // ->?fb, one quark is known
if (PDGHelpers::isAWBoson(mela_event.intermediateVid.at(iv))){ // (W+/-)->?fb
if (PDGHelpers::isUpTypeQuark(MYIDUP_tmp[2*iv+1])){ // (W-)->?ub
int id_dn = TMath::Sign(1, -MYIDUP_tmp[2*iv+1]);
int id_st = TMath::Sign(3, -MYIDUP_tmp[2*iv+1]);
int id_bt = TMath::Sign(5, -MYIDUP_tmp[2*iv+1]);
idarray[iv].push_back(pair<int, int>(id_dn, MYIDUP_tmp[2*iv+1]));
idarray[iv].push_back(pair<int, int>(id_st, MYIDUP_tmp[2*iv+1]));
idarray[iv].push_back(pair<int, int>(id_bt, MYIDUP_tmp[2*iv+1]));
}
else if (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[2*iv+1])){ // (W+)->?db
int id_up = TMath::Sign(2, -MYIDUP_tmp[2*iv+1]);
int id_ch = TMath::Sign(4, -MYIDUP_tmp[2*iv+1]);
idarray[iv].push_back(pair<int, int>(id_up, MYIDUP_tmp[2*iv+1]));
idarray[iv].push_back(pair<int, int>(id_ch, MYIDUP_tmp[2*iv+1]));
}
}
else if (PDGHelpers::isAZBoson(mela_event.intermediateVid.at(iv))){ // Z->?fb
idarray[iv].push_back(pair<int, int>(-MYIDUP_tmp[2*iv+1], MYIDUP_tmp[2*iv+1]));
}
}
else{ // Both fermions unknown
if (PDGHelpers::isAWBoson(mela_event.intermediateVid.at(iv))){ // (W+/-)->??
for (int iqu=1; iqu<=2; iqu++){
int id_up = iqu*2;
for (int iqd=1; iqd<=3; iqd++){
int id_dn = iqd*2-1;
if (iv==0){ idarray[iv].push_back(pair<int, int>(id_up, -id_dn)); idarray[iv].push_back(pair<int, int>(-id_dn, id_up)); }
else{ idarray[iv].push_back(pair<int, int>(id_dn, -id_up)); idarray[iv].push_back(pair<int, int>(-id_up, id_dn)); }
}
}
}
else if (PDGHelpers::isAZBoson(mela_event.intermediateVid.at(iv))){ // Z->??
for (int iq=1; iq<=5; iq++){ idarray[iv].push_back(pair<int, int>(iq, -iq)); idarray[iv].push_back(pair<int, int>(-iq, iq)); }
}
}
}
// Variables to set L1/2 and R1/2 couplings into RcdME
const int InvalidMode=-1, WWMode=0, ZZMode=1, ZgMode=5, ggMode=7;
int VVMode=InvalidMode;
if (PDGHelpers::isAWBoson(mela_event.intermediateVid.at(0)) && PDGHelpers::isAWBoson(mela_event.intermediateVid.at(1))) VVMode=WWMode;
else if (PDGHelpers::isAZBoson(mela_event.intermediateVid.at(0)) && PDGHelpers::isAZBoson(mela_event.intermediateVid.at(1))) VVMode=ZZMode;
else if (PDGHelpers::isAPhoton(mela_event.intermediateVid.at(0)) && PDGHelpers::isAPhoton(mela_event.intermediateVid.at(1))) VVMode=ggMode;
else if (
(PDGHelpers::isAZBoson(mela_event.intermediateVid.at(0)) && PDGHelpers::isAPhoton(mela_event.intermediateVid.at(1)))
||
(PDGHelpers::isAZBoson(mela_event.intermediateVid.at(1)) && PDGHelpers::isAPhoton(mela_event.intermediateVid.at(0)))
) VVMode=ZgMode;
double aL1=0, aL2=0, aR1=0, aR2=0;
int nNonZero=0;
for (unsigned int v1=0; v1<idarray[0].size(); v1++){
for (unsigned int v2=0; v2<idarray[1].size(); v2++){
// Convert the particle ids to JHU convention
if (idarray[0].at(v1).first!=-9000) MYIDUP[0] = convertLHEreverse(&(idarray[0].at(v1).first));
if (idarray[0].at(v1).second!=-9000) MYIDUP[1] = convertLHEreverse(&(idarray[0].at(v1).second));
if (idarray[1].at(v2).first!=-9000) MYIDUP[2] = convertLHEreverse(&(idarray[1].at(v2).first));
if (idarray[1].at(v2).second!=-9000) MYIDUP[3] = convertLHEreverse(&(idarray[1].at(v2).second));
// Check working ids
if (verbosity>=TVar::DEBUG){ for (unsigned int idau=0; idau<4; idau++) MELAout << "MYIDUP[" << idau << "]=" << MYIDUP[idau] << endl; }
// Determine M_V and Ga_V in JHUGen, needed for g1 vs everything else.
for (int ip=0; ip<2; ip++){ idfirst[ip]=MYIDUP[ip]; idsecond[ip]=MYIDUP[ip+2]; }
__modjhugenmela_MOD_setdecaymodes(idfirst, idsecond); // Set M_V and Ga_V in JHUGen
if (verbosity>=TVar::DEBUG){
double mv, gv;
__modjhugenmela_MOD_getmvgv(&mv, &gv);
MELAout << "TUtil::JHUGenMatEl: M_V=" << mv/GeV << ", Ga_V=" << gv/GeV << endl;
__modjhugenmela_MOD_getmvprimegvprime(&mv, &gv);
MELAout << "TUtil::JHUGenMatEl: M_Vprime=" << mv/GeV << ", Ga_Vprime=" << gv/GeV << endl;
}
// Sum over possible left/right couplings of the Vs
double aLRtmp[4]={ 0 };
__modjhugenmela_MOD_getdecaycouplings(&VVMode, MYIDUP, &(aLRtmp[0]), &(aLRtmp[1]), &(aLRtmp[2]), &(aLRtmp[3]));
if (idarray[0].size()>1){
aL1 = sqrt(pow(aL1, 2)+pow(aLRtmp[0], 2));
aR1 = sqrt(pow(aR1, 2)+pow(aLRtmp[1], 2));
}
else{
aL1 = aLRtmp[0];
aR1 = aLRtmp[1];
}
if (idarray[1].size()>1){
aL2 = sqrt(pow(aL2, 2)+pow(aLRtmp[2], 2));
aR2 = sqrt(pow(aR2, 2)+pow(aLRtmp[3], 2));
}
else{
aL2 = aLRtmp[2];
aR2 = aLRtmp[3];
}
double MatElTmp=0.;
if (production == TVar::ZZGG){
if (isSpinZero) __modhiggs_MOD_evalamp_gg_h_vv(p4, MYIDUP, &MatElTmp);
else if (isSpinTwo) __modgraviton_MOD_evalamp_gg_g_vv(p4, MYIDUP, &MatElTmp);
}
else if (production == TVar::ZZQQB){
if (isSpinOne) __modzprime_MOD_evalamp_qqb_zprime_vv(p4, MYIDUP, &MatElTmp);
else if (isSpinTwo) __modgraviton_MOD_evalamp_qqb_g_vv(p4, MYIDUP, &MatElTmp);
}
else if (production == TVar::ZZINDEPENDENT){
if (isSpinZero) __modhiggs_MOD_evalamp_h_vv(p4, MYIDUP, &MatElTmp);
else if (isSpinOne) __modzprime_MOD_evalamp_zprime_vv(p4, MYIDUP, &MatElTmp);
else if (isSpinTwo) __modgraviton_MOD_evalamp_g_vv(p4, MYIDUP, &MatElTmp);
}
// Add CKM elements since they are not included
if (PDGHelpers::isAWBoson(mela_event.intermediateVid.at(0))) MatElTmp *= pow(__modparameters_MOD_ckmbare(&(idarray[0].at(v1).first), &(idarray[0].at(v1).second)), 2);
if (PDGHelpers::isAWBoson(mela_event.intermediateVid.at(1))) MatElTmp *= pow(__modparameters_MOD_ckmbare(&(idarray[1].at(v2).first), &(idarray[1].at(v2).second)), 2);
if (verbosity >= TVar::DEBUG) MELAout << "=====\nTUtil::JHUGenMatEl: Instance MatElTmp = " << MatElTmp << "\n=====" << endl;
MatElSq += MatElTmp;
if (MatElTmp>0.) nNonZero++;
}
}
if (nNonZero>0) MatElSq /= ((double)nNonZero);
if (verbosity >= TVar::DEBUG){
MELAout << "TUtil::JHUGenMatEl: Number of matrix element instances computed: " << nNonZero << endl;
MELAout << "TUtil::JHUGenMatEl: MatElSq after division = " << MatElSq << endl;
}
// Set aL/R 1,2 into RcdME
RcdME->setVDaughterCouplings(aL1, aR1, 0);
RcdME->setVDaughterCouplings(aL2, aR2, 1);
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout
<< "TUtil::JHUGenMatEl: aL1, aR1, aL2, aR2: "
<< aL1 << ", " << aR1 << ", " << aL2 << ", " << aR2
<< endl;
// This constant is needed to account for the different units used in JHUGen compared to MCFM
int GeVexponent_MEsq = 4-((int)mela_event.pDaughters.size())*2;
if (production == TVar::ZZINDEPENDENT) GeVexponent_MEsq += 2; // Amplitude missing m from production and 1/m**2 from propagator == Amplitude missing 1/m == MEsq missing 1/m**2
double constant = pow(GeV, -GeVexponent_MEsq);
MatElSq *= constant;
// Set RcdME information for ME and parton distributions, taking into account the mothers if id!=0 (i.e. if not unknown).
if (mela_event.pMothers.at(0).first!=0 && mela_event.pMothers.at(1).first!=0){
int ix=5, iy=5;
if (abs(mela_event.pMothers.at(0).first)<6) ix=mela_event.pMothers.at(0).first + 5;
if (abs(mela_event.pMothers.at(1).first)<6) iy=mela_event.pMothers.at(1).first + 5;
msq[iy][ix]=MatElSq; // Note that SumMEPdf receives a transposed msq
}
else{
if (production == TVar::ZZGG || production == TVar::ZZINDEPENDENT) msq[5][5]=MatElSq;
else if (production == TVar::ZZQQB){
for (int ix=0; ix<5; ix++){ msq[ix][10-ix]=MatElSq; msq[10-ix][ix]=MatElSq; }
}
}
if (production!=TVar::ZZINDEPENDENT) SumMEPDF(MomStore[0], MomStore[1], msq, RcdME, EBEAM, verbosity);
else{ // If production is ZZINDEPENDENT, only set gg index with fx1,2[g,g]=1.
double fx_dummy[nmsq]={ 0 }; fx_dummy[5]=1.;
RcdME->setPartonWeights(fx_dummy, fx_dummy);
RcdME->setMEArray(msq, true);
RcdME->computeWeightedMEArray();
}
if (verbosity >= TVar::DEBUG) MELAout << "TUtil::JHUGenMatEl: Final MatElSq = " << MatElSq << endl;
// Reset alphas
if (verbosity>=TVar::DEBUG){
MELAout
<< "TUtil::JHUGenMatEl: Reset AlphaS:\n"
<< "\tBefore reset, alphas scale: " << scale_.scale << ", PDF scale: " << facscale_.facscale << endl;
}
SetAlphaS(defaultRenScale, defaultFacScale, 1., 1., defaultNloop, defaultNflav, defaultPdflabel);
if (verbosity>=TVar::DEBUG){
GetAlphaS(&alphasVal, &alphasmzVal);
MELAout
<< "TUtil::JHUGenMatEl: Reset AlphaS result:\n"
<< "\tAfter reset, alphas scale: " << scale_.scale << ", PDF scale: " << facscale_.facscale << ", alphas(Qren): " << alphasVal << ", alphas(MZ): " << alphasmzVal << endl;
}
return MatElSq;
}
// VBF and HJJ (QCD), H undecayed, includes H BW
double TUtil::HJJMatEl(
const TVar::Process& process, const TVar::Production& production, const TVar::MatrixElement& matrixElement,
event_scales_type* event_scales, MelaIO* RcdME,
const double& EBEAM,
TVar::VerbosityLevel verbosity
){
const double GeV=1./100.; // JHUGen mom. scale factor
double sum_msqjk = 0;
// by default assume only gg productions
// FOTRAN convention -5 -4 -3 -2 -1 0 1 2 3 4 5
// parton flavor bbar cbar sbar ubar dbar g d u s c b
// C++ convention 0 1 2 3 4 5 6 7 8 9 10
//2-D matrix is reversed in fortran
// msq[ parton2 ] [ parton1 ]
// flavor_msq[jj][ii] = fx1[ii]*fx2[jj]*msq[jj][ii];
double MatElsq[nmsq][nmsq]={ { 0 } };
double MatElsq_tmp[nmsq][nmsq]={ { 0 } }; // For H+J
double msq_tmp=0; // For "*_exact"
if (matrixElement!=TVar::JHUGen){ if (verbosity>=TVar::ERROR) MELAerr << "TUtil::HJJMatEl: Non-JHUGen MEs are not supported" << endl; return sum_msqjk; }
if (!(production == TVar::JJQCD || production == TVar::JJVBF || production == TVar::JQCD)){ if (verbosity>=TVar::ERROR) MELAerr << "TUtil::HJJMatEl: Production is not supported!" << endl; return sum_msqjk; }
// Notice that partIncCode is specific for this subroutine
int nRequested_AssociatedJets=2;
if (production == TVar::JQCD) nRequested_AssociatedJets=1;
int partIncCode=TVar::kUseAssociated_Jets; // Only use associated partons in the pT=0 frame boost
simple_event_record mela_event;
mela_event.AssociationCode=partIncCode;
mela_event.nRequested_AssociatedJets=nRequested_AssociatedJets;
GetBoostedParticleVectors(
RcdME->melaCand,
mela_event,
verbosity
);
if (mela_event.pAssociated.size()==0){ if (verbosity>=TVar::ERROR) MELAerr << "TUtil::HJJMatEl: Number of associated particles is 0!" << endl; return sum_msqjk; }
int MYIDUP_tmp[4]={ 0 }; // "Incoming" partons 1, 2, "outgoing" partons 3, 4
double p4[5][4]={ { 0 } };
double pOneJet[4][4] ={ { 0 } }; // For HJ
TLorentzVector MomStore[mxpart];
for (int i = 0; i < mxpart; i++) MomStore[i].SetXYZT(0, 0, 0, 0);
// p4(0:4,i) = (E(i),px(i),py(i),pz(i))
// i=0,1: g1,g2 or q1, qb2 (outgoing convention)
// i=2,3: J1, J2 in outgoing convention when possible
// i=4: H
for (int ipar=0; ipar<2; ipar++){
TLorentzVector* momTmp = &(mela_event.pMothers.at(ipar).second);
int* idtmp = &(mela_event.pMothers.at(ipar).first);
if (!PDGHelpers::isAnUnknownJet(*idtmp)) MYIDUP_tmp[ipar] = *idtmp;
else MYIDUP_tmp[ipar] = 0;
if (momTmp->T()>0.){
p4[ipar][0] = momTmp->T()*GeV;
p4[ipar][1] = momTmp->X()*GeV;
p4[ipar][2] = momTmp->Y()*GeV;
p4[ipar][3] = momTmp->Z()*GeV;
MomStore[ipar] = (*momTmp);
}
else{
p4[ipar][0] = -momTmp->T()*GeV;
p4[ipar][1] = -momTmp->X()*GeV;
p4[ipar][2] = -momTmp->Y()*GeV;
p4[ipar][3] = -momTmp->Z()*GeV;
MomStore[ipar] = -(*momTmp);
MYIDUP_tmp[ipar] = -MYIDUP_tmp[ipar];
}
}
for (unsigned int ipar=0; ipar<2; ipar++){
if (ipar<mela_event.pAssociated.size()){
TLorentzVector* momTmp = &(mela_event.pAssociated.at(ipar).second);
int* idtmp = &(mela_event.pAssociated.at(ipar).first);
if (!PDGHelpers::isAnUnknownJet(*idtmp)) MYIDUP_tmp[ipar+2] = *idtmp;
else MYIDUP_tmp[ipar+2] = 0;
p4[ipar+2][0] = momTmp->T()*GeV;
p4[ipar+2][1] = momTmp->X()*GeV;
p4[ipar+2][2] = momTmp->Y()*GeV;
p4[ipar+2][3] = momTmp->Z()*GeV;
MomStore[ipar+6] = (*momTmp); // i==(2, 3, 4) is (J1, J2, H), recorded as MomStore (I1, I2, 0, 0, 0, H, J1, J2)
}
else MYIDUP_tmp[ipar+2] = -9000; // No need to set p4, which is already 0 by initialization
}
for (unsigned int ipar=0; ipar<mela_event.pDaughters.size(); ipar++){
TLorentzVector* momTmp = &(mela_event.pDaughters.at(ipar).second);
p4[4][0] += momTmp->T()*GeV;
p4[4][1] += momTmp->X()*GeV;
p4[4][2] += momTmp->Y()*GeV;
p4[4][3] += momTmp->Z()*GeV;
MomStore[5] = MomStore[5] + (*momTmp); // i==(2, 3, 4) is (J1, J2, H), recorded as MomStore (I1, I2, 0, 0, 0, H, J1, J2)
}
// Momenta for HJ
for (unsigned int i = 0; i < 4; i++){
if (i<2){ for (unsigned int j = 0; j < 4; j++) pOneJet[i][j] = p4[i][j]; } // p1 p2
else if (i==2){ for (unsigned int j = 0; j < 4; j++) pOneJet[i][j] = p4[4][j]; } // H
else{ for (unsigned int j = 0; j < 4; j++) pOneJet[i][j] = p4[2][j]; } // J1
}
if (verbosity >= TVar::DEBUG){
for (unsigned int i=0; i<5; i++) MELAout << "p["<<i<<"] (Px, Py, Pz, E, M):\t" << p4[i][1]/GeV << '\t' << p4[i][2]/GeV << '\t' << p4[i][3]/GeV << '\t' << p4[i][0]/GeV << '\t' << sqrt(fabs(pow(p4[i][0], 2)-pow(p4[i][1], 2)-pow(p4[i][2], 2)-pow(p4[i][3], 2)))/GeV << endl;
MELAout << "One-jet momenta: " << endl;
for (unsigned int i=0; i<4; i++) MELAout << "pOneJet["<<i<<"] (Px, Py, Pz, E, M):\t" << pOneJet[i][1]/GeV << '\t' << pOneJet[i][2]/GeV << '\t' << pOneJet[i][3]/GeV << '\t' << pOneJet[i][0]/GeV << '\t' << sqrt(fabs(pow(pOneJet[i][0], 2)-pow(pOneJet[i][1], 2)-pow(pOneJet[i][2], 2)-pow(pOneJet[i][3], 2)))/GeV << endl;
}
double defaultRenScale = scale_.scale;
double defaultFacScale = facscale_.facscale;
int defaultNloop = nlooprun_.nlooprun;
int defaultNflav = nflav_.nflav;
string defaultPdflabel = pdlabel_.pdlabel;
double renQ = InterpretScaleScheme(production, matrixElement, event_scales->renomalizationScheme, MomStore);
double facQ = InterpretScaleScheme(production, matrixElement, event_scales->factorizationScheme, MomStore);
SetAlphaS(renQ, facQ, event_scales->ren_scale_factor, event_scales->fac_scale_factor, 1, 5, "cteq6_l");
double alphasVal, alphasmzVal;
GetAlphaS(&alphasVal, &alphasmzVal);
RcdME->setRenormalizationScale(renQ);
RcdME->setFactorizationScale(facQ);
RcdME->setAlphaS(alphasVal);
RcdME->setAlphaSatMZ(alphasmzVal);
RcdME->setHiggsMassWidth(masses_mcfm_.hmass, masses_mcfm_.hwidth, 0);
RcdME->setHiggsMassWidth(spinzerohiggs_anomcoupl_.h2mass, spinzerohiggs_anomcoupl_.h2width, 1);
if (verbosity>=TVar::DEBUG){
MELAout
<< "TUtil::HJJMatEl: Set AlphaS:\n"
<< "\tBefore set, alphas scale: " << defaultRenScale << ", PDF scale: " << defaultFacScale << '\n'
<< "\trenQ: " << renQ << " ( x " << event_scales->ren_scale_factor << "), facQ: " << facQ << " ( x " << event_scales->fac_scale_factor << ")\n"
<< "\tAfter set, alphas scale: " << scale_.scale << ", PDF scale: " << facscale_.facscale << ", alphas(Qren): " << alphasVal << ", alphas(MZ): " << alphasmzVal << endl;
}
// Since we have a lot of these checks, do them here.
bool partonIsUnknown[4];
for (unsigned int ip=0; ip<4; ip++) partonIsUnknown[ip] = (MYIDUP_tmp[ip]==0);
// NOTE ON HJ AND HJJ CHANNEL HASHES:
// THEY ONLY RETURN ISEL>=JSEL CASES. ISEL<JSEL NEEDS TO BE DONE MANUALLY.
if (production == TVar::JQCD){ // Computation is already for all possible qqb/qg/qbg/gg, and incoming q, qb and g flavor have 1-1 correspondence to the outgoing jet flavor.
__modhiggsj_MOD_evalamp_hj(pOneJet, MatElsq_tmp);
for (int isel=-5; isel<=5; isel++){
if (!partonIsUnknown[0] && !((PDGHelpers::isAGluon(MYIDUP_tmp[0]) && isel==0) || MYIDUP_tmp[0]==isel)) continue;
for (int jsel=-5; jsel<=5; jsel++){
if (!partonIsUnknown[1] && !((PDGHelpers::isAGluon(MYIDUP_tmp[1]) && jsel==0) || MYIDUP_tmp[1]==jsel)) continue;
int rsel;
if (isel!=0 && jsel!=0) rsel=0; // Covers qqb->Hg
else if (isel==0) rsel=jsel; // Covers gg->Hg, gq->Hq, gqb->Hqb
else rsel=isel; // Covers qg->Hq, qbg->Hqb
if (!partonIsUnknown[2] && !((PDGHelpers::isAGluon(MYIDUP_tmp[2]) && rsel==0) || MYIDUP_tmp[2]==rsel)) continue;
MatElsq[jsel+5][isel+5] = MatElsq_tmp[jsel+5][isel+5]; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG) MELAout << "Channel (isel, jsel)=" << isel << ", " << jsel << endl;
}
}
}
else if (production == TVar::JJQCD){
const std::vector<TNumericUtil::intTriplet_t>& ijsel = Get_JHUGenHash_OnshellHJJHash();
int nijchannels = ijsel.size();
for (int ic=0; ic<nijchannels; ic++){
// Emulate EvalWeighted_HJJ_test
int isel = ijsel[ic][0];
int jsel = ijsel[ic][1];
int code = ijsel[ic][2];
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "HJJ channel " << ic << " code " << code << endl;
// Default assignments
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "HJJ mother unswapped case" << endl;
int rsel=isel;
int ssel=jsel;
if (
(partonIsUnknown[0] || ((PDGHelpers::isAGluon(MYIDUP_tmp[0]) && isel==0) || MYIDUP_tmp[0]==isel))
&&
(partonIsUnknown[1] || ((PDGHelpers::isAGluon(MYIDUP_tmp[1]) && jsel==0) || MYIDUP_tmp[1]==jsel))
){ // Do it this way to be able to swap isel and jsel later
if (isel==0 && jsel==0){ // gg->?
if (code==2){ // gg->qqb
// Only compute u-ub. The amplitude is multiplied by nf=5
rsel=1;
ssel=-1;
if (
(partonIsUnknown[2] || (PDGHelpers::isAQuark(MYIDUP_tmp[2]) && MYIDUP_tmp[2]>0))
&&
(partonIsUnknown[3] || (PDGHelpers::isAQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[3]<0))
){
__modhiggsjj_MOD_evalamp_sbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << rsel << ", " << ssel << '\t' << msq_tmp << endl;
}
if (
(partonIsUnknown[2] || (PDGHelpers::isAQuark(MYIDUP_tmp[2]) && MYIDUP_tmp[2]<0))
&&
(partonIsUnknown[3] || (PDGHelpers::isAQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[3]>0))
){
__modhiggsjj_MOD_evalamp_sbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << ssel << ", " << rsel << '\t' << msq_tmp << endl;
}
}
else{ // gg->gg
// rsel=ssel=g already
if (
(partonIsUnknown[2] || (PDGHelpers::isAGluon(MYIDUP_tmp[2]) && rsel==0))
&&
(partonIsUnknown[3] || (PDGHelpers::isAGluon(MYIDUP_tmp[3]) && ssel==0))
){
__modhiggsjj_MOD_evalamp_sbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << rsel << ", " << ssel << '\t' << msq_tmp << endl;
}
}
}
else if (isel==0 || jsel==0){ // qg/qbg/gq/gqb->qg/qbg/gq/gqb
if (
(partonIsUnknown[2] || ((PDGHelpers::isAGluon(MYIDUP_tmp[2]) && rsel==0) || MYIDUP_tmp[2]==rsel))
&&
(partonIsUnknown[3] || ((PDGHelpers::isAGluon(MYIDUP_tmp[3]) && ssel==0) || MYIDUP_tmp[3]==ssel))
){
__modhiggsjj_MOD_evalamp_sbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << rsel << ", " << ssel << '\t' << msq_tmp << endl;
}
if (
(partonIsUnknown[2] || ((PDGHelpers::isAGluon(MYIDUP_tmp[2]) && ssel==0) || MYIDUP_tmp[2]==ssel))
&&
(partonIsUnknown[3] || ((PDGHelpers::isAGluon(MYIDUP_tmp[3]) && rsel==0) || MYIDUP_tmp[3]==rsel))
){
__modhiggsjj_MOD_evalamp_sbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << ssel << ", " << rsel << '\t' << msq_tmp << endl;
}
}
else if ((isel>0 && jsel<0) || (isel<0 && jsel>0)){ // qQb/qbQ->?
if (code==1 && isel==-jsel){ // qqb/qbq->gg
rsel=0; ssel=0;
if (
(partonIsUnknown[2] || PDGHelpers::isAGluon(MYIDUP_tmp[2]))
&&
(partonIsUnknown[3] || PDGHelpers::isAGluon(MYIDUP_tmp[3]))
){
__modhiggsjj_MOD_evalamp_sbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << rsel << ", " << ssel << '\t' << msq_tmp << endl;
}
}
else if (code==3 && isel==-jsel){ // qqb->QQb
if (abs(isel)!=1){ rsel=1; ssel=-1; } // Make sure rsel, ssel are not of same flavor as isel, jsel
else{ rsel=2; ssel=-2; }
// The amplitude is aready multiplied by nf-1, so no need to calculate everything (nf-1) times.
if (
(partonIsUnknown[2] && partonIsUnknown[3])
||
(partonIsUnknown[2] && std::abs(MYIDUP_tmp[3])!=std::abs(isel) && MYIDUP_tmp[3]<0)
||
(std::abs(MYIDUP_tmp[2])!=std::abs(isel) && MYIDUP_tmp[2]>0 && partonIsUnknown[3])
||
(std::abs(MYIDUP_tmp[2])!=std::abs(isel) && MYIDUP_tmp[2]==-MYIDUP_tmp[3] && MYIDUP_tmp[2]>0)
){
__modhiggsjj_MOD_evalamp_sbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << rsel << ", " << ssel << '\t' << msq_tmp << endl;
}
if (
(partonIsUnknown[2] && partonIsUnknown[3])
||
(partonIsUnknown[2] && std::abs(MYIDUP_tmp[3])!=std::abs(isel) && MYIDUP_tmp[3]>0)
||
(std::abs(MYIDUP_tmp[2])!=std::abs(isel) && MYIDUP_tmp[2]<0 && partonIsUnknown[3])
||
(std::abs(MYIDUP_tmp[2])!=std::abs(isel) && MYIDUP_tmp[2]==-MYIDUP_tmp[3] && MYIDUP_tmp[2]<0)
){
__modhiggsjj_MOD_evalamp_sbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << ssel << ", " << rsel << '\t' << msq_tmp << endl;
}
}
else{ // qQb/qbQ->qQb/qbQ
if (
(partonIsUnknown[2] || MYIDUP_tmp[2]==rsel)
&&
(partonIsUnknown[3] || MYIDUP_tmp[3]==ssel)
){
__modhiggsjj_MOD_evalamp_sbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << rsel << ", " << ssel << '\t' << msq_tmp << endl;
}
if (
(partonIsUnknown[2] || MYIDUP_tmp[2]==ssel)
&&
(partonIsUnknown[3] || MYIDUP_tmp[3]==rsel)
){
__modhiggsjj_MOD_evalamp_sbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << rsel << ", " << ssel << '\t' << msq_tmp << endl;
}
}
}
else{
if (
(partonIsUnknown[2] || MYIDUP_tmp[2]==rsel)
&&
(partonIsUnknown[3] || MYIDUP_tmp[3]==ssel)
){
__modhiggsjj_MOD_evalamp_sbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << rsel << ", " << ssel << '\t' << msq_tmp << endl;
}
if (
rsel!=ssel
&&
(partonIsUnknown[2] || MYIDUP_tmp[2]==ssel)
&&
(partonIsUnknown[3] || MYIDUP_tmp[3]==rsel)
){
__modhiggsjj_MOD_evalamp_sbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << ssel << ", " << rsel << '\t' << msq_tmp << endl;
}
}
} // End unswapped isel>=jsel cases
if (isel==jsel) continue;
isel = ijsel[ic][1];
jsel = ijsel[ic][0];
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "HJJ mother swapped case" << endl;
// Reset to default assignments
rsel=isel;
ssel=jsel;
if (
(partonIsUnknown[0] || ((PDGHelpers::isAGluon(MYIDUP_tmp[0]) && isel==0) || MYIDUP_tmp[0]==isel))
&&
(partonIsUnknown[1] || ((PDGHelpers::isAGluon(MYIDUP_tmp[1]) && jsel==0) || MYIDUP_tmp[1]==jsel))
){
// isel==jsel==0 is already eliminated by isel!=jsel condition
if (isel==0 || jsel==0){ // qg/qbg/gq/gqb->qg/qbg/gq/gqb
if (
(partonIsUnknown[2] || ((PDGHelpers::isAGluon(MYIDUP_tmp[2]) && rsel==0) || MYIDUP_tmp[2]==rsel))
&&
(partonIsUnknown[3] || ((PDGHelpers::isAGluon(MYIDUP_tmp[3]) && ssel==0) || MYIDUP_tmp[3]==ssel))
){
__modhiggsjj_MOD_evalamp_sbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << rsel << ", " << ssel << '\t' << msq_tmp << endl;
}
if (
(partonIsUnknown[2] || ((PDGHelpers::isAGluon(MYIDUP_tmp[2]) && ssel==0) || MYIDUP_tmp[2]==ssel))
&&
(partonIsUnknown[3] || ((PDGHelpers::isAGluon(MYIDUP_tmp[3]) && rsel==0) || MYIDUP_tmp[3]==rsel))
){
__modhiggsjj_MOD_evalamp_sbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << ssel << ", " << rsel << '\t' << msq_tmp << endl;
}
}
else if ((isel>0 && jsel<0) || (isel<0 && jsel>0)){ // qQb/qbQ->?
if (code==1 && isel==-jsel){ // qqb/qbq->gg
rsel=0; ssel=0;
if (
(partonIsUnknown[2] || PDGHelpers::isAGluon(MYIDUP_tmp[2]))
&&
(partonIsUnknown[3] || PDGHelpers::isAGluon(MYIDUP_tmp[3]))
){
__modhiggsjj_MOD_evalamp_sbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << rsel << ", " << ssel << '\t' << msq_tmp << endl;
}
}
else if(code==3 && isel==-jsel){ // qqb->QQb
if (abs(isel)!=1){ rsel=1; ssel=-1; } // Make sure rsel, ssel are not of same flavor as isel, jsel
else{ rsel=2; ssel=-2; }
// The amplitude is aready multiplied by nf-1, so no need to calculate everything (nf-1) times.
if (
(partonIsUnknown[2] && partonIsUnknown[3])
||
(partonIsUnknown[2] && std::abs(MYIDUP_tmp[3])!=std::abs(isel) && MYIDUP_tmp[3]<0)
||
(std::abs(MYIDUP_tmp[2])!=std::abs(isel) && MYIDUP_tmp[2]>0 && partonIsUnknown[3])
||
(std::abs(MYIDUP_tmp[2])!=std::abs(isel) && MYIDUP_tmp[2]==-MYIDUP_tmp[3] && MYIDUP_tmp[2]>0)
){
__modhiggsjj_MOD_evalamp_sbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << rsel << ", " << ssel << '\t' << msq_tmp << endl;
}
if (
(partonIsUnknown[2] && partonIsUnknown[3])
||
(partonIsUnknown[2] && std::abs(MYIDUP_tmp[3])!=std::abs(isel) && MYIDUP_tmp[3]>0)
||
(std::abs(MYIDUP_tmp[2])!=std::abs(isel) && MYIDUP_tmp[2]<0 && partonIsUnknown[3])
||
(std::abs(MYIDUP_tmp[2])!=std::abs(isel) && MYIDUP_tmp[2]==-MYIDUP_tmp[3] && MYIDUP_tmp[2]<0)
){
__modhiggsjj_MOD_evalamp_sbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << ssel << ", " << rsel << '\t' << msq_tmp << endl;
}
}
else{ // qQb/qbQ->qQb/qbQ
if (
(partonIsUnknown[2] || MYIDUP_tmp[2]==rsel)
&&
(partonIsUnknown[3] || MYIDUP_tmp[3]==ssel)
){
__modhiggsjj_MOD_evalamp_sbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << rsel << ", " << ssel << '\t' << msq_tmp << endl;
}
if (
(partonIsUnknown[2] || MYIDUP_tmp[2]==ssel)
&&
(partonIsUnknown[3] || MYIDUP_tmp[3]==rsel)
){
__modhiggsjj_MOD_evalamp_sbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << ssel << ", " << rsel << '\t' << msq_tmp << endl;
}
}
}
else{
if (
(partonIsUnknown[2] || MYIDUP_tmp[2]==rsel)
&&
(partonIsUnknown[3] || MYIDUP_tmp[3]==ssel)
){
__modhiggsjj_MOD_evalamp_sbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << rsel << ", " << ssel << '\t' << msq_tmp << endl;
}
if (
rsel!=ssel
&&
(partonIsUnknown[2] || MYIDUP_tmp[2]==ssel)
&&
(partonIsUnknown[3] || MYIDUP_tmp[3]==rsel)
){
__modhiggsjj_MOD_evalamp_sbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << ssel << ", " << rsel << '\t' << msq_tmp << endl;
}
}
} // End swapped isel<jsel cases
} // End loop over ic<nijchannels
} // End production == TVar::JJQCD
else if (production == TVar::JJVBF){
int isel, jsel, rsel, ssel;
/*
1234/1243 [0] vs [1] correspond to transposing 12 and 34 at the same time.
Eg. 12->34 == udbar->udbar
1234[0] : 1=u, 2=dbar, 3=u, 4=dbar
1243[0] : 1=u, 2=dbar, 4=u, 3=dbar
1234[1] : 2=u, 1=dbar, 4=u, 3=dbar
1243[1] : 2=u, 1=dbar, 3=u, 4=dbar
*/
double ckm_takeout=1;
double msq_uu_zz_ijrs1234[2]={ 0 };
double msq_uu_zz_ijrs1243[2]={ 0 };
double msq_dd_zz_ijrs1234[2]={ 0 };
double msq_dd_zz_ijrs1243[2]={ 0 };
double msq_ubarubar_zz_ijrs1234[2]={ 0 };
double msq_ubarubar_zz_ijrs1243[2]={ 0 };
double msq_dbardbar_zz_ijrs1234[2]={ 0 };
double msq_dbardbar_zz_ijrs1243[2]={ 0 };
double msq_uu_zzid_ijrs1234[2]={ 0 };
double msq_uu_zzid_ijrs1243[2]={ 0 };
double msq_dd_zzid_ijrs1234[2]={ 0 };
double msq_dd_zzid_ijrs1243[2]={ 0 };
double msq_ubarubar_zzid_ijrs1234[2]={ 0 };
double msq_ubarubar_zzid_ijrs1243[2]={ 0 };
double msq_dbardbar_zzid_ijrs1234[2]={ 0 };
double msq_dbardbar_zzid_ijrs1243[2]={ 0 };
double msq_udbar_zz_ijrs1234[2]={ 0 };
double msq_udbar_zz_ijrs1243[2]={ 0 };
double msq_dubar_zz_ijrs1234[2]={ 0 };
double msq_dubar_zz_ijrs1243[2]={ 0 };
double msq_uubar_zz_ijrs1234[2]={ 0 };
double msq_uubar_zz_ijrs1243[2]={ 0 };
double msq_ddbar_zz_ijrs1234[2]={ 0 };
double msq_ddbar_zz_ijrs1243[2]={ 0 };
double msq_uubar_ww_ijrs1234[2]={ 0 };
double msq_uubar_ww_ijrs1243[2]={ 0 };
double msq_ddbar_ww_ijrs1234[2]={ 0 };
double msq_ddbar_ww_ijrs1243[2]={ 0 };
double msq_ud_wwonly_ijrs1234[2]={ 0 };
double msq_ud_wwonly_ijrs1243[2]={ 0 };
double msq_ubardbar_wwonly_ijrs1234[2]={ 0 };
double msq_ubardbar_wwonly_ijrs1243[2]={ 0 };
// ud, ubardbar ZZ(+)WW case to be added separately inside a loop.
// NOTE: The order should be u>c>d>s>b; particle>antiparticle
if (
(partonIsUnknown[0] || (PDGHelpers::isUpTypeQuark(MYIDUP_tmp[0]) && MYIDUP_tmp[0]>0))
&&
(partonIsUnknown[1] || (PDGHelpers::isUpTypeQuark(MYIDUP_tmp[1]) && MYIDUP_tmp[1]>0))
&&
(partonIsUnknown[2] || (PDGHelpers::isUpTypeQuark(MYIDUP_tmp[2]) && MYIDUP_tmp[2]>0))
&&
(partonIsUnknown[3] || (PDGHelpers::isUpTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[3]>0))
){
isel=2; jsel=4; // uu'->(ZZ)->uu'
rsel=isel; ssel=jsel;
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &(msq_uu_zz_ijrs1234[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &(msq_uu_zz_ijrs1243[0]));
// Swapping i/j vs r/s makes no physical difference here.
msq_uu_zz_ijrs1234[1] = msq_uu_zz_ijrs1234[0];
msq_uu_zz_ijrs1243[1] = msq_uu_zz_ijrs1243[0];
isel=2; jsel=2; // uu->(ZZ)->uu
rsel=isel; ssel=jsel;
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &(msq_uu_zzid_ijrs1234[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &(msq_uu_zzid_ijrs1243[0]));
// Swapping i/j vs r/s makes no physical difference here.
msq_uu_zzid_ijrs1234[1] = msq_uu_zzid_ijrs1234[0];
msq_uu_zzid_ijrs1243[1] = msq_uu_zzid_ijrs1243[0];
}
if (
(partonIsUnknown[0] || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[0]) && MYIDUP_tmp[0]>0))
&&
(partonIsUnknown[1] || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[1]) && MYIDUP_tmp[1]>0))
&&
(partonIsUnknown[2] || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[2]) && MYIDUP_tmp[2]>0))
&&
(partonIsUnknown[3] || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[3]>0))
){
isel=1; jsel=3; // dd'->(ZZ)->dd'
rsel=isel; ssel=jsel;
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &(msq_dd_zz_ijrs1234[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &(msq_dd_zz_ijrs1243[0]));
// Swapping i/j vs r/s makes no physical difference here.
msq_dd_zz_ijrs1234[1] = msq_dd_zz_ijrs1234[0];
msq_dd_zz_ijrs1243[1] = msq_dd_zz_ijrs1243[0];
isel=1; jsel=1; // dd->(ZZ)->dd
rsel=isel; ssel=jsel;
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &(msq_dd_zzid_ijrs1234[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &(msq_dd_zzid_ijrs1243[0]));
// Swapping i/j vs r/s makes no physical difference here.
msq_dd_zzid_ijrs1234[1] = msq_dd_zzid_ijrs1234[0];
msq_dd_zzid_ijrs1243[1] = msq_dd_zzid_ijrs1243[0];
}
if (
(partonIsUnknown[0] || (PDGHelpers::isUpTypeQuark(MYIDUP_tmp[0]) && MYIDUP_tmp[0]<0))
&&
(partonIsUnknown[1] || (PDGHelpers::isUpTypeQuark(MYIDUP_tmp[1]) && MYIDUP_tmp[1]<0))
&&
(partonIsUnknown[2] || (PDGHelpers::isUpTypeQuark(MYIDUP_tmp[2]) && MYIDUP_tmp[2]<0))
&&
(partonIsUnknown[3] || (PDGHelpers::isUpTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[3]<0))
){
isel=-2; jsel=-4; // ubarubar'->(ZZ)->ubarubar'
rsel=isel; ssel=jsel;
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &(msq_ubarubar_zz_ijrs1234[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &(msq_ubarubar_zz_ijrs1243[0]));
// Swapping i/j vs r/s makes no physical difference here.
msq_ubarubar_zz_ijrs1234[1] = msq_ubarubar_zz_ijrs1234[0];
msq_ubarubar_zz_ijrs1243[1] = msq_ubarubar_zz_ijrs1243[0];
isel=-2; jsel=-2; // ubarubar->(ZZ)->ubarubar
rsel=isel; ssel=jsel;
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &(msq_ubarubar_zzid_ijrs1234[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &(msq_ubarubar_zzid_ijrs1243[0]));
// Swapping i/j vs r/s makes no physical difference here.
msq_ubarubar_zzid_ijrs1234[1] = msq_ubarubar_zzid_ijrs1234[0];
msq_ubarubar_zzid_ijrs1243[1] = msq_ubarubar_zzid_ijrs1243[0];
}
if (
(partonIsUnknown[0] || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[0]) && MYIDUP_tmp[0]<0))
&&
(partonIsUnknown[1] || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[1]) && MYIDUP_tmp[1]<0))
&&
(partonIsUnknown[2] || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[2]) && MYIDUP_tmp[2]<0))
&&
(partonIsUnknown[3] || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[3]<0))
){
isel=-1; jsel=-3; // dbardbar'->(ZZ)->dbardbar'
rsel=isel; ssel=jsel;
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &(msq_dbardbar_zz_ijrs1234[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &(msq_dbardbar_zz_ijrs1243[0]));
// Swapping i/j vs r/s makes no physical difference here.
msq_dbardbar_zz_ijrs1234[1] = msq_dbardbar_zz_ijrs1234[0];
msq_dbardbar_zz_ijrs1243[1] = msq_dbardbar_zz_ijrs1243[0];
isel=-1; jsel=-1; // dbardbar->(ZZ)->dbardbar
rsel=isel; ssel=jsel;
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &(msq_dbardbar_zzid_ijrs1234[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &(msq_dbardbar_zzid_ijrs1243[0]));
// Swapping i/j vs r/s makes no physical difference here.
msq_dbardbar_zzid_ijrs1234[1] = msq_dbardbar_zzid_ijrs1234[0];
msq_dbardbar_zzid_ijrs1243[1] = msq_dbardbar_zzid_ijrs1243[0];
}
if (
(
(partonIsUnknown[0] && partonIsUnknown[1])
||
(
(PDGHelpers::isUpTypeQuark(MYIDUP_tmp[0]) && MYIDUP_tmp[0]>0 && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[1]) && MYIDUP_tmp[1]<0)
||
(PDGHelpers::isUpTypeQuark(MYIDUP_tmp[1]) && MYIDUP_tmp[1]>0 && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[0]) && MYIDUP_tmp[0]<0)
)
||
(partonIsUnknown[0] && ((PDGHelpers::isUpTypeQuark(MYIDUP_tmp[1]) && MYIDUP_tmp[1]>0) || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[1]) && MYIDUP_tmp[1]<0)))
||
(partonIsUnknown[1] && ((PDGHelpers::isUpTypeQuark(MYIDUP_tmp[0]) && MYIDUP_tmp[0]>0) || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[0]) && MYIDUP_tmp[0]<0)))
)
&&
(
(partonIsUnknown[2] && partonIsUnknown[3])
||
(
(PDGHelpers::isUpTypeQuark(MYIDUP_tmp[2]) && MYIDUP_tmp[2]>0 && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[3]<0)
||
(PDGHelpers::isUpTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[3]>0 && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[2]) && MYIDUP_tmp[2]<0)
)
||
(partonIsUnknown[2] && ((PDGHelpers::isUpTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[3]>0) || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[3]<0)))
||
(partonIsUnknown[3] && ((PDGHelpers::isUpTypeQuark(MYIDUP_tmp[2]) && MYIDUP_tmp[2]>0) || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[2]) && MYIDUP_tmp[2]<0)))
)
){
isel=2; jsel=-1; // udbar->(ZZ)->udbar
rsel=isel; ssel=jsel;
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &(msq_udbar_zz_ijrs1234[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &(msq_udbar_zz_ijrs1243[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &jsel, &isel, &ssel, &rsel, &(msq_udbar_zz_ijrs1234[1]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &jsel, &isel, &rsel, &ssel, &(msq_udbar_zz_ijrs1243[1]));
}
if (
(
(partonIsUnknown[0] && partonIsUnknown[1])
||
(
(PDGHelpers::isUpTypeQuark(MYIDUP_tmp[0]) && MYIDUP_tmp[0]<0 && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[1]) && MYIDUP_tmp[1]>0)
||
(PDGHelpers::isUpTypeQuark(MYIDUP_tmp[1]) && MYIDUP_tmp[1]<0 && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[0]) && MYIDUP_tmp[0]>0)
)
||
(partonIsUnknown[0] && ((PDGHelpers::isUpTypeQuark(MYIDUP_tmp[1]) && MYIDUP_tmp[1]<0) || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[1]) && MYIDUP_tmp[1]>0)))
||
(partonIsUnknown[1] && ((PDGHelpers::isUpTypeQuark(MYIDUP_tmp[0]) && MYIDUP_tmp[0]<0) || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[0]) && MYIDUP_tmp[0]>0)))
)
&&
(
(partonIsUnknown[2] && partonIsUnknown[3])
||
(
(PDGHelpers::isUpTypeQuark(MYIDUP_tmp[2]) && MYIDUP_tmp[2]<0 && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[3]>0)
||
(PDGHelpers::isUpTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[3]<0 && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[2]) && MYIDUP_tmp[2]>0)
)
||
(partonIsUnknown[2] && ((PDGHelpers::isUpTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[3]<0) || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[3]>0)))
||
(partonIsUnknown[3] && ((PDGHelpers::isUpTypeQuark(MYIDUP_tmp[2]) && MYIDUP_tmp[2]<0) || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[2]) && MYIDUP_tmp[2]>0)))
)
){
isel=1; jsel=-2; // dubar->(ZZ)->dubar
rsel=isel; ssel=jsel;
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &(msq_dubar_zz_ijrs1234[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &(msq_dubar_zz_ijrs1243[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &jsel, &isel, &ssel, &rsel, &(msq_dubar_zz_ijrs1234[1]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &jsel, &isel, &rsel, &ssel, &(msq_dubar_zz_ijrs1243[1]));
}
if (
(partonIsUnknown[0] && partonIsUnknown[1])
||
(PDGHelpers::isUpTypeQuark(MYIDUP_tmp[0]) && PDGHelpers::isUpTypeQuark(MYIDUP_tmp[1]) && MYIDUP_tmp[0]*MYIDUP_tmp[1]<0)
||
(partonIsUnknown[0] && PDGHelpers::isUpTypeQuark(MYIDUP_tmp[1]))
||
(partonIsUnknown[1] && PDGHelpers::isUpTypeQuark(MYIDUP_tmp[0]))
){
isel=2; jsel=-2; // uubar->(ZZ)->uubar
if (
(partonIsUnknown[2] && partonIsUnknown[3])
||
(PDGHelpers::isUpTypeQuark(MYIDUP_tmp[2]) && PDGHelpers::isUpTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[2]*MYIDUP_tmp[3]<0)
||
(partonIsUnknown[2] && PDGHelpers::isUpTypeQuark(MYIDUP_tmp[3]))
||
(partonIsUnknown[3] && PDGHelpers::isUpTypeQuark(MYIDUP_tmp[2]))
){
rsel=isel; ssel=jsel; // uubar->(ZZ)->uubar
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &(msq_uubar_zz_ijrs1234[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &(msq_uubar_zz_ijrs1243[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &jsel, &isel, &ssel, &rsel, &(msq_uubar_zz_ijrs1234[1]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &jsel, &isel, &rsel, &ssel, &(msq_uubar_zz_ijrs1243[1]));
}
if (
(partonIsUnknown[2] && partonIsUnknown[3])
||
(PDGHelpers::isDownTypeQuark(MYIDUP_tmp[2]) && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[2]*MYIDUP_tmp[3]<0)
||
(partonIsUnknown[2] && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[3]))
||
(partonIsUnknown[3] && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[2]))
){
rsel=-1; ssel=1; // uubar->(WW)->ddbar
double ckm_ir = 0.;
double ckm_js = 0.;
while (ckm_ir==0.){
rsel += 2;
ssel -= 2;
if (abs(rsel)>=6){
rsel=-1; ssel=1;
isel+=2; jsel-=2;
continue;
}
if (abs(isel)>=6) break;
ckm_ir = __modparameters_MOD_ckmbare(&isel, &rsel);
ckm_js = __modparameters_MOD_ckmbare(&jsel, &ssel);
}
if (ckm_ir!=0.){
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &(msq_uubar_ww_ijrs1234[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &(msq_uubar_ww_ijrs1243[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &jsel, &isel, &ssel, &rsel, &(msq_uubar_ww_ijrs1234[1]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &jsel, &isel, &rsel, &ssel, &(msq_uubar_ww_ijrs1243[1]));
ckm_takeout = pow(ckm_ir*ckm_js, 2);
for (unsigned int iswap=0; iswap<2; iswap++){
msq_uubar_ww_ijrs1234[iswap] /= ckm_takeout;
msq_uubar_ww_ijrs1243[iswap] /= ckm_takeout;
}
}
}
}
if (
(partonIsUnknown[0] && partonIsUnknown[1])
||
(PDGHelpers::isDownTypeQuark(MYIDUP_tmp[0]) && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[1]) && MYIDUP_tmp[0]*MYIDUP_tmp[1]<0)
||
(partonIsUnknown[0] && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[1]))
||
(partonIsUnknown[1] && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[0]))
){
isel=1; jsel=-1;
if (
(partonIsUnknown[2] && partonIsUnknown[3])
||
(PDGHelpers::isDownTypeQuark(MYIDUP_tmp[2]) && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[2]*MYIDUP_tmp[3]<0)
||
(partonIsUnknown[2] && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[3]))
||
(partonIsUnknown[3] && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[2]))
){
rsel=isel; ssel=jsel; // ddbar->(ZZ)->ddbar
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &(msq_ddbar_zz_ijrs1234[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &(msq_ddbar_zz_ijrs1243[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &jsel, &isel, &ssel, &rsel, &(msq_ddbar_zz_ijrs1234[1]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &jsel, &isel, &rsel, &ssel, &(msq_ddbar_zz_ijrs1243[1]));
}
if (
(partonIsUnknown[2] && partonIsUnknown[3])
||
(PDGHelpers::isUpTypeQuark(MYIDUP_tmp[2]) && PDGHelpers::isUpTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[2]*MYIDUP_tmp[3]<0)
||
(partonIsUnknown[2] && PDGHelpers::isUpTypeQuark(MYIDUP_tmp[3]))
||
(partonIsUnknown[3] && PDGHelpers::isUpTypeQuark(MYIDUP_tmp[2]))
){
rsel=0; ssel=0; // ddbar->(WW)->uubar
double ckm_ir = 0.;
double ckm_js = 0.;
while (ckm_ir==0.){
rsel += 2;
ssel -= 2;
if (abs(rsel)>=6){
rsel=0; ssel=0;
isel+=2; jsel-=2;
continue;
}
if (abs(isel)>=6) break;
ckm_ir = __modparameters_MOD_ckmbare(&isel, &rsel);
ckm_js = __modparameters_MOD_ckmbare(&jsel, &ssel);
}
if (ckm_ir!=0.){
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &(msq_ddbar_ww_ijrs1234[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &(msq_ddbar_ww_ijrs1243[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &jsel, &isel, &ssel, &rsel, &(msq_ddbar_ww_ijrs1234[1]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &jsel, &isel, &rsel, &ssel, &(msq_ddbar_ww_ijrs1243[1]));
ckm_takeout = pow(ckm_ir*ckm_js, 2);
for (unsigned int iswap=0; iswap<2; iswap++){
msq_ddbar_ww_ijrs1234[iswap] /= ckm_takeout;
msq_ddbar_ww_ijrs1243[iswap] /= ckm_takeout;
}
}
}
}
if (
(
(partonIsUnknown[0] && partonIsUnknown[1])
||
(
(PDGHelpers::isUpTypeQuark(MYIDUP_tmp[0]) && MYIDUP_tmp[0]>0 && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[1]) && MYIDUP_tmp[1]>0)
||
(PDGHelpers::isUpTypeQuark(MYIDUP_tmp[1]) && MYIDUP_tmp[1]>0 && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[0]) && MYIDUP_tmp[0]>0)
)
||
(partonIsUnknown[0] && ((PDGHelpers::isUpTypeQuark(MYIDUP_tmp[1]) && MYIDUP_tmp[1]>0) || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[1]) && MYIDUP_tmp[1]>0)))
||
(partonIsUnknown[1] && ((PDGHelpers::isUpTypeQuark(MYIDUP_tmp[0]) && MYIDUP_tmp[0]>0) || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[0]) && MYIDUP_tmp[0]>0)))
)
&&
(
(partonIsUnknown[2] && partonIsUnknown[3])
||
(
(PDGHelpers::isUpTypeQuark(MYIDUP_tmp[2]) && MYIDUP_tmp[2]>0 && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[3]>0)
||
(PDGHelpers::isUpTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[3]>0 && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[2]) && MYIDUP_tmp[2]>0)
)
||
(partonIsUnknown[2] && ((PDGHelpers::isUpTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[3]>0) || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[3]>0)))
||
(partonIsUnknown[3] && ((PDGHelpers::isUpTypeQuark(MYIDUP_tmp[2]) && MYIDUP_tmp[2]>0) || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[2]) && MYIDUP_tmp[2]>0)))
)
){
// ud->(WW)->d'u'
double ckm_ir = 0.;
double ckm_js = 0.;
const unsigned int nCombinations = 6;
int ijrs_arr[nCombinations][4] ={
{ 2, 3, 1, 4 },
{ 2, 3, 5, 4 },
{ 2, 5, 1, 4 },
{ 2, 5, 3, 4 },
{ 2, 1, 3, 4 },
{ 2, 1, 5, 4 }
};
for (unsigned int ijrs=0; ijrs<nCombinations; ijrs++){
isel = ijrs_arr[ijrs][0];
jsel = ijrs_arr[ijrs][1];
rsel = ijrs_arr[ijrs][2];
ssel = ijrs_arr[ijrs][3];
ckm_ir = __modparameters_MOD_ckmbare(&isel, &rsel);
ckm_js = __modparameters_MOD_ckmbare(&jsel, &ssel);
if (ckm_ir!=0. && ckm_js!=0.) break;
}
if (ckm_ir!=0. && ckm_js!=0.){
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &(msq_ud_wwonly_ijrs1234[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &(msq_ud_wwonly_ijrs1243[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &jsel, &isel, &ssel, &rsel, &(msq_ud_wwonly_ijrs1234[1]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &jsel, &isel, &rsel, &ssel, &(msq_ud_wwonly_ijrs1243[1]));
ckm_takeout = pow(ckm_ir*ckm_js, 2);
for (unsigned int iswap=0; iswap<2; iswap++){
msq_ud_wwonly_ijrs1234[iswap] /= ckm_takeout;
msq_ud_wwonly_ijrs1243[iswap] /= ckm_takeout;
}
}
}
if (
(
(partonIsUnknown[0] && partonIsUnknown[1])
||
(
(PDGHelpers::isUpTypeQuark(MYIDUP_tmp[0]) && MYIDUP_tmp[0]<0 && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[1]) && MYIDUP_tmp[1]<0)
||
(PDGHelpers::isUpTypeQuark(MYIDUP_tmp[1]) && MYIDUP_tmp[1]<0 && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[0]) && MYIDUP_tmp[0]<0)
)
||
(partonIsUnknown[0] && ((PDGHelpers::isUpTypeQuark(MYIDUP_tmp[1]) && MYIDUP_tmp[1]<0) || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[1]) && MYIDUP_tmp[1]<0)))
||
(partonIsUnknown[1] && ((PDGHelpers::isUpTypeQuark(MYIDUP_tmp[0]) && MYIDUP_tmp[0]<0) || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[0]) && MYIDUP_tmp[0]<0)))
)
&&
(
(partonIsUnknown[2] && partonIsUnknown[3])
||
(
(PDGHelpers::isUpTypeQuark(MYIDUP_tmp[2]) && MYIDUP_tmp[2]<0 && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[3]<0)
||
(PDGHelpers::isUpTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[3]<0 && PDGHelpers::isDownTypeQuark(MYIDUP_tmp[2]) && MYIDUP_tmp[2]<0)
)
||
(partonIsUnknown[2] && ((PDGHelpers::isUpTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[3]<0) || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[3]) && MYIDUP_tmp[3]<0)))
||
(partonIsUnknown[3] && ((PDGHelpers::isUpTypeQuark(MYIDUP_tmp[2]) && MYIDUP_tmp[2]<0) || (PDGHelpers::isDownTypeQuark(MYIDUP_tmp[2]) && MYIDUP_tmp[2]<0)))
)
){
// ubardbar->(WW)->dbar'ubar'
double ckm_ir = 0.;
double ckm_js = 0.;
const unsigned int nCombinations = 6;
int ijrs_arr[nCombinations][4] ={
{ -2, -3, -1, -4 },
{ -2, -3, -5, -4 },
{ -2, -5, -1, -4 },
{ -2, -5, -3, -4 },
{ -2, -1, -3, -4 },
{ -2, -1, -5, -4 }
};
for (unsigned int ijrs=0; ijrs<nCombinations; ijrs++){
isel = ijrs_arr[ijrs][0];
jsel = ijrs_arr[ijrs][1];
rsel = ijrs_arr[ijrs][2];
ssel = ijrs_arr[ijrs][3];
ckm_ir = __modparameters_MOD_ckmbare(&isel, &rsel);
ckm_js = __modparameters_MOD_ckmbare(&jsel, &ssel);
if (ckm_ir!=0. && ckm_js!=0.) break;
}
if (ckm_ir!=0. && ckm_js!=0.){
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &(msq_ubardbar_wwonly_ijrs1234[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &(msq_ubardbar_wwonly_ijrs1243[0]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &jsel, &isel, &ssel, &rsel, &(msq_ubardbar_wwonly_ijrs1234[1]));
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &jsel, &isel, &rsel, &ssel, &(msq_ubardbar_wwonly_ijrs1243[1]));
ckm_takeout = pow(ckm_ir*ckm_js, 2);
for (unsigned int iswap=0; iswap<2; iswap++){
msq_ubardbar_wwonly_ijrs1234[iswap] /= ckm_takeout;
msq_ubardbar_wwonly_ijrs1243[iswap] /= ckm_takeout;
}
}
}
if (verbosity>=TVar::DEBUG_VERBOSE){
MELAout << "TUtil::HJJMatEl: The pre-computed MEs:" << endl;
for (unsigned int iswap=0; iswap<2; iswap++){
MELAout
<< "\tmsq_uu_zz_ijrs1234[" << iswap << "] = " << msq_uu_zz_ijrs1234[iswap] << '\n'
<< "\tmsq_uu_zz_ijrs1243[" << iswap << "] = " << msq_uu_zz_ijrs1243[iswap] << '\n'
<< "\tmsq_dd_zz_ijrs1234[" << iswap << "] = " << msq_dd_zz_ijrs1234[iswap] << '\n'
<< "\tmsq_dd_zz_ijrs1243[" << iswap << "] = " << msq_dd_zz_ijrs1243[iswap] << '\n'
<< "\tmsq_ubarubar_zz_ijrs1234[" << iswap << "] = " << msq_ubarubar_zz_ijrs1234[iswap] << '\n'
<< "\tmsq_ubarubar_zz_ijrs1243[" << iswap << "] = " << msq_ubarubar_zz_ijrs1243[iswap] << '\n'
<< "\tmsq_dbardbar_zz_ijrs1234[" << iswap << "] = " << msq_dbardbar_zz_ijrs1234[iswap] << '\n'
<< "\tmsq_dbardbar_zz_ijrs1243[" << iswap << "] = " << msq_dbardbar_zz_ijrs1243[iswap] << '\n'
<< "\tmsq_uu_zzid_ijrs1234[" << iswap << "] = " << msq_uu_zzid_ijrs1234[iswap] << '\n'
<< "\tmsq_uu_zzid_ijrs1243[" << iswap << "] = " << msq_uu_zzid_ijrs1243[iswap] << '\n'
<< "\tmsq_dd_zzid_ijrs1234[" << iswap << "] = " << msq_dd_zzid_ijrs1234[iswap] << '\n'
<< "\tmsq_dd_zzid_ijrs1243[" << iswap << "] = " << msq_dd_zzid_ijrs1243[iswap] << '\n'
<< "\tmsq_ubarubar_zzid_ijrs1234[" << iswap << "] = " << msq_ubarubar_zzid_ijrs1234[iswap] << '\n'
<< "\tmsq_ubarubar_zzid_ijrs1243[" << iswap << "] = " << msq_ubarubar_zzid_ijrs1243[iswap] << '\n'
<< "\tmsq_dbardbar_zzid_ijrs1234[" << iswap << "] = " << msq_dbardbar_zzid_ijrs1234[iswap] << '\n'
<< "\tmsq_dbardbar_zzid_ijrs1243[" << iswap << "] = " << msq_dbardbar_zzid_ijrs1243[iswap] << '\n'
<< "\tmsq_udbar_zz_ijrs1234[" << iswap << "] = " << msq_udbar_zz_ijrs1234[iswap] << '\n'
<< "\tmsq_udbar_zz_ijrs1243[" << iswap << "] = " << msq_udbar_zz_ijrs1243[iswap] << '\n'
<< "\tmsq_dubar_zz_ijrs1234[" << iswap << "] = " << msq_dubar_zz_ijrs1234[iswap] << '\n'
<< "\tmsq_dubar_zz_ijrs1243[" << iswap << "] = " << msq_dubar_zz_ijrs1243[iswap] << '\n'
<< "\tmsq_uubar_zz_ijrs1234[" << iswap << "] = " << msq_uubar_zz_ijrs1234[iswap] << '\n'
<< "\tmsq_uubar_zz_ijrs1243[" << iswap << "] = " << msq_uubar_zz_ijrs1243[iswap] << '\n'
<< "\tmsq_ddbar_zz_ijrs1234[" << iswap << "] = " << msq_ddbar_zz_ijrs1234[iswap] << '\n'
<< "\tmsq_ddbar_zz_ijrs1243[" << iswap << "] = " << msq_ddbar_zz_ijrs1243[iswap] << '\n'
<< "\tmsq_uubar_ww_ijrs1234[" << iswap << "] = " << msq_uubar_ww_ijrs1234[iswap] << '\n'
<< "\tmsq_uubar_ww_ijrs1243[" << iswap << "] = " << msq_uubar_ww_ijrs1243[iswap] << '\n'
<< "\tmsq_ddbar_ww_ijrs1234[" << iswap << "] = " << msq_ddbar_ww_ijrs1234[iswap] << '\n'
<< "\tmsq_ddbar_ww_ijrs1243[" << iswap << "] = " << msq_ddbar_ww_ijrs1243[iswap] << '\n'
<< "\tmsq_ud_wwonly_ijrs1234[" << iswap << "] = " << msq_ud_wwonly_ijrs1234[iswap] << '\n'
<< "\tmsq_ud_wwonly_ijrs1243[" << iswap << "] = " << msq_ud_wwonly_ijrs1243[iswap] << '\n'
<< "\tmsq_ubardbar_wwonly_ijrs1234[" << iswap << "] = " << msq_ubardbar_wwonly_ijrs1234[iswap] << '\n'
<< "\tmsq_ubardbar_wwonly_ijrs1243[" << iswap << "] = " << msq_ubardbar_wwonly_ijrs1243[iswap]
<< endl;
}
}
const std::vector<TNumericUtil::intTriplet_t>& ijsel = Get_JHUGenHash_OnshellVBFHash();
int nijchannels = ijsel.size();
// BEGIN COMPUTATION
for (int ic=0; ic<nijchannels; ic++){
// Emulate EvalWeighted_HJJ_test
isel = ijsel[ic][0];
jsel = ijsel[ic][1];
int code = ijsel[ic][2];
bool ijselIsUpType[2];
bool ijselIsDownType[2];
bool ijselIsParticle[2];
bool ijselIsAntiparticle[2];
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "VBF channel " << ic << " code " << code << endl;
// Default assignments
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "VBF mother unswapped case" << endl;
// Set r=i, s=j default values
rsel=isel;
ssel=jsel;
// Set i-j bools
ijselIsUpType[0] = (PDGHelpers::isUpTypeQuark(isel));
ijselIsUpType[1] = (PDGHelpers::isUpTypeQuark(jsel));
ijselIsDownType[0] = (PDGHelpers::isDownTypeQuark(isel));
ijselIsDownType[1] = (PDGHelpers::isDownTypeQuark(jsel));
ijselIsParticle[0] = (isel>0); ijselIsAntiparticle[0] = (isel<0);
ijselIsParticle[1] = (jsel>0); ijselIsAntiparticle[1] = (jsel<0);
if (
(partonIsUnknown[0] || MYIDUP_tmp[0]==isel)
&&
(partonIsUnknown[1] || MYIDUP_tmp[1]==jsel)
){ // Do it this way to be able to swap isel and jsel later
if (code==1){ // Only ZZ->H possible
// rsel=isel and ssel=jsel already
if (
(partonIsUnknown[2] || MYIDUP_tmp[2]==rsel)
&&
(partonIsUnknown[3] || MYIDUP_tmp[3]==ssel)
){
msq_tmp=0;
if (ijselIsUpType[0] && ijselIsUpType[1]){
if (ijselIsParticle[0] && ijselIsParticle[1]){
if (isel!=jsel) msq_tmp = msq_uu_zz_ijrs1234[0];
else msq_tmp = msq_uu_zzid_ijrs1234[0];
}
else if (ijselIsAntiparticle[0] && ijselIsAntiparticle[1]){
if (isel!=jsel) msq_tmp = msq_ubarubar_zz_ijrs1234[0];
else msq_tmp = msq_ubarubar_zzid_ijrs1234[0];
}
else if (ijselIsParticle[0] && ijselIsAntiparticle[1]) msq_tmp = msq_uubar_zz_ijrs1234[0];
}
else if (ijselIsDownType[0] && ijselIsDownType[1]){
if (ijselIsParticle[0] && ijselIsParticle[1]){
if (isel!=jsel) msq_tmp = msq_dd_zz_ijrs1234[0];
else msq_tmp = msq_dd_zzid_ijrs1234[0];
}
else if (ijselIsAntiparticle[0] && ijselIsAntiparticle[1]){
if (isel!=jsel) msq_tmp = msq_dbardbar_zz_ijrs1234[0];
else msq_tmp = msq_dbardbar_zzid_ijrs1234[0];
}
else if (ijselIsParticle[0] && ijselIsAntiparticle[1]) msq_tmp = msq_ddbar_zz_ijrs1234[0];
}
else if (ijselIsUpType[0] && ijselIsDownType[1] && ijselIsParticle[0] && ijselIsAntiparticle[1]) msq_tmp = msq_udbar_zz_ijrs1234[0];
else if (ijselIsDownType[0] && ijselIsUpType[1] && ijselIsParticle[0] && ijselIsAntiparticle[1]) msq_tmp = msq_dubar_zz_ijrs1234[0];
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << rsel << ", " << ssel << '\t' << msq_tmp << endl;
}
if (
rsel!=ssel
&&
(partonIsUnknown[2] || MYIDUP_tmp[2]==ssel)
&&
(partonIsUnknown[3] || MYIDUP_tmp[3]==rsel)
){
msq_tmp=0;
if (ijselIsUpType[0] && ijselIsUpType[1]){
if (ijselIsParticle[0] && ijselIsParticle[1]){
if (isel!=jsel) msq_tmp = msq_uu_zz_ijrs1243[0];
else msq_tmp = msq_uu_zzid_ijrs1243[0];
}
else if (ijselIsAntiparticle[0] && ijselIsAntiparticle[1]){
if (isel!=jsel) msq_tmp = msq_ubarubar_zz_ijrs1243[0];
else msq_tmp = msq_ubarubar_zzid_ijrs1243[0];
}
else if (ijselIsParticle[0] && ijselIsAntiparticle[1]) msq_tmp = msq_uubar_zz_ijrs1243[0];
}
else if (ijselIsDownType[0] && ijselIsDownType[1]){
if (ijselIsParticle[0] && ijselIsParticle[1]){
if (isel!=jsel) msq_tmp = msq_dd_zz_ijrs1243[0];
else msq_tmp = msq_dd_zzid_ijrs1243[0];
}
else if (ijselIsAntiparticle[0] && ijselIsAntiparticle[1]){
if (isel!=jsel) msq_tmp = msq_dbardbar_zz_ijrs1243[0];
else msq_tmp = msq_dbardbar_zzid_ijrs1243[0];
}
else if (ijselIsParticle[0] && ijselIsAntiparticle[1]) msq_tmp = msq_ddbar_zz_ijrs1243[0];
}
else if (ijselIsUpType[0] && ijselIsDownType[1] && ijselIsParticle[0] && ijselIsAntiparticle[1]) msq_tmp = msq_udbar_zz_ijrs1243[0];
else if (ijselIsDownType[0] && ijselIsUpType[1] && ijselIsParticle[0] && ijselIsAntiparticle[1]) msq_tmp = msq_dubar_zz_ijrs1243[0];
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << ssel << ", " << rsel << '\t' << msq_tmp << endl;
}
}
else if (code==0){ // code==0 means WW->H is also possible with no interference to ZZ->H, for example u ub -> d db.
vector<int> possible_rsel;
vector<int> possible_ssel;
vector<double> possible_Vsqir;
vector<double> possible_Vsqjs;
if (ijselIsUpType[0]){ possible_rsel.push_back(1); possible_rsel.push_back(3); possible_rsel.push_back(5); }
else if (ijselIsDownType[0]){ possible_rsel.push_back(2); possible_rsel.push_back(4); }
for (unsigned int ix=0; ix<possible_rsel.size(); ix++){
rsel=possible_rsel.at(ix);
double ckmval = pow(__modparameters_MOD_ckmbare(&isel, &rsel), 2);
possible_Vsqir.push_back(ckmval);
}
if (ijselIsUpType[1]){ possible_ssel.push_back(1); possible_ssel.push_back(3); possible_ssel.push_back(5); }
else if (ijselIsDownType[1]){ possible_ssel.push_back(2); possible_ssel.push_back(4); }
for (unsigned int iy=0; iy<possible_ssel.size(); iy++){
ssel=possible_ssel.at(iy);
double ckmval = pow(__modparameters_MOD_ckmbare(&jsel, &ssel), 2);
possible_Vsqjs.push_back(ckmval);
}
// Combine the ME and ME_swap based on actual ids
for (unsigned int ix=0; ix<possible_rsel.size(); ix++){
rsel=possible_rsel.at(ix)*TMath::Sign(1, isel);
for (unsigned int iy=0; iy<possible_ssel.size(); iy++){
ssel=possible_ssel.at(iy)*TMath::Sign(1, jsel);
double ckmval = possible_Vsqir.at(ix)*possible_Vsqjs.at(iy);
if (
(partonIsUnknown[2] || MYIDUP_tmp[2]==rsel)
&&
(partonIsUnknown[3] || MYIDUP_tmp[3]==ssel)
){
msq_tmp=0;
if (ijselIsUpType[0] && ijselIsUpType[1] && ijselIsParticle[0] && ijselIsAntiparticle[1]) msq_tmp = msq_uubar_ww_ijrs1234[0];
else if (ijselIsDownType[0] && ijselIsDownType[1] && ijselIsParticle[0] && ijselIsAntiparticle[1]) msq_tmp = msq_ddbar_ww_ijrs1234[0];
msq_tmp *= ckmval;
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << rsel << ", " << ssel << '\t' << msq_tmp << endl;
}
if (
rsel!=ssel
&&
(partonIsUnknown[2] || MYIDUP_tmp[2]==ssel)
&&
(partonIsUnknown[3] || MYIDUP_tmp[3]==rsel)
){
msq_tmp=0;
if (ijselIsUpType[0] && ijselIsUpType[1] && ijselIsParticle[0] && ijselIsAntiparticle[1]) msq_tmp = msq_uubar_ww_ijrs1243[0];
else if (ijselIsDownType[0] && ijselIsDownType[1] && ijselIsParticle[0] && ijselIsAntiparticle[1]) msq_tmp = msq_ddbar_ww_ijrs1243[0];
msq_tmp *= ckmval;
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << ssel << ", " << rsel << '\t' << msq_tmp << endl;
}
}
}
}
else{ // code==2 means states with WW/ZZ interference allowed, for example u1 d2 -> u3 d4 + d4 u3.
vector<int> possible_rsel;
vector<int> possible_ssel;
vector<double> possible_Vsqir;
vector<double> possible_Vsqjs;
if (ijselIsUpType[0]){ possible_rsel.push_back(1); possible_rsel.push_back(3); possible_rsel.push_back(5); }
else if (ijselIsDownType[0]){ possible_rsel.push_back(2); possible_rsel.push_back(4); }
for (unsigned int ix=0; ix<possible_rsel.size(); ix++){
rsel=possible_rsel.at(ix);
double ckmval = pow(__modparameters_MOD_ckmbare(&isel, &rsel), 2);
possible_Vsqir.push_back(ckmval);
}
if (ijselIsUpType[1]){ possible_ssel.push_back(1); possible_ssel.push_back(3); possible_ssel.push_back(5); }
else if (ijselIsDownType[1]){ possible_ssel.push_back(2); possible_ssel.push_back(4); }
for (unsigned int iy=0; iy<possible_ssel.size(); iy++){
ssel=possible_ssel.at(iy);
double ckmval = pow(__modparameters_MOD_ckmbare(&jsel, &ssel), 2);
possible_Vsqjs.push_back(ckmval);
}
// Loop over all possible combinations to get interference correct
for (unsigned int ix=0; ix<possible_rsel.size(); ix++){
rsel=possible_rsel.at(ix)*TMath::Sign(1, isel);
for (unsigned int iy=0; iy<possible_ssel.size(); iy++){
ssel=possible_ssel.at(iy)*TMath::Sign(1, jsel);
double ckmval = possible_Vsqir.at(ix)*possible_Vsqjs.at(iy);
if (
(partonIsUnknown[2] || MYIDUP_tmp[2]==rsel)
&&
(partonIsUnknown[3] || MYIDUP_tmp[3]==ssel)
){
if (rsel!=jsel && ssel!=isel){
msq_tmp=0;
if (ijselIsUpType[0] && ijselIsDownType[1]){
if (ijselIsParticle[0] && ijselIsParticle[1]) msq_tmp = msq_ud_wwonly_ijrs1234[0];
else if (ijselIsAntiparticle[0] && ijselIsAntiparticle[1]) msq_tmp = msq_ubardbar_wwonly_ijrs1234[0];
}
msq_tmp *= ckmval;
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << rsel << ", " << ssel << '\t' << msq_tmp << endl;
}
else{
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << rsel << ", " << ssel << '\t' << msq_tmp << endl;
}
}
if (
rsel!=ssel
&&
(partonIsUnknown[2] || MYIDUP_tmp[2]==ssel)
&&
(partonIsUnknown[3] || MYIDUP_tmp[3]==rsel)
){
if (rsel!=jsel && ssel!=isel){
msq_tmp=0;
if (ijselIsUpType[0] && ijselIsDownType[1]){
if (ijselIsParticle[0] && ijselIsParticle[1]) msq_tmp = msq_ud_wwonly_ijrs1243[0];
else if (ijselIsAntiparticle[0] && ijselIsAntiparticle[1]) msq_tmp = msq_ubardbar_wwonly_ijrs1243[0];
}
msq_tmp *= ckmval;
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << ssel << ", " << rsel << '\t' << msq_tmp << endl;
}
else{
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << ssel << ", " << rsel << '\t' << msq_tmp << endl;
}
}
}
}
}
} // End unswapped isel>=jsel cases
if (isel==jsel) continue;
isel = ijsel[ic][1];
jsel = ijsel[ic][0];
// Reset to default assignments
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "VBF mother swapped case" << endl;
// Set r=i, s=j default values
rsel=isel;
ssel=jsel;
// Set i-j bools
ijselIsUpType[0] = (PDGHelpers::isUpTypeQuark(isel));
ijselIsUpType[1] = (PDGHelpers::isUpTypeQuark(jsel));
ijselIsDownType[0] = (PDGHelpers::isDownTypeQuark(isel));
ijselIsDownType[1] = (PDGHelpers::isDownTypeQuark(jsel));
ijselIsParticle[0] = (isel>0); ijselIsAntiparticle[0] = (isel<0);
ijselIsParticle[1] = (jsel>0); ijselIsAntiparticle[1] = (jsel<0);
if (
(partonIsUnknown[0] || ((PDGHelpers::isAGluon(MYIDUP_tmp[0]) && isel==0) || MYIDUP_tmp[0]==isel))
&&
(partonIsUnknown[1] || ((PDGHelpers::isAGluon(MYIDUP_tmp[1]) && jsel==0) || MYIDUP_tmp[1]==jsel))
){
// isel==jsel==0 is already eliminated by isel!=jsel condition
if (code==1){ // Only ZZ->H possible
// rsel=isel and ssel=jsel already
if (
(partonIsUnknown[2] || MYIDUP_tmp[2]==rsel)
&&
(partonIsUnknown[3] || MYIDUP_tmp[3]==ssel)
){
msq_tmp=0;
if (ijselIsUpType[1] && ijselIsUpType[0]){
if (ijselIsParticle[1] && ijselIsParticle[0]){
if (isel!=jsel) msq_tmp = msq_uu_zz_ijrs1234[1];
else msq_tmp = msq_uu_zzid_ijrs1234[1];
}
else if (ijselIsAntiparticle[1] && ijselIsAntiparticle[0]){
if (isel!=jsel) msq_tmp = msq_ubarubar_zz_ijrs1234[1];
else msq_tmp = msq_ubarubar_zzid_ijrs1234[1];
}
else if (ijselIsParticle[1] && ijselIsAntiparticle[0]) msq_tmp = msq_uubar_zz_ijrs1234[1];
}
else if (ijselIsDownType[1] && ijselIsDownType[0]){
if (ijselIsParticle[1] && ijselIsParticle[0]){
if (isel!=jsel) msq_tmp = msq_dd_zz_ijrs1234[1];
else msq_tmp = msq_dd_zzid_ijrs1234[1];
}
else if (ijselIsAntiparticle[1] && ijselIsAntiparticle[0]){
if (isel!=jsel) msq_tmp = msq_dbardbar_zz_ijrs1234[1];
else msq_tmp = msq_dbardbar_zzid_ijrs1234[1];
}
else if (ijselIsParticle[1] && ijselIsAntiparticle[0]) msq_tmp = msq_ddbar_zz_ijrs1234[1];
}
else if (ijselIsUpType[1] && ijselIsDownType[0] && ijselIsParticle[1] && ijselIsAntiparticle[0]) msq_tmp = msq_udbar_zz_ijrs1234[1];
else if (ijselIsDownType[1] && ijselIsUpType[0] && ijselIsParticle[1] && ijselIsAntiparticle[0]) msq_tmp = msq_dubar_zz_ijrs1234[1];
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << rsel << ", " << ssel << '\t' << msq_tmp << endl;
}
if (
rsel!=ssel
&&
(partonIsUnknown[2] || MYIDUP_tmp[2]==ssel)
&&
(partonIsUnknown[3] || MYIDUP_tmp[3]==rsel)
){
msq_tmp=0;
if (ijselIsUpType[1] && ijselIsUpType[0]){
if (ijselIsParticle[1] && ijselIsParticle[0]){
if (isel!=jsel) msq_tmp = msq_uu_zz_ijrs1243[1];
else msq_tmp = msq_uu_zzid_ijrs1243[1];
}
else if (ijselIsAntiparticle[1] && ijselIsAntiparticle[0]){
if (isel!=jsel) msq_tmp = msq_ubarubar_zz_ijrs1243[1];
else msq_tmp = msq_ubarubar_zzid_ijrs1243[1];
}
else if (ijselIsParticle[1] && ijselIsAntiparticle[0]) msq_tmp = msq_uubar_zz_ijrs1243[1];
}
else if (ijselIsDownType[1] && ijselIsDownType[0]){
if (ijselIsParticle[1] && ijselIsParticle[0]){
if (isel!=jsel) msq_tmp = msq_dd_zz_ijrs1243[1];
else msq_tmp = msq_dd_zzid_ijrs1243[1];
}
else if (ijselIsAntiparticle[1] && ijselIsAntiparticle[0]){
if (isel!=jsel) msq_tmp = msq_dbardbar_zz_ijrs1243[1];
else msq_tmp = msq_dbardbar_zzid_ijrs1243[1];
}
else if (ijselIsParticle[1] && ijselIsAntiparticle[0]) msq_tmp = msq_ddbar_zz_ijrs1243[1];
}
else if (ijselIsUpType[1] && ijselIsDownType[0] && ijselIsParticle[1] && ijselIsAntiparticle[0]) msq_tmp = msq_udbar_zz_ijrs1243[1];
else if (ijselIsDownType[1] && ijselIsUpType[0] && ijselIsParticle[1] && ijselIsAntiparticle[0]) msq_tmp = msq_dubar_zz_ijrs1243[1];
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << ssel << ", " << rsel << '\t' << msq_tmp << endl;
}
}
else if (code==0){ // code==0 means WW->H is also possible with no interference to ZZ->H, for example u ub -> d db.
vector<int> possible_rsel;
vector<int> possible_ssel;
vector<double> possible_Vsqir;
vector<double> possible_Vsqjs;
if (ijselIsUpType[0]){ possible_rsel.push_back(1); possible_rsel.push_back(3); possible_rsel.push_back(5); }
else if (ijselIsDownType[0]){ possible_rsel.push_back(2); possible_rsel.push_back(4); }
for (unsigned int ix=0; ix<possible_rsel.size(); ix++){
rsel=possible_rsel.at(ix);
double ckmval = pow(__modparameters_MOD_ckmbare(&isel, &rsel), 2);
possible_Vsqir.push_back(ckmval);
}
if (ijselIsUpType[1]){ possible_ssel.push_back(1); possible_ssel.push_back(3); possible_ssel.push_back(5); }
else if (ijselIsDownType[1]){ possible_ssel.push_back(2); possible_ssel.push_back(4); }
for (unsigned int iy=0; iy<possible_ssel.size(); iy++){
ssel=possible_ssel.at(iy);
double ckmval = pow(__modparameters_MOD_ckmbare(&jsel, &ssel), 2);
possible_Vsqjs.push_back(ckmval);
}
// Combine the ME and ME_swap based on actual ids
for (unsigned int ix=0; ix<possible_rsel.size(); ix++){
rsel=possible_rsel.at(ix)*TMath::Sign(1, isel);
for (unsigned int iy=0; iy<possible_ssel.size(); iy++){
ssel=possible_ssel.at(iy)*TMath::Sign(1, jsel);
double ckmval = possible_Vsqir.at(ix)*possible_Vsqjs.at(iy);
if (
(partonIsUnknown[2] || MYIDUP_tmp[2]==rsel)
&&
(partonIsUnknown[3] || MYIDUP_tmp[3]==ssel)
){
msq_tmp=0;
if (ijselIsUpType[1] && ijselIsUpType[0] && ijselIsParticle[1] && ijselIsAntiparticle[0]) msq_tmp = msq_uubar_ww_ijrs1234[1];
else if (ijselIsDownType[1] && ijselIsDownType[0] && ijselIsParticle[1] && ijselIsAntiparticle[0]) msq_tmp = msq_ddbar_ww_ijrs1234[1];
msq_tmp *= ckmval;
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << rsel << ", " << ssel << '\t' << msq_tmp << endl;
}
if (
rsel!=ssel
&&
(partonIsUnknown[2] || MYIDUP_tmp[2]==ssel)
&&
(partonIsUnknown[3] || MYIDUP_tmp[3]==rsel)
){
msq_tmp=0;
if (ijselIsUpType[1] && ijselIsUpType[0] && ijselIsParticle[1] && ijselIsAntiparticle[0]) msq_tmp = msq_uubar_ww_ijrs1243[1];
else if (ijselIsDownType[1] && ijselIsDownType[0] && ijselIsParticle[1] && ijselIsAntiparticle[0]) msq_tmp = msq_ddbar_ww_ijrs1243[1];
msq_tmp *= ckmval;
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << ssel << ", " << rsel << '\t' << msq_tmp << endl;
}
}
}
}
else{ // code==2 means states with WW/ZZ interference allowed, for example u1 d2 -> u3 d4 + d4 u3.
vector<int> possible_rsel;
vector<int> possible_ssel;
vector<double> possible_Vsqir;
vector<double> possible_Vsqjs;
if (ijselIsUpType[0]){ possible_rsel.push_back(1); possible_rsel.push_back(3); possible_rsel.push_back(5); }
else if (ijselIsDownType[0]){ possible_rsel.push_back(2); possible_rsel.push_back(4); }
for (unsigned int ix=0; ix<possible_rsel.size(); ix++){
rsel=possible_rsel.at(ix);
double ckmval = pow(__modparameters_MOD_ckmbare(&isel, &rsel), 2);
possible_Vsqir.push_back(ckmval);
}
if (ijselIsUpType[1]){ possible_ssel.push_back(1); possible_ssel.push_back(3); possible_ssel.push_back(5); }
else if (ijselIsDownType[1]){ possible_ssel.push_back(2); possible_ssel.push_back(4); }
for (unsigned int iy=0; iy<possible_ssel.size(); iy++){
ssel=possible_ssel.at(iy);
double ckmval = pow(__modparameters_MOD_ckmbare(&jsel, &ssel), 2);
possible_Vsqjs.push_back(ckmval);
}
// Loop over all possible combinations to get interference correct
for (unsigned int ix=0; ix<possible_rsel.size(); ix++){
rsel=possible_rsel.at(ix)*TMath::Sign(1, isel);
for (unsigned int iy=0; iy<possible_ssel.size(); iy++){
ssel=possible_ssel.at(iy)*TMath::Sign(1, jsel);
double ckmval = possible_Vsqir.at(ix)*possible_Vsqjs.at(iy);
if (
(partonIsUnknown[2] || MYIDUP_tmp[2]==rsel)
&&
(partonIsUnknown[3] || MYIDUP_tmp[3]==ssel)
){
if (rsel!=jsel && ssel!=isel){
msq_tmp=0;
if (ijselIsUpType[1] && ijselIsDownType[0]){
if (ijselIsParticle[1] && ijselIsParticle[0]) msq_tmp = msq_ud_wwonly_ijrs1234[1];
else if (ijselIsAntiparticle[1] && ijselIsAntiparticle[0]) msq_tmp = msq_ubardbar_wwonly_ijrs1234[1];
}
msq_tmp *= ckmval;
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << rsel << ", " << ssel << '\t' << msq_tmp << endl;
}
else{
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &rsel, &ssel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << rsel << ", " << ssel << '\t' << msq_tmp << endl;
}
}
if (
rsel!=ssel
&&
(partonIsUnknown[2] || MYIDUP_tmp[2]==ssel)
&&
(partonIsUnknown[3] || MYIDUP_tmp[3]==rsel)
){
if (rsel!=jsel && ssel!=isel){
msq_tmp=0;
if (ijselIsUpType[1] && ijselIsDownType[0]){
if (ijselIsParticle[1] && ijselIsParticle[0]) msq_tmp = msq_ud_wwonly_ijrs1243[1];
else if (ijselIsAntiparticle[1] && ijselIsAntiparticle[0]) msq_tmp = msq_ubardbar_wwonly_ijrs1243[1];
}
msq_tmp *= ckmval;
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << ssel << ", " << rsel << '\t' << msq_tmp << endl;
}
else{
__modhiggsjj_MOD_evalamp_wbfh_unsymm_sa_select_exact(p4, &isel, &jsel, &ssel, &rsel, &msq_tmp);
MatElsq[jsel+5][isel+5] += msq_tmp; // Assign only those that match gen. info, if present at all.
if (verbosity >= TVar::DEBUG_VERBOSE) MELAout << "Channel (isel, jsel, rsel, ssel)=" << isel << ", " << jsel << ", " << ssel << ", " << rsel << '\t' << msq_tmp << endl;
}
}
}
}
}
} // End swapped isel<jsel cases
} // End loop over ic<nijchannels
// END COMPUTATION
} // End production == TVar::JJVBF
int GeVexponent_MEsq = 4-(1+nRequested_AssociatedJets)*2;
double constant = pow(GeV, -GeVexponent_MEsq);
for (int ii=0; ii<nmsq; ii++){ for (int jj=0; jj<nmsq; jj++) MatElsq[jj][ii] *= constant; }
// FOTRAN convention -5 -4 -3 -2 -1 0 1 2 3 4 5
// parton flavor bbar cbar sbar ubar dbar g d u s c b
// C++ convention 0 1 2 3 4 5 6 7 8 9 10
if (verbosity >= TVar::DEBUG){
MELAout << "MatElsq:\n";
for (int ii = 0; ii < nmsq; ii++){ for (int jj = 0; jj < nmsq; jj++) MELAout << MatElsq[jj][ii] << '\t'; MELAout << endl; }
}
sum_msqjk = SumMEPDF(MomStore[0], MomStore[1], MatElsq, RcdME, EBEAM, verbosity);
/*
if (verbosity >= TVar::ERROR && (std::isnan(sum_msqjk) || std::isinf(sum_msqjk))){
MELAout << "TUtil::HJJMatEl: FAILURE!" << endl;
MELAout << "MatElsq:\n";
for (int ii = 0; ii < nmsq; ii++){ for (int jj = 0; jj < nmsq; jj++) MELAout << MatElsq[jj][ii] << '\t'; MELAout << endl; }
double fx[2][nmsq];
RcdME->getPartonWeights(fx[0], fx[1]);
for (int ii = 0; ii < nmsq; ii++){ for (int jj = 0; jj < 2; jj++) MELAout << fx[jj][ii] << '\t'; MELAout << endl; }
for (int i=0; i<5; i++) MELAout << "p["<<i<<"] (Px, Py, Pz, E, M):\t" << p4[i][1]/GeV << '\t' << p4[i][2]/GeV << '\t' << p4[i][3]/GeV << '\t' << p4[i][0]/GeV << '\t' << sqrt(fabs(pow(p4[i][0], 2)-pow(p4[i][1], 2)-pow(p4[i][2], 2)-pow(p4[i][3], 2)))/GeV << endl;
TUtil::PrintCandidateSummary(RcdME->melaCand);
MELAout << endl;
}
*/
if (verbosity>=TVar::DEBUG){
MELAout
<< "TUtil::HJJMatEl: Reset AlphaS:\n"
<< "\tBefore reset, alphas scale: " << scale_.scale << ", PDF scale: " << facscale_.facscale << endl;
}
SetAlphaS(defaultRenScale, defaultFacScale, 1., 1., defaultNloop, defaultNflav, defaultPdflabel);
if (verbosity>=TVar::DEBUG){
GetAlphaS(&alphasVal, &alphasmzVal);
MELAout
<< "TUtil::HJJMatEl: Reset AlphaS result:\n"
<< "\tAfter reset, alphas scale: " << scale_.scale << ", PDF scale: " << facscale_.facscale << ", alphas(Qren): " << alphasVal << ", alphas(MZ): " << alphasmzVal << endl;
}
return sum_msqjk;
}
// VH, H undecayed or Hbb
double TUtil::VHiggsMatEl(
const TVar::Process& process, const TVar::Production& production, const TVar::MatrixElement& matrixElement,
event_scales_type* event_scales, MelaIO* RcdME,
const double& EBEAM,
bool includeHiggsDecay,
TVar::VerbosityLevel verbosity
){
const double GeV=1./100.; // JHUGen mom. scale factor
double sum_msqjk = 0;
// by default assume only gg productions
// FOTRAN convention -5 -4 -3 -2 -1 0 1 2 3 4 5
// parton flavor bbar cbar sbar ubar dbar g d u s c b
// C++ convention 0 1 2 3 4 5 6 7 8 9 10
//2-D matrix is reversed in fortran
// msq[ parton2 ] [ parton1 ]
// flavor_msq[jj][ii] = fx1[ii]*fx2[jj]*msq[jj][ii];
double MatElsq[nmsq][nmsq]={ { 0 } };
if (matrixElement!=TVar::JHUGen){ if (verbosity>=TVar::ERROR) MELAerr << "TUtil::VHiggsMatEl: Non-JHUGen MEs are not supported" << endl; return sum_msqjk; }
if (!(production == TVar::Lep_ZH || production == TVar::Lep_WH || production == TVar::Had_ZH || production == TVar::Had_WH || production == TVar::GammaH)){ if (verbosity>=TVar::ERROR) MELAerr << "TUtil::VHiggsMatEl: Production is not supported!" << endl; return sum_msqjk; }
int nRequested_AssociatedJets=0;
int nRequested_AssociatedLeptons=0;
int nRequested_AssociatedPhotons=0;
int AssociationVCompatibility=0;
int partIncCode=TVar::kNoAssociated; // Just to avoid warnings
if (production == TVar::Had_ZH || production == TVar::Had_WH){ // Only use associated partons
partIncCode=TVar::kUseAssociated_Jets;
nRequested_AssociatedJets=2;
}
else if (production == TVar::Lep_ZH || production == TVar::Lep_WH){ // Only use associated leptons(+)neutrinos
partIncCode=TVar::kUseAssociated_Leptons;
nRequested_AssociatedLeptons=2;
}
else if (production == TVar::GammaH){ // Only use associated photon
partIncCode=TVar::kUseAssociated_Photons;
nRequested_AssociatedPhotons=1;
}
if (production == TVar::Lep_WH || production == TVar::Had_WH) AssociationVCompatibility=24;
else if (production == TVar::Lep_ZH || production == TVar::Had_ZH) AssociationVCompatibility=23;
else if (production == TVar::GammaH) AssociationVCompatibility=22;
simple_event_record mela_event;
mela_event.AssociationCode=partIncCode;
mela_event.AssociationVCompatibility=AssociationVCompatibility;
mela_event.nRequested_AssociatedJets=nRequested_AssociatedJets;
mela_event.nRequested_AssociatedLeptons=nRequested_AssociatedLeptons;
mela_event.nRequested_AssociatedPhotons=nRequested_AssociatedPhotons;
GetBoostedParticleVectors(
RcdME->melaCand,
mela_event,
verbosity
);
if ((mela_event.pAssociated.size()<(unsigned int)(nRequested_AssociatedJets+nRequested_AssociatedLeptons) && production!=TVar::GammaH) || (mela_event.pAssociated.size()<(unsigned int)nRequested_AssociatedPhotons && production == TVar::GammaH)){
if (verbosity>=TVar::ERROR){
MELAerr << "TUtil::VHiggsMatEl: Number of associated particles (" << mela_event.pAssociated.size() << ") is less than ";
if (production!=TVar::GammaH) MELAerr << (nRequested_AssociatedJets+nRequested_AssociatedLeptons);
else MELAerr << nRequested_AssociatedPhotons;
MELAerr << endl;
}
return sum_msqjk;
}
int MYIDUP_prod[4]={ 0 }; // "Incoming" partons 1, 2, "outgoing" partons 3, 4
int MYIDUP_dec[2]={ -9000, -9000 }; // "Outgoing" partons 1, 2 from the Higgs (->bb)
double p4[9][4] ={ { 0 } };
double helicities[9] ={ 0 };
int vh_ids[9] ={ 0 };
TLorentzVector MomStore[mxpart];
for (int i = 0; i < mxpart; i++) MomStore[i].SetXYZT(0, 0, 0, 0);
// p4(0:8,i) = (E(i),px(i),py(i),pz(i))
// i=0,1: q1, qb2 (outgoing convention)
// i=2,3: V*, V
// i=4: H
// i=5,6: f, fb from V
// i=7,8: b, bb from H
for (int ipar=0; ipar<2; ipar++){
TLorentzVector* momTmp = &(mela_event.pMothers.at(ipar).second);
int* idtmp = &(mela_event.pMothers.at(ipar).first);
if (!PDGHelpers::isAnUnknownJet(*idtmp)) MYIDUP_prod[ipar] = *idtmp;
else MYIDUP_prod[ipar] = 0;
if (momTmp->T()>0.){
p4[ipar][0] = momTmp->T()*GeV;
p4[ipar][1] = momTmp->X()*GeV;
p4[ipar][2] = momTmp->Y()*GeV;
p4[ipar][3] = momTmp->Z()*GeV;
MomStore[ipar] = (*momTmp);
}
else{
p4[ipar][0] = -momTmp->T()*GeV;
p4[ipar][1] = -momTmp->X()*GeV;
p4[ipar][2] = -momTmp->Y()*GeV;
p4[ipar][3] = -momTmp->Z()*GeV;
MomStore[ipar] = -(*momTmp);
MYIDUP_prod[ipar] = -MYIDUP_prod[ipar];
}
}
// Associated particles
for (int ipar=0; ipar<(production!=TVar::GammaH ? 2 : 1); ipar++){
TLorentzVector* momTmp = &(mela_event.pAssociated.at(ipar).second);
int* idtmp = &(mela_event.pAssociated.at(ipar).first);
if (!PDGHelpers::isAnUnknownJet(*idtmp)) MYIDUP_prod[ipar+2] = *idtmp;
else MYIDUP_prod[ipar+2] = 0;
p4[ipar+5][0] = momTmp->T()*GeV;
p4[ipar+5][1] = momTmp->X()*GeV;
p4[ipar+5][2] = momTmp->Y()*GeV;
p4[ipar+5][3] = momTmp->Z()*GeV;
MomStore[ipar+6] = (*momTmp);
}
if (production == TVar::GammaH) MYIDUP_prod[3]=-9000;
if (PDGHelpers::isAGluon(MYIDUP_prod[0]) || PDGHelpers::isAGluon(MYIDUP_prod[1])){ if (verbosity>=TVar::INFO) MELAerr << "TUtil::VHiggsMatEl: Initial state gluons are not permitted!" << endl; return sum_msqjk; }
if (PDGHelpers::isAGluon(MYIDUP_prod[2]) || PDGHelpers::isAGluon(MYIDUP_prod[3])){ if (verbosity>=TVar::INFO) MELAerr << "TUtil::VHiggsMatEl: Final state gluons are not permitted!" << endl; return sum_msqjk; }
if (production == TVar::GammaH && !PDGHelpers::isAPhoton(MYIDUP_prod[2])){ if (verbosity>=TVar::ERROR) MELAerr << "TUtil::VHiggsMatEl: GammaH associated photon (id=" << MYIDUP_prod[2] << ") is not a photon! Please fix its id." << endl; return sum_msqjk; }
// Decay V/f ids
// MYIDUP_dec as size=2 because JHUGen supports b-bbar decay
for (int iv=0; iv<2; iv++){
int idtmp = mela_event.intermediateVid.at(iv);
if (!PDGHelpers::isAnUnknownJet(idtmp)) MYIDUP_dec[iv] = idtmp;
else MYIDUP_dec[iv] = 0;
}
// Decay daughters
for (unsigned int ipar=0; ipar<mela_event.pDaughters.size(); ipar++){
TLorentzVector* momTmp = &(mela_event.pDaughters.at(ipar).second);
if (mela_event.pDaughters.size()==1){
p4[ipar+7][0] = momTmp->T()*GeV;
p4[ipar+7][1] = momTmp->X()*GeV;
p4[ipar+7][2] = momTmp->Y()*GeV;
p4[ipar+7][3] = momTmp->Z()*GeV;
MomStore[5] = (*momTmp); // 5
}
else if (mela_event.pDaughters.size()==2){
p4[ipar+7][0] = momTmp->T()*GeV;
p4[ipar+7][1] = momTmp->X()*GeV;
p4[ipar+7][2] = momTmp->Y()*GeV;
p4[ipar+7][3] = momTmp->Z()*GeV;
MomStore[2*ipar+2] = (*momTmp); // 2,4
if (PDGHelpers::isAQuark(mela_event.pDaughters.at(ipar).first)) MYIDUP_dec[ipar]=mela_event.pDaughters.at(ipar).first;
}
else if (mela_event.pDaughters.size()==3){
if (ipar<2){
p4[7][0] += momTmp->T()*GeV;
p4[7][1] += momTmp->X()*GeV;
p4[7][2] += momTmp->Y()*GeV;
p4[7][3] += momTmp->Z()*GeV;
}
else{
p4[8][0] = momTmp->T()*GeV;
p4[8][1] = momTmp->X()*GeV;
p4[8][2] = momTmp->Y()*GeV;
p4[8][3] = momTmp->Z()*GeV;
}
MomStore[ipar+2] = (*momTmp); // 2,3,4
}
else if (mela_event.pDaughters.size()==4){
if (ipar<2){
p4[7][0] += momTmp->T()*GeV;
p4[7][1] += momTmp->X()*GeV;
p4[7][2] += momTmp->Y()*GeV;
p4[7][3] += momTmp->Z()*GeV;
}
else{
p4[8][0] += momTmp->T()*GeV;
p4[8][1] += momTmp->X()*GeV;
p4[8][2] += momTmp->Y()*GeV;
p4[8][3] += momTmp->Z()*GeV;
}
MomStore[ipar+2] = (*momTmp); // 2,3,4,5
}
else{ // Should never happen
p4[7][0] += momTmp->T()*GeV;
p4[7][1] += momTmp->X()*GeV;
p4[7][2] += momTmp->Y()*GeV;
p4[7][3] += momTmp->Z()*GeV;
MomStore[5] = MomStore[5] + (*momTmp);
}
}
for (int ix=0; ix<4; ix++){
p4[3][ix] = p4[5][ix] + p4[6][ix];
p4[4][ix] = p4[7][ix] + p4[8][ix];
p4[2][ix] = p4[3][ix] + p4[4][ix];
}
vh_ids[4] = 25;
if (production == TVar::Lep_ZH || production == TVar::Had_ZH || production == TVar::GammaH) vh_ids[2] = 23;
else if (production == TVar::Lep_WH || production == TVar::Had_WH) vh_ids[2] = 24; // To be changed later
if (production!=TVar::GammaH) vh_ids[3] = vh_ids[2]; // To be changed later for WH
else vh_ids[3] = 22;
// H->ffb decay is turned off, so no need to loop over helicities[7]=helicities[8]=+-1
vh_ids[7] = 5; helicities[7] = 1;
vh_ids[8] = -5; helicities[8] = 1;
int HDKon = 0;
if (includeHiggsDecay && MYIDUP_dec[0]!=-9000 && MYIDUP_dec[1]!=-9000 && MYIDUP_dec[0]==-MYIDUP_dec[1]){ // H->ffb
HDKon=1;
__modjhugenmela_MOD_sethdk(&HDKon);
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::VHiggsMatEl: HDKon" << endl;
}
else if (verbosity>=TVar::INFO && includeHiggsDecay) MELAerr << "TUtil::VHiggsMatEl: includeHiggsDecay=true is not supported for the present decay mode." << endl;
if (verbosity>=TVar::DEBUG){
for (int i=0; i<9; i++) MELAout << "p4(" << vh_ids[i] << ") = " << p4[i][0] << ", " << p4[i][1] << ", " << p4[i][2] << ", " << p4[i][3] << "\n";
}
double defaultRenScale = scale_.scale;
double defaultFacScale = facscale_.facscale;
int defaultNloop = nlooprun_.nlooprun;
int defaultNflav = nflav_.nflav;
string defaultPdflabel = pdlabel_.pdlabel;
double renQ = InterpretScaleScheme(production, matrixElement, event_scales->renomalizationScheme, MomStore);
double facQ = InterpretScaleScheme(production, matrixElement, event_scales->factorizationScheme, MomStore);
SetAlphaS(renQ, facQ, event_scales->ren_scale_factor, event_scales->fac_scale_factor, 1, 5, "cteq6_l");
double alphasVal, alphasmzVal;
GetAlphaS(&alphasVal, &alphasmzVal);
RcdME->setRenormalizationScale(renQ);
RcdME->setFactorizationScale(facQ);
RcdME->setAlphaS(alphasVal);
RcdME->setAlphaSatMZ(alphasmzVal);
RcdME->setHiggsMassWidth(masses_mcfm_.hmass, masses_mcfm_.hwidth, 0);
RcdME->setHiggsMassWidth(spinzerohiggs_anomcoupl_.h2mass, spinzerohiggs_anomcoupl_.h2width, 1);
if (verbosity>=TVar::DEBUG){
MELAout
<< "TUtil::VHiggsMatEl: Set AlphaS:\n"
<< "\tBefore set, alphas scale: " << defaultRenScale << ", PDF scale: " << defaultFacScale << '\n'
<< "\trenQ: " << renQ << " ( x " << event_scales->ren_scale_factor << "), facQ: " << facQ << " ( x " << event_scales->fac_scale_factor << ")\n"
<< "\tAfter set, alphas scale: " << scale_.scale << ", PDF scale: " << facscale_.facscale << ", alphas(Qren): " << alphasVal << ", alphas(MZ): " << alphasmzVal << endl;
}
// Since we have a lot of these checks, do them here.
bool partonIsKnown[4];
for (unsigned int ip=0; ip<4; ip++) partonIsKnown[ip] = (MYIDUP_prod[ip]!=0);
if ((production == TVar::Lep_WH || production == TVar::Lep_ZH || production == TVar::GammaH) && !(partonIsKnown[2] && partonIsKnown[3])){ if (verbosity>=TVar::INFO) MELAerr << "TUtil::VHiggsMatEl: Final state particles in leptonic/photonic VH have to have a definite id!" << endl; return sum_msqjk; }
const double allowed_helicities[2] ={ -1, 1 }; // L,R
// Setup outgoing H decay products (H->f fbar), templated with H->b bar if both fermions are unknown.
vector<pair<int, int>> Hffparticles;
double Hffscale=1;
if (HDKon!=0){
if (!PDGHelpers::isAnUnknownJet(MYIDUP_dec[0]) || !PDGHelpers::isAnUnknownJet(MYIDUP_dec[1])){ // If one particle is known, pick that line
if (!PDGHelpers::isAnUnknownJet(MYIDUP_dec[0])) Hffparticles.push_back(pair<int, int>(MYIDUP_dec[0], -MYIDUP_dec[0]));
else Hffparticles.push_back(pair<int, int>(-MYIDUP_dec[1], MYIDUP_dec[1]));
}
else{ // Else loop over possible quark lines
double Hffscalesum=0;
for (int hquark=1; hquark<=5; hquark++){
double Hffmass = __modparameters_MOD_getmass(&hquark);
Hffscalesum += Hffmass;
if (hquark==5){
Hffparticles.push_back(pair<int, int>(hquark, -hquark));
Hffparticles.push_back(pair<int, int>(-hquark, hquark));
Hffscale /= Hffmass;
}
}
Hffscale *= Hffscalesum;
}
}
if (verbosity>=TVar::DEBUG){
MELAout << "TUtil::VHiggsMatEl: Outgoing H-> f fbar particles to compute for the ME template:" << endl;
for (unsigned int ihf=0; ihf<Hffparticles.size(); ihf++) MELAout << "\t - (id8, id9) = (" << Hffparticles.at(ihf).first << ", " << Hffparticles.at(ihf).second << ")" << endl;
MELAout << "TUtil::VHiggsMatEl: ME scale for the H-> f fbar particles: " << Hffscale << endl;
}
if (production == TVar::Lep_WH || production == TVar::Had_WH){
// Setup incoming partons
vector<pair<int, int>> incomingPartons;
if (partonIsKnown[0] && partonIsKnown[1]) incomingPartons.push_back(pair<int, int>(MYIDUP_prod[0], MYIDUP_prod[1])); // Parton 0 and 1 are both known
// FIXME: The following 2/1 assignments assume the CKM element for this pair is non-zero (there are divisions by Vckmsq_in/out later on).
else if (!partonIsKnown[0] && !partonIsKnown[1]){ // Parton 0 and 1 are unknown
// Consider all 4 incoming cases: d au, au d, u ad, ad u
incomingPartons.push_back(pair<int, int>(1, -2)); // du~ -> W-
incomingPartons.push_back(pair<int, int>(-2, 1)); // u~d -> W-
incomingPartons.push_back(pair<int, int>(2, -1)); // ud~ -> W+
incomingPartons.push_back(pair<int, int>(-1, 2)); // d~u -> W+
}
else if (!partonIsKnown[1] && partonIsKnown[0]){ // Parton 0 is known
// Consider the only possible general cases
if (PDGHelpers::isUpTypeQuark(MYIDUP_prod[0])){ // ud~ or u~d
for (int iqf=1; iqf<=5; iqf++){
if (iqf%2==0) continue;
int jqf = -TMath::Sign(iqf, MYIDUP_prod[0]);
double ckm_test = __modparameters_MOD_ckmbare(&(MYIDUP_prod[0]), &jqf);
if (ckm_test!=0.){ incomingPartons.push_back(pair<int, int>(MYIDUP_prod[0], jqf)); break; }
}
}
else if (PDGHelpers::isDownTypeQuark(MYIDUP_prod[0])){ // du~ or d~u
for (int iqf=2; iqf<=4; iqf++){
if (iqf%2==1) continue;
int jqf = -TMath::Sign(iqf, MYIDUP_prod[0]);
double ckm_test = __modparameters_MOD_ckmbare(&(MYIDUP_prod[0]), &jqf);
if (ckm_test!=0.){ incomingPartons.push_back(pair<int, int>(MYIDUP_prod[0], jqf)); break; }
}
}
}
else/* if (!partonIsKnown[0] && partonIsKnown[1])*/{ // Parton 1 is known
// Consider the only possible general cases
if (PDGHelpers::isUpTypeQuark(MYIDUP_prod[1])){ // ud~ or u~d
for (int iqf=1; iqf<=5; iqf++){
if (iqf%2==0) continue;
int jqf = -TMath::Sign(iqf, MYIDUP_prod[1]);
double ckm_test = __modparameters_MOD_ckmbare(&jqf, &(MYIDUP_prod[1]));
if (ckm_test!=0.){ incomingPartons.push_back(pair<int, int>(jqf, MYIDUP_prod[1])); break; }
}
}
else if (PDGHelpers::isDownTypeQuark(MYIDUP_prod[1])){ // du~ or d~u
for (int iqf=2; iqf<=4; iqf++){
if (iqf%2==1) continue;
int jqf = -TMath::Sign(iqf, MYIDUP_prod[1]);
double ckm_test = __modparameters_MOD_ckmbare(&jqf, &(MYIDUP_prod[1]));
if (ckm_test!=0.){ incomingPartons.push_back(pair<int, int>(jqf, MYIDUP_prod[1])); break; }
}
}
}
if (verbosity>=TVar::DEBUG){
MELAout << "TUtil::VHiggsMatEl: Incoming partons to compute for the ME template:" << endl;
for (auto& inpart:incomingPartons) MELAout << "\t - (id1, id2) = (" << inpart.first << ", " << inpart.second << ")" << endl;
}
// Setup outgoing partons
vector<pair<int, int>> outgoingPartons;
if (partonIsKnown[2] && partonIsKnown[3]) outgoingPartons.push_back(pair<int, int>(MYIDUP_prod[2], MYIDUP_prod[3])); // Parton 0 and 1 are both known or Lep_WH
// FIXME: The following 2/1 assignments assume the CKM element for this pair is non-zero (there are divisions by Vckmsq_in/out later on).
else if (!partonIsKnown[2] && !partonIsKnown[3]){ // Parton 0 and 1 are unknown
// Consider all 4 outgoing cases: d au, au d, u ad, ad u
outgoingPartons.push_back(pair<int, int>(1, -2)); // W- -> du~
outgoingPartons.push_back(pair<int, int>(-2, 1)); // W- -> u~d
outgoingPartons.push_back(pair<int, int>(2, -1)); // W+ -> ud~
outgoingPartons.push_back(pair<int, int>(-1, 2)); // W+ -> d~u
}
else if (!partonIsKnown[3] && partonIsKnown[2]){ // Parton 0 is known
// Consider the only possible general cases
if (PDGHelpers::isUpTypeQuark(MYIDUP_prod[2])){ // ud~ or u~d
for (int iqf=1; iqf<=5; iqf++){
if (iqf%2==0) continue;
int jqf = -TMath::Sign(iqf, MYIDUP_prod[2]);
double ckm_test = __modparameters_MOD_ckmbare(&(MYIDUP_prod[2]), &jqf);
if (ckm_test!=0.){ outgoingPartons.push_back(pair<int, int>(MYIDUP_prod[2], jqf)); break; }
}
}
else if (PDGHelpers::isDownTypeQuark(MYIDUP_prod[2])){ // du~ or d~u
for (int iqf=2; iqf<=4; iqf++){
if (iqf%2==1) continue;
int jqf = -TMath::Sign(iqf, MYIDUP_prod[2]);
double ckm_test = __modparameters_MOD_ckmbare(&(MYIDUP_prod[2]), &jqf);
if (ckm_test!=0.){ outgoingPartons.push_back(pair<int, int>(MYIDUP_prod[2], jqf)); break; }
}
}
}
else/* if (!partonIsKnown[2] && partonIsKnown[3])*/{ // Parton 1 is known
// Consider the only possible general cases
if (PDGHelpers::isUpTypeQuark(MYIDUP_prod[3])){ // ud~ or u~d
for (int iqf=1; iqf<=5; iqf++){
if (iqf%2==0) continue;
int jqf = -TMath::Sign(iqf, MYIDUP_prod[3]);
double ckm_test = __modparameters_MOD_ckmbare(&jqf, &(MYIDUP_prod[3]));
if (ckm_test!=0.){ outgoingPartons.push_back(pair<int, int>(jqf, MYIDUP_prod[3])); break; }
}
}
else if (PDGHelpers::isDownTypeQuark(MYIDUP_prod[3])){ // du~ or d~u
for (int iqf=2; iqf<=4; iqf++){
if (iqf%2==1) continue;
int jqf = -TMath::Sign(iqf, MYIDUP_prod[3]);
double ckm_test = __modparameters_MOD_ckmbare(&jqf, &(MYIDUP_prod[3]));
if (ckm_test!=0.){ outgoingPartons.push_back(pair<int, int>(jqf, MYIDUP_prod[3])); break; }
}
}
}
if (verbosity>=TVar::DEBUG){
MELAout << "TUtil::VHiggsMatEl: Outgoing particles to compute for the ME template:" << endl;
for (auto& outpart:outgoingPartons) MELAout << "\t - (id6, id7) = (" << outpart.first << ", " << outpart.second << ")" << endl;
}
for (auto& inpart:incomingPartons){
vh_ids[0] = inpart.first;
vh_ids[1] = inpart.second;
vh_ids[2] = PDGHelpers::getCoupledVertex(vh_ids[0], vh_ids[1]);
if (!PDGHelpers::isAWBoson(vh_ids[2])) continue;
if (verbosity>=TVar::DEBUG) MELAout << "\tIncoming " << vh_ids[0] << "," << vh_ids[1] << " -> " << vh_ids[2] << endl;
double Vckmsq_in = pow(__modparameters_MOD_ckmbare(&(vh_ids[0]), &(vh_ids[1])), 2);
if (verbosity>=TVar::DEBUG) MELAout << "\tNeed to divide the ME by |VCKM_incoming|**2 = " << Vckmsq_in << endl;
for (auto& outpart:outgoingPartons){
vh_ids[5] = outpart.first;
vh_ids[6] = outpart.second;
vh_ids[3] = PDGHelpers::getCoupledVertex(vh_ids[5], vh_ids[6]);
if (vh_ids[2]!=vh_ids[3]) continue;
if (verbosity>=TVar::DEBUG) MELAout << "\t\tOutgoing " << vh_ids[3] << " -> " << vh_ids[5] << "," << vh_ids[6] << endl;
// Compute a raw ME
double msq=0;
for (int h01 = 0; h01 < 2; h01++){
helicities[0] = allowed_helicities[h01];
helicities[1] = -helicities[0];
for (int h56 = 0; h56 < 2; h56++){
helicities[5] = allowed_helicities[h56];
helicities[6] = -helicities[5];
double msq_inst=0;
if (HDKon==0) __modvhiggs_MOD_evalamp_vhiggs(vh_ids, helicities, p4, &msq_inst);
else{
for (int h78=0; h78<2; h78++){
helicities[7]=allowed_helicities[h78];
helicities[8]=allowed_helicities[h78];
for (unsigned int ihf=0; ihf<Hffparticles.size(); ihf++){
vh_ids[7]=Hffparticles.at(ihf).first;
vh_ids[8]=Hffparticles.at(ihf).second;
double msq_inst_LR=0;
__modvhiggs_MOD_evalamp_vhiggs(vh_ids, helicities, p4, &msq_inst_LR);
msq_inst += msq_inst_LR;
} // End loop over template H->f fbar products
} // End loop over the spin of H->f fbar line
msq_inst *= Hffscale;
} // End HDKon!=0
msq += msq_inst;
} // End loop over h56
} // End loop over h01
// Determine the outgoing scale
double scalesum_out=0;
if (!(partonIsKnown[2] && partonIsKnown[3])){
double Vckmsq_out = pow(__modparameters_MOD_ckm(&(vh_ids[5]), &(vh_ids[6])), 2);
if (verbosity>=TVar::DEBUG) MELAout << "\t\tDividing ME by |VCKM_outgoing|**2 = " << Vckmsq_out << endl;
msq /= Vckmsq_out;
for (int outgoing1=1; outgoing1<=nf; outgoing1++){
if (partonIsKnown[2] && outgoing1!=abs(vh_ids[5])) continue;
if (outgoing1%2!=abs(vh_ids[5])%2 || outgoing1==6) continue;
int iout = outgoing1 * TMath::Sign(1, vh_ids[5]);
for (int outgoing2=1; outgoing2<=nf; outgoing2++){
if (partonIsKnown[3] && outgoing2!=abs(vh_ids[6])) continue;
if (outgoing2%2!=abs(vh_ids[6])%2 || outgoing2==6) continue;
int jout = outgoing2 * TMath::Sign(1, vh_ids[6]);
scalesum_out += pow(__modparameters_MOD_ckm(&(iout), &(jout)), 2);
}
}
}
else scalesum_out = 1;
if (verbosity>=TVar::DEBUG) MELAout << "\t\tScale for outgoing particles: " << scalesum_out << endl;
// Divide ME by the incoming scale factor (will be multiplied again inside the loop)
if (!partonIsKnown[0] || !partonIsKnown[1]){
if (verbosity>=TVar::DEBUG) MELAout << "\t\tDividing ME by |VCKM_incoming|**2 = " << Vckmsq_in << endl;
msq /= Vckmsq_in;
}
// Sum all possible combinations
for (int incoming1=1; incoming1<=nf; incoming1++){
if (partonIsKnown[0] && incoming1!=abs(vh_ids[0])) continue;
if (incoming1%2!=abs(vh_ids[0])%2 || incoming1==6) continue;
int iin = incoming1 * TMath::Sign(1, vh_ids[0]);
for (int incoming2=1; incoming2<=nf; incoming2++){
if (partonIsKnown[1] && incoming2!=abs(vh_ids[1])) continue;
if (incoming2%2!=abs(vh_ids[1])%2 || incoming2==6) continue;
int jin = incoming2 * TMath::Sign(1, vh_ids[1]);
if (verbosity>=TVar::DEBUG) MELAout << "\t\t\tiin,jin = " << iin << "," << jin << endl;
double scale_in=1;
if (!partonIsKnown[0] || !partonIsKnown[1]){
scale_in = pow(__modparameters_MOD_ckmbare(&(iin), &(jin)), 2);
if (verbosity>=TVar::DEBUG) MELAout << "\t\tScale for incoming particles: " << scale_in << endl;
}
MatElsq[jin+5][iin+5] += msq * 0.25 * scale_in *scalesum_out;
}
}
// msq is now added to MatElSq.
} // End loop over outgoing particle templates
} // End loop over incoming parton templates
} // End WH
else{ // ZH, GammaH
// Setup incoming partons
vector<pair<int, int>> incomingPartons;
if (partonIsKnown[0] && partonIsKnown[1]) incomingPartons.push_back(pair<int, int>(MYIDUP_prod[0], MYIDUP_prod[1])); // Parton 0 and 1 are both known
else if (!partonIsKnown[0] && !partonIsKnown[1]){ // Parton 0 and 1 are unknown
// Consider all 4 incoming cases: d ad, ad d, u au, au u
incomingPartons.push_back(pair<int, int>(1, -1)); // dd~ -> Z
incomingPartons.push_back(pair<int, int>(-1, 1)); // d~d -> Z
incomingPartons.push_back(pair<int, int>(2, -2)); // uu~ -> Z
incomingPartons.push_back(pair<int, int>(-2, 2)); // u~u -> Z
}
else if (!partonIsKnown[1] && partonIsKnown[0]) // Parton 0 is known
incomingPartons.push_back(pair<int, int>(MYIDUP_prod[0], -MYIDUP_prod[0])); // id1, -id1
else/* if (!partonIsKnown[0] && partonIsKnown[1])*/ // Parton 1 is known
incomingPartons.push_back(pair<int, int>(-MYIDUP_prod[1], MYIDUP_prod[1])); // -id2, id2
if (verbosity>=TVar::DEBUG){
MELAout << "TUtil::VHiggsMatEl: Incoming partons to compute for the ME template:" << endl;
for (auto& inpart:incomingPartons) MELAout << "\t - (id1, id2) = (" << inpart.first << ", " << inpart.second << ")" << endl;
}
// Setup outgoing partons
vector<pair<int, int>> outgoingPartons;
if ((partonIsKnown[2] && partonIsKnown[3]) || production == TVar::GammaH) outgoingPartons.push_back(pair<int, int>(MYIDUP_prod[2], MYIDUP_prod[3])); // Parton 0 and 1 are both known or Lep_ZH
else if (!partonIsKnown[2] && !partonIsKnown[3]){ // Parton 0 and 1 are unknown
// Consider all 4 outgoing cases: d au, au d, u ad, ad u
outgoingPartons.push_back(pair<int, int>(1, -1)); // Z -> dd~
outgoingPartons.push_back(pair<int, int>(-1, 1)); // Z -> d~d
outgoingPartons.push_back(pair<int, int>(2, -2)); // Z -> uu~
outgoingPartons.push_back(pair<int, int>(-2, 2)); // Z -> u~u
}
else if (!partonIsKnown[3] && partonIsKnown[2]) // Parton 0 is known
outgoingPartons.push_back(pair<int, int>(MYIDUP_prod[2], -MYIDUP_prod[2])); // id1, -id1
else/* if (!partonIsKnown[2] && partonIsKnown[3])*/ // Parton 1 is known
outgoingPartons.push_back(pair<int, int>(-MYIDUP_prod[3], MYIDUP_prod[3])); // -id2, id2
if (verbosity>=TVar::DEBUG){
MELAout << "TUtil::VHiggsMatEl: Outgoing particles to compute for the ME template:" << endl;
for (unsigned int op=0; op<outgoingPartons.size(); op++) MELAout << "\t - (id6, id7) = (" << outgoingPartons.at(op).first << ", " << outgoingPartons.at(op).second << ")" << endl;
}
for (auto& inpart:incomingPartons){
vh_ids[0] = inpart.first;
vh_ids[1] = inpart.second;
vh_ids[2] = PDGHelpers::getCoupledVertex(vh_ids[0], vh_ids[1]);
if (!PDGHelpers::isAZBoson(vh_ids[2])) continue; // Notice, Z-> Gamma + H should also have the id of the Z!
if (verbosity>=TVar::DEBUG) MELAout << "\tIncoming " << vh_ids[0] << "," << vh_ids[1] << " -> " << vh_ids[2] << endl;
// Scale for the incoming state is 1
for (auto& outpart:outgoingPartons){
vh_ids[5] = outpart.first;
vh_ids[6] = outpart.second;
if (production == TVar::GammaH) vh_ids[3] = 22;
else{
vh_ids[3] = PDGHelpers::getCoupledVertex(vh_ids[5], vh_ids[6]);
if (vh_ids[2]!=vh_ids[3]) continue;
}
if (verbosity>=TVar::DEBUG) MELAout << "\t\tOutgoing " << vh_ids[3] << " -> " << vh_ids[5] << "," << vh_ids[6] << endl;
// Compute a raw ME
double msq=0;
for (int h01 = 0; h01 < 2; h01++){
helicities[0] = allowed_helicities[h01];
helicities[1] = -helicities[0];
for (int h56 = 0; h56 < 2; h56++){
helicities[5] = allowed_helicities[h56];
helicities[6] = -helicities[5];
double msq_inst=0;
if (HDKon==0) __modvhiggs_MOD_evalamp_vhiggs(vh_ids, helicities, p4, &msq_inst);
else{
for (int h78=0; h78<2; h78++){
helicities[7]=allowed_helicities[h78];
helicities[8]=allowed_helicities[h78];
for (unsigned int ihf=0; ihf<Hffparticles.size(); ihf++){
vh_ids[7]=Hffparticles.at(ihf).first;
vh_ids[8]=Hffparticles.at(ihf).second;
double msq_inst_LR=0;
__modvhiggs_MOD_evalamp_vhiggs(vh_ids, helicities, p4, &msq_inst_LR);
msq_inst += msq_inst_LR;
} // End loop over template H->f fbar products
} // End loop over the spin of H->f fbar line
msq_inst *= Hffscale;
} // End HDKon!=0
msq += msq_inst;
} // End loop over h56
} // End loop over h01
// Determine the outgoing scale
double scale_out=1;
if (!partonIsKnown[2] && !partonIsKnown[3] && production!=TVar::GammaH){
if (PDGHelpers::isDownTypeQuark(vh_ids[5])) scale_out=3;
else if (PDGHelpers::isUpTypeQuark(vh_ids[5])) scale_out=2;
}
if (verbosity>=TVar::DEBUG) MELAout << "\t\tScale for outgoing particles: " << scale_out << endl;
// Sum all possible combinations
for (int incoming1=1; incoming1<=nf; incoming1++){
if (partonIsKnown[0] && incoming1!=abs(vh_ids[0])) continue;
if (incoming1%2!=abs(vh_ids[0])%2 || incoming1==6) continue;
int iin = incoming1 * TMath::Sign(1, vh_ids[0]);
int jin=-iin;
if (verbosity>=TVar::DEBUG) MELAout << "\t\t\tiin,jin = " << iin << "," << jin << endl;
MatElsq[jin+5][iin+5] += msq * 0.25 * scale_out; // No incoming state scale
}
// msq is now added to MatElSq.
} // End loop over outgoing particle templates
} // End loop over incoming parton templates
} // End ZH, GammaH
int GeVexponent_MEsq;
if (HDKon==0) GeVexponent_MEsq = 4-(1+nRequested_AssociatedJets+nRequested_AssociatedLeptons+nRequested_AssociatedPhotons)*2-4; // Amplitude has additional 1/m**2 from propagator == MEsq has additional 1/m**4
else GeVexponent_MEsq = 4-(2+nRequested_AssociatedJets+nRequested_AssociatedLeptons+nRequested_AssociatedPhotons)*2;
double constant = pow(GeV, -GeVexponent_MEsq);
for (int ii=0; ii<nmsq; ii++){ for (int jj=0; jj<nmsq; jj++) MatElsq[jj][ii] *= constant; }
if (verbosity >= TVar::DEBUG){
MELAout << "MatElsq:\n";
for (int ii = 0; ii < nmsq; ii++){ for (int jj = 0; jj < nmsq; jj++) MELAout << MatElsq[jj][ii] << '\t'; MELAout << endl; }
}
sum_msqjk = SumMEPDF(MomStore[0], MomStore[1], MatElsq, RcdME, EBEAM, verbosity);
// Turn H_DK off
if (HDKon!=0){
HDKon=0;
__modjhugenmela_MOD_sethdk(&HDKon);
}
if (verbosity>=TVar::DEBUG){
MELAout
<< "TUtil::VHiggsMatEl: Reset AlphaS:\n"
<< "\tBefore reset, alphas scale: " << scale_.scale << ", PDF scale: " << facscale_.facscale << endl;
}
SetAlphaS(defaultRenScale, defaultFacScale, 1., 1., defaultNloop, defaultNflav, defaultPdflabel);
if (verbosity>=TVar::DEBUG){
GetAlphaS(&alphasVal, &alphasmzVal);
MELAout
<< "TUtil::VHiggsMatEl: Reset AlphaS result:\n"
<< "\tAfter reset, alphas scale: " << scale_.scale << ", PDF scale: " << facscale_.facscale << ", alphas(Qren): " << alphasVal << ", alphas(MZ): " << alphasmzVal << endl;
}
return sum_msqjk;
}
// ttH, H undecayed
double TUtil::TTHiggsMatEl(
const TVar::Process& process, const TVar::Production& production, const TVar::MatrixElement& matrixElement,
event_scales_type* event_scales, MelaIO* RcdME,
const double& EBEAM,
int topDecay, int topProcess,
TVar::VerbosityLevel verbosity
){
const double GeV=1./100.; // JHUGen mom. scale factor
double sum_msqjk = 0;
double MatElsq[nmsq][nmsq]={ { 0 } };
if (matrixElement!=TVar::JHUGen){ if (verbosity>=TVar::ERROR) MELAerr << "TUtil::TTHiggsMatEl: Non-JHUGen MEs are not supported." << endl; return sum_msqjk; }
if (production!=TVar::ttH){ if (verbosity>=TVar::ERROR) MELAerr << "TUtil::TTHiggsMatEl: Only ttH is supported." << endl; return sum_msqjk; }
int partIncCode;
int nRequested_Tops=1;
int nRequested_Antitops=1;
if (topDecay>0) partIncCode=TVar::kUseAssociated_UnstableTops; // Look for unstable tops
else partIncCode=TVar::kUseAssociated_StableTops; // Look for stable tops
simple_event_record mela_event;
mela_event.AssociationCode=partIncCode;
mela_event.nRequested_Tops=nRequested_Tops;
mela_event.nRequested_Antitops=nRequested_Antitops;
GetBoostedParticleVectors(
RcdME->melaCand,
mela_event,
verbosity
);
if (topDecay==0 && (mela_event.pStableTops.size()<1 || mela_event.pStableAntitops.size()<1)){
if (verbosity>=TVar::ERROR) MELAerr
<< "TUtil::TTHiggsMatEl: Number of stable tops (" << mela_event.pStableTops.size() << ")"
<< " and number of stable antitops (" << mela_event.pStableAntitops.size() << ")"
<< " in ttH process are not 1!" << endl;
return sum_msqjk;
}
else if (topDecay>0 && (mela_event.pTopDaughters.size()<1 || mela_event.pAntitopDaughters.size()<1)){
if (verbosity>=TVar::ERROR) MELAerr
<< "TUtil::TTHiggsMatEl: Number of set of top daughters (" << mela_event.pTopDaughters.size() << ")"
<< " and number of set of antitop daughters (" << mela_event.pAntitopDaughters.size() << ")"
<< " in ttH process are not 1!" << endl;
return sum_msqjk;
}
else if (topDecay>0 && (mela_event.pTopDaughters.at(0).size()!=3 || mela_event.pAntitopDaughters.at(0).size()!=3)){
if (verbosity>=TVar::ERROR) MELAerr
<< "TUtil::TTHiggsMatEl: Number of top daughters (" << mela_event.pTopDaughters.at(0).size() << ")"
<< " and number of antitop daughters (" << mela_event.pAntitopDaughters.at(0).size() << ")"
<< " in ttH process are not 3!" << endl;
return sum_msqjk;
}
SimpleParticleCollection_t topDaughters;
SimpleParticleCollection_t antitopDaughters;
bool isUnknown[2]={ true, true };
if (topDecay>0){
// Daughters are assumed to have been ordered as b, Wf, Wfb already.
for (unsigned int itd=0; itd<mela_event.pTopDaughters.at(0).size(); itd++) topDaughters.push_back(mela_event.pTopDaughters.at(0).at(itd));
for (unsigned int itd=0; itd<mela_event.pAntitopDaughters.at(0).size(); itd++) antitopDaughters.push_back(mela_event.pAntitopDaughters.at(0).at(itd));
}
else{
for (unsigned int itop=0; itop<mela_event.pStableTops.size(); itop++) topDaughters.push_back(mela_event.pStableTops.at(itop));
for (unsigned int itop=0; itop<mela_event.pStableAntitops.size(); itop++) antitopDaughters.push_back(mela_event.pStableAntitops.at(itop));
}
// Check if either top is definitely identified
for (unsigned int itd=0; itd<topDaughters.size(); itd++){ if (!PDGHelpers::isAnUnknownJet(topDaughters.at(itd).first)){ isUnknown[0]=false; break; } }
for (unsigned int itd=0; itd<antitopDaughters.size(); itd++){ if (!PDGHelpers::isAnUnknownJet(antitopDaughters.at(itd).first)){ isUnknown[1]=false; break; } }
// Start assigning the momenta
// 0,1: p1 p2
// 2-4: H,tb,t
// 5-8: bb,W-,f,fb
// 9-12: b,W+,fb,f
double p4[13][4]={ { 0 } };
double MYIDUP_prod[2]={ 0 };
TLorentzVector MomStore[mxpart];
for (int i = 0; i < mxpart; i++) MomStore[i].SetXYZT(0, 0, 0, 0);
for (int ipar=0; ipar<2; ipar++){
TLorentzVector* momTmp = &(mela_event.pMothers.at(ipar).second);
int* idtmp = &(mela_event.pMothers.at(ipar).first);
if (!PDGHelpers::isAnUnknownJet(*idtmp)) MYIDUP_prod[ipar] = *idtmp;
else MYIDUP_prod[ipar] = 0;
if (momTmp->T()>0.){
p4[ipar][0] = -momTmp->T()*GeV;
p4[ipar][1] = -momTmp->X()*GeV;
p4[ipar][2] = -momTmp->Y()*GeV;
p4[ipar][3] = -momTmp->Z()*GeV;
MomStore[ipar] = (*momTmp);
}
else{
p4[ipar][0] = momTmp->T()*GeV;
p4[ipar][1] = momTmp->X()*GeV;
p4[ipar][2] = momTmp->Y()*GeV;
p4[ipar][3] = momTmp->Z()*GeV;
MomStore[ipar] = -(*momTmp);
MYIDUP_prod[ipar] = -MYIDUP_prod[ipar];
}
}
// Assign top momenta
// t(4) -> b(9) W+(10) (-> f(12) fb(11))
const unsigned int t_pos=4;
const unsigned int b_pos=9;
const unsigned int Wp_pos=10;
const unsigned int Wpf_pos=12;
const unsigned int Wpfb_pos=11;
for (unsigned int ipar=0; ipar<topDaughters.size(); ipar++){
TLorentzVector* momTmp = &(topDaughters.at(ipar).second);
if (topDaughters.size()==1){
p4[t_pos][0] = momTmp->T()*GeV;
p4[t_pos][1] = momTmp->X()*GeV;
p4[t_pos][2] = momTmp->Y()*GeV;
p4[t_pos][3] = momTmp->Z()*GeV;
}
// size==3
else if (ipar==0){ // b
p4[b_pos][0] = momTmp->T()*GeV;
p4[b_pos][1] = momTmp->X()*GeV;
p4[b_pos][2] = momTmp->Y()*GeV;
p4[b_pos][3] = momTmp->Z()*GeV;
}
else if (ipar==2){ // Wfb
p4[Wpfb_pos][0] = momTmp->T()*GeV;
p4[Wpfb_pos][1] = momTmp->X()*GeV;
p4[Wpfb_pos][2] = momTmp->Y()*GeV;
p4[Wpfb_pos][3] = momTmp->Z()*GeV;
p4[Wp_pos][0] += p4[Wpfb_pos][0];
p4[Wp_pos][1] += p4[Wpfb_pos][1];
p4[Wp_pos][2] += p4[Wpfb_pos][2];
p4[Wp_pos][3] += p4[Wpfb_pos][3];
}
else/* if (ipar==1)*/{ // Wf
p4[Wpf_pos][0] = momTmp->T()*GeV;
p4[Wpf_pos][1] = momTmp->X()*GeV;
p4[Wpf_pos][2] = momTmp->Y()*GeV;
p4[Wpf_pos][3] = momTmp->Z()*GeV;
p4[Wp_pos][0] += p4[Wpf_pos][0];
p4[Wp_pos][1] += p4[Wpf_pos][1];
p4[Wp_pos][2] += p4[Wpf_pos][2];
p4[Wp_pos][3] += p4[Wpf_pos][3];
}
MomStore[6] = MomStore[6] + (*momTmp); // MomStore (I1, I2, 0, 0, 0, H, J1, J2)
}
if (topDaughters.size()!=1){ for (unsigned int ix=0; ix<4; ix++){ for (unsigned int ip=b_pos; ip<=Wp_pos; ip++) p4[t_pos][ix] = p4[ip][ix]; } }
// Assign antitop momenta
// tb(3) -> bb(5) W-(6) (-> f(7) fb(8))
const unsigned int tb_pos=3;
const unsigned int bb_pos=5;
const unsigned int Wm_pos=6;
const unsigned int Wmf_pos=7;
const unsigned int Wmfb_pos=8;
for (unsigned int ipar=0; ipar<antitopDaughters.size(); ipar++){
TLorentzVector* momTmp = &(antitopDaughters.at(ipar).second);
if (antitopDaughters.size()==1){
p4[tb_pos][0] = momTmp->T()*GeV;
p4[tb_pos][1] = momTmp->X()*GeV;
p4[tb_pos][2] = momTmp->Y()*GeV;
p4[tb_pos][3] = momTmp->Z()*GeV;
}
// size==3
else if (ipar==0){ // bb
p4[bb_pos][0] = momTmp->T()*GeV;
p4[bb_pos][1] = momTmp->X()*GeV;
p4[bb_pos][2] = momTmp->Y()*GeV;
p4[bb_pos][3] = momTmp->Z()*GeV;
}
else if (ipar==1){ // Wf
p4[Wmf_pos][0] = momTmp->T()*GeV;
p4[Wmf_pos][1] = momTmp->X()*GeV;
p4[Wmf_pos][2] = momTmp->Y()*GeV;
p4[Wmf_pos][3] = momTmp->Z()*GeV;
p4[Wm_pos][0] += p4[Wmf_pos][0];
p4[Wm_pos][1] += p4[Wmf_pos][1];
p4[Wm_pos][2] += p4[Wmf_pos][2];
p4[Wm_pos][3] += p4[Wmf_pos][3];
}
else/* if (ipar==1)*/{ // Wfb
p4[Wmfb_pos][0] = momTmp->T()*GeV;
p4[Wmfb_pos][1] = momTmp->X()*GeV;
p4[Wmfb_pos][2] = momTmp->Y()*GeV;
p4[Wmfb_pos][3] = momTmp->Z()*GeV;
p4[Wm_pos][0] += p4[Wmfb_pos][0];
p4[Wm_pos][1] += p4[Wmfb_pos][1];
p4[Wm_pos][2] += p4[Wmfb_pos][2];
p4[Wm_pos][3] += p4[Wmfb_pos][3];
}
MomStore[7] = MomStore[7] + (*momTmp); // MomStore (I1, I2, 0, 0, 0, H, J1, J2)
}
if (antitopDaughters.size()!=1){ for (unsigned int ix=0; ix<4; ix++){ for (unsigned int ip=5; ip<=6; ip++) p4[tb_pos][ix] = p4[ip][ix]; } }
for (unsigned int ipar=0; ipar<mela_event.pDaughters.size(); ipar++){
TLorentzVector* momTmp = &(mela_event.pDaughters.at(ipar).second);
p4[2][0] += momTmp->T()*GeV;
p4[2][1] += momTmp->X()*GeV;
p4[2][2] += momTmp->Y()*GeV;
p4[2][3] += momTmp->Z()*GeV;
MomStore[5] = MomStore[5] + (*momTmp); // i==(2, 3, 4) is (J1, J2, H), recorded as MomStore (I1, I2, 0, 0, 0, H, J1, J2)
}
if (verbosity >= TVar::DEBUG){
for (int ii=0; ii<13; ii++){ MELAout << "p4[" << ii << "] = "; for (int jj=0; jj<4; jj++) MELAout << p4[ii][jj]/GeV << '\t'; MELAout << endl; }
}
double defaultRenScale = scale_.scale;
double defaultFacScale = facscale_.facscale;
int defaultNloop = nlooprun_.nlooprun;
int defaultNflav = nflav_.nflav;
string defaultPdflabel = pdlabel_.pdlabel;
double renQ = InterpretScaleScheme(production, matrixElement, event_scales->renomalizationScheme, MomStore);
double facQ = InterpretScaleScheme(production, matrixElement, event_scales->factorizationScheme, MomStore);
SetAlphaS(renQ, facQ, event_scales->ren_scale_factor, event_scales->fac_scale_factor, 1, 5, "cteq6_l");
double alphasVal, alphasmzVal;
GetAlphaS(&alphasVal, &alphasmzVal);
RcdME->setRenormalizationScale(renQ);
RcdME->setFactorizationScale(facQ);
RcdME->setAlphaS(alphasVal);
RcdME->setAlphaSatMZ(alphasmzVal);
RcdME->setHiggsMassWidth(masses_mcfm_.hmass, masses_mcfm_.hwidth, 0);
RcdME->setHiggsMassWidth(spinzerohiggs_anomcoupl_.h2mass, spinzerohiggs_anomcoupl_.h2width, 1);
if (verbosity>=TVar::DEBUG){
MELAout
<< "TUtil::TTHiggsMatEl: Set AlphaS:\n"
<< "\tBefore set, alphas scale: " << defaultRenScale << ", PDF scale: " << defaultFacScale << '\n'
<< "\trenQ: " << renQ << " ( x " << event_scales->ren_scale_factor << "), facQ: " << facQ << " ( x " << event_scales->fac_scale_factor << ")\n"
<< "\tAfter set, alphas scale: " << scale_.scale << ", PDF scale: " << facscale_.facscale << ", alphas(Qren): " << alphasVal << ", alphas(MZ): " << alphasmzVal << endl;
}
__modjhugenmela_MOD_settopdecays(&topDecay);
/***** BEGIN TTH ME CALCULATION *****/
for (unsigned int ib1=0; ib1<3; ib1++){
if (topDaughters.size()==1 && ib1!=0) continue;
else if (topDaughters.size()==3 && !PDGHelpers::isAnUnknownJet(topDaughters.at(0).first) && ib1!=0) continue;
unsigned int b1index;
if (ib1==0) b1index = b_pos;
else if (ib1==1) b1index = Wpf_pos;
else b1index = Wpfb_pos;
for (unsigned int if1=0; if1<3; if1++){
if (topDaughters.size()==1 && if1!=0) continue;
else if (topDaughters.size()==3 && !PDGHelpers::isAnUnknownJet(topDaughters.at(1).first) && if1!=0) continue;
unsigned int f1index;
if (if1==0) f1index = Wpf_pos;
else if (if1==2) f1index = b_pos;
else f1index = Wpfb_pos;
for (unsigned int ifb1=0; ifb1<3; ifb1++){
if (topDaughters.size()==1 && ifb1!=0) continue;
else if (topDaughters.size()==3 && !PDGHelpers::isAnUnknownJet(topDaughters.at(2).first) && ifb1!=0) continue;
unsigned int fb1index;
if (ifb1==2) fb1index = Wpf_pos;
else if (ifb1==1) fb1index = b_pos;
else fb1index = Wpfb_pos;
if (b1index==f1index || b1index==fb1index || f1index==fb1index) continue;
for (unsigned int ib2=0; ib2<3; ib2++){
if (antitopDaughters.size()==1 && ib2!=0) continue;
else if (antitopDaughters.size()==3 && !PDGHelpers::isAnUnknownJet(antitopDaughters.at(0).first) && ib2!=0) continue;
unsigned int b2index;
if (ib2==0) b2index = bb_pos;
else if (ib2==1) b2index = Wmf_pos;
else b2index = Wmfb_pos;
for (unsigned int if2=0; if2<3; if2++){
if (antitopDaughters.size()==1 && if2!=0) continue;
else if (antitopDaughters.size()==3 && !PDGHelpers::isAnUnknownJet(antitopDaughters.at(1).first) && if2!=0) continue;
unsigned int f2index;
if (if2==0) f2index = Wmf_pos;
else if (if2==2) f2index = bb_pos;
else f2index = Wmfb_pos;
for (unsigned int ifb2=0; ifb2<3; ifb2++){
if (antitopDaughters.size()==1 && ifb2!=0) continue;
else if (antitopDaughters.size()==3 && !PDGHelpers::isAnUnknownJet(antitopDaughters.at(2).first) && ifb2!=0) continue;
unsigned int fb2index;
if (ifb2==2) fb2index = Wmf_pos;
else if (ifb2==1) fb2index = bb_pos;
else fb2index = Wmfb_pos;
if (b2index==f2index || b2index==fb2index || f2index==fb2index) continue;
double p4_current[13][4]={ { 0 } };
for (unsigned int ix=0; ix<4; ix++){
for (unsigned int ip=0; ip<=2; ip++) p4_current[ip][ix] = p4[ip][ix]; // I1, I2, H do not change.
p4_current[t_pos][ix] = p4[t_pos][ix]; // t does not change.
p4_current[b1index][ix] = p4[b_pos][ix]; // Assign b to different position.
p4_current[f1index][ix] = p4[Wpf_pos][ix]; // Assign Wp->f? to different position.
p4_current[fb1index][ix] = p4[Wpfb_pos][ix]; // Assign Wp->?fb to different position.
p4_current[Wp_pos][ix] = p4_current[Wpf_pos][ix] + p4_current[Wpfb_pos][ix]; // Re-sum W+ momentum.
p4_current[tb_pos][ix] = p4[tb_pos][ix]; // tb does not change.
p4_current[b2index][ix] = p4[bb_pos][ix]; // Assign bb to different position.
p4_current[f2index][ix] = p4[Wmf_pos][ix]; // Assign Wm->f? to different position.
p4_current[fb2index][ix] = p4[Wmfb_pos][ix]; // Assign Wm->?fb to different position.
p4_current[Wm_pos][ix] = p4_current[Wmf_pos][ix] + p4_current[Wmfb_pos][ix]; // Re-sum W- momentum.
}
if (verbosity>=TVar::DEBUG){
MELAout
<< "TUtil::TTHiggsMatEl: Unswapped instance for "
<< "b(" << b_pos << ") -> " << b1index << ", "
<< "Wpf(" << Wpf_pos << ") -> " << f1index << ", "
<< "Wpfb(" << Wpfb_pos << ") -> " << fb1index << ", "
<< "bb(" << bb_pos << ") -> " << b2index << ", "
<< "Wmf(" << Wmf_pos << ") -> " << f2index << ", "
<< "Wmfb(" << Wmfb_pos << ") -> " << fb2index << endl;
for (int ii=0; ii<13; ii++){ MELAout << "p4_instance[" << ii << "] = "; for (int jj=0; jj<4; jj++) MELAout << p4_current[ii][jj]/GeV << '\t'; MELAout << endl; }
MELAout << endl;
}
double MatElsq_tmp[nmsq][nmsq]={ { 0 } };
double MatElsq_tmp_swap[nmsq][nmsq]={ { 0 } };
__modttbhiggs_MOD_evalxsec_pp_ttbh(p4_current, &topProcess, MatElsq_tmp);
if (isUnknown[0] && isUnknown[1]){
for (unsigned int ix=0; ix<4; ix++){
swap(p4_current[t_pos][ix], p4_current[tb_pos][ix]);
swap(p4_current[b_pos][ix], p4_current[bb_pos][ix]);
swap(p4_current[Wp_pos][ix], p4_current[Wm_pos][ix]);
swap(p4_current[Wpf_pos][ix], p4_current[Wmf_pos][ix]);
swap(p4_current[Wpfb_pos][ix], p4_current[Wmfb_pos][ix]);
}
__modttbhiggs_MOD_evalxsec_pp_ttbh(p4_current, &topProcess, MatElsq_tmp_swap);
for (int ix=0; ix<11; ix++){ for (int iy=0; iy<11; iy++) MatElsq_tmp[iy][ix] = (MatElsq_tmp[iy][ix]+MatElsq_tmp_swap[iy][ix])/2.; }
}
for (int ix=0; ix<11; ix++){ for (int iy=0; iy<11; iy++) MatElsq[iy][ix] += MatElsq_tmp[iy][ix]; }
if (verbosity>=TVar::DEBUG){
MELAout
<< "TUtil::TTHiggsMatEl: Swapped instance for "
<< "b(" << b_pos << ") -> " << b1index << ", "
<< "Wpf(" << Wpf_pos << ") -> " << f1index << ", "
<< "Wpfb(" << Wpfb_pos << ") -> " << fb1index << ", "
<< "bb(" << bb_pos << ") -> " << b2index << ", "
<< "Wmf(" << Wmf_pos << ") -> " << f2index << ", "
<< "Wmfb(" << Wmfb_pos << ") -> " << fb2index << endl;
for (int ii=0; ii<13; ii++){ MELAout << "p4_instance[" << ii << "] = "; for (int jj=0; jj<4; jj++) MELAout << p4_current[ii][jj]/GeV << '\t'; MELAout << endl; }
MELAout << endl;
}
} // End loop over ifb2
} // End loop over if2
} // End loop over ib2
} // End loop over ifb1
} // End loop over if1
} // End loop over ib1
/***** END TTH ME CALCULATION *****/
int defaultTopDecay=-1;
__modjhugenmela_MOD_settopdecays(&defaultTopDecay); // reset top decay
int GeVexponent_MEsq;
if (topDecay>0) GeVexponent_MEsq = 4-(1+3*(nRequested_Tops+nRequested_Antitops))*2;
else GeVexponent_MEsq = 4-(1+nRequested_Tops+nRequested_Antitops)*2;
double constant = pow(GeV, -GeVexponent_MEsq);
for (int ii=0; ii<nmsq; ii++){ for (int jj=0; jj<nmsq; jj++) MatElsq[jj][ii] *= constant; }
if (verbosity>=TVar::DEBUG){
MELAout << "TUtil::TTHiggsMatEl: MEsq[ip][jp] = " << endl;
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++) MELAout << MatElsq[jquark+5][iquark+5] << '\t';
MELAout << endl;
}
}
sum_msqjk = SumMEPDF(MomStore[0], MomStore[1], MatElsq, RcdME, EBEAM, verbosity);
if (verbosity>=TVar::DEBUG){
MELAout
<< "TUtil::TTHiggsMatEl: Reset AlphaS:\n"
<< "\tBefore reset, alphas scale: " << scale_.scale << ", PDF scale: " << facscale_.facscale << endl;
}
SetAlphaS(defaultRenScale, defaultFacScale, 1., 1., defaultNloop, defaultNflav, defaultPdflabel);
if (verbosity>=TVar::DEBUG){
GetAlphaS(&alphasVal, &alphasmzVal);
MELAout
<< "TUtil::TTHiggsMatEl: Reset AlphaS result:\n"
<< "\tAfter reset, alphas scale: " << scale_.scale << ", PDF scale: " << facscale_.facscale << ", alphas(Qren): " << alphasVal << ", alphas(MZ): " << alphasmzVal << endl;
}
return sum_msqjk;
}
// bbH, H undecayed
double TUtil::BBHiggsMatEl(
const TVar::Process& process, const TVar::Production& production, const TVar::MatrixElement& matrixElement,
event_scales_type* event_scales, MelaIO* RcdME,
const double& EBEAM,
int botProcess,
TVar::VerbosityLevel verbosity
){
const double GeV=1./100.; // JHUGen mom. scale factor
double sum_msqjk = 0;
double MatElsq[nmsq][nmsq]={ { 0 } };
double MatElsq_tmp[nmsq][nmsq]={ { 0 } };
if (matrixElement!=TVar::JHUGen){ if (verbosity>=TVar::ERROR) MELAerr << "TUtil::BBHiggsMatEl: Non-JHUGen MEs are not supported." << endl; return sum_msqjk; }
if (production!=TVar::bbH){ if (verbosity>=TVar::ERROR) MELAerr << "TUtil::BBHiggsMatEl: Only bbH is supported." << endl; return sum_msqjk; }
int partIncCode=TVar::kUseAssociated_Jets; // Look for jets
int nRequested_AssociatedJets=2;
simple_event_record mela_event;
mela_event.AssociationCode=partIncCode;
mela_event.nRequested_AssociatedJets=nRequested_AssociatedJets;
GetBoostedParticleVectors(
RcdME->melaCand,
mela_event,
verbosity
);
if (mela_event.pAssociated.size()<2){
if (verbosity>=TVar::ERROR) MELAerr
<< "TUtil::BBHiggsMatEl: Number of stable bs (" << mela_event.pAssociated.size() << ")"
<<" in bbH process is not 2!" << endl;
return sum_msqjk;
}
SimpleParticleCollection_t topDaughters;
SimpleParticleCollection_t antitopDaughters;
bool isUnknown[2]; isUnknown[0]=false; isUnknown[1]=false;
if (mela_event.pAssociated.at(0).first>=0){ topDaughters.push_back(mela_event.pAssociated.at(0)); isUnknown[0]=(PDGHelpers::isAnUnknownJet(mela_event.pAssociated.at(0).first)); }
else antitopDaughters.push_back(mela_event.pAssociated.at(0));
if (mela_event.pAssociated.at(1).first<=0){ antitopDaughters.push_back(mela_event.pAssociated.at(1)); isUnknown[1]=(PDGHelpers::isAnUnknownJet(mela_event.pAssociated.at(1).first)); }
else topDaughters.push_back(mela_event.pAssociated.at(1));
// Start assigning the momenta
// 0,1: p1 p2
// 2-4: H,tb,t
// 5-8: bb,W-,f,fb
// 9-12: b,W+,fb,f
double p4[13][4]={ { 0 } };
double MYIDUP_prod[2]={ 0 };
TLorentzVector MomStore[mxpart];
for (int i = 0; i < mxpart; i++) MomStore[i].SetXYZT(0, 0, 0, 0);
for (int ipar=0; ipar<2; ipar++){
TLorentzVector* momTmp = &(mela_event.pMothers.at(ipar).second);
int* idtmp = &(mela_event.pMothers.at(ipar).first);
if (!PDGHelpers::isAnUnknownJet(*idtmp)) MYIDUP_prod[ipar] = *idtmp;
else MYIDUP_prod[ipar] = 0;
if (momTmp->T()>0.){
p4[ipar][0] = -momTmp->T()*GeV;
p4[ipar][1] = -momTmp->X()*GeV;
p4[ipar][2] = -momTmp->Y()*GeV;
p4[ipar][3] = -momTmp->Z()*GeV;
MomStore[ipar] = (*momTmp);
}
else{
p4[ipar][0] = momTmp->T()*GeV;
p4[ipar][1] = momTmp->X()*GeV;
p4[ipar][2] = momTmp->Y()*GeV;
p4[ipar][3] = momTmp->Z()*GeV;
MomStore[ipar] = -(*momTmp);
MYIDUP_prod[ipar] = -MYIDUP_prod[ipar];
}
}
// Assign b momenta
for (unsigned int ipar=0; ipar<topDaughters.size(); ipar++){
TLorentzVector* momTmp = &(topDaughters.at(ipar).second);
p4[4][0] = momTmp->T()*GeV;
p4[4][1] = momTmp->X()*GeV;
p4[4][2] = momTmp->Y()*GeV;
p4[4][3] = momTmp->Z()*GeV;
MomStore[6] = MomStore[6] + (*momTmp); // MomStore (I1, I2, 0, 0, 0, H, J1, J2)
}
// Assign bb momenta
for (unsigned int ipar=0; ipar<antitopDaughters.size(); ipar++){
TLorentzVector* momTmp = &(antitopDaughters.at(ipar).second);
p4[3][0] = momTmp->T()*GeV;
p4[3][1] = momTmp->X()*GeV;
p4[3][2] = momTmp->Y()*GeV;
p4[3][3] = momTmp->Z()*GeV;
MomStore[7] = MomStore[7] + (*momTmp); // MomStore (I1, I2, 0, 0, 0, H, J1, J2)
}
for (unsigned int ipar=0; ipar<mela_event.pDaughters.size(); ipar++){
TLorentzVector* momTmp = &(mela_event.pDaughters.at(ipar).second);
p4[2][0] += momTmp->T()*GeV;
p4[2][1] += momTmp->X()*GeV;
p4[2][2] += momTmp->Y()*GeV;
p4[2][3] += momTmp->Z()*GeV;
MomStore[5] = MomStore[5] + (*momTmp); // i==(2, 3, 4) is (J1, J2, H), recorded as MomStore (I1, I2, 0, 0, 0, H, J1, J2)
}
if (verbosity >= TVar::DEBUG){
for (int ii=0; ii<13; ii++){ MELAout << "p4[" << ii << "] = "; for (int jj=0; jj<4; jj++) MELAout << p4[ii][jj]/GeV << '\t'; MELAout << endl; }
}
double defaultRenScale = scale_.scale;
double defaultFacScale = facscale_.facscale;
//MELAout << "Default scales: " << defaultRenScale << '\t' << defaultFacScale << endl;
int defaultNloop = nlooprun_.nlooprun;
int defaultNflav = nflav_.nflav;
string defaultPdflabel = pdlabel_.pdlabel;
double renQ = InterpretScaleScheme(production, matrixElement, event_scales->renomalizationScheme, MomStore);
double facQ = InterpretScaleScheme(production, matrixElement, event_scales->factorizationScheme, MomStore);
SetAlphaS(renQ, facQ, event_scales->ren_scale_factor, event_scales->fac_scale_factor, 1, 5, "cteq6_l");
double alphasVal, alphasmzVal;
GetAlphaS(&alphasVal, &alphasmzVal);
RcdME->setRenormalizationScale(renQ);
RcdME->setFactorizationScale(facQ);
RcdME->setAlphaS(alphasVal);
RcdME->setAlphaSatMZ(alphasmzVal);
RcdME->setHiggsMassWidth(masses_mcfm_.hmass, masses_mcfm_.hwidth, 0);
RcdME->setHiggsMassWidth(spinzerohiggs_anomcoupl_.h2mass, spinzerohiggs_anomcoupl_.h2width, 1);
if (verbosity>=TVar::DEBUG){
MELAout
<< "TUtil::BBHiggsMatEl: Set AlphaS:\n"
<< "\tBefore set, alphas scale: " << defaultRenScale << ", PDF scale: " << defaultFacScale << '\n'
<< "\trenQ: " << renQ << " ( x " << event_scales->ren_scale_factor << "), facQ: " << facQ << " ( x " << event_scales->fac_scale_factor << ")\n"
<< "\tAfter set, alphas scale: " << scale_.scale << ", PDF scale: " << facscale_.facscale << ", alphas(Qren): " << alphasVal << ", alphas(MZ): " << alphasmzVal << endl;
}
__modttbhiggs_MOD_evalxsec_pp_bbbh(p4, &botProcess, MatElsq);
if (isUnknown[0] && isUnknown[1]){
for (unsigned int ix=0; ix<4; ix++) swap(p4[3][ix], p4[4][ix]);
__modttbhiggs_MOD_evalxsec_pp_bbbh(p4, &botProcess, MatElsq_tmp);
for (int ix=0; ix<11; ix++){ for (int iy=0; iy<11; iy++) MatElsq[iy][ix] = (MatElsq[iy][ix]+MatElsq_tmp[iy][ix])/2.; }
}
int GeVexponent_MEsq = 4-(1+nRequested_AssociatedJets)*2;
double constant = pow(GeV, -GeVexponent_MEsq);
for (int ii=0; ii<nmsq; ii++){ for (int jj=0; jj<nmsq; jj++) MatElsq[jj][ii] *= constant; }
if (verbosity>=TVar::DEBUG){
MELAout << "TUtil::BBHiggsMatEl: MEsq[ip][jp] = " << endl;
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++) MELAout << MatElsq[jquark+5][iquark+5] << '\t';
MELAout << endl;
}
}
sum_msqjk = SumMEPDF(MomStore[0], MomStore[1], MatElsq, RcdME, EBEAM, verbosity);
if (verbosity>=TVar::DEBUG){
MELAout
<< "TUtil::BBHiggsMatEl: Reset AlphaS:\n"
<< "\tBefore reset, alphas scale: " << scale_.scale << ", PDF scale: " << facscale_.facscale << endl;
}
SetAlphaS(defaultRenScale, defaultFacScale, 1., 1., defaultNloop, defaultNflav, defaultPdflabel);
if (verbosity>=TVar::DEBUG){
GetAlphaS(&alphasVal, &alphasmzVal);
MELAout
<< "TUtil::BBHiggsMatEl: Reset AlphaS result:\n"
<< "\tAfter reset, alphas scale: " << scale_.scale << ", PDF scale: " << facscale_.facscale << ", alphas(Qren): " << alphasVal << ", alphas(MZ): " << alphasmzVal << endl;
}
return sum_msqjk;
}
// Wipe MEs
int TUtil::WipeMEArray(const TVar::Process& process, const TVar::Production& production, const int id[mxpart], double msq[nmsq][nmsq], const TVar::VerbosityLevel& verbosity){
if (verbosity>=TVar::DEBUG){
MELAout << "TUtil::WipeMEArray: Initial MEsq:" << endl;
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++) MELAout << msq[jquark+5][iquark+5] << '\t';
MELAout << endl;
}
}
int nInstances=0;
if (
(production == TVar::ZZINDEPENDENT || production == TVar::ZZQQB)
||
((production == TVar::ZZQQB_STU || production == TVar::ZZQQB_S || production == TVar::ZZQQB_TU) && process == TVar::bkgZZ)
){
// Sum over valid MEs without PDF weights
// By far the dominant contribution is uub initial state.
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++){
if (
(PDGHelpers::isAnUnknownJet(id[0]) || (PDGHelpers::isAGluon(id[0]) && iquark==0) || iquark==id[0])
&&
(PDGHelpers::isAnUnknownJet(id[1]) || (PDGHelpers::isAGluon(id[1]) && jquark==0) || jquark==id[1])
){
if (msq[jquark+5][iquark+5]>0.) nInstances++;
}
else msq[jquark+5][iquark+5]=0; // Kill the ME instance if mothers are known and their ids do not match the PDF indices.
}
}
}
else if (production == TVar::ZZGG){
if (
(PDGHelpers::isAnUnknownJet(id[0]) || PDGHelpers::isAGluon(id[0]))
&&
(PDGHelpers::isAnUnknownJet(id[1]) || PDGHelpers::isAGluon(id[1]))
){
if (msq[5][5]>0.) nInstances=1;
}
else msq[5][5]=0; // Kill the ME instance if mothers are known and their ids do not match to gluons.
}
else if (
production == TVar::Had_WH || production == TVar::Had_ZH
|| production == TVar::Had_WH_S || production == TVar::Had_ZH_S
|| production == TVar::Had_WH_TU || production == TVar::Had_ZH_TU
|| production == TVar::Lep_WH || production == TVar::Lep_ZH
|| production == TVar::Lep_WH_S || production == TVar::Lep_ZH_S
|| production == TVar::Lep_WH_TU || production == TVar::Lep_ZH_TU
|| production == TVar::JJVBF || production == TVar::JJEW || production == TVar::JJEWQCD
|| production == TVar::JJVBF_S || production == TVar::JJEW_S || production == TVar::JJEWQCD_S
|| production == TVar::JJVBF_TU || production == TVar::JJEW_TU || production == TVar::JJEWQCD_TU
|| production == TVar::JJQCD || production == TVar::JJQCD_S || production == TVar::JJQCD_TU
){
// Z+2 jets
if (process == TVar::bkgZJets){
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++){
if (
(PDGHelpers::isAnUnknownJet(id[0]) || (PDGHelpers::isAGluon(id[0]) && iquark==0) || iquark==id[0])
&&
(PDGHelpers::isAnUnknownJet(id[1]) || (PDGHelpers::isAGluon(id[1]) && jquark==0) || jquark==id[1])
){
if (msq[jquark+5][iquark+5]>0.) nInstances++;
}
else msq[jquark+5][iquark+5]=0; // Kill the ME instance if mothers are known and their ids do not match the PDF indices.
}
}
}
// VBF or QCD MCFM SBI, S or B
else{
for (int iquark=-5; iquark<=5; iquark++){
for (int jquark=-5; jquark<=5; jquark++){
if (
(
PDGHelpers::isAnUnknownJet(id[0]) || (PDGHelpers::isAGluon(id[0]) && iquark==0) || iquark==id[0]
)
&&
(
PDGHelpers::isAnUnknownJet(id[1]) || (PDGHelpers::isAGluon(id[1]) && jquark==0) || jquark==id[1]
)
){
// Kill all non-VH initial parton states
if (
(
(
production == TVar::Had_WH || production == TVar::Lep_WH
|| production == TVar::Had_WH_S || production == TVar::Lep_WH_S
|| production == TVar::Had_WH_TU || production == TVar::Lep_WH_TU
)
&&
(
(TMath::Sign(1, iquark)==TMath::Sign(1, jquark))
||
(PDGHelpers::isUpTypeQuark(iquark) && PDGHelpers::isUpTypeQuark(jquark))
||
(PDGHelpers::isDownTypeQuark(iquark) && PDGHelpers::isDownTypeQuark(jquark))
)
)
||
(
(
production == TVar::Had_ZH || production == TVar::Lep_ZH
|| production == TVar::Had_ZH_S || production == TVar::Lep_ZH_S
|| production == TVar::Had_ZH_TU || production == TVar::Lep_ZH_TU
)
&&
(iquark!=-jquark)
)
) msq[jquark+5][iquark+5]=0;
// Check against a hash
int order[2]={ -1, -1 };
TMCFMUtils::AssociatedParticleOrdering_QQVVQQAny(iquark, jquark, id[6], id[7], order);
if (order[0]<0 || order[1]<0) msq[jquark+5][iquark+5]=0;
if (msq[jquark+5][iquark+5]>0.) nInstances++;
}
else msq[jquark+5][iquark+5]=0; // Kill the ME instance if mothers are known and their ids do not match the PDF indices.
}
}
}
}
return nInstances;
}
// CheckPartonMomFraction computes xx[0:1] based on p0, p1
bool TUtil::CheckPartonMomFraction(const TLorentzVector& p0, const TLorentzVector& p1, double xx[2], const double& EBEAM, const TVar::VerbosityLevel& verbosity){
//Make sure parton Level Energy fraction is [0,1]
//phase space function already makes sure the parton energy fraction between [min,1]
xx[0]=p0.P()/EBEAM;
xx[1]=p1.P()/EBEAM;
if (
xx[0]>1. || xx[0]<=xmin_.xmin
||
xx[1]>1. || xx[1]<=xmin_.xmin
||
EBEAM<=0.
){
if (verbosity>=TVar::ERROR){
if (xx[0]>1. || xx[1]>1.) MELAerr << "TUtil::CheckPartonMomFraction: At least one of the parton momentum fractions is greater than 1." << endl;
else if (xx[0]<=xmin_.xmin || xx[1]<=xmin_.xmin) MELAerr << "TUtil::CheckPartonMomFraction: At least one of the parton momentum fractions is less than or equal to " << xmin_.xmin << "." << endl;
else MELAerr << "TUtil::CheckPartonMomFraction: EBEAM=" << EBEAM << "<=0." << endl;
}
return false;
}
else{
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::CheckPartonMomFraction: xx[0]: " << xx[0] << ", xx[1] = " << xx[1] << ", xmin = " << xmin_.xmin << endl;
return true;
}
}
// ComputePDF does the PDF computation
void TUtil::ComputePDF(const TLorentzVector& p0, const TLorentzVector& p1, double fx1[nmsq], double fx2[nmsq], const double& EBEAM, const TVar::VerbosityLevel& verbosity){
if (verbosity>=TVar::DEBUG) MELAout << "Begin TUtil::ComputePDF"<< endl;
double xx[2]={ 0 };
if (CheckPartonMomFraction(p0, p1, xx, EBEAM, verbosity)){
///// USE JHUGEN SUBROUTINE (Accomodates LHAPDF) /////
double fx1x2_jhu[2][13]={ { 0 } };
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::ComputePDF: Calling setpdfs with xx[0]: " << xx[0] << ", xx[1] = " << xx[1] << endl;
__modkinematics_MOD_setpdfs(&(xx[0]), &(xx[1]), fx1x2_jhu);
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::ComputePDF: called"<< endl;
for (int ip=-6; ip<=6; ip++){
// JHUGen assignment is in JHU id coventions (up <-> down, g==g)
int fac=0;
if (ip!=0 && (abs(ip)%2==0)) fac=-1;
else if (ip!=0) fac=+1;
if (ip<0) fac=-fac;
int jp=ip+fac;
fx1[jp+5]=fx1x2_jhu[0][ip+6];
fx2[jp+5]=fx1x2_jhu[1][ip+6];
}
/*
///// USE MCFM SUBROUTINE fdist_linux /////
//Calculate Pdf
//Parton Density Function is always evalualted at pT=0 frame
//Always pass address through fortran function
fdist_(&density_.ih1, &xx[0], &facscale_.facscale, fx1);
fdist_(&density_.ih2, &xx[1], &facscale_.facscale, fx2);
*/
}
if (verbosity>=TVar::DEBUG){
MELAout << "End TUtil::ComputePDF:"<< endl;
for (int ip=-nf; ip<=nf; ip++) MELAout << "(fx1, fx2)[" << ip << "] = (" << fx1[ip+5] << " , " << fx2[ip+5] << ")" << endl;
}
}
// SumMEPDF sums over all production parton flavors according to PDF and calls ComputePDF
double TUtil::SumMEPDF(const TLorentzVector& p0, const TLorentzVector& p1, double msq[nmsq][nmsq], MelaIO* RcdME, const double& EBEAM, const TVar::VerbosityLevel& verbosity){
if (verbosity>=TVar::DEBUG) MELAout << "Begin TUtil::SumMEPDF"<< endl;
double fx1[nmsq]={ 0 };
double fx2[nmsq]={ 0 };
//double wgt_msq[nmsq][nmsq]={ { 0 } };
ComputePDF(p0, p1, fx1, fx2, EBEAM, verbosity);
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::SumMEPDF: Setting RcdME"<< endl;
RcdME->setPartonWeights(fx1, fx2);
RcdME->setMEArray(msq, true);
RcdME->computeWeightedMEArray();
//RcdME->getWeightedMEArray(wgt_msq);
if (verbosity>=TVar::DEBUG) MELAout << "End TUtil::SumMEPDF"<< endl;
return RcdME->getSumME();
}
// Propagator reweighting
double TUtil::ResonancePropagator(double const& sqrts, TVar::ResonancePropagatorScheme scheme){
__modjhugenmela_MOD_resetmubarhgabarh();
const double GeV=1./100.; // JHUGen mom. scale factor
int isch=(int)scheme;
double shat_jhu = pow(sqrts*GeV, 2);
double prop = __modkinematics_MOD_getbwpropagator(&shat_jhu, &isch);
if (scheme!=TVar::NoPropagator) prop *= pow(GeV, 4);
return prop;
}
// GetBoostedParticleVectors decomposes the MELACandidate object melaCand into mothers, daughters, associateds and tops
// and boosts them to the pT=0 frame for the particular mela_event.AssociationCode, which is a product of TVar::kUseAssociated* (prime numbers).
// If no mothers are present, it assigns mothers as Z>0, Z<0. If they are present, it orders them as "incoming" q-qbar / g-qbar / q-g / g-g
// Associated particles passed are different based on the code. If code==1, no associated particles are passed.
// mela_event.intermediateVids are needed to keep track of the decay mode. TVar::Process or TVar::Production do not keep track of the V/f decay modes.
// This is the major replacement functionality of the TVar lepton flavors.
void TUtil::GetBoostedParticleVectors(
MELACandidate* melaCand,
simple_event_record& mela_event,
TVar::VerbosityLevel verbosity
){
if (verbosity>=TVar::DEBUG) MELAout << "Begin GetBoostedParticleVectors" << endl;
// This is the beginning of one long function.
int const& code = mela_event.AssociationCode;
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::GetBoostedParticleVectors: code=" << code << endl;
int const& aVhypo = mela_event.AssociationVCompatibility;
TLorentzVector const nullFourVector(0, 0, 0, 0);
SimpleParticleCollection_t daughters;
vector<int> idVstar; idVstar.reserve(2);
if (melaCand->getNDaughters()==0){
// Undecayed Higgs has V1=H, V2=empty, no sortedDaughters!
daughters.push_back(SimpleParticle_t(melaCand->id, melaCand->p4));
idVstar.push_back(melaCand->id);
idVstar.push_back(-9000);
}
else{
// H->ffb has V1=f->f, V2=fb->fb
// H->GG has V1=G->G, V2=G->G
// H->ZG has V1=Z->ffb, V2=G->G
// Everything else is as expected.
for (unsigned char iv=0; iv<2; iv++){ // 2 Vs are guaranteed in MELACandidate.
MELAParticle* Vdau = melaCand->getSortedV(iv);
if (Vdau){
int idtmp = Vdau->id;
for (MELAParticle* Vdau_i:Vdau->getDaughters()){
if (Vdau_i && Vdau_i->passSelection) daughters.push_back(SimpleParticle_t(Vdau_i->id, Vdau_i->p4));
}
if (idtmp!=0 || Vdau->getNDaughters()>0){ // Avoid "empty" intermediate Vs of the MELACandidate object
if (Vdau->getNDaughters()>=2 && PDGHelpers::isAPhoton(idtmp)) idtmp=23; // Special case to avoid V->2f with massless decay mode (could happen by mistake)
idVstar.push_back(idtmp);
}
}
else idVstar.push_back(-9000);
}
}
if (daughters.size()>=2){
size_t nffs = daughters.size()/2;
for (size_t iv=0; iv<nffs; iv++){
pair<TLorentzVector, TLorentzVector> corrPair = TUtil::removeMassFromPair(
daughters.at(2*iv+0).second, daughters.at(2*iv+0).first,
daughters.at(2*iv+1).second, daughters.at(2*iv+1).first
);
daughters.at(2*iv+0).second = corrPair.first;
daughters.at(2*iv+1).second = corrPair.second;
}
if (2*nffs<daughters.size()){
TLorentzVector tmp = nullFourVector;
SimpleParticle_t& lastDau = daughters.back();
pair<TLorentzVector, TLorentzVector> corrPair = TUtil::removeMassFromPair(
lastDau.second, lastDau.first,
tmp, -9000
);
lastDau.second = corrPair.first;
}
}
/***** ASSOCIATED PARTICLES *****/
if (verbosity>=TVar::DEBUG){
MELAout << "TUtil::GetBoostedParticleVectors: nRequestedLeps=" << mela_event.nRequested_AssociatedLeptons << endl;
MELAout << "TUtil::GetBoostedParticleVectors: nRequestedJets=" << mela_event.nRequested_AssociatedJets << endl;
MELAout << "TUtil::GetBoostedParticleVectors: nRequestedPhotons=" << mela_event.nRequested_AssociatedPhotons << endl;
}
int nsatisfied_jets=0;
int nsatisfied_lnus=0;
int nsatisfied_gammas=0;
vector<MELAParticle*> candidateVs; // Used if aVhypo!=0
SimpleParticleCollection_t associated;
if (aVhypo!=0){
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::GetBoostedParticleVectors: aVhypo!=0 case start" << endl;
vector<MELAParticle*> asortedVs = melaCand->getAssociatedSortedVs();
for (MELAParticle* Vdau:asortedVs){ // Loop over associated Vs
if (Vdau){
bool doAdd=false;
int idV = Vdau->id;
if ((abs(idV)==aVhypo || idV==0) && Vdau->getNDaughters()>0 && Vdau->passSelection){ // If the V is unknown or compatible with the requested hypothesis
doAdd=true;
for (MELAParticle* Vdau_i:Vdau->getDaughters()){ // Loop over the daughters of V
if (!Vdau_i){ doAdd=false; break; }
else if (
(mela_event.nRequested_AssociatedLeptons==0 && (PDGHelpers::isALepton(Vdau_i->id) || PDGHelpers::isANeutrino(Vdau_i->id)))
||
(mela_event.nRequested_AssociatedJets==0 && PDGHelpers::isAJet(Vdau_i->id))
||
!Vdau_i->passSelection // Protection against incorrect Vdau passSelection flag
){
doAdd=false; break;
}
}
}
if (doAdd) candidateVs.push_back(Vdau);
}
} // End loop over associated Vs
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::GetBoostedParticleVectors: candidateVs size = " << candidateVs.size() << endl;
// Pick however many candidates necessary to fill up the requested number of jets or lepton(+)neutrinos
for (MELAParticle* Vdau:candidateVs){
SimpleParticleCollection_t associated_tmp;
for (MELAParticle* part:Vdau->getDaughters()){ // Loop over the daughters of V
if (
part->passSelection
&&
(PDGHelpers::isALepton(part->id) || PDGHelpers::isANeutrino(part->id))
&&
nsatisfied_lnus<mela_event.nRequested_AssociatedLeptons
){
nsatisfied_lnus++;
associated_tmp.push_back(SimpleParticle_t(part->id, part->p4));
}
else if (
part->passSelection
&&
PDGHelpers::isAJet(part->id)
&&
nsatisfied_jets<mela_event.nRequested_AssociatedJets
){
nsatisfied_jets++;
associated_tmp.push_back(SimpleParticle_t(part->id, part->p4));
}
}
// Add the id of the intermediate V into the idVstar array
if (associated_tmp.size()>=2 || (associated_tmp.size()==1 && PDGHelpers::isAPhoton(associated_tmp.at(0).first))) idVstar.push_back(Vdau->id); // Only add the V-id of pairs that passed
// Adjust the kinematics of associated V-originating particles
if (associated_tmp.size()>=2){ // ==1 means a photon, so omit it here.
unsigned int nffs = associated_tmp.size()/2;
for (unsigned int iv=0; iv<nffs; iv++){
pair<TLorentzVector, TLorentzVector> corrPair = TUtil::removeMassFromPair(
associated_tmp.at(2*iv+0).second, associated_tmp.at(2*iv+0).first,
associated_tmp.at(2*iv+1).second, associated_tmp.at(2*iv+1).first
);
associated_tmp.at(2*iv+0).second = corrPair.first;
associated_tmp.at(2*iv+1).second = corrPair.second;
}
if (2*nffs<associated_tmp.size()){
TLorentzVector tmp = nullFourVector;
pair<TLorentzVector, TLorentzVector> corrPair = TUtil::removeMassFromPair(
associated_tmp.at(associated_tmp.size()-1).second, associated_tmp.at(associated_tmp.size()-1).first,
tmp, -9000
);
associated_tmp.at(associated_tmp.size()-1).second = corrPair.first;
}
}
for (SimpleParticle_t& sp:associated_tmp) associated.push_back(sp); // Fill associated at the last step
}
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::GetBoostedParticleVectors: aVhypo!=0 case associated.size=" << associated.size() << endl;
}
else{ // Could be split to aVhypo==0 and aVhypo<0 if associated V+jets is needed
// Associated leptons
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::GetBoostedParticleVectors: aVhypo==0 case begin" << endl;
if (code%TVar::kUseAssociated_Leptons==0){
SimpleParticleCollection_t associated_tmp;
for (MELAParticle* part:melaCand->getAssociatedLeptons()){
if (part && part->passSelection && nsatisfied_lnus<mela_event.nRequested_AssociatedLeptons){
nsatisfied_lnus++;
associated_tmp.push_back(SimpleParticle_t(part->id, part->p4));
}
}
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::GetBoostedParticleVectors: aVhypo==0 lep case associated_tmp.size=" << associated_tmp.size() << endl;
// Adjust the kinematics of associated non-V-originating particles
if (associated_tmp.size()>=1){
size_t nffs = associated_tmp.size()/2;
for (size_t iv=0; iv<nffs; iv++){
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::GetBoostedParticleVectors: Removing mass from lepton pair " << 2*iv+0 << '\t' << 2*iv+1 << endl;
pair<TLorentzVector, TLorentzVector> corrPair = TUtil::removeMassFromPair(
associated_tmp.at(2*iv+0).second, associated_tmp.at(2*iv+0).first,
associated_tmp.at(2*iv+1).second, associated_tmp.at(2*iv+1).first
);
associated_tmp.at(2*iv+0).second = corrPair.first;
associated_tmp.at(2*iv+1).second = corrPair.second;
}
if (2*nffs<associated_tmp.size()){
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::GetBoostedParticleVectors: Removing mass from last lepton " << associated_tmp.size()-1 << endl;
TLorentzVector tmp = nullFourVector;
SimpleParticle_t& lastAssociated = associated_tmp.at(associated_tmp.size()-1);
pair<TLorentzVector, TLorentzVector> corrPair = TUtil::removeMassFromPair(
lastAssociated.second, lastAssociated.first,
tmp, -9000
);
lastAssociated.second = corrPair.first;
}
}
for (SimpleParticle_t& sp:associated_tmp) associated.push_back(sp); // Fill associated at the last step
}
// Associated jets
if (code%TVar::kUseAssociated_Jets==0){
SimpleParticleCollection_t associated_tmp;
for (MELAParticle* part:melaCand->getAssociatedJets()){
if (part && part->passSelection && nsatisfied_jets<mela_event.nRequested_AssociatedJets){
nsatisfied_jets++;
associated_tmp.push_back(SimpleParticle_t(part->id, part->p4));
}
}
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::GetBoostedParticleVectors: aVhypo==0 jet case associated_tmp.size=" << associated_tmp.size() << endl;
// Adjust the kinematics of associated non-V-originating particles
if (associated_tmp.size()>=1){
unsigned int nffs = associated_tmp.size()/2;
for (unsigned int iv=0; iv<nffs; iv++){
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::GetBoostedParticleVectors: Removing mass from jet pair " << 2*iv+0 << '\t' << 2*iv+1 << endl;
pair<TLorentzVector, TLorentzVector> corrPair = TUtil::removeMassFromPair(
associated_tmp.at(2*iv+0).second, associated_tmp.at(2*iv+0).first,
associated_tmp.at(2*iv+1).second, associated_tmp.at(2*iv+1).first
);
associated_tmp.at(2*iv+0).second = corrPair.first;
associated_tmp.at(2*iv+1).second = corrPair.second;
}
if (2*nffs<associated_tmp.size()){
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::GetBoostedParticleVectors: Removing mass from last jet " << associated_tmp.size()-1 << endl;
TLorentzVector tmp = nullFourVector;
SimpleParticle_t& lastAssociated = associated_tmp.at(associated_tmp.size()-1);
pair<TLorentzVector, TLorentzVector> corrPair = TUtil::removeMassFromPair(
lastAssociated.second, lastAssociated.first,
tmp, -9000
);
lastAssociated.second = corrPair.first;
}
}
for (SimpleParticle_t& sp:associated_tmp) associated.push_back(sp); // Fill associated at the last step
}
} // End if(aVhypo!=0)-else statement
if (code%TVar::kUseAssociated_Photons==0){
for (MELAParticle* part:melaCand->getAssociatedPhotons()){
if (part && part->passSelection && nsatisfied_gammas<mela_event.nRequested_AssociatedPhotons){
nsatisfied_gammas++;
associated.push_back(SimpleParticle_t(part->id, part->p4));
}
}
}
/***** END ASSOCIATED PARTICLES *****/
if (verbosity>=TVar::DEBUG) MELAout << "TUtil::GetBoostedParticleVectors: associated.size=" << associated.size() << endl;
/***** ASSOCIATED TOP OBJECTS *****/
int nsatisfied_tops=0;
int nsatisfied_antitops=0;
vector<SimpleParticleCollection_t> topDaughters;
vector<SimpleParticleCollection_t> antitopDaughters;
SimpleParticleCollection_t stableTops;
SimpleParticleCollection_t stableAntitops;
vector<MELATopCandidate_t*> tops;
vector<MELATopCandidate_t*> topbars;
vector<MELATopCandidate_t*> unknowntops;
if (code%TVar::kUseAssociated_StableTops==0 && code%TVar::kUseAssociated_UnstableTops==0 && verbosity>=TVar::INFO) MELAerr << "TUtil::GetBoostedParticleVectors: Stable and unstable tops are not supported at the same time!" << endl;
else if (code%TVar::kUseAssociated_StableTops==0 || code%TVar::kUseAssociated_UnstableTops==0){
for (MELATopCandidate_t* theTop:melaCand->getAssociatedTops()){
if (theTop && theTop->passSelection){
vector<MELATopCandidate_t*>* particleArray;
if (theTop->id==6) particleArray = &tops;
else if (theTop->id==-6) particleArray = &topbars;
else particleArray = &unknowntops;
if (
(code%TVar::kUseAssociated_StableTops==0)
||
(theTop->getNDaughters()==3 && code%TVar::kUseAssociated_UnstableTops==0)
) particleArray->push_back(theTop);
}
}
if (verbosity>=TVar::DEBUG){ MELAout << "TUtil::GetBoostedParticleVectors: tops.size=" << tops.size() << ", topbars.size=" << topbars.size() << ", unknowntops.size=" << unknowntops.size() << endl; }
// Fill the stable/unstable top arrays
for (MELATopCandidate_t* theTop:tops){
if (code%TVar::kUseAssociated_StableTops==0 && nsatisfied_tops<mela_event.nRequested_Tops){ // Case with no daughters needed
nsatisfied_tops++;
stableTops.push_back(SimpleParticle_t(theTop->id, theTop->p4));
}
else if (code%TVar::kUseAssociated_UnstableTops==0 && theTop->getNDaughters()==3 && nsatisfied_tops<mela_event.nRequested_Tops){ // Case with daughters needed
nsatisfied_tops++;
SimpleParticleCollection_t vdaughters;
MELAParticle* bottom = theTop->getPartnerParticle();
MELAParticle* Wf = theTop->getWFermion();
MELAParticle* Wfb = theTop->getWAntifermion();
if (bottom) vdaughters.push_back(SimpleParticle_t(bottom->id, bottom->p4));
if (Wf) vdaughters.push_back(SimpleParticle_t(Wf->id, Wf->p4));
if (Wfb) vdaughters.push_back(SimpleParticle_t(Wfb->id, Wfb->p4));
TUtil::adjustTopDaughters(vdaughters); // Adjust top daughter kinematics
if (vdaughters.size()==3) topDaughters.push_back(vdaughters);
}
}
for (MELATopCandidate_t* theTop:topbars){
if (code%TVar::kUseAssociated_StableTops==0 && nsatisfied_antitops<mela_event.nRequested_Antitops){ // Case with no daughters needed
nsatisfied_antitops++;
stableAntitops.push_back(SimpleParticle_t(theTop->id, theTop->p4));
}
else if (code%TVar::kUseAssociated_UnstableTops==0 && nsatisfied_antitops<mela_event.nRequested_Antitops){ // Case with daughters needed
nsatisfied_antitops++;
SimpleParticleCollection_t vdaughters;
MELAParticle* bottom = theTop->getPartnerParticle();
MELAParticle* Wf = theTop->getWFermion();
MELAParticle* Wfb = theTop->getWAntifermion();
if (bottom) vdaughters.push_back(SimpleParticle_t(bottom->id, bottom->p4));
if (Wf) vdaughters.push_back(SimpleParticle_t(Wf->id, Wf->p4));
if (Wfb) vdaughters.push_back(SimpleParticle_t(Wfb->id, Wfb->p4));
TUtil::adjustTopDaughters(vdaughters); // Adjust top daughter kinematics
if (vdaughters.size()==3) antitopDaughters.push_back(vdaughters);
}
else break;
}
// Loop over the unknown-id tops
// Fill tops, then antitops from the unknown tops
for (MELATopCandidate_t* theTop:unknowntops){
// t, then tb cases with no daughters needed
if (code%TVar::kUseAssociated_StableTops==0 && nsatisfied_tops<mela_event.nRequested_Tops){
nsatisfied_tops++;
stableTops.push_back(SimpleParticle_t(theTop->id, theTop->p4));
}
else if (code%TVar::kUseAssociated_StableTops==0 && nsatisfied_antitops<mela_event.nRequested_Antitops){
nsatisfied_antitops++;
stableAntitops.push_back(SimpleParticle_t(theTop->id, theTop->p4));
}
// t, then tb cases with daughters needed
else if (code%TVar::kUseAssociated_UnstableTops==0 && nsatisfied_tops<mela_event.nRequested_Tops){
nsatisfied_tops++;
SimpleParticleCollection_t vdaughters;
MELAParticle* bottom = theTop->getPartnerParticle();
MELAParticle* Wf = theTop->getWFermion();
MELAParticle* Wfb = theTop->getWAntifermion();
if (bottom) vdaughters.push_back(SimpleParticle_t(bottom->id, bottom->p4));
if (Wf) vdaughters.push_back(SimpleParticle_t(Wf->id, Wf->p4));
if (Wfb) vdaughters.push_back(SimpleParticle_t(Wfb->id, Wfb->p4));
TUtil::adjustTopDaughters(vdaughters); // Adjust top daughter kinematics
if (vdaughters.size()==3) topDaughters.push_back(vdaughters);
}
else if (code%TVar::kUseAssociated_UnstableTops==0 && nsatisfied_antitops<mela_event.nRequested_Antitops){
nsatisfied_antitops++;
SimpleParticleCollection_t vdaughters;
MELAParticle* bottom = theTop->getPartnerParticle();
MELAParticle* Wf = theTop->getWFermion();
MELAParticle* Wfb = theTop->getWAntifermion();
if (bottom) vdaughters.push_back(SimpleParticle_t(bottom->id, bottom->p4));
if (Wf) vdaughters.push_back(SimpleParticle_t(Wf->id, Wf->p4));
if (Wfb) vdaughters.push_back(SimpleParticle_t(Wfb->id, Wfb->p4));
TUtil::adjustTopDaughters(vdaughters); // Adjust top daughter kinematics
if (vdaughters.size()==3) antitopDaughters.push_back(vdaughters);
}
}
}
/***** END ASSOCIATED TOP OBJECTS *****/
if (verbosity>=TVar::DEBUG){
MELAout << "TUtil::GetBoostedParticleVectors: stableTops.size=" << stableTops.size() << endl;
MELAout << "TUtil::GetBoostedParticleVectors: stableAntitops.size=" << stableAntitops.size() << endl;
MELAout << "TUtil::GetBoostedParticleVectors: topDaughters.size=" << topDaughters.size() << endl;
for (unsigned int itop=0; itop<topDaughters.size(); itop++) MELAout << "TUtil::GetBoostedParticleVectors: topDaughters.at(" << itop << ").size=" << topDaughters.at(itop).size() << endl;
MELAout << "TUtil::GetBoostedParticleVectors: antitopDaughters.size=" << antitopDaughters.size() << endl;
for (unsigned int itop=0; itop<antitopDaughters.size(); itop++) MELAout << "TUtil::GetBoostedParticleVectors: antitopDaughters.at(" << itop << ").size=" << antitopDaughters.at(itop).size() << endl;
}
/***** BOOSTS TO THE CORRECT PT=0 FRAME *****/
// Gather all final state particles collected for this frame
TLorentzVector pTotal(0, 0, 0, 0);
for (SimpleParticle_t const& sp:daughters) pTotal = pTotal + sp.second;
for (SimpleParticle_t const& sp:associated) pTotal = pTotal + sp.second;
for (SimpleParticle_t const& sp:stableTops) pTotal = pTotal + sp.second;
for (SimpleParticle_t const& sp:stableAntitops) pTotal = pTotal + sp.second;
for (SimpleParticleCollection_t const& spc:topDaughters){ for (SimpleParticle_t const& sp:spc) pTotal = pTotal + sp.second; }
for (SimpleParticleCollection_t const& spc:antitopDaughters){ for (SimpleParticle_t const& sp:spc) pTotal = pTotal + sp.second; }
// Get the boost vector and boost all final state particles
double qX = pTotal.X();
double qY = pTotal.Y();
double qE = pTotal.T();
if ((qX*qX+qY*qY)>0.){
TVector3 boostV(-qX/qE, -qY/qE, 0.);
for (SimpleParticle_t& sp:daughters) sp.second.Boost(boostV);
for (SimpleParticle_t& sp:associated) sp.second.Boost(boostV);
for (SimpleParticle_t& sp:stableTops) sp.second.Boost(boostV);
for (SimpleParticle_t& sp:stableAntitops) sp.second.Boost(boostV);
for (SimpleParticleCollection_t& spc:topDaughters){ for (SimpleParticle_t& sp:spc) sp.second.Boost(boostV); }
for (SimpleParticleCollection_t& spc:antitopDaughters){ for (SimpleParticle_t& sp:spc) sp.second.Boost(boostV); }
pTotal.Boost(boostV);
}
// Mothers need special treatment:
// In case they are undefined, mother id is unknown, and mothers are ordered as M1==(pz>0) and M2==(pz<0).
// In case they are defined, mothers are first matched to the assumed momenta through their pz's.
// They are ordered by M1==f, M2==fb afterward if this is possible.
// Notice that the momenta of the mother objects are not actually used. If the event is truly a gen. particle, everything would be in the pT=0 frame to begin with, and everybody is happy in reweighting.
double sysPz= pTotal.Z();
double sysE = pTotal.T();
double pz0 = (sysE+sysPz)/2.;
double pz1 = -(sysE-sysPz)/2.;
double E0 = pz0;
double E1 = -pz1;
int motherId[2]={ 0, 0 };
if (melaCand->getNMothers()==2){
for (int ip=0; ip<2; ip++) motherId[ip]=melaCand->getMother(ip)->id;
// Match the "assumed" M'1==(larger signed pz) and M'2==(smaller signed pz) to the pz of the actual mothers:
// Swap pZs to get the correct momentum matching default M1, M2.
if (TMath::Sign(1., melaCand->getMother(0)->z()-melaCand->getMother(1)->z())!=TMath::Sign(1., pz0-pz1)){ swap(pz0, pz1); swap(E0, E1); }
// Swap the ids of mothers and their pT=0-assumed momenta to achieve ordering as "incoming" q-qbar
if ((motherId[0]<0 && motherId[1]>=0) || (motherId[1]>0 && motherId[0]<=0)){
swap(pz0, pz1);
swap(E0, E1);
swap(motherId[0], motherId[1]);
}
}
TLorentzVector pM[2];
pM[0].SetXYZT(0., 0., pz0, E0);
pM[1].SetXYZT(0., 0., pz1, E1);
// Fill the ids of the V intermediates to the candidate daughters
mela_event.intermediateVid.clear();
TUtilHelpers::copyVector(idVstar, mela_event.intermediateVid);
// Fill the mothers
mela_event.pMothers.clear();
for (unsigned int ip=0; ip<2; ip++){ mela_event.pMothers.push_back(SimpleParticle_t(motherId[ip], pM[ip])); }
// Fill the daughters
mela_event.pDaughters.clear();
TUtilHelpers::copyVector(daughters, mela_event.pDaughters);
// Fill the associated particles
mela_event.pAssociated.clear();
TUtilHelpers::copyVector(associated, mela_event.pAssociated);
// Fill the stable tops and antitops
mela_event.pStableTops.clear();
TUtilHelpers::copyVector(stableTops, mela_event.pStableTops);
mela_event.pStableAntitops.clear();
TUtilHelpers::copyVector(stableAntitops, mela_event.pStableAntitops);
// Fill the daughters of unstable tops and antitops
mela_event.pTopDaughters.clear();
TUtilHelpers::copyVector(topDaughters, mela_event.pTopDaughters);
mela_event.pAntitopDaughters.clear();
TUtilHelpers::copyVector(antitopDaughters, mela_event.pAntitopDaughters);
// This is the end of one long function.
if (verbosity>=TVar::DEBUG){
MELAout << "TUtil::GetBoostedParticleVectors mela_event.intermediateVid.size=" << mela_event.intermediateVid.size() << endl;
MELAout << "TUtil::GetBoostedParticleVectors mela_event.pMothers.size=" << mela_event.pMothers.size() << endl;
MELAout << "TUtil::GetBoostedParticleVectors mela_event.pDaughters.size=" << mela_event.pDaughters.size() << endl;
MELAout << "TUtil::GetBoostedParticleVectors mela_event.pAssociated.size=" << mela_event.pAssociated.size() << endl;
MELAout << "TUtil::GetBoostedParticleVectors mela_event.pStableTops.size=" << mela_event.pStableTops.size() << endl;
MELAout << "TUtil::GetBoostedParticleVectors mela_event.pStableAntitops.size=" << mela_event.pStableAntitops.size() << endl;
MELAout << "TUtil::GetBoostedParticleVectors mela_event.pTopDaughters.size=" << mela_event.pTopDaughters.size() << endl;
MELAout << "TUtil::GetBoostedParticleVectors mela_event.pAntitopDaughters.size=" << mela_event.pAntitopDaughters.size() << endl;
MELAout << "End GetBoostedParticleVectors" << endl;
}
}
// Convert vectors of simple particles to MELAParticles and create a MELACandidate
// The output lists could be members of TEvtProb directly.
MELACandidate* TUtil::ConvertVectorFormat(
// Inputs
SimpleParticleCollection_t* pDaughters,
SimpleParticleCollection_t* pAssociated,
SimpleParticleCollection_t* pMothers,
bool isGen,
// Outputs
std::vector<MELAParticle*>* particleList,
std::vector<MELACandidate*>* candList
){
MELACandidate* cand=nullptr;
if (!pDaughters){ MELAerr << "TUtil::ConvertVectorFormat: No daughters!" << endl; return cand; }
else if (pDaughters->size()==0){ MELAerr << "TUtil::ConvertVectorFormat: Daughter size==0!" << endl; return cand; }
else if (pDaughters->size()>4){ MELAerr << "TUtil::ConvertVectorFormat: Daughter size " << pDaughters->size() << ">4 is not supported!" << endl; return cand; }
if (pMothers && pMothers->size()!=2){ MELAerr << "TUtil::ConvertVectorFormat: Mothers momentum size (" << pMothers->size() << ") has to have had been 2! Continuing by omitting mothers." << endl; /*return cand;*/ }
// Create mother, daughter and associated particle MELAParticle objects
std::vector<MELAParticle*> daughters;
std::vector<MELAParticle*> aparticles;
std::vector<MELAParticle*> mothers;
for (auto& spart:(*pDaughters)){
MELAParticle* onePart = new MELAParticle(spart.first, spart.second);
onePart->setGenStatus(1); // Final state status
if (particleList) particleList->push_back(onePart);
daughters.push_back(onePart);
}
if (pAssociated){
for (auto& spart:(*pAssociated)){
MELAParticle* onePart = new MELAParticle(spart.first, spart.second);
onePart->setGenStatus(1); // Final state status
if (particleList) particleList->push_back(onePart);
aparticles.push_back(onePart);
}
}
if (pMothers && pMothers->size()==2){
for (auto& spart:(*pMothers)){
MELAParticle* onePart = new MELAParticle(spart.first, spart.second);
onePart->setGenStatus(-1); // Mother status
if (particleList) particleList->push_back(onePart);
mothers.push_back(onePart);
}
}
// Create the candidate
/***** Adaptation of LHEAnalyzer::Event::constructVVCandidates *****/
/*
The assumption is that the daughters make sense for either ffb, gamgam, Zgam, ZZ or WW.
No checking is done on whether particle-antiparticle pairing is correct when necessary.
If not, you will get a seg. fault!
*/
// Undecayed Higgs
if (daughters.size()==1){
cand = new MELACandidate(25, (daughters.at(0))->p4); // No sorting!
cand->setDecayMode(TVar::CandidateDecay_Stable); // Explicitly set the decay mode in case the default of MELACandidate changes in the future
}
// GG / ff final states
else if (daughters.size()==2){
MELAParticle* F1 = daughters.at(0);
MELAParticle* F2 = daughters.at(1);
TLorentzVector pH = F1->p4+F2->p4;
cand = new MELACandidate(25, pH);
cand->addDaughter(F1);
cand->addDaughter(F2);
TVar::CandidateDecayMode defaultHDecayMode = PDGHelpers::HDecayMode;
if (PDGHelpers::isAPhoton(F1->id) && PDGHelpers::isAPhoton(F2->id)) PDGHelpers::setCandidateDecayMode(TVar::CandidateDecay_GG);
else PDGHelpers::setCandidateDecayMode(TVar::CandidateDecay_ff);
cand->sortDaughters();
PDGHelpers::setCandidateDecayMode(defaultHDecayMode);
}
// ZG / WG
else if (daughters.size()==3){
MELAParticle* F1 = daughters.at(0);
MELAParticle* F2 = daughters.at(1);
MELAParticle* gamma = daughters.at(2);
if (PDGHelpers::isAPhoton(F1->id)){
MELAParticle* tmp = F1;
F1 = gamma;
gamma = tmp;
}
else if (PDGHelpers::isAPhoton(F2->id)){
MELAParticle* tmp = F2;
F2 = gamma;
gamma = tmp;
}
TLorentzVector pH = F1->p4+F2->p4+gamma->p4;
double charge = F1->charge()+F2->charge()+gamma->charge();
cand = new MELACandidate(25, pH);
cand->addDaughter(F1);
cand->addDaughter(F2);
cand->addDaughter(gamma);
TVar::CandidateDecayMode defaultHDecayMode = PDGHelpers::HDecayMode;
if (fabs(charge)<0.01) PDGHelpers::setCandidateDecayMode(TVar::CandidateDecay_ZG); // ZG
else PDGHelpers::setCandidateDecayMode(TVar::CandidateDecay_WG); // WG, un-tested
cand->sortDaughters();
PDGHelpers::setCandidateDecayMode(defaultHDecayMode);
}
// ZZ / WW / ZW (!)
else/* if (daughters.size()==4)*/{
TLorentzVector pH(0, 0, 0, 0);
double charge = 0.;
for (unsigned char ip=0; ip<4; ip++){ pH = pH + (daughters.at(ip))->p4; charge += (daughters.at(ip))->charge(); }
cand = new MELACandidate(25, pH);
for (unsigned char ip=0; ip<4; ip++) cand->addDaughter(daughters.at(ip));
// FIXME/REIMPLEMENT: ZW trickier than I thought: Summing over charges over all 4f is not enough, affects SSSF pairing in ZZ
//TVar::CandidateDecayMode defaultHDecayMode = PDGHelpers::HDecayMode;
//if (fabs(charge)>0.01) PDGHelpers::setCandidateDecayMode(TVar::CandidateDecay_ZW);
if (
PDGHelpers::HDecayMode!=TVar::CandidateDecay_WW
&& PDGHelpers::HDecayMode!=TVar::CandidateDecay_ZZ
&& PDGHelpers::HDecayMode!=TVar::CandidateDecay_ZW
){
MELAerr << "TUtil::ConvertVectorFormat: PDGHelpers::HDecayMode = " << PDGHelpers::HDecayMode << " is set incorrectly for Ndaughters=" << daughters.size() << ". There is no automatic mechnism for this scenario. ";
MELAerr << "Suggestion: Call PDGHelpers::setCandidateDecayMode(TVar::CandidateDecay_XY) before this call." << endl;
assert(0);
}
cand->sortDaughters();
//PDGHelpers::setCandidateDecayMode(defaultHDecayMode);
}
/***** Adaptation of LHEAnalyzer::Event::addVVCandidateMother *****/
if (!mothers.empty()){ // ==2
for (auto& part:mothers) cand->addMother(part);
if (isGen) cand->setGenStatus(-1); // Candidate is a gen. particle!
}
/***** Adaptation of LHEAnalyzer::Event::addVVCandidateAppendages *****/
if (!aparticles.empty()){
for (auto& part:aparticles){
const int& partId = part->id;
if (PDGHelpers::isALepton(partId)) cand->addAssociatedLepton(part);
else if (PDGHelpers::isANeutrino(partId)) cand->addAssociatedNeutrino(part); // Be careful: Neutrinos are neutrinos, but also "leptons" in MELACandidate!
else if (PDGHelpers::isAPhoton(partId)) cand->addAssociatedPhoton(part);
else if (PDGHelpers::isAJet(partId)) cand->addAssociatedJet(part);
}
cand->addAssociatedVs(); // For the VH topology
}
if (candList && cand) candList->push_back(cand);
return cand;
}
// Convert the vector of three body decay daughters (as simple particles) to MELAParticles and create a MELAThreeBodyDecayCandidate
// The output lists could be members of TEvtProb directly.
MELAThreeBodyDecayCandidate* TUtil::ConvertThreeBodyDecayCandidate(
// Input
SimpleParticleCollection_t* tbdDaughters,
// Outputs
std::vector<MELAParticle*>* particleList,
std::vector<MELAThreeBodyDecayCandidate*>* tbdCandList
){
MELAThreeBodyDecayCandidate* cand=nullptr;
if (!tbdDaughters){ MELAerr << "TUtil::ConvertThreeBodyDecayCandidate: No daughters!" << endl; return cand; }
else if (tbdDaughters->empty()){ MELAerr << "TUtil::ConvertThreeBodyDecayCandidate: Daughter size==0!" << endl; return cand; }
else if (!(tbdDaughters->size()==1 || tbdDaughters->size()==3)){ MELAerr << "TUtil::ConvertThreeBodyDecayCandidate: Daughter size " << tbdDaughters->size() << "!=1 or 3 is not supported!" << endl; return cand; }
if (tbdDaughters->size()==1){
if (abs((tbdDaughters->at(0)).first)==6 || (tbdDaughters->at(0)).first==0){
cand = new MELAThreeBodyDecayCandidate((tbdDaughters->at(0)).first, (tbdDaughters->at(0)).second);
tbdCandList->push_back(cand);
}
}
else if (tbdDaughters->size()==3){
MELAParticle* partnerPart = new MELAParticle((tbdDaughters->at(0)).first, (tbdDaughters->at(0)).second);
MELAParticle* Wf = new MELAParticle((tbdDaughters->at(1)).first, (tbdDaughters->at(1)).second);
MELAParticle* Wfb = new MELAParticle((tbdDaughters->at(2)).first, (tbdDaughters->at(2)).second);
if (Wf->id<0 || Wfb->id>0) std::swap(Wf, Wfb);
particleList->push_back(partnerPart);
particleList->push_back(Wf);
particleList->push_back(Wfb);
cand = new MELAThreeBodyDecayCandidate(partnerPart, Wf, Wfb);
tbdCandList->push_back(cand);
}
return cand;
}
void TUtil::PrintCandidateSummary(MELACandidate* cand){
MELAout << "***** TUtil::PrintCandidateSummary *****" << endl;
MELAout << "Candidate: " << cand << endl;
if (cand) MELAout << *cand;
}
void TUtil::PrintCandidateSummary(simple_event_record* cand){
MELAout << "***** TUtil::PrintCandidateSummary (Simple Event Record) *****" << endl;
MELAout << "Candidate: " << cand << endl;
if (cand){
MELAout << "\tAssociationCode: " << cand->AssociationCode << endl;
MELAout << "\tAssociationVCompatibility: " << cand->AssociationVCompatibility << endl;
MELAout << "\tnRequested_AssociatedJets: " << cand->nRequested_AssociatedJets << endl;
MELAout << "\tnRequested_AssociatedLeptons: " << cand->nRequested_AssociatedLeptons << endl;
MELAout << "\tnRequested_AssociatedPhotons: " << cand->nRequested_AssociatedPhotons << endl;
MELAout << "\tnRequested_Tops: " << cand->nRequested_Tops << endl;
MELAout << "\tnRequested_Antitops: " << cand->nRequested_Antitops << endl;
MELAout << "\tHas " << cand->pMothers.size() << " mothers" << endl;
for (unsigned int ip=0; ip<cand->pMothers.size(); ip++){
SimpleParticle_t* part = &(cand->pMothers.at(ip));
MELAout
<< "\t\tV" << ip << " (" << part->first << ") (X,Y,Z,T)=( "
<< part->second.X() << " , "
<< part->second.Y() << " , "
<< part->second.Z() << " , "
<< part->second.T() << " )" << endl;
}
MELAout << "\tHas " << cand->intermediateVid.size() << " sorted daughter Vs" << endl;
for (unsigned int iv=0; iv<cand->intermediateVid.size(); iv++) MELAout << "\t\tV" << iv << " (" << cand->intermediateVid.at(iv) << ")" << endl;
MELAout << "\tHas " << cand->pDaughters.size() << " daughters" << endl;
for (unsigned int ip=0; ip<cand->pDaughters.size(); ip++){
SimpleParticle_t* part = &(cand->pDaughters.at(ip));
MELAout
<< "\t\tDau[" << ip << "] (" << part->first << ") (X,Y,Z,T)=( "
<< part->second.X() << " , "
<< part->second.Y() << " , "
<< part->second.Z() << " , "
<< part->second.T() << " )" << endl;
}
MELAout << "\tHas " << cand->pAssociated.size() << " associated particles" << endl;
for (unsigned int ip=0; ip<cand->pAssociated.size(); ip++){
SimpleParticle_t* part = &(cand->pAssociated.at(ip));
MELAout
<< "\t\tAPart[" << ip << "] (" << part->first << ") (X,Y,Z,T)=( "
<< part->second.X() << " , "
<< part->second.Y() << " , "
<< part->second.Z() << " , "
<< part->second.T() << " )" << endl;
}
MELAout << "\tHas " << cand->pStableTops.size() << " stable tops" << endl;
for (unsigned int ip=0; ip<cand->pStableTops.size(); ip++){
SimpleParticle_t* part = &(cand->pStableTops.at(ip));
MELAout
<< "\t\tAPart[" << ip << "] (" << part->first << ") (X,Y,Z,T)=( "
<< part->second.X() << " , "
<< part->second.Y() << " , "
<< part->second.Z() << " , "
<< part->second.T() << " )" << endl;
}
MELAout << "\tHas " << cand->pStableAntitops.size() << " stable antitops" << endl;
for (unsigned int ip=0; ip<cand->pStableAntitops.size(); ip++){
SimpleParticle_t* part = &(cand->pStableAntitops.at(ip));
MELAout
<< "\t\tAPart[" << ip << "] (" << part->first << ") (X,Y,Z,T)=( "
<< part->second.X() << " , "
<< part->second.Y() << " , "
<< part->second.Z() << " , "
<< part->second.T() << " )" << endl;
}
MELAout << "\tHas " << cand->pTopDaughters.size() << " unstable tops" << endl;
for (unsigned int ip=0; ip<cand->pTopDaughters.size(); ip++){
MELAout << "\t\tTop[" << ip << "] daughters:" << endl;
for (unsigned int jp=0; jp<cand->pTopDaughters.at(ip).size(); jp++){
SimpleParticle_t* part = &(cand->pTopDaughters.at(ip).at(jp));
MELAout
<< "\t\t- Top daughter[" << ip << jp << "] (" << part->first << ") (X,Y,Z,T)=( "
<< part->second.X() << " , "
<< part->second.Y() << " , "
<< part->second.Z() << " , "
<< part->second.T() << " )" << endl;
}
}
MELAout << "\tHas " << cand->pAntitopDaughters.size() << " unstable antitops" << endl;
for (unsigned int ip=0; ip<cand->pAntitopDaughters.size(); ip++){
MELAout << "\t\tAntitop[" << ip << "] daughters:" << endl;
for (unsigned int jp=0; jp<cand->pAntitopDaughters.at(ip).size(); jp++){
SimpleParticle_t* part = &(cand->pAntitopDaughters.at(ip).at(jp));
MELAout
<< "\t\t- Antitop daughter[" << ip << jp << "] (" << part->first << ") (X,Y,Z,T)=( "
<< part->second.X() << " , "
<< part->second.Y() << " , "
<< part->second.Z() << " , "
<< part->second.T() << " )" << endl;
}
}
}
}
| 49.081649 | 320 | 0.629324 | [
"object",
"vector",
"transform"
] |
5885332a6fe8d11365fbaff856a63690891caa98 | 6,062 | cpp | C++ | compiler/exo/src/Pass/MergeConcatNodesPass.cpp | chogba6/ONE | 3d35259f89ee3109cfd35ab6f38c231904487f3b | [
"Apache-2.0"
] | 255 | 2020-05-22T07:45:29.000Z | 2022-03-29T23:58:22.000Z | compiler/exo/src/Pass/MergeConcatNodesPass.cpp | chogba6/ONE | 3d35259f89ee3109cfd35ab6f38c231904487f3b | [
"Apache-2.0"
] | 5,102 | 2020-05-22T07:48:33.000Z | 2022-03-31T23:43:39.000Z | compiler/exo/src/Pass/MergeConcatNodesPass.cpp | chogba6/ONE | 3d35259f89ee3109cfd35ab6f38c231904487f3b | [
"Apache-2.0"
] | 120 | 2020-05-22T07:51:08.000Z | 2022-02-16T19:08:05.000Z | /*
* Copyright (c) 2019 Samsung Electronics Co., Ltd. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "MergeConcatNodesPass.h"
#include "Dialect/IR/TFLNodes.h"
#include <oops/InternalExn.h>
#include <vector>
namespace
{
bool canMerge(locoex::TFLConcatenation *node1, locoex::TFLConcatenation *node2)
{
if (node1->fusedActivationFunction() != node2->fusedActivationFunction())
return false;
if (node1->axis() != node2->axis())
return false;
switch (node1->fusedActivationFunction())
{
case locoex::FusedActFunc::NONE:
case locoex::FusedActFunc::RELU:
case locoex::FusedActFunc::RELU6:
return true;
// case locoex::FusedActFunc::TANH:
// return false;
default:
INTERNAL_EXN_V("Unknown FusedActFunc", oops::to_uint32(node1->fusedActivationFunction()));
}
}
/**
* @brief Collect all the inputs of newly created TFLConcatenation nodes
*
* in:0 -------------------------------\
* in:1 ---- TFLConcatenation:0 -------- TFLConcatenation:3 --- C
* (axis = 0, NONE) (axis = 0, NONE)
* in:2 ---/ /
* in:3 ---- TFLConcatenation:1 ------/
* (axis = 1, NONE) /
* in:4 ---/ /
* in:5 ---- TFLConcatenation:2 ---/
* (axis = 0, RELU)
* in:6 ---/
*
* For exmaple, if graph is like above, dfs(TFLConcatenation:3) will
* return [in:0, in:1, in:2, TFLConcatenation:1, TFLConcatenation:2]
*
* TFLConcatenation:0 can be merged to TFLConcatenation:3,
* because axis and fusedActivationFunction are same.
* It means that [in:1, in:2] will be linked as inputs of new TFLConcatenation.
*
* However, TFLConcatenation:1 and TFLConcatenation:2 cannot be merged to
* TFLConcatenation:3 because axis and fusedActivationFunction of each are different.
* So [in:3, in:4, in:5, in:6] will not be linked as inputs of new TFLConcatenation
* and [TFLConcatenation:1, TFLConcatenation:2] will be linked instead.
*
* Therefore, inputs of newly created TFLConcatenation node for merging
* TFLConcatenation:3 will be [in:0, in:1, in:2, TFLConcatenation:1, TFLConcatenation:2]
* and dfs(TFLConcatenation:3) will return it.
*
*
* @note The input nodes should be traversed by LRV,
* which is from left to right (input:0 --> input:N)
*/
std::vector<loco::Node *> dfs(locoex::TFLConcatenation *root)
{
std::vector<loco::Node *> res;
for (uint32_t i = 0; i < root->numValues(); ++i)
{
auto input = dynamic_cast<locoex::TFLConcatenation *>(root->values(i));
if (input != nullptr && canMerge(input, root))
{
auto children = dfs(input);
for (auto child : children)
res.push_back(child);
}
else
{
res.push_back(root->values(i));
}
}
return res;
}
} // namespace
namespace exo
{
/**
* @brief Merge TFLConcatenate nodes whose axis and fusedActivationFunction are same
*
* [Before]
* in:0 -------------------------------\
* in:1 ---- TFLConcatenation:0 -------- TFLConcatenation:3 --- C
* (axis = 0, NONE) (axis = 0, NONE)
* in:2 ---/ /
* in:3 ---- TFLConcatenation:1 ------/
* (axis = 1, NONE) /
* in:4 ---/ /
* in:5 ---- TFLConcatenation:2 ---/
* (axis = 0, RELU)
* in:6 ---/
*
* [After]
* in:0 -------------------------------\
* in:1 -------------------------------- TFLConcatenation:4 --- C
* (axis = 0, NONE)
* in:2 -------------------------------/
* in:3 ---- TFLConcatenation:1 ------/
* (axis = 1, NONE) /
* in:4 ---/ /
* in:5 ---- TFLConcatenation:2 ---/
* (axis = 0, RELU)
* in:6 ---/
*
*
* in:1 ---- TFLConcatenation:0 ----
* (axis = 0, NONE)
* in:2 ---/
*
*
* ---- TFLConcatenation:3 ----
* (axis = 0, NONE)
*/
bool MergeConcatNodesPass::run(loco::Graph *graph)
{
// Let's enumerate nodes required to compute output nodes
auto active_nodes = loco::active_nodes(loco::output_nodes(graph));
// Find TFLConcatenation nodes which have another TFLConcatenation nodes
// as inputs, with same axis and same fusedActivationFunction
std::vector<locoex::TFLConcatenation *> candidates;
for (auto node : active_nodes)
{
if (auto concat = dynamic_cast<locoex::TFLConcatenation *>(node))
{
for (uint32_t i = 0; i < concat->numValues(); ++i)
{
auto input = dynamic_cast<locoex::TFLConcatenation *>(concat->values(i));
if (input != nullptr && canMerge(input, concat))
{
candidates.push_back(concat);
break;
}
}
}
}
// Merge multiple TFLConcatenation nodes as one TFLConcatenation node
for (auto node : candidates)
{
auto inputs = dfs(node);
auto new_concat = graph->nodes()->create<locoex::TFLConcatenation>(inputs.size());
new_concat->axis(node->axis());
new_concat->fusedActivationFunction(node->fusedActivationFunction());
for (uint32_t i = 0; i < inputs.size(); ++i)
new_concat->values(i, inputs.at(i));
loco::replace(node).with(new_concat);
for (uint32_t i = 0; i < node->numValues(); ++i)
node->values(i, nullptr);
}
return candidates.size() > 0;
}
} // namespace exo
| 31.572917 | 96 | 0.571264 | [
"vector"
] |
588736af698333d3a57380469e9faf6ccd890576 | 2,790 | hpp | C++ | KFContrib/KFNetwork/KFNetEvent.hpp | 282951387/KFrame | 5d6e953f7cc312321c36632715259394ca67144c | [
"Apache-2.0"
] | 1 | 2021-04-26T09:31:32.000Z | 2021-04-26T09:31:32.000Z | KFContrib/KFNetwork/KFNetEvent.hpp | 282951387/KFrame | 5d6e953f7cc312321c36632715259394ca67144c | [
"Apache-2.0"
] | null | null | null | KFContrib/KFNetwork/KFNetEvent.hpp | 282951387/KFrame | 5d6e953f7cc312321c36632715259394ca67144c | [
"Apache-2.0"
] | null | null | null | #ifndef __NET_EVENT_H__
#define __NET_EVENT_H__
#include "KFNetDefine.hpp"
#include "KFQueue.h"
namespace KFrame
{
// 网络时间函数
typedef std::function<void( const KFNetEventData* eventdata )> KFEventFunction;
typedef std::function<void( const KFNetEventData* eventdata )> KFNetServerFunction;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class KFNetEvent
{
public:
KFNetEvent();
virtual ~KFNetEvent();
// 初始化
void InitEvent( uint32 maxcount );
// 关闭
void ShutEvent();
// 添加连接事件
void AddEvent( uint32 type, uint64 id, void* data = nullptr, const char* describe = "", int32 code = 0 );
// 事件更新
void RunEvent();
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// 绑定连接事件
template< class T >
void BindConnectFunction( T* object, void ( T::*handle )( const KFNetEventData* eventdata ) )
{
_kf_connect_function = std::bind( handle, object, std::placeholders::_1 );
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// 绑定关闭事件
template< class T >
void BindDisconnectFunction( T* object, void ( T::*handle )( const KFNetEventData* eventdata ) )
{
_kf_disconnect_function = std::bind( handle, object, std::placeholders::_1 );
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// 绑定失败事件
template< class T >
void BindFailedFunction( T* object, void ( T::*handle )( const KFNetEventData* eventdata ) )
{
_kf_failed_function = std::bind( handle, object, std::placeholders::_1 );
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// 绑定关闭事件
template< class T >
void BindShutFunction( T* object, void ( T::*handle )( const KFNetEventData* eventdata ) )
{
_kf_shut_function = std::bind( handle, object, std::placeholders::_1 );
}
protected:
// 处理绑定时间
void HandleBindEventFunction( const KFNetEventData* eventdata );
protected:
// 回调函数
KFEventFunction _kf_connect_function;
KFEventFunction _kf_disconnect_function;
KFEventFunction _kf_failed_function;
KFEventFunction _kf_shut_function;
// 事件列表
KFQueue< KFNetEventData > _net_event_data;
};
}
#endif | 35.769231 | 124 | 0.453405 | [
"object"
] |
5887933c93d09fbd3f5c503f8e709d91833d6c69 | 91,095 | cxx | C++ | TRD/TRDbase/AliTRDCalibraFillHisto.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | TRD/TRDbase/AliTRDCalibraFillHisto.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | TRD/TRDbase/AliTRDCalibraFillHisto.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | //**************************************************************************
// * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
// * *
// * Author: The ALICE Off-line Project. *
// * Contributors are mentioned in the code where appropriate. *
// * *
// * Permission to use, copy, modify and distribute this software and its *
// * documentation strictly for non-commercial purposes is hereby granted *
// * without fee, provided that the above copyright notice appears in all *
// * copies and that both the copyright notice and this permission notice *
//* appear in the supporting documentation. The authors make no claims *
//* about the suitability of this software for any purpose. It is *
//* provided "as is" without express or implied warranty. *
//**************************************************************************/
/* $Id$ */
/////////////////////////////////////////////////////////////////////////////////
//
// AliTRDCalibraFillHisto
//
// This class is for the TRD calibration of the relative gain factor, the drift velocity,
// the time 0 and the pad response function. It fills histos or vectors.
// It can be used for the calibration per chamber but also per group of pads and eventually per pad.
// The user has to choose with the functions SetNz and SetNrphi the precision of the calibration (see AliTRDCalibraMode).
// 2D Histograms (Histo2d) or vectors (Vector2d), then converted in Trees, will be filled
// from RAW DATA in a run or from reconstructed TRD tracks during the offline tracking
// in the function "FollowBackProlongation" (AliTRDtracker)
// Per default the functions to fill are off.
//
// Authors:
// R. Bailhache (R.Bailhache@gsi.de, rbailhache@ikf.uni-frankfurt.de)
// J. Book (jbook@ikf.uni-frankfurt.de)
//
//////////////////////////////////////////////////////////////////////////////////////
#include <TProfile2D.h>
#include <TProfile.h>
#include <TFile.h>
#include <TStyle.h>
#include <TCanvas.h>
#include <TObjArray.h>
#include <TObject.h>
#include <TH1F.h>
#include <TH2I.h>
#include <TH2.h>
#include <TStopwatch.h>
#include <TMath.h>
#include <TDirectory.h>
#include <TTreeStream.h>
#include <TVectorD.h>
#include <TLinearFitter.h>
#include "AliLog.h"
#include "AliESDtrack.h"
#include "AliTRDCalibraFillHisto.h"
#include "AliTRDCalibraMode.h"
#include "AliTRDCalibraVector.h"
#include "AliTRDCalibraVdriftLinearFit.h"
#include "AliTRDCalibraExbAltFit.h"
#include "AliTRDcalibDB.h"
#include "AliTRDCommonParam.h"
#include "AliTRDpadPlane.h"
#include "AliTRDcluster.h"
#include "AliTRDtrackV1.h"
#include "AliRawReader.h"
#include "AliRawReaderDate.h"
#include "AliTRDgeometry.h"
#include "AliTRDfeeParam.h"
#include "AliTRDCalROC.h"
#include "AliTRDCalPad.h"
#include "AliTRDCalDet.h"
#include "AliTRDdigitsManager.h"
#include "AliTRDdigitsParam.h"
#include "AliTRDSignalIndex.h"
#include "AliTRDarrayADC.h"
#include "AliTRDrawStream.h"
#include "AliCDBEntry.h"
#include "AliCDBManager.h"
#ifdef ALI_DATE
#include "event.h"
#endif
ClassImp(AliTRDCalibraFillHisto)
AliTRDCalibraFillHisto* AliTRDCalibraFillHisto::fgInstance = 0;
Bool_t AliTRDCalibraFillHisto::fgTerminated = kFALSE;
//_____________singleton implementation_________________________________________________
AliTRDCalibraFillHisto *AliTRDCalibraFillHisto::Instance()
{
//
// Singleton implementation
//
if (fgTerminated != kFALSE) {
return 0;
}
if (fgInstance == 0) {
fgInstance = new AliTRDCalibraFillHisto();
}
return fgInstance;
}
//______________________________________________________________________________________
void AliTRDCalibraFillHisto::Terminate()
{
//
// Singleton implementation
// Deletes the instance of this class
//
fgTerminated = kTRUE;
if (fgInstance != 0) {
delete fgInstance;
fgInstance = 0;
}
}
//______________________________________________________________________________________
AliTRDCalibraFillHisto::AliTRDCalibraFillHisto()
:TObject()
,fGeo(0)
,fCalibDB(0)
,fIsHLT(kFALSE)
,fCH2dOn(kFALSE)
,fPH2dOn(kFALSE)
,fPRF2dOn(kFALSE)
,fHisto2d(kFALSE)
,fVector2d(kFALSE)
,fLinearFitterOn(kFALSE)
,fLinearFitterDebugOn(kFALSE)
,fExbAltFitOn(kFALSE)
,fScaleWithTPCSignal(kFALSE)
,fRelativeScale(0)
,fThresholdClusterPRF2(15.0)
,fLimitChargeIntegration(kFALSE)
,fFillWithZero(kFALSE)
,fNormalizeNbOfCluster(kFALSE)
,fMaxCluster(0)
,fNbMaxCluster(0)
,fCutWithVdriftCalib(kFALSE)
,fMinNbTRDtracklets(0)
,fMinTRDMomentum(0.0)
,fTakeSnapshot(kTRUE)
,fFirstRunGain(0)
,fVersionGainUsed(0)
,fSubVersionGainUsed(0)
,fFirstRunGainLocal(0)
,fVersionGainLocalUsed(0)
,fSubVersionGainLocalUsed(0)
,fFirstRunVdrift(0)
,fVersionVdriftUsed(0)
,fSubVersionVdriftUsed(0)
,fFirstRunExB(0)
,fVersionExBUsed(0)
,fSubVersionExBUsed(0)
,fCalibraMode(new AliTRDCalibraMode())
,fDebugStreamer(0)
,fDebugLevel(0)
,fDetectorPreviousTrack(-1)
,fMCMPrevious(-1)
,fROBPrevious(-1)
,fNumberClusters(1)
,fNumberClustersf(30)
,fNumberClustersProcent(0.5)
,fThresholdClustersDAQ(120.0)
,fNumberRowDAQ(2)
,fNumberColDAQ(4)
,fProcent(6.0)
,fDifference(17)
,fNumberTrack(0)
,fTimeMax(0)
,fSf(10.0)
,fRangeHistoCharge(150)
,fNumberBinCharge(50)
,fNumberBinPRF(10)
,fNgroupprf(3)
,fAmpTotal(0x0)
,fPHPlace(0x0)
,fPHValue(0x0)
,fGoodTracklet(kTRUE)
,fLinearFitterTracklet(0x0)
,fEntriesCH(0x0)
,fEntriesLinearFitter(0x0)
,fCalibraVector(0x0)
,fPH2d(0x0)
,fPRF2d(0x0)
,fCH2d(0x0)
,fLinearFitterArray(540)
,fLinearVdriftFit(0x0)
,fExbAltFit(0x0)
,fCalDetGain(0x0)
,fCalROCGain(0x0)
{
//
// Default constructor
//
//
// Init some default values
//
fNumberUsedCh[0] = 0;
fNumberUsedCh[1] = 0;
fNumberUsedPh[0] = 0;
fNumberUsedPh[1] = 0;
fGeo = new AliTRDgeometry();
fCalibDB = AliTRDcalibDB::Instance();
}
//______________________________________________________________________________________
AliTRDCalibraFillHisto::AliTRDCalibraFillHisto(const AliTRDCalibraFillHisto &c)
:TObject(c)
,fGeo(0)
,fCalibDB(0)
,fIsHLT(c.fIsHLT)
,fCH2dOn(c.fCH2dOn)
,fPH2dOn(c.fPH2dOn)
,fPRF2dOn(c.fPRF2dOn)
,fHisto2d(c.fHisto2d)
,fVector2d(c.fVector2d)
,fLinearFitterOn(c.fLinearFitterOn)
,fLinearFitterDebugOn(c.fLinearFitterDebugOn)
,fExbAltFitOn(c.fExbAltFitOn)
,fScaleWithTPCSignal(c.fScaleWithTPCSignal)
,fRelativeScale(c.fRelativeScale)
,fThresholdClusterPRF2(c.fThresholdClusterPRF2)
,fLimitChargeIntegration(c.fLimitChargeIntegration)
,fFillWithZero(c.fFillWithZero)
,fNormalizeNbOfCluster(c.fNormalizeNbOfCluster)
,fMaxCluster(c.fMaxCluster)
,fNbMaxCluster(c.fNbMaxCluster)
,fCutWithVdriftCalib(c.fCutWithVdriftCalib)
,fMinNbTRDtracklets(c.fMinNbTRDtracklets)
,fMinTRDMomentum(c.fMinTRDMomentum)
,fTakeSnapshot(c.fTakeSnapshot)
,fFirstRunGain(c.fFirstRunGain)
,fVersionGainUsed(c.fVersionGainUsed)
,fSubVersionGainUsed(c.fSubVersionGainUsed)
,fFirstRunGainLocal(c.fFirstRunGainLocal)
,fVersionGainLocalUsed(c.fVersionGainLocalUsed)
,fSubVersionGainLocalUsed(c.fSubVersionGainLocalUsed)
,fFirstRunVdrift(c.fFirstRunVdrift)
,fVersionVdriftUsed(c.fVersionVdriftUsed)
,fSubVersionVdriftUsed(c.fSubVersionVdriftUsed)
,fFirstRunExB(c.fFirstRunExB)
,fVersionExBUsed(c.fVersionExBUsed)
,fSubVersionExBUsed(c.fSubVersionExBUsed)
,fCalibraMode(0x0)
,fDebugStreamer(0)
,fDebugLevel(c.fDebugLevel)
,fDetectorPreviousTrack(c.fDetectorPreviousTrack)
,fMCMPrevious(c.fMCMPrevious)
,fROBPrevious(c.fROBPrevious)
,fNumberClusters(c.fNumberClusters)
,fNumberClustersf(c.fNumberClustersf)
,fNumberClustersProcent(c.fNumberClustersProcent)
,fThresholdClustersDAQ(c.fThresholdClustersDAQ)
,fNumberRowDAQ(c.fNumberRowDAQ)
,fNumberColDAQ(c.fNumberColDAQ)
,fProcent(c.fProcent)
,fDifference(c.fDifference)
,fNumberTrack(c.fNumberTrack)
,fTimeMax(c.fTimeMax)
,fSf(c.fSf)
,fRangeHistoCharge(c.fRangeHistoCharge)
,fNumberBinCharge(c.fNumberBinCharge)
,fNumberBinPRF(c.fNumberBinPRF)
,fNgroupprf(c.fNgroupprf)
,fAmpTotal(0x0)
,fPHPlace(0x0)
,fPHValue(0x0)
,fGoodTracklet(c.fGoodTracklet)
,fLinearFitterTracklet(0x0)
,fEntriesCH(0x0)
,fEntriesLinearFitter(0x0)
,fCalibraVector(0x0)
,fPH2d(0x0)
,fPRF2d(0x0)
,fCH2d(0x0)
,fLinearFitterArray(540)
,fLinearVdriftFit(0x0)
,fExbAltFit(0x0)
,fCalDetGain(0x0)
,fCalROCGain(0x0)
{
//
// Copy constructor
//
if(c.fCalibraMode) fCalibraMode = new AliTRDCalibraMode(*c.fCalibraMode);
if(c.fCalibraVector) fCalibraVector = new AliTRDCalibraVector(*c.fCalibraVector);
if(c.fPH2d) {
fPH2d = new TProfile2D(*c.fPH2d);
fPH2d->SetDirectory(0);
}
if(c.fPRF2d) {
fPRF2d = new TProfile2D(*c.fPRF2d);
fPRF2d->SetDirectory(0);
}
if(c.fCH2d) {
fCH2d = new TH2I(*c.fCH2d);
fCH2d->SetDirectory(0);
}
if(c.fLinearVdriftFit){
fLinearVdriftFit = new AliTRDCalibraVdriftLinearFit(*c.fLinearVdriftFit);
}
if(c.fExbAltFit){
fExbAltFit = new AliTRDCalibraExbAltFit(*c.fExbAltFit);
}
if(c.fCalDetGain) fCalDetGain = new AliTRDCalDet(*c.fCalDetGain);
if(c.fCalROCGain) fCalROCGain = new AliTRDCalROC(*c.fCalROCGain);
if (fGeo) {
delete fGeo;
}
fGeo = new AliTRDgeometry();
fCalibDB = AliTRDcalibDB::Instance();
fNumberUsedCh[0] = 0;
fNumberUsedCh[1] = 0;
fNumberUsedPh[0] = 0;
fNumberUsedPh[1] = 0;
}
//____________________________________________________________________________________
AliTRDCalibraFillHisto::~AliTRDCalibraFillHisto()
{
//
// AliTRDCalibraFillHisto destructor
//
ClearHistos();
if ( fDebugStreamer ) delete fDebugStreamer;
if ( fCalDetGain ) delete fCalDetGain;
if ( fCalROCGain ) delete fCalROCGain;
if( fLinearFitterTracklet ) { delete fLinearFitterTracklet; }
delete [] fPHPlace;
delete [] fPHValue;
delete [] fEntriesCH;
delete [] fEntriesLinearFitter;
delete [] fAmpTotal;
for(Int_t idet=0; idet<AliTRDgeometry::kNdet; idet++){
TLinearFitter *f = (TLinearFitter*)fLinearFitterArray.At(idet);
if(f) { delete f;}
}
if(fLinearVdriftFit) delete fLinearVdriftFit;
if(fExbAltFit) delete fExbAltFit;
if (fGeo) {
delete fGeo;
}
}
//_____________________________________________________________________________
void AliTRDCalibraFillHisto::Destroy()
{
//
// Delete instance
//
if (fgInstance) {
delete fgInstance;
fgInstance = 0x0;
}
}
//_____________________________________________________________________________
void AliTRDCalibraFillHisto::DestroyDebugStreamer()
{
//
// Delete DebugStreamer
//
if ( fDebugStreamer ) delete fDebugStreamer;
fDebugStreamer = 0x0;
}
//_____________________________________________________________________________
void AliTRDCalibraFillHisto::ClearHistos()
{
//
// Delete the histos
//
if (fPH2d) {
delete fPH2d;
fPH2d = 0x0;
}
if (fCH2d) {
delete fCH2d;
fCH2d = 0x0;
}
if (fPRF2d) {
delete fPRF2d;
fPRF2d = 0x0;
}
}
//////////////////////////////////////////////////////////////////////////////////
// calibration with AliTRDtrackV1: Init, Update
//////////////////////////////////////////////////////////////////////////////////
//____________Functions for initialising the AliTRDCalibraFillHisto in the code_________
Bool_t AliTRDCalibraFillHisto::Init2Dhistos(Int_t nboftimebin)
{
//
// Init the histograms and stuff to be filled
//
// DB Setting
// Get cal
AliTRDcalibDB *cal = AliTRDcalibDB::Instance();
if (!cal) {
AliInfo("Could not get calibDB");
return kFALSE;
}
AliTRDCommonParam *parCom = AliTRDCommonParam::Instance();
if (!parCom) {
AliInfo("Could not get CommonParam");
return kFALSE;
}
// Some parameters
if(nboftimebin > 0) fTimeMax = nboftimebin;
else fTimeMax = cal->GetNumberOfTimeBinsDCS();
if(fTimeMax <= 0) fTimeMax = 30;
printf("////////////////////////////////////////////\n");
printf("Number of time bins in calibration component %d\n",fTimeMax);
printf("////////////////////////////////////////////\n");
fSf = parCom->GetSamplingFrequency();
if(!fNormalizeNbOfCluster) fRelativeScale = 20.0;
else fRelativeScale = 1.18;
fNumberClustersf = fTimeMax;
fNumberClusters = (Int_t)(fNumberClustersProcent*fTimeMax);
// Init linear fitter
if(!fLinearFitterTracklet) {
fLinearFitterTracklet = new TLinearFitter(2,"pol1");
fLinearFitterTracklet->StoreData(kTRUE);
}
// Calcul Xbins Chambd0, Chamb2
Int_t ntotal0 = CalculateTotalNumberOfBins(0);
Int_t ntotal1 = CalculateTotalNumberOfBins(1);
Int_t ntotal2 = CalculateTotalNumberOfBins(2);
// If vector method On initialised all the stuff
if(fVector2d){
fCalibraVector = new AliTRDCalibraVector();
fCalibraVector->SetNumberBinCharge(fNumberBinCharge);
fCalibraVector->SetTimeMax(fTimeMax);
if(fNgroupprf != 0) {
fCalibraVector->SetNumberBinPRF(2*fNgroupprf*fNumberBinPRF);
fCalibraVector->SetPRFRange((Float_t)(3.0*fNgroupprf));
}
else {
fCalibraVector->SetNumberBinPRF(fNumberBinPRF);
fCalibraVector->SetPRFRange(1.5);
}
for(Int_t k = 0; k < 3; k++){
fCalibraVector->SetDetCha0(k,fCalibraMode->GetDetChamb0(k));
fCalibraVector->SetDetCha2(k,fCalibraMode->GetDetChamb2(k));
}
fCalibraVector->SetNzNrphi(0,fCalibraMode->GetNz(0),fCalibraMode->GetNrphi(0));
fCalibraVector->SetNzNrphi(1,fCalibraMode->GetNz(1),fCalibraMode->GetNrphi(1));
fCalibraVector->SetNzNrphi(2,fCalibraMode->GetNz(2),fCalibraMode->GetNrphi(2));
fCalibraVector->SetNbGroupPRF(fNgroupprf);
}
// Create the 2D histos corresponding to the pad groupCalibration mode
if (fCH2dOn) {
AliInfo(Form("The pad calibration mode for the relative gain calibration: Nz %d, and Nrphi %d"
,fCalibraMode->GetNz(0)
,fCalibraMode->GetNrphi(0)));
// Create the 2D histo
if (fHisto2d) {
CreateCH2d(ntotal0);
}
// Variable
fAmpTotal = new Float_t[TMath::Max(fCalibraMode->GetDetChamb2(0),fCalibraMode->GetDetChamb0(0))];
for (Int_t k = 0; k < TMath::Max(fCalibraMode->GetDetChamb2(0),fCalibraMode->GetDetChamb0(0)); k++) {
fAmpTotal[k] = 0.0;
}
//Statistics
fEntriesCH = new Int_t[ntotal0];
for(Int_t k = 0; k < ntotal0; k++){
fEntriesCH[k] = 0;
}
}
if (fPH2dOn) {
AliInfo(Form("The pad calibration mode for the drift velocity calibration: Nz %d, and Nrphi %d"
,fCalibraMode->GetNz(1)
,fCalibraMode->GetNrphi(1)));
// Create the 2D histo
if (fHisto2d) {
CreatePH2d(ntotal1);
}
// Variable
fPHPlace = new Short_t[fTimeMax];
for (Int_t k = 0; k < fTimeMax; k++) {
fPHPlace[k] = -1;
}
fPHValue = new Float_t[fTimeMax];
for (Int_t k = 0; k < fTimeMax; k++) {
fPHValue[k] = 0.0;
}
}
if (fLinearFitterOn) {
if(fLinearFitterDebugOn) {
fLinearFitterArray.SetName("ArrayLinearFitters");
fEntriesLinearFitter = new Int_t[540];
for(Int_t k = 0; k < 540; k++){
fEntriesLinearFitter[k] = 0;
}
}
fLinearVdriftFit = new AliTRDCalibraVdriftLinearFit();
//TString nameee("Ver");
//nameee += fVersionExBUsed;
//nameee += "Subver";
//nameee += fSubVersionExBUsed;
//nameee += "FirstRun";
//nameee += fFirstRunExB;
//nameee += "Nz";
//fLinearVdriftFit->SetNameCalibUsed(nameee);
}
if(fExbAltFitOn){
fExbAltFit = new AliTRDCalibraExbAltFit();
}
if (fPRF2dOn) {
AliInfo(Form("The pad calibration mode for the PRF calibration: Nz %d, and Nrphi %d"
,fCalibraMode->GetNz(2)
,fCalibraMode->GetNrphi(2)));
// Create the 2D histo
if (fHisto2d) {
CreatePRF2d(ntotal2);
}
}
return kTRUE;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
Bool_t AliTRDCalibraFillHisto::InitCalDet()
{
//
// Init the Gain Cal Det
//
// DB Setting
// Get cal
AliCDBEntry *entry = 0x0;
if(fTakeSnapshot) {
entry = AliCDBManager::Instance()->Get("TRD/Calib/ChamberGainFactor");
}
else {
entry = AliCDBManager::Instance()->Get("TRD/Calib/ChamberGainFactor",fFirstRunGain,fVersionGainUsed,fSubVersionGainUsed);
}
if(!entry) {
AliError("No gain det calibration entry found");
return kFALSE;
}
AliTRDCalDet *calDet = (AliTRDCalDet *)entry->GetObject();
if(!calDet) {
AliError("No calDet gain found");
return kFALSE;
}
if( fCalDetGain ){
fCalDetGain->~AliTRDCalDet();
new(fCalDetGain) AliTRDCalDet(*(calDet));
}else fCalDetGain = new AliTRDCalDet(*(calDet));
if((fVersionGainUsed > 0) && (fVersionVdriftUsed > 0) && (fVersionExBUsed > 0)) {
// Extra protection to be sure but should normally not happen
// title CH2d
TString name("Ver");
name += fVersionGainUsed;
name += "Subver";
name += fSubVersionGainUsed;
name += "FirstRun";
name += fFirstRunGain;
name += "Nz";
name += fCalibraMode->GetNz(0);
name += "Nrphi";
name += fCalibraMode->GetNrphi(0);
fCH2d->SetTitle(name);
// title PH2d
TString namee("Ver");
namee += fVersionVdriftUsed;
namee += "Subver";
namee += fSubVersionVdriftUsed;
namee += "FirstRun";
namee += fFirstRunVdrift;
namee += "Nz";
namee += fCalibraMode->GetNz(1);
namee += "Nrphi";
namee += fCalibraMode->GetNrphi(1);
fPH2d->SetTitle(namee);
// title AliTRDCalibraVdriftLinearFit
TString nameee("Ver");
nameee += fVersionExBUsed;
nameee += "Subver";
nameee += fSubVersionExBUsed;
nameee += "FirstRun";
nameee += fFirstRunExB;
nameee += "Nz";
fLinearVdriftFit->SetNameCalibUsed(nameee);
}
return kTRUE;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
Bool_t AliTRDCalibraFillHisto::InitCalPad(Int_t detector)
{
//
// Init the Gain Cal Pad
//
// DB Setting
// Get cal
AliCDBEntry *entry = 0x0;
if(fTakeSnapshot) {
entry = AliCDBManager::Instance()->Get("TRD/Calib/LocalGainFactor");
}
else {
entry = AliCDBManager::Instance()->Get("TRD/Calib/LocalGainFactor",fFirstRunGain,fVersionGainUsed,fSubVersionGainUsed);
}
if(!entry) {
AliError("No gain pad calibration entry found");
return kFALSE;
}
AliTRDCalPad *calPad = (AliTRDCalPad *)entry->GetObject();
if(!calPad) {
AliError("No calPad gain found");
return kFALSE;
}
AliTRDCalROC *calRoc = (AliTRDCalROC *)calPad->GetCalROC(detector);
if(!calRoc) {
AliError("No calRoc gain found");
return kFALSE;
}
if( fCalROCGain ){
fCalROCGain->~AliTRDCalROC();
new(fCalROCGain) AliTRDCalROC(*(calRoc));
}else fCalROCGain = new AliTRDCalROC(*(calRoc));
return kTRUE;
}
//____________Offline tracking in the AliTRDtracker____________________________
Bool_t AliTRDCalibraFillHisto::UpdateHistogramsV1(const AliTRDtrackV1 *t,const AliESDtrack *esdtrack)
{
//
// Use AliTRDtrackV1 for the calibration
//
const AliTRDseedV1 *tracklet = 0x0; // tracklet per plane
AliTRDcluster *cl = 0x0; // cluster attached now to the tracklet
AliTRDcluster *cls = 0x0; // shared cluster attached now to the tracklet
Bool_t newtr = kTRUE; // new track
//
// Cut on the number of TRD tracklets
//
Int_t numberoftrdtracklets = t->GetNumberOfTracklets();
if(numberoftrdtracklets < fMinNbTRDtracklets) return kFALSE;
Double_t tpcsignal = 1.0;
if(esdtrack) tpcsignal = esdtrack->GetTPCsignal()/50.0;
if(fScaleWithTPCSignal && tpcsignal <0.00001) return kFALSE;
//
if (!fCalibDB) {
AliInfo("Could not get calibDB");
return kFALSE;
}
///////////////////////////
// loop over the tracklet
///////////////////////////
for(Int_t itr = 0; itr < 6; itr++){
if(!(tracklet = t->GetTracklet(itr))) continue;
if(!tracklet->IsOK()) continue;
fNumberTrack++;
ResetfVariablestracklet();
Float_t momentum = t->GetMomentum(itr);
if(TMath::Abs(momentum) < fMinTRDMomentum) continue;
//////////////////////////////////////////
// localisation of the tracklet and dqdl
//////////////////////////////////////////
Int_t layer = tracklet->GetPlane();
Int_t ic = 0;
while(!(cl = tracklet->GetClusters(ic++))) continue;
Int_t detector = cl->GetDetector();
if (detector != fDetectorPreviousTrack) {
// if not a new track
if(!newtr){
// don't use the rest of this track if in the same plane
if (layer == GetLayer(fDetectorPreviousTrack)) {
//printf("bad tracklet, same layer for detector %d\n",detector);
break;
}
}
//Localise the detector bin
LocalisationDetectorXbins(detector);
// Get calib objects
if(!fIsHLT) InitCalPad(detector);
// reset
fDetectorPreviousTrack = detector;
}
newtr = kFALSE;
////////////////////////////
// loop over the clusters
////////////////////////////
Double_t chargeQ = 0.0;
Int_t nbclusters = 0;
for(int jc=0; jc<AliTRDseedV1::kNtb; jc++){
if(!(cl = tracklet->GetClusters(jc))) continue;
nbclusters++;
// Store the info bis of the tracklet
Int_t row = cl->GetPadRow();
Int_t col = cl->GetPadCol();
CheckGoodTrackletV1(cl);
Int_t group[2] = {0,0};
if(fCH2dOn) group[0] = CalculateCalibrationGroup(0,row,col);
if(fPH2dOn) group[1] = CalculateCalibrationGroup(1,row,col);
// Add the charge if shared cluster
cls = tracklet->GetClusters(jc+AliTRDseedV1::kNtb);
//
//Scale with TPC signal or not
if(!fScaleWithTPCSignal) {
chargeQ += StoreInfoCHPHtrack(cl, tracklet->GetQperTB(jc),group,row,col,cls); //tracklet->GetdQdl(jc)
//printf("Do not scale now\n");
}
else {
chargeQ += StoreInfoCHPHtrack(cl, tracklet->GetQperTB(jc)/tpcsignal,group,row,col,cls); //tracklet->GetdQdl(jc)
}
}
////////////////////////////////////////
// Fill the stuffs if a good tracklet
////////////////////////////////////////
if (fGoodTracklet) {
// drift velocity unables to cut bad tracklets
Bool_t pass = FindP1TrackPHtrackletV1(tracklet, nbclusters);
//printf("pass %d and nbclusters %d\n",pass,nbclusters);
// Gain calibration
if (fCH2dOn) {
if(fCutWithVdriftCalib) {
if(pass) FillTheInfoOfTheTrackCH(nbclusters);
} else {
FillTheInfoOfTheTrackCH(nbclusters);
}
}
// PH calibration
if (fPH2dOn) {
if(fCutWithVdriftCalib) {
if(pass) FillTheInfoOfTheTrackPH();
}
else {
FillTheInfoOfTheTrackPH();
}
}
if(pass && fPRF2dOn) HandlePRFtrackletV1(tracklet,nbclusters);
/////////////////////////////////////////////////////////
// Debug
////////////////////////////////////////////////////////
if(fDebugLevel > 0){
//printf("test\n");
if ( !fDebugStreamer ) {
//debug stream
TDirectory *backup = gDirectory;
fDebugStreamer = new TTreeSRedirector("TRDdebugCalibraFill.root");
if ( backup ) backup->cd(); //we don't want to be cd'd to the debug streamer
}
Int_t stacke = AliTRDgeometry::GetStack(detector);
Int_t sme = AliTRDgeometry::GetSector(detector);
Int_t layere = AliTRDgeometry::GetLayer(detector);
// Some variables
Float_t b[2] = {0.0,0.0};
Float_t bCov[3] = {0.0,0.0,0.0};
if(esdtrack) esdtrack->GetImpactParameters(b,bCov);
if (bCov[0]<=0 || bCov[2]<=0) {
bCov[0]=0; bCov[2]=0;
}
Float_t dcaxy = b[0];
Float_t dcaz = b[1];
Int_t tpcnbclusters = 0;
if(esdtrack) tpcnbclusters = esdtrack->GetTPCclusters(0);
Double_t ttpcsignal = 0.0;
if(esdtrack) ttpcsignal = esdtrack->GetTPCsignal();
Int_t cutvdriftlinear = 0;
if(!pass) cutvdriftlinear = 1;
(* fDebugStreamer) << "FillCharge"<<
"detector="<<detector<<
"stack="<<stacke<<
"sm="<<sme<<
"layere="<<layere<<
"dcaxy="<<dcaxy<<
"dcaz="<<dcaz<<
"nbtpccls="<<tpcnbclusters<<
"tpcsignal="<<ttpcsignal<<
"cutvdriftlinear="<<cutvdriftlinear<<
"ptrd="<<momentum<<
"nbtrdtracklet="<<numberoftrdtracklets<<
"charge="<<chargeQ<<
"\n";
}
} // if a good tracklet
}
return kTRUE;
}
///////////////////////////////////////////////////////////////////////////////////
// Routine inside the update with AliTRDtrack
///////////////////////////////////////////////////////////////////////////////////
//____________Offine tracking in the AliTRDtracker_____________________________
Bool_t AliTRDCalibraFillHisto::FindP1TrackPHtrackletV1(const AliTRDseedV1 *tracklet, Int_t nbclusters)
{
//
// Drift velocity calibration:
// Fit the clusters with a straight line
// From the slope find the drift velocity
//
////////////////////////////////////////////////
//Number of points: if less than 3 return kFALSE
/////////////////////////////////////////////////
if(nbclusters <= 2) return kFALSE;
////////////
//Variables
////////////
// results of the linear fit
Double_t dydt = 0.0; // dydt tracklet after straight line fit
Double_t errorpar = 0.0; // error after straight line fit on dy/dt
Double_t pointError = 0.0; // error after straight line fit
// pad row problemes: avoid tracklet that cross pad rows, tilting angle in the constant
Int_t crossrow = 0; // if it crosses a pad row
Int_t rowp = -1; // if it crosses a pad row
Float_t tnt = tracklet->GetTilt(); // tan tiltingangle
fLinearFitterTracklet->ClearPoints();
///////////////////////////////////////////
// Take the parameters of the track
//////////////////////////////////////////
// take now the snp, tnp and tgl from the track
Double_t snp = tracklet->GetSnp(); // sin dy/dx at the end of the chamber
Double_t tnp = 0.0; // dy/dx at the end of the chamber
if( TMath::Abs(snp) < 1.){
tnp = snp / TMath::Sqrt((1.-snp)*(1.+snp));
}
Double_t tgl = tracklet->GetTgl(); // dz/dl
Double_t dzdx = tgl*TMath::Sqrt(1+tnp*tnp); // dz/dx calculated from dz/dl
// at the entrance
//Double_t tnp = tracklet->GetYref(1); // dy/dx at the entrance of the chamber
//Double_t tgl = tracklet->GetZref(1); // dz/dl at the entrance of the chamber
//Double_t dzdx = tgl; //*TMath::Sqrt(1+tnp*tnp); // dz/dx from dz/dl
// at the end with correction due to linear fit
//Double_t tnp = tracklet->GetYfit(1); // dy/dx at the end of the chamber after fit correction
//Double_t tgl = tracklet->GetZfit(1); // dz/dl at the end of the chamber after fit correction
////////////////////////////
// loop over the clusters
////////////////////////////
Int_t nbli = 0;
AliTRDcluster *cl = 0x0;
//////////////////////////////
// Check no shared clusters
//////////////////////////////
for(int icc=AliTRDseedV1::kNtb; icc<AliTRDseedV1::kNclusters; icc++){
cl = tracklet->GetClusters(icc);
if(cl) crossrow = 1;
}
//////////////////////////////////
// Loop clusters
//////////////////////////////////
Float_t sigArr[AliTRDfeeParam::GetNcol()];
memset(sigArr, 0, AliTRDfeeParam::GetNcol()*sizeof(sigArr[0]));
Int_t ncl=0, tbf=0, tbl=0;
for(int ic=0; ic<AliTRDseedV1::kNtb; ic++){
if(!(cl = tracklet->GetClusters(ic))) continue;
if(!tbf) tbf=ic;
tbl=ic;
ncl++;
Int_t col = cl->GetPadCol();
for(int ip=-1, jp=2; jp<5; ip++, jp++){
Int_t idx=col+ip;
if(idx<0 || idx>=AliTRDfeeParam::GetNcol()) continue;
sigArr[idx]+=((Float_t)cl->GetSignals()[jp]);
}
if((fLimitChargeIntegration) && (!cl->IsInChamber())) continue;
Double_t ycluster = cl->GetY();
Int_t time = cl->GetPadTime();
Double_t timeis = time/fSf;
//See if cross two pad rows
Int_t row = cl->GetPadRow();
if(rowp==-1) rowp = row;
if(row != rowp) crossrow = 1;
fLinearFitterTracklet->AddPoint(&timeis,ycluster,1);
nbli++;
}
////////////////////////////////////
// Do the straight line fit now
///////////////////////////////////
if(nbli <= 2){
fLinearFitterTracklet->ClearPoints();
return kFALSE;
}
TVectorD pars;
fLinearFitterTracklet->Eval();
fLinearFitterTracklet->GetParameters(pars);
pointError = TMath::Sqrt(TMath::Abs(fLinearFitterTracklet->GetChisquare()/(nbli-2)));
errorpar = fLinearFitterTracklet->GetParError(1)*pointError;
dydt = pars[1];
//printf("chis %f, nbli %d, pointError %f, parError %f, errorpar %f\n",fLinearFitterTracklet->GetChisquare(),nbli,pointError,fLinearFitterTracklet->GetParError(1),errorpar);
fLinearFitterTracklet->ClearPoints();
////////////////////////////////////
// Calc the projection of the clusters on the y direction
///////////////////////////////////
Float_t signalSum(0.);
Float_t mean = 0.0, rms = 0.0;
Float_t dydx = tracklet->GetYref(1), tilt = tracklet->GetTilt(); // ,dzdx = tracklet->GetZref(1); (identical to the previous definition!)
Float_t dz = dzdx*(tbl-tbf)/10;
if(ncl>10){
for(Int_t ip(0); ip<AliTRDfeeParam::GetNcol(); ip++){
signalSum+=sigArr[ip];
mean+=ip*sigArr[ip];
}
if(signalSum > 0.0) mean/=signalSum;
for(Int_t ip = 0; ip<AliTRDfeeParam::GetNcol(); ip++)
rms+=sigArr[ip]*(ip-mean)*(ip-mean);
if(signalSum > 0.0) rms = TMath::Sqrt(TMath::Abs(rms/signalSum));
rms -= TMath::Abs(dz*tilt);
dydx -= dzdx*tilt;
}
////////////////////////////////
// Debug stuff
///////////////////////////////
if(fDebugLevel > 1){
if ( !fDebugStreamer ) {
//debug stream
TDirectory *backup = gDirectory;
fDebugStreamer = new TTreeSRedirector("TRDdebugCalibraFill.root");
if ( backup ) backup->cd(); //we don't want to be cd'd to the debug streamer
}
float xcoord = tnp-dzdx*tnt;
float pt = tracklet->GetPt();
Int_t layer = GetLayer(fDetectorPreviousTrack);
(* fDebugStreamer) << "FindP1TrackPHtrackletV1"<<
//"snpright="<<snpright<<
"nbli="<<nbli<<
"nbclusters="<<nbclusters<<
"detector="<<fDetectorPreviousTrack<<
"layer="<<layer<<
"snp="<<snp<<
"tnp="<<tnp<<
"tgl="<<tgl<<
"tnt="<<tnt<<
"dydt="<<dydt<<
"dzdx="<<dzdx<<
"crossrow="<<crossrow<<
"errorpar="<<errorpar<<
"pointError="<<pointError<<
"xcoord="<<xcoord<<
"pt="<<pt<<
"rms="<<rms<<
"dydx="<<dydx<<
"dz="<<dz<<
"tilt="<<tilt<<
"ncl="<<ncl<<
"\n";
}
/////////////////////////
// Cuts quality
////////////////////////
if(nbclusters < fNumberClusters) return kFALSE;
if(nbclusters > fNumberClustersf) return kFALSE;
if(pointError >= 0.3) return kFALSE;
if(crossrow == 1) return kTRUE;
///////////////////////
// Fill
//////////////////////
if(fLinearFitterOn){
//Add to the linear fitter of the detector
if( TMath::Abs(snp) < 1.){
Double_t x = tnp-dzdx*tnt;
if(fLinearFitterDebugOn) {
(GetLinearFitter(fDetectorPreviousTrack,kTRUE))->AddPoint(&x,dydt);
fEntriesLinearFitter[fDetectorPreviousTrack]++;
}
fLinearVdriftFit->Update(fDetectorPreviousTrack,x,pars[1]);
}
}
if(fExbAltFitOn){
fExbAltFit->Update(fDetectorPreviousTrack,dydx,rms);
}
return kTRUE;
}
//____________Offine tracking in the AliTRDtracker_____________________________
Bool_t AliTRDCalibraFillHisto::HandlePRFtrackletV1(const AliTRDseedV1 *tracklet, Int_t nbclusters)
{
//
// PRF width calibration
// Assume a Gaussian shape: determinate the position of the three pad clusters
// Fit with a straight line
// Take the fitted values for all the clusters (3 or 2 pad clusters)
// Fill the PRF as function of angle of the track
//
//
//printf("begin\n");
///////////////////////////////////////////
// Take the parameters of the track
//////////////////////////////////////////
// take now the snp, tnp and tgl from the track
Double_t snp = tracklet->GetSnp(); // sin dy/dx at the end of the chamber
Double_t tnp = 0.0; // dy/dx at the end of the chamber
if( TMath::Abs(snp) < 1.){
tnp = snp / TMath::Sqrt((1.-snp)*(1.+snp));
}
Double_t tgl = tracklet->GetTgl(); // dz/dl
Double_t dzdx = tgl*TMath::Sqrt(1+tnp*tnp); // dz/dx calculated from dz/dl
// at the entrance
//Double_t tnp = tracklet->GetYref(1); // dy/dx at the entrance of the chamber
//Double_t tgl = tracklet->GetZref(1); // dz/dl at the entrance of the chamber
//Double_t dzdx = tgl; //*TMath::Sqrt(1+tnp*tnp); // dz/dx from dz/dl
// at the end with correction due to linear fit
//Double_t tnp = tracklet->GetYfit(1); // dy/dx at the end of the chamber after fit correction
//Double_t tgl = tracklet->GetZfit(1); // dz/dl at the end of the chamber after fit correction
///////////////////////////////
// Calculate tnp group shift
///////////////////////////////
Bool_t echec = kFALSE;
Double_t shift = 0.0;
//Calculate the shift in x coresponding to this tnp
if(fNgroupprf != 0.0){
shift = -3.0*(fNgroupprf-1)-1.5;
Double_t limithigh = -0.2*(fNgroupprf-1);
if((tnp < (-0.2*fNgroupprf)) || (tnp > (0.2*fNgroupprf))) echec = kTRUE;
else{
while(tnp > limithigh){
limithigh += 0.2;
shift += 3.0;
}
}
}
// do nothing if out of tnp range
//printf("echec %d\n",(Int_t)echec);
if(echec) return kFALSE;
///////////////////////
// Variables
//////////////////////
Int_t nb3pc = 0; // number of three pads clusters used for fit
// to see the difference between the fit and the 3 pad clusters position
Double_t padPositions[AliTRDseedV1::kNtb];
memset(padPositions, 0, AliTRDseedV1::kNtb*sizeof(Double_t));
fLinearFitterTracklet->ClearPoints();
//printf("loop clusters \n");
////////////////////////////
// loop over the clusters
////////////////////////////
AliTRDcluster *cl = 0x0;
for(int ic=0; ic<AliTRDseedV1::kNtb; ic++){
// reject shared clusters on pad row
if((ic+AliTRDseedV1::kNtb) < AliTRDseedV1::kNclusters) {
cl = tracklet->GetClusters(ic+AliTRDseedV1::kNtb);
if(cl) continue;
}
cl = tracklet->GetClusters(ic);
if(!cl) continue;
Double_t time = cl->GetPadTime();
if((time<=7) || (time>=21)) continue;
Short_t *signals = cl->GetSignals();
Float_t xcenter = 0.0;
Bool_t echec1 = kTRUE;
/////////////////////////////////////////////////////////////
// Center 3 balanced: position with the center of the pad
/////////////////////////////////////////////////////////////
if ((((Float_t) signals[3]) > 0.0) &&
(((Float_t) signals[2]) > 0.0) &&
(((Float_t) signals[4]) > 0.0)) {
echec1 = kFALSE;
// Security if the denomiateur is 0
if ((((Float_t) (((Float_t) signals[3]) * ((Float_t) signals[3]))) /
((Float_t) (((Float_t) signals[2]) * ((Float_t) signals[4])))) != 1.0) {
xcenter = 0.5 * (TMath::Log((Float_t) (((Float_t) signals[4]) / ((Float_t) signals[2]))))
/ (TMath::Log(((Float_t) (((Float_t) signals[3]) * ((Float_t) signals[3])))
/ ((Float_t) (((Float_t) signals[2]) * ((Float_t) signals[4])))));
}
else {
echec1 = kTRUE;
}
}
if(TMath::Abs(xcenter) > 0.5) echec1 = kTRUE;
if(echec1) continue;
////////////////////////////////////////////////////////
//if no echec1: calculate with the position of the pad
// Position of the cluster
// fill the linear fitter
///////////////////////////////////////////////////////
Double_t padPosition = xcenter + cl->GetPadCol();
padPositions[ic] = padPosition;
nb3pc++;
fLinearFitterTracklet->AddPoint(&time, padPosition,1);
}//clusters loop
//printf("Fin loop clusters \n");
//////////////////////////////
// fit with a straight line
/////////////////////////////
if(nb3pc < 3){
fLinearFitterTracklet->ClearPoints();
return kFALSE;
}
fLinearFitterTracklet->Eval();
TVectorD line(2);
fLinearFitterTracklet->GetParameters(line);
Float_t pointError = -1.0;
if( fLinearFitterTracklet->GetChisquare()>=0.0) {
pointError = TMath::Sqrt( fLinearFitterTracklet->GetChisquare()/(nb3pc-2));
}
fLinearFitterTracklet->ClearPoints();
//printf("PRF second loop \n");
////////////////////////////////////////////////
// Fill the PRF: Second loop over clusters
//////////////////////////////////////////////
for(int ic=0; ic<AliTRDseedV1::kNtb; ic++){
// reject shared clusters on pad row
cl = tracklet->GetClusters(ic+AliTRDseedV1::kNtb);
if(((ic+AliTRDseedV1::kNtb) < AliTRDseedV1::kNclusters) && (cl)) continue;
//
cl = tracklet->GetClusters(ic);
if(!cl) continue;
Short_t *signals = cl->GetSignals(); // signal
Double_t time = cl->GetPadTime(); // time bin
Float_t padPosTracklet = line[0]+line[1]*time; // reconstruct position from fit
Float_t padPos = cl->GetPadCol(); // middle pad
Double_t dpad = padPosTracklet - padPos; // reconstruct position relative to middle pad from fit
Float_t ycenter = 0.0; // relative center charge
Float_t ymin = 0.0; // relative left charge
Float_t ymax = 0.0; // relative right charge
////////////////////////////////////////////////////////////////
// Calculate ycenter, ymin and ymax even for two pad clusters
////////////////////////////////////////////////////////////////
if(((((Float_t) signals[3]) > 0.0) && (((Float_t) signals[2]) > 0.0)) ||
((((Float_t) signals[3]) > 0.0) && (((Float_t) signals[4]) > 0.0))){
Float_t sum = ((Float_t) signals[2]) + ((Float_t) signals[3]) + ((Float_t) signals[4]);
if(sum > 0.0) ycenter = ((Float_t) signals[3])/ sum;
if(sum > 0.0) ymin = ((Float_t) signals[2])/ sum;
if(sum > 0.0) ymax = ((Float_t) signals[4])/ sum;
}
/////////////////////////
// Calibration group
////////////////////////
Int_t rowcl = cl->GetPadRow(); // row of cluster
Int_t colcl = cl->GetPadCol(); // col of cluster
Int_t grouplocal = CalculateCalibrationGroup(2,rowcl,colcl); // calcul the corresponding group
Int_t caligroup = fCalibraMode->GetXbins(2)+ grouplocal; // calcul the corresponding group
Float_t xcl = cl->GetY(); // y cluster
Float_t qcl = cl->GetQ(); // charge cluster
Int_t layer = GetLayer(fDetectorPreviousTrack); // layer
Int_t stack = GetStack(fDetectorPreviousTrack); // stack
Double_t xdiff = dpad; // reconstructed position constant
Double_t x = dpad; // reconstructed position moved
Float_t ep = pointError; // error of fit
Float_t signal1 = (Float_t)signals[1]; // signal at the border
Float_t signal3 = (Float_t)signals[3]; // signal
Float_t signal2 = (Float_t)signals[2]; // signal
Float_t signal4 = (Float_t)signals[4]; // signal
Float_t signal5 = (Float_t)signals[5]; // signal at the border
/////////////////////
// Debug stuff
////////////////////
if(fDebugLevel > 1){
if ( !fDebugStreamer ) {
//debug stream
TDirectory *backup = gDirectory;
fDebugStreamer = new TTreeSRedirector("TRDdebugCalibraFill.root");
if ( backup ) backup->cd(); //we don't want to be cd'd to the debug streamer
}
x = xdiff;
Int_t type=0;
Float_t y = ycenter;
(* fDebugStreamer) << "HandlePRFtrackletV1"<<
"caligroup="<<caligroup<<
"detector="<<fDetectorPreviousTrack<<
"layer="<<layer<<
"stack="<<stack<<
"npoints="<<nbclusters<<
"Np="<<nb3pc<<
"ep="<<ep<<
"type="<<type<<
"snp="<<snp<<
"tnp="<<tnp<<
"tgl="<<tgl<<
"dzdx="<<dzdx<<
"padPos="<<padPos<<
"padPosition="<<padPositions[ic]<<
"padPosTracklet="<<padPosTracklet<<
"x="<<x<<
"y="<<y<<
"xcl="<<xcl<<
"qcl="<<qcl<<
"signal1="<<signal1<<
"signal2="<<signal2<<
"signal3="<<signal3<<
"signal4="<<signal4<<
"signal5="<<signal5<<
"time="<<time<<
"\n";
x=-(xdiff+1);
y = ymin;
type=-1;
(* fDebugStreamer) << "HandlePRFtrackletV1"<<
"caligroup="<<caligroup<<
"detector="<<fDetectorPreviousTrack<<
"layer="<<layer<<
"stack="<<stack<<
"npoints="<<nbclusters<<
"Np="<<nb3pc<<
"ep="<<ep<<
"type="<<type<<
"snp="<<snp<<
"tnp="<<tnp<<
"tgl="<<tgl<<
"dzdx="<<dzdx<<
"padPos="<<padPos<<
"padPosition="<<padPositions[ic]<<
"padPosTracklet="<<padPosTracklet<<
"x="<<x<<
"y="<<y<<
"xcl="<<xcl<<
"qcl="<<qcl<<
"signal1="<<signal1<<
"signal2="<<signal2<<
"signal3="<<signal3<<
"signal4="<<signal4<<
"signal5="<<signal5<<
"time="<<time<<
"\n";
x=1-xdiff;
y = ymax;
type=1;
(* fDebugStreamer) << "HandlePRFtrackletV1"<<
"caligroup="<<caligroup<<
"detector="<<fDetectorPreviousTrack<<
"layer="<<layer<<
"stack="<<stack<<
"npoints="<<nbclusters<<
"Np="<<nb3pc<<
"ep="<<ep<<
"type="<<type<<
"snp="<<snp<<
"tnp="<<tnp<<
"tgl="<<tgl<<
"dzdx="<<dzdx<<
"padPos="<<padPos<<
"padPosition="<<padPositions[ic]<<
"padPosTracklet="<<padPosTracklet<<
"x="<<x<<
"y="<<y<<
"xcl="<<xcl<<
"qcl="<<qcl<<
"signal1="<<signal1<<
"signal2="<<signal2<<
"signal3="<<signal3<<
"signal4="<<signal4<<
"signal5="<<signal5<<
"time="<<time<<
"\n";
}
/////////////////////
// Cuts quality
/////////////////////
if(nbclusters < fNumberClusters) continue;
if(nbclusters > fNumberClustersf) continue;
if(nb3pc <= 5) continue;
if((time >= 21) || (time < 7)) continue;
if(TMath::Abs(qcl) < 80) continue;
if( TMath::Abs(snp) > 1.) continue;
////////////////////////
// Fill the histos
///////////////////////
if (fHisto2d) {
if(TMath::Abs(dpad) < 1.5) {
fPRF2d->Fill(shift+dpad,(caligroup+0.5),ycenter);
fPRF2d->Fill(shift-dpad,(caligroup+0.5),ycenter);
//printf("place %f, ycenter %f\n",(shift+dpad),ycenter);
}
if((ymin > 0.0) && (TMath::Abs(dpad+1.0) < 1.5)) {
fPRF2d->Fill(shift-(dpad+1.0),(caligroup+0.5),ymin);
fPRF2d->Fill(shift+(dpad+1.0),(caligroup+0.5),ymin);
}
if((ymax > 0.0) && (TMath::Abs(dpad-1.0) < 1.5)) {
fPRF2d->Fill(shift+1.0-dpad,(caligroup+0.5),ymax);
fPRF2d->Fill(shift-1.0+dpad,(caligroup+0.5),ymax);
}
}
// vector method
if (fVector2d) {
if(TMath::Abs(dpad) < 1.5) {
fCalibraVector->UpdateVectorPRF(fDetectorPreviousTrack,grouplocal,shift+dpad,ycenter);
fCalibraVector->UpdateVectorPRF(fDetectorPreviousTrack,grouplocal,shift-dpad,ycenter);
}
if((ymin > 0.0) && (TMath::Abs(dpad+1.0) < 1.5)) {
fCalibraVector->UpdateVectorPRF(fDetectorPreviousTrack,grouplocal,shift-(dpad+1.0),ymin);
fCalibraVector->UpdateVectorPRF(fDetectorPreviousTrack,grouplocal,shift+(dpad+1.0),ymin);
}
if((ymax > 0.0) && (TMath::Abs(dpad-1.0) < 1.5)) {
fCalibraVector->UpdateVectorPRF(fDetectorPreviousTrack,grouplocal,shift+1.0-dpad,ymax);
fCalibraVector->UpdateVectorPRF(fDetectorPreviousTrack,grouplocal,shift-1.0+dpad,ymax);
}
}
} // second loop over clusters
return kTRUE;
}
///////////////////////////////////////////////////////////////////////////////////////
// Pad row col stuff: see if masked or not
///////////////////////////////////////////////////////////////////////////////////////
//_____________________________________________________________________________
void AliTRDCalibraFillHisto::CheckGoodTrackletV1(const AliTRDcluster *cl)
{
//
// See if we are not near a masked pad
//
if(cl->IsMasked()) fGoodTracklet = kFALSE;
}
//_____________________________________________________________________________
void AliTRDCalibraFillHisto::CheckGoodTrackletV0(const Int_t detector,const Int_t row,const Int_t col)
{
//
// See if we are not near a masked pad
//
if (!IsPadOn(detector, col, row)) {
fGoodTracklet = kFALSE;
}
if (col > 0) {
if (!IsPadOn(detector, col-1, row)) {
fGoodTracklet = kFALSE;
}
}
if (col < 143) {
if (!IsPadOn(detector, col+1, row)) {
fGoodTracklet = kFALSE;
}
}
}
//_____________________________________________________________________________
Bool_t AliTRDCalibraFillHisto::IsPadOn(Int_t detector, Int_t row, Int_t col) const
{
//
// Look in the choosen database if the pad is On.
// If no the track will be "not good"
//
// Get the parameter object
AliTRDcalibDB *cal = AliTRDcalibDB::Instance();
if (!cal) {
AliInfo("Could not get calibDB");
return kFALSE;
}
if (!cal->IsChamberGood(detector) ||
cal->IsChamberNoData(detector) ||
cal->IsPadMasked(detector,col,row)) {
return kFALSE;
}
else {
return kTRUE;
}
}
///////////////////////////////////////////////////////////////////////////////////////
// Calibration groups: calculate the number of groups, localise...
////////////////////////////////////////////////////////////////////////////////////////
//_____________________________________________________________________________
Int_t AliTRDCalibraFillHisto::CalculateCalibrationGroup(Int_t i, Int_t row, Int_t col) const
{
//
// Calculate the calibration group number for i
//
// Row of the cluster and position in the pad groups
Int_t posr = 0;
if (fCalibraMode->GetNnZ(i) != 0) {
posr = (Int_t) row / fCalibraMode->GetNnZ(i);
}
// Col of the cluster and position in the pad groups
Int_t posc = 0;
if (fCalibraMode->GetNnRphi(i) != 0) {
posc = (Int_t) col / fCalibraMode->GetNnRphi(i);
}
return posc*fCalibraMode->GetNfragZ(i)+posr;
}
//____________________________________________________________________________________
Int_t AliTRDCalibraFillHisto::CalculateTotalNumberOfBins(Int_t i)
{
//
// Calculate the total number of calibration groups
//
Int_t ntotal = 0;
// All together
if((fCalibraMode->GetNz(i)==100) && (fCalibraMode->GetNrphi(i)==100)){
ntotal = 1;
AliInfo(Form("Total number of Xbins: %d for i %d",ntotal,i));
return ntotal;
}
// Per Supermodule
if((fCalibraMode->GetNz(i)==10) && (fCalibraMode->GetNrphi(i)==10)){
ntotal = 18;
AliInfo(Form("Total number of Xbins: %d for i %d",ntotal,i));
return ntotal;
}
// More
fCalibraMode->ModePadCalibration(2,i);
fCalibraMode->ModePadFragmentation(0,2,0,i);
fCalibraMode->SetDetChamb2(i);
ntotal += 6 * 18 * fCalibraMode->GetDetChamb2(i);
fCalibraMode->ModePadCalibration(0,i);
fCalibraMode->ModePadFragmentation(0,0,0,i);
fCalibraMode->SetDetChamb0(i);
ntotal += 6 * 4 * 18 * fCalibraMode->GetDetChamb0(i);
AliInfo(Form("Total number of Xbins: %d for i %d",ntotal,i));
return ntotal;
}
//_____________________________________________________________________________
void AliTRDCalibraFillHisto::SetNz(Int_t i, Short_t Nz)
{
//
// Set the mode of calibration group in the z direction for the parameter i
//
if ((Nz >= 0) &&
(Nz < 5)) {
fCalibraMode->SetNz(i, Nz);
}
else {
AliInfo("You have to choose between 0 and 4");
}
}
//_____________________________________________________________________________
void AliTRDCalibraFillHisto::SetNrphi(Int_t i, Short_t Nrphi)
{
//
// Set the mode of calibration group in the rphi direction for the parameter i
//
if ((Nrphi >= 0) &&
(Nrphi < 7)) {
fCalibraMode->SetNrphi(i ,Nrphi);
}
else {
AliInfo("You have to choose between 0 and 6");
}
}
//_____________________________________________________________________________
void AliTRDCalibraFillHisto::SetAllTogether(Int_t i)
{
//
// Set the mode of calibration group all together
//
if(fVector2d == kTRUE) {
AliInfo("Can not work with the vector method");
return;
}
fCalibraMode->SetAllTogether(i);
}
//_____________________________________________________________________________
void AliTRDCalibraFillHisto::SetPerSuperModule(Int_t i)
{
//
// Set the mode of calibration group per supermodule
//
if(fVector2d == kTRUE) {
AliInfo("Can not work with the vector method");
return;
}
fCalibraMode->SetPerSuperModule(i);
}
//____________Set the pad calibration variables for the detector_______________
Bool_t AliTRDCalibraFillHisto::LocalisationDetectorXbins(Int_t detector)
{
//
// For the detector calcul the first Xbins and set the number of row
// and col pads per calibration groups, the number of calibration
// groups in the detector.
//
// first Xbins of the detector
if (fCH2dOn) {
fCalibraMode->CalculXBins(detector,0);
}
if (fPH2dOn) {
fCalibraMode->CalculXBins(detector,1);
}
if (fPRF2dOn) {
fCalibraMode->CalculXBins(detector,2);
}
// fragmentation of idect
for (Int_t i = 0; i < 3; i++) {
fCalibraMode->ModePadCalibration((Int_t) GetStack(detector),i);
fCalibraMode->ModePadFragmentation((Int_t) GetLayer(detector)
, (Int_t) GetStack(detector)
, (Int_t) GetSector(detector),i);
}
return kTRUE;
}
//_____________________________________________________________________________
void AliTRDCalibraFillHisto::SetNumberGroupsPRF(Short_t numberGroupsPRF)
{
//
// Should be between 0 and 6
//
if ((numberGroupsPRF < 0) || (numberGroupsPRF > 6)) {
AliInfo("The number of groups must be between 0 and 6!");
}
else {
fNgroupprf = numberGroupsPRF;
}
}
///////////////////////////////////////////////////////////////////////////////////////////
// Per tracklet: store or reset the info, fill the histos with the info
//////////////////////////////////////////////////////////////////////////////////////////
//_____________________________________________________________________________
Float_t AliTRDCalibraFillHisto::StoreInfoCHPHtrack(const AliTRDcluster *cl,const Double_t dqdl,const Int_t *group,const Int_t row,const Int_t col,const AliTRDcluster *cls)
{
//
// Store the infos in fAmpTotal, fPHPlace and fPHValue
// Correct from the gain correction before
// cls is shared cluster if any
// Return the charge
//
//
//printf("StoreInfoCHPHtrack\n");
// time bin of the cluster not corrected
Int_t time = cl->GetPadTime();
Float_t charge = TMath::Abs(cl->GetQ());
if(cls) {
charge += TMath::Abs(cls->GetQ());
//printf("AliTRDCalibraFillHisto::Add the cluster charge");
}
//printf("Store::time %d, amplitude %f\n",time,dqdl);
//Correct for the gain coefficient used in the database for reconstruction
Float_t correctthegain = 1.0;
if(fIsHLT) correctthegain = fCalDetGain->GetValue(fDetectorPreviousTrack);
else correctthegain = fCalDetGain->GetValue(fDetectorPreviousTrack)*fCalROCGain->GetValue(col,row);
Float_t correction = 1.0;
Float_t normalisation = 1.13; //org: 6.67; 1st: 1.056; 2nd: 1.13;
// we divide with gain in AliTRDclusterizer::Transform...
if( correctthegain > 0 ) normalisation /= correctthegain;
// take dd/dl corrected from the angle of the track
correction = dqdl / (normalisation);
// Fill the fAmpTotal with the charge
if (fCH2dOn) {
if((!fLimitChargeIntegration) || (cl->IsInChamber())) {
//printf("Store::group %d, amplitude %f\n",group[0],correction);
fAmpTotal[(Int_t) group[0]] += correction;
}
}
// Fill the fPHPlace and value
if (fPH2dOn) {
if (time>=0 && time<fTimeMax) {
fPHPlace[time] = group[1];
fPHValue[time] = charge;
}
}
return correction;
}
//____________Offine tracking in the AliTRDtracker_____________________________
void AliTRDCalibraFillHisto::ResetfVariablestracklet()
{
//
// Reset values per tracklet
//
//Reset good tracklet
fGoodTracklet = kTRUE;
// Reset the fPHValue
if (fPH2dOn) {
//Reset the fPHValue and fPHPlace
for (Int_t k = 0; k < fTimeMax; k++) {
fPHValue[k] = 0.0;
fPHPlace[k] = -1;
}
}
// Reset the fAmpTotal where we put value
if (fCH2dOn) {
for (Int_t k = 0; k < fCalibraMode->GetNfragZ(0)*fCalibraMode->GetNfragRphi(0); k++) {
fAmpTotal[k] = 0.0;
}
}
}
//____________Offine tracking in the AliTRDtracker_____________________________
void AliTRDCalibraFillHisto::FillTheInfoOfTheTrackCH(Int_t nbclusters)
{
//
// For the offline tracking or mcm tracklets
// This function will be called in the functions UpdateHistogram...
// to fill the info of a track for the relativ gain calibration
//
Int_t nb = 0; // Nombre de zones traversees
Int_t fd = -1; // Premiere zone non nulle
Float_t totalcharge = 0.0; // Total charge for the supermodule histo
//printf("CH2d nbclusters %d, fNumberClusters %d, fNumberClustersf %d\n",nbclusters,fNumberClusters,fNumberClustersf);
if(nbclusters < fNumberClusters) return;
if(nbclusters > fNumberClustersf) return;
// Normalize with the number of clusters
Double_t normalizeCst = fRelativeScale;
if(fNormalizeNbOfCluster) normalizeCst = normalizeCst*nbclusters;
//printf("Number of groups in one detector %d\n",fCalibraMode->GetNfragZ(0)*fCalibraMode->GetNfragRphi(0));
// See if the track goes through different zones
for (Int_t k = 0; k < fCalibraMode->GetNfragZ(0)*fCalibraMode->GetNfragRphi(0); k++) {
//printf("fAmpTotal %f for %d\n",fAmpTotal[k],k);
if (fAmpTotal[k] > 0.0) {
totalcharge += fAmpTotal[k];
nb++;
if (nb == 1) {
fd = k;
}
}
}
//printf("CH2d: nb %d, fd %d, calibration group %d, amplitude %f, detector %d\n",nb,fd,fCalibraMode->GetXbins(0),fAmpTotal[fd]/normalizeCst,fDetectorPreviousTrack);
switch (nb)
{
case 1:
fNumberUsedCh[0]++;
fEntriesCH[fCalibraMode->GetXbins(0)+fd]++;
if (fHisto2d) {
FillCH2d(fCalibraMode->GetXbins(0)+fd,fAmpTotal[fd]/normalizeCst);
//fCH2d->Fill(fAmpTotal[fd]/normalizeCst,fCalibraMode->GetXbins(0)+fd+0.5);
}
if (fVector2d) {
fCalibraVector->UpdateVectorCH(fDetectorPreviousTrack,fd,fAmpTotal[fd]/normalizeCst);
}
break;
case 2:
if ((fAmpTotal[fd] > 0.0) &&
(fAmpTotal[fd+1] > 0.0)) {
// One of the two very big
if (fAmpTotal[fd] > fProcent*fAmpTotal[fd+1]) {
if (fHisto2d) {
FillCH2d(fCalibraMode->GetXbins(0)+fd,fAmpTotal[fd]/normalizeCst);
//fCH2d->Fill(fAmpTotal[fd]/normalizeCst,fCalibraMode->GetXbins(0)+fd+0.5);
}
if (fVector2d) {
fCalibraVector->UpdateVectorCH(fDetectorPreviousTrack,fd,fAmpTotal[fd]/normalizeCst);
}
fNumberUsedCh[1]++;
fEntriesCH[fCalibraMode->GetXbins(0)+fd]++;
}
if (fAmpTotal[fd+1] > fProcent*fAmpTotal[fd]) {
if (fHisto2d) {
FillCH2d(fCalibraMode->GetXbins(0)+fd+1,fAmpTotal[fd+1]/normalizeCst);
//fCH2d->Fill(fAmpTotal[fd+1]/normalizeCst,fCalibraMode->GetXbins(0)+fd+1.5);
}
if (fVector2d) {
fCalibraVector->UpdateVectorCH(fDetectorPreviousTrack,fd+1,fAmpTotal[fd+1]/normalizeCst);
}
fNumberUsedCh[1]++;
fEntriesCH[fCalibraMode->GetXbins(0)+fd+1]++;
}
}
if (fCalibraMode->GetNfragZ(0) > 1) {
if (fAmpTotal[fd] > 0.0) {
if ((fd+fCalibraMode->GetNfragZ(0)) < (fCalibraMode->GetNfragZ(0)*fCalibraMode->GetNfragRphi(0))) {
if (fAmpTotal[fd+fCalibraMode->GetNfragZ(0)] > 0.0) {
// One of the two very big
if (fAmpTotal[fd] > fProcent*fAmpTotal[fd+fCalibraMode->GetNfragZ(0)]) {
if (fHisto2d) {
FillCH2d(fCalibraMode->GetXbins(0)+fd,fAmpTotal[fd]/normalizeCst);
//fCH2d->Fill(fAmpTotal[fd]/normalizeCst,fCalibraMode->GetXbins(0)+fd+0.5);
}
if (fVector2d) {
fCalibraVector->UpdateVectorCH(fDetectorPreviousTrack,fd,fAmpTotal[fd]/normalizeCst);
}
fNumberUsedCh[1]++;
fEntriesCH[fCalibraMode->GetXbins(0)+fd]++;
}
if (fAmpTotal[fd+fCalibraMode->GetNfragZ(0)] > fProcent*fAmpTotal[fd]) {
if (fHisto2d) {
FillCH2d(fCalibraMode->GetXbins(0)+fd+fCalibraMode->GetNfragZ(0),fAmpTotal[fd+fCalibraMode->GetNfragZ(0)]/normalizeCst);
//fCH2d->Fill(fAmpTotal[fd+fCalibraMode->GetNfragZ(0)]/normalizeCst,fCalibraMode->GetXbins(0)+fd+fCalibraMode->GetNfragZ(0)+0.5);
}
fNumberUsedCh[1]++;
fEntriesCH[fCalibraMode->GetXbins(0)+fd+fCalibraMode->GetNfragZ(0)]++;
if (fVector2d) {
fCalibraVector->UpdateVectorCH(fDetectorPreviousTrack,fd+fCalibraMode->GetNfragZ(0),fAmpTotal[fd+fCalibraMode->GetNfragZ(0)]/normalizeCst);
}
}
}
}
}
}
break;
default: break;
}
}
//____________Offine tracking in the AliTRDtracker_____________________________
void AliTRDCalibraFillHisto::FillTheInfoOfTheTrackPH()
{
//
// For the offline tracking or mcm tracklets
// This function will be called in the functions UpdateHistogram...
// to fill the info of a track for the drift velocity calibration
//
Int_t nb = 1; // Nombre de zones traversees 1, 2 ou plus de 3
Int_t fd1 = -1; // Premiere zone non nulle
Int_t fd2 = -1; // Deuxieme zone non nulle
Int_t k1 = -1; // Debut de la premiere zone
Int_t k2 = -1; // Debut de la seconde zone
Int_t nbclusters = 0; // number of clusters
// See if the track goes through different zones
for (Int_t k = 0; k < fTimeMax; k++) {
if (fPHValue[k] > 0.0) {
nbclusters++;
if (fd1 == -1) {
fd1 = fPHPlace[k];
k1 = k;
}
if (fPHPlace[k] != fd1) {
if (fd2 == -1) {
k2 = k;
fd2 = fPHPlace[k];
nb = 2;
}
if (fPHPlace[k] != fd2) {
nb = 3;
}
}
}
}
// See if noise before and after
if(fMaxCluster > 0) {
if(fPHValue[0] > fMaxCluster) return;
if(fTimeMax > fNbMaxCluster) {
for(Int_t k = (fTimeMax-fNbMaxCluster); k < fTimeMax; k++){
if(fPHValue[k] > fMaxCluster) return;
}
}
}
//printf("nbclusters %d, low limit %d, high limit %d\n",nbclusters,fNumberClusters,fNumberClustersf);
if(nbclusters < fNumberClusters) return;
if(nbclusters > fNumberClustersf) return;
switch(nb)
{
case 1:
fNumberUsedPh[0]++;
for (Int_t i = 0; i < fTimeMax; i++) {
if (fHisto2d) {
if(fFillWithZero) fPH2d->Fill((Float_t) i/fSf,(fCalibraMode->GetXbins(1)+fd1)+0.5,(Float_t) fPHValue[i]);
else {
if(((Float_t) fPHValue[i] > 0.0)) fPH2d->Fill((Float_t) i/fSf,(fCalibraMode->GetXbins(1)+fd1)+0.5,(Float_t) fPHValue[i]);
}
//printf("Fill the time bin %d with %f\n",i,fPHValue[i]);
}
if (fVector2d) {
if(fFillWithZero) fCalibraVector->UpdateVectorPH(fDetectorPreviousTrack,fd1,i,fPHValue[i]);
else {
if(((Float_t) fPHValue[i] > 0.0)) fCalibraVector->UpdateVectorPH(fDetectorPreviousTrack,fd1,i,fPHValue[i]);
}
}
}
break;
case 2:
if ((fd1 == fd2+1) ||
(fd2 == fd1+1)) {
// One of the two fast all the think
if (k2 > (k1+fDifference)) {
//we choose to fill the fd1 with all the values
fNumberUsedPh[1]++;
for (Int_t i = 0; i < fTimeMax; i++) {
if (fHisto2d) {
if(fFillWithZero) fPH2d->Fill((Float_t) i/fSf,(fCalibraMode->GetXbins(1)+fd1)+0.5,(Float_t) fPHValue[i]);
else {
if(((Float_t) fPHValue[i] > 0.0)) fPH2d->Fill((Float_t) i/fSf,(fCalibraMode->GetXbins(1)+fd1)+0.5,(Float_t) fPHValue[i]);
}
}
if (fVector2d) {
if(fFillWithZero) fCalibraVector->UpdateVectorPH(fDetectorPreviousTrack,fd1,i,fPHValue[i]);
else {
if(((Float_t) fPHValue[i] > 0.0)) fCalibraVector->UpdateVectorPH(fDetectorPreviousTrack,fd1,i,fPHValue[i]);
}
}
}
}
if ((k2+fDifference) < fTimeMax) {
//we choose to fill the fd2 with all the values
fNumberUsedPh[1]++;
for (Int_t i = 0; i < fTimeMax; i++) {
if (fHisto2d) {
if(fFillWithZero) fPH2d->Fill((Float_t) i/fSf,(fCalibraMode->GetXbins(1)+fd2)+0.5,(Float_t) fPHValue[i]);
else {
if(((Float_t) fPHValue[i] > 0.0)) fPH2d->Fill((Float_t) i/fSf,(fCalibraMode->GetXbins(1)+fd2)+0.5,(Float_t) fPHValue[i]);
}
}
if (fVector2d) {
if(fFillWithZero) fCalibraVector->UpdateVectorPH(fDetectorPreviousTrack,fd2,i,fPHValue[i]);
else {
if(((Float_t) fPHValue[i] > 0.0)) fCalibraVector->UpdateVectorPH(fDetectorPreviousTrack,fd2,i,fPHValue[i]);
}
}
}
}
}
// Two zones voisines sinon rien!
if (fCalibraMode->GetNfragZ(1) > 1) {
// Case 2
if ((fd1+fCalibraMode->GetNfragZ(1)) < (fCalibraMode->GetNfragZ(1)*fCalibraMode->GetNfragRphi(1))) {
if (fd2 == (fd1+fCalibraMode->GetNfragZ(1))) {
// One of the two fast all the think
if (k2 > (k1+fDifference)) {
//we choose to fill the fd1 with all the values
fNumberUsedPh[1]++;
for (Int_t i = 0; i < fTimeMax; i++) {
if (fHisto2d) {
if(fFillWithZero) fPH2d->Fill((Float_t) i/fSf,(fCalibraMode->GetXbins(1)+fd1)+0.5,(Float_t) fPHValue[i]);
else {
if(((Float_t) fPHValue[i] > 0.0)) fPH2d->Fill((Float_t) i/fSf,(fCalibraMode->GetXbins(1)+fd1)+0.5,(Float_t) fPHValue[i]);
}
}
if (fVector2d) {
if(fFillWithZero) fCalibraVector->UpdateVectorPH(fDetectorPreviousTrack,fd1,i,fPHValue[i]);
else {
if(((Float_t) fPHValue[i] > 0.0)) fCalibraVector->UpdateVectorPH(fDetectorPreviousTrack,fd1,i,fPHValue[i]);
}
}
}
}
if ((k2+fDifference) < fTimeMax) {
//we choose to fill the fd2 with all the values
fNumberUsedPh[1]++;
for (Int_t i = 0; i < fTimeMax; i++) {
if (fHisto2d) {
if(fFillWithZero) fPH2d->Fill((Float_t) i/fSf,(fCalibraMode->GetXbins(1)+fd2)+0.5,(Float_t) fPHValue[i]);
else {
if(((Float_t) fPHValue[i] > 0.0)) fPH2d->Fill((Float_t) i/fSf,(fCalibraMode->GetXbins(1)+fd2)+0.5,(Float_t) fPHValue[i]);
}
}
if (fVector2d) {
if(fFillWithZero) fCalibraVector->UpdateVectorPH(fDetectorPreviousTrack,fd2,i,fPHValue[i]);
else {
if(((Float_t) fPHValue[i] > 0.0)) fCalibraVector->UpdateVectorPH(fDetectorPreviousTrack,fd2,i,fPHValue[i]);
}
}
}
}
}
}
// Two zones voisines sinon rien!
// Case 3
if ((fd1 - fCalibraMode->GetNfragZ(1)) >= 0) {
if (fd2 == (fd1 - fCalibraMode->GetNfragZ(1))) {
// One of the two fast all the think
if (k2 > (k1 + fDifference)) {
//we choose to fill the fd1 with all the values
fNumberUsedPh[1]++;
for (Int_t i = 0; i < fTimeMax; i++) {
if (fHisto2d) {
if(fFillWithZero) fPH2d->Fill((Float_t) i/fSf,(fCalibraMode->GetXbins(1)+fd1)+0.5,(Float_t) fPHValue[i]);
else {
if(((Float_t) fPHValue[i] > 0.0)) fPH2d->Fill((Float_t) i/fSf,(fCalibraMode->GetXbins(1)+fd1)+0.5,(Float_t) fPHValue[i]);
}
}
if (fVector2d) {
if(fFillWithZero) fCalibraVector->UpdateVectorPH(fDetectorPreviousTrack,fd1,i,fPHValue[i]);
else {
if(((Float_t) fPHValue[i] > 0.0)) fCalibraVector->UpdateVectorPH(fDetectorPreviousTrack,fd1,i,fPHValue[i]);
}
}
}
}
if ((k2+fDifference) < fTimeMax) {
//we choose to fill the fd2 with all the values
fNumberUsedPh[1]++;
for (Int_t i = 0; i < fTimeMax; i++) {
if (fHisto2d) {
if(fFillWithZero) fPH2d->Fill((Float_t) i/fSf,(fCalibraMode->GetXbins(1)+fd2)+0.5,(Float_t) fPHValue[i]);
else {
if(((Float_t) fPHValue[i] > 0.0)) fPH2d->Fill((Float_t) i/fSf,(fCalibraMode->GetXbins(1)+fd2)+0.5,(Float_t) fPHValue[i]);
}
}
if (fVector2d) {
if(fFillWithZero) fCalibraVector->UpdateVectorPH(fDetectorPreviousTrack,fd2,i,fPHValue[i]);
else {
if(((Float_t) fPHValue[i] > 0.0)) fCalibraVector->UpdateVectorPH(fDetectorPreviousTrack,fd2,i,fPHValue[i]);
}
}
}
}
}
}
}
break;
default: break;
}
}
//////////////////////////////////////////////////////////////////////////////////////////
// DAQ process functions
/////////////////////////////////////////////////////////////////////////////////////////
//_____________________________________________________________________
Int_t AliTRDCalibraFillHisto::ProcessEventDAQ(AliRawReader *rawReader)
{ //main
//
// Event Processing loop - AliTRDrawStream
//
// 0 timebin problem
// 1 no input
// 2 input
// Same algorithm as TestBeam but different reader
//
AliTRDrawStream *rawStream = new AliTRDrawStream(rawReader);
AliTRDdigitsManager *digitsManager = new AliTRDdigitsManager(kTRUE);
digitsManager->CreateArrays();
Int_t withInput = 1;
Double_t phvalue[16][144][36];
for(Int_t k = 0; k < 36; k++){
for(Int_t j = 0; j < 16; j++){
for(Int_t c = 0; c < 144; c++){
phvalue[j][c][k] = 0.0;
}
}
}
fDetectorPreviousTrack = -1;
fMCMPrevious = -1;
fROBPrevious = -1;
Int_t nbtimebin = 0;
Int_t baseline = 10;
fTimeMax = 0;
Int_t det = 0;
while ((det = rawStream->NextChamber(digitsManager, NULL, NULL)) >= 0) { //idetector
if (digitsManager->GetIndexes(det)->HasEntry()) {//QA
// printf("there is ADC data on this chamber!\n");
AliTRDarrayADC *digits = (AliTRDarrayADC *) digitsManager->GetDigits(det); //mod
if (digits->HasData()) { //array
AliTRDSignalIndex *indexes = digitsManager->GetIndexes(det);
if (indexes->IsAllocated() == kFALSE) {
AliError("Indexes do not exist!");
break;
}
Int_t iRow = 0;
Int_t iCol = 0;
indexes->ResetCounters();
while (indexes->NextRCIndex(iRow, iCol)) { //column,row
//printf(" det %d \t row %d \t col %d \t digit\n",det,iRow,iCol);
//while (rawStream->Next()) {
Int_t idetector = det; // current detector
//Int_t imcm = rawStream->GetMCM(); // current MCM
//Int_t irob = rawStream->GetROB(); // current ROB
if((fDetectorPreviousTrack != idetector) && (fDetectorPreviousTrack != -1)) {
// Fill
withInput = TMath::Max(FillDAQ(phvalue),withInput);
// reset
for(Int_t k = 0; k < 36; k++){
for(Int_t j = 0; j < 16; j++){
for(Int_t c = 0; c < 144; c++){
phvalue[j][c][k] = 0.0;
}
}
}
}
fDetectorPreviousTrack = idetector;
//fMCMPrevious = imcm;
//fROBPrevious = irob;
// nbtimebin = rawStream->GetNumberOfTimeBins(); // number of time bins read from data
AliTRDdigitsParam *digitParam = (AliTRDdigitsParam *)digitsManager->GetDigitsParam();
nbtimebin = digitParam->GetNTimeBins(det); // number of time bins read from data
baseline = digitParam->GetADCbaseline(det); // baseline
if(nbtimebin == 0) return 0;
if((fTimeMax != 0) && (nbtimebin != fTimeMax)) return 0;
fTimeMax = nbtimebin;
fNumberClustersf = fTimeMax;
fNumberClusters = (Int_t)(fNumberClustersProcent*fTimeMax);
for(Int_t itime = 0; itime < nbtimebin; itime++) {
// phvalue[row][col][itime] = signal[itime]-baseline;
phvalue[iRow][iCol][itime] = (Short_t)(digits->GetData(iRow,iCol,itime) - baseline);
/*if(phvalue[iRow][iCol][itime] >= 20) {
printf("----------> phvalue[%d][%d][%d] %d baseline %d \n",
iRow,
iCol,
itime,
(Short_t)(digits->GetData(iRow,iCol,itime)),
baseline);
}*/
}
}//column,row
// fill the last one
if(fDetectorPreviousTrack != -1){
// Fill
withInput = TMath::Max(FillDAQ(phvalue),withInput);
// printf("\n ---> withinput %d\n\n",withInput);
// reset
for(Int_t k = 0; k < 36; k++){
for(Int_t j = 0; j < 16; j++){
for(Int_t c = 0; c < 144; c++){
phvalue[j][c][k] = 0.0;
}
}
}
}
}//array
}//QA
digitsManager->ClearArrays(det);
}//idetector
delete digitsManager;
delete rawStream;
return withInput;
}//main
//_____________________________________________________________________
//////////////////////////////////////////////////////////////////////////////
// Routine inside the DAQ process
/////////////////////////////////////////////////////////////////////////////
//_______________________________________________________________________
Int_t AliTRDCalibraFillHisto::FillDAQ(Double_t phvalue[16][144][36]){
//
// Look for the maximum by collapsing over the time
// Sum over four pad col and two pad row
//
Int_t used = 0;
Int_t idect = fDetectorPreviousTrack;
//printf("Enter Detector %d\n",fDetectorPreviousTrack);
Double_t sum[36];
for(Int_t tb = 0; tb < 36; tb++){
sum[tb] = 0.0;
}
//fGoodTracklet = kTRUE;
//fDetectorPreviousTrack = 0;
///////////////////////////
// look for maximum
/////////////////////////
Int_t imaxRow = 0;
Int_t imaxCol = 0;
Double_t integralMax = -1;
for (Int_t ir = 1; ir <= 15; ir++)
{
for (Int_t ic = 2; ic <= 142; ic++)
{
Double_t integral = 0;
for (Int_t ishiftR = 0; ishiftR < fNumberRowDAQ; ishiftR++)
{
for (Int_t ishiftC = -fNumberColDAQ; ishiftC < fNumberColDAQ; ishiftC++)
{
if (ir + ishiftR >= 1 && ir + ishiftR <= 16 &&
ic + ishiftC >= 1 && ic + ishiftC <= 144)
{
for(Int_t tb = 0; tb< fTimeMax; tb++){
integral += phvalue[ir + ishiftR-1][ic + ishiftC-1][tb];
}// addtb
} //addsignal
} //shiftC
} // shiftR
if (integralMax < integral)
{
imaxRow = ir;
imaxCol = ic;
integralMax = integral;
} // check max integral
} //ic
} // ir
// printf("imaxRow %d, imaxCol %d, fTimeMax %d, integralMax %f\n",imaxRow,imaxCol,fTimeMax, integralMax);
//if((imaxRow == 0) || (imaxRow >= 15) || (imaxCol <= 3) || (imaxCol >= 140)) {
// used=1;
// return used;
// }
if(((imaxRow + fNumberRowDAQ) > 16) || (imaxRow == 0) || ((imaxCol - fNumberColDAQ) <= 1) || ((imaxCol + fNumberColDAQ) >= 144)) {
used=1;
return used;
}
//CheckGoodTrackletV0(fDetectorPreviousTrack,imaxRow,imaxCol);
//if(!fGoodTracklet) used = 1;;
// /////////////////////////////////////////////////////
// sum ober 2 row and 4 pad cols for each time bins
// ////////////////////////////////////////////////////
for (Int_t ishiftR = 0; ishiftR < fNumberRowDAQ; ishiftR++)
{
for (Int_t ishiftC = -fNumberColDAQ; ishiftC < fNumberColDAQ; ishiftC++)
{
if (imaxRow + ishiftR >= 1 && imaxRow + ishiftR <= 16 &&
imaxCol + ishiftC >= 1 && imaxCol + ishiftC <= 144)
{
for(Int_t it = 0; it < fTimeMax; it++){
sum[it] += phvalue[imaxRow + ishiftR-1][imaxCol + ishiftC-1][it];
}
}
} // col shift
}// row shift
Int_t nbcl = 0;
Double_t sumcharge = 0.0;
for(Int_t it = 0; it < fTimeMax; it++){
sumcharge += sum[it];
if(sum[it] > fThresholdClustersDAQ) nbcl++;
}
/////////////////////////////////////////////////////////
// Debug
////////////////////////////////////////////////////////
if(fDebugLevel > 1){
if ( !fDebugStreamer ) {
//debug stream
TDirectory *backup = gDirectory;
fDebugStreamer = new TTreeSRedirector("TRDdebugCalibraFill.root");
if ( backup ) backup->cd(); //we don't want to be cd'd to the debug streamer
}
Double_t amph0 = sum[0];
Double_t amphlast = sum[fTimeMax-1];
Double_t rms = TMath::RMS(fTimeMax,sum);
Int_t goodtracklet = (Int_t) fGoodTracklet;
for(Int_t it = 0; it < fTimeMax; it++){
Double_t clustera = sum[it];
(* fDebugStreamer) << "FillDAQa"<<
"ampTotal="<<sumcharge<<
"row="<<imaxRow<<
"col="<<imaxCol<<
"detector="<<idect<<
"amph0="<<amph0<<
"amphlast="<<amphlast<<
"goodtracklet="<<goodtracklet<<
"clustera="<<clustera<<
"it="<<it<<
"rms="<<rms<<
"nbcl="<<nbcl<<
"\n";
}
}
////////////////////////////////////////////////////////
// fill
///////////////////////////////////////////////////////
//printf("fNumberClusters %d, fNumberClustersf %d\n",fNumberClusters,fNumberClustersf);
if(sum[0] > 100.0) used = 1;
if(nbcl < fNumberClusters) used = 1;
if(nbcl > fNumberClustersf) used = 1;
//if(fDetectorPreviousTrack == 15){
// printf("rms %f and first time bin %f\n",TMath::RMS(fTimeMax,sum),sum[0]);
//}
//if((TMath::RMS(fTimeMax,sum) <= 10.0) && (sum[0] > 200.0)) return 1;
if(used == 0){
for(Int_t it = 0; it < fTimeMax; it++){
if(fFillWithZero) UpdateDAQ(fDetectorPreviousTrack,0,0,it,sum[it],fTimeMax);
else{
if(sum[it] > 0.0) UpdateDAQ(fDetectorPreviousTrack,0,0,it,sum[it],fTimeMax);
}
//if(fFillWithZero) UpdateDAQ(0,0,0,it,sum[it],fTimeMax);
//else{
// if(sum[it] > 0.0) UpdateDAQ(0,0,0,it,sum[it],fTimeMax);
//}
}
//((TH2I *)GetCH2d()->Fill(sumcharge/30.0,fDetectorPreviousTrack));
used = 2;
//printf("Pass Detector %d\n",fDetectorPreviousTrack);
}
return used;
}
//____________Online trackling in AliTRDtrigger________________________________
Bool_t AliTRDCalibraFillHisto::UpdateDAQ(Int_t det, Int_t /*row*/, Int_t /*col*/, Int_t timebin, Float_t signal, Int_t nbtimebins)
{
//
// For the DAQ
// Fill a simple average pulse height
//
((TProfile2D *)GetPH2d(nbtimebins,fSf))->Fill((Float_t) timebin/fSf,det+0.5,(Float_t) signal);
return kTRUE;
}
//____________Write_____________________________________________________
//_____________________________________________________________________
void AliTRDCalibraFillHisto::Write2d(const Char_t *filename, Bool_t append)
{
//
// Write infos to file
//
//For debugging
if ( fDebugStreamer ) {
delete fDebugStreamer;
fDebugStreamer = 0x0;
}
AliInfo(Form("Numbertrack: %d Numberusedch[0]: %d, Numberusedch[1]: %d Numberusedph[0]: %d, Numberusedph[1]: %d"
,fNumberTrack
,fNumberUsedCh[0]
,fNumberUsedCh[1]
,fNumberUsedPh[0]
,fNumberUsedPh[1]));
TDirectory *backup = gDirectory;
TString option;
if ( append )
option = "update";
else
option = "recreate";
TFile f(filename,option.Data());
TStopwatch stopwatch;
stopwatch.Start();
if(fVector2d) {
f.WriteTObject(fCalibraVector);
}
if (fCH2dOn ) {
if (fHisto2d) {
f.WriteTObject(fCH2d);
}
}
if (fPH2dOn ) {
if (fHisto2d) {
f.WriteTObject(fPH2d);
}
}
if (fPRF2dOn) {
if (fHisto2d) {
f.WriteTObject(fPRF2d);
}
}
if(fLinearFitterOn){
if(fLinearFitterDebugOn) AnalyseLinearFitter();
f.WriteTObject(fLinearVdriftFit);
}
f.Close();
if ( backup ) backup->cd();
AliInfo(Form("Execution time Write2d: R:%.2fs C:%.2fs"
,stopwatch.RealTime(),stopwatch.CpuTime()));
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Stats stuff
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//___________________________________________probe the histos__________________________________________________
Double_t *AliTRDCalibraFillHisto::StatH(TH2 *h, Int_t i)
{
//
// Check the number of stats in h, 0 is TH2I 1 is TProfile2D
// debug mode with 2 for TH2I and 3 for TProfile2D
// It gives a pointer to a Double_t[7] with the info following...
// [0] : number of calibration groups with entries
// [1] : minimal number of entries found
// [2] : calibration group number of the min
// [3] : maximal number of entries found
// [4] : calibration group number of the max
// [5] : mean number of entries found
// [6] : mean relative error
//
Double_t *info = new Double_t[7];
// Number of Xbins (detectors or groups of pads)
Int_t nbins = h->GetNbinsY(); //number of calibration groups
Int_t nxbins = h->GetNbinsX(); //number of bins per histo
// Initialise
Double_t nbwe = 0; //number of calibration groups with entries
Double_t minentries = 0; //minimal number of entries found
Double_t maxentries = 0; //maximal number of entries found
Double_t placemin = 0; //calibration group number of the min
Double_t placemax = -1; //calibration group number of the max
Double_t meanstats = 0.0; //mean number of entries over the calibration group with at least ome entry
Double_t meanrelativerror = 0.0; //mean relativ error in the TProfile2D
Double_t counter = 0;
//Debug
TH1F *nbEntries = 0x0;//distribution of the number of entries
TH1F *nbEntriesPerGroup = 0x0;//Number of entries per group
TProfile *nbEntriesPerSp = 0x0;//Number of entries for one supermodule
// Beginning of the loop over the calibration groups
for (Int_t idect = 0; idect < nbins; idect++) {
TH1I *projch = (TH1I *) h->ProjectionX("projch",idect+1,idect+1,(Option_t *)"e");
projch->SetDirectory(0);
// Number of entries for this calibration group
Double_t nentries = 0.0;
if((i%2) == 0){
for (Int_t k = 0; k < nxbins; k++) {
nentries += h->GetBinContent(h->GetBin(k+1,idect+1));
}
}
else{
for (Int_t k = 0; k < nxbins; k++) {
nentries += ((TProfile2D *)h)->GetBinEntries(h->GetBin(k+1,idect+1));
if(h->GetBinContent(h->GetBin(k+1,idect+1)) != 0) {
meanrelativerror += (h->GetBinError(h->GetBin(k+1,idect+1))/(TMath::Abs(h->GetBinContent(h->GetBin(k+1,idect+1)))));
counter++;
}
}
}
//Debug
if(i > 1){
if(nentries > 0){
if(!((Bool_t)nbEntries)) nbEntries = new TH1F("Number of entries","Number of entries",100,(Int_t)nentries/2,nentries*2);
nbEntries->SetDirectory(0);
nbEntries->Fill(nentries);
if(!((Bool_t)nbEntriesPerGroup)) nbEntriesPerGroup = new TH1F("Number of entries per group","Number of entries per group",nbins,0,nbins);
nbEntriesPerGroup->SetDirectory(0);
nbEntriesPerGroup->Fill(idect+0.5,nentries);
if(!((Bool_t)nbEntriesPerSp)) nbEntriesPerSp = new TProfile("Number of entries per supermodule","Number of entries per supermodule",(Int_t)(nbins/18),0,(Int_t)(nbins/18));
nbEntriesPerSp->SetDirectory(0);
nbEntriesPerSp->Fill((idect%((Int_t)(nbins/18)))+0.5,nentries);
}
}
//min amd max
if(nentries > maxentries){
maxentries = nentries;
placemax = idect;
}
if(idect == 0) {
minentries = nentries;
}
if(nentries < minentries){
minentries = nentries;
placemin = idect;
}
//nbwe
if(nentries > 0) {
nbwe++;
meanstats += nentries;
}
}//calibration groups loop
if(nbwe > 0) meanstats /= nbwe;
if(counter > 0) meanrelativerror /= counter;
AliInfo(Form("There are %f calibration groups with entries",nbwe));
AliInfo(Form("The minimum number of entries is %f for the group %f",minentries,placemin));
AliInfo(Form("The maximum number of entries is %f for the group %f",maxentries,placemax));
AliInfo(Form("The mean number of entries is %f",meanstats));
if((i%2) == 1) AliInfo(Form("The mean relative error is %f",meanrelativerror));
info[0] = nbwe;
info[1] = minentries;
info[2] = placemin;
info[3] = maxentries;
info[4] = placemax;
info[5] = meanstats;
info[6] = meanrelativerror;
if(nbEntries && nbEntriesPerSp && nbEntriesPerGroup){
gStyle->SetPalette(1);
gStyle->SetOptStat(1111);
gStyle->SetPadBorderMode(0);
gStyle->SetCanvasColor(10);
gStyle->SetPadLeftMargin(0.13);
gStyle->SetPadRightMargin(0.01);
TCanvas *stat = new TCanvas("stat","",50,50,600,800);
stat->Divide(2,1);
stat->cd(1);
nbEntries->Draw("");
stat->cd(2);
nbEntriesPerSp->SetStats(0);
nbEntriesPerSp->Draw("");
TCanvas *stat1 = new TCanvas("stat1","",50,50,600,800);
stat1->cd();
nbEntriesPerGroup->SetStats(0);
nbEntriesPerGroup->Draw("");
}
return info;
}
//____________________________________________________________________________
Double_t *AliTRDCalibraFillHisto::GetMeanMedianRMSNumberCH()
{
//
// Return a Int_t[4] with:
// 0 Mean number of entries
// 1 median of number of entries
// 2 rms of number of entries
// 3 number of group with entries
//
Double_t *stat = new Double_t[4];
stat[3] = 0.0;
Int_t nbofgroups = CalculateTotalNumberOfBins(0);
Double_t *weight = new Double_t[nbofgroups];
Double_t *nonul = new Double_t[nbofgroups];
for(Int_t k = 0; k < nbofgroups; k++){
if(fEntriesCH[k] > 0) {
weight[k] = 1.0;
nonul[(Int_t)stat[3]] = fEntriesCH[k];
stat[3]++;
}
else weight[k] = 0.0;
}
stat[0] = TMath::Mean(nbofgroups,fEntriesCH,weight);
stat[1] = TMath::Median(nbofgroups,fEntriesCH,weight);
stat[2] = TMath::RMS((Int_t)stat[3],nonul);
delete [] weight;
delete [] nonul;
return stat;
}
//____________________________________________________________________________
Double_t *AliTRDCalibraFillHisto::GetMeanMedianRMSNumberLinearFitter() const
{
//
// Return a Int_t[4] with:
// 0 Mean number of entries
// 1 median of number of entries
// 2 rms of number of entries
// 3 number of group with entries
//
Double_t *stat = new Double_t[4];
stat[3] = 0.0;
Int_t nbofgroups = 540;
Double_t *weight = new Double_t[nbofgroups];
Int_t *nonul = new Int_t[nbofgroups];
for(Int_t k = 0; k < nbofgroups; k++){
if(fEntriesLinearFitter[k] > 0) {
weight[k] = 1.0;
nonul[(Int_t) stat[3]] = fEntriesLinearFitter[k];
stat[3]++;
}
else weight[k] = 0.0;
}
stat[0] = TMath::Mean(nbofgroups,fEntriesLinearFitter,weight);
stat[1] = TMath::Median(nbofgroups,fEntriesLinearFitter,weight);
stat[2] = TMath::RMS((Int_t)stat[3],nonul);
delete [] weight;
delete [] nonul;
return stat;
}
//////////////////////////////////////////////////////////////////////////////////////
// Create Histos
//////////////////////////////////////////////////////////////////////////////////////
//_____________________________________________________________________________
void AliTRDCalibraFillHisto::CreatePRF2d(Int_t nn)
{
//
// Create the 2D histos: here we have 2*fNgroupprf bins in tnp of 0.2 amplitude each
// If fNgroupprf is zero then no binning in tnp
//
TString name("Nz");
name += fCalibraMode->GetNz(2);
name += "Nrphi";
name += fCalibraMode->GetNrphi(2);
name += "Ngp";
name += fNgroupprf;
if(fNgroupprf != 0){
fPRF2d = new TProfile2D("PRF2d",(const Char_t *) name
,2*fNgroupprf*fNumberBinPRF,-3.0*fNgroupprf,3.0*fNgroupprf,nn,0,nn);
fPRF2d->SetYTitle("Det/pad groups");
fPRF2d->SetXTitle("Position x/W [pad width units]");
fPRF2d->SetZTitle("Q_{i}/Q_{total}");
fPRF2d->SetStats(0);
}
else{
fPRF2d = new TProfile2D("PRF2d",(const Char_t *) name
,fNumberBinPRF,-1.5,1.5,nn,0,nn);
fPRF2d->SetYTitle("Det/pad groups");
fPRF2d->SetXTitle("Position x/W [pad width units]");
fPRF2d->SetZTitle("Q_{i}/Q_{total}");
fPRF2d->SetStats(0);
}
}
//_____________________________________________________________________________
void AliTRDCalibraFillHisto::CreatePH2d(Int_t nn)
{
//
// Create the 2D histos
//
fPH2d = new TProfile2D("PH2d",""
,fTimeMax,-0.5/fSf,(Float_t) (fTimeMax-0.5)/fSf
,nn,0,nn);
fPH2d->SetYTitle("Det/pad groups");
fPH2d->SetXTitle("time [#mus]");
fPH2d->SetZTitle("<PH> [a.u.]");
fPH2d->SetStats(0);
}
//_____________________________________________________________________________
void AliTRDCalibraFillHisto::CreateCH2d(Int_t nn)
{
//
// Create the 2D histos
//
fCH2d = new TH2I("CH2d",""
,(Int_t)fNumberBinCharge,0,fRangeHistoCharge,nn,0,nn);
fCH2d->SetYTitle("Det/pad groups");
fCH2d->SetXTitle("charge deposit [a.u]");
fCH2d->SetZTitle("counts");
fCH2d->SetStats(0);
fCH2d->Sumw2();
}
//////////////////////////////////////////////////////////////////////////////////
// Set relative scale
/////////////////////////////////////////////////////////////////////////////////
//_____________________________________________________________________________
void AliTRDCalibraFillHisto::SetRelativeScale(Float_t RelativeScale)
{
//
// Set the factor that will divide the deposited charge
// to fit in the histo range [0,fRangeHistoCharge]
//
if (RelativeScale > 0.0) {
fRelativeScale = RelativeScale;
}
else {
AliInfo("RelativeScale must be strict positif!");
}
}
//////////////////////////////////////////////////////////////////////////////////
// Quick way to fill a histo
//////////////////////////////////////////////////////////////////////////////////
//_____________________________________________________________________
void AliTRDCalibraFillHisto::FillCH2d(Int_t x, Float_t y)
{
//
// FillCH2d: Marian style
// RS: DON'T use Mariany style, such histo is unmergable
//
//skip simply the value out of range
if((y>=fRangeHistoCharge) || (y<0.0)) return;
if(fRangeHistoCharge < 0.0) return;
fCH2d->Fill(y,x); // RS
/*
//Calcul the y place
Int_t yplace = (Int_t) (fNumberBinCharge*y/fRangeHistoCharge)+1;
Int_t place = (fNumberBinCharge+2)*(x+1)+yplace;
//Fill
fCH2d->GetArray()[place]++;
*/
}
//////////////////////////////////////////////////////////////////////////////////
// Geometrical functions
///////////////////////////////////////////////////////////////////////////////////
//_____________________________________________________________________________
Int_t AliTRDCalibraFillHisto::GetLayer(Int_t d) const
{
//
// Reconstruct the layer number from the detector number
//
return ((Int_t) (d % 6));
}
//_____________________________________________________________________________
Int_t AliTRDCalibraFillHisto::GetStack(Int_t d) const
{
//
// Reconstruct the stack number from the detector number
//
const Int_t kNlayer = 6;
return ((Int_t) (d % 30) / kNlayer);
}
//_____________________________________________________________________________
Int_t AliTRDCalibraFillHisto::GetSector(Int_t d) const
{
//
// Reconstruct the sector number from the detector number
//
Int_t fg = 30;
return ((Int_t) (d / fg));
}
///////////////////////////////////////////////////////////////////////////////////
// Getter functions for DAQ of the CH2d and the PH2d
//////////////////////////////////////////////////////////////////////////////////
//_____________________________________________________________________
TProfile2D* AliTRDCalibraFillHisto::GetPH2d(Int_t nbtimebin, Float_t samplefrequency)
{
//
// return pointer to fPH2d TProfile2D
// create a new TProfile2D if it doesn't exist allready
//
if ( fPH2d )
return fPH2d;
// Some parameters
fTimeMax = nbtimebin;
fSf = samplefrequency;
CreatePH2d(540);
return fPH2d;
}
//_____________________________________________________________________
TH2I* AliTRDCalibraFillHisto::GetCH2d()
{
//
// return pointer to fCH2d TH2I
// create a new TH2I if it doesn't exist allready
//
if ( fCH2d )
return fCH2d;
CreateCH2d(540);
return fCH2d;
}
////////////////////////////////////////////////////////////////////////////////////////////
// Drift velocity calibration
///////////////////////////////////////////////////////////////////////////////////////////
//_____________________________________________________________________
TLinearFitter* AliTRDCalibraFillHisto::GetLinearFitter(Int_t detector, Bool_t force)
{
//
// return pointer to TLinearFitter Calibration
// if force is true create a new TLinearFitter if it doesn't exist allready
//
if ((!force) || (fLinearFitterArray.UncheckedAt(detector))){
return (TLinearFitter*)fLinearFitterArray.UncheckedAt(detector);
}
// if we are forced and TLinearFitter doesn't yet exist create it
// new TLinearFitter
TLinearFitter *linearfitter = new TLinearFitter(2,"pol1");
fLinearFitterArray.AddAt(linearfitter,detector);
return linearfitter;
}
//____________________________________________________________________________
void AliTRDCalibraFillHisto::AnalyseLinearFitter()
{
//
// Analyse array of linear fitter because can not be written
// Store two arrays: one with the param the other one with the error param + number of entries
//
for(Int_t k = 0; k < 540; k++){
TLinearFitter *linearfitter = GetLinearFitter(k);
if((linearfitter!=0) && (fEntriesLinearFitter[k]>10)){
TVectorD *par = new TVectorD(2);
TVectorD pare = TVectorD(2);
TVectorD *parE = new TVectorD(3);
if((linearfitter->EvalRobust(0.8)==0)) {
//linearfitter->Eval();
linearfitter->GetParameters(*par);
//linearfitter->GetErrors(pare);
//Float_t ppointError = TMath::Sqrt(TMath::Abs(linearfitter->GetChisquare())/fEntriesLinearFitter[k]);
//(*parE)[0] = pare[0]*ppointError;
//(*parE)[1] = pare[1]*ppointError;
(*parE)[0] = 0.0;
(*parE)[1] = 0.0;
(*parE)[2] = (Double_t) fEntriesLinearFitter[k];
((TObjArray *)fLinearVdriftFit->GetPArray())->AddAt(par,k);
((TObjArray *)fLinearVdriftFit->GetEArray())->AddAt(parE,k);
}
}
}
}
| 31.29337 | 175 | 0.598661 | [
"object",
"shape",
"vector",
"transform"
] |
58882c551fd569ae0c34947a9f2b108d7b884963 | 5,396 | cpp | C++ | master/geometrize-master/geometrize-master/geometrize/script/bindings/bindingswrapper.cpp | AlexRogalskiy/DevArtifacts | 931aabb8cbf27656151c54856eb2ea7d1153203a | [
"MIT"
] | 4 | 2018-09-07T15:35:24.000Z | 2019-03-27T09:48:12.000Z | master/geometrize-master/geometrize-master/geometrize/script/bindings/bindingswrapper.cpp | AlexRogalskiy/DevArtifacts | 931aabb8cbf27656151c54856eb2ea7d1153203a | [
"MIT"
] | 371 | 2020-03-04T21:51:56.000Z | 2022-03-31T20:59:11.000Z | master/geometrize-master/geometrize-master/geometrize/script/bindings/bindingswrapper.cpp | AlexRogalskiy/DevArtifacts | 931aabb8cbf27656151c54856eb2ea7d1153203a | [
"MIT"
] | 3 | 2019-06-18T19:57:17.000Z | 2020-11-06T03:55:08.000Z | #include "bindingswrapper.h"
#include <cassert>
#include <QString>
#include "common/formatsupport.h"
#include "common/searchpaths.h"
#include "common/util.h"
#include "exporter/gifexporter.h"
#include "localization/localization.h"
#include "task/taskutil.h"
namespace geometrize
{
namespace script
{
namespace bindings
{
std::string getApplicationDirectoryPath()
{
return geometrize::searchpaths::getApplicationDirectoryPath();
}
void printToConsole(const std::string& str)
{
geometrize::util::printToConsole(str);
}
void messageBox(const std::string& str)
{
geometrize::util::messageBox(str);
}
void debugBreak()
{
geometrize::util::debugBreak();
}
bool fileExists(const std::string& filePath)
{
return geometrize::util::fileExists(filePath);
}
bool directoryExists(const std::string& dirPath)
{
return geometrize::util::directoryExists(dirPath);
}
bool directoryContainsFile(const std::string& dirPath, const std::string& fileName)
{
return geometrize::util::directoryContainsFile(dirPath, fileName);
}
std::string readFileAsString(const std::string& filePath)
{
return geometrize::util::readFileAsString(filePath);
}
std::vector<std::string> getFilePathsForDirectory(const std::string& dirPath)
{
return geometrize::util::getFilePathsForDirectory(dirPath);
}
std::vector<std::string> getScriptSearchPaths()
{
return geometrize::searchpaths::getScriptSearchPaths();
}
std::vector<std::string> getTemplateSearchPaths()
{
return geometrize::searchpaths::getTemplateSearchPaths();
}
std::string getFirstFileWithExtension(const std::string& dirPath, const std::string& extension)
{
return geometrize::util::getFirstFileWithExtension(dirPath, extension);
}
std::string getFirstFileWithExtensions(const std::string& dirPath, const std::vector<std::string>& extensions)
{
return geometrize::util::getFirstFileWithExtensions(dirPath, extensions);
}
std::vector<std::string> getFilesWithExtensions(const std::string& dirPath, const std::vector<std::string>& extensions)
{
std::vector<std::string> files;
for(const std::string& extension : extensions) {
// TODO
}
return files;
}
std::vector<std::string> getFilesWithExtension(const std::string& dirPath, const std::string& extension)
{
return getFilesWithExtensions(dirPath, { extension });
}
std::vector<std::string> getSupportedImageFileExtensions()
{
return geometrize::format::getReadableImageFileExtensions(false);
}
std::vector<std::string> getScriptsForPath(const std::string& dirPath)
{
return geometrize::util::getScriptsForPath(dirPath);
}
void openTask(const std::string& url, const bool addToRecents)
{
// Horrible workaround because QUrl doesn't handle Qt resource file prefixes well
// See: https://forum.qt.io/topic/1494/universal-solution-for-resource-prefix
// Note this breaks QUrl validation too (QUrl isValid chokes when given this modified url)
QString qUrl{QString::fromStdString(url)};
const QString strToReplace{":/"};
if(qUrl.startsWith(strToReplace)) {
qUrl.replace(0, strToReplace.size(), "qrc:///");
}
geometrize::util::openTasks(QStringList(QString::fromStdString(url)), addToRecents);
}
bool openInDefaultApplication(const std::string& path)
{
return geometrize::util::openInDefaultApplication(path);
}
bool revealInDefaultApplication(const std::string& path)
{
return geometrize::util::revealInDefaultApplication(path);
}
void clearGlobalClipboard()
{
geometrize::util::clearGlobalClipboard();
}
std::string getGlobalClipboardText()
{
return geometrize::util::getGlobalClipboardText();
}
void setGlobalClipboardText(const std::string& text)
{
geometrize::util::setGlobalClipboardText(text);
}
bool stringBeginsWith(const std::string& str, const std::string& prefix)
{
return geometrize::util::stringBeginsWith(str, prefix);
}
bool stringEndsWith(const std::string& str, const std::string& suffix)
{
return geometrize::util::stringEndsWith(str, suffix);
}
std::string getAppDataLocation()
{
return geometrize::util::getAppDataLocation();
}
bool writeStringToFile(const std::string& str, const std::string& path)
{
return geometrize::util::writeStringToFile(str, path);
}
std::string percentEncode(const std::string& str)
{
return geometrize::util::percentEncode(str);
}
int randomInRange(const int lower, const int upper)
{
return geometrize::util::randomInRange(lower, upper);
}
int clamp(const int value, const int lower, const int upper)
{
return geometrize::util::clamp(value, lower, upper);
}
std::vector<std::string> split(const std::string& s, const char delimiter)
{
return geometrize::util::split(s, delimiter);
}
void setTranslatorsForLocale(const std::string& locale)
{
geometrize::setTranslatorsForLocale(QString::fromStdString(locale));
}
bool exportGIF(const std::vector<geometrize::ShapeResult>& data,
const std::uint32_t inputWidth,
const std::uint32_t inputHeight,
const std::uint32_t outputWidth,
const std::uint32_t outputHeight,
const std::size_t frameSkip,
const std::string& filePath)
{
return geometrize::exporter::exportGIF(data, inputWidth, inputHeight, outputWidth, outputHeight, [frameSkip](std::size_t frameIndex) {
return frameSkip == 0U ? false : (frameIndex % frameSkip == 0);
}, filePath);
}
}
}
}
| 24.981481 | 138 | 0.735545 | [
"vector"
] |
58912d7fe36ec685282923345baaeb5f29d2ce03 | 3,497 | cpp | C++ | SerialPrograms/Source/PokemonLA/Inference/PokemonLA_SelectedRegionDetector.cpp | BlizzardHero/Arduino-Source | bc4ce6433651b0feef488735098900f8bf4144f8 | [
"MIT"
] | null | null | null | SerialPrograms/Source/PokemonLA/Inference/PokemonLA_SelectedRegionDetector.cpp | BlizzardHero/Arduino-Source | bc4ce6433651b0feef488735098900f8bf4144f8 | [
"MIT"
] | null | null | null | SerialPrograms/Source/PokemonLA/Inference/PokemonLA_SelectedRegionDetector.cpp | BlizzardHero/Arduino-Source | bc4ce6433651b0feef488735098900f8bf4144f8 | [
"MIT"
] | null | null | null | /* Selected Region Detector
*
* From: https://github.com/PokemonAutomation/Arduino-Source
*
*/
#include <QImage>
#include "CommonFramework/ImageMatch/ImageDiff.h"
#include "CommonFramework/InferenceInfra/InferenceRoutines.h"
#include "CommonFramework/Tools/VideoOverlaySet.h"
#include "PokemonLA_SelectedRegionDetector.h"
namespace PokemonAutomation{
namespace NintendoSwitch{
namespace PokemonLA{
const char* MAP_REGION_NAMES[] = {
"None",
"Jubilife Village",
"Obsidian Fieldlands",
"Crimson Mirelands",
"Cobalt Coastlands",
"Coronet Highlands",
"Alabaster Islands",
"Ancient Retreat",
};
class MapLocationDetector : public VisualInferenceCallback{
public:
MapLocationDetector(const QImage& screen)
: VisualInferenceCallback("MapLocationDetector")
, m_current_region(MapRegion::NONE)
{
m_regions.emplace_back(MapRegion::JUBILIFE, ImageFloatBox(0.252, 0.400, 0.025, 0.150), screen);
m_regions.emplace_back(MapRegion::FIELDLANDS, ImageFloatBox(0.415, 0.550, 0.025, 0.150), screen);
m_regions.emplace_back(MapRegion::MIRELANDS, ImageFloatBox(0.750, 0.570, 0.025, 0.150), screen);
m_regions.emplace_back(MapRegion::COASTLANDS, ImageFloatBox(0.865, 0.240, 0.025, 0.150), screen);
m_regions.emplace_back(MapRegion::HIGHLANDS, ImageFloatBox(0.508, 0.320, 0.025, 0.150), screen);
m_regions.emplace_back(MapRegion::ICELANDS, ImageFloatBox(0.457, 0.060, 0.025, 0.150), screen);
m_regions.emplace_back(MapRegion::RETREAT, ImageFloatBox(0.635, 0.285, 0.025, 0.150), screen);
}
MapRegion current_region() const{
return m_current_region;
}
virtual void make_overlays(VideoOverlaySet& items) const override{
// for (const RegionState& region : m_regions){
// items.add(COLOR_CYAN, region.box);
// }
}
virtual bool process_frame(
const QImage& frame,
std::chrono::system_clock::time_point timestamp
) override{
if (frame.isNull()){
return false;
}
for (RegionState& region : m_regions){
QImage current = extract_box(frame, region.box);
if (current.size() != region.start.size()){
region.start = current;
continue;
}
double rmsd = ImageMatch::pixel_RMSD(region.start, current);
if (rmsd > 20){
m_current_region = region.region;
return true;
}
}
return false;
}
private:
struct RegionState{
MapRegion region;
ImageFloatBox box;
QImage start;
RegionState(MapRegion p_region, const ImageFloatBox& p_box, const QImage& screen)
: region(p_region)
, box(p_box)
, start(extract_box(screen, box))
{}
};
std::vector<RegionState> m_regions;
MapRegion m_current_region;
};
MapRegion detect_selected_region(ProgramEnvironment& env, ConsoleHandle& console){
MapLocationDetector detector(console.video().snapshot());
int ret = wait_until(
env, console,
std::chrono::seconds(2),
{ &detector }
);
MapRegion region = detector.current_region();
if (ret < 0){
console.log("Unable to detect active region on map.", COLOR_RED);
}else{
console.log(std::string("Current Selection: ") + MAP_REGION_NAMES[(int)region]);
}
return region;
}
}
}
}
| 29.635593 | 107 | 0.637975 | [
"vector"
] |
58921ee8856074d640897c409204dce9447f790a | 1,460 | cpp | C++ | src/0297.cpp | downdemo/LeetCode-Solutions-in-Cpp17 | e6ad1bd56ecea08fc418a9b50e78bdac23860e9f | [
"MIT"
] | 38 | 2020-03-05T06:38:32.000Z | 2022-03-11T02:32:14.000Z | src/0297.cpp | downdemo/LeetCode-Solutions-in-Cpp17 | e6ad1bd56ecea08fc418a9b50e78bdac23860e9f | [
"MIT"
] | null | null | null | src/0297.cpp | downdemo/LeetCode-Solutions-in-Cpp17 | e6ad1bd56ecea08fc418a9b50e78bdac23860e9f | [
"MIT"
] | 16 | 2020-04-02T15:13:20.000Z | 2022-02-25T07:34:35.000Z | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if (!root) {
return "";
}
queue<TreeNode*> q;
q.emplace(root);
stringstream ss;
while (!empty(q)) {
TreeNode* t = q.front();
q.pop();
if (t) {
ss << t->val << " ";
q.emplace(t->left);
q.emplace(t->right);
} else {
ss << "# ";
}
}
return ss.str();
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if (empty(data)) {
return nullptr;
}
stringstream ss{data};
string s;
ss >> s;
TreeNode* root = new TreeNode(stoi(s));
queue<TreeNode*> q;
q.emplace(root);
while (!empty(q)) {
TreeNode* t = q.front();
q.pop();
ss >> s;
if (s == "#") {
t->left = nullptr;
} else {
t->left = new TreeNode(stoi(s));
q.emplace(t->left);
}
ss >> s;
if (s == "#") {
t->right = nullptr;
} else {
t->right = new TreeNode(stoi(s));
q.emplace(t->right);
}
}
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
| 20.857143 | 61 | 0.493836 | [
"object"
] |
589333fe07160848277864de749f1b25c6654331 | 3,857 | cpp | C++ | www/snapper/engine/providers/StorageController.cpp | lenovo/Snapper | 4300739bbdf0b101c7ddd8be09c89f582bf47202 | [
"BSD-3-Clause"
] | 4 | 2019-09-04T23:49:58.000Z | 2020-08-05T05:46:49.000Z | www/snapper/engine/providers/StorageController.cpp | lenovo/Snapper | 4300739bbdf0b101c7ddd8be09c89f582bf47202 | [
"BSD-3-Clause"
] | 1 | 2019-09-24T20:42:29.000Z | 2019-09-25T00:28:19.000Z | www/snapper/engine/providers/StorageController.cpp | lenovo/Snapper | 4300739bbdf0b101c7ddd8be09c89f582bf47202 | [
"BSD-3-Clause"
] | null | null | null | //---------------------------------------------------------------------
// <copyright file="PowerControl.cpp" company="Lenovo">
// Copyright (c) 2018-present, Lenovo. All rights reserved. Licensed under BSD, see COPYING.BSD file for details.
// </copyright>
//---------------------------------------------------------------------
#include "class/StorageController.h"
#include "class/ClassNames.h"
#include <www/engine/rf_debug.h>
#include <www/engine/topology.h>
namespace snapper { namespace providers
{
std::shared_ptr<memid_acckey_map> StorageController::getlist_memid_acckey(std::string containing_path)
{
std::shared_ptr<memid_acckey_map> list = std::make_shared<memid_acckey_map>();
bson::BSONObj dataobjs;
std::string relpath = containing_path.substr(0, containing_path.find(" "));
DataInterfaceMgr::mockupGetData(relpath, dataobjs);
std::vector<bson::BSONElement> pctls = BE_Array(dataobjs.getField("StorageControllers"));
for(int i = 0; i < pctls.size(); i++)
{
bson::BSONObj p = pctls[i].Obj();
string name = p.getStringField("MemberId");
(*list)[name] = std::string(name)+"@"+get_name();
}
return list;
}
int StorageController::autoexpand_array(bson::BSONArrayBuilder* a, std::string containing_path, std::shared_ptr<bson::BSONObj> q_param )
{
bson::BSONObj dataobjs;
std::string relpath = containing_path.substr(0, containing_path.find(" "));// from parent /redfish/v1/Chassis/1/Power
DataInterfaceMgr::mockupGetData(relpath, dataobjs);
std::cout << "auto expand Scontroller ..... " << containing_path << std::endl;
std::vector<bson::BSONElement> scs = BE_Array(dataobjs.getField("StorageControllers"));
for(int i = 0; i < scs.size(); i++)
{
bson::BSONObj p = scs[i].Obj();
setobj("MemberId", MAKE_BSON_OBJ("MemberId", p.getStringField("MemberId")));
setobj("Name", MAKE_BSON_OBJ("Name", p.getStringField("Name")));
setobj("Manufacturer", MAKE_BSON_OBJ("Manufacturer", p.getStringField("Manufacturer")));
setobj("Model", MAKE_BSON_OBJ("Model", p.getStringField("Model")));
setobj("PartNumber", MAKE_BSON_OBJ("PartNumber", p.getStringField("PartNumber")));
setobj("SerialNumber", MAKE_BSON_OBJ("SerialNumber", p.getStringField("SerialNumber")));
setobj("FirmwareVersion", MAKE_BSON_OBJ("FirmwareVersion", p.getStringField("FirmwareVersion")));
bson::BSONElement e = p.getField("Identifiers");
if(e.eoo() != true)
{
bson::BSONObjBuilder t;
t.append(e);
if(strlen(e.fieldName()))
setobj(e.fieldName(), std::make_shared<bson::BSONObj>(t.obj()) );
}
set_status_obj(MAKE_ENUM_STRING(State_Enabled), MAKE_ENUM_STRING(Health_OK), MAKE_ENUM_STRING(Health_OK));
SnapperProvider::auto_build_objects_ResGET(containing_path);
bson::BSONObj o = ::bson::fromjson(serialize_objs());
a->append(o);
reset_obj();
}
return RFRC_SUCCESS;
}
int StorageController::handle_get(shared_ptr<::snapper::service::request_context> request)
{
return RFRC_METHOD_NOT_ALLOWED;
}
int StorageController::handle_post(shared_ptr<::snapper::service::request_context> request)
{
return RFRC_METHOD_NOT_ALLOWED;
}
int StorageController::handle_patch(shared_ptr<::snapper::service::request_context> request)
{
return RFRC_METHOD_NOT_ALLOWED;
}
int StorageController::handle_put(shared_ptr<::snapper::service::request_context> request)
{
return RFRC_METHOD_NOT_ALLOWED;
}
int StorageController::handle_delete(shared_ptr<::snapper::service::request_context> request)
{
return RFRC_METHOD_NOT_ALLOWED;
}
REGISTER_PROVIDER(StorageController);
}}
| 35.712963 | 137 | 0.649987 | [
"vector",
"model"
] |
5895b313b463c50f65c07e6cb6288440af7f4bda | 7,186 | cpp | C++ | trajeclike.cpp | ihh/trajectory-likelihood | 3064f9acd6cb5d7a85129053415530f339c2a255 | [
"MIT"
] | 11 | 2020-03-28T09:03:53.000Z | 2021-04-30T23:59:59.000Z | trajeclike.cpp | ihh/trajectory-likelihood | 3064f9acd6cb5d7a85129053415530f339c2a255 | [
"MIT"
] | 1 | 2020-06-15T10:51:40.000Z | 2020-06-20T15:20:12.000Z | trajeclike.cpp | ihh/trajectory-likelihood | 3064f9acd6cb5d7a85129053415530f339c2a255 | [
"MIT"
] | null | null | null | #include <chrono>
#include <iostream>
#include <boost/program_options.hpp>
#include "trajec.h"
#include "simulate.h"
#include "moments.h"
#include "cim.h"
#include "tkf.h"
using namespace TrajectoryLikelihood;
using namespace std;
namespace po = boost::program_options;
int main (int argc, char** argv) {
po::options_description opts ("Options");
opts.add_options()
("help,h", "display this help message")
("verbose,v", po::value<int>()->default_value(0), "logging verbosity")
("lambda,L", po::value<double>(), "insertion rate (default is same as mu)")
("mu,M", po::value<double>()->default_value(.049), "deletion rate")
("x,X", po::value<double>(), "insertion extension probability (default is same as y)")
("y,Y", po::value<double>()->default_value(.543), "deletion extension probability")
("time,t", po::value<double>()->default_value(1), "time parameter")
("maxevents,E", po::value<int>()->default_value(3), "max # of indel events in trajectory")
("maxlen,l", po::value<int>()->default_value(10), "max length of chop zone")
("benchmark,b", "perform time benchmark instead of likelihood calculation")
("simulate,s", "perform stochastic simulation instead of likelihood calculation")
("counts,c", "report simulation counts instead of probabilities")
("initlen,i", po::value<int>()->default_value(1000), "initial sequence length for simulation")
("trials,n", po::value<int>()->default_value(100000), "number of simulation trials")
("moments,m", "use method of moments (Holmes 2020) for likelihood calculations")
("cim,C", "use De Maio 2020 Cumulative Indel Model for likelihood calculations")
("tkf91", "use TKF91 Pair HMM for likelihood calculations")
("tkf92", "use TKF92 Pair HMM for likelihood calculations")
("rs07", "use RS07 Pair HMM for likelihood calculations")
("prank", "use PRANK Pair HMM for likelihood calculations")
("dt,D", po::value<double>()->default_value(.01), "time step for numerical integration")
("seed,d", po::value<unsigned long long>()->default_value(mt19937::default_seed), "seed for random number generator")
("seedtime,T", "use current time as a seed");
po::variables_map vm;
po::parsed_options parsed = po::command_line_parser(argc,argv).options(opts).run();
po::store (parsed, vm);
po::notify(vm);
if (vm.count("help")) {
cout << opts << endl;
return EXIT_SUCCESS;
}
// logging
const int verbose = vm.at("verbose").as<int>();
// get General Geometric Indel Model params (De Maio 2020; Holmes 2020)
const double mu_ggi = vm.at("mu").as<double>();
const double lambda_ggi = vm.count("lambda") ? vm.at("lambda").as<double>() : mu_ggi;
const double rDel = vm.at("y").as<double>();
const double rIns = vm.count("x") ? vm.at("x").as<double>() : rDel;
// convert params to Long Indel Model scaling (Miklos, Lunter & Holmes 2004)
const double mu_li = mu_ggi / (1. - rDel);
const double gamma_li = (lambda_ggi * (1. - rIns)) / (mu_ggi * (1. - rDel));
const IndelParams params (gamma_li, mu_li, rDel, rIns);
if (verbose) {
// log params in GGI format
cerr << "mu_GGI=" << params.totalRightwardDeletionRatePerSite() << " lambda_GGI=" << params.totalInsertionRatePerSite() << " x=" << params.rIns << " y=" << params.rDel << endl;
}
// get remaining params
const double t = vm.at("time").as<double>();
const bool reportCounts = vm.count("simulate") && vm.count("counts");
const int maxLen = vm.at("maxlen").as<int>();
const double dt = vm.at("dt").as<double>();
vector<vector<double> > probs;
if (vm.count("benchmark")) {
const int E = vm.at("maxevents").as<int>();
cout << "chopZoneLength meanTime/uS error" << endl;
const int trials = vm.at("trials").as<int>();
for (int L = 1; L <= maxLen; ++L) {
double tSum = 0, tSum2 = 0;
for (int n = 0; n < trials; ++n) {
const auto tStart = std::chrono::system_clock::now();
const ChopZoneConfig config (E, L, verbose);
(void) chopZoneLikelihoods (params, t, config);
const auto tEnd = std::chrono::system_clock::now();
const double t = std::chrono::duration_cast< std::chrono::microseconds >(tEnd - tStart).count();
tSum += t;
tSum2 += t*t;
}
const double tMean = tSum / (double) trials, t2Mean = tSum2 / (double) trials;
cout << L << " " << tMean << " " << sqrt ((t2Mean - tMean*tMean) / (double) trials) << endl;
}
} else {
if (vm.count("simulate")) {
const SimulationConfig config (vm.at("initlen").as<int>(), maxLen, vm.at("trials").as<int>(), verbose);
const bool useClock = vm.count("seedtime");
unsigned long long seed;
if (useClock)
seed = std::chrono::duration_cast< std::chrono::milliseconds >(std::chrono::system_clock::now().time_since_epoch()).count();
else
seed = vm.at("seed").as<unsigned long long>();
cerr << "Random number seed: " << seed << endl;
mt19937 rnd (seed);
probs = chopZoneSimulatedProbabilities (params, t, config, rnd, reportCounts);
} else if (vm.count("moments")) {
const Moments moments (params, t, dt, verbose);
probs = moments.chopZoneLikelihoods (maxLen);
} else if (vm.count("cim")) {
const CumulativeIndelModel cim (params, t, dt, verbose);
probs = cim.chopZoneLikelihoods (maxLen);
} else if (vm.count("tkf91")) {
const TKF91 tkf91 (params, t, verbose);
probs = tkf91.chopZoneLikelihoods (maxLen);
} else if (vm.count("tkf92")) {
const TKF92 tkf92 (params, t, verbose);
probs = tkf92.chopZoneLikelihoods (maxLen);
} else if (vm.count("prank")) {
const PRANK prank (params, t, verbose);
probs = prank.chopZoneLikelihoods (maxLen);
} else if (vm.count("rs07")) {
const RS07 rs07 (params, t, verbose);
probs = rs07.chopZoneLikelihoods (maxLen);
} else {
const ChopZoneConfig config (vm.at("maxevents").as<int>(), maxLen, verbose);
probs = chopZoneLikelihoods (params, t, config);
}
double total = 0;
for (const auto& pd: probs) {
for (double p: pd)
total += p;
cout << to_string_join (pd) << endl;
}
if (verbose) {
cerr << "Entry in row i, column j is " << (reportCounts ? "count" : "probability") << " of inserting i residues and deleting j residues before the next match" << endl;
if (reportCounts)
cerr << "Final count represents overflow (chop zones that were larger than size limit)" << endl;
cerr << "Total: " << total << endl;
if (!vm.count("counts")) {
double ei = 0, ed = 0, ei2 = 0, ed2 = 0, eid = 0, pi0 = 0, pd0 = 0;
for (int i = 0; i < probs.size(); ++i)
for (int d = 0; d < probs[i].size(); ++d) {
const double p = probs[i][d];
ei += i * p;
ed += d * p;
ei2 += i * i * p;
ed2 += d * d * p;
eid += i * d * p;
if (i == 0)
pi0 += p;
if (d == 0)
pd0 += p;
}
cerr << "E[#ins]=" << ei << " E[#del]=" << ed
<< " E[#ins^2]=" << ei2 << " E[#del^2]=" << ed2
<< " V[#ins]=" << (ei2 - ei*ei) << " V[#del]=" << (ed2 - ed*ed)
<< " E[#ins*#del]=" << eid
<< " Cov(#ins,#del)=" << (eid-ei*ed)
<< endl;
}
}
}
return EXIT_SUCCESS;
}
| 42.270588 | 182 | 0.616476 | [
"vector",
"model"
] |
58a8dbdb03195cb4c331555f4c459fc6e0ebc313 | 689 | cpp | C++ | geometry/test/convex_hull.test.cpp | ankit6776/cplib-cpp | b9f8927a6c7301374c470856828aa1f5667d967b | [
"MIT"
] | 20 | 2021-06-21T00:18:54.000Z | 2022-03-17T17:45:44.000Z | geometry/test/convex_hull.test.cpp | ankit6776/cplib-cpp | b9f8927a6c7301374c470856828aa1f5667d967b | [
"MIT"
] | 56 | 2021-06-03T14:42:13.000Z | 2022-03-26T14:15:30.000Z | geometry/test/convex_hull.test.cpp | ankit6776/cplib-cpp | b9f8927a6c7301374c470856828aa1f5667d967b | [
"MIT"
] | 3 | 2019-12-11T06:45:45.000Z | 2020-09-07T13:45:32.000Z | #include "../geometry.hpp"
#define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_4_A"
#include <cmath>
#include <cstdio>
#include <iostream>
using namespace std;
int main() {
int N;
cin >> N;
vector<Point2d<double>> P(N);
P[0].set_eps(1e-9);
for (auto &p : P) cin >> p;
vector<pair<int, int>> ps;
for (auto idx : convex_hull(P, true)) ps.emplace_back(llround(P[idx].y), llround(P[idx].x));
int init = min_element(ps.begin(), ps.end()) - ps.begin();
printf("%lu\n", ps.size());
for (size_t i = 0; i < ps.size(); i++) {
printf("%d %d\n", ps[(i + init) % ps.size()].second, ps[(i + init) % ps.size()].first);
}
}
| 28.708333 | 96 | 0.580552 | [
"geometry",
"vector"
] |
58b0bd56bc5acea077a2bdb6016688cb081546c2 | 7,663 | cc | C++ | third_party/blink/renderer/core/html/parser/text_resource_decoder_builder.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | third_party/blink/renderer/core/html/parser/text_resource_decoder_builder.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | third_party/blink/renderer/core/html/parser/text_resource_decoder_builder.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | /*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. 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
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "third_party/blink/renderer/core/html/parser/text_resource_decoder_builder.h"
#include <memory>
#include "base/cxx17_backports.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/platform/network/mime/mime_type_registry.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
namespace blink {
static inline bool CanReferToParentFrameEncoding(
const LocalFrame* frame,
const LocalFrame* parent_frame) {
return parent_frame &&
parent_frame->DomWindow()->GetSecurityOrigin()->CanAccess(
frame->DomWindow()->GetSecurityOrigin());
}
namespace {
struct LegacyEncoding {
const char* domain;
const char* encoding;
};
static const LegacyEncoding kEncodings[] = {
{"au", "windows-1252"}, {"az", "ISO-8859-9"}, {"bd", "windows-1252"},
{"bg", "windows-1251"}, {"br", "windows-1252"}, {"ca", "windows-1252"},
{"ch", "windows-1252"}, {"cn", "GBK"}, {"cz", "windows-1250"},
{"de", "windows-1252"}, {"dk", "windows-1252"}, {"ee", "windows-1256"},
{"eg", "windows-1257"}, {"et", "windows-1252"}, {"fi", "windows-1252"},
{"fr", "windows-1252"}, {"gb", "windows-1252"}, {"gr", "ISO-8859-7"},
{"hk", "Big5"}, {"hr", "windows-1250"}, {"hu", "ISO-8859-2"},
{"il", "windows-1255"}, {"ir", "windows-1257"}, {"is", "windows-1252"},
{"it", "windows-1252"}, {"jp", "Shift_JIS"}, {"kr", "windows-949"},
{"lt", "windows-1256"}, {"lv", "windows-1256"}, {"mk", "windows-1251"},
{"nl", "windows-1252"}, {"no", "windows-1252"}, {"pl", "ISO-8859-2"},
{"pt", "windows-1252"}, {"ro", "ISO-8859-2"}, {"rs", "windows-1251"},
{"ru", "windows-1251"}, {"se", "windows-1252"}, {"si", "ISO-8859-2"},
{"sk", "windows-1250"}, {"th", "windows-874"}, {"tr", "ISO-8859-9"},
{"tw", "Big5"}, {"tz", "windows-1252"}, {"ua", "windows-1251"},
{"us", "windows-1252"}, {"vn", "windows-1258"}, {"xa", "windows-1252"},
{"xb", "windows-1257"}};
static const WTF::TextEncoding GetEncodingFromDomain(const KURL& url) {
Vector<String> tokens;
url.Host().Split(".", tokens);
if (!tokens.IsEmpty()) {
auto tld = tokens.back();
for (size_t i = 0; i < base::size(kEncodings); i++) {
if (tld == kEncodings[i].domain)
return WTF::TextEncoding(kEncodings[i].encoding);
}
}
return WTF::TextEncoding();
}
TextResourceDecoderOptions::ContentType DetermineContentType(
const String& mime_type) {
if (EqualIgnoringASCIICase(mime_type, "text/css"))
return TextResourceDecoderOptions::kCSSContent;
if (EqualIgnoringASCIICase(mime_type, "text/html"))
return TextResourceDecoderOptions::kHTMLContent;
if (MIMETypeRegistry::IsXMLMIMEType(mime_type))
return TextResourceDecoderOptions::kXMLContent;
return TextResourceDecoderOptions::kPlainTextContent;
}
} // namespace
std::unique_ptr<TextResourceDecoder> BuildTextResourceDecoderFor(
Document* document,
const AtomicString& mime_type,
const AtomicString& encoding) {
const WTF::TextEncoding encoding_from_domain =
GetEncodingFromDomain(document->Url());
LocalFrame* frame = document->GetFrame();
LocalFrame* parent_frame = nullptr;
if (frame)
parent_frame = DynamicTo<LocalFrame>(frame->Tree().Parent());
// Set the hint encoding to the parent frame encoding only if the parent and
// the current frames share the security origin. We impose this condition
// because somebody can make a child frameg63 containing a carefully crafted
// html/javascript in one encoding that can be mistaken for hintEncoding (or
// related encoding) by an auto detector. When interpreted in the latter, it
// could be an attack vector.
// FIXME: This might be too cautious for non-7bit-encodings and we may
// consider relaxing this later after testing.
bool use_hint_encoding =
frame && CanReferToParentFrameEncoding(frame, parent_frame);
std::unique_ptr<TextResourceDecoder> decoder;
if (frame && frame->GetSettings()) {
const WTF::TextEncoding default_encoding =
encoding_from_domain.IsValid()
? encoding_from_domain
: WTF::TextEncoding(
frame->GetSettings()->GetDefaultTextEncodingName());
// Disable autodetection for XML/JSON to honor the default encoding (UTF-8)
// for unlabelled documents.
if (MIMETypeRegistry::IsXMLMIMEType(mime_type)) {
decoder =
std::make_unique<TextResourceDecoder>(TextResourceDecoderOptions(
TextResourceDecoderOptions::kXMLContent, default_encoding));
use_hint_encoding = false;
} else if (MIMETypeRegistry::IsJSONMimeType(mime_type)) {
decoder =
std::make_unique<TextResourceDecoder>(TextResourceDecoderOptions(
TextResourceDecoderOptions::kJSONContent, default_encoding));
use_hint_encoding = false;
} else {
WTF::TextEncoding hint_encoding;
if (use_hint_encoding &&
parent_frame->GetDocument()->EncodingWasDetectedHeuristically())
hint_encoding = parent_frame->GetDocument()->Encoding();
decoder = std::make_unique<TextResourceDecoder>(
TextResourceDecoderOptions::CreateWithAutoDetection(
DetermineContentType(mime_type), default_encoding, hint_encoding,
document->Url()));
}
} else {
decoder = std::make_unique<TextResourceDecoder>(TextResourceDecoderOptions(
DetermineContentType(mime_type), encoding_from_domain));
}
DCHECK(decoder);
if (!encoding.IsEmpty()) {
decoder->SetEncoding(WTF::TextEncoding(encoding.GetString()),
TextResourceDecoder::kEncodingFromHTTPHeader);
} else if (use_hint_encoding) {
decoder->SetEncoding(parent_frame->GetDocument()->Encoding(),
TextResourceDecoder::kEncodingFromParentFrame);
}
return decoder;
}
} // namespace blink
| 43.788571 | 86 | 0.692157 | [
"vector"
] |
58b978858c2f45518539d8270b4b4c4ccacf4fa7 | 8,379 | cpp | C++ | src/lib/operators/join_verification.cpp | hyrise-mp/hyrise | cefb5fb70dfc0a6e43f35d7dd098d7ac703d4602 | [
"MIT"
] | 2 | 2019-05-28T12:09:04.000Z | 2019-05-29T08:18:43.000Z | src/lib/operators/join_verification.cpp | hyrise-mp/hyrise | cefb5fb70dfc0a6e43f35d7dd098d7ac703d4602 | [
"MIT"
] | 69 | 2019-05-24T10:01:32.000Z | 2019-12-13T19:09:05.000Z | src/lib/operators/join_verification.cpp | hyrise-mp/hyrise | cefb5fb70dfc0a6e43f35d7dd098d7ac703d4602 | [
"MIT"
] | null | null | null | #include "join_verification.hpp"
#include "resolve_type.hpp"
#include "type_comparison.hpp"
namespace {
template <typename T>
std::vector<T> concatenate(const std::vector<T>& l, const std::vector<T>& r) {
auto result = l;
result.insert(result.end(), r.begin(), r.end());
return result;
}
} // namespace
namespace opossum {
bool JoinVerification::supports(JoinMode join_mode, PredicateCondition predicate_condition, DataType left_data_type,
DataType right_data_type, bool secondary_predicates) {
return true;
}
JoinVerification::JoinVerification(const std::shared_ptr<const AbstractOperator>& left,
const std::shared_ptr<const AbstractOperator>& right, const JoinMode mode,
const OperatorJoinPredicate& primary_predicate,
const std::vector<OperatorJoinPredicate>& secondary_predicates)
: AbstractJoinOperator(OperatorType::JoinVerification, left, right, mode, primary_predicate, secondary_predicates) {
}
const std::string JoinVerification::name() const { return "JoinVerification"; }
std::shared_ptr<const Table> JoinVerification::_on_execute() {
const auto output_table = _build_output_table({}, TableType::Data);
const auto left_tuples = input_table_left()->get_rows();
const auto right_tuples = input_table_right()->get_rows();
// Tuples with NULLs used to fill up tuples in outer joins that do not find a match
const auto null_tuple_left = Tuple(input_table_left()->column_count(), NullValue{});
const auto null_tuple_right = Tuple(input_table_right()->column_count(), NullValue{});
switch (_mode) {
case JoinMode::Inner:
for (const auto& left_tuple : left_tuples) {
for (const auto& right_tuple : right_tuples) {
if (_tuples_match(left_tuple, right_tuple)) {
output_table->append(concatenate(left_tuple, right_tuple));
}
}
}
break;
case JoinMode::Left:
for (const auto& left_tuple : left_tuples) {
auto has_match = false;
for (const auto& right_tuple : right_tuples) {
if (_tuples_match(left_tuple, right_tuple)) {
has_match = true;
output_table->append(concatenate(left_tuple, right_tuple));
}
}
if (!has_match) {
output_table->append(concatenate(left_tuple, null_tuple_right));
}
}
break;
case JoinMode::Right:
for (const auto& right_tuple : right_tuples) {
auto has_match = false;
for (const auto& left_tuple : left_tuples) {
if (_tuples_match(left_tuple, right_tuple)) {
has_match = true;
output_table->append(concatenate(left_tuple, right_tuple));
}
}
if (!has_match) {
output_table->append(concatenate(null_tuple_left, right_tuple));
}
}
break;
case JoinMode::FullOuter: {
// Track which tuples from each side have matches
auto left_matches = std::vector<bool>(input_table_left()->row_count(), false);
auto right_matches = std::vector<bool>(input_table_right()->row_count(), false);
for (size_t left_tuple_idx{0}; left_tuple_idx < left_tuples.size(); ++left_tuple_idx) {
const auto& left_tuple = left_tuples[left_tuple_idx];
for (size_t right_tuple_idx{0}; right_tuple_idx < right_tuples.size(); ++right_tuple_idx) {
const auto& right_tuple = right_tuples[right_tuple_idx];
if (_tuples_match(left_tuple, right_tuple)) {
output_table->append(concatenate(left_tuple, right_tuple));
left_matches[left_tuple_idx] = true;
right_matches[right_tuple_idx] = true;
}
}
}
// Add tuples without matches to output table
for (size_t left_tuple_idx{0}; left_tuple_idx < input_table_left()->row_count(); ++left_tuple_idx) {
if (!left_matches[left_tuple_idx]) {
output_table->append(concatenate(left_tuples[left_tuple_idx], null_tuple_right));
}
}
for (size_t right_tuple_idx{0}; right_tuple_idx < input_table_right()->row_count(); ++right_tuple_idx) {
if (!right_matches[right_tuple_idx]) {
output_table->append(concatenate(null_tuple_left, right_tuples[right_tuple_idx]));
}
}
} break;
case JoinMode::Semi: {
for (const auto& left_tuple : left_tuples) {
const auto has_match = std::any_of(right_tuples.begin(), right_tuples.end(), [&](const auto& right_tuple) {
return _tuples_match(left_tuple, right_tuple);
});
if (has_match) {
output_table->append(left_tuple);
}
}
} break;
case JoinMode::AntiNullAsTrue:
case JoinMode::AntiNullAsFalse: {
for (const auto& left_tuple : left_tuples) {
const auto has_no_match = std::none_of(right_tuples.begin(), right_tuples.end(), [&](const auto& right_tuple) {
return _tuples_match(left_tuple, right_tuple);
});
if (has_no_match) {
output_table->append(left_tuple);
}
}
} break;
case JoinMode::Cross:
Fail("Cross join not supported");
break;
}
return output_table;
}
bool JoinVerification::_tuples_match(const Tuple& tuple_left, const Tuple& tuple_right) const {
if (!_evaluate_predicate(_primary_predicate, tuple_left, tuple_right)) {
return false;
}
return std::all_of(_secondary_predicates.begin(), _secondary_predicates.end(), [&](const auto& secondary_predicate) {
return _evaluate_predicate(secondary_predicate, tuple_left, tuple_right);
});
}
bool JoinVerification::_evaluate_predicate(const OperatorJoinPredicate& predicate, const Tuple& tuple_left,
const Tuple& tuple_right) const {
auto result = false;
const auto variant_left = tuple_left[predicate.column_ids.first];
const auto variant_right = tuple_right[predicate.column_ids.second];
if (variant_is_null(variant_left) || variant_is_null(variant_right)) {
// AntiNullAsTrue is the only JoinMode that treats null-booleans as TRUE, all others treat it as FALSE
return _mode == JoinMode::AntiNullAsTrue;
}
resolve_data_type(data_type_from_all_type_variant(variant_left), [&](const auto data_type_left_t) {
using ColumnDataTypeLeft = typename decltype(data_type_left_t)::type;
// Capturing references in nested lambda to avoid GCC bug
// "internal compiler error: in tsubst_copy, at cp/pt.c:15347"
auto& variant_left_1 = variant_left;
auto& variant_right_1 = variant_right;
resolve_data_type(data_type_from_all_type_variant(variant_right), [&](const auto data_type_right_t) {
using ColumnDataTypeRight = typename decltype(data_type_right_t)::type;
// Capturing references in nested lambda to avoid GCC bug
// "internal compiler error: in tsubst_copy, at cp/pt.c:15347"
auto& result_2 = result;
auto& variant_left_2 = variant_left_1;
auto& variant_right_2 = variant_right_1;
if constexpr (std::is_same_v<ColumnDataTypeLeft, pmr_string> == std::is_same_v<ColumnDataTypeRight, pmr_string>) {
// Capturing references in nested lambda to avoid GCC bug
// "internal compiler error: in tsubst_copy, at cp/pt.c:15347"
auto& result_3 = result_2;
auto& variant_left_3 = variant_left_2;
auto& variant_right_3 = variant_right_2;
with_comparator(predicate.predicate_condition, [&](const auto comparator) {
result_3 = comparator(boost::get<ColumnDataTypeLeft>(variant_left_3),
boost::get<ColumnDataTypeRight>(variant_right_3));
});
} else {
Fail("Cannot compare string with non-string type");
}
});
});
return result;
}
std::shared_ptr<AbstractOperator> JoinVerification::_on_deep_copy(
const std::shared_ptr<AbstractOperator>& copied_input_left,
const std::shared_ptr<AbstractOperator>& copied_input_right) const {
return std::make_shared<JoinVerification>(copied_input_left, copied_input_right, _mode, _primary_predicate,
_secondary_predicates);
}
void JoinVerification::_on_set_parameters(const std::unordered_map<ParameterID, AllTypeVariant>& parameters) {}
} // namespace opossum
| 37.743243 | 120 | 0.671441 | [
"vector"
] |
58bd0cb10a5b6a970e4bf506a0601d383d02b807 | 3,891 | cpp | C++ | src/player_simple.cpp | indjev99/Sixty-Six-Bot | 7a09e4fade6671ebf51f8721b860b7f48653d7a9 | [
"MIT"
] | null | null | null | src/player_simple.cpp | indjev99/Sixty-Six-Bot | 7a09e4fade6671ebf51f8721b860b7f48653d7a9 | [
"MIT"
] | null | null | null | src/player_simple.cpp | indjev99/Sixty-Six-Bot | 7a09e4fade6671ebf51f8721b860b7f48653d7a9 | [
"MIT"
] | null | null | null | #include "player_simple.h"
#include "config.h"
#include "util.h"
#include "rng.h"
#include <algorithm>
#include <numeric>
static const int CLOSE_TAKE_VALUE = (std::accumulate(CARD_VALUES, CARD_VALUES + NUM_RANKS, 0) + NUM_RANKS / 2) / NUM_RANKS;
static const int KEEP_TRUMP_VALUE = CARD_VALUES[NUM_RANKS - 1];
void PlayerSimple::startSet() {}
void PlayerSimple::startGame()
{
trickNumber = 0;
}
void PlayerSimple::giveState(bool closed, int talonSize, Card trumpCard, int selfScore, int oppScore)
{
if (trickNumber == 0) trumpSuit = trumpCard.suit;
this->closed = closed;
this->talonSize = talonSize;
this->selfScore = selfScore;
}
void PlayerSimple::giveHand(const std::vector<Card>& hand)
{
this->hand = hand;
}
void PlayerSimple::giveMove(Move move, bool self)
{
leadCard = move.card;
}
void PlayerSimple::giveResponse(Card card, bool self)
{
++trickNumber;
}
void PlayerSimple::giveGameResult(int newPoints, int selfPoints, int oppPoints) {}
void PlayerSimple::giveSetResult(int result) {}
bool isBetter(int trumpSuit, Card card, Card other)
{
if ((card.suit == trumpSuit) != (other.suit == trumpSuit)) return card.suit == trumpSuit;
return card.rank > other.rank;
}
int PlayerSimple::getMove(const std::vector<int>& valid)
{
if (std::find(valid.begin(), valid.end(), M_EXCHANGE) != valid.end()) return M_EXCHANGE;
int targetMarriageSuit = -1;
std::vector<bool> isMarriageSuit = findMarriageSuits(hand);
for (int i = 0; i < NUM_SUITS; ++i)
{
if (isMarriageSuit[i]) targetMarriageSuit = i;
}
if (isMarriageSuit[trumpSuit]) targetMarriageSuit = trumpSuit;
if (trickNumber > 0 && targetMarriageSuit != -1)
{
for (int i = 0; i < (int) hand.size(); ++i)
{
if (hand[i].suit == targetMarriageSuit && hand[i].rank == MARRIAGE_RANKS[0]) return i;
}
}
if (std::find(valid.begin(), valid.end(), M_CLOSE) != valid.end())
{
std::vector<Card> sortedHand = hand;
std::sort(sortedHand.begin(), sortedHand.end());
int prevSuit = NUM_SUITS;
int closingScore = selfScore;
bool canTake = false;
int numTrumpsTaken = 0;
for (int i = sortedHand.size(); i >= 0; --i)
{
if (sortedHand[i].suit != prevSuit) canTake = sortedHand[i].rank == R_ACE;
else canTake = canTake && (sortedHand[i].rank == sortedHand[i + 1].rank - 1);
if (canTake) closingScore += CARD_VALUES[sortedHand[i].rank] + CLOSE_TAKE_VALUE;
if (canTake && sortedHand[i].suit == trumpSuit) ++numTrumpsTaken;
prevSuit = sortedHand[i].suit;
}
if (numTrumpsTaken >= (NUM_RANKS - 1) / 2 && closingScore >= WIN_TRESH) return M_CLOSE;
}
int move = -1;
bool targetBetter = closed || talonSize == 0;
for (int i = 0; i < (int) hand.size(); ++i)
{
if (move == -1 || isBetter(trumpSuit, hand[i], hand[move]) == targetBetter) move = i;
}
return move;
}
int PlayerSimple::getResponse(const std::vector<int>& valid)
{
std::vector<int> priorities(hand.size(), 0);
std::vector<bool> isMarriageSuit = findMarriageSuits(hand);
for (int i : valid)
{
if (hand[i].suit == trumpSuit) priorities[i] -= KEEP_TRUMP_VALUE + hand[i].rank;
if (isMarriageSuit[hand[i].suit] && isMarriageRank(hand[i].rank)) priorities[i] -= hand[i].suit != trumpSuit ? REG_MARRIAGE_VALUE : TRUMP_MARRIAGE_VALUE;
if (!leadWinsTrick(trumpSuit, leadCard, hand[i])) priorities[i] += CARD_VALUES[leadCard.rank] + (hand[i].suit != trumpSuit) * CARD_VALUES[hand[i].rank];
else priorities[i] -= CARD_VALUES[leadCard.rank] + CARD_VALUES[hand[i].rank];
}
int response = -1;
for (int i : valid)
{
if (response == -1 || priorities[i] > priorities[response]) response = i;
}
return response;
}
| 31.634146 | 161 | 0.631714 | [
"vector"
] |
58c89b2a3d1d8ec10a6ecdd2407c01c7fe1be994 | 737 | cpp | C++ | moci/moci_graphics_base/base/image.cpp | tobanteAudio/moci | a0a764e8a5270f9344ff57366fea36f72e7e3aa4 | [
"BSD-2-Clause"
] | null | null | null | moci/moci_graphics_base/base/image.cpp | tobanteAudio/moci | a0a764e8a5270f9344ff57366fea36f72e7e3aa4 | [
"BSD-2-Clause"
] | 16 | 2020-03-19T22:08:47.000Z | 2020-06-18T18:55:00.000Z | moci/moci_graphics_base/base/image.cpp | tobanteAudio/moci | a0a764e8a5270f9344ff57366fea36f72e7e3aa4 | [
"BSD-2-Clause"
] | null | null | null | #include "image.hpp"
#include "moci_core/core/logging.hpp"
#include "stb_image.h"
#include "stb_image_resize.h"
namespace moci
{
Image::Image(std::string const& path) { LoadFromFile(path); }
bool Image::LoadFromFile(std::string const& path)
{
auto* data = stbi_load(path.c_str(), &width_, &height_, &numChannels_, 0);
if (data == nullptr)
{
MOCI_CORE_ERROR("Image loading: {}", path);
stbi_image_free(data);
return false;
}
auto* start = reinterpret_cast<std::uint8_t*>(data);
auto* end = reinterpret_cast<std::uint8_t*>(data) + width_ * height_ * numChannels_;
data_ = Vector<std::uint8_t>(start, end);
stbi_image_free(data);
return true;
}
} // namespace moci | 24.566667 | 90 | 0.651289 | [
"vector"
] |
58ca079dd0faebdf5f977e958f26e569d3e46050 | 9,076 | cc | C++ | content/renderer/screen_orientation/screen_orientation_dispatcher_unittest.cc | xzhan96/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-01-07T18:51:03.000Z | 2021-01-07T18:51:03.000Z | content/renderer/screen_orientation/screen_orientation_dispatcher_unittest.cc | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/renderer/screen_orientation/screen_orientation_dispatcher_unittest.cc | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/screen_orientation/screen_orientation_dispatcher.h"
#include <list>
#include <memory>
#include <tuple>
#include "base/logging.h"
#include "content/common/screen_orientation_messages.h"
#include "content/public/test/test_utils.h"
#include "ipc/ipc_test_sink.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/WebKit/public/platform/modules/screen_orientation/WebLockOrientationCallback.h"
namespace content {
// MockLockOrientationCallback is an implementation of
// WebLockOrientationCallback and takes a LockOrientationResultHolder* as a
// parameter when being constructed. The |results_| pointer is owned by the
// caller and not by the callback object. The intent being that as soon as the
// callback is resolved, it will be killed so we use the
// LockOrientationResultHolder to know in which state the callback object is at
// any time.
class MockLockOrientationCallback : public blink::WebLockOrientationCallback {
public:
struct LockOrientationResultHolder {
LockOrientationResultHolder()
: succeeded_(false), failed_(false) {}
bool succeeded_;
bool failed_;
blink::WebLockOrientationError error_;
};
explicit MockLockOrientationCallback(LockOrientationResultHolder* results)
: results_(results) {}
void onSuccess() override { results_->succeeded_ = true; }
void onError(blink::WebLockOrientationError error) override {
results_->failed_ = true;
results_->error_ = error;
}
private:
~MockLockOrientationCallback() override {}
LockOrientationResultHolder* results_;
};
class ScreenOrientationDispatcherWithSink : public ScreenOrientationDispatcher {
public:
explicit ScreenOrientationDispatcherWithSink(IPC::TestSink* sink)
:ScreenOrientationDispatcher(NULL) , sink_(sink) {
}
bool Send(IPC::Message* message) override { return sink_->Send(message); }
IPC::TestSink* sink_;
};
class ScreenOrientationDispatcherTest : public testing::Test {
protected:
void SetUp() override {
dispatcher_.reset(new ScreenOrientationDispatcherWithSink(&sink_));
}
int GetFirstLockRequestIdFromSink() {
const IPC::Message* msg = sink().GetFirstMessageMatching(
ScreenOrientationHostMsg_LockRequest::ID);
EXPECT_TRUE(msg != NULL);
std::tuple<blink::WebScreenOrientationLockType, int> params;
ScreenOrientationHostMsg_LockRequest::Read(msg, ¶ms);
return std::get<1>(params);
}
IPC::TestSink& sink() {
return sink_;
}
void LockOrientation(blink::WebScreenOrientationLockType orientation,
blink::WebLockOrientationCallback* callback) {
dispatcher_->lockOrientation(orientation, callback);
}
void UnlockOrientation() {
dispatcher_->unlockOrientation();
}
void OnMessageReceived(const IPC::Message& message) {
dispatcher_->OnMessageReceived(message);
}
int routing_id() const {
// We return a fake routing_id() in the context of this test.
return 0;
}
IPC::TestSink sink_;
std::unique_ptr<ScreenOrientationDispatcher> dispatcher_;
};
// Test that calling lockOrientation() followed by unlockOrientation() cancel
// the lockOrientation().
TEST_F(ScreenOrientationDispatcherTest, CancelPending_Unlocking) {
MockLockOrientationCallback::LockOrientationResultHolder callback_results;
LockOrientation(blink::WebScreenOrientationLockPortraitPrimary,
new MockLockOrientationCallback(&callback_results));
UnlockOrientation();
EXPECT_FALSE(callback_results.succeeded_);
EXPECT_TRUE(callback_results.failed_);
EXPECT_EQ(blink::WebLockOrientationErrorCanceled, callback_results.error_);
}
// Test that calling lockOrientation() twice cancel the first lockOrientation().
TEST_F(ScreenOrientationDispatcherTest, CancelPending_DoubleLock) {
MockLockOrientationCallback::LockOrientationResultHolder callback_results;
// We create the object to prevent leaks but never actually use it.
MockLockOrientationCallback::LockOrientationResultHolder callback_results2;
LockOrientation(blink::WebScreenOrientationLockPortraitPrimary,
new MockLockOrientationCallback(&callback_results));
LockOrientation(blink::WebScreenOrientationLockPortraitPrimary,
new MockLockOrientationCallback(&callback_results2));
EXPECT_FALSE(callback_results.succeeded_);
EXPECT_TRUE(callback_results.failed_);
EXPECT_EQ(blink::WebLockOrientationErrorCanceled, callback_results.error_);
}
// Test that when a LockError message is received, the request is set as failed
// with the correct values.
TEST_F(ScreenOrientationDispatcherTest, LockRequest_Error) {
std::list<blink::WebLockOrientationError> errors;
errors.push_back(blink::WebLockOrientationErrorNotAvailable);
errors.push_back(
blink::WebLockOrientationErrorFullscreenRequired);
errors.push_back(blink::WebLockOrientationErrorCanceled);
for (std::list<blink::WebLockOrientationError>::const_iterator
it = errors.begin(); it != errors.end(); ++it) {
MockLockOrientationCallback::LockOrientationResultHolder callback_results;
LockOrientation(blink::WebScreenOrientationLockPortraitPrimary,
new MockLockOrientationCallback(&callback_results));
int request_id = GetFirstLockRequestIdFromSink();
OnMessageReceived(
ScreenOrientationMsg_LockError(routing_id(), request_id, *it));
EXPECT_FALSE(callback_results.succeeded_);
EXPECT_TRUE(callback_results.failed_);
EXPECT_EQ(*it, callback_results.error_);
sink().ClearMessages();
}
}
// Test that when a LockSuccess message is received, the request is set as
// succeeded.
TEST_F(ScreenOrientationDispatcherTest, LockRequest_Success) {
MockLockOrientationCallback::LockOrientationResultHolder callback_results;
LockOrientation(blink::WebScreenOrientationLockPortraitPrimary,
new MockLockOrientationCallback(&callback_results));
int request_id = GetFirstLockRequestIdFromSink();
OnMessageReceived(ScreenOrientationMsg_LockSuccess(routing_id(),
request_id));
EXPECT_TRUE(callback_results.succeeded_);
EXPECT_FALSE(callback_results.failed_);
sink().ClearMessages();
}
// Test an edge case: a LockSuccess is received but it matches no pending
// callback.
TEST_F(ScreenOrientationDispatcherTest, SuccessForUnknownRequest) {
MockLockOrientationCallback::LockOrientationResultHolder callback_results;
LockOrientation(blink::WebScreenOrientationLockPortraitPrimary,
new MockLockOrientationCallback(&callback_results));
int request_id = GetFirstLockRequestIdFromSink();
OnMessageReceived(ScreenOrientationMsg_LockSuccess(routing_id(),
request_id + 1));
EXPECT_FALSE(callback_results.succeeded_);
EXPECT_FALSE(callback_results.failed_);
}
// Test an edge case: a LockError is received but it matches no pending
// callback.
TEST_F(ScreenOrientationDispatcherTest, ErrorForUnknownRequest) {
MockLockOrientationCallback::LockOrientationResultHolder callback_results;
LockOrientation(blink::WebScreenOrientationLockPortraitPrimary,
new MockLockOrientationCallback(&callback_results));
int request_id = GetFirstLockRequestIdFromSink();
OnMessageReceived(ScreenOrientationMsg_LockError(
routing_id(), request_id + 1, blink::WebLockOrientationErrorCanceled));
EXPECT_FALSE(callback_results.succeeded_);
EXPECT_FALSE(callback_results.failed_);
}
// Test the following scenario:
// - request1 is received by the dispatcher;
// - request2 is received by the dispatcher;
// - request1 is rejected;
// - request1 success response is received.
// Expected: request1 is still rejected, request2 has not been set as succeeded.
TEST_F(ScreenOrientationDispatcherTest, RaceScenario) {
MockLockOrientationCallback::LockOrientationResultHolder callback_results1;
MockLockOrientationCallback::LockOrientationResultHolder callback_results2;
LockOrientation(blink::WebScreenOrientationLockPortraitPrimary,
new MockLockOrientationCallback(&callback_results1));
int request_id1 = GetFirstLockRequestIdFromSink();
LockOrientation(blink::WebScreenOrientationLockLandscapePrimary,
new MockLockOrientationCallback(&callback_results2));
// callback_results1 must be rejected, tested in CancelPending_DoubleLock.
OnMessageReceived(ScreenOrientationMsg_LockSuccess(routing_id(),
request_id1));
// First request is still rejected.
EXPECT_FALSE(callback_results1.succeeded_);
EXPECT_TRUE(callback_results1.failed_);
EXPECT_EQ(blink::WebLockOrientationErrorCanceled, callback_results1.error_);
// Second request is still pending.
EXPECT_FALSE(callback_results2.succeeded_);
EXPECT_FALSE(callback_results2.failed_);
}
} // namespace content
| 37.349794 | 101 | 0.768621 | [
"object"
] |
58caead27cf5c9f82ddf5bbbf25c65e7b4b3d284 | 3,928 | cpp | C++ | src/detection_to_spencer_detected_person.cpp | tuw-robotics/tuw_object_converter | 6ec93e821eb1ad3b9a1b4bf9ba3c1fd1ba763069 | [
"BSD-3-Clause"
] | null | null | null | src/detection_to_spencer_detected_person.cpp | tuw-robotics/tuw_object_converter | 6ec93e821eb1ad3b9a1b4bf9ba3c1fd1ba763069 | [
"BSD-3-Clause"
] | null | null | null | src/detection_to_spencer_detected_person.cpp | tuw-robotics/tuw_object_converter | 6ec93e821eb1ad3b9a1b4bf9ba3c1fd1ba763069 | [
"BSD-3-Clause"
] | null | null | null | /***************************************************************************
* Software License Agreement (BSD License) *
* Copyright (C) 2017 by Florian Beck <florian.beck@tuwien.ac.at> *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions *
* are met: *
* *
* 1. Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* 2. 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. *
* 3. Neither the name of the copyright holder nor the names of its *
* contributors may be used to endorse or promote products derived *
* from this software without specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS *
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE *
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, *
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, *
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; *
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER *
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT *
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY *
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *
* POSSIBILITY OF SUCH DAMAGE. *
***************************************************************************/
#include "tuw_object_converter/detection_to_spencer_detected_person.h"
DetectionToSpencerDetectedPersonNode::DetectionToSpencerDetectedPersonNode(ros::NodeHandle& nh) : nh_(nh), nh_private_("~")
{
sub_detection_ = nh_.subscribe("object_detection_topic", 1, &DetectionToSpencerDetectedPersonNode::detectionCallback, this);
pub_tracks_ = nh_.advertise<spencer_tracking_msgs::DetectedPersons>("detected_persons_topic", 100);
}
void DetectionToSpencerDetectedPersonNode::detectionCallback(const tuw_object_msgs::ObjectDetection& msg)
{
spencer_tracking_msgs::DetectedPersons detected_persons;
detected_persons.header = msg.header;
for(auto&& obj_it = msg.objects.begin(); obj_it != msg.objects.end(); obj_it++)
{
spencer_tracking_msgs::DetectedPerson detected_person;
detected_person.detection_id = obj_it->object.ids[0];
detected_person.confidence = obj_it->object.ids_confidence[0];
detected_person.pose.pose = obj_it->object.pose;
detected_person.modality = msg.sensor_type;
for(size_t i = 0; i < obj_it->covariance_pose.size() && i < 36; i++)
{
detected_person.pose.covariance[i] = obj_it->covariance_pose[i];
}
detected_persons.detections.emplace_back(detected_person);
}
pub_tracks_.publish(detected_persons);
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "detection_to_spencer_detected_person_node");
ros::NodeHandle nh;
DetectionToSpencerDetectedPersonNode detection_to_spencer_detected_person_node(nh);
ros::spin();
return 0;
}
| 51.684211 | 126 | 0.617872 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.