<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <hspp/CardSets/CoreCardsGen.hpp>
#include <hspp/Enchants/Effects.hpp>
#include <hspp/Tasks/SimpleTasks/AddEnchantmentTask.hpp>
#include <hspp/Tasks/SimpleTasks/DamageTask.hpp>
#include <hspp/Tasks/SimpleTasks/DestroyTask.hpp>
#include <hspp/Tasks/SimpleTasks/DiscardTask.hpp>
#include <hspp/Tasks/SimpleTasks/HealFullTask.hpp>
#include <hspp/Tasks/SimpleTasks/HealTask.hpp>

using namespace Hearthstonepp::SimpleTasks;

namespace Hearthstonepp
{
void CoreCardsGen::AddHeroes(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddHeroPowers(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddDruid(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddDruidNonCollect(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddHunter(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddHunterNonCollect(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddMage(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddMageNonCollect(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddPaladin(std::map<std::string, Power>& cards)
{
    (void)cards;

    // --------------------------------------- MINION - PALADIN
    // [CS2_088] Guardian of Kings - COST:7 [ATK:5/HP:6]
    // - Faction: Neutral, Set: Core, Rarity: Free
    // --------------------------------------------------------
    // Text: Battlecry: Restore 6 Health to your hero.
    // --------------------------------------------------------
    // GameTag:
    // - BATTLECRY = 1
    // --------------------------------------------------------
    Power power;
    power.AddPowerTask(new HealTask(EntityType::HERO, 6));
    cards.emplace("CS2_088", power);
}

void CoreCardsGen::AddPaladinNonCollect(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddPriest(std::map<std::string, Power>& cards)
{
    // ----------------------------------------- SPELL - PRIEST
    // [CS1_112] Holy Nova - COST:5
    // - Faction: Neutral, Set: Core, Rarity: Free
    // --------------------------------------------------------
    // Text: Deal $2 damage to all enemies.
    //       Restore #2 Health to all friendly characters.
    // --------------------------------------------------------
    Power power;
    power.AddPowerTask(new DamageTask(EntityType::ENEMIES, 2));
    power.AddPowerTask(new HealTask(EntityType::FRIENDS, 2));
    cards.emplace("CS1_112", power);

    // ----------------------------------------- SPELL - PRIEST
    // [CS1_113] Mind Control - COST:10
    // - Faction: neutral, Set: core, Rarity: free
    // --------------------------------------------------------
    // Text: Take control of an enemy minion.
    // --------------------------------------------------------
    // PlayReq:
    // - REQ_TARGET_TO_PLAY = 0
    // - REQ_MINION_TARGET = 0
    // - REQ_ENEMY_TARGET = 0
    // - REQ_NUM_MINION_SLOTS = 1
    // --------------------------------------------------------
}

void CoreCardsGen::AddPriestNonCollect(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddRogue(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddRogueNonCollect(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddShaman(std::map<std::string, Power>& cards)
{
    // ----------------------------------------- SPELL - SHAMAN
    // [CS2_041] Ancestral Healing - COST:0
    // - Faction: Neutral, Set: Basic, Rarity: Free
    // --------------------------------------------------------
    // Text: Restore a minion
    //       to full Health and
    //       give it Taunt.
    // --------------------------------------------------------
    // PlayReq:
    // - REQ_TARGET_TO_PLAY = 0
    // - REQ_MINION_TARGET = 0
    // --------------------------------------------------------
    // Tag:
    // - TAUNT = 1
    // --------------------------------------------------------
    Power power;
    power.AddPowerTask(new HealFullTask(EntityType::TARGET));
    power.AddPowerTask(new AddEnchantmentTask("CS2_041e", EntityType::TARGET));
    cards.emplace("CS2_041", power);
}

void CoreCardsGen::AddShamanNonCollect(std::map<std::string, Power>& cards)
{
    // ----------------------------------- ENCHANTMENT - SHAMAN
    // [CS2_041e] Ancestral Infusion (*) - COST:0
    // - Set: core,
    // --------------------------------------------------------
    // Text: Taunt.
    // --------------------------------------------------------
    // GameTag:
    // - TAUNT = 1
    // --------------------------------------------------------
    Power power;
    power.AddEnchant(new Enchant(Effects::Taunt));
    cards.emplace("CS2_041e", power);
}

void CoreCardsGen::AddWarlock(std::map<std::string, Power>& cards)
{
    // --------------------------------------- MINION - NEUTRAL
    // [EX1_306] Succubus - COST:2 [ATK:4/HP:3]
    // - Fac: horde, Set: core, Rarity: free
    // --------------------------------------------------------
    // Text: Battlecry: Discard a random card.
    // --------------------------------------------------------
    // GameTag:
    // - BATTLECRY = 1
    // --------------------------------------------------------
    Power power;
    power.AddPowerTask(new DiscardTask(EntityType::HAND));
    cards.emplace("EX1_306", power);
}

void CoreCardsGen::AddWarlockNonCollect(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddWarrior(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddWarriorNonCollect(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddNeutral(std::map<std::string, Power>& cards)
{
    // --------------------------------------- MINION - NEUTRAL
    // [EX1_066] Acidic Swamp Ooze - COST:2 [ATK:3/HP:2]
    // - Fac: alliance, Set: core, Rarity: free
    // --------------------------------------------------------
    // Text: Battlecry: Destroy your opponent's weapon.
    // --------------------------------------------------------
    // GameTag:
    // - BATTLECRY = 1
    // --------------------------------------------------------
    Power power;
    power.AddPowerTask(new DestroyTask(EntityType::ENEMY_WEAPON));
    cards.emplace("EX1_066", power);
}

void CoreCardsGen::AddNeutralNonCollect(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddAll(std::map<std::string, Power>& cards)
{
    AddHeroes(cards);
    AddHeroPowers(cards);

    AddDruid(cards);
    AddDruidNonCollect(cards);

    AddHunter(cards);
    AddHunterNonCollect(cards);

    AddMage(cards);
    AddMageNonCollect(cards);

    AddPaladin(cards);
    AddPaladinNonCollect(cards);

    AddPriest(cards);
    AddPriestNonCollect(cards);

    AddRogue(cards);
    AddRogueNonCollect(cards);

    AddShaman(cards);
    AddShamanNonCollect(cards);

    AddWarlock(cards);
    AddWarlockNonCollect(cards);

    AddWarrior(cards);
    AddWarriorNonCollect(cards);

    AddNeutral(cards);
    AddNeutralNonCollect(cards);
}
}  // namespace Hearthstonepp
<commit_msg>feat(card-impl): Use ClearData() method<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <hspp/CardSets/CoreCardsGen.hpp>
#include <hspp/Enchants/Effects.hpp>
#include <hspp/Tasks/SimpleTasks/AddEnchantmentTask.hpp>
#include <hspp/Tasks/SimpleTasks/DamageTask.hpp>
#include <hspp/Tasks/SimpleTasks/DestroyTask.hpp>
#include <hspp/Tasks/SimpleTasks/DiscardTask.hpp>
#include <hspp/Tasks/SimpleTasks/HealFullTask.hpp>
#include <hspp/Tasks/SimpleTasks/HealTask.hpp>

using namespace Hearthstonepp::SimpleTasks;

namespace Hearthstonepp
{
void CoreCardsGen::AddHeroes(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddHeroPowers(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddDruid(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddDruidNonCollect(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddHunter(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddHunterNonCollect(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddMage(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddMageNonCollect(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddPaladin(std::map<std::string, Power>& cards)
{
    // --------------------------------------- MINION - PALADIN
    // [CS2_088] Guardian of Kings - COST:7 [ATK:5/HP:6]
    // - Faction: Neutral, Set: Core, Rarity: Free
    // --------------------------------------------------------
    // Text: Battlecry: Restore 6 Health to your hero.
    // --------------------------------------------------------
    // GameTag:
    // - BATTLECRY = 1
    // --------------------------------------------------------
    Power power;
    power.AddPowerTask(new HealTask(EntityType::HERO, 6));
    cards.emplace("CS2_088", power);
}

void CoreCardsGen::AddPaladinNonCollect(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddPriest(std::map<std::string, Power>& cards)
{
    Power power;

    // ----------------------------------------- SPELL - PRIEST
    // [CS1_112] Holy Nova - COST:5
    // - Faction: Neutral, Set: Core, Rarity: Free
    // --------------------------------------------------------
    // Text: Deal $2 damage to all enemies.
    //       Restore #2 Health to all friendly characters.
    // --------------------------------------------------------
    power.ClearData();
    power.AddPowerTask(new DamageTask(EntityType::ENEMIES, 2));
    power.AddPowerTask(new HealTask(EntityType::FRIENDS, 2));
    cards.emplace("CS1_112", power);

    // ----------------------------------------- SPELL - PRIEST
    // [CS1_113] Mind Control - COST:10
    // - Faction: Neutral, Set: Core, Rarity: Free
    // --------------------------------------------------------
    // Text: Take control of an enemy minion.
    // --------------------------------------------------------
    // PlayReq:
    // - REQ_TARGET_TO_PLAY = 0
    // - REQ_MINION_TARGET = 0
    // - REQ_ENEMY_TARGET = 0
    // - REQ_NUM_MINION_SLOTS = 1
    // --------------------------------------------------------
}

void CoreCardsGen::AddPriestNonCollect(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddRogue(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddRogueNonCollect(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddShaman(std::map<std::string, Power>& cards)
{
    // ----------------------------------------- SPELL - SHAMAN
    // [CS2_041] Ancestral Healing - COST:0
    // - Faction: Neutral, Set: Core, Rarity: Free
    // --------------------------------------------------------
    // Text: Restore a minion
    //       to full Health and
    //       give it Taunt.
    // --------------------------------------------------------
    // PlayReq:
    // - REQ_TARGET_TO_PLAY = 0
    // - REQ_MINION_TARGET = 0
    // --------------------------------------------------------
    // Tag:
    // - TAUNT = 1
    // --------------------------------------------------------
    Power power;
    power.AddPowerTask(new HealFullTask(EntityType::TARGET));
    power.AddPowerTask(new AddEnchantmentTask("CS2_041e", EntityType::TARGET));
    cards.emplace("CS2_041", power);
}

void CoreCardsGen::AddShamanNonCollect(std::map<std::string, Power>& cards)
{
    // ----------------------------------- ENCHANTMENT - SHAMAN
    // [CS2_041e] Ancestral Infusion (*) - COST:0
    // - Set: Core,
    // --------------------------------------------------------
    // Text: Taunt.
    // --------------------------------------------------------
    // GameTag:
    // - TAUNT = 1
    // --------------------------------------------------------
    Power power;
    power.AddEnchant(new Enchant(Effects::Taunt));
    cards.emplace("CS2_041e", power);
}

void CoreCardsGen::AddWarlock(std::map<std::string, Power>& cards)
{
    // --------------------------------------- MINION - NEUTRAL
    // [EX1_306] Succubus - COST:2 [ATK:4/HP:3]
    // - Faction: Horde, Set: Core, Rarity: Free
    // --------------------------------------------------------
    // Text: Battlecry: Discard a random card.
    // --------------------------------------------------------
    // GameTag:
    // - BATTLECRY = 1
    // --------------------------------------------------------
    Power power;
    power.AddPowerTask(new DiscardTask(EntityType::HAND));
    cards.emplace("EX1_306", power);
}

void CoreCardsGen::AddWarlockNonCollect(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddWarrior(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddWarriorNonCollect(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddNeutral(std::map<std::string, Power>& cards)
{
    // --------------------------------------- MINION - NEUTRAL
    // [EX1_066] Acidic Swamp Ooze - COST:2 [ATK:3/HP:2]
    // - Faction: Alliance, Set: Core, Rarity: Free
    // --------------------------------------------------------
    // Text: Battlecry: Destroy your opponent's weapon.
    // --------------------------------------------------------
    // GameTag:
    // - BATTLECRY = 1
    // --------------------------------------------------------
    Power power;
    power.AddPowerTask(new DestroyTask(EntityType::ENEMY_WEAPON));
    cards.emplace("EX1_066", power);
}

void CoreCardsGen::AddNeutralNonCollect(std::map<std::string, Power>& cards)
{
    (void)cards;
}

void CoreCardsGen::AddAll(std::map<std::string, Power>& cards)
{
    AddHeroes(cards);
    AddHeroPowers(cards);

    AddDruid(cards);
    AddDruidNonCollect(cards);

    AddHunter(cards);
    AddHunterNonCollect(cards);

    AddMage(cards);
    AddMageNonCollect(cards);

    AddPaladin(cards);
    AddPaladinNonCollect(cards);

    AddPriest(cards);
    AddPriestNonCollect(cards);

    AddRogue(cards);
    AddRogueNonCollect(cards);

    AddShaman(cards);
    AddShamanNonCollect(cards);

    AddWarlock(cards);
    AddWarlockNonCollect(cards);

    AddWarrior(cards);
    AddWarriorNonCollect(cards);

    AddNeutral(cards);
    AddNeutralNonCollect(cards);
}
}  // namespace Hearthstonepp
<|endoftext|>


<commit_before>#include "Streak.h"

Streak::Streak(uint16_t columns,
  uint16_t rows,
  uint8_t hue,
  uint8_t saturation,
  CRGB * leds)
: Visualization(columns, rows, hue, saturation, leds)
{
  this->length = 0;
  this->minLength = 8;
  this->maxLength = 16;
  this->minInterval = 0;
  this->maxInterval = 90;
}

void Streak::inititalize() {
  this->interval = random8(this->minInterval, this->maxInterval);
  this->column = random8(this->columns);
  this->length = random8(this->minLength, this->maxLength);
  if (this->randomHue) {
    this->setHue(random(256));
  }
}

void Streak::display (unsigned long currentTime) {
  int currentFrame = this->frame % (this->rows + this->length);

  if (currentFrame == 0) {
    this->inititalize();
  }

  if (currentTime > this->nextTime) {
    // Serial.print(this->id);
    // Serial.print(": ");
    // Serial.println(currentTime);
    this->frame++;
    this->nextTime = currentTime + this->interval;
  }

  int y = currentFrame;
  int pos;
  for (uint8_t i=0; i<this->length; i++) {
    if ((y - i >= 0) && (y - i < this->rows)) {
      pos = this->xy2Pos(this->column, y - i);
      this->leds[pos] = this->color;

      if (this->fade) {
        this->leds[pos].fadeLightBy((256 / this->length) * i);
      }
    }
  }
}

void Streak::setLengthMinMax(uint8_t min, uint8_t max) {
  this->minLength = min;
  this->maxLength = max;
}

void Streak::setIntervalMinMax(uint8_t min, uint8_t max) {
  this->minInterval = min;
  this->maxInterval = max;
}

void Streak::setFade(bool on) {
  this->fade = on;
}

void Streak::setRandomHue(bool on) {
  this->randomHue = on;
}
<commit_msg>initialize bools<commit_after>#include "Streak.h"

Streak::Streak(uint16_t columns,
  uint16_t rows,
  uint8_t hue,
  uint8_t saturation,
  CRGB * leds)
: Visualization(columns, rows, hue, saturation, leds)
{
  this->length = 0;
  this->minLength = 8;
  this->maxLength = 16;
  this->minInterval = 0;
  this->maxInterval = 90;
  this->randomHue = false;
  this->fade = true;
}

void Streak::inititalize() {
  this->interval = random8(this->minInterval, this->maxInterval);
  this->column = random8(this->columns);
  this->length = random8(this->minLength, this->maxLength);
  if (this->randomHue) {
    this->setHue(random(256));
  }
}

void Streak::display (unsigned long currentTime) {
  int currentFrame = this->frame % (this->rows + this->length);

  if (currentFrame == 0) {
    this->inititalize();
  }

  if (currentTime > this->nextTime) {
    // Serial.print(this->id);
    // Serial.print(": ");
    // Serial.println(currentTime);
    this->frame++;
    this->nextTime = currentTime + this->interval;
  }

  int y = currentFrame;
  int pos;
  for (uint8_t i=0; i<this->length; i++) {
    if ((y - i >= 0) && (y - i < this->rows)) {
      pos = this->xy2Pos(this->column, y - i);
      this->leds[pos] = this->color;

      if (this->fade) {
        this->leds[pos].fadeLightBy((256 / this->length) * i);
      }
    }
  }
}

void Streak::setLengthMinMax(uint8_t min, uint8_t max) {
  this->minLength = min;
  this->maxLength = max;
}

void Streak::setIntervalMinMax(uint8_t min, uint8_t max) {
  this->minInterval = min;
  this->maxInterval = max;
}

void Streak::setFade(bool on) {
  this->fade = on;
}

void Streak::setRandomHue(bool on) {
  this->randomHue = on;
}
<|endoftext|>


<commit_before><commit_msg>add a multiplicity cut for PbPb and XeXe sample<commit_after><|endoftext|>


<commit_before>/***************************************************************************
              Anders Knospe - last modified on 26 March 2016
              Arvind Khuntia - last modified on 20 Nov 2020
	      //Lauches phi analysis with rsn mini package for Pb-Pb@ 5.02 Tev
	      //Allows basic configuration of pile-up check and event cuts
	      ****************************************************************************/
#if !defined (__CINT__) || defined (__CLING__)
R__ADD_INCLUDE_PATH($ALICE_PHYSICS)
#include <PWGLF/RESONANCES/macros/mini/ConfigPhiPbPb5TeVRun2.C>
#endif

enum pairYCutSet { kPairDefault=0,
  kCentral //=1
};

enum eventCutSet { kEvtDefault=0,
  kNoPileUpCut, //=1
  kDefaultVtx8,//=2
  kDefaultVtx12, //=3
  kVertexoff //=4
};

enum eventMixConfig { kDisabled = -1,
  kMixDefault,//=0 //10 events, Dvz = 1cm, DC = 10
  k5Evts, //=1 //5 events, Dvz = 1cm, DC = 10
  k5Cent,  //=2 //10 events, Dvz = 1cm, DC = 5
  k5Evts5Cent //3 //5 events, Dvz = 1 cm, DC  = 5
};

AliRsnMiniAnalysisTask * AddTaskPhiPbPb5TeVRun2
(
 Bool_t      isMC = kFALSE,
 Bool_t      isPP = kFALSE,
 AliRsnMiniValue::EType    cosThetaType = AliRsnMiniValue::kCosThetaHe,
 TString     outNameSuffix = "tpc2stof3sveto",
 Int_t       evtCutSetID = 0,
 Int_t       mixingConfigID = 0,
 Int_t       aodFilterBit = 5,
 Int_t       customQualityCutsID = 1,
 AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate=AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,
 Float_t     nsigmaKa = 2.,
 Bool_t      timeRangeCut = kTRUE,
 Bool_t      isESD = kFALSE,
 Bool_t      enableMonitor = kTRUE,
 Bool_t      IsMcTrueOnly = kFALSE,
 TString     monitorOpt = "NoSIGN",
 Bool_t      useMixLS = 0,
 Bool_t      checkReflex = 0,
 UInt_t      triggerMask = AliVEvent::kINT7,
 Int_t       pairCutSetID = 0
 )

{
  //-------------------------------------------
  //                  event cuts
  //-------------------------------------------
  Bool_t      rejectPileUp = kTRUE;
  Double_t    vtxZcut = 10.0;//cm, default cut on vtx z
  Int_t       MultBins = aodFilterBit/100;

  if(evtCutSetID==eventCutSet::kNoPileUpCut) rejectPileUp=kFALSE;
  if(evtCutSetID==eventCutSet::kDefaultVtx8) vtxZcut=8.0; //cm
  if(evtCutSetID==eventCutSet::kDefaultVtx12) vtxZcut=12.0; //cm
  if(evtCutSetID==eventCutSet::kVertexoff) vtxZcut=1.e6; //off

  if(!isPP || isMC || MultBins) rejectPileUp=kFALSE;
  //-------------------------------------------
  //                pair cuts
  //-------------------------------------------
  Double_t    minYlab=-0.5;
  Double_t    maxYlab= 0.5;
  if(pairCutSetID==pairYCutSet::kCentral){ minYlab=-0.3; maxYlab=0.3;} //|y_cm|<0.3
  //-------------------------------------------
  //            mixing settings
  //-------------------------------------------
  Int_t       nmix=0;
  Float_t     maxDiffVzMix=1.;
  Float_t     maxDiffMultMix=10.;

  if(mixingConfigID==eventMixConfig::kMixDefault) nmix=10;
  if(mixingConfigID==eventMixConfig::k5Evts) nmix=5;
  if(mixingConfigID==eventMixConfig::k5Cent) maxDiffMultMix=5;
  if(mixingConfigID==eventMixConfig::k5Evts5Cent){nmix=5; maxDiffMultMix=5;}
  //--------------------------------------------
  //             INITIALIZATION
  //--------------------------------------------
  // retrieve analysis manager
  AliAnalysisManager* mgr=AliAnalysisManager::GetAnalysisManager();
  if(!mgr){
    ::Error("AddTaskPhiPbPb5TeVRun2", "No analysis manager to connect to ==>");
    return NULL;
  }

  // create the task and configure
  TString taskName=Form("phi%s%s_%i",(isPP? "pp" : "PbPb"),(isMC ? "MC" : "Data"),(Int_t)cutKaCandidate);
  AliRsnMiniAnalysisTask* task=new AliRsnMiniAnalysisTask(taskName.Data(),isMC);
  if (isESD) task->UseESDTriggerMask(triggerMask); //ESD ****** check this *****
  else task->SelectCollisionCandidates(triggerMask); //AOD
  if (isPP)  task->UseMultiplicity("QUALITY");
  else task->UseMultiplicity("AliMultSelection_V0M");//only for run2

  // set event mixing options
  task->UseContinuousMix();
  //task->UseBinnedMix();
  task->SetNMix(nmix);
  task->SetMaxDiffVz(maxDiffVzMix);
  task->SetMaxDiffMult(maxDiffMultMix);
  task->SetMaxDiffAngle(20.0*TMath::DegToRad());
  task->SetUseTimeRangeCut(timeRangeCut);
  ::Info("AddTaskPhiPbPb5TeVRun2", Form("Event mixing configuration: \n events to mix = %i "
                                        "\n max diff. vtxZ = cm %5.3f \n max diff multi = %5.3f", nmix, maxDiffVzMix, maxDiffMultMix));
  mgr->AddTask(task);
  // cut on primary vertex:
  // - 2nd argument --> |Vz| range
  // - 3rd argument --> minimum required number of contributors to vtx
  // - 4th argument --> tells if TPC stand-alone vertexes must be accepted

  AliRsnCutEventUtils* cutEventUtils=0;
  cutEventUtils=new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp);
  cutEventUtils->SetCheckAcceptedMultSelection();

  //AliRsnCutPrimaryVertex* cutVertex=0;
  //cutVertex=new AliRsnCutPrimaryVertex("cutVertex",vtxZcut,0,kFALSE);

  // define and fill cut set for event cut
  AliRsnCutSet* eventCuts=0;
  eventCuts=new AliRsnCutSet("eventCuts",AliRsnTarget::kEvent);
  //eventCuts->AddCut(cutVertex);
  eventCuts->AddCut(cutEventUtils);
  eventCuts->SetCutScheme(Form("%s%s",cutEventUtils->GetName()));
  task->SetEventCuts(eventCuts);

  // ------------ EVENT-ONLY COMPUTATIONS -----------------------

  //vertex
  Int_t vtxID=task->CreateValue(AliRsnMiniValue::kVz,kFALSE);
  AliRsnMiniOutput* outVtx=task->CreateOutput("eventVtx","HIST","EVENT");
  outVtx->AddAxis(vtxID,400,-20.0,20.0);

  //multiplicity or centrality
  Int_t multID=task->CreateValue(AliRsnMiniValue::kMult,kFALSE);
  AliRsnMiniOutput* outMult=task->CreateOutput("eventMult","HIST","EVENT");
  if(isPP && !MultBins) outMult->AddAxis(multID,400,0.5,400.5);
  else outMult->AddAxis(multID,110,0.,110.);

  TH2F* hvz=new TH2F("hVzVsCent","",110,0.,110., 240,-12.0,12.0);
  task->SetEventQAHist("vz",hvz);//plugs this histogram into the fHAEventVz data member

  TH2F* hmc=new TH2F("MultiVsCent","", 110,0.,110., 400,0.5,400.5);
  hmc->GetYaxis()->SetTitle("QUALITY");
  task->SetEventQAHist("multicent",hmc);//plugs this histogram into the fHAEventMultiCent data member

  //--------- PAIR CUTS (common to all resonances) --- ----------

  AliRsnCutMiniPair* cutY=new AliRsnCutMiniPair("cutRapidity",AliRsnCutMiniPair::kRapidityRange);
  cutY->SetRangeD(minYlab,maxYlab);
  AliRsnCutSet* cutsPair=new AliRsnCutSet("pairCuts",AliRsnTarget::kMother);
  cutsPair->AddCut(cutY);
  cutsPair->SetCutScheme(cutY->GetName());

  //------------------ CONFIG ANALYSIS ----------------------------

  //gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigPhiPP8TeV.C");
#if !defined (__CINT__) || defined (__CLING__)
  if(!ConfigPhiPbPb5TeVRun2(task,isMC,isPP,cutsPair,aodFilterBit,cosThetaType,customQualityCutsID,cutKaCandidate,nsigmaKa,enableMonitor,isMC&IsMcTrueOnly,monitorOpt.Data(),useMixLS)) return 0x0;

#else
  // gROOT->LoadMacro("ConfigPhiPbPb5TeVRun2.C");
    gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigPhiPbPb5TeVRun2.C");
  if(!ConfigPhiPbPb5TeVRun2(task,isMC,isPP,cutsPair,aodFilterBit,cosThetaType,customQualityCutsID,cutKaCandidate,nsigmaKa,enableMonitor,isMC&IsMcTrueOnly,monitorOpt.Data(),useMixLS)) return 0x0;
#endif

  //------------------- CONTAINERS ------------------------

  TString outputFileName = AliAnalysisManager::GetCommonFileName();
  //  outputFileName += ":Rsn";
  Printf("AddAnalysisTaskPhiPbPb5TeVRun2 - Set OutputFileName : \n %s\n",outputFileName.Data());

  AliAnalysisDataContainer* output=mgr->CreateContainer(Form("RsnOut_%s",outNameSuffix.Data()),
							TList::Class(),
							AliAnalysisManager::kOutputContainer,
							outputFileName);
  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 1, output);
  return task;
}

<commit_msg>bug fix [rsn-phi meson analysis]<commit_after>/***************************************************************************
              Anders Knospe - last modified on 26 March 2016
              Arvind Khuntia - last modified on 20 Nov 2020
	      //Lauches phi analysis with rsn mini package for Pb-Pb@ 5.02 Tev
	      //Allows basic configuration of pile-up check and event cuts
	      ****************************************************************************/
#if !defined (__CINT__) || defined (__CLING__)
R__ADD_INCLUDE_PATH($ALICE_PHYSICS)
#include <PWGLF/RESONANCES/macros/mini/ConfigPhiPbPb5TeVRun2.C>
#endif

enum pairYCutSet { kPairDefault=0,
  kCentral //=1
};

enum eventCutSet { kEvtDefault=0,
  kNoPileUpCut, //=1
  kDefaultVtx8,//=2
  kDefaultVtx12, //=3
  kVertexoff //=4
};

enum eventMixConfig { kDisabled = -1,
  kMixDefault,//=0 //10 events, Dvz = 1cm, DC = 10
  k5Evts, //=1 //5 events, Dvz = 1cm, DC = 10
  k5Cent,  //=2 //10 events, Dvz = 1cm, DC = 5
  k5Evts5Cent //3 //5 events, Dvz = 1 cm, DC  = 5
};

AliRsnMiniAnalysisTask * AddTaskPhiPbPb5TeVRun2
(
 Bool_t      isMC = kFALSE,
 Bool_t      isPP = kFALSE,
 AliRsnMiniValue::EType    cosThetaType = AliRsnMiniValue::kCosThetaHe,
 TString     outNameSuffix = "tpc2stof3sveto",
 Int_t       evtCutSetID = 0,
 Int_t       mixingConfigID = 0,
 Int_t       aodFilterBit = 5,
 Int_t       customQualityCutsID = 1,
 AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate=AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,
 Float_t     nsigmaKa = 2.,
 Bool_t      timeRangeCut = kTRUE,
 Bool_t      isESD = kFALSE,
 Bool_t      enableMonitor = kTRUE,
 Bool_t      IsMcTrueOnly = kFALSE,
 TString     monitorOpt = "PbPb",
 Bool_t      useMixLS = 0,
 Bool_t      checkReflex = 0,
 UInt_t      triggerMask = AliVEvent::kINT7,
 Int_t       pairCutSetID = 0
 )

{
  //-------------------------------------------
  //                  event cuts
  //-------------------------------------------
  Bool_t      rejectPileUp = kTRUE;
  Double_t    vtxZcut = 10.0;//cm, default cut on vtx z
  Int_t       MultBins = aodFilterBit/100;

  if(evtCutSetID==eventCutSet::kNoPileUpCut) rejectPileUp=kFALSE;
  if(evtCutSetID==eventCutSet::kDefaultVtx8) vtxZcut=8.0; //cm
  if(evtCutSetID==eventCutSet::kDefaultVtx12) vtxZcut=12.0; //cm
  if(evtCutSetID==eventCutSet::kVertexoff) vtxZcut=1.e6; //off

  if(!isPP || isMC || MultBins) rejectPileUp=kFALSE;
  //-------------------------------------------
  //                pair cuts
  //-------------------------------------------
  Double_t    minYlab=-0.5;
  Double_t    maxYlab= 0.5;
  if(pairCutSetID==pairYCutSet::kCentral){ minYlab=-0.3; maxYlab=0.3;} //|y_cm|<0.3
  //-------------------------------------------
  //            mixing settings
  //-------------------------------------------
  Int_t       nmix=0;
  Float_t     maxDiffVzMix=1.;
  Float_t     maxDiffMultMix=10.;

  if(mixingConfigID==eventMixConfig::kMixDefault) nmix=10;
  if(mixingConfigID==eventMixConfig::k5Evts) nmix=5;
  if(mixingConfigID==eventMixConfig::k5Cent) maxDiffMultMix=5;
  if(mixingConfigID==eventMixConfig::k5Evts5Cent){nmix=5; maxDiffMultMix=5;}
  //--------------------------------------------
  //             INITIALIZATION
  //--------------------------------------------
  // retrieve analysis manager
  AliAnalysisManager* mgr=AliAnalysisManager::GetAnalysisManager();
  if(!mgr){
    ::Error("AddTaskPhiPbPb5TeVRun2", "No analysis manager to connect to ==>");
    return NULL;
  }

  // create the task and configure
  TString taskName=Form("phi%s%s_%i",(isPP? "pp" : "PbPb"),(isMC ? "MC" : "Data"),(Int_t)cutKaCandidate);
  AliRsnMiniAnalysisTask* task=new AliRsnMiniAnalysisTask(taskName.Data(),isMC);
  if (isESD) task->UseESDTriggerMask(triggerMask); //ESD ****** check this *****
  else task->SelectCollisionCandidates(triggerMask); //AOD
  if (isPP)  task->UseMultiplicity("QUALITY");
  else task->UseMultiplicity("AliMultSelection_V0M");//only for run2

  // set event mixing options
  task->UseContinuousMix();
  //task->UseBinnedMix();
  task->SetNMix(nmix);
  task->SetMaxDiffVz(maxDiffVzMix);
  task->SetMaxDiffMult(maxDiffMultMix);
  task->SetMaxDiffAngle(20.0*TMath::DegToRad());
  task->SetUseTimeRangeCut(timeRangeCut);
  ::Info("AddTaskPhiPbPb5TeVRun2", Form("Event mixing configuration: \n events to mix = %i "
                                        "\n max diff. vtxZ = cm %5.3f \n max diff multi = %5.3f", nmix, maxDiffVzMix, maxDiffMultMix));
  mgr->AddTask(task);
  // cut on primary vertex:
  // - 2nd argument --> |Vz| range
  // - 3rd argument --> minimum required number of contributors to vtx
  // - 4th argument --> tells if TPC stand-alone vertexes must be accepted

  AliRsnCutEventUtils* cutEventUtils=0;
  cutEventUtils=new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp);
  cutEventUtils->SetCheckAcceptedMultSelection();

  //AliRsnCutPrimaryVertex* cutVertex=0;
  //cutVertex=new AliRsnCutPrimaryVertex("cutVertex",vtxZcut,0,kFALSE);

  // define and fill cut set for event cut
  AliRsnCutSet* eventCuts=0;
  eventCuts=new AliRsnCutSet("eventCuts",AliRsnTarget::kEvent);
  //eventCuts->AddCut(cutVertex);
  eventCuts->AddCut(cutEventUtils);
  eventCuts->SetCutScheme(Form("%s",cutEventUtils->GetName()));
  task->SetEventCuts(eventCuts);

  // ------------ EVENT-ONLY COMPUTATIONS -----------------------

  //vertex
  Int_t vtxID=task->CreateValue(AliRsnMiniValue::kVz,kFALSE);
  AliRsnMiniOutput* outVtx=task->CreateOutput("eventVtx","HIST","EVENT");
  outVtx->AddAxis(vtxID,400,-20.0,20.0);

  //multiplicity or centrality
  Int_t multID=task->CreateValue(AliRsnMiniValue::kMult,kFALSE);
  AliRsnMiniOutput* outMult=task->CreateOutput("eventMult","HIST","EVENT");
  if(isPP && !MultBins) outMult->AddAxis(multID,400,0.5,400.5);
  else outMult->AddAxis(multID,110,0.,110.);

  TH2F* hvz=new TH2F("hVzVsCent","",110,0.,110., 240,-12.0,12.0);
  task->SetEventQAHist("vz",hvz);//plugs this histogram into the fHAEventVz data member

  TH2F* hmc=new TH2F("MultiVsCent","", 110,0.,110., 400,0.5,400.5);
  hmc->GetYaxis()->SetTitle("QUALITY");
  task->SetEventQAHist("multicent",hmc);//plugs this histogram into the fHAEventMultiCent data member

  //--------- PAIR CUTS (common to all resonances) --- ----------

  AliRsnCutMiniPair* cutY=new AliRsnCutMiniPair("cutRapidity",AliRsnCutMiniPair::kRapidityRange);
  cutY->SetRangeD(minYlab,maxYlab);
  AliRsnCutSet* cutsPair=new AliRsnCutSet("pairCuts",AliRsnTarget::kMother);
  cutsPair->AddCut(cutY);
  cutsPair->SetCutScheme(cutY->GetName());

  //------------------ CONFIG ANALYSIS ----------------------------

  //gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigPhiPP8TeV.C");
#if !defined (__CINT__) || defined (__CLING__)
  if(!ConfigPhiPbPb5TeVRun2(task,isMC,isPP,cutsPair,aodFilterBit,cosThetaType,customQualityCutsID,cutKaCandidate,nsigmaKa,enableMonitor,isMC&IsMcTrueOnly,monitorOpt.Data(),useMixLS)) return 0x0;

#else
  // gROOT->LoadMacro("ConfigPhiPbPb5TeVRun2.C");
    gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigPhiPbPb5TeVRun2.C");
  if(!ConfigPhiPbPb5TeVRun2(task,isMC,isPP,cutsPair,aodFilterBit,cosThetaType,customQualityCutsID,cutKaCandidate,nsigmaKa,enableMonitor,isMC&IsMcTrueOnly,monitorOpt.Data(),useMixLS)) return 0x0;
#endif

  //------------------- CONTAINERS ------------------------

  TString outputFileName = AliAnalysisManager::GetCommonFileName();
  //  outputFileName += ":Rsn";
  Printf("AddAnalysisTaskPhiPbPb5TeVRun2 - Set OutputFileName : \n %s\n",outputFileName.Data());

  AliAnalysisDataContainer* output=mgr->CreateContainer(Form("RsnOut_%s",outNameSuffix.Data()),
							TList::Class(),
							AliAnalysisManager::kOutputContainer,
							outputFileName);
  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 1, output);
  return task;
}

<|endoftext|>


<commit_before><commit_msg>nomsg<commit_after><|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkRawImageIOTest4.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <fstream>
#include "itkRawImageIO.h"
#include "itkImageFileReader.h"
#include "itkImage.h"
#include "itkImageLinearIteratorWithIndex.h"

// Helper class for reading a file and checking the content
template< typename TImageType >
class RawImageIOReadFileTester
{

public:
// Only single method of this class
int Read( const char *filename , bool ReadBigEndian, unsigned int dims[] )
  {

    const unsigned int ImageDimension = TImageType::ImageDimension;

    typedef typename TImageType::PixelType   PixelType;
    typedef itk::ImageFileReader<TImageType> ReaderType;
    typedef itk::RawImageIO<PixelType,ImageDimension> IOType;

    typename IOType::Pointer io = IOType::New();

    io->SetFileTypeToBinary();

    if( ReadBigEndian )
      {
      io->SetByteOrderToBigEndian();
      }
    else
      {
      io->SetByteOrderToLittleEndian();
      }

    for( unsigned int j = 0; j < TImageType::ImageDimension; j++ )
      {
      io->SetDimensions( j, dims[j] );
      }

    typename ReaderType::Pointer reader = ReaderType::New();
    reader->SetFileName( filename );
    reader->SetImageIO( io );
    reader->Update();

    typedef itk::ImageLinearIteratorWithIndex<TImageType> Iterator;
    Iterator it( reader->GetOutput(), reader->GetOutput()->GetBufferedRegion() );

    it.GoToBegin();
    it.SetDirection( 0 );

    PixelType value = itk::NumericTraits< PixelType >::Zero;
    while ( !it.IsAtEnd() )
      {
      while ( !it.IsAtEndOfLine() )
        {
        PixelType readValue = it.Get();
        std::cout << readValue << " ";
        if( readValue != value )
          {
          std::cerr << "At index " << it.GetIndex() << std::endl;
          std::cerr << "the value " << value << " was expected  " << std::endl;
          std::cerr << "but value " << readValue << " was read  " << std::endl;
          return EXIT_FAILURE;
          }
        ++it;
        ++value;
        }
      std::cout << std::endl;
      it.NextLine();
      }
    return EXIT_SUCCESS;
  }

};

int itkRawImageIOTest4(int, char**)
{

  typedef unsigned short PixelType;
  const unsigned int ImageDimension = 2;

  typedef itk::RawImageIO<PixelType,ImageDimension> IOType;
  typedef itk::Image<PixelType,ImageDimension> ImageType;

  char filenameBigEndian[]     = "testBinaryBigEndian.raw";
  char filenameLittleEndian[]  = "testBinaryLittleEndian.raw";

  unsigned int dims[ImageDimension] = { 5, 5 };

  typedef itk::PixelTraits< PixelType >::ValueType ComponentType;
  typedef itk::ByteSwapper< ComponentType >              ByteSwapperType;

  PixelType value = itk::NumericTraits< PixelType >::Zero;
  unsigned int numberOfPixels = dims[0] * dims[1];

  // Create the BigEndian binary file
  std::ofstream outputFile1;
#ifdef _WIN32
  outputFile1.open( filenameBigEndian , std::ios::out | std::ios::binary );
#else
  outputFile1.open( filenameBigEndian );
#endif

  if( outputFile1.fail() )
    {
    std::cerr << "itkRawImageIOTest4:Error writing the test file" << std::endl;
    return EXIT_FAILURE;
    }

  for( unsigned int i = 0; i < numberOfPixels; i++ )
    {
    PixelType swappedValue = value;
    // make sure that the file is written in
    // BigEndian regardless of the platform
    ByteSwapperType::SwapFromSystemToBigEndian( &swappedValue );
    outputFile1.write( reinterpret_cast<char*>(&swappedValue),
                      sizeof(swappedValue) );
    ++value;
    }
  outputFile1.close();

  if( outputFile1.fail() )
    {
    std::cerr << "itkRawImageIOTest4:Error writing the test file" << std::endl;
    return EXIT_FAILURE;
    }

  // Create the LittleEndian binary file
  std::ofstream outputFile2;
#ifdef _WIN32
  outputFile2.open( filenameLittleEndian , std::ios::out | std::ios::binary );
#else
  outputFile2.open( filenameLittleEndian );
#endif

  if( outputFile2.fail() )
    {
    std::cerr << "itkRawImageIOTest4:Error writing the test file" << std::endl;
    return EXIT_FAILURE;
    }

  value = itk::NumericTraits< PixelType >::Zero;
  for( unsigned int i = 0; i < numberOfPixels; i++ )
    {
    PixelType swappedValue = value;
    // make sure that the file is written in
    // LittleEndian regardless of the platform
    ByteSwapperType::SwapFromSystemToLittleEndian( &swappedValue );
    outputFile2.write( reinterpret_cast<char*>(&swappedValue),
                      sizeof(swappedValue) );
    ++value;
    }
  outputFile2.close();

  if( outputFile2.fail() )
    {
    std::cerr << "itkRawImageIOTest4:Error writing the test file" << std::endl;
    return EXIT_FAILURE;
    }

  RawImageIOReadFileTester<ImageType>  readTester;

  int status = EXIT_FAILURE;

  std::cout << "Testing read of Big Endian File" << std::endl;
  bool fileIsBigEndian = true;
  status = readTester.Read( filenameBigEndian, fileIsBigEndian, dims );
  if( status==EXIT_FAILURE )
    {
    std::cerr << "Reading Raw BigEndian FAILED !!" << std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout << "Reading Raw BigEndian PASSED !!" << std::endl << std::endl;
    }

  std::cout << "Testing read of Little Endian File" << std::endl;
  fileIsBigEndian = false;
  status = readTester.Read( filenameLittleEndian, fileIsBigEndian, dims );
  if( status==EXIT_FAILURE )
    {
    std::cerr << "Reading Raw LittleEndian FAILED !!" << std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout << "Reading Raw LittleEndian PASSED !!" << std::endl << std::endl;
    }

  std::cout << "Test PASSED !!" << std::endl << std::endl;

  return EXIT_SUCCESS;

}

<commit_msg>ERR: warnings.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkRawImageIOTest4.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <fstream>
#include "itkRawImageIO.h"
#include "itkImageFileReader.h"
#include "itkImage.h"
#include "itkImageLinearIteratorWithIndex.h"

// Helper class for reading a file and checking the content
template< typename TImageType >
class RawImageIOReadFileTester
{

public:
// Only single method of this class
int Read( const char *filename , bool ReadBigEndian, unsigned int dims[] )
  {

    const unsigned int ImageDimension = TImageType::ImageDimension;

    typedef typename TImageType::PixelType   PixelType;
    typedef itk::ImageFileReader<TImageType> ReaderType;
    typedef itk::RawImageIO<PixelType,ImageDimension> IOType;

    typename IOType::Pointer io = IOType::New();

    io->SetFileTypeToBinary();

    if( ReadBigEndian )
      {
      io->SetByteOrderToBigEndian();
      }
    else
      {
      io->SetByteOrderToLittleEndian();
      }

    for( unsigned int j = 0; j < TImageType::ImageDimension; j++ )
      {
      io->SetDimensions( j, dims[j] );
      }

    typename ReaderType::Pointer reader = ReaderType::New();
    reader->SetFileName( filename );
    reader->SetImageIO( io );
    reader->Update();

    typedef itk::ImageLinearIteratorWithIndex<TImageType> Iterator;
    Iterator it( reader->GetOutput(), reader->GetOutput()->GetBufferedRegion() );

    it.GoToBegin();
    it.SetDirection( 0 );

    PixelType value = itk::NumericTraits< PixelType >::Zero;
    while ( !it.IsAtEnd() )
      {
      while ( !it.IsAtEndOfLine() )
        {
        PixelType readValue = it.Get();
        std::cout << readValue << " ";
        if( readValue != value )
          {
          std::cerr << "At index " << it.GetIndex() << std::endl;
          std::cerr << "the value " << value << " was expected  " << std::endl;
          std::cerr << "but value " << readValue << " was read  " << std::endl;
          return EXIT_FAILURE;
          }
        ++it;
        ++value;
        }
      std::cout << std::endl;
      it.NextLine();
      }
    return EXIT_SUCCESS;
  }

};

int itkRawImageIOTest4(int, char**)
{

  typedef unsigned short PixelType;
  const unsigned int ImageDimension = 2;

  typedef itk::RawImageIO<PixelType,ImageDimension> IOType;
  typedef itk::Image<PixelType,ImageDimension> ImageType;

  char filenameBigEndian[]     = "testBinaryBigEndian.raw";
  char filenameLittleEndian[]  = "testBinaryLittleEndian.raw";

  unsigned int dims[ImageDimension] = { 5, 5 };

  typedef itk::PixelTraits< PixelType >::ValueType ComponentType;
  typedef itk::ByteSwapper< ComponentType >              ByteSwapperType;

  PixelType value = itk::NumericTraits< PixelType >::Zero;
  unsigned int numberOfPixels = dims[0] * dims[1];

  // Create the BigEndian binary file
  std::ofstream outputFile1;
#ifdef _WIN32
  outputFile1.open( filenameBigEndian , std::ios::out | std::ios::binary );
#else
  outputFile1.open( filenameBigEndian );
#endif

  if( outputFile1.fail() )
    {
    std::cerr << "itkRawImageIOTest4:Error writing the test file" << std::endl;
    return EXIT_FAILURE;
    }

  for( unsigned int i = 0; i < numberOfPixels; i++ )
    {
    PixelType swappedValue = value;
    // make sure that the file is written in
    // BigEndian regardless of the platform
    ByteSwapperType::SwapFromSystemToBigEndian( &swappedValue );
    outputFile1.write( reinterpret_cast<char*>(&swappedValue),
                      sizeof(swappedValue) );
    ++value;
    }
  outputFile1.close();

  if( outputFile1.fail() )
    {
    std::cerr << "itkRawImageIOTest4:Error writing the test file" << std::endl;
    return EXIT_FAILURE;
    }

  // Create the LittleEndian binary file
  std::ofstream outputFile2;
#ifdef _WIN32
  outputFile2.open( filenameLittleEndian , std::ios::out | std::ios::binary );
#else
  outputFile2.open( filenameLittleEndian );
#endif

  if( outputFile2.fail() )
    {
    std::cerr << "itkRawImageIOTest4:Error writing the test file" << std::endl;
    return EXIT_FAILURE;
    }

  value = itk::NumericTraits< PixelType >::Zero;
  for( unsigned int i = 0; i < numberOfPixels; i++ )
    {
    PixelType swappedValue = value;
    // make sure that the file is written in
    // LittleEndian regardless of the platform
    ByteSwapperType::SwapFromSystemToLittleEndian( &swappedValue );
    outputFile2.write( reinterpret_cast<char*>(&swappedValue),
                      sizeof(swappedValue) );
    ++value;
    }
  outputFile2.close();

  if( outputFile2.fail() )
    {
    std::cerr << "itkRawImageIOTest4:Error writing the test file" << std::endl;
    return EXIT_FAILURE;
    }

  RawImageIOReadFileTester<ImageType>  readTester;

  int status;

  std::cout << "Testing read of Big Endian File" << std::endl;
  bool fileIsBigEndian = true;
  status = readTester.Read( filenameBigEndian, fileIsBigEndian, dims );
  if( status==EXIT_FAILURE )
    {
    std::cerr << "Reading Raw BigEndian FAILED !!" << std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout << "Reading Raw BigEndian PASSED !!" << std::endl << std::endl;
    }

  std::cout << "Testing read of Little Endian File" << std::endl;
  fileIsBigEndian = false;
  status = readTester.Read( filenameLittleEndian, fileIsBigEndian, dims );
  if( status==EXIT_FAILURE )
    {
    std::cerr << "Reading Raw LittleEndian FAILED !!" << std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout << "Reading Raw LittleEndian PASSED !!" << std::endl << std::endl;
    }

  std::cout << "Test PASSED !!" << std::endl << std::endl;

  return EXIT_SUCCESS;

}

<|endoftext|>


<commit_before>#ifndef PITO_INTERCEPTOR_APPLICATION_HPP
#define PITO_INTERCEPTOR_APPLICATION_HPP

#include <pito/config.hpp>
#include <pito/interceptor/jail/environment.hpp>

namespace pito { namespace interceptor {

namespace detail {
    void search_for_preload_library(std::string const& libraryFileName, std::string& preloadLibrary) {
        char const *ldPath = jail::getenv(PITO_LD_LIBRARY_PATH);
        if (ldPath) {
            char const *ldPathEnd = ldPath;
            while (*(++ldPathEnd) != '\0') {}

            char const *colon = ldPath;
            do {
                colon = std::find(colon, ldPathEnd, ':');
                if (colon != ldPath) {
                    preloadLibrary.assign(ldPath, colon);
                    preloadLibrary.append("/").append(libraryFileName);
                    if (! access(preloadLibrary.c_str(), R_OK)) return;
                    else preloadLibrary = "";
                }
                ldPath = ++colon;
            } while (colon < ldPathEnd);
        }

        preloadLibrary = PITO_LIB_PREFIX;
        preloadLibrary.append(libraryFileName);
        if (access(preloadLibrary.c_str(), R_OK)) preloadLibrary = "";
        else {
            // make the library an absolute path
            if (*jail::preload.begin() != '/') {
                char buff_[512];
                getcwd(buff_, sizeof(buff_));
                std::string newLibraryPath = buff_;
                newLibraryPath.append("/").append(jail::preload);
                jail::preload = newLibraryPath;
            }
        }
    }
}

void search_for_preload_library(std::string& libraryFileName, std::string& preloadLibrary) {
    libraryFileName.append(PITO_SHARED_LIB_FILE_EXTENSION);
    detail::search_for_preload_library(libraryFileName, preloadLibrary);
}

// search in $LD_LIBRARY_PATH, then installed location
void search_for_preload_library(std::string& libraryFileName, std::string& preloadLibrary, std::string const& pathOverride) {
    libraryFileName.append(PITO_SHARED_LIB_FILE_EXTENSION);
    if (! pathOverride.empty()) {
        if ('/' != *(preloadLibrary.end() - 1)) preloadLibrary.append("/");
        preloadLibrary.append(libraryFileName);
        if (! access(preloadLibrary.c_str(), R_OK)) return;
    }
    detail::search_for_preload_library(libraryFileName, preloadLibrary);
}

} }

#endif
<commit_msg>some missing stuffs<commit_after>#ifndef PITO_INTERCEPTOR_APPLICATION_HPP
#define PITO_INTERCEPTOR_APPLICATION_HPP

#include <pito/config.hpp>
#include <pito/interceptor/jail/environment.hpp>

namespace pito { namespace interceptor {

namespace detail {
    void search_for_preload_library(std::string const& libraryFileName, std::string& preloadLibrary) {
        char const *ldPath = jail::getenv(PITO_LD_LIBRARY_PATH);
        if (ldPath) {
            char const *ldPathEnd = ldPath;
            while (*(++ldPathEnd) != '\0') {}

            char const *colon = ldPath;
            do {
                colon = std::find(colon, ldPathEnd, ':');
                if (colon != ldPath) {
                    preloadLibrary.assign(ldPath, colon);
                    preloadLibrary.append("/").append(libraryFileName);
                    if (! access(preloadLibrary.c_str(), R_OK)) break;
                    else preloadLibrary = "";
                }
                ldPath = ++colon;
            } while (colon < ldPathEnd);
        }

        preloadLibrary = PITO_LIB_PREFIX;
        preloadLibrary.append(libraryFileName);
        if (access(preloadLibrary.c_str(), R_OK)) preloadLibrary = "";
        else {
            // make the library an absolute path
            if (*preloadLibrary.begin() != '/') {
                char buff_[512];
                getcwd(buff_, sizeof(buff_));
                std::string newLibraryPath = buff_;
                newLibraryPath.append("/").append(preloadLibrary);
                preloadLibrary = newLibraryPath;
            }
        }
    }
}

void search_for_preload_library(std::string& libraryFileName, std::string& preloadLibrary) {
    libraryFileName.append(PITO_SHARED_LIB_FILE_EXTENSION);
    detail::search_for_preload_library(libraryFileName, preloadLibrary);
}

// search in $LD_LIBRARY_PATH, then installed location
void search_for_preload_library(std::string& libraryFileName, std::string& preloadLibrary, std::string const& pathOverride) {
    libraryFileName.append(PITO_SHARED_LIB_FILE_EXTENSION);
    if (! pathOverride.empty()) {
        if ('/' != *(preloadLibrary.end() - 1)) preloadLibrary.append("/");
        preloadLibrary.append(libraryFileName);
        if (! access(preloadLibrary.c_str(), R_OK)) return;
    }
    detail::search_for_preload_library(libraryFileName, preloadLibrary);
}

} }

#endif
<|endoftext|>


<commit_before>/*
* Copyright 2017 Huy Cuong Nguyen
* Copyright 2017 Axel Waggershauser
*
* 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 "BitMatrixIO.h"
#include "BitArray.h"

#include <fstream>

namespace ZXing {

std::string ToString(const BitMatrix& matrix, char one, char zero, bool addSpace, bool printAsCString)
{
	std::string result;
	result.reserve((addSpace ? 2 : 1) * (matrix.width() * matrix.height()) + matrix.height());
	for (int y = 0; y < matrix.height(); ++y) {
		BitArray row;
		matrix.getRow(y, row);
		if (printAsCString)
			result += '"';
		for (auto bit : row) {
			result += bit ? one : zero;
			if (addSpace)
				result += ' ';
		}
		if (printAsCString)
			result += "\\n\"";
		result += '\n';
	}
	return result;
}

BitMatrix ParseBitMatrix(const std::string& str, char one, bool expectSpace)
{
	auto lineLength = str.find('\n');
	if (lineLength == std::string::npos)
		return {};

	int height = static_cast<int>(str.length() / (lineLength + 1));
	int width = static_cast<int>(expectSpace ? lineLength / 2 : lineLength);
	BitMatrix mat(width, height);
	for (int y = 0; y < height; ++y) {
		size_t offset = y * (lineLength + 1);
		for (int x = 0; x < width; ++x) {
			if (str.at(offset) == one)
				mat.set(x, y);
			offset += expectSpace ? 2 : 1;
		}
	}
	return mat;
}

void SaveAsPBM(const BitMatrix& matrix, const std::string filename, int quiteZone)
{
	auto out = Inflate(matrix.copy(), 0, 0, quiteZone);
	std::ofstream file(filename);
	file << "P1\n" << out.width() << ' ' << out.height() << '\n';
	file << ToString(out, '1', '0', true);
}

} // ZXing
<commit_msg>BitMatrixIO: code simplification<commit_after>/*
* Copyright 2017 Huy Cuong Nguyen
* Copyright 2017 Axel Waggershauser
*
* 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 "BitMatrixIO.h"
#include "BitArray.h"

#include <fstream>

namespace ZXing {

std::string ToString(const BitMatrix& matrix, char one, char zero, bool addSpace, bool printAsCString)
{
	std::string result;
	result.reserve((addSpace ? 2 : 1) * (matrix.width() * matrix.height()) + matrix.height());
	for (int y = 0; y < matrix.height(); ++y) {
		BitArray row;
		matrix.getRow(y, row);
		if (printAsCString)
			result += '"';
		for (auto bit : row) {
			result += bit ? one : zero;
			if (addSpace)
				result += ' ';
		}
		if (printAsCString)
			result += "\\n\"";
		result += '\n';
	}
	return result;
}

BitMatrix ParseBitMatrix(const std::string& str, char one, bool expectSpace)
{
	auto lineLength = str.find('\n');
	if (lineLength == std::string::npos)
		return {};

	int strStride = expectSpace ? 2 : 1;
	int height = static_cast<int>(str.length() / (lineLength + 1));
	int width = static_cast<int>(lineLength / strStride);
	BitMatrix mat(width, height);
	for (int y = 0; y < height; ++y) {
		size_t offset = y * (lineLength + 1);
		for (int x = 0; x < width; ++x, offset += strStride) {
			if (str[offset] == one)
				mat.set(x, y);
		}
	}
	return mat;
}

void SaveAsPBM(const BitMatrix& matrix, const std::string filename, int quiteZone)
{
	auto out = Inflate(matrix.copy(), 0, 0, quiteZone);
	std::ofstream file(filename);
	file << "P1\n" << out.width() << ' ' << out.height() << '\n';
	file << ToString(out, '1', '0', true);
}

} // ZXing
<|endoftext|>


<commit_before>#include "style.h"

#include "scene/scene.h"
#include "scene/sceneLayer.h"
#include "scene/light.h"
#include "tile/tile.h"
#include "gl/vboMesh.h"
#include "view/view.h"

namespace Tangram {

    Style::Style(std::string _name, Blending _blendMode, GLenum _drawMode) :
    m_name(_name),
    m_blend(_blendMode),
    m_drawMode(_drawMode),
    m_contextLost(true) {
}

Style::~Style() {}

void Style::build(const std::vector<std::unique_ptr<Light>>& _lights) {

    constructVertexLayout();
    constructShaderProgram();

    switch (m_lightingType) {
        case LightingType::vertex:
            m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_VERTEX\n", false);
            break;
        case LightingType::fragment:
            m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_FRAGMENT\n", false);
            break;
        default:
            break;
    }

    m_material->injectOnProgram(*m_shaderProgram);

    for (auto& light : _lights) {
        light->injectOnProgram(*m_shaderProgram);
    }

}

void Style::setMaterial(const std::shared_ptr<Material>& _material) {

    m_material = _material;

}

void Style::setLightingType(LightingType _type){

    m_lightingType = _type;

}

void Style::buildFeature(Tile& _tile, const Feature& _feat, const DrawRule& _rule) const {

    auto& mesh = _tile.getMesh(*this);

    if (!mesh) {
        mesh.reset(newMesh());
    }

    switch (_feat.geometryType) {
        case GeometryType::points:
            for (auto& point : _feat.points) {
                buildPoint(point, _rule, _feat.props, *mesh, _tile);
            }
            break;
        case GeometryType::lines:
            for (auto& line : _feat.lines) {
                buildLine(line, _rule, _feat.props, *mesh, _tile);
            }
            break;
        case GeometryType::polygons:
            for (auto& polygon : _feat.polygons) {
                buildPolygon(polygon, _rule, _feat.props, *mesh, _tile);
            }
            break;
        default:
            break;
    }

}

void Style::setupShaderUniforms(int _textureUnit, bool _update, Scene& _scene) {
    for (const auto& uniformPair : m_styleUniforms) {
        const auto& name = uniformPair.first;
        const auto& value = uniformPair.second;

        auto& textures = _scene.textures();

        if (value.is<std::string>()) {

            auto& tex = textures[value.get<std::string>()];

            tex->update(_textureUnit);
            tex->bind(_textureUnit);

            if (_update) {
                m_shaderProgram->setUniformi(name, _textureUnit);
            }

            _textureUnit++;

        } else {
            if (!_update) { continue; }

            if (value.is<bool>()) {
                m_shaderProgram->setUniformi(name, value.get<bool>());
            } else if(value.is<float>()) {
                m_shaderProgram->setUniformf(name, value.get<float>());
            } else if(value.is<glm::vec2>()) {
                m_shaderProgram->setUniformf(name, value.get<glm::vec2>());
            } else if(value.is<glm::vec3>()) {
                m_shaderProgram->setUniformf(name, value.get<glm::vec3>());
            } else if(value.is<glm::vec4>()) {
                m_shaderProgram->setUniformf(name, value.get<glm::vec4>());
            } else {
                // TODO: Throw away uniform on loading!
                // none_type
            }
        }
    }
}

void Style::onBeginDrawFrame(const View& _view, Scene& _scene) {

    bool contextLost = glContextLost();

    m_material->setupProgram(*m_shaderProgram);

    // Set up lights
    for (const auto& light : _scene.lights()) {
        light->setupProgram(_view, *m_shaderProgram);
    }

    // Set Map Position
    if (m_dirtyViewport) {
        const auto& mapPos = _view.getPosition();
        m_shaderProgram->setUniformf("u_resolution", _view.getWidth(), _view.getHeight());
        m_shaderProgram->setUniformf("u_map_position", mapPos.x, mapPos.y, _view.getZoom());
    }

    setupShaderUniforms(0, contextLost, _scene);

    // Configure render state
    switch (m_blend) {
        case Blending::none:
            RenderState::blending(GL_FALSE);
            RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
            RenderState::depthTest(GL_TRUE);
            RenderState::depthWrite(GL_TRUE);
            break;
        case Blending::add:
            RenderState::blending(GL_TRUE);
            RenderState::blendingFunc(GL_ONE, GL_ONE);
            RenderState::depthTest(GL_FALSE);
            RenderState::depthWrite(GL_TRUE);
            break;
        case Blending::multiply:
            RenderState::blending(GL_TRUE);
            RenderState::blendingFunc(GL_ZERO, GL_SRC_COLOR);
            RenderState::depthTest(GL_FALSE);
            RenderState::depthWrite(GL_TRUE);
            break;
        case Blending::overlay:
            RenderState::blending(GL_TRUE);
            RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
            RenderState::depthTest(GL_FALSE);
            RenderState::depthWrite(GL_FALSE);
            break;
        case Blending::inlay:
            // TODO: inlay does not behave correctly for labels because they don't have a z position
            RenderState::blending(GL_TRUE);
            RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
            RenderState::depthTest(GL_TRUE);
            RenderState::depthWrite(GL_FALSE);
            break;
        default:
            break;
    }
}

void Style::onBeginBuildTile(Tile& _tile) const {
    // No-op by default
}

void Style::onEndBuildTile(Tile& _tile) const {
    // No-op by default
}

void Style::buildPoint(const Point& _point, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const {
    // No-op by default
}

void Style::buildLine(const Line& _line, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const {
    // No-op by default
}

void Style::buildPolygon(const Polygon& _polygon, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const {
    // No-op by default
}

bool Style::glContextLost() {
    bool contextLost = m_contextLost;
    if (m_contextLost) {
        m_contextLost = false;
    }
    return contextLost;
}

}
<commit_msg>Respect 'visible' draw rule<commit_after>#include "style.h"

#include "scene/scene.h"
#include "scene/sceneLayer.h"
#include "scene/light.h"
#include "scene/styleParam.h"
#include "tile/tile.h"
#include "gl/vboMesh.h"
#include "view/view.h"

namespace Tangram {

    Style::Style(std::string _name, Blending _blendMode, GLenum _drawMode) :
    m_name(_name),
    m_blend(_blendMode),
    m_drawMode(_drawMode),
    m_contextLost(true) {
}

Style::~Style() {}

void Style::build(const std::vector<std::unique_ptr<Light>>& _lights) {

    constructVertexLayout();
    constructShaderProgram();

    switch (m_lightingType) {
        case LightingType::vertex:
            m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_VERTEX\n", false);
            break;
        case LightingType::fragment:
            m_shaderProgram->addSourceBlock("defines", "#define TANGRAM_LIGHTING_FRAGMENT\n", false);
            break;
        default:
            break;
    }

    m_material->injectOnProgram(*m_shaderProgram);

    for (auto& light : _lights) {
        light->injectOnProgram(*m_shaderProgram);
    }

}

void Style::setMaterial(const std::shared_ptr<Material>& _material) {

    m_material = _material;

}

void Style::setLightingType(LightingType _type){

    m_lightingType = _type;

}

void Style::buildFeature(Tile& _tile, const Feature& _feat, const DrawRule& _rule) const {

    bool visible;
    if (_rule.get(StyleParamKey::visible, visible) && !visible) {
        return;
    }

    auto& mesh = _tile.getMesh(*this);

    if (!mesh) {
        mesh.reset(newMesh());
    }

    switch (_feat.geometryType) {
        case GeometryType::points:
            for (auto& point : _feat.points) {
                buildPoint(point, _rule, _feat.props, *mesh, _tile);
            }
            break;
        case GeometryType::lines:
            for (auto& line : _feat.lines) {
                buildLine(line, _rule, _feat.props, *mesh, _tile);
            }
            break;
        case GeometryType::polygons:
            for (auto& polygon : _feat.polygons) {
                buildPolygon(polygon, _rule, _feat.props, *mesh, _tile);
            }
            break;
        default:
            break;
    }

}

void Style::setupShaderUniforms(int _textureUnit, bool _update, Scene& _scene) {
    for (const auto& uniformPair : m_styleUniforms) {
        const auto& name = uniformPair.first;
        const auto& value = uniformPair.second;

        auto& textures = _scene.textures();

        if (value.is<std::string>()) {

            auto& tex = textures[value.get<std::string>()];

            tex->update(_textureUnit);
            tex->bind(_textureUnit);

            if (_update) {
                m_shaderProgram->setUniformi(name, _textureUnit);
            }

            _textureUnit++;

        } else {
            if (!_update) { continue; }

            if (value.is<bool>()) {
                m_shaderProgram->setUniformi(name, value.get<bool>());
            } else if(value.is<float>()) {
                m_shaderProgram->setUniformf(name, value.get<float>());
            } else if(value.is<glm::vec2>()) {
                m_shaderProgram->setUniformf(name, value.get<glm::vec2>());
            } else if(value.is<glm::vec3>()) {
                m_shaderProgram->setUniformf(name, value.get<glm::vec3>());
            } else if(value.is<glm::vec4>()) {
                m_shaderProgram->setUniformf(name, value.get<glm::vec4>());
            } else {
                // TODO: Throw away uniform on loading!
                // none_type
            }
        }
    }
}

void Style::onBeginDrawFrame(const View& _view, Scene& _scene) {

    bool contextLost = glContextLost();

    m_material->setupProgram(*m_shaderProgram);

    // Set up lights
    for (const auto& light : _scene.lights()) {
        light->setupProgram(_view, *m_shaderProgram);
    }

    // Set Map Position
    if (m_dirtyViewport) {
        const auto& mapPos = _view.getPosition();
        m_shaderProgram->setUniformf("u_resolution", _view.getWidth(), _view.getHeight());
        m_shaderProgram->setUniformf("u_map_position", mapPos.x, mapPos.y, _view.getZoom());
    }

    setupShaderUniforms(0, contextLost, _scene);

    // Configure render state
    switch (m_blend) {
        case Blending::none:
            RenderState::blending(GL_FALSE);
            RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
            RenderState::depthTest(GL_TRUE);
            RenderState::depthWrite(GL_TRUE);
            break;
        case Blending::add:
            RenderState::blending(GL_TRUE);
            RenderState::blendingFunc(GL_ONE, GL_ONE);
            RenderState::depthTest(GL_FALSE);
            RenderState::depthWrite(GL_TRUE);
            break;
        case Blending::multiply:
            RenderState::blending(GL_TRUE);
            RenderState::blendingFunc(GL_ZERO, GL_SRC_COLOR);
            RenderState::depthTest(GL_FALSE);
            RenderState::depthWrite(GL_TRUE);
            break;
        case Blending::overlay:
            RenderState::blending(GL_TRUE);
            RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
            RenderState::depthTest(GL_FALSE);
            RenderState::depthWrite(GL_FALSE);
            break;
        case Blending::inlay:
            // TODO: inlay does not behave correctly for labels because they don't have a z position
            RenderState::blending(GL_TRUE);
            RenderState::blendingFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
            RenderState::depthTest(GL_TRUE);
            RenderState::depthWrite(GL_FALSE);
            break;
        default:
            break;
    }
}

void Style::onBeginBuildTile(Tile& _tile) const {
    // No-op by default
}

void Style::onEndBuildTile(Tile& _tile) const {
    // No-op by default
}

void Style::buildPoint(const Point& _point, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const {
    // No-op by default
}

void Style::buildLine(const Line& _line, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const {
    // No-op by default
}

void Style::buildPolygon(const Polygon& _polygon, const DrawRule& _rule, const Properties& _props, VboMesh& _mesh, Tile& _tile) const {
    // No-op by default
}

bool Style::glContextLost() {
    bool contextLost = m_contextLost;
    if (m_contextLost) {
        m_contextLost = false;
    }
    return contextLost;
}

}
<|endoftext|>


<commit_before>//=-- Profilesummary.cpp - Profile summary computation ----------------------=//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains support for computing profile summary data.
//
//===----------------------------------------------------------------------===//

#include "llvm/IR/Attributes.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Type.h"
#include "llvm/ProfileData/InstrProf.h"
#include "llvm/ProfileData/ProfileCommon.h"
#include "llvm/ProfileData/SampleProf.h"
#include "llvm/Support/Casting.h"

using namespace llvm;

// A set of cutoff values. Each value, when divided by ProfileSummary::Scale
// (which is 1000000) is a desired percentile of total counts.
const std::vector<uint32_t> ProfileSummary::DefaultCutoffs(
    {10000,  /*  1% */
     100000, /* 10% */
     200000, 300000, 400000, 500000, 600000, 500000, 600000, 700000, 800000,
     900000, 950000, 990000, 999000, 999900, 999990, 999999});
const char *ProfileSummary::KindStr[2] = {"InstrProf", "SampleProfile"};

void InstrProfSummary::addRecord(const InstrProfRecord &R) {
  addEntryCount(R.Counts[0]);
  for (size_t I = 1, E = R.Counts.size(); I < E; ++I)
    addInternalCount(R.Counts[I]);
}

// To compute the detailed summary, we consider each line containing samples as
// equivalent to a block with a count in the instrumented profile.
void SampleProfileSummary::addRecord(const sampleprof::FunctionSamples &FS) {
  NumFunctions++;
  if (FS.getHeadSamples() > MaxFunctionCount)
    MaxFunctionCount = FS.getHeadSamples();
  for (const auto &I : FS.getBodySamples())
    addCount(I.second.getSamples());
}

// The argument to this method is a vector of cutoff percentages and the return
// value is a vector of (Cutoff, MinCount, NumCounts) triplets.
void ProfileSummary::computeDetailedSummary() {
  if (DetailedSummaryCutoffs.empty())
    return;
  auto Iter = CountFrequencies.begin();
  auto End = CountFrequencies.end();
  std::sort(DetailedSummaryCutoffs.begin(), DetailedSummaryCutoffs.end());

  uint32_t CountsSeen = 0;
  uint64_t CurrSum = 0, Count = 0;

  for (uint32_t Cutoff : DetailedSummaryCutoffs) {
    assert(Cutoff <= 999999);
    APInt Temp(128, TotalCount);
    APInt N(128, Cutoff);
    APInt D(128, ProfileSummary::Scale);
    Temp *= N;
    Temp = Temp.sdiv(D);
    uint64_t DesiredCount = Temp.getZExtValue();
    assert(DesiredCount <= TotalCount);
    while (CurrSum < DesiredCount && Iter != End) {
      Count = Iter->first;
      uint32_t Freq = Iter->second;
      CurrSum += (Count * Freq);
      CountsSeen += Freq;
      Iter++;
    }
    assert(CurrSum >= DesiredCount);
    ProfileSummaryEntry PSE = {Cutoff, Count, CountsSeen};
    DetailedSummary.push_back(PSE);
  }
}

// Returns true if the function is a hot function.
bool ProfileSummary::isFunctionHot(const Function *F) {
  // FIXME: update when summary data is stored in module's metadata.
  return false;
}

// Returns true if the function is a cold function.
bool ProfileSummary::isFunctionUnlikely(const Function *F) {
  if (F->hasFnAttribute(Attribute::Cold)) {
    return true;
  }
  if (!F->getEntryCount()) {
    return false;
  }
  // FIXME: update when summary data is stored in module's metadata.
  return (*F->getEntryCount()) == 0;
}

InstrProfSummary::InstrProfSummary(const IndexedInstrProf::Summary &S)
    : ProfileSummary(PSK_Instr),
      MaxInternalBlockCount(
          S.get(IndexedInstrProf::Summary::MaxInternalBlockCount)) {

  TotalCount = S.get(IndexedInstrProf::Summary::TotalBlockCount);
  MaxCount = S.get(IndexedInstrProf::Summary::MaxBlockCount);
  MaxFunctionCount = S.get(IndexedInstrProf::Summary::MaxFunctionCount);
  NumCounts = S.get(IndexedInstrProf::Summary::TotalNumBlocks);
  NumFunctions = S.get(IndexedInstrProf::Summary::TotalNumFunctions);

  for (unsigned I = 0; I < S.NumCutoffEntries; I++) {
    const IndexedInstrProf::Summary::Entry &Ent = S.getEntry(I);
    DetailedSummary.emplace_back((uint32_t)Ent.Cutoff, Ent.MinBlockCount,
                                 Ent.NumBlocks);
  }
}

void InstrProfSummary::addEntryCount(uint64_t Count) {
  addCount(Count);
  NumFunctions++;
  if (Count > MaxFunctionCount)
    MaxFunctionCount = Count;
}

void InstrProfSummary::addInternalCount(uint64_t Count) {
  addCount(Count);
  if (Count > MaxInternalBlockCount)
    MaxInternalBlockCount = Count;
}

// Return an MDTuple with two elements. The first element is a string Key and
// the second is a uint64_t Value.
static Metadata *getKeyValMD(LLVMContext &Context, const char *Key,
                             uint64_t Val) {
  Type *Int64Ty = Type::getInt64Ty(Context);
  Metadata *Ops[2] = {MDString::get(Context, Key),
                      ConstantAsMetadata::get(ConstantInt::get(Int64Ty, Val))};
  return MDTuple::get(Context, Ops);
}

// Return an MDTuple with two elements. The first element is a string Key and
// the second is a string Value.
static Metadata *getKeyValMD(LLVMContext &Context, const char *Key,
                             const char *Val) {
  Metadata *Ops[2] = {MDString::get(Context, Key), MDString::get(Context, Val)};
  return MDTuple::get(Context, Ops);
}

// This returns an MDTuple representing the detiled summary. The tuple has two
// elements: a string "DetailedSummary" and an MDTuple representing the value
// of the detailed summary. Each element of this tuple is again an MDTuple whose
// elements are the (Cutoff, MinCount, NumCounts) triplet of the
// DetailedSummaryEntry.
Metadata *ProfileSummary::getDetailedSummaryMD(LLVMContext &Context) {
  std::vector<Metadata *> Entries;
  Type *Int32Ty = Type::getInt32Ty(Context);
  Type *Int64Ty = Type::getInt64Ty(Context);
  for (auto &Entry : DetailedSummary) {
    Metadata *EntryMD[3] = {
        ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Entry.Cutoff)),
        ConstantAsMetadata::get(ConstantInt::get(Int64Ty, Entry.MinCount)),
        ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Entry.NumCounts))};
    Entries.push_back(MDTuple::get(Context, EntryMD));
  }
  Metadata *Ops[2] = {MDString::get(Context, "DetailedSummary"),
                      MDTuple::get(Context, Entries)};
  return MDTuple::get(Context, Ops);
}

// This returns an MDTuple representing this ProfileSummary object. The first
// entry of this tuple is another MDTuple of two elements: a string
// "ProfileFormat" and a string representing the format ("InstrProf" or
// "SampleProfile"). The rest of the elements of the outer MDTuple are specific
// to the kind of profile summary as returned by getFormatSpecificMD.
Metadata *ProfileSummary::getMD(LLVMContext &Context) {
  std::vector<Metadata *> Components;
  Components.push_back(getKeyValMD(Context, "ProfileFormat", getKindStr()));
  std::vector<Metadata *> Res = getFormatSpecificMD(Context);
  Components.insert(Components.end(), Res.begin(), Res.end());
  return MDTuple::get(Context, Components);
}

// Returns a vector of MDTuples specific to InstrProfSummary. The first six
// elements of this vector are (Key, Val) pairs of the six scalar fields of
// InstrProfSummary (TotalCount, MaxBlockCount, MaxInternalBlockCount,
// MaxFunctionCount, NumBlocks, NumFunctions). The last element of this vector
// is an MDTuple returned by getDetailedSummaryMD.
std::vector<Metadata *>
InstrProfSummary::getFormatSpecificMD(LLVMContext &Context) {
  std::vector<Metadata *> Components;

  Components.push_back(getKeyValMD(Context, "TotalCount", getTotalCount()));
  Components.push_back(
      getKeyValMD(Context, "MaxBlockCount", getMaxBlockCount()));
  Components.push_back(getKeyValMD(Context, "MaxInternalBlockCount",
                                   getMaxInternalBlockCount()));
  Components.push_back(
      getKeyValMD(Context, "MaxFunctionCount", getMaxFunctionCount()));
  Components.push_back(getKeyValMD(Context, "NumBlocks", getNumBlocks()));
  Components.push_back(getKeyValMD(Context, "NumFunctions", getNumFunctions()));

  Components.push_back(getDetailedSummaryMD(Context));
  return Components;
}

std::vector<Metadata *>
SampleProfileSummary::getFormatSpecificMD(LLVMContext &Context) {
  std::vector<Metadata *> Components;

  Components.push_back(getKeyValMD(Context, "TotalSamples", getTotalSamples()));
  Components.push_back(
      getKeyValMD(Context, "MaxSamplesPerLine", getMaxSamplesPerLine()));
  Components.push_back(
      getKeyValMD(Context, "MaxFunctionCount", getMaxFunctionCount()));
  Components.push_back(
      getKeyValMD(Context, "NumLinesWithSamples", getNumLinesWithSamples()));
  Components.push_back(getKeyValMD(Context, "NumFunctions", NumFunctions));

  Components.push_back(getDetailedSummaryMD(Context));
  return Components;
}

// Parse an MDTuple representing (Key, Val) pair.
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val) {
  if (!MD)
    return false;
  if (MD->getNumOperands() != 2)
    return false;
  MDString *KeyMD = dyn_cast<MDString>(MD->getOperand(0));
  ConstantAsMetadata *ValMD = dyn_cast<ConstantAsMetadata>(MD->getOperand(1));
  if (!KeyMD || !ValMD)
    return false;
  if (!KeyMD->getString().equals(Key))
    return false;
  Val = cast<ConstantInt>(ValMD->getValue())->getZExtValue();
  return true;
}

// Check if an MDTuple represents a (Key, Val) pair.
static bool isKeyValuePair(MDTuple *MD, const char *Key, const char *Val) {
  if (!MD || MD->getNumOperands() != 2)
    return false;
  MDString *KeyMD = dyn_cast<MDString>(MD->getOperand(0));
  MDString *ValMD = dyn_cast<MDString>(MD->getOperand(1));
  if (!KeyMD || !ValMD)
    return false;
  if (!KeyMD->getString().equals(Key) || !ValMD->getString().equals(Val))
    return false;
  return true;
}

// Parse an MDTuple representing detailed summary.
static bool getSummaryFromMD(MDTuple *MD, SummaryEntryVector &Summary) {
  if (!MD || MD->getNumOperands() != 2)
    return false;
  MDString *KeyMD = dyn_cast<MDString>(MD->getOperand(0));
  if (!KeyMD || !KeyMD->getString().equals("DetailedSummary"))
    return false;
  MDTuple *EntriesMD = dyn_cast<MDTuple>(MD->getOperand(1));
  if (!EntriesMD)
    return false;
  for (auto &&MDOp : EntriesMD->operands()) {
    MDTuple *EntryMD = dyn_cast<MDTuple>(MDOp);
    if (!EntryMD || EntryMD->getNumOperands() != 3)
      return false;
    ConstantAsMetadata *Op0 =
        dyn_cast<ConstantAsMetadata>(EntryMD->getOperand(0));
    ConstantAsMetadata *Op1 =
        dyn_cast<ConstantAsMetadata>(EntryMD->getOperand(1));
    ConstantAsMetadata *Op2 =
        dyn_cast<ConstantAsMetadata>(EntryMD->getOperand(2));

    if (!Op0 || !Op1 || !Op2)
      return false;
    Summary.emplace_back(cast<ConstantInt>(Op0->getValue())->getZExtValue(),
                         cast<ConstantInt>(Op1->getValue())->getZExtValue(),
                         cast<ConstantInt>(Op2->getValue())->getZExtValue());
  }
  return true;
}

// Parse an MDTuple representing an InstrProfSummary object.
static ProfileSummary *getInstrProfSummaryFromMD(MDTuple *Tuple) {
  uint64_t NumBlocks, TotalCount, NumFunctions, MaxFunctionCount, MaxBlockCount,
      MaxInternalBlockCount;
  SummaryEntryVector Summary;

  if (Tuple->getNumOperands() != 8)
    return nullptr;

  // Skip operand 0 which has been already parsed in the caller
  if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(1)), "TotalCount",
              TotalCount))
    return nullptr;
  if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(2)), "MaxBlockCount",
              MaxBlockCount))
    return nullptr;
  if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(3)), "MaxInternalBlockCount",
              MaxInternalBlockCount))
    return nullptr;
  if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(4)), "MaxFunctionCount",
              MaxFunctionCount))
    return nullptr;
  if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(5)), "NumBlocks", NumBlocks))
    return nullptr;
  if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(6)), "NumFunctions",
              NumFunctions))
    return nullptr;
  if (!getSummaryFromMD(dyn_cast<MDTuple>(Tuple->getOperand(7)), Summary))
    return nullptr;
  return new InstrProfSummary(TotalCount, MaxBlockCount, MaxInternalBlockCount,
                              MaxFunctionCount, NumBlocks, NumFunctions,
                              Summary);
}

// Parse an MDTuple representing a SampleProfileSummary object.
static ProfileSummary *getSampleProfileSummaryFromMD(MDTuple *Tuple) {
  uint64_t TotalSamples, MaxSamplesPerLine, MaxFunctionCount,
      NumLinesWithSamples, NumFunctions;
  SummaryEntryVector Summary;

  if (Tuple->getNumOperands() != 7)
    return nullptr;

  // Skip operand 0 which has been already parsed in the caller
  if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(1)), "TotalSamples",
              TotalSamples))
    return nullptr;
  if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(2)), "MaxSamplesPerLine",
              MaxSamplesPerLine))
    return nullptr;
  if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(3)), "MaxFunctionCount",
              MaxFunctionCount))
    return nullptr;
  if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(4)), "NumLinesWithSamples",
              NumLinesWithSamples))
    return nullptr;
  if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(5)), "NumFunctions",
              NumFunctions))
    return nullptr;
  if (!getSummaryFromMD(dyn_cast<MDTuple>(Tuple->getOperand(6)), Summary))
    return nullptr;
  return new SampleProfileSummary(TotalSamples, MaxSamplesPerLine,
                                  MaxFunctionCount, NumLinesWithSamples,
                                  NumFunctions, Summary);
}

