<commit_before>/**************************************************************************
 * 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$ */

// Class to encapsulate the ALICE updates to TDatabasePDG.h
// Can be used by TGeant3 and TGeant4
// It contains also the constants for the PDG particle IDs.
// Should evolve towards dynamical loading from external data base.
// Comments to: andreas.morsch@cern.ch

#include "AliPDG.h"
#include "TDatabasePDG.h"

ClassImp(AliPDG)

void AliPDG::AddParticlesToPdgDataBase()
{

//
// Add particles to the PDG data base
//

  static Bool_t bAdded = kFALSE;
  // Check if already called
  if(bAdded)return;
  bAdded = true;

  TDatabasePDG *pdgDB = TDatabasePDG::Instance();
  const Int_t kspe=50000000;

  // PDG nuclear states are 10-digit numbers
  // 10LZZZAAAI e.g. deuteron is
  // 1000010020
  const Int_t kion=1000000000;

/*
  const Double_t kAu2Gev=0.9314943228;
*/

  const Double_t khSlash = 1.0545726663e-27;
  const Double_t kErg2Gev = 1/1.6021773349e-3;
  const Double_t khShGev = khSlash*kErg2Gev;
  const Double_t kYear2Sec = 3600*24*365.25;

//
// Bottom mesons
// mass and life-time from PDG
//
  pdgDB->AddParticle("Upsilon(3S)","Upsilon(3S)",10.3552,kTRUE,
                     0,1,"Bottonium",200553);

// QCD diffractive states
  pdgDB->AddParticle("rho_diff0","rho_diff0",0,kTRUE,
		     0,0,"QCD diffr. state",9900110);
  pdgDB->AddParticle("pi_diffr+","pi_diffr+",0,kTRUE,
		     0,1,"QCD diffr. state",9900210);
  pdgDB->AddParticle("omega_di","omega_di",0,kTRUE,
		     0,0,"QCD diffr. state",9900220);
  pdgDB->AddParticle("phi_diff","phi_diff",0,kTRUE,
		     0,0,"QCD diffr. state",9900330);
  pdgDB->AddParticle("J/psi_di","J/psi_di",0,kTRUE,
		     0,0,"QCD diffr. state",9900440);
  pdgDB->AddParticle("n_diffr0","n_diffr0",0,kTRUE,
		     0,0,"QCD diffr. state",9902110);
  pdgDB->AddParticle("p_diffr+","p_diffr+",0,kTRUE,
		     0,1,"QCD diffr. state",9902210);

// From Herwig
  pdgDB->AddParticle("PSID    ", " ", 3.7699, kFALSE, 0.0, 0, "meson",   30443);

  pdgDB->AddParticle("A_00    ", " ", 0.9960, kFALSE, 0.0, 0, "meson",  9000111);
  pdgDB->AddParticle("A_0+    ", " ", 0.9960, kFALSE, 0.0,+3, "meson",  9000211);
  pdgDB->AddParticle("A_0-    ", " ", 0.9960, kFALSE, 0.0,-3, "meson", -9000211);

  pdgDB->AddParticle("F0P0    ", " ", 0.9960, kFALSE, 0.0, 0, "meson",  9010221);

  pdgDB->AddParticle("KDL_2+  ", " ", 1.773,  kFALSE, 0.0,+3, "meson",   10325);
  pdgDB->AddParticle("KDL_2-  ", " ", 1.773,  kFALSE, 0.0,-3, "meson",  -10325);

  pdgDB->AddParticle("KDL_20  ", " ", 1.773,  kFALSE, 0.0, 0, "meson",   10315);
  pdgDB->AddParticle("KDL_2BR0", " ", 1.773,  kFALSE, 0.0, 0, "meson",  -10315);

  pdgDB->AddParticle("PI_2+   ", " ", 1.670,  kFALSE, 0.0,+3, "meson",   10215);
  pdgDB->AddParticle("PI_2-   ", " ", 1.670,  kFALSE, 0.0,-3, "meson",  -10215);
  pdgDB->AddParticle("PI_20   ", " ", 1.670,  kFALSE, 0.0, 0, "meson",   10115);

  pdgDB->AddParticle("KD*+    ", " ", 1.717,  kFALSE, 0.0,+3, "meson",   30323);
  pdgDB->AddParticle("KD*-    ", " ", 1.717,  kFALSE, 0.0,-3, "meson",  -30323);

  pdgDB->AddParticle("KD*0    ", " ", 1.717,  kFALSE, 0.0, 0, "meson",   30313);
  pdgDB->AddParticle("KDBR*0  ", " ", 1.717,  kFALSE, 0.0, 0, "meson",  -30313);

  pdgDB->AddParticle("RHOD+   ", " ", 1.700,  kFALSE, 0.0,+3, "meson",   30213);
  pdgDB->AddParticle("RHOD-   ", " ", 1.700,  kFALSE, 0.0,-3, "meson",  -30213);
  pdgDB->AddParticle("RHOD0   ", " ", 1.700,  kFALSE, 0.0, 0, "meson",   30113);

  pdgDB->AddParticle("ETA_2(L)", " ", 1.632,  kFALSE, 0.0, 0, "meson",   10225);
  pdgDB->AddParticle("ETA_2(H)", " ", 1.854,  kFALSE, 0.0, 0, "meson",   10335);
  pdgDB->AddParticle("OMEGA(H)", " ", 1.649,  kFALSE, 0.0, 0, "meson",   30223);

  pdgDB->AddParticle("KDH_2+  ", " ", 1.816,  kFALSE, 0.0,+3, "meson",   20325);
  pdgDB->AddParticle("KDH_2-  ", " ", 1.816,  kFALSE, 0.0,-3, "meson",  -20325);

  pdgDB->AddParticle("KDH_20  ", " ", 1.816,  kFALSE, 0.0, 0, "meson",   20315);
  pdgDB->AddParticle("KDH_2BR0", " ", 1.816,  kFALSE, 0.0, 0, "meson",  -20315);

  pdgDB->AddParticle("KD_3+   ", " ", 1.773,  kFALSE, 0.0,+3, "meson",     327);
  pdgDB->AddParticle("KD_3-   ", " ", 1.773,  kFALSE, 0.0,-3, "meson",    -327);

  pdgDB->AddParticle("KD_30   ", " ", 1.773,  kFALSE, 0.0, 0, "meson",     317);
  pdgDB->AddParticle("KD_3BR0 ", " ", 1.773,  kFALSE, 0.0, 0, "meson",    -317);

  pdgDB->AddParticle("RHO_3+  ", " ", 1.691,  kFALSE, 0.0,+3, "meson",     217);
  pdgDB->AddParticle("RHO_3-  ", " ", 1.691,  kFALSE, 0.0,-3, "meson",    -217);
  pdgDB->AddParticle("RHO_30  ", " ", 1.691,  kFALSE, 0.0, 0, "meson",     117);
  pdgDB->AddParticle("OMEGA_3 ", " ", 1.667,  kFALSE, 0.0, 0, "meson",     227);
  pdgDB->AddParticle("PHI_3   ", " ", 1.854,  kFALSE, 0.0, 0, "meson",     337);

  pdgDB->AddParticle("CHI2P_B0", " ", 10.232, kFALSE, 0.0, 0, "meson", 110551);
  pdgDB->AddParticle("CHI2P_B1", " ", 10.255, kFALSE, 0.0, 0, "meson", 120553);
  pdgDB->AddParticle("CHI2P_B2", " ", 10.269, kFALSE, 0.0, 0, "meson", 100555);
  pdgDB->AddParticle("UPSLON4S", " ", 10.580, kFALSE, 0.0, 0, "meson", 300553);

  // IONS
  //
  // Done by default now from Pythia6 table
  // Needed for other generators
  // So check if already defined

  Int_t ionCode = kion+10020;
  if(!pdgDB->GetParticle(ionCode)){
      pdgDB->AddParticle("Deuteron","Deuteron", 1.875613, kTRUE,
			 0,3,"Ion",ionCode);
  }
  pdgDB->AddAntiParticle("AntiDeuteron", - ionCode);

  ionCode = kion+10030;
  if(!pdgDB->GetParticle(ionCode)){
    pdgDB->AddParticle("Triton","Triton", 2.80925, kFALSE,
                     khShGev/(12.33*kYear2Sec),3,"Ion",ionCode);
  }
  pdgDB->AddAntiParticle("AntiTriton", - ionCode);

  ionCode = kion+20030;
  if(!pdgDB->GetParticle(ionCode)){
    pdgDB->AddParticle("HE3","HE3", 2.80923,kFALSE,
                     0,6,"Ion",ionCode);
  }
  pdgDB->AddAntiParticle("AntiHE3", - ionCode);

  ionCode = kion+20040;
  if(!pdgDB->GetParticle(ionCode)){
    pdgDB->AddParticle("Alpha","Alpha", 3.727417, kTRUE,
		       khShGev/(12.33*kYear2Sec), 6, "Ion", ionCode);
  }
  pdgDB->AddAntiParticle("AntiAlpha", - ionCode);

// Special particles
//
  pdgDB->AddParticle("Cherenkov","Cherenkov",0,kFALSE,
		     0,0,"Special",kspe+50);
  pdgDB->AddParticle("FeedbackPhoton","FeedbackPhoton",0,kFALSE,
		     0,0,"Special",kspe+51);
  pdgDB->AddParticle("Lambda1520","Lambda1520",1.5195,kFALSE,
		     0.0156,0,"Resonance",3124);
  pdgDB->AddAntiParticle("Lambda1520bar",-3124);
}

<commit_msg>Added Hypertriton to PDG DB<commit_after>/**************************************************************************
 * 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$ */

// Class to encapsulate the ALICE updates to TDatabasePDG.h
// Can be used by TGeant3 and TGeant4
// It contains also the constants for the PDG particle IDs.
// Should evolve towards dynamical loading from external data base.
// Comments to: andreas.morsch@cern.ch

#include "AliPDG.h"
#include "TDatabasePDG.h"

ClassImp(AliPDG)

void AliPDG::AddParticlesToPdgDataBase()
{

//
// Add particles to the PDG data base
//

  static Bool_t bAdded = kFALSE;
  // Check if already called
  if(bAdded)return;
  bAdded = true;

  TDatabasePDG *pdgDB = TDatabasePDG::Instance();
  const Int_t kspe=50000000;

  // PDG nuclear states are 10-digit numbers
  // 10LZZZAAAI e.g. deuteron is
  // 1000010020
  const Int_t kion=1000000000;

/*
  const Double_t kAu2Gev=0.9314943228;
*/

  const Double_t khSlash = 1.0545726663e-27;
  const Double_t kErg2Gev = 1/1.6021773349e-3;
  const Double_t khShGev = khSlash*kErg2Gev;
  const Double_t kYear2Sec = 3600*24*365.25;

//
// Bottom mesons
// mass and life-time from PDG
//
  pdgDB->AddParticle("Upsilon(3S)","Upsilon(3S)",10.3552,kTRUE,
                     0,1,"Bottonium",200553);

// QCD diffractive states
  pdgDB->AddParticle("rho_diff0","rho_diff0",0,kTRUE,
		     0,0,"QCD diffr. state",9900110);
  pdgDB->AddParticle("pi_diffr+","pi_diffr+",0,kTRUE,
		     0,1,"QCD diffr. state",9900210);
  pdgDB->AddParticle("omega_di","omega_di",0,kTRUE,
		     0,0,"QCD diffr. state",9900220);
  pdgDB->AddParticle("phi_diff","phi_diff",0,kTRUE,
		     0,0,"QCD diffr. state",9900330);
  pdgDB->AddParticle("J/psi_di","J/psi_di",0,kTRUE,
		     0,0,"QCD diffr. state",9900440);
  pdgDB->AddParticle("n_diffr0","n_diffr0",0,kTRUE,
		     0,0,"QCD diffr. state",9902110);
  pdgDB->AddParticle("p_diffr+","p_diffr+",0,kTRUE,
		     0,1,"QCD diffr. state",9902210);

// From Herwig
  pdgDB->AddParticle("PSID    ", " ", 3.7699, kFALSE, 0.0, 0, "meson",   30443);

  pdgDB->AddParticle("A_00    ", " ", 0.9960, kFALSE, 0.0, 0, "meson",  9000111);
  pdgDB->AddParticle("A_0+    ", " ", 0.9960, kFALSE, 0.0,+3, "meson",  9000211);
  pdgDB->AddParticle("A_0-    ", " ", 0.9960, kFALSE, 0.0,-3, "meson", -9000211);

  pdgDB->AddParticle("F0P0    ", " ", 0.9960, kFALSE, 0.0, 0, "meson",  9010221);

  pdgDB->AddParticle("KDL_2+  ", " ", 1.773,  kFALSE, 0.0,+3, "meson",   10325);
  pdgDB->AddParticle("KDL_2-  ", " ", 1.773,  kFALSE, 0.0,-3, "meson",  -10325);

  pdgDB->AddParticle("KDL_20  ", " ", 1.773,  kFALSE, 0.0, 0, "meson",   10315);
  pdgDB->AddParticle("KDL_2BR0", " ", 1.773,  kFALSE, 0.0, 0, "meson",  -10315);

  pdgDB->AddParticle("PI_2+   ", " ", 1.670,  kFALSE, 0.0,+3, "meson",   10215);
  pdgDB->AddParticle("PI_2-   ", " ", 1.670,  kFALSE, 0.0,-3, "meson",  -10215);
  pdgDB->AddParticle("PI_20   ", " ", 1.670,  kFALSE, 0.0, 0, "meson",   10115);

  pdgDB->AddParticle("KD*+    ", " ", 1.717,  kFALSE, 0.0,+3, "meson",   30323);
  pdgDB->AddParticle("KD*-    ", " ", 1.717,  kFALSE, 0.0,-3, "meson",  -30323);

  pdgDB->AddParticle("KD*0    ", " ", 1.717,  kFALSE, 0.0, 0, "meson",   30313);
  pdgDB->AddParticle("KDBR*0  ", " ", 1.717,  kFALSE, 0.0, 0, "meson",  -30313);

  pdgDB->AddParticle("RHOD+   ", " ", 1.700,  kFALSE, 0.0,+3, "meson",   30213);
  pdgDB->AddParticle("RHOD-   ", " ", 1.700,  kFALSE, 0.0,-3, "meson",  -30213);
  pdgDB->AddParticle("RHOD0   ", " ", 1.700,  kFALSE, 0.0, 0, "meson",   30113);

  pdgDB->AddParticle("ETA_2(L)", " ", 1.632,  kFALSE, 0.0, 0, "meson",   10225);
  pdgDB->AddParticle("ETA_2(H)", " ", 1.854,  kFALSE, 0.0, 0, "meson",   10335);
  pdgDB->AddParticle("OMEGA(H)", " ", 1.649,  kFALSE, 0.0, 0, "meson",   30223);

  pdgDB->AddParticle("KDH_2+  ", " ", 1.816,  kFALSE, 0.0,+3, "meson",   20325);
  pdgDB->AddParticle("KDH_2-  ", " ", 1.816,  kFALSE, 0.0,-3, "meson",  -20325);

  pdgDB->AddParticle("KDH_20  ", " ", 1.816,  kFALSE, 0.0, 0, "meson",   20315);
  pdgDB->AddParticle("KDH_2BR0", " ", 1.816,  kFALSE, 0.0, 0, "meson",  -20315);

  pdgDB->AddParticle("KD_3+   ", " ", 1.773,  kFALSE, 0.0,+3, "meson",     327);
  pdgDB->AddParticle("KD_3-   ", " ", 1.773,  kFALSE, 0.0,-3, "meson",    -327);

  pdgDB->AddParticle("KD_30   ", " ", 1.773,  kFALSE, 0.0, 0, "meson",     317);
  pdgDB->AddParticle("KD_3BR0 ", " ", 1.773,  kFALSE, 0.0, 0, "meson",    -317);

  pdgDB->AddParticle("RHO_3+  ", " ", 1.691,  kFALSE, 0.0,+3, "meson",     217);
  pdgDB->AddParticle("RHO_3-  ", " ", 1.691,  kFALSE, 0.0,-3, "meson",    -217);
  pdgDB->AddParticle("RHO_30  ", " ", 1.691,  kFALSE, 0.0, 0, "meson",     117);
  pdgDB->AddParticle("OMEGA_3 ", " ", 1.667,  kFALSE, 0.0, 0, "meson",     227);
  pdgDB->AddParticle("PHI_3   ", " ", 1.854,  kFALSE, 0.0, 0, "meson",     337);

  pdgDB->AddParticle("CHI2P_B0", " ", 10.232, kFALSE, 0.0, 0, "meson", 110551);
  pdgDB->AddParticle("CHI2P_B1", " ", 10.255, kFALSE, 0.0, 0, "meson", 120553);
  pdgDB->AddParticle("CHI2P_B2", " ", 10.269, kFALSE, 0.0, 0, "meson", 100555);
  pdgDB->AddParticle("UPSLON4S", " ", 10.580, kFALSE, 0.0, 0, "meson", 300553);

  // IONS
  //
  // Done by default now from Pythia6 table
  // Needed for other generators
  // So check if already defined

  Int_t ionCode = kion+10020;
  if(!pdgDB->GetParticle(ionCode)){
      pdgDB->AddParticle("Deuteron","Deuteron", 1.875613, kTRUE,
			 0,3,"Ion",ionCode);
  }
  pdgDB->AddAntiParticle("AntiDeuteron", - ionCode);

  ionCode = kion+10030;
  if(!pdgDB->GetParticle(ionCode)){
    pdgDB->AddParticle("Triton","Triton", 2.80925, kFALSE,
                     khShGev/(12.33*kYear2Sec),3,"Ion",ionCode);
  }
  pdgDB->AddAntiParticle("AntiTriton", - ionCode);

  ionCode = kion+20030;
  if(!pdgDB->GetParticle(ionCode)){
    pdgDB->AddParticle("HE3","HE3", 2.80923,kFALSE,
                     0,6,"Ion",ionCode);
  }
  pdgDB->AddAntiParticle("AntiHE3", - ionCode);

  ionCode = kion+20040;
  if(!pdgDB->GetParticle(ionCode)){
    pdgDB->AddParticle("Alpha","Alpha", 3.727417, kTRUE,
		       khShGev/(12.33*kYear2Sec), 6, "Ion", ionCode);
  }
  pdgDB->AddAntiParticle("AntiAlpha", - ionCode);

// Special particles
//
  pdgDB->AddParticle("Cherenkov","Cherenkov",0,kFALSE,
		     0,0,"Special",kspe+50);
  pdgDB->AddParticle("FeedbackPhoton","FeedbackPhoton",0,kFALSE,
		     0,0,"Special",kspe+51);
  pdgDB->AddParticle("Lambda1520","Lambda1520",1.5195,kFALSE,
		     0.0156,0,"Resonance",3124);
  pdgDB->AddAntiParticle("Lambda1520bar",-3124);

  //Hyper nuclei and exotica
  ionCode = 1010010030;
  if(!pdgDB->GetParticle(ionCode)){
    pdgDB->AddParticle("HyperTriton","HyperTriton", 2.99131, kFALSE,
		       2.5-15, 3, "Ion", ionCode);// FIXME: check width
  }

  ionCode = -1010010030;
  if(!pdgDB->GetParticle(ionCode)){
    pdgDB->AddParticle("AntiHyperTriton","AntiHyperTriton", 2.99131, kFALSE,
		       2.5e-15, 3, "Ion", ionCode);// FIXME: check width
  }

}

<|endoftext|>


<commit_before>#include "tr_local.h"

TextManager* ptText = nullptr;
static fontRegisteredCallback currentCallback = nullptr;

void TextManager::FontRequestCallback(AssetComponent* pComponent) {
	if (ptText != nullptr && pComponent != nullptr) {
		ComponentFont* pFont = pComponent->data.fontComponent;
		SDL_RWops* rw = SDL_RWFromMem(pFont->fontData, pComponent->meta.decompressedSize - sizeof(pFont->head));
		const char* compName = pComponent->meta.componentName;

		if (rw == nullptr) {
			trap->Print(PRIORITY_WARNING, "Couldn't read memory for font component %s\n", compName);
			return;
		}
		TTF_Font* ttfFont = TTF_OpenFontIndexRW(rw, 0, pFont->head.pointSize, pFont->head.fontFace);
		if (ttfFont == nullptr) {
			trap->Print(PRIORITY_WARNING, "Could not load font component %s (reason: %s)\n", compName, TTF_GetError());
			SDL_RWclose(rw);
			return;
		}

		TTF_SetFontStyle(ttfFont, pFont->head.style);

		ptText->umFontsRegistered[compName] = (Font*)ttfFont;
		if (currentCallback != nullptr) {
			currentCallback(compName, (Font*)ttfFont);
		}
	}
}

void TextManager::RegisterFontAsync(const char* szFontComponent, fontRegisteredCallback callback) {
	auto it = umFontsRegistered.find(szFontComponent);
	if (it == umFontsRegistered.end()) {
		// It's not there
		umFontsRegistered[szFontComponent] = nullptr;
		currentCallback = callback;
		trap->ResourceAsyncURI(szFontComponent, TextManager::FontRequestCallback);
	}
	else {
		callback(szFontComponent, it->second);
	}
}

void TextManager::RenderTextSolid(Font* font, const char* text, int x, int y, int r, int g, int b) {
	SDL_Color color = { r, g, b, 255 };
	SDL_Surface* surf = TTF_RenderText_Solid((TTF_Font*)font, text, color);
	if (surf == nullptr) {
		return;
	}

	SDL_Surface* surf2 = SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_ARGB8888, 0);
	SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, surf2);
	SDL_Rect dstRct{ x, y, 0, 0 };
	SDL_RenderCopy(renderer, tex, &dstRct, &surf->clip_rect);
	SDL_FreeSurface(surf);
	SDL_FreeSurface(surf2);

	// Cache the texture so we can kill it after this frame
	vTextFields.push_back(tex);
}

void TextManager::RenderTextShaded(Font* font, const char* text, int x, int y, int br, int bg, int bb, int fr, int fg, int fb) {
	SDL_Color cB = { br, bg, bb, 255 };
	SDL_Color cF = { fr, fg, fb, 255 };
	SDL_Surface* surf = TTF_RenderText_Shaded((TTF_Font*)font, text, cF, cB);
	if (surf == nullptr) {
		return;
	}

	SDL_Surface* surf2 = SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_ARGB8888, 0);
	SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, surf2);
	SDL_Rect dstRct{ x, y, 0, 0 };
	SDL_RenderCopy(renderer, tex, &dstRct, &surf->clip_rect);
	SDL_FreeSurface(surf);
	SDL_FreeSurface(surf2);

	// Cache the texture so we can kill it after this frame
	vTextFields.push_back(tex);
}

void TextManager::RenderTextBlended(Font* font, const char* text, int x, int y, int r, int g, int b) {
	SDL_Color color = { r, g, b, 255 };
	SDL_Surface* surf = TTF_RenderText_Blended((TTF_Font*)font, text, color);
	if (surf == nullptr) {
		return;
	}

	SDL_Surface* surf2 = SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_ARGB8888, 0);
	SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, surf2);
	SDL_Rect dstRct{ x, y, 0, 0 };
	SDL_RenderCopy(renderer, tex, &dstRct, &surf->clip_rect);
	SDL_FreeSurface(surf);
	SDL_FreeSurface(surf2);

	// Cache the texture so we can kill it after this frame
	vTextFields.push_back(tex);
}

void TextManager::ResetFrame() {
	for (auto it = vTextFields.begin(); it != vTextFields.end(); it++) {
		SDL_DestroyTexture(*it);
	}
	vTextFields.clear();
}

TextManager::TextManager() {}
TextManager::~TextManager() {
	for (auto it = vTextFields.begin(); it != vTextFields.end(); it++) {
		SDL_DestroyTexture(*it);
	}
	for (auto it = umFontsRegistered.begin(); it != umFontsRegistered.begin(); ++it) {
		TTF_CloseFont((TTF_Font*)it->second);
	}
	umFontsRegistered.clear();
	vTextFields.clear();
	currentCallback = nullptr;
}<commit_msg>Call TTF_Init and TTF_Quit when starting the TextManager on SDL renderer.<commit_after>#include "tr_local.h"

TextManager* ptText = nullptr;
static fontRegisteredCallback currentCallback = nullptr;

void TextManager::FontRequestCallback(AssetComponent* pComponent) {
	if (ptText != nullptr && pComponent != nullptr) {
		ComponentFont* pFont = pComponent->data.fontComponent;
		SDL_RWops* rw = SDL_RWFromMem(pFont->fontData, pComponent->meta.decompressedSize - sizeof(pFont->head));
		const char* compName = pComponent->meta.componentName;

		if (rw == nullptr) {
			trap->Print(PRIORITY_WARNING, "Couldn't read memory for font component %s\n", compName);
			return;
		}
		TTF_Font* ttfFont = TTF_OpenFontIndexRW(rw, 0, pFont->head.pointSize, pFont->head.fontFace);
		if (ttfFont == nullptr) {
			trap->Print(PRIORITY_WARNING, "Could not load font component %s (reason: %s)\n", compName, TTF_GetError());
			SDL_RWclose(rw);
			return;
		}

		TTF_SetFontStyle(ttfFont, pFont->head.style);

		ptText->umFontsRegistered[compName] = (Font*)ttfFont;
		if (currentCallback != nullptr) {
			currentCallback(compName, (Font*)ttfFont);
		}
	}
}

void TextManager::RegisterFontAsync(const char* szFontComponent, fontRegisteredCallback callback) {
	auto it = umFontsRegistered.find(szFontComponent);
	if (it == umFontsRegistered.end()) {
		// It's not there
		umFontsRegistered[szFontComponent] = nullptr;
		currentCallback = callback;
		trap->ResourceAsyncURI(szFontComponent, TextManager::FontRequestCallback);
	}
	else {
		callback(szFontComponent, it->second);
	}
}