ProfileSummary *ProfileSummary::getFromMD(Metadata *MD) {
  if (!isa<MDTuple>(MD))
    return nullptr;
  MDTuple *Tuple = cast<MDTuple>(MD);
  auto &FormatMD = Tuple->getOperand(0);
  if (isKeyValuePair(dyn_cast_or_null<MDTuple>(FormatMD), "ProfileFormat",
                     "SampleProfile"))
    return getSampleProfileSummaryFromMD(Tuple);
  else if (isKeyValuePair(dyn_cast_or_null<MDTuple>(FormatMD), "ProfileFormat",
                          "InstrProf"))
    return getInstrProfSummaryFromMD(Tuple);
  else
    return nullptr;
}
<commit_msg>Add a note about the "entry count" used the profile summary<commit_after>//=-- Profilesummary.cpp - Profile summary computation ----------------------=//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains support for computing profile summary data.
//
//===----------------------------------------------------------------------===//

#include "llvm/IR/Attributes.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Type.h"
#include "llvm/ProfileData/InstrProf.h"
#include "llvm/ProfileData/ProfileCommon.h"
#include "llvm/ProfileData/SampleProf.h"
#include "llvm/Support/Casting.h"

using namespace llvm;

// A set of cutoff values. Each value, when divided by ProfileSummary::Scale
// (which is 1000000) is a desired percentile of total counts.
const std::vector<uint32_t> ProfileSummary::DefaultCutoffs(
    {10000,  /*  1% */
     100000, /* 10% */
     200000, 300000, 400000, 500000, 600000, 500000, 600000, 700000, 800000,
     900000, 950000, 990000, 999000, 999900, 999990, 999999});
const char *ProfileSummary::KindStr[2] = {"InstrProf", "SampleProfile"};

void InstrProfSummary::addRecord(const InstrProfRecord &R) {
  // The first counter is not necessarily an entry count for IR
  // instrumentation profiles.
  // Eventually MaxFunctionCount will become obsolete and this can be
  // removed.
  addEntryCount(R.Counts[0]);
  for (size_t I = 1, E = R.Counts.size(); I < E; ++I)
    addInternalCount(R.Counts[I]);
}

// To compute the detailed summary, we consider each line containing samples as
// equivalent to a block with a count in the instrumented profile.
void SampleProfileSummary::addRecord(const sampleprof::FunctionSamples &FS) {
  NumFunctions++;
  if (FS.getHeadSamples() > MaxFunctionCount)
    MaxFunctionCount = FS.getHeadSamples();
  for (const auto &I : FS.getBodySamples())
    addCount(I.second.getSamples());
}

// The argument to this method is a vector of cutoff percentages and the return
// value is a vector of (Cutoff, MinCount, NumCounts) triplets.
void ProfileSummary::computeDetailedSummary() {
  if (DetailedSummaryCutoffs.empty())
    return;
  auto Iter = CountFrequencies.begin();
  auto End = CountFrequencies.end();
  std::sort(DetailedSummaryCutoffs.begin(), DetailedSummaryCutoffs.end());

  uint32_t CountsSeen = 0;
  uint64_t CurrSum = 0, Count = 0;

  for (uint32_t Cutoff : DetailedSummaryCutoffs) {
    assert(Cutoff <= 999999);
    APInt Temp(128, TotalCount);
    APInt N(128, Cutoff);
    APInt D(128, ProfileSummary::Scale);
    Temp *= N;
    Temp = Temp.sdiv(D);
    uint64_t DesiredCount = Temp.getZExtValue();
    assert(DesiredCount <= TotalCount);
    while (CurrSum < DesiredCount && Iter != End) {
      Count = Iter->first;
      uint32_t Freq = Iter->second;
      CurrSum += (Count * Freq);
      CountsSeen += Freq;
      Iter++;
    }
    assert(CurrSum >= DesiredCount);
    ProfileSummaryEntry PSE = {Cutoff, Count, CountsSeen};
    DetailedSummary.push_back(PSE);
  }
}