void TextManager::RenderTextSolid(Font* font, const char* text, int x, int y, int r, int g, int b) {
	SDL_Color color = { r, g, b, 255 };
	SDL_Surface* surf = TTF_RenderText_Solid((TTF_Font*)font, text, color);
	if (surf == nullptr) {
		return;
	}

	SDL_Surface* surf2 = SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_ARGB8888, 0);
	SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, surf2);
	SDL_Rect dstRct{ x, y, 0, 0 };
	SDL_RenderCopy(renderer, tex, &dstRct, &surf->clip_rect);
	SDL_FreeSurface(surf);
	SDL_FreeSurface(surf2);

	// Cache the texture so we can kill it after this frame
	vTextFields.push_back(tex);
}

void TextManager::RenderTextShaded(Font* font, const char* text, int x, int y, int br, int bg, int bb, int fr, int fg, int fb) {
	SDL_Color cB = { br, bg, bb, 255 };
	SDL_Color cF = { fr, fg, fb, 255 };
	SDL_Surface* surf = TTF_RenderText_Shaded((TTF_Font*)font, text, cF, cB);
	if (surf == nullptr) {
		return;
	}

	SDL_Surface* surf2 = SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_ARGB8888, 0);
	SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, surf2);
	SDL_Rect dstRct{ x, y, 0, 0 };
	SDL_RenderCopy(renderer, tex, &dstRct, &surf->clip_rect);
	SDL_FreeSurface(surf);
	SDL_FreeSurface(surf2);

	// Cache the texture so we can kill it after this frame
	vTextFields.push_back(tex);
}

void TextManager::RenderTextBlended(Font* font, const char* text, int x, int y, int r, int g, int b) {
	SDL_Color color = { r, g, b, 255 };
	SDL_Surface* surf = TTF_RenderText_Blended((TTF_Font*)font, text, color);
	if (surf == nullptr) {
		return;
	}

	SDL_Surface* surf2 = SDL_ConvertSurfaceFormat(surf, SDL_PIXELFORMAT_ARGB8888, 0);
	SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, surf2);
	SDL_Rect dstRct{ x, y, 0, 0 };
	SDL_RenderCopy(renderer, tex, &dstRct, &surf->clip_rect);
	SDL_FreeSurface(surf);
	SDL_FreeSurface(surf2);

	// Cache the texture so we can kill it after this frame
	vTextFields.push_back(tex);
}

void TextManager::ResetFrame() {
	for (auto it = vTextFields.begin(); it != vTextFields.end(); it++) {
		SDL_DestroyTexture(*it);
	}
	vTextFields.clear();
}

TextManager::TextManager() {
	TTF_Init();
}

TextManager::~TextManager() {
	for (auto it = vTextFields.begin(); it != vTextFields.end(); it++) {
		SDL_DestroyTexture(*it);
	}
	for (auto it = umFontsRegistered.begin(); it != umFontsRegistered.begin(); ++it) {
		TTF_CloseFont((TTF_Font*)it->second);
	}
	umFontsRegistered.clear();
	vTextFields.clear();
	currentCallback = nullptr;

	TTF_Quit();
}<|endoftext|>


<commit_before>/*! CreditMetrics.cpp : Defines the entry point for the console application.
	Note: The given .csv files are not formatted consistently. The .csv parsers below are
	designed to handle the inconsistencies present in the files in a somewhat
	general manner by removing extra characters and white space.
*/
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <functional>
#include <numeric>
#include <cctype>
#include <locale>
#include <random>
#include <boost/algorithm/string.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
using namespace std;

static inline string& trim(string& s) {
	//left
	s.erase(s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace))));
	//right
	s.erase(find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(), s.end());
	return s;
}
static inline int convertInt(string strInt)
{
	trim(strInt);
	return ::atoi(strInt.c_str());
}
static inline double convertDouble(string strDouble)
{
	trim(strDouble);
	return ::atof(strDouble.c_str());
}
static inline double convertPercent(string strPercent)
{
	replace(strPercent.begin(), strPercent.end(), '%', ' ');
	return convertDouble(strPercent) / 100;
}
static inline string sanitizeString(string str)
{
	boost::to_upper(str);
	trim(str);
	return str;
}

template <class R> class CSV : public vector<R>
{
public:
	CSV(const string& filename, size_t skipLines)
	{
		ifstream file(filename);
		if (!file.good())
		{
			throw runtime_error("File does not exist");
		}
		while (!file.eof())
		{
			string strline;
			getline(file, strline);
			if (skipLines > 0)
			{
				skipLines--;
				continue;
			}
			if (strline.empty())
			{
				continue;
			}
			stringstream streamline(strline);
			vector<string> cells;
			while (!streamline.eof())
			{
				string cell;
				getline(streamline, cell, ',');
				if (cell != "")
				{
					cells.push_back(cell);
				}
			}
			if (cells.empty())
			{
				continue;
			}
			push_back(R(cells));
		}
	}
	const string toString()
	{
		string ret;
		for (size_t i = 0, n = size(); i < n; i++)
			ret = ret + at(i).toString() + "\n";
		return ret;
	}
};
class IssuerEntry
{
public:
	IssuerEntry(const vector<string>& cells):
		name(sanitizeString(cells.at(0))),
		rating(sanitizeString(cells.at(1))),
		industry(sanitizeString(cells.at(2)))
	{}
	const string name;
	const string rating;
	const string industry;
	const string toString() const
	{
		return string()
			+ name + "," + rating + "," + industry;
	}
};
class IssuerData : public CSV<IssuerEntry>
{
public:
	IssuerData() : CSV("issuers.csv", 1) { }
	IssuerEntry* getByName(string name)
	{
		for (size_t i = 0, n = size(); i < n; i++)
		{
			IssuerEntry& issuer = at(i);
			if(issuer.name == name)
				return &issuer;
		}
		return nullptr;
	}
};
class PortfolioEntry
{
public:
	PortfolioEntry(const vector<string>& cells) :
		name(sanitizeString(cells.at(0))),
		instrumentType(sanitizeString(cells.at(1))),
		cusip(cells.at(2)),
		notional(convertNotional(cells.at(3))),
		maturity(cells.at(4)),
		coupon(convertPercent(cells.at(5))),
		couponsPerYear(convertInt(cells.at(6))),
		price(convertPrice(cells.at(7))),
		yield(convertPercent(cells.at(8))),
		cleanPrice(convertPrice(cells.at(9))),
		exprr(convertPercent(cells.at(10)))
	{}
	const string name, instrumentType, cusip, maturity;
	const int notional, couponsPerYear;
	const double coupon, price, yield, cleanPrice,exprr;
	const string toString() const
	{
		return string()
			+ name + "," + instrumentType + ","
			+ cusip + "," + to_string(notional) + ","
			+ maturity + "," + to_string(coupon) + ","
			+ to_string(couponsPerYear) + "," + to_string(price) + ","
			+ to_string(yield) + "," + to_string(cleanPrice) + ","
			+ to_string(exprr);
	}
private:
	int convertNotional(string strNotional)
	{
		return convertInt(strNotional);
	}
	double convertPrice(string strPrice)
	{
		replace(strPrice.begin(), strPrice.end(), '$', ' ');
		return convertDouble(strPrice);
	}
};
class PortfolioData : public CSV<PortfolioEntry>
{
public:
	PortfolioData() : CSV("portfolio_for_project.csv", 1) { }
	PortfolioEntry* getByName(string name)
	{
		for (size_t i = 0, n = size(); i < n; i++)
		{
			PortfolioEntry& issuer = at(i);
			if (issuer.name == name)
				return &issuer;
		}
		return nullptr;
	}
	/*! Response for Part B, Step 2) Reported Value
		\return The reported value of the portfolio in millions of dollars
	*/
	double getReportedValue()
	{
		double marketValue = 0;
		for (size_t i = 0, n = size(); i < n; i++)
		{
			PortfolioEntry& row = at(i);
			double targetValue;
			if (row.instrumentType == "CDS")
				targetValue = row.cleanPrice;
			else
				targetValue = row.price;
			marketValue = marketValue + (row.notional*targetValue / 100);
		}
		return marketValue;
	}
	/*! Response for Part B, Step 2) Theoretical Value
	\return The theoretical value of the portfolio in millions of dollars
	*/
	double getTheorValue()
	{
		double theorValue = 0;
		for (size_t i = 0, n = size(); i < n; i++)
		{
			PortfolioEntry& row = at(i);
			theorValue = theorValue + (row.notional*row.cleanPrice / 100);
		}
		return theorValue;
	}
};
class YieldEntry
{
public:
	YieldEntry(const vector<string>& cells):
		term(convertDouble(cells.at(0))),
		aaa(convertPercent(cells.at(1))),
		aa(convertPercent(cells.at(2))),
		a(convertPercent(cells.at(3))),
		bbb(convertPercent(cells.at(4))),
		bb(convertPercent(cells.at(5))),
		b(convertPercent(cells.at(6))),
		ccc(convertPercent(cells.at(7))),
		govt(convertPercent(cells.at(8)))
	{}
	const double term, aaa, aa, a, bbb, bb, b, ccc, govt;
	const string toString() const
	{
		return string()
			+ to_string(term) + "," + to_string(aaa) + ","
			+ to_string(aa) + "," + to_string(a) + ","
			+ to_string(bbb) + "," + to_string(bb) + ","
			+ to_string(b) + "," + to_string(ccc) + ","
			+ to_string(govt);
	}
};
class YieldData : public CSV<YieldEntry>
{
public:
	YieldData() : CSV("yield_curve_for_project.csv", 1) { }
	YieldEntry* getByTerm(double term)
	{
		for (size_t i = 0, n = size(); i < n; i++)
		{
			YieldEntry& yield = at(i);
			if (yield.term == term)
				return &yield;
		}
		return nullptr;
	}
};
class MatrixRow : public vector<double>
{
public:
	MatrixRow(const vector<string>& cells)
	{
		for (size_t i = 1, n = cells.size(); i < n; i++)
		{
			push_back(convertDouble(cells.at(i)));
		}
	}
	using vector::vector;
	string toString()
	{
		string ret;
		for (size_t i = 0, n = size(); i < n; i++)
		{
			if (i > 0)
				ret = ret + ",";
			ret = ret + to_string(at(i));
		}
		return ret;
	}
};
class Matrix : public CSV<MatrixRow>
{
public:
	Matrix(const string& filename, size_t skipLines) : CSV(filename, skipLines) {}
};
class ScenarioEntry
{
public:
	ScenarioEntry(IssuerEntry& entry) :
		name(entry.name),
		rating(convertRating(entry.rating))
	{}
	const string name;
	const int rating;
	const int convertRating(string rating) const
	{
		int convertedRating;
		if (rating == "AAA")
			convertedRating = 0;
		else if (rating == "AA")
			convertedRating = 1;
		else if (rating == "A")
			convertedRating = 2;
		else if (rating == "BBB")
			convertedRating = 3;
		else if (rating == "BB")
			convertedRating = 4;
		else if (rating == "B")
			convertedRating = 5;
		else if (rating == "CCC")
			convertedRating = 6;
		else if (rating == "C")
			convertedRating = 6;
		else if (rating == "D")
			convertedRating = 7;
		return convertedRating;
	}
};
class Scenario : public vector<ScenarioEntry>
{
public:
	Scenario(IssuerData& data)
	{
		for (size_t i = 0, n = data.size(); i < n; i++)
			push_back(ScenarioEntry(data.at(i)));
	}
	vector<ScenarioEntry> entries;
	ScenarioEntry* getByName(string name)
	{
		for (size_t i = 0, n = size(); i < n; i++)
		{
			ScenarioEntry& entry = at(i);
			if (entry.name == name)
				return &entry;
		}
		return nullptr;
	}
};
class Monte
{
public:
	Monte(int N, IssuerData& issuerData)
	{
		for (size_t i = 0; i < N; i++)
		{
			scenarios.push_back(Scenario(issuerData));
		}
	}
	vector<Scenario> scenarios;
};
int main(int argc, char* argv[])
{
	try
	{
		random_device rd;
		mt19937 gen(rd());
		uniform_real_distribution<> dis(0, 1);

		IssuerData issuerData;
		// cout << issuerData.toString();
		PortfolioData portfolioData;
		// cout << portfolioData.toString();
		YieldData yieldData;
		// cout << yieldData.toString();
		Matrix correlationMatrix("correlation_matrix_for_project.csv", 1);
		// cout << correlationMatrix.toString();
		Matrix transitionMatrix("transition_matrix_for_project.csv", 3);
		MatrixRow row{ 0,0,0,0,0,0,0,1 };
		transitionMatrix.push_back(row);
		// cout << transitionMatrix.toString();
		// cout << portfolioData.getReportedValue() << endl;
		// cout << portfolioData.getTheorValue() << endl;

		boost::numeric::ublas::matrix<double> priceMatrix(portfolioData.size(), 8);
		for (size_t i = 0, n1 = priceMatrix.size1(); i < n1; i++)
		{
			PortfolioEntry& row = portfolioData.at(i);
			if (row.instrumentType == "CDS")
			{
				for (size_t j = 0, n2 = priceMatrix.size2() - 1; j < n2; j++)
					priceMatrix(i, j) = dis(gen);
			}
			else
			{
				for (size_t j = 0, n2 = priceMatrix.size2() - 1; j < n2; j++)
					priceMatrix(i, j) = row.cleanPrice;
			}
			priceMatrix(i, priceMatrix.size2() - 1) = row.exprr * 100;
		}
		//cout << priceMatrix << endl;

		int N = 2000;
		Monte monteCarlo(N, issuerData);

		vector<double> portfolioValues;
		vector<double> changeInValues;
		double changeInValueTotal = 0;
		for (size_t i = 0, n1 = monteCarlo.scenarios.size(); i < n1; i++)
		{
			double portfolioValue = 0;
			Scenario& scenario = monteCarlo.scenarios.at(i);
			for (size_t j = 0, n2 = portfolioData.size(); j < n2; j++)
			{
				PortfolioEntry& portfolio = portfolioData.at(j);
				ScenarioEntry* scenarioEntry = scenario.getByName(portfolio.name);
				if (!scenarioEntry)
					throw runtime_error("No known scenario entry for \"" + portfolio.name + "\"");
				portfolioValue = portfolioValue + ((priceMatrix(j, scenarioEntry->rating)*portfolio.notional) * ((double)1/100));
			}
			portfolioValues.push_back(portfolioValue);
			double changeInValue = portfolioValue - portfolioData.getTheorValue();
			changeInValues.push_back(changeInValue);
			changeInValueTotal = changeInValueTotal + changeInValue;
		}

		double meanChangeInValue = changeInValueTotal / (double)changeInValues.size();
		double sq_sum = inner_product(changeInValues.begin(), changeInValues.end(), changeInValues.begin(), 0.0);
		double stdev = sqrt((sq_sum / (double)changeInValues.size()) - (meanChangeInValue * meanChangeInValue));

		cout << changeInValues[0] << endl;
		cout << meanChangeInValue << endl;
		cout << stdev << endl;
	}
	catch (const exception &e)
	{
		cerr << "error: " << e.what() << "\n";
	}
	getchar();
}<commit_msg>Added statistics, VaR, and CVaR calculations<commit_after>/*! CreditMetrics.cpp : Defines the entry point for the console application.
	Note: The given .csv files are not formatted consistently. The .csv parsers below are
	designed to handle the inconsistencies present in the files in a somewhat
	general manner by removing extra characters and white space.
*/
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <functional>
#include <numeric>
#include <cctype>
#include <locale>
#include <random>
#include <boost/algorithm/string.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
using namespace std;