// Returns true if the function is a hot function.
bool ProfileSummary::isFunctionHot(const Function *F) {
  // FIXME: update when summary data is stored in module's metadata.
  return false;
}

// Returns true if the function is a cold function.
bool ProfileSummary::isFunctionUnlikely(const Function *F) {
  if (F->hasFnAttribute(Attribute::Cold)) {
    return true;
  }
  if (!F->getEntryCount()) {
    return false;
  }
  // FIXME: update when summary data is stored in module's metadata.
  return (*F->getEntryCount()) == 0;
}

InstrProfSummary::InstrProfSummary(const IndexedInstrProf::Summary &S)
    : ProfileSummary(PSK_Instr),
      MaxInternalBlockCount(
          S.get(IndexedInstrProf::Summary::MaxInternalBlockCount)) {

  TotalCount = S.get(IndexedInstrProf::Summary::TotalBlockCount);
  MaxCount = S.get(IndexedInstrProf::Summary::MaxBlockCount);
  MaxFunctionCount = S.get(IndexedInstrProf::Summary::MaxFunctionCount);
  NumCounts = S.get(IndexedInstrProf::Summary::TotalNumBlocks);
  NumFunctions = S.get(IndexedInstrProf::Summary::TotalNumFunctions);

  for (unsigned I = 0; I < S.NumCutoffEntries; I++) {
    const IndexedInstrProf::Summary::Entry &Ent = S.getEntry(I);
    DetailedSummary.emplace_back((uint32_t)Ent.Cutoff, Ent.MinBlockCount,
                                 Ent.NumBlocks);
  }
}