static inline string& trim(string& s) {
	//left
	s.erase(s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace))));
	//right
	s.erase(find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(), s.end());
	return s;
}
static inline int convertInt(string strInt)
{
	trim(strInt);
	return ::atoi(strInt.c_str());
}
static inline double convertDouble(string strDouble)
{
	trim(strDouble);
	return ::atof(strDouble.c_str());
}
static inline double convertPercent(string strPercent)
{
	replace(strPercent.begin(), strPercent.end(), '%', ' ');
	return convertDouble(strPercent) / 100;
}
static inline string sanitizeString(string str)
{
	boost::to_upper(str);
	trim(str);
	return str;
}

template <class R> class CSV : public vector<R>
{
public:
	CSV(const string& filename, size_t skipLines)
	{
		ifstream file(filename);
		if (!file.good())
		{
			throw runtime_error("File does not exist");
		}
		while (!file.eof())
		{
			string strline;
			getline(file, strline);
			if (skipLines > 0)
			{
				skipLines--;
				continue;
			}
			if (strline.empty())
			{
				continue;
			}
			stringstream streamline(strline);
			vector<string> cells;
			while (!streamline.eof())
			{
				string cell;
				getline(streamline, cell, ',');
				if (cell != "")
				{
					cells.push_back(cell);
				}
			}
			if (cells.empty())
			{
				continue;
			}
			push_back(R(cells));
		}
	}
	const string toString()
	{
		string ret;
		for (size_t i = 0, n = size(); i < n; i++)
			ret = ret + at(i).toString() + "\n";
		return ret;
	}
};
class IssuerEntry
{
public:
	IssuerEntry(const vector<string>& cells):
		name(sanitizeString(cells.at(0))),
		rating(sanitizeString(cells.at(1))),
		industry(sanitizeString(cells.at(2)))
	{}
	const string name;
	const string rating;
	const string industry;
	const string toString() const
	{
		return string()
			+ name + "," + rating + "," + industry;
	}
};
class IssuerData : public CSV<IssuerEntry>
{
public:
	IssuerData() : CSV("issuers.csv", 1) { }
	IssuerEntry* getByName(string name)
	{
		for (size_t i = 0, n = size(); i < n; i++)
		{
			IssuerEntry& issuer = at(i);
			if(issuer.name == name)
				return &issuer;
		}
		return nullptr;
	}
};
class PortfolioEntry
{
public:
	PortfolioEntry(const vector<string>& cells) :
		name(sanitizeString(cells.at(0))),
		instrumentType(sanitizeString(cells.at(1))),
		cusip(cells.at(2)),
		notional(convertNotional(cells.at(3))),
		maturity(cells.at(4)),
		coupon(convertPercent(cells.at(5))),
		couponsPerYear(convertInt(cells.at(6))),
		price(convertPrice(cells.at(7))),
		yield(convertPercent(cells.at(8))),
		cleanPrice(convertPrice(cells.at(9))),
		exprr(convertPercent(cells.at(10)))
	{}
	const string name, instrumentType, cusip, maturity;
	const int notional, couponsPerYear;
	const double coupon, price, yield, cleanPrice,exprr;
	const string toString() const
	{
		return string()
			+ name + "," + instrumentType + ","
			+ cusip + "," + to_string(notional) + ","
			+ maturity + "," + to_string(coupon) + ","
			+ to_string(couponsPerYear) + "," + to_string(price) + ","
			+ to_string(yield) + "," + to_string(cleanPrice) + ","
			+ to_string(exprr);
	}
private:
	int convertNotional(string strNotional)
	{
		return convertInt(strNotional);
	}
	double convertPrice(string strPrice)
	{
		replace(strPrice.begin(), strPrice.end(), '$', ' ');
		return convertDouble(strPrice);
	}
};
class PortfolioData : public CSV<PortfolioEntry>
{
public:
	PortfolioData() : CSV("portfolio_for_project.csv", 1) { }
	PortfolioEntry* getByName(string name)
	{
		for (size_t i = 0, n = size(); i < n; i++)
		{
			PortfolioEntry& issuer = at(i);
			if (issuer.name == name)
				return &issuer;
		}
		return nullptr;
	}
	/*! Response for Part B, Step 2) Reported Value
		\return The reported value of the portfolio in millions of dollars
	*/
	double getReportedValue()
	{
		double marketValue = 0;
		for (size_t i = 0, n = size(); i < n; i++)
		{
			PortfolioEntry& row = at(i);
			double targetValue;
			if (row.instrumentType == "CDS")
				targetValue = row.cleanPrice;
			else
				targetValue = row.price;
			marketValue = marketValue + (row.notional*targetValue / 100);
		}
		return marketValue;
	}
	/*! Response for Part B, Step 2) Theoretical Value
	\return The theoretical value of the portfolio in millions of dollars
	*/
	double getTheorValue()
	{
		double theorValue = 0;
		for (size_t i = 0, n = size(); i < n; i++)
		{
			PortfolioEntry& row = at(i);
			theorValue = theorValue + (row.notional*row.cleanPrice / 100);
		}
		return theorValue;
	}
};
class YieldEntry
{
public:
	YieldEntry(const vector<string>& cells):
		term(convertDouble(cells.at(0))),
		aaa(convertPercent(cells.at(1))),
		aa(convertPercent(cells.at(2))),
		a(convertPercent(cells.at(3))),
		bbb(convertPercent(cells.at(4))),
		bb(convertPercent(cells.at(5))),
		b(convertPercent(cells.at(6))),
		ccc(convertPercent(cells.at(7))),
		govt(convertPercent(cells.at(8)))
	{}
	const double term, aaa, aa, a, bbb, bb, b, ccc, govt;
	const string toString() const
	{
		return string()
			+ to_string(term) + "," + to_string(aaa) + ","
			+ to_string(aa) + "," + to_string(a) + ","
			+ to_string(bbb) + "," + to_string(bb) + ","
			+ to_string(b) + "," + to_string(ccc) + ","
			+ to_string(govt);
	}
};
class YieldData : public CSV<YieldEntry>
{
public:
	YieldData() : CSV("yield_curve_for_project.csv", 1) { }
	YieldEntry* getByTerm(double term)
	{
		for (size_t i = 0, n = size(); i < n; i++)
		{
			YieldEntry& yield = at(i);
			if (yield.term == term)
				return &yield;
		}
		return nullptr;
	}
};
class MatrixRow : public vector<double>
{
public:
	MatrixRow(const vector<string>& cells)
	{
		for (size_t i = 1, n = cells.size(); i < n; i++)
		{
			push_back(convertDouble(cells.at(i)));
		}
	}
	using vector::vector;
	string toString()
	{
		string ret;
		for (size_t i = 0, n = size(); i < n; i++)
		{
			if (i > 0)
				ret = ret + ",";
			ret = ret + to_string(at(i));
		}
		return ret;
	}
};
class Matrix : public CSV<MatrixRow>
{
public:
	Matrix(const string& filename, size_t skipLines) : CSV(filename, skipLines) {}
};
class ScenarioEntry
{
public:
	ScenarioEntry(IssuerEntry& entry) :
		name(entry.name),
		rating(convertRating(entry.rating))
	{}
	const string name;
	const int rating;
	const int convertRating(string rating) const
	{
		int convertedRating;
		if (rating == "AAA")
			convertedRating = 0;
		else if (rating == "AA")
			convertedRating = 1;
		else if (rating == "A")
			convertedRating = 2;
		else if (rating == "BBB")
			convertedRating = 3;
		else if (rating == "BB")
			convertedRating = 4;
		else if (rating == "B")
			convertedRating = 5;
		else if (rating == "CCC")
			convertedRating = 6;
		else if (rating == "C")
			convertedRating = 6;
		else if (rating == "D")
			convertedRating = 7;
		return convertedRating;
	}
};
class Scenario : public vector<ScenarioEntry>
{
public:
	Scenario(IssuerData& data)
	{
		for (size_t i = 0, n = data.size(); i < n; i++)
			push_back(ScenarioEntry(data.at(i)));
	}
	vector<ScenarioEntry> entries;
	ScenarioEntry* getByName(string name)
	{
		for (size_t i = 0, n = size(); i < n; i++)
		{
			ScenarioEntry& entry = at(i);
			if (entry.name == name)
				return &entry;
		}
		return nullptr;
	}
};
class Monte
{
public:
	Monte(int N, IssuerData& issuerData)
	{
		for (size_t i = 0; i < N; i++)
		{
			scenarios.push_back(Scenario(issuerData));
		}
	}
	vector<Scenario> scenarios;
};
int main(int argc, char* argv[])
{
	try
	{
		random_device rd;
		mt19937 gen(rd());
		uniform_real_distribution<> dis(0, 1);

		IssuerData issuerData;
		// cout << issuerData.toString();
		PortfolioData portfolioData;
		// cout << portfolioData.toString();
		YieldData yieldData;
		// cout << yieldData.toString();
		Matrix correlationMatrix("correlation_matrix_for_project.csv", 1);
		// cout << correlationMatrix.toString();
		Matrix transitionMatrix("transition_matrix_for_project.csv", 3);
		MatrixRow row{ 0,0,0,0,0,0,0,1 };
		transitionMatrix.push_back(row);
		// cout << transitionMatrix.toString();
		cout << "The initial reported portfolio value is " << portfolioData.getReportedValue() << endl;
		cout << "The initial theoretical portfolio value is " << portfolioData.getTheorValue() << endl;

		boost::numeric::ublas::matrix<double> priceMatrix(portfolioData.size(), 8);
		for (size_t i = 0, n1 = priceMatrix.size1(); i < n1; i++)
		{
			PortfolioEntry& row = portfolioData.at(i);
			if (row.instrumentType == "CDS")
			{
				for (size_t j = 0, n2 = priceMatrix.size2() - 1; j < n2; j++)
					priceMatrix(i, j) = dis(gen);
			}
			else
			{
				for (size_t j = 0, n2 = priceMatrix.size2() - 1; j < n2; j++)
					priceMatrix(i, j) = row.cleanPrice;
			}
			priceMatrix(i, priceMatrix.size2() - 1) = row.exprr * 100;
		}
		//cout << priceMatrix << endl;

		int N = 2000;
		Monte monteCarlo(N, issuerData);

		vector<double> portfolioValues;
		vector<double> changeInValues;
		double changeInValueTotal = 0;
		for (size_t i = 0, n1 = monteCarlo.scenarios.size(); i < n1; i++)
		{
			double portfolioValue = 0;
			Scenario& scenario = monteCarlo.scenarios.at(i);
			for (size_t j = 0, n2 = portfolioData.size(); j < n2; j++)
			{
				PortfolioEntry& portfolio = portfolioData.at(j);
				ScenarioEntry* scenarioEntry = scenario.getByName(portfolio.name);
				if (!scenarioEntry)
					throw runtime_error("No known scenario entry for \"" + portfolio.name + "\"");
				portfolioValue = portfolioValue + ((priceMatrix(j, scenarioEntry->rating)*portfolio.notional) * ((double)1/100));
			}
			portfolioValues.push_back(portfolioValue);
			double changeInValue = portfolioValue - portfolioData.getTheorValue();
			changeInValues.push_back(changeInValue);
			changeInValueTotal = changeInValueTotal + changeInValue;
		}

		double meanChangeInValue = changeInValueTotal / (double)changeInValues.size();
		double sq_sum = inner_product(changeInValues.begin(), changeInValues.end(), changeInValues.begin(), 0.0);
		double stdev = sqrt((sq_sum / (double)changeInValues.size()) - (meanChangeInValue * meanChangeInValue));

		//cout << changeInValues[0] << endl;
		cout << "The average change in value is " << meanChangeInValue << endl;
		cout << "The standard deviations of the change in value is " << stdev << endl;

		sort(changeInValues.begin(), changeInValues.end());
		double var95Percentile = changeInValues.at((int) (changeInValues.size()*0.05));
		double var99Percentile = changeInValues.at((int) (changeInValues.size()*0.01));

		double percentile = 98;
		double cvar = 0;
		for (size_t i = 0, n1 = (int)(((100-percentile)*0.01)*changeInValues.size()); i < n1; i++)
		{
			cvar = cvar + changeInValues.at(i);
		}
		double cvarPercentile = cvar / (double)(((100 - percentile)*0.01)*changeInValues.size());

		cout << "VaR at the 95th percentile is " << var95Percentile << endl;
		cout << "VaR at the 99th percentile is " << var99Percentile << endl;
		cout << "VaR at the desired percentile is " << cvarPercentile << endl;

	}
	catch (const exception &e)
	{
		cerr << "error: " << e.what() << "\n";
	}
	getchar();
}<|endoftext|>


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