void InstrProfSummary::addEntryCount(uint64_t Count) {
  addCount(Count);
  NumFunctions++;
  if (Count > MaxFunctionCount)
    MaxFunctionCount = Count;
}

void InstrProfSummary::addInternalCount(uint64_t Count) {
  addCount(Count);
  if (Count > MaxInternalBlockCount)
    MaxInternalBlockCount = Count;
}

// Return an MDTuple with two elements. The first element is a string Key and
// the second is a uint64_t Value.
static Metadata *getKeyValMD(LLVMContext &Context, const char *Key,
                             uint64_t Val) {
  Type *Int64Ty = Type::getInt64Ty(Context);
  Metadata *Ops[2] = {MDString::get(Context, Key),
                      ConstantAsMetadata::get(ConstantInt::get(Int64Ty, Val))};
  return MDTuple::get(Context, Ops);
}

// Return an MDTuple with two elements. The first element is a string Key and
// the second is a string Value.
static Metadata *getKeyValMD(LLVMContext &Context, const char *Key,
                             const char *Val) {
  Metadata *Ops[2] = {MDString::get(Context, Key), MDString::get(Context, Val)};
  return MDTuple::get(Context, Ops);
}

// This returns an MDTuple representing the detiled summary. The tuple has two
// elements: a string "DetailedSummary" and an MDTuple representing the value
// of the detailed summary. Each element of this tuple is again an MDTuple whose
// elements are the (Cutoff, MinCount, NumCounts) triplet of the
// DetailedSummaryEntry.
Metadata *ProfileSummary::getDetailedSummaryMD(LLVMContext &Context) {
  std::vector<Metadata *> Entries;
  Type *Int32Ty = Type::getInt32Ty(Context);
  Type *Int64Ty = Type::getInt64Ty(Context);
  for (auto &Entry : DetailedSummary) {
    Metadata *EntryMD[3] = {
        ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Entry.Cutoff)),
        ConstantAsMetadata::get(ConstantInt::get(Int64Ty, Entry.MinCount)),
        ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Entry.NumCounts))};
    Entries.push_back(MDTuple::get(Context, EntryMD));
  }
  Metadata *Ops[2] = {MDString::get(Context, "DetailedSummary"),
                      MDTuple::get(Context, Entries)};
  return MDTuple::get(Context, Ops);
}

// This returns an MDTuple representing this ProfileSummary object. The first
// entry of this tuple is another MDTuple of two elements: a string
// "ProfileFormat" and a string representing the format ("InstrProf" or
// "SampleProfile"). The rest of the elements of the outer MDTuple are specific
// to the kind of profile summary as returned by getFormatSpecificMD.
Metadata *ProfileSummary::getMD(LLVMContext &Context) {
  std::vector<Metadata *> Components;
  Components.push_back(getKeyValMD(Context, "ProfileFormat", getKindStr()));
  std::vector<Metadata *> Res = getFormatSpecificMD(Context);
  Components.insert(Components.end(), Res.begin(), Res.end());
  return MDTuple::get(Context, Components);
}

// Returns a vector of MDTuples specific to InstrProfSummary. The first six
// elements of this vector are (Key, Val) pairs of the six scalar fields of
// InstrProfSummary (TotalCount, MaxBlockCount, MaxInternalBlockCount,
// MaxFunctionCount, NumBlocks, NumFunctions). The last element of this vector
// is an MDTuple returned by getDetailedSummaryMD.
std::vector<Metadata *>
InstrProfSummary::getFormatSpecificMD(LLVMContext &Context) {
  std::vector<Metadata *> Components;

  Components.push_back(getKeyValMD(Context, "TotalCount", getTotalCount()));
  Components.push_back(
      getKeyValMD(Context, "MaxBlockCount", getMaxBlockCount()));
  Components.push_back(getKeyValMD(Context, "MaxInternalBlockCount",
                                   getMaxInternalBlockCount()));
  Components.push_back(
      getKeyValMD(Context, "MaxFunctionCount", getMaxFunctionCount()));
  Components.push_back(getKeyValMD(Context, "NumBlocks", getNumBlocks()));
  Components.push_back(getKeyValMD(Context, "NumFunctions", getNumFunctions()));

  Components.push_back(getDetailedSummaryMD(Context));
  return Components;
}