#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

#include <boost/filesystem.hpp>
#include <boost/format.hpp>

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <radical/radiometric_response.h>

#include "grabbers/grabber.h"

#include "utils/plot_radiometric_response.h"
#include "utils/program_options.h"

#include "calibration.h"
#include "dataset.h"
#include "dataset_collection.h"
#include "engel_calibration.h"

#if HAVE_CERES
#include "debevec_calibration.h"
#define DEFAULT_METHOD "debevec"
#else
#define DEFAULT_METHOD "engel"
#endif

class Options : public OptionsBase {
 public:
  std::string data_source = "";
  std::string output;
  double convergence_threshold = 1e-5;
  std::string calibration_method = DEFAULT_METHOD;
  bool no_visualization = false;
  std::string save_dataset = "";
  DatasetCollection::Parameters dc;
  unsigned int verbosity = 1;
  unsigned int num_pixels = 5;
  bool interactive = false;
  double smoothing = 50;

 protected:
  virtual void addOptions(boost::program_options::options_description& desc) override {
    namespace po = boost::program_options;
    desc.add_options()("output,o", po::value<std::string>(&output),
                       "Output filename with calibrated response function (default: camera model name + \".\" + camera "
                       "serial number + \".crf\" suffix)");
    desc.add_options()("threshold,t", po::value<double>(&convergence_threshold),
                       "Threshold for energy update after which convergence is declared (default: 1e-5)");
    desc.add_options()("method,m", po::value<std::string>(&calibration_method),
                       "Calibration method to use (default: engel)");
    desc.add_options()("no-visualization", po::bool_switch(&no_visualization),
                       "Do not visualize the calibration process and results");
    desc.add_options()("save-dataset,s", po::value<std::string>(&save_dataset),
                       "Save collected dataset in the given directory");
    desc.add_options()("verbosity,v", po::value<unsigned int>(&verbosity)->default_value(verbosity),
                       "Verbosity level (0 - silent, 1 - normal, 2 - verbose)");
    desc.add_options()("num-pixels", po::value<unsigned int>(&num_pixels)->default_value(num_pixels),
                       "Number of pixels");
    desc.add_options()("interactive", po::bool_switch(&interactive), "Interactive");
    desc.add_options()("smoothing", po::value<double>(&smoothing)->default_value(smoothing), "Smoothing lambda");

    boost::program_options::options_description dcopt("Data collection");
    dcopt.add_options()("exposure-min", po::value<int>(&dc.exposure_min),
                        "Minimum exposure (default: depends on the camera)");
    dcopt.add_options()("exposure-max", po::value<int>(&dc.exposure_max),
                        "Maximum exposure (default: depends on the camera)");
    dcopt.add_options()("factor,f", po::value<float>(&dc.exposure_factor),
                        "Multiplication factor for exposure (default: to cover desired exposure range in 30 steps)");
    dcopt.add_options()("average,a",
                        po::value<unsigned int>(&dc.num_average_frames)->default_value(dc.num_average_frames),
                        "Number of consecutive frames to average into each image");
    dcopt.add_options()("images,i", po::value<unsigned int>(&dc.num_images)->default_value(dc.num_images),
                        "Number of images to take at each exposure setting");
    dcopt.add_options()("lag,l",
                        po::value<unsigned int>(&dc.exposure_control_lag)->default_value(dc.exposure_control_lag),
                        "Number of frames to skip after changing exposure setting");
    dcopt.add_options()("valid-min",
                        po::value<unsigned int>(&dc.valid_intensity_min)->default_value(dc.valid_intensity_min),
                        "Minimum valid intensity value of the sensor");
    dcopt.add_options()("valid-max",
                        po::value<unsigned int>(&dc.valid_intensity_max)->default_value(dc.valid_intensity_max),
                        "Maximum valid intensity value of the sensor");
    dcopt.add_options()("bloom-radius", po::value<unsigned int>(&dc.bloom_radius)->default_value(dc.bloom_radius),
                        "Radius of the blooming effect");
    desc.add(dcopt);
  }

  virtual void addPositional(boost::program_options::options_description& desc,
                             boost::program_options::positional_options_description& positional) override {
    namespace po = boost::program_options;
    desc.add_options()("data-source", po::value<std::string>(&data_source),
                       "Data source, either a camera (\"asus\", \"intel\"), or a path to dataset");
    positional.add("data-source", -1);
  }

  virtual void printHelp() override {
    std::cout << "Usage: calibrate_radiometric_response [options] <data-source>" << std::endl;
    std::cout << "" << std::endl;
    std::cout << "Calibrate radiometric response of a camera. Two algorithms are available:" << std::endl;
    std::cout << " * Engel et al. (A Photometrically Calibrated Benchmark For Monocular Visual Odometry)" << std::endl;
    std::cout << " * Debevec and Malik (Recovering High Dynamic Range Radiance Maps from Photographs)" << std::endl;
    std::cout << "" << std::endl;
    std::cout << "Working range of the sensor can be specified with --valid-min/--valid-max options." << std::endl;
    std::cout << "Pixels with intensity values outside this range do not contribute to the energy and" << std::endl;
    std::cout << "irradiance computation, however radiometric response is estimated for them as well." << std::endl;
    std::cout << "" << std::endl;
  }
};