std::vector<Metadata *>
SampleProfileSummary::getFormatSpecificMD(LLVMContext &Context) {
  std::vector<Metadata *> Components;

  Components.push_back(getKeyValMD(Context, "TotalSamples", getTotalSamples()));
  Components.push_back(
      getKeyValMD(Context, "MaxSamplesPerLine", getMaxSamplesPerLine()));
  Components.push_back(
      getKeyValMD(Context, "MaxFunctionCount", getMaxFunctionCount()));
  Components.push_back(
      getKeyValMD(Context, "NumLinesWithSamples", getNumLinesWithSamples()));
  Components.push_back(getKeyValMD(Context, "NumFunctions", NumFunctions));

  Components.push_back(getDetailedSummaryMD(Context));
  return Components;
}

// Parse an MDTuple representing (Key, Val) pair.
static bool getVal(MDTuple *MD, const char *Key, uint64_t &Val) {
  if (!MD)
    return false;
  if (MD->getNumOperands() != 2)
    return false;
  MDString *KeyMD = dyn_cast<MDString>(MD->getOperand(0));
  ConstantAsMetadata *ValMD = dyn_cast<ConstantAsMetadata>(MD->getOperand(1));
  if (!KeyMD || !ValMD)
    return false;
  if (!KeyMD->getString().equals(Key))
    return false;
  Val = cast<ConstantInt>(ValMD->getValue())->getZExtValue();
  return true;
}