int main(int argc, const char** argv) {
  Options options;
  if (!options.parse(argc, argv))
    return 1;

  auto imshow = [&options](const cv::Mat& image, int w = -1) {
    if (!options.no_visualization) {
      cv::imshow("Calibration", image);
      cv::waitKey(w);
    }
  };

  auto data = Dataset::load(options.data_source);
  if (data) {
    if (!options("output")) {
      auto dir = boost::filesystem::canonical(options.data_source);
      options.output = (dir / dir.filename()).native() + ".crf";
    }
    if (options.verbosity)
      std::cout << "Loaded dataset from: " << options.data_source << std::endl;
  } else {
    grabbers::Grabber::Ptr grabber;

    try {
      grabber = grabbers::createGrabber(options.data_source);
    } catch (grabbers::GrabberException& e) {
      std::cerr << "Failed to create a grabber"
                << (options.data_source != "" ? " for camera " + options.data_source : "") << std::endl;
      return 1;
    }

    grabber->setAutoExposureEnabled(false);
    grabber->setAutoWhiteBalanceEnabled(false);

    if (!options("output"))
      options.output = grabber->getCameraUID() + ".crf";
    if (!options("exposure-min"))
      options.dc.exposure_min = grabber->getExposureRange().first;
    if (!options("exposure-max"))
      options.dc.exposure_max = grabber->getExposureRange().second;
    if (!options("factor"))
      options.dc.exposure_factor = std::pow(options.dc.exposure_max / options.dc.exposure_min, 1.0 / 30);

    // Change exposure to requested min value, wait some time until it works
    cv::Mat frame;
    for (size_t i = 0; i < 100; ++i) {
      grabber->grabFrame(frame);
      imshow(frame, 30);
      grabber->setExposure(options.dc.exposure_min);
    }

    DatasetCollection data_collection(grabber, options.dc);

    while (grabber->hasMoreFrames()) {
      grabber->grabFrame(frame);
      imshow(frame, 30);
      if (data_collection.addFrame(frame))
        break;
    }

    data = data_collection.getDataset();

    if (options.save_dataset != "") {
      if (options.verbosity)
        std::cout << "Saving dataset to: " << options.save_dataset << std::endl;
      data->save(options.save_dataset);
      std::ofstream file(options.save_dataset + "/DESCRIPTION.txt");
      if (file.is_open()) {
        file << "Camera: " << grabber->getCameraUID() << std::endl;
        file << "Resolution: " << data->getImageSize() << std::endl;
        file << "Exposure range: " << options.dc.exposure_min << " " << options.dc.exposure_max << std::endl;
        file << "Exposure factor: " << options.dc.exposure_factor << std::endl;
        file << "Images per exposure time: " << options.dc.num_images << std::endl;
        file << "Frames averaged into an image: " << options.dc.num_average_frames << std::endl;
        file.close();
      }
    }
  }

  Calibration::Ptr calibration;

  if (options.calibration_method == "engel") {
    auto cal = std::make_shared<EngelCalibration>();
    cal->setConvergenceThreshold(options.convergence_threshold);
    calibration = cal;
  } else if (options.calibration_method == "debevec") {
#if HAVE_CERES
    auto cal = std::make_shared<DebevecCalibration>();
    cal->setNumPixels(options.num_pixels);
    cal->setSmoothingLambda(options.smoothing);
    calibration = cal;
#else
    std::cerr << "Debevec calibration is not supported because the project was compiled without Ceres.\n";
    return 2;
#endif
  } else {
    std::cerr << "Unknown calibration method: " << options.calibration_method
              << ". Please specify \"engel\" or \"debevec\".\n";
    return 1;
  }

  auto limshow = [=](const cv::Mat& image) {
    cv::imshow("Calibration", image);
    cv::waitKey(options.interactive ? -1 : 1);
  };

  calibration->setValidPixelRange(options.dc.valid_intensity_min, options.dc.valid_intensity_max);
  calibration->setVerbosity(options.verbosity);
  if (!options.no_visualization)
    calibration->setVisualizeProgress(limshow);

  cv::Mat response = calibration->calibrate(*data);

  if (options.verbosity)
    std::cout << "Done, writing response to: " << options.output << std::endl;
  radical::RadiometricResponse rr(response);
  rr.save(options.output);

  imshow(utils::plotRadiometricResponse(rr));

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

#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

#include <boost/filesystem.hpp>
#include <boost/format.hpp>

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <radical/radiometric_response.h>

#include "grabbers/grabber.h"

#include "utils/plot_radiometric_response.h"
#include "utils/program_options.h"

#include "calibration.h"
#include "dataset.h"
#include "dataset_collection.h"
#include "engel_calibration.h"

#if HAVE_CERES
#include "debevec_calibration.h"
#define DEFAULT_METHOD "debevec"
#else
#define DEFAULT_METHOD "engel"
#endif

class Options : public OptionsBase {
 public:
  std::string data_source = "";
  std::string output;
  double convergence_threshold = 1e-5;
  std::string calibration_method = DEFAULT_METHOD;
  bool no_visualization = false;
  std::string save_dataset = "";
  DatasetCollection::Parameters dc;
  unsigned int verbosity = 1;
  unsigned int num_pixels = 5;
  bool interactive = false;
  double smoothing = 50;
  bool print = false;

 protected:
  virtual void addOptions(boost::program_options::options_description& desc) override {
    namespace po = boost::program_options;
    desc.add_options()("output,o", po::value<std::string>(&output),
                       "Output filename with calibrated response function (default: camera model name + \".\" + camera "
                       "serial number + \".crf\" suffix)");
    desc.add_options()("threshold,t", po::value<double>(&convergence_threshold),
                       "Threshold for energy update after which convergence is declared (default: 1e-5)");
    desc.add_options()("method,m", po::value<std::string>(&calibration_method),
                       "Calibration method to use (default: engel)");
    desc.add_options()("no-visualization", po::bool_switch(&no_visualization),
                       "Do not visualize the calibration process and results");
    desc.add_options()("save-dataset,s", po::value<std::string>(&save_dataset),
                       "Save collected dataset in the given directory");
    desc.add_options()("verbosity,v", po::value<unsigned int>(&verbosity)->default_value(verbosity),
                       "Verbosity level (0 - silent, 1 - normal, 2 - verbose)");
    desc.add_options()("num-pixels", po::value<unsigned int>(&num_pixels)->default_value(num_pixels),
                       "Number of pixels");
    desc.add_options()("interactive", po::bool_switch(&interactive), "Interactive");
    desc.add_options()("smoothing", po::value<double>(&smoothing)->default_value(smoothing), "Smoothing lambda");
    desc.add_options()("print", po::bool_switch(&print), "Print calibrated response function to stdout");

    boost::program_options::options_description dcopt("Data collection");
    dcopt.add_options()("exposure-min", po::value<int>(&dc.exposure_min),
                        "Minimum exposure (default: depends on the camera)");
    dcopt.add_options()("exposure-max", po::value<int>(&dc.exposure_max),
                        "Maximum exposure (default: depends on the camera)");
    dcopt.add_options()("factor,f", po::value<float>(&dc.exposure_factor),
                        "Multiplication factor for exposure (default: to cover desired exposure range in 30 steps)");
    dcopt.add_options()("average,a",
                        po::value<unsigned int>(&dc.num_average_frames)->default_value(dc.num_average_frames),
                        "Number of consecutive frames to average into each image");
    dcopt.add_options()("images,i", po::value<unsigned int>(&dc.num_images)->default_value(dc.num_images),
                        "Number of images to take at each exposure setting");
    dcopt.add_options()("lag,l",
                        po::value<unsigned int>(&dc.exposure_control_lag)->default_value(dc.exposure_control_lag),
                        "Number of frames to skip after changing exposure setting");
    dcopt.add_options()("valid-min",
                        po::value<unsigned int>(&dc.valid_intensity_min)->default_value(dc.valid_intensity_min),
                        "Minimum valid intensity value of the sensor");
    dcopt.add_options()("valid-max",
                        po::value<unsigned int>(&dc.valid_intensity_max)->default_value(dc.valid_intensity_max),
                        "Maximum valid intensity value of the sensor");
    dcopt.add_options()("bloom-radius", po::value<unsigned int>(&dc.bloom_radius)->default_value(dc.bloom_radius),
                        "Radius of the blooming effect");
    desc.add(dcopt);
  }

  virtual void addPositional(boost::program_options::options_description& desc,
                             boost::program_options::positional_options_description& positional) override {
    namespace po = boost::program_options;
    desc.add_options()("data-source", po::value<std::string>(&data_source),
                       "Data source, either a camera (\"asus\", \"intel\"), or a path to dataset");
    positional.add("data-source", -1);
  }

  virtual void printHelp() override {
    std::cout << "Usage: calibrate_radiometric_response [options] <data-source>" << std::endl;
    std::cout << "" << std::endl;
    std::cout << "Calibrate radiometric response of a camera. Two algorithms are available:" << std::endl;
    std::cout << " * Engel et al. (A Photometrically Calibrated Benchmark For Monocular Visual Odometry)" << std::endl;
    std::cout << " * Debevec and Malik (Recovering High Dynamic Range Radiance Maps from Photographs)" << std::endl;
    std::cout << "" << std::endl;
    std::cout << "Working range of the sensor can be specified with --valid-min/--valid-max options." << std::endl;
    std::cout << "Pixels with intensity values outside this range do not contribute to the energy and" << std::endl;
    std::cout << "irradiance computation, however radiometric response is estimated for them as well." << std::endl;
    std::cout << "" << std::endl;
  }
};

int main(int argc, const char** argv) {
  Options options;
  if (!options.parse(argc, argv))
    return 1;

  auto imshow = [&options](const cv::Mat& image, int w = -1) {
    if (!options.no_visualization) {
      cv::imshow("Calibration", image);
      cv::waitKey(w);
    }
  };

  auto data = Dataset::load(options.data_source);
  if (data) {
    if (!options("output")) {
      auto dir = boost::filesystem::canonical(options.data_source);
      options.output = (dir / dir.filename()).native() + ".crf";
    }
    if (options.verbosity)
      std::cout << "Loaded dataset from: " << options.data_source << std::endl;
  } else {
    grabbers::Grabber::Ptr grabber;

    try {
      grabber = grabbers::createGrabber(options.data_source);
    } catch (grabbers::GrabberException& e) {
      std::cerr << "Failed to create a grabber"
                << (options.data_source != "" ? " for camera " + options.data_source : "") << std::endl;
      return 1;
    }

    grabber->setAutoExposureEnabled(false);
    grabber->setAutoWhiteBalanceEnabled(false);

    if (!options("output"))
      options.output = grabber->getCameraUID() + ".crf";
    if (!options("exposure-min"))
      options.dc.exposure_min = grabber->getExposureRange().first;
    if (!options("exposure-max"))
      options.dc.exposure_max = grabber->getExposureRange().second;
    if (!options("factor"))
      options.dc.exposure_factor = std::pow(options.dc.exposure_max / options.dc.exposure_min, 1.0 / 30);

    // Change exposure to requested min value, wait some time until it works
    cv::Mat frame;
    for (size_t i = 0; i < 100; ++i) {
      grabber->grabFrame(frame);
      imshow(frame, 30);
      grabber->setExposure(options.dc.exposure_min);
    }

    DatasetCollection data_collection(grabber, options.dc);

    while (grabber->hasMoreFrames()) {
      grabber->grabFrame(frame);
      imshow(frame, 30);
      if (data_collection.addFrame(frame))
        break;
    }

    data = data_collection.getDataset();

    if (options.save_dataset != "") {
      if (options.verbosity)
        std::cout << "Saving dataset to: " << options.save_dataset << std::endl;
      data->save(options.save_dataset);
      std::ofstream file(options.save_dataset + "/DESCRIPTION.txt");
      if (file.is_open()) {
        file << "Camera: " << grabber->getCameraUID() << std::endl;
        file << "Resolution: " << data->getImageSize() << std::endl;
        file << "Exposure range: " << options.dc.exposure_min << " " << options.dc.exposure_max << std::endl;
        file << "Exposure factor: " << options.dc.exposure_factor << std::endl;
        file << "Images per exposure time: " << options.dc.num_images << std::endl;
        file << "Frames averaged into an image: " << options.dc.num_average_frames << std::endl;
        file.close();
      }
    }
  }

  Calibration::Ptr calibration;

  if (options.calibration_method == "engel") {
    auto cal = std::make_shared<EngelCalibration>();
    cal->setConvergenceThreshold(options.convergence_threshold);
    calibration = cal;
  } else if (options.calibration_method == "debevec") {
#if HAVE_CERES
    auto cal = std::make_shared<DebevecCalibration>();
    cal->setNumPixels(options.num_pixels);
    cal->setSmoothingLambda(options.smoothing);
    calibration = cal;
#else
    std::cerr << "Debevec calibration is not supported because the project was compiled without Ceres.\n";
    return 2;
#endif
  } else {
    std::cerr << "Unknown calibration method: " << options.calibration_method
              << ". Please specify \"engel\" or \"debevec\".\n";
    return 1;
  }

  auto limshow = [=](const cv::Mat& image) {
    cv::imshow("Calibration", image);
    cv::waitKey(options.interactive ? -1 : 1);
  };

  calibration->setValidPixelRange(options.dc.valid_intensity_min, options.dc.valid_intensity_max);
  calibration->setVerbosity(options.verbosity);
  if (!options.no_visualization)
    calibration->setVisualizeProgress(limshow);

  cv::Mat response = calibration->calibrate(*data);

  if (options.verbosity)
    std::cout << "Done, writing response to: " << options.output << std::endl;
  radical::RadiometricResponse rr(response);
  rr.save(options.output);

  imshow(utils::plotRadiometricResponse(rr));

  if (options.print) {
    std::vector<cv::Mat> response_channels;
    cv::split(response, response_channels);
    for (const auto& ch : response_channels) {
      for (size_t i = 0; i < ch.total(); ++i)
        std::cout << ch.at<float>(i) << " ";
      std::cout << std::endl;
    }
  }

  return 0;
}
<|endoftext|>


<commit_before><commit_msg>Changes to the wheel separation<commit_after><|endoftext|>


<commit_before>#ifndef _DNACOMMON_BABEDEAD_HPP_
#define _DNACOMMON_BABEDEAD_HPP_

#include "BlenderConnection.hpp"
#include "zeus/Math.hpp"

namespace DataSpec
{

template<class BabeDeadLight>
void ReadBabeDeadLightToBlender(hecl::BlenderConnection::PyOutStream& os,
                                const BabeDeadLight& light, unsigned s, unsigned l)
{
    switch (light.lightType)
    {
    case BabeDeadLight::LightType::LocalAmbient:
    case BabeDeadLight::LightType::LocalAmbient2:
        os.format("bg_node.inputs[0].default_value = (%f,%f,%f,1.0)\n"
                  "bg_node.inputs[1].default_value = %f\n",
                  light.color.vec[0], light.color.vec[1], light.color.vec[2],
                  light.q / 8.0);
        return;
    case BabeDeadLight::LightType::Directional:
        os.format("lamp = bpy.data.lamps.new('LAMP_%01u_%03u', 'SUN')\n"
                  "lamp_obj = bpy.data.objects.new(lamp.name, lamp)\n"
                  "lamp_obj.rotation_mode = 'QUATERNION'\n"
                  "lamp_obj.rotation_quaternion = Vector((0,0,-1)).rotation_difference(Vector((%f,%f,%f)))\n"
                  "\n", s, l,
                  light.direction.vec[0], light.direction.vec[1], light.direction.vec[2]);
        break;
    case BabeDeadLight::LightType::Custom:
        os.format("lamp = bpy.data.lamps.new('LAMP_%01u_%03u', 'POINT')\n"
                  "lamp_obj = bpy.data.objects.new(lamp.name, lamp)\n"
                  "\n", s, l);
        break;
    case BabeDeadLight::LightType::Spot:
    case BabeDeadLight::LightType::Spot2:
        os.format("lamp = bpy.data.lamps.new('LAMP_%01u_%03u', 'SPOT')\n"
                  "lamp.spot_size = %f\n"
                  "lamp_obj = bpy.data.objects.new(lamp.name, lamp)\n"
                  "lamp_obj.rotation_mode = 'QUATERNION'\n"
                  "lamp_obj.rotation_quaternion = Vector((0,0,-1)).rotation_difference(Vector((%f,%f,%f)))\n"
                  "\n", s, l,
                  zeus::degToRad(light.spotCutoff),
                  light.direction.vec[0], light.direction.vec[1], light.direction.vec[2]);
        break;
    default: return;
    }

    os.format("lamp.retro_layer = %u\n"
              "lamp.retro_origtype = %u\n"
              "lamp.falloff_type = 'INVERSE_COEFFICIENTS'\n"
              "lamp.use_nodes = True\n"
              "falloff_node = lamp.node_tree.nodes.new('ShaderNodeLightFalloff')\n"
              "lamp.energy = 0.0\n"
              "falloff_node.inputs[0].default_value = %f\n"
              "hue_sat_node = lamp.node_tree.nodes.new('ShaderNodeHueSaturation')\n"
              "hue_sat_node.inputs[1].default_value = 1.25\n"
              "hue_sat_node.inputs[4].default_value = (%f,%f,%f,1.0)\n"
              "lamp.node_tree.links.new(hue_sat_node.outputs[0], lamp.node_tree.nodes['Emission'].inputs[0])\n"
              "lamp_obj.location = (%f,%f,%f)\n"
              "bpy.context.scene.objects.link(lamp_obj)\n"
              "\n", s, light.lightType, light.q / 8.0,
              light.color.vec[0], light.color.vec[1], light.color.vec[2],
              light.position.vec[0], light.position.vec[1], light.position.vec[2]);

    switch (light.falloff)
    {
    case BabeDeadLight::Falloff::Constant:
        os << "falloff_node.inputs[0].default_value *= 75.0\n"
              "lamp.node_tree.links.new(falloff_node.outputs[2], lamp.node_tree.nodes['Emission'].inputs[1])\n";
        os.format("lamp.constant_coefficient = 2.0 / %f\n", light.q);
        break;
    case BabeDeadLight::Falloff::Linear:
        os << "lamp.node_tree.links.new(falloff_node.outputs[1], lamp.node_tree.nodes['Emission'].inputs[1])\n";
        os.format("lamp.linear_coefficient = 250 / %f\n", light.q);
        break;
    case BabeDeadLight::Falloff::Quadratic:
        os << "lamp.node_tree.links.new(falloff_node.outputs[0], lamp.node_tree.nodes['Emission'].inputs[1])\n";
        os.format("lamp.quadratic_coefficient = 25000 / %f\n", light.q);
        break;
    default: break;
    }
}

}

#endif // _DNACOMMON_BABEDEAD_HPP_
<commit_msg>BabeDead python fix<commit_after>#ifndef _DNACOMMON_BABEDEAD_HPP_
#define _DNACOMMON_BABEDEAD_HPP_

#include "BlenderConnection.hpp"
#include "zeus/Math.hpp"
#include <cfloat>

namespace DataSpec
{

template<class BabeDeadLight>
void ReadBabeDeadLightToBlender(hecl::BlenderConnection::PyOutStream& os,
                                const BabeDeadLight& light, unsigned s, unsigned l)
{
    switch (light.lightType)
    {
    case BabeDeadLight::LightType::LocalAmbient:
    case BabeDeadLight::LightType::LocalAmbient2:
        os.format("bg_node.inputs[0].default_value = (%f,%f,%f,1.0)\n"
                  "bg_node.inputs[1].default_value = %f\n",
                  light.color.vec[0], light.color.vec[1], light.color.vec[2],
                  light.q / 8.0);
        return;
    case BabeDeadLight::LightType::Directional:
        os.format("lamp = bpy.data.lamps.new('LAMP_%01u_%03u', 'SUN')\n"
                  "lamp_obj = bpy.data.objects.new(lamp.name, lamp)\n"
                  "lamp_obj.rotation_mode = 'QUATERNION'\n"
                  "lamp_obj.rotation_quaternion = Vector((0,0,-1)).rotation_difference(Vector((%f,%f,%f)))\n"
                  "\n", s, l,
                  light.direction.vec[0], light.direction.vec[1], light.direction.vec[2]);
        break;
    case BabeDeadLight::LightType::Custom:
        os.format("lamp = bpy.data.lamps.new('LAMP_%01u_%03u', 'POINT')\n"
                  "lamp_obj = bpy.data.objects.new(lamp.name, lamp)\n"
                  "\n", s, l);
        break;
    case BabeDeadLight::LightType::Spot:
    case BabeDeadLight::LightType::Spot2:
        os.format("lamp = bpy.data.lamps.new('LAMP_%01u_%03u', 'SPOT')\n"
                  "lamp.spot_size = %f\n"
                  "lamp_obj = bpy.data.objects.new(lamp.name, lamp)\n"
                  "lamp_obj.rotation_mode = 'QUATERNION'\n"
                  "lamp_obj.rotation_quaternion = Vector((0,0,-1)).rotation_difference(Vector((%f,%f,%f)))\n"
                  "\n", s, l,
                  zeus::degToRad(light.spotCutoff),
                  light.direction.vec[0], light.direction.vec[1], light.direction.vec[2]);
        break;
    default: return;
    }

    os.format("lamp.retro_layer = %u\n"
              "lamp.retro_origtype = %u\n"
              "lamp.falloff_type = 'INVERSE_COEFFICIENTS'\n"
              "lamp.constant_coefficient = 0\n"
              "lamp.use_nodes = True\n"
              "falloff_node = lamp.node_tree.nodes.new('ShaderNodeLightFalloff')\n"
              "lamp.energy = 0.0\n"
              "falloff_node.inputs[0].default_value = %f\n"
              "hue_sat_node = lamp.node_tree.nodes.new('ShaderNodeHueSaturation')\n"
              "hue_sat_node.inputs[1].default_value = 1.25\n"
              "hue_sat_node.inputs[4].default_value = (%f,%f,%f,1.0)\n"
              "lamp.node_tree.links.new(hue_sat_node.outputs[0], lamp.node_tree.nodes['Emission'].inputs[0])\n"
              "lamp_obj.location = (%f,%f,%f)\n"
              "bpy.context.scene.objects.link(lamp_obj)\n"
              "\n", s, light.lightType, light.q / 8.0,
              light.color.vec[0], light.color.vec[1], light.color.vec[2],
              light.position.vec[0], light.position.vec[1], light.position.vec[2]);

    switch (light.falloff)
    {
    case BabeDeadLight::Falloff::Constant:
        os << "falloff_node.inputs[0].default_value *= 75.0\n"
              "lamp.node_tree.links.new(falloff_node.outputs[2], lamp.node_tree.nodes['Emission'].inputs[1])\n";
        if (light.q > FLT_EPSILON)
            os.format("lamp.constant_coefficient = 2.0 / %f\n", light.q);
        break;
    case BabeDeadLight::Falloff::Linear:
        os << "lamp.node_tree.links.new(falloff_node.outputs[1], lamp.node_tree.nodes['Emission'].inputs[1])\n";
        if (light.q > FLT_EPSILON)
            os.format("lamp.linear_coefficient = 250 / %f\n", light.q);
        break;
    case BabeDeadLight::Falloff::Quadratic:
        os << "lamp.node_tree.links.new(falloff_node.outputs[0], lamp.node_tree.nodes['Emission'].inputs[1])\n";
        if (light.q > FLT_EPSILON)
            os.format("lamp.quadratic_coefficient = 25000 / %f\n", light.q);
        break;
    default: break;
    }
}

}

#endif // _DNACOMMON_BABEDEAD_HPP_
<|endoftext|>


<commit_before>/***********************************
   Copyright 2017 Ravishankar Mathur

   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 <OpenFrames/FrameManager.hpp>
#include <OpenFrames/Model.hpp>
#include <OpenFrames/WindowProxy.hpp>
#include <osg/ArgumentParser>

using namespace OpenFrames;

/** This example loads and displays a model using OpenFrames.
  **/
int main(int argc, char** argv)
{
  // Parse user inputs
  osg::ArgumentParser arguments(&argc, argv);

  // Use VR mode
  bool useVR = arguments.read("--vr");
  unsigned int width = 640, height = 480;
  if (useVR) // Switch to VR mirror window size
  {
    width = 1080 / 2;
    height = 1200 / 2;
  }

  // Set VR world units per meter scale
  double worldUnitsPerMeter = 1.0;
  arguments.read("--vrScale", worldUnitsPerMeter);
  if (worldUnitsPerMeter < 1.0)
  {
    OSG_NOTICE << "VR WorldUnits/Meter ratio must be >= 1.0. Setting to 1.0" << std::endl;
    worldUnitsPerMeter = 1.0;
  }

  // Get model filename
  std::string filename;
  for (int pos = 1; pos < arguments.argc(); ++pos)
  {
    if (!arguments.isOption(pos))
    {
      filename = arguments[pos];
      break;
    }
  }

  if (filename.length() == 0)
  {
    OSG_NOTICE << "Please specify a filename" << std::endl;
    return 1;
  }

	// Create the window interface
	unsigned int x = 30, y = 30;
	unsigned int nrows = 1, ncols = 1;
	bool isEmbedded = false;
	osg::ref_ptr<WindowProxy> myWindow = new WindowProxy(x, y, width, height, nrows, ncols, isEmbedded, useVR);
	myWindow->setWorldUnitsPerMeter(worldUnitsPerMeter);
	myWindow->setWorldUnitsPerMeterLimits(1.0, DBL_MAX);

	// Create Model for Barnegat tileset
	Model *theModel = new Model("Model", 0.5, 0.5, 0.5, 0.9);
  if (!theModel->setModel(filename))
  {
    return 1;
  }
  theModel->showNameLabel(false);

	// Create a manager to handle the spatial scene
	FrameManager* fm = new FrameManager;
	fm->setFrame(theModel);

	// Set up the scene
	myWindow->setScene(fm, 0, 0);
	//myWindow->getGridPosition(0, 0)->setBackgroundColor(0, 0, 0);

	myWindow->startThread(); // Start window animation
	myWindow->join(); // Wait for window animation to finish

	return 0;
}
<commit_msg>Formatting updates<commit_after>/***********************************
   Copyright 2017 Ravishankar Mathur

   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 <OpenFrames/FrameManager.hpp>
#include <OpenFrames/Model.hpp>
#include <OpenFrames/WindowProxy.hpp>
#include <osg/ArgumentParser>

using namespace OpenFrames;

/** This example loads and displays a model using OpenFrames.
  **/
int main(int argc, char** argv)
{
  // Parse user inputs
  osg::ArgumentParser arguments(&argc, argv);

  // Use VR mode
  bool useVR = arguments.read("--vr");
  unsigned int width = 800, height = 600;
  if (useVR) // Switch to VR mirror window size
  {
    width = 1080 / 2;
    height = 1200 / 2;
  }

  // Set VR world units per meter scale
  double worldUnitsPerMeter = 1.0;
  arguments.read("--vrScale", worldUnitsPerMeter);
  if (worldUnitsPerMeter < 1.0)
  {
    OSG_NOTICE << "VR WorldUnits/Meter ratio must be >= 1.0. Setting to 1.0" << std::endl;
    worldUnitsPerMeter = 1.0;
  }

  // Get model filename
  std::string filename;
  for (int pos = 1; pos < arguments.argc(); ++pos)
  {
    if (!arguments.isOption(pos))
    {
      filename = arguments[pos];
      break;
    }
  }

  if (filename.length() == 0)
  {
    OSG_NOTICE << "Please specify a filename" << std::endl;
    return 1;
  }

  // Create the window interface
  unsigned int x = 30, y = 30;
  unsigned int nrows = 1, ncols = 1;
  bool isEmbedded = false;
  osg::ref_ptr<WindowProxy> myWindow = new WindowProxy(x, y, width, height, nrows, ncols, isEmbedded, useVR);
  myWindow->setWorldUnitsPerMeter(worldUnitsPerMeter);
  myWindow->setWorldUnitsPerMeterLimits(1.0, DBL_MAX);

  // Create Model for to hold user-specified model
  Model *theModel = new Model("Model", 0.5, 0.5, 0.5, 0.9);
  if (!theModel->setModel(filename))
  {
    return 1;
  }
  theModel->showNameLabel(false);

  // Create a frame manager to handle the scene
  FrameManager* fm = new FrameManager;
  fm->setFrame(theModel);

  // Set up the scene
  myWindow->setScene(fm, 0, 0);
  //myWindow->getGridPosition(0, 0)->setBackgroundColor(0, 0, 0);

  myWindow->startThread(); // Start window animation
  myWindow->join(); // Wait for window animation to finish

  return 0;
}
<|endoftext|>


<commit_before>
/**************************************************************************
 * Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. *
 * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for          *
 * full copyright notice.                                                 *
 **************************************************************************/

//************************************************************************
///
/// \file emcal_digits.C
/// \brief Visualize EMCAL digits
///
/// A macro to read and visualize EMCAL digits
///
/// \author Magali Estienne <magali.estienne@cern.ch>, SUBATECH. EMCal implementation, June 2008
/// \author Gustavo Conesa Balbastre <Gustavo.Conesa.Balbastre@cern.ch>, LPSC-IN2P3-CNRS. DCal implementation + doxygen, May 2015.
//************************************************************************

#ifndef __CINT__

#include <TEveManager.h>
#include <TEveQuadSet.h>
#include <TGeoNode.h>
#include <TGeoBBox.h>
#include <TGeoManager.h>
#include <TStyle.h>
#include <TEveTrans.h>
#include <TClonesArray.h>
#include <TTree.h>
#include <TBranch.h>

#include <EveBase/AliEveEventManager.h>

#include <AliRunLoader.h>
#include <AliCluster.h>
#include <AliEMCALGeometry.h>
#include <AliEMCALDigit.h>
#include <AliLog.h>

#endif

void emcal_digits()
{
  AliEveEventManager::AssertGeometry();

  TGeoNode* node = gGeoManager->GetTopVolume()->FindNode("XEN1_1");
  if (!node) return;

  Int_t nModules = node->GetNdaughters();

  TEveElementList* l = new TEveElementList("EMCAL");
  l->SetTitle("Tooltip");
  gEve->AddElement(l);

  TGeoBBox* bbbox = (TGeoBBox*) node->GetDaughter(0) ->GetVolume()->GetShape();
  TEveFrameBox* frame_big = new TEveFrameBox();
  frame_big->SetFrameColorRGBA(200,200,0,50);
  frame_big->SetAABoxCenterHalfSize(0, 0, 0, bbbox->GetDX(), bbbox->GetDY(), bbbox->GetDZ());

  TEveFrameBox* frame_sml  = 0x0;
  TEveFrameBox* frame_dcl  = 0x0;
  TEveFrameBox* frame_smld = 0x0;

  if (nModules > 10)
  {
    TGeoBBox* sbbox = (TGeoBBox*) node->GetDaughter(10)->GetVolume()->GetShape();
    frame_sml = new TEveFrameBox();
    frame_sml->SetFrameColorRGBA(200,200,0,50);
    frame_sml->SetAABoxCenterHalfSize(0, 0, 0, sbbox->GetDX(), sbbox->GetDY(), sbbox->GetDZ());
  }

  if (nModules > 12)
  {
    TGeoBBox* dbbox = (TGeoBBox*) node->GetDaughter(12)->GetVolume()->GetShape();
    frame_dcl = new TEveFrameBox();
    frame_dcl->SetFrameColorRGBA(200,200,0,50);
    frame_dcl->SetAABoxCenterHalfSize(0, 0, 0, dbbox->GetDX(), dbbox->GetDY(), dbbox->GetDZ());

    TGeoBBox* sdbbox = (TGeoBBox*) node->GetDaughter(18)->GetVolume()->GetShape();
    frame_smld = new TEveFrameBox();
    frame_smld->SetFrameColorRGBA(200,200,0,50);
    frame_smld->SetAABoxCenterHalfSize(0, 0, 0, sdbbox->GetDX(), sdbbox->GetDY(), sdbbox->GetDZ());
  }

  gStyle->SetPalette(1, 0);
  TEveRGBAPalette* pal = new TEveRGBAPalette(0, 512);
  pal->SetLimits(0, 1024);

  TEveQuadSet* smodules[20];
  memset(smodules,0,20*sizeof(TEveQuadSet*));

  AliEMCALGeometry * geom  = AliEMCALGeometry::GetInstance();
  if (!geom) geom  = AliEMCALGeometry::GetInstance("EMCAL_COMPLETE12SMV1_DCAL_8SM");

  for (Int_t sm =0; sm < nModules; ++sm)
  {
    TEveQuadSet* q = new TEveQuadSet(Form("SM %d", sm+1));
    q->SetOwnIds(kTRUE);
    q->Reset(TEveQuadSet::kQT_RectangleYZFixedDimX, kFALSE, 32);
    q->SetDefWidth (geom->GetPhiTileSize());
    q->SetDefHeight(geom->GetEtaTileSize());

    q->RefMainTrans().SetFrom(*node->GetDaughter(sm)->GetMatrix());

    if     (sm < 10) q->SetFrame(frame_big );
    else if(sm < 12) q->SetFrame(frame_sml );
    else if(sm < 18) q->SetFrame(frame_dcl );
    else if(sm < 20) q->SetFrame(frame_smld);

    q->SetPalette(pal);

    gEve->AddElement(q, l);
    smodules[sm] = q;
  }

  AliRunLoader* rl =  AliEveEventManager::AssertRunLoader();

  rl->LoadDigits("EMCAL");
  TTree* dt = rl->GetTreeD("EMCAL", kFALSE);
  if (!dt) return;

  TClonesArray *digits = 0;
  dt->SetBranchAddress("EMCAL", &digits);
  dt->GetEntry(0);
  Int_t nEnt = digits->GetEntriesFast();
  AliEMCALDigit * dig;

  Float_t amp   = -1 ;
  Float_t time  = -1 ;
  Int_t id      = -1 ;
  Int_t iSupMod =  0 ;
  Int_t iTower  =  0 ;
  Int_t iIphi   =  0 ;
  Int_t iIeta   =  0 ;
  Int_t iphi    =  0 ;
  Int_t ieta    =  0 ;
  Double_t x, y, z;

  for (Int_t idig = 0; idig < nEnt; ++idig)
  {
    dig = static_cast<AliEMCALDigit *>(digits->At(idig));

    if(dig != 0)
    {
      id   = dig->GetId() ; //cell (digit) label
      amp  = dig->GetAmp(); //amplitude in cell (digit)
      time = dig->GetTime();//time of creation of digit after collision

//      AliDebugGeneral("emcal_digits", 5, Form("Cell ID %3d, Amplitude: %f", id, amp));
      // cout<<"Cell ID "<<id<<" Amp "<<amp<<endl;//" time "<<time<<endl;

      //Geometry methods
      geom->GetCellIndex(id,iSupMod,iTower,iIphi,iIeta);
      //Gives SuperModule and Tower numbers
      geom->GetCellPhiEtaIndexInSModule(iSupMod,iTower,
					iIphi, iIeta,iphi,ieta);
      //Gives label of cell in eta-phi position per each supermodule

//      AliDebugGeneral("emcal_digits", 5, Form("SModule %3d; Tover %3d; Eta %3d; Phi %3d; Cell Eta %3d; Cell Phi %3d",
//		       iSupMod, iTower, iIeta, iIphi, ieta, iphi));
      // cout<< "SModule "<<iSupMod<<"; Tower "<<iTower
      //     <<"; Eta "<<iIeta<<"; Phi "<<iIphi
      //     <<"; Cell Eta "<<ieta<<"; Cell Phi "<<iphi<<endl;

      geom->RelPosCellInSModule(id, x, y, z);
      // cout << x <<" "<< y <<" "<< z <<endl;
//      AliDebugGeneral("emcal_digits", 5, Form("(x,y,z)=(%8.3f,%8.3f,%8.3f)", x, y, z));

      TEveQuadSet* q = smodules[iSupMod];
      if (q)
      {
        q->AddQuad(y, z);
        q->QuadValue(TMath::Nint(amp));
        q->QuadId(new AliEMCALDigit(*dig));
      }
    }
//    else
//    {
//      AliDebugGeneral("emcal_digits", 1, Form("Digit pointer 0x0"));
//      cout<<"Digit pointer 0x0"<<endl;
//    }
  }

  rl->UnloadDigits("EMCAL");

  for (Int_t sm = 0; sm < nModules; ++sm)
  {
    smodules[iSupMod]->RefitPlex();
  }

  gEve->Redraw3D();
}
<commit_msg>several fixes, geometry instance, proper array size with SM numbers, proper SM index<commit_after>
/**************************************************************************
 * Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. *
 * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for          *
 * full copyright notice.                                                 *
 **************************************************************************/

//************************************************************************
///
/// \file emcal_digits.C
/// \brief Visualize EMCAL digits
///
/// A macro to read and visualize EMCAL digits
///
/// \author Magali Estienne <magali.estienne@cern.ch>, SUBATECH. EMCal implementation, June 2008
/// \author Gustavo Conesa Balbastre <Gustavo.Conesa.Balbastre@cern.ch>, LPSC-IN2P3-CNRS. DCal implementation + doxygen, May 2015.
//************************************************************************

#ifndef __CINT__

#include <TEveManager.h>
#include <TEveQuadSet.h>
#include <TGeoNode.h>
#include <TGeoBBox.h>
#include <TGeoManager.h>
#include <TStyle.h>
#include <TEveTrans.h>
#include <TClonesArray.h>
#include <TTree.h>
#include <TBranch.h>

#include <EveBase/AliEveEventManager.h>

#include <AliRunLoader.h>
#include <AliCluster.h>
#include <AliEMCALGeometry.h>
#include <AliEMCALDigit.h>
#include <AliLog.h>

#endif

void emcal_digits()
{
  AliEveEventManager::AssertGeometry();

  TGeoNode* node = gGeoManager->GetTopVolume()->FindNode("XEN1_1");
  if (!node) return;

  AliEMCALGeometry * geom  = AliEMCALGeometry::GetInstance();
  if (!geom)
  {
    printf("xxx Set default geo as Run2 xxx\n");
    geom  = AliEMCALGeometry::GetInstance("EMCAL_COMPLETE12SMV1_DCAL_8SM");
  }

  Int_t nModules = node->GetNdaughters();

  if(nModules != geom->GetNumberOfSuperModules())
    printf("*** === EMCAL DIGITS - N Daughter Nodes %d - N super mod %d === ***\n",
           node->GetNdaughters(), geom->GetNumberOfSuperModules());

  TEveElementList* l = new TEveElementList("EMCAL");
  l->SetTitle("Tooltip");
  gEve->AddElement(l);

  TGeoBBox* bbbox = (TGeoBBox*) node->GetDaughter(0) ->GetVolume()->GetShape();
  TEveFrameBox* frame_big = new TEveFrameBox();
  frame_big->SetFrameColorRGBA(200,200,0,50);
  frame_big->SetAABoxCenterHalfSize(0, 0, 0, bbbox->GetDX(), bbbox->GetDY(), bbbox->GetDZ());

  TEveFrameBox* frame_sml  = 0x0;
  TEveFrameBox* frame_dcl  = 0x0;
  TEveFrameBox* frame_smld = 0x0;

  if (nModules > 10)
  {
    TGeoBBox* sbbox = (TGeoBBox*) node->GetDaughter(10)->GetVolume()->GetShape();
    frame_sml = new TEveFrameBox();
    frame_sml->SetFrameColorRGBA(200,200,0,50);
    frame_sml->SetAABoxCenterHalfSize(0, 0, 0, sbbox->GetDX(), sbbox->GetDY(), sbbox->GetDZ());
  }

  if (nModules > 12)
  {
    TGeoBBox* dbbox = (TGeoBBox*) node->GetDaughter(12)->GetVolume()->GetShape();
    frame_dcl = new TEveFrameBox();
    frame_dcl->SetFrameColorRGBA(200,200,0,50);
    frame_dcl->SetAABoxCenterHalfSize(0, 0, 0, dbbox->GetDX(), dbbox->GetDY(), dbbox->GetDZ());

    TGeoBBox* sdbbox = (TGeoBBox*) node->GetDaughter(18)->GetVolume()->GetShape();
    frame_smld = new TEveFrameBox();
    frame_smld->SetFrameColorRGBA(200,200,0,50);
    frame_smld->SetAABoxCenterHalfSize(0, 0, 0, sdbbox->GetDX(), sdbbox->GetDY(), sdbbox->GetDZ());
  }

  gStyle->SetPalette(1, 0);
  TEveRGBAPalette* pal = new TEveRGBAPalette(0, 512);
  pal->SetLimits(0, 1024);

  const Int_t nSM = nModules;
  TEveQuadSet* smodules[nSM];
  memset(smodules,0,nModules*sizeof(TEveQuadSet*));

  for (Int_t sm = 0; sm < nModules; ++sm)
  {
    TEveQuadSet* q = new TEveQuadSet(Form("SM %d", sm+1));
    q->SetOwnIds(kTRUE);
    q->Reset(TEveQuadSet::kQT_RectangleYZFixedDimX, kFALSE, 32);
    q->SetDefWidth (geom->GetPhiTileSize());
    q->SetDefHeight(geom->GetEtaTileSize());

    q->RefMainTrans().SetFrom(*node->GetDaughter(sm)->GetMatrix());

    if     (sm < 10) q->SetFrame(frame_big );
    else if(sm < 12) q->SetFrame(frame_sml );
    else if(sm < 18) q->SetFrame(frame_dcl );
    else if(sm < 20) q->SetFrame(frame_smld);

    q->SetPalette(pal);

    gEve->AddElement(q, l);
    smodules[sm] = q;
  }

  AliRunLoader* rl =  AliEveEventManager::AssertRunLoader();

  rl->LoadDigits("EMCAL");
  TTree* dt = rl->GetTreeD("EMCAL", kFALSE);
  if (!dt) return;

  TClonesArray *digits = 0;
  dt->SetBranchAddress("EMCAL", &digits);
  dt->GetEntry(0);
  Int_t nEnt = digits->GetEntriesFast();
  AliEMCALDigit * dig;

  Float_t amp   = -1 ;
  Float_t time  = -1 ;
  Int_t id      = -1 ;
  Int_t iSupMod =  0 ;
  Int_t iTower  =  0 ;
  Int_t iIphi   =  0 ;
  Int_t iIeta   =  0 ;
  Int_t iphi    =  0 ;
  Int_t ieta    =  0 ;
  Double_t x, y, z;

  for (Int_t idig = 0; idig < nEnt; ++idig)
  {
    dig = static_cast<AliEMCALDigit *>(digits->At(idig));

    if (!dig ) continue ;

    id   = dig->GetId() ; //cell (digit) label
    amp  = dig->GetAmplitude(); //amplitude in cell (digit)
    time = dig->GetTime();//time of creation of digit after collision

    // Do not add too low ADC values (3 times pedestal)
    if(amp < 3) continue;

    //printf("\t Digit %d/%d: Cell ID %d; Amp %f; time %2.3e\n",idig+1,nEnt,id,amp,time);

    //Geometry methods
    geom->GetCellIndex(id,iSupMod,iTower,iIphi,iIeta);
    //Gives SuperModule and Tower numbers
    geom->GetCellPhiEtaIndexInSModule(iSupMod,iTower,iIphi, iIeta,iphi,ieta);
    //Gives label of cell in eta-phi position per each supermodule

    //if ( iSupMod == 13 || iSupMod == 15 || iSupMod == 17 )
    //  printf("\t \t amp %2.2f iSM %d, iphi %d, ieta %d\n",amp,iSupMod,iphi,ieta);

    geom->RelPosCellInSModule(id, x, y, z);

    // It should not happen, but in case the OCDB file is not the
    // correct one.
    if(iSupMod >= nModules) continue;

    TEveQuadSet* q = smodules[iSupMod];
    if (q)
    {
      q->AddQuad(y, z);
      q->QuadValue(TMath::Nint(amp));
      q->QuadId(new AliEMCALDigit(*dig));
    }
  }

  rl->UnloadDigits("EMCAL");

  for (Int_t sm = 0; sm < nModules; ++sm)
  {
    smodules[sm]->RefitPlex();
  }

  gEve->Redraw3D();
}
<|endoftext|>