// Check if an MDTuple represents a (Key, Val) pair.
static bool isKeyValuePair(MDTuple *MD, const char *Key, const char *Val) {
  if (!MD || MD->getNumOperands() != 2)
    return false;
  MDString *KeyMD = dyn_cast<MDString>(MD->getOperand(0));
  MDString *ValMD = dyn_cast<MDString>(MD->getOperand(1));
  if (!KeyMD || !ValMD)
    return false;
  if (!KeyMD->getString().equals(Key) || !ValMD->getString().equals(Val))
    return false;
  return true;
}

// Parse an MDTuple representing detailed summary.
static bool getSummaryFromMD(MDTuple *MD, SummaryEntryVector &Summary) {
  if (!MD || MD->getNumOperands() != 2)
    return false;
  MDString *KeyMD = dyn_cast<MDString>(MD->getOperand(0));
  if (!KeyMD || !KeyMD->getString().equals("DetailedSummary"))
    return false;
  MDTuple *EntriesMD = dyn_cast<MDTuple>(MD->getOperand(1));
  if (!EntriesMD)
    return false;
  for (auto &&MDOp : EntriesMD->operands()) {
    MDTuple *EntryMD = dyn_cast<MDTuple>(MDOp);
    if (!EntryMD || EntryMD->getNumOperands() != 3)
      return false;
    ConstantAsMetadata *Op0 =
        dyn_cast<ConstantAsMetadata>(EntryMD->getOperand(0));
    ConstantAsMetadata *Op1 =
        dyn_cast<ConstantAsMetadata>(EntryMD->getOperand(1));
    ConstantAsMetadata *Op2 =
        dyn_cast<ConstantAsMetadata>(EntryMD->getOperand(2));

    if (!Op0 || !Op1 || !Op2)
      return false;
    Summary.emplace_back(cast<ConstantInt>(Op0->getValue())->getZExtValue(),
                         cast<ConstantInt>(Op1->getValue())->getZExtValue(),
                         cast<ConstantInt>(Op2->getValue())->getZExtValue());
  }
  return true;
}

// Parse an MDTuple representing an InstrProfSummary object.
static ProfileSummary *getInstrProfSummaryFromMD(MDTuple *Tuple) {
  uint64_t NumBlocks, TotalCount, NumFunctions, MaxFunctionCount, MaxBlockCount,
      MaxInternalBlockCount;
  SummaryEntryVector Summary;

  if (Tuple->getNumOperands() != 8)
    return nullptr;

  // Skip operand 0 which has been already parsed in the caller
  if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(1)), "TotalCount",
              TotalCount))
    return nullptr;
  if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(2)), "MaxBlockCount",
              MaxBlockCount))
    return nullptr;
  if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(3)), "MaxInternalBlockCount",
              MaxInternalBlockCount))
    return nullptr;
  if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(4)), "MaxFunctionCount",
              MaxFunctionCount))
    return nullptr;
  if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(5)), "NumBlocks", NumBlocks))
    return nullptr;
  if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(6)), "NumFunctions",
              NumFunctions))
    return nullptr;
  if (!getSummaryFromMD(dyn_cast<MDTuple>(Tuple->getOperand(7)), Summary))
    return nullptr;
  return new InstrProfSummary(TotalCount, MaxBlockCount, MaxInternalBlockCount,
                              MaxFunctionCount, NumBlocks, NumFunctions,
                              Summary);
}

// Parse an MDTuple representing a SampleProfileSummary object.
static ProfileSummary *getSampleProfileSummaryFromMD(MDTuple *Tuple) {
  uint64_t TotalSamples, MaxSamplesPerLine, MaxFunctionCount,
      NumLinesWithSamples, NumFunctions;
  SummaryEntryVector Summary;

  if (Tuple->getNumOperands() != 7)
    return nullptr;

  // Skip operand 0 which has been already parsed in the caller
  if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(1)), "TotalSamples",
              TotalSamples))
    return nullptr;
  if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(2)), "MaxSamplesPerLine",
              MaxSamplesPerLine))
    return nullptr;
  if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(3)), "MaxFunctionCount",
              MaxFunctionCount))
    return nullptr;
  if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(4)), "NumLinesWithSamples",
              NumLinesWithSamples))
    return nullptr;
  if (!getVal(dyn_cast<MDTuple>(Tuple->getOperand(5)), "NumFunctions",
              NumFunctions))
    return nullptr;
  if (!getSummaryFromMD(dyn_cast<MDTuple>(Tuple->getOperand(6)), Summary))
    return nullptr;
  return new SampleProfileSummary(TotalSamples, MaxSamplesPerLine,
                                  MaxFunctionCount, NumLinesWithSamples,
                                  NumFunctions, Summary);
}

ProfileSummary *ProfileSummary::getFromMD(Metadata *MD) {
  if (!isa<MDTuple>(MD))
    return nullptr;
  MDTuple *Tuple = cast<MDTuple>(MD);
  auto &FormatMD = Tuple->getOperand(0);
  if (isKeyValuePair(dyn_cast_or_null<MDTuple>(FormatMD), "ProfileFormat",
                     "SampleProfile"))
    return getSampleProfileSummaryFromMD(Tuple);
  else if (isKeyValuePair(dyn_cast_or_null<MDTuple>(FormatMD), "ProfileFormat",
                          "InstrProf"))
    return getInstrProfSummaryFromMD(Tuple);
  else
    return nullptr;
}
<|endoftext|>