<commit_before>AliAnalysisTaskElectronEfficiencyV2* AddTask_rbailhac_ElectronEfficiencyV2_PbPb(Bool_t getFromAlien = kFALSE,
										TString cFileName ="Config_rbailhac_ElectronEfficiencyV2_PbPb.C",
										UInt_t trigger = AliVEvent::kINT7,
										Int_t rejpileup = 1,
										const Int_t CenMin =  0,
										const Int_t CenMax = 10,
										const Float_t PtMin =  0.2,
										const Float_t PtMax = 10.0,
										const Float_t EtaMin = -0.8,
										const Float_t EtaMax = +0.8,
										const Bool_t UsePtVec = kTRUE,
										const Bool_t DoULSLS = kTRUE,
										const TString generators = "pizero_0;eta_1;etaprime_2;rho_3;omega_4;phi_5;jpsi_6;Pythia CC_0;Pythia BB_0;Pythia B_0;",
										const std::string resolutionFilename ="",
										const std::string cocktailFilename   ="",
										const std::string centralityFilename ="",
										const TString outname = "LMEE.root")
{

  //get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTask_rbailhac_test", "No analysis manager found.");
    return 0;
  }

  //Base Directory for GRID / LEGO Train
  TString configBasePath= "$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/";
  if(getFromAlien && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/r/rbailhac/PWGDQ/dielectron/macrosLMEE/%s .",cFileName.Data()))) ){
    configBasePath=Form("%s/",gSystem->pwd());
  }

  TString configFilePath(configBasePath+cFileName);

  std::cout << "Configpath:  " << configFilePath << std::endl;

  if (!gROOT->GetListOfGlobalFunctions()->FindObject("Config_rbailhac_ElectronEfficiencyV2_PbPb")) {
    printf("Load macro now\n");
    gROOT->LoadMacro(configFilePath.Data());
  }

  // trigger
  TString triggername = "NULL";
  if(trigger == (UInt_t)AliVEvent::kINT7)             triggername = "kINT7";
  else if(trigger == (UInt_t)AliVEvent::kCentral)     triggername = "kCentral";
  else if(trigger == (UInt_t)AliVEvent::kSemiCentral) triggername = "kSemiCentral";
  else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral | AliVEvent::kSemiCentral)) triggername = "kCombinedCentralityTriggers";
  else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral))                           triggername = "kCombinedCentral";
  else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kSemiCentral))                       triggername = "kCombinedSemiCentral";

  // generators
  TString suffixgen = "";
  if(generators.Contains("Pythia CC") && (generators.Contains("Pythia BB") || generators.Contains("Pythia B"))) suffixgen = "_CC_BB";
  else if(generators.Contains("Pythia CC")) suffixgen = "_CC";
  else if(generators.Contains("Pythia BB") || generators.Contains("Pythia B")) suffixgen = "_BB";
  else if(generators.Contains("pizero_0")) suffixgen = "_LF";
  else suffixgen = "";

  // generator index
  TString suffixgenID = "";
  std::vector<UInt_t> genID;
  const Int_t ngenID = (Int_t)gROOT->ProcessLine("GetGenID()");
  if(ngenID > 0) {
    for (unsigned int i = 0; i < ngenID+1; ++i){
      UInt_t valuegenID = (UInt_t)(gROOT->ProcessLine(Form("GetGenID(%d)",i)));
      genID.push_back(valuegenID);
      suffixgenID += valuegenID;
    }
  }

  //create task and add it to the manager (MB)
  TString appendix;
  appendix += TString::Format("Cen%d_%d_%s_%s_%s",CenMin,CenMax,triggername.Data(),suffixgen.Data(),suffixgenID.Data());
  printf("appendix %s\n", appendix.Data());

  //##########################################################
  //############################################################
  // Creating an instance of the task
  AliAnalysisTaskElectronEfficiencyV2* task = new AliAnalysisTaskElectronEfficiencyV2(Form("TaskElectronEfficiencyV2_%s",appendix.Data()));
  gROOT->GetListOfSpecials()->Add(task);//this is only for ProcessLine(AddMCSignal);

  // #########################################################
  // #########################################################
  // Set TOF correction
  // if(tofcor){
  //  SetEtaCorrectionTOFRMS(task, AliDielectronVarManager::kP, AliDielectronVarManager::kEta);
  //  SetEtaCorrectionTOFMean(task, AliDielectronVarManager::kP, AliDielectronVarManager::kEta);
  //}

  // #########################################################
  // #########################################################
  // Event selection. Is the same for all the different cutsettings
  task->SetEnablePhysicsSelection(kTRUE);//always ON in Run2 analyses for both data and MC.
  task->SetTriggerMask(trigger);
  task->SetEventFilter((reinterpret_cast<AliDielectronEventCuts*>(gROOT->ProcessLine(Form("GetEventCuts(%f,%f,%d,\"%s\")",(Float_t)CenMin,(Float_t)CenMax,rejpileup,"V0M")))));

  // #########################################################
  // #########################################################
  // Set minimum and maximum values of generated tracks. Only used to save computing power.
  // Do not set here your analysis pt-cuts
  task->SetMinPtGen(0.1);
  task->SetMaxPtGen(1e+10);
  task->SetMinEtaGen(-1.5);
  task->SetMaxEtaGen(+1.5);

  // #########################################################
  // #########################################################
  // Set minimum and maximum values for pairing
  task->SetKinematicCuts(PtMin, PtMax, EtaMin, EtaMax);

  // #########################################################
  // #########################################################
  // Set Binning single variables
  if (UsePtVec == true) {
    const Int_t Npt = 68;
    Double_t pte[Npt] = {0.00,0.10,0.11,0.12,0.13,0.14,0.15,0.155,0.16,0.165,0.17,0.175,0.18,0.185,0.19,0.195,0.20,0.205,0.21,0.215,0.22,0.225,0.23,0.235,0.24,0.245,0.25,0.255,0.26,0.265,0.27,0.275,0.28,0.285,0.29,0.295,0.30,0.32,0.34,0.36,0.38,0.40,0.43,0.46,0.49,0.52,0.55,0.60,0.65,0.70,0.75,0.80,0.90,1.00,1.10,1.20,1.40,1.60,1.80,2.00,2.40,2.80,3.20,3.70,4.50,6.00,8.00,12.0};
    std::vector<double> v_pte(pte,std::end(pte));
    task->SetPtBins(v_pte);
  }
  else task->SetPtBinsLinear   (0,  10, 100);
  task->SetEtaBinsLinear (-1.,1.,20); // 40 before
  task->SetPhiBinsLinear  (0, TMath::TwoPi(), 36); // 90 before
  task->SetThetaBinsLinear(0, TMath::TwoPi(), 60);

  // pair variables
  const Int_t Nmee = 150;
  Double_t mee[Nmee] = {};
  for(Int_t i=0  ;i<110 ;i++) mee[i] = 0.01 * (i-  0) +  0.0;//from 0 to 1.09 GeV/c2, every 0.01 GeV/c2
  for(Int_t i=110;i<Nmee;i++) mee[i] = 0.1  * (i-110) +  1.1;//from 1.1 to 5 GeV/c2, evety 0.1 GeV/c2
  std::vector<double> v_mee(mee,std::end(mee));

  const Int_t NpTee = 130;
  Double_t pTee[NpTee] = {};
  for(Int_t i=0  ;i<20   ;i++) pTee[i] = 0.005 * (i-  0) +  0.0;//from 0 to 0.095 GeV/c, every 0.005 GeV/c
  for(Int_t i=20 ;i<119  ;i++) pTee[i] = 0.1  * (i- 20) +  0.1;//from 0.1 to 9.9 GeV/c, evety 0.1 GeV/c
  for(Int_t i=119;i<NpTee;i++) pTee[i] = 1.0  * (i-119) + 10.0;//from 10 to 20 GeV/c, evety 1.0 GeV/c
  std::vector<double> v_pTee(pTee,std::end(pTee));
  task->SetMassBins(v_mee);
  task->SetPairPtBins(v_pTee);
  //task->SetPhiVBinsLinear(0, TMath::Pi(), 100);
  //task->SetFillPhiV(kTRUE);

  // #########################################################
  // #########################################################
  //task->SetSmearGenerated(kFALSE); // cross check smearing the MC at single level and filling resolution maps
 // Resolution File, If resoFilename = "" no correction is applied
  task->SetResolutionFile(resolutionFilename);
  task->SetResolutionFileFromAlien("/alice/cern.ch/user/r/rbailhac/supportFiles/" + resolutionFilename);
  task->SetResolutionDeltaPtBinsLinear   (-10., 2., (Int_t)gROOT->ProcessLine("GetNbinsDeltaMom()"));
  task->SetResolutionRelPtBinsLinear   (0., 2.,  (Int_t)gROOT->ProcessLine("GetNbinsRelMom()"));
  task->SetResolutionEtaBinsLinear  (-0.4, 0.4, (Int_t)gROOT->ProcessLine("GetNbinsDeltaEta()"));
  task->SetResolutionPhiBinsLinear  (-0.4, 0.4, (Int_t)gROOT->ProcessLine("GetNbinsDeltaPhi()"));
  task->SetResolutionThetaBinsLinear(-0.4, 0.4, (Int_t)gROOT->ProcessLine("GetNbinsDeltaTheta()"));

  //###########################################################
  //############################################################
  // Set MCSignal and Cutsetting to fill the support histograms
  task->SetSupportHistoMCSignalAndCutsetting(0,0);//fill support histograms for first MCsignal and first cutsetting

  // #########################################################
  // #########################################################
  // Set centrality correction. If resoFilename = "" no correction is applied
  task->SetCentralityFile(centralityFilename);

  // #########################################################
  // #########################################################
  // Pairing related config
  task->SetDoPairing(kTRUE);
  task->SetULSandLS(DoULSLS);

  //#####################################################
  //######################################################
  // Generators
  cout<<"Efficiency based on MC generators: " << generators <<endl;
  TString generatorsPair=generators;
  task->SetGeneratorMCSignalName(generatorsPair);
  task->SetGeneratorULSSignalName(generators);

  //#################################################
  //#################################################
  // generator ID to select pile-up or not
  if(ngenID > 0) {
    task->SetGeneratorMCSignalIndex(genID);
    task->SetGeneratorULSSignalIndex(genID);
    task->SetCheckGenID(kTRUE);
  }

  //###############################################
  //##############################################
  task->SetCocktailWeighting(cocktailFilename);
  task->SetCocktailWeightingFromAlien("/alice/cern.ch/user/r/rbailhac/supportFiles/" + cocktailFilename);

  // #########################################################
  // #########################################################
  // Add MCSignals. Can be set to see differences of:
  // e.g. secondaries and primaries. or primaries from charm and resonances
  gROOT->ProcessLine(Form("AddSingleLegMCSignal(%s)",task->GetName()));//not task itself, task name
  gROOT->ProcessLine(Form("AddPairMCSignal(%s)"     ,task->GetName()));//not task itself, task name

  // #########################################################
  // #########################################################
  // Adding cutsettings
 // Cuts
  // Number of cuts
  const Int_t nDie = (Int_t)gROOT->ProcessLine("GetN()");
  //add dielectron analysis with different cuts to the task
  for (Int_t i=0; i<nDie; ++i){ //nDie defined in config file
    AliAnalysisFilter *filter = reinterpret_cast<AliAnalysisFilter*>(gROOT->ProcessLine(Form("Config_rbailhac_ElectronEfficiencyV2_PbPb(%d)",i)));
    task->AddTrackCuts(filter);
  }

  //########################################
  //########################################
  TString outlistname = Form("efficiency_%s",appendix.Data());
  const TString fileName = outname;
  mgr->AddTask(task);
  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 1, mgr->CreateContainer(outlistname, TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s",fileName.Data())));

  return task;
}
<commit_msg>Adapt to run with different event selection for pile-up<commit_after>AliAnalysisTaskElectronEfficiencyV2* AddTask_rbailhac_ElectronEfficiencyV2_PbPb(Bool_t getFromAlien = kFALSE,
										TString cFileName ="Config_rbailhac_ElectronEfficiencyV2_PbPb.C",
										UInt_t trigger = AliVEvent::kINT7,
										Int_t rejpileup = 1,
										const Int_t CenMin =  0,
										const Int_t CenMax = 10,
										const Float_t PtMin =  0.2,
										const Float_t PtMax = 10.0,
										const Float_t EtaMin = -0.8,
										const Float_t EtaMax = +0.8,
										const Bool_t UsePtVec = kTRUE,
										const Bool_t DoULSLS = kTRUE,
										const TString generators = "pizero_0;eta_1;etaprime_2;rho_3;omega_4;phi_5;jpsi_6;Pythia CC_0;Pythia BB_0;Pythia B_0;",
										const std::string resolutionFilename ="",
										const std::string cocktailFilename   ="",
										const std::string centralityFilename ="",
										const TString outname = "LMEE.root")
{

  //get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTask_rbailhac_test", "No analysis manager found.");
    return 0;
  }

  //Base Directory for GRID / LEGO Train
  TString configBasePath= "$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/";
  if(getFromAlien && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/r/rbailhac/PWGDQ/dielectron/macrosLMEE/%s .",cFileName.Data()))) ){
    configBasePath=Form("%s/",gSystem->pwd());
  }

  TString configFilePath(configBasePath+cFileName);

  std::cout << "Configpath:  " << configFilePath << std::endl;

  if (!gROOT->GetListOfGlobalFunctions()->FindObject("Config_rbailhac_ElectronEfficiencyV2_PbPb")) {
    printf("Load macro now\n");
    gROOT->LoadMacro(configFilePath.Data());
  }

  // trigger
  TString triggername = "NULL";
  if(trigger == (UInt_t)AliVEvent::kINT7)             triggername = "kINT7";
  else if(trigger == (UInt_t)AliVEvent::kCentral)     triggername = "kCentral";
  else if(trigger == (UInt_t)AliVEvent::kSemiCentral) triggername = "kSemiCentral";
  else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral | AliVEvent::kSemiCentral)) triggername = "kCombinedCentralityTriggers";
  else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kCentral))                           triggername = "kCombinedCentral";
  else if(trigger == (UInt_t)(AliVEvent::kINT7 | AliVEvent::kSemiCentral))                       triggername = "kCombinedSemiCentral";

  // generators
  TString suffixgen = "";
  if(generators.Contains("Pythia CC") && (generators.Contains("Pythia BB") || generators.Contains("Pythia B"))) suffixgen = "_CC_BB";
  else if(generators.Contains("Pythia CC")) suffixgen = "_CC";
  else if(generators.Contains("Pythia BB") || generators.Contains("Pythia B")) suffixgen = "_BB";
  else if(generators.Contains("pizero_0")) suffixgen = "_LF";
  else suffixgen = "";

  // generator index
  TString suffixgenID = "";
  std::vector<UInt_t> genID;
  const Int_t ngenID = (Int_t)gROOT->ProcessLine("GetGenID()");
  if(ngenID > 0) {
    for (unsigned int i = 0; i < ngenID+1; ++i){
      UInt_t valuegenID = (UInt_t)(gROOT->ProcessLine(Form("GetGenID(%d)",i)));
      genID.push_back(valuegenID);
      suffixgenID += valuegenID;
    }
  }

  //create task and add it to the manager (MB)
  TString appendix;
  appendix += TString::Format("Cen%d_%d_%s_%s_%s_Pileup%d",CenMin,CenMax,triggername.Data(),suffixgen.Data(),suffixgenID.Data(),rejpileup);
  printf("appendix %s\n", appendix.Data());

  //##########################################################
  //############################################################
  // Creating an instance of the task
  AliAnalysisTaskElectronEfficiencyV2* task = new AliAnalysisTaskElectronEfficiencyV2(Form("TaskElectronEfficiencyV2_%s",appendix.Data()));
  gROOT->GetListOfSpecials()->Add(task);//this is only for ProcessLine(AddMCSignal);

  // #########################################################
  // #########################################################
  // Set TOF correction
  // if(tofcor){
  //  SetEtaCorrectionTOFRMS(task, AliDielectronVarManager::kP, AliDielectronVarManager::kEta);
  //  SetEtaCorrectionTOFMean(task, AliDielectronVarManager::kP, AliDielectronVarManager::kEta);
  //}

  // #########################################################
  // #########################################################
  // Event selection. Is the same for all the different cutsettings
  task->SetEnablePhysicsSelection(kTRUE);//always ON in Run2 analyses for both data and MC.
  task->SetTriggerMask(trigger);
  task->SetEventFilter((reinterpret_cast<AliDielectronEventCuts*>(gROOT->ProcessLine(Form("GetEventCuts(%f,%f,%d,\"%s\")",(Float_t)CenMin,(Float_t)CenMax,rejpileup,"V0M")))));

  // #########################################################
  // #########################################################
  // Set minimum and maximum values of generated tracks. Only used to save computing power.
  // Do not set here your analysis pt-cuts
  task->SetMinPtGen(0.1);
  task->SetMaxPtGen(1e+10);
  task->SetMinEtaGen(-1.5);
  task->SetMaxEtaGen(+1.5);

  // #########################################################
  // #########################################################
  // Set minimum and maximum values for pairing
  task->SetKinematicCuts(PtMin, PtMax, EtaMin, EtaMax);

  // #########################################################
  // #########################################################
  // Set Binning single variables
  if (UsePtVec == true) {
    const Int_t Npt = 68;
    Double_t pte[Npt] = {0.00,0.10,0.11,0.12,0.13,0.14,0.15,0.155,0.16,0.165,0.17,0.175,0.18,0.185,0.19,0.195,0.20,0.205,0.21,0.215,0.22,0.225,0.23,0.235,0.24,0.245,0.25,0.255,0.26,0.265,0.27,0.275,0.28,0.285,0.29,0.295,0.30,0.32,0.34,0.36,0.38,0.40,0.43,0.46,0.49,0.52,0.55,0.60,0.65,0.70,0.75,0.80,0.90,1.00,1.10,1.20,1.40,1.60,1.80,2.00,2.40,2.80,3.20,3.70,4.50,6.00,8.00,12.0};
    std::vector<double> v_pte(pte,std::end(pte));
    task->SetPtBins(v_pte);
  }
  else task->SetPtBinsLinear   (0,  10, 100);
  task->SetEtaBinsLinear (-1.,1.,20); // 40 before
  task->SetPhiBinsLinear  (0, TMath::TwoPi(), 36); // 90 before
  task->SetThetaBinsLinear(0, TMath::TwoPi(), 60);

  // pair variables
  const Int_t Nmee = 150;
  Double_t mee[Nmee] = {};
  for(Int_t i=0  ;i<110 ;i++) mee[i] = 0.01 * (i-  0) +  0.0;//from 0 to 1.09 GeV/c2, every 0.01 GeV/c2
  for(Int_t i=110;i<Nmee;i++) mee[i] = 0.1  * (i-110) +  1.1;//from 1.1 to 5 GeV/c2, evety 0.1 GeV/c2
  std::vector<double> v_mee(mee,std::end(mee));

  const Int_t NpTee = 130;
  Double_t pTee[NpTee] = {};
  for(Int_t i=0  ;i<20   ;i++) pTee[i] = 0.005 * (i-  0) +  0.0;//from 0 to 0.095 GeV/c, every 0.005 GeV/c
  for(Int_t i=20 ;i<119  ;i++) pTee[i] = 0.1  * (i- 20) +  0.1;//from 0.1 to 9.9 GeV/c, evety 0.1 GeV/c
  for(Int_t i=119;i<NpTee;i++) pTee[i] = 1.0  * (i-119) + 10.0;//from 10 to 20 GeV/c, evety 1.0 GeV/c
  std::vector<double> v_pTee(pTee,std::end(pTee));
  task->SetMassBins(v_mee);
  task->SetPairPtBins(v_pTee);
  //task->SetPhiVBinsLinear(0, TMath::Pi(), 100);
  //task->SetFillPhiV(kTRUE);

  // #########################################################
  // #########################################################
  //task->SetSmearGenerated(kFALSE); // cross check smearing the MC at single level and filling resolution maps
 // Resolution File, If resoFilename = "" no correction is applied
  task->SetResolutionFile(resolutionFilename);
  task->SetResolutionFileFromAlien("/alice/cern.ch/user/r/rbailhac/supportFiles/" + resolutionFilename);
  task->SetResolutionDeltaPtBinsLinear   (-10., 2., (Int_t)gROOT->ProcessLine("GetNbinsDeltaMom()"));
  task->SetResolutionRelPtBinsLinear   (0., 2.,  (Int_t)gROOT->ProcessLine("GetNbinsRelMom()"));
  task->SetResolutionEtaBinsLinear  (-0.4, 0.4, (Int_t)gROOT->ProcessLine("GetNbinsDeltaEta()"));
  task->SetResolutionPhiBinsLinear  (-0.4, 0.4, (Int_t)gROOT->ProcessLine("GetNbinsDeltaPhi()"));
  task->SetResolutionThetaBinsLinear(-0.4, 0.4, (Int_t)gROOT->ProcessLine("GetNbinsDeltaTheta()"));

  //###########################################################
  //############################################################
  // Set MCSignal and Cutsetting to fill the support histograms
  task->SetSupportHistoMCSignalAndCutsetting(0,0);//fill support histograms for first MCsignal and first cutsetting

  // #########################################################
  // #########################################################
  // Set centrality correction. If resoFilename = "" no correction is applied
  task->SetCentralityFile(centralityFilename);

  // #########################################################
  // #########################################################
  // Pairing related config
  task->SetDoPairing(kTRUE);
  task->SetULSandLS(DoULSLS);

  //#####################################################
  //######################################################
  // Generators
  cout<<"Efficiency based on MC generators: " << generators <<endl;
  TString generatorsPair=generators;
  task->SetGeneratorMCSignalName(generatorsPair);
  task->SetGeneratorULSSignalName(generators);

  //#################################################
  //#################################################
  // generator ID to select pile-up or not
  if(ngenID > 0) {
    task->SetGeneratorMCSignalIndex(genID);
    task->SetGeneratorULSSignalIndex(genID);
    task->SetCheckGenID(kTRUE);
  }

  //###############################################
  //##############################################
  task->SetCocktailWeighting(cocktailFilename);
  task->SetCocktailWeightingFromAlien("/alice/cern.ch/user/r/rbailhac/supportFiles/" + cocktailFilename);

  // #########################################################
  // #########################################################
  // Add MCSignals. Can be set to see differences of:
  // e.g. secondaries and primaries. or primaries from charm and resonances
  gROOT->ProcessLine(Form("AddSingleLegMCSignal(%s)",task->GetName()));//not task itself, task name
  gROOT->ProcessLine(Form("AddPairMCSignal(%s)"     ,task->GetName()));//not task itself, task name

  // #########################################################
  // #########################################################
  // Adding cutsettings
 // Cuts
  // Number of cuts
  const Int_t nDie = (Int_t)gROOT->ProcessLine("GetN()");
  //add dielectron analysis with different cuts to the task
  for (Int_t i=0; i<nDie; ++i){ //nDie defined in config file
    AliAnalysisFilter *filter = reinterpret_cast<AliAnalysisFilter*>(gROOT->ProcessLine(Form("Config_rbailhac_ElectronEfficiencyV2_PbPb(%d)",i)));
    task->AddTrackCuts(filter);
  }

  //########################################
  //########################################
  TString outlistname = Form("efficiency_%s",appendix.Data());
  const TString fileName = outname;
  mgr->AddTask(task);
  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 1, mgr->CreateContainer(outlistname, TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s",fileName.Data())));

  return task;
}
<|endoftext|>


<commit_before>#ifndef JSPROC_JOB_HPP_
#define JSPROC_JOB_HPP_

#include <stdarg.h>             // va_list

#include "arch/runtime/runtime_utils.hpp" // fd_t
#include "containers/archive/archive.hpp"
#include "containers/archive/fd_stream.hpp"

namespace jsproc {

// Abstract base class for jobs.
class job_t {
  public:
    virtual ~job_t() {}

    // Passed in to a job on the worker process side.
    class control_t : public unix_socket_stream_t {
      private:
        friend class spawner_t;
        control_t(pid_t pid, fd_t fd);

      public:
        void vlog(const char *fmt, va_list ap);
        void log(const char *fmt, ...)
            __attribute__((format (printf, 2, 3)));

      private:
        pid_t pid_;
    };

    // Sends us over a stream.
    // Returns 0 on success, -1 on error.
    int send(write_stream_t *stream);

    // Receives and runs a job. Called on worker process side. Returns 0 on
    // success, -1 on failure.
    static int accept_job(control_t *control);

    /* ----- Pure virtual methods ----- */

    // Serialization methods. Suggest implementing by invoking
    // RDB_MAKE_ME_SERIALIZABLE_#(..) in subclass definition.
    friend class write_message_t;
    friend class archive_deserializer_t;
    virtual void rdb_serialize(write_message_t &msg) const = 0;
    virtual archive_result_t rdb_deserialize(read_stream_t *s) = 0;

    // Called on worker process side.
    virtual void run_job(control_t *control) = 0;

    // Returns a function that deserializes & runs an instance of the
    // appropriate job type. Called on worker process side.
    typedef void (*func_t)(control_t*);
    virtual func_t job_runner() = 0;
};

template <class instance_t>
class auto_job_t : public job_t {
    static void job_runner_func(control_t *control) {
        // Get the job instance.
        instance_t job;
        archive_result_t res = deserialize(control, &job);

        if (res != ARCHIVE_SUCCESS) {
            control->log("Could not deserialize job: %s",
                         res == ARCHIVE_SOCK_ERROR ? "socket error" :
                         res == ARCHIVE_SOCK_EOF ? "end of file" :
                         res == ARCHIVE_RANGE_ERROR ? "range error" :
                         "unknown error");
            // TODO (rntz): shouldn't we just die here?
            return;
        }

        // Run it.
        job.run_job(control);
    }

    func_t job_runner() { return job_runner_func; }
};

} // namespace jsproc

#endif // JSPROC_JOB_HPP_
<commit_msg>crash_or_trap on job failure<commit_after>#ifndef JSPROC_JOB_HPP_
#define JSPROC_JOB_HPP_

#include <stdarg.h>             // va_list
#include <stdlib.h>             // exit

#include "arch/runtime/runtime_utils.hpp" // fd_t
#include "containers/archive/archive.hpp"
#include "containers/archive/fd_stream.hpp"

namespace jsproc {

// Abstract base class for jobs.
class job_t {
  public:
    virtual ~job_t() {}

    // Passed in to a job on the worker process side.
    class control_t : public unix_socket_stream_t {
      private:
        friend class spawner_t;
        control_t(pid_t pid, fd_t fd);

      public:
        void vlog(const char *fmt, va_list ap);
        void log(const char *fmt, ...)
            __attribute__((format (printf, 2, 3)));

      private:
        pid_t pid_;
    };

    // Sends us over a stream.
    // Returns 0 on success, -1 on error.
    int send(write_stream_t *stream);

    // Receives and runs a job. Called on worker process side. Returns 0 on
    // success, -1 on failure.
    static int accept_job(control_t *control);

    /* ----- Pure virtual methods ----- */

    // Serialization methods. Suggest implementing by invoking
    // RDB_MAKE_ME_SERIALIZABLE_#(..) in subclass definition.
    friend class write_message_t;
    friend class archive_deserializer_t;
    virtual void rdb_serialize(write_message_t &msg) const = 0;
    virtual archive_result_t rdb_deserialize(read_stream_t *s) = 0;

    // Called on worker process side.
    virtual void run_job(control_t *control) = 0;

    // Returns a function that deserializes & runs an instance of the
    // appropriate job type. Called on worker process side.
    typedef void (*func_t)(control_t*);
    virtual func_t job_runner() = 0;
};

template <class instance_t>
class auto_job_t : public job_t {
    static void job_runner_func(control_t *control) {
        // Get the job instance.
        instance_t job;
        archive_result_t res = deserialize(control, &job);

        if (res != ARCHIVE_SUCCESS) {
            control->log("Could not deserialize job: %s",
                         res == ARCHIVE_SOCK_ERROR ? "socket error" :
                         res == ARCHIVE_SOCK_EOF ? "end of file" :
                         res == ARCHIVE_RANGE_ERROR ? "range error" :
                         "unknown error");
            crash_or_trap("worker: could not deserialize job");
        }

        // Run it.
        job.run_job(control);
    }

    func_t job_runner() { return job_runner_func; }
};

} // namespace jsproc

#endif // JSPROC_JOB_HPP_
<|endoftext|>


<commit_before>#include "katlasview.h"

#include <cmath>
#include <QtCore/QAbstractItemModel>
#include <QtGui/QSizePolicy>
#include <QtCore/QTime>
#include <QtGui/QSizePolicy>
#include <QtGui/QRegion>

#include "clippainter.h"
#include "katlasviewinputhandler.h"
#include "katlasviewpopupmenu.h"
#include "quaternion.h"
#include "texcolorizer.h"

#include "measuretool.h"

KAtlasView::KAtlasView(QWidget *parent)
    : QWidget(parent)
{
	setMinimumSize(200, 300);
	setFocusPolicy(Qt::WheelFocus);
        setFocus(Qt::OtherFocusReason);
	m_pGlobe = new KAtlasGlobe( this );

	QPalette p = palette();
	p.setColor(QPalette::Window,Qt::black);
	setPalette(p);

	setBackgroundRole(QPalette::Window);
	setAutoFillBackground(true);

//	setAttribute(Qt::WA_NoSystemBackground);

	m_pCanvasImage = new QImage(parent->width(),parent->height(),QImage::Format_ARGB32_Premultiplied);
	m_pGlobe->setCanvasImage( m_pCanvasImage );

	inputhandler = new KAtlasViewInputHandler(this, m_pGlobe);
	installEventFilter(inputhandler);
	setMouseTracking(true);

	m_popupmenu = new KAtlasViewPopupMenu(this, m_pGlobe);
	connect( inputhandler, SIGNAL( lmbRequest( int, int ) ), m_popupmenu, SLOT( showLmbMenu( int, int ) ) );
	connect( inputhandler, SIGNAL( rmbRequest( int, int ) ), m_popupmenu, SLOT( showRmbMenu( int, int ) ) );

	m_pMeasureTool = new MeasureTool( this );

	connect( m_popupmenu, SIGNAL( addMeasurePoint( float, float ) ), m_pMeasureTool, SLOT( addMeasurePoint( float, float ) ) );
	connect( m_popupmenu, SIGNAL( removeMeasurePoints() ), m_pMeasureTool, SLOT( removeMeasurePoints( ) ) );

	m_logzoom = 0;
	m_zoomStep = 40;
	goHome();
	minimumzoom = 50;
}

void KAtlasView::zoomView(int zoom){
	// prevent infinite loops

	if ( zoom  == m_logzoom )
		return;

	m_logzoom = zoom;

	emit zoomChanged(zoom);

	int radius = fromLogScale(zoom);

	if ( radius == m_pGlobe->getRadius() )
		return;

	m_pGlobe->setRadius(radius);
	repaint();

	setActiveRegion();
}

void KAtlasView::zoomViewBy(int zoomstep){
	// prevent infinite loops

	int zoom = m_pGlobe->getRadius();
	int tryZoom = toLogScale(zoom) + zoomstep;
//	qDebug() << QString::number(tryZoom) << " " << QString::number(minimumzoom);
	if ( tryZoom >= minimumzoom ) {
		zoom = tryZoom;
		zoomView(zoom);
	}
}

void KAtlasView::zoomIn(){
	zoomViewBy(m_zoomStep);
}

void KAtlasView::zoomOut(){
	zoomViewBy(-m_zoomStep);
}

void KAtlasView::rotateBy(const float& phi, const float& theta){
	m_pGlobe->rotateBy(phi, theta);

	repaint();
}

void KAtlasView::centerOn(const float& phi, const float& theta){
	m_pGlobe->rotateTo(phi, theta);

	repaint();
}

void KAtlasView::centerOn(const QModelIndex& index){

	PlaceMarkModel* model = (PlaceMarkModel*)m_pGlobe->getPlaceMarkModel();
	if (model == 0) qDebug("model null");

	PlaceMark* mark = model->placeMark( index );

	m_pGlobe->placeContainer()->clearSelected();

	if (mark != 0){
		float lng, lat;
		mark->coordinate(lng, lat);
		centerOn(-lat*180.0/M_PI, -lng*180.0/M_PI);
		mark->setSelected(1);
		m_crosshair.setEnabled( true );
	}
	else
		m_crosshair.setEnabled( false );

	m_pGlobe->placeContainer()->clearTextPixmaps();
	m_pGlobe->placeContainer()->sort();

	repaint();
}

void KAtlasView::moveLeft(){
	rotateBy(0, getMoveStep());
}

void KAtlasView::moveRight(){
	rotateBy(0, -getMoveStep());
}

void KAtlasView::moveUp(){
	rotateBy(getMoveStep(), 0);
}

void KAtlasView::moveDown(){
	rotateBy(-getMoveStep(), 0);
}

void KAtlasView::resizeEvent (QResizeEvent*){
//	Redefine the area where the mousepointer becomes a navigationarrow
	setActiveRegion();
	if ( m_pCanvasImage != 0 ) delete m_pCanvasImage;
	m_pCanvasImage = new QImage(width(),height(),QImage::Format_ARGB32_Premultiplied);
	m_pGlobe->setCanvasImage( m_pCanvasImage );
	m_pGlobe->resize();

	repaint();
}

bool KAtlasView::getGlobeSphericals(int x, int y, float& alpha, float& beta){

	int radius = m_pGlobe->getRadius();
	int imgrx = width() >> 1;
	int imgry = height() >> 1;

	const float radiusf = 1.0/(float)(radius);

	if ( radius > sqrt((x - imgrx)*(x - imgrx) + (y - imgry)*(y - imgry)) ) {

		float qy = radiusf * (float)(y - imgry);
		float qr = 1.0 - qy*qy;
		float qx = (float)(x - imgrx) * radiusf;

		float qr2z = qr - qx*qx;
		float qz = (qr2z > 0.0) ? sqrt(qr2z) : 0.0;

		Quaternion qpos(0,qx,qy,qz);
		qpos.rotateAroundAxis(m_pGlobe->getPlanetAxis());
		qpos.getSpherical( alpha, beta );

		return true;
	}
	else {
		return false;
	}
}

void KAtlasView::setActiveRegion(){
	int zoom = m_pGlobe->getRadius();

	activeRegion = QRegion(25,25,width()-50,height()-50, QRegion::Rectangle);

	if ( zoom < sqrt(width()*width()+ height()*height())/2){
		activeRegion &= QRegion(width()/2-zoom, height()/2-zoom, 2*zoom, 2*zoom, QRegion::Ellipse);
	}
}

const QRegion KAtlasView::getActiveRegion(){
	return activeRegion;
}

void KAtlasView::paintEvent(QPaintEvent *evt)
{
//	QTime timer;
//	timer.restart();
//	Debugging Active Region
//	painter.setClipRegion(activeRegion);

//	if(m_pGlobe->needsUpdate() || m_pCanvasImage->isNull() || m_pCanvasImage->size() != size())
//	{
		int radius = m_pGlobe->getRadius();
		bool clip = (radius > m_pCanvasImage->width()/2 || radius > m_pCanvasImage->height()/2) ? true : false;

		ClipPainter painter( this, clip);
//		QPainter painter(this);
//		painter.setClipRect(10, 10, m_pCanvasImage->width() - 1 , m_pCanvasImage->height()-1 );
//		painter.setClipping( true );
//		painter.clearNodeCount();
		QRect dirty = evt->rect();
		m_pGlobe->paintGlobe(&painter,dirty);

		painter.drawPixmap(10, m_pCanvasImage->height()-40,
		m_mapscale.drawScaleBarPixmap( m_pGlobe->getRadius(),m_pCanvasImage-> width()/2 - 20));

		painter.drawPixmap( m_pCanvasImage->width()-60, 10,
		m_windrose.drawWindRosePixmap( m_pCanvasImage->width(), m_pCanvasImage->height(), m_pGlobe->northPoleY() ) );

		m_crosshair.paintCrossHair( &painter, m_pCanvasImage->width(), m_pCanvasImage->height() );

		m_pMeasureTool->paintMeasurePoints( &painter, m_pCanvasImage->width()/2, m_pCanvasImage->height()/2, radius, m_pGlobe->getPlanetAxis(), true );
//		qDebug() << "Nodes: " << painter.nodeCount();
//	}
/*
	else
	{
		// Draw cached pixmap to widget
		QPainter pixmapPainter(this);
		QRect rect(0, 0, width(), height());
		pixmapPainter.drawImage(rect, m_pCanvasImage, rect);
	}
*/
//		qDebug() << "PaintEvent: " << timer.elapsed();
}

void KAtlasView::goHome(){
//	m_pGlobe->rotateTo(0, 0);
	m_pGlobe->rotateTo(54.8, -9.4);
	zoomView(1050); // default 1050

	update(); // not obsolete in case the zoomlevel stays unaltered
}

float KAtlasView::getMoveStep(){
	if ( m_pGlobe->getRadius() < sqrt(width()*width() + height()*height()))
		return 0.1f;
	else
		return atanf((float)width()/(float)(2 * m_pGlobe->getRadius())) * 0.2f;
}

int KAtlasView::fromLogScale(int zoom){
	zoom = (int) pow(M_E, ((float)zoom/200));
//	zoom = (int) pow(2, ((float)zoom/200));
	return zoom;
}

int KAtlasView::toLogScale(int zoom){
	zoom = (int)(200.0f*logf((float)zoom));
	return zoom;
}

#include "katlasview.moc"
<commit_msg><commit_after>#include "katlasview.h"

#include <cmath>
#include <QtCore/QAbstractItemModel>
#include <QtGui/QSizePolicy>
#include <QtCore/QTime>
#include <QtGui/QSizePolicy>
#include <QtGui/QRegion>

#include "clippainter.h"
#include "katlasviewinputhandler.h"
#include "katlasviewpopupmenu.h"
#include "quaternion.h"
#include "texcolorizer.h"

#include "measuretool.h"

#ifdef Q_CC_MSVC
  static double sqrt(int a) { return sqrt((double)a); }
#endif

KAtlasView::KAtlasView(QWidget *parent)
    : QWidget(parent)
{
	setMinimumSize(200, 300);
	setFocusPolicy(Qt::WheelFocus);
        setFocus(Qt::OtherFocusReason);
	m_pGlobe = new KAtlasGlobe( this );

	QPalette p = palette();
	p.setColor(QPalette::Window,Qt::black);
	setPalette(p);

	setBackgroundRole(QPalette::Window);
	setAutoFillBackground(true);

//	setAttribute(Qt::WA_NoSystemBackground);

	m_pCanvasImage = new QImage(parent->width(),parent->height(),QImage::Format_ARGB32_Premultiplied);
	m_pGlobe->setCanvasImage( m_pCanvasImage );

	inputhandler = new KAtlasViewInputHandler(this, m_pGlobe);
	installEventFilter(inputhandler);
	setMouseTracking(true);

	m_popupmenu = new KAtlasViewPopupMenu(this, m_pGlobe);
	connect( inputhandler, SIGNAL( lmbRequest( int, int ) ), m_popupmenu, SLOT( showLmbMenu( int, int ) ) );
	connect( inputhandler, SIGNAL( rmbRequest( int, int ) ), m_popupmenu, SLOT( showRmbMenu( int, int ) ) );

	m_pMeasureTool = new MeasureTool( this );

	connect( m_popupmenu, SIGNAL( addMeasurePoint( float, float ) ), m_pMeasureTool, SLOT( addMeasurePoint( float, float ) ) );
	connect( m_popupmenu, SIGNAL( removeMeasurePoints() ), m_pMeasureTool, SLOT( removeMeasurePoints( ) ) );

	m_logzoom = 0;
	m_zoomStep = 40;
	goHome();
	minimumzoom = 50;
}

void KAtlasView::zoomView(int zoom){
	// prevent infinite loops

	if ( zoom  == m_logzoom )
		return;

	m_logzoom = zoom;

	emit zoomChanged(zoom);

	int radius = fromLogScale(zoom);

	if ( radius == m_pGlobe->getRadius() )
		return;

	m_pGlobe->setRadius(radius);
	repaint();

	setActiveRegion();
}

void KAtlasView::zoomViewBy(int zoomstep){
	// prevent infinite loops

	int zoom = m_pGlobe->getRadius();
	int tryZoom = toLogScale(zoom) + zoomstep;
//	qDebug() << QString::number(tryZoom) << " " << QString::number(minimumzoom);
	if ( tryZoom >= minimumzoom ) {
		zoom = tryZoom;
		zoomView(zoom);
	}
}

void KAtlasView::zoomIn(){
	zoomViewBy(m_zoomStep);
}

void KAtlasView::zoomOut(){
	zoomViewBy(-m_zoomStep);
}

void KAtlasView::rotateBy(const float& phi, const float& theta){
	m_pGlobe->rotateBy(phi, theta);

	repaint();
}

void KAtlasView::centerOn(const float& phi, const float& theta){
	m_pGlobe->rotateTo(phi, theta);

	repaint();
}

void KAtlasView::centerOn(const QModelIndex& index){

	PlaceMarkModel* model = (PlaceMarkModel*)m_pGlobe->getPlaceMarkModel();
	if (model == 0) qDebug("model null");

	PlaceMark* mark = model->placeMark( index );

	m_pGlobe->placeContainer()->clearSelected();

	if (mark != 0){
		float lng, lat;
		mark->coordinate(lng, lat);
		centerOn(-lat*180.0/M_PI, -lng*180.0/M_PI);
		mark->setSelected(1);
		m_crosshair.setEnabled( true );
	}
	else
		m_crosshair.setEnabled( false );

	m_pGlobe->placeContainer()->clearTextPixmaps();
	m_pGlobe->placeContainer()->sort();

	repaint();
}

void KAtlasView::moveLeft(){
	rotateBy(0, getMoveStep());
}

void KAtlasView::moveRight(){
	rotateBy(0, -getMoveStep());
}

void KAtlasView::moveUp(){
	rotateBy(getMoveStep(), 0);
}

void KAtlasView::moveDown(){
	rotateBy(-getMoveStep(), 0);
}

void KAtlasView::resizeEvent (QResizeEvent*){
//	Redefine the area where the mousepointer becomes a navigationarrow
	setActiveRegion();
	if ( m_pCanvasImage != 0 ) delete m_pCanvasImage;
	m_pCanvasImage = new QImage(width(),height(),QImage::Format_ARGB32_Premultiplied);
	m_pGlobe->setCanvasImage( m_pCanvasImage );
	m_pGlobe->resize();

	repaint();
}

bool KAtlasView::getGlobeSphericals(int x, int y, float& alpha, float& beta){

	int radius = m_pGlobe->getRadius();
	int imgrx = width() >> 1;
	int imgry = height() >> 1;

	const float radiusf = 1.0/(float)(radius);

	if ( radius > sqrt((x - imgrx)*(x - imgrx) + (y - imgry)*(y - imgry)) ) {

		float qy = radiusf * (float)(y - imgry);
		float qr = 1.0 - qy*qy;
		float qx = (float)(x - imgrx) * radiusf;

		float qr2z = qr - qx*qx;
		float qz = (qr2z > 0.0) ? sqrt(qr2z) : 0.0;

		Quaternion qpos(0,qx,qy,qz);
		qpos.rotateAroundAxis(m_pGlobe->getPlanetAxis());
		qpos.getSpherical( alpha, beta );

		return true;
	}
	else {
		return false;
	}
}

void KAtlasView::setActiveRegion(){
	int zoom = m_pGlobe->getRadius();

	activeRegion = QRegion(25,25,width()-50,height()-50, QRegion::Rectangle);

	if ( zoom < sqrt(width()*width()+ height()*height())/2){
		activeRegion &= QRegion(width()/2-zoom, height()/2-zoom, 2*zoom, 2*zoom, QRegion::Ellipse);
	}
}

const QRegion KAtlasView::getActiveRegion(){
	return activeRegion;
}

void KAtlasView::paintEvent(QPaintEvent *evt)
{
//	QTime timer;
//	timer.restart();
//	Debugging Active Region
//	painter.setClipRegion(activeRegion);

//	if(m_pGlobe->needsUpdate() || m_pCanvasImage->isNull() || m_pCanvasImage->size() != size())
//	{
		int radius = m_pGlobe->getRadius();
		bool clip = (radius > m_pCanvasImage->width()/2 || radius > m_pCanvasImage->height()/2) ? true : false;

		ClipPainter painter( this, clip);
//		QPainter painter(this);
//		painter.setClipRect(10, 10, m_pCanvasImage->width() - 1 , m_pCanvasImage->height()-1 );
//		painter.setClipping( true );
//		painter.clearNodeCount();
		QRect dirty = evt->rect();
		m_pGlobe->paintGlobe(&painter,dirty);

		painter.drawPixmap(10, m_pCanvasImage->height()-40,
		m_mapscale.drawScaleBarPixmap( m_pGlobe->getRadius(),m_pCanvasImage-> width()/2 - 20));

		painter.drawPixmap( m_pCanvasImage->width()-60, 10,
		m_windrose.drawWindRosePixmap( m_pCanvasImage->width(), m_pCanvasImage->height(), m_pGlobe->northPoleY() ) );

		m_crosshair.paintCrossHair( &painter, m_pCanvasImage->width(), m_pCanvasImage->height() );

		m_pMeasureTool->paintMeasurePoints( &painter, m_pCanvasImage->width()/2, m_pCanvasImage->height()/2, radius, m_pGlobe->getPlanetAxis(), true );
//		qDebug() << "Nodes: " << painter.nodeCount();
//	}
/*
	else
	{
		// Draw cached pixmap to widget
		QPainter pixmapPainter(this);
		QRect rect(0, 0, width(), height());
		pixmapPainter.drawImage(rect, m_pCanvasImage, rect);
	}
*/
//		qDebug() << "PaintEvent: " << timer.elapsed();
}

void KAtlasView::goHome(){
//	m_pGlobe->rotateTo(0, 0);
	m_pGlobe->rotateTo(54.8, -9.4);
	zoomView(1050); // default 1050

	update(); // not obsolete in case the zoomlevel stays unaltered
}

float KAtlasView::getMoveStep(){
	if ( m_pGlobe->getRadius() < sqrt(width()*width() + height()*height()))
		return 0.1f;
	else
		return atanf((float)width()/(float)(2 * m_pGlobe->getRadius())) * 0.2f;
}

int KAtlasView::fromLogScale(int zoom){
	zoom = (int) pow(M_E, ((float)zoom/200));
//	zoom = (int) pow(2, ((float)zoom/200));
	return zoom;
}

int KAtlasView::toLogScale(int zoom){
	zoom = (int)(200.0f*logf((float)zoom));
	return zoom;
}

#include "katlasview.moc"
<|endoftext|>


<commit_before>/*

	Copyright (c) 2011, The Chinese University of Hong Kong

	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 "scoring_function.hpp"

namespace idock
{
	const fl scoring_function::Cutoff = static_cast<fl>(8);
	const fl scoring_function::Cutoff_Sqr = Cutoff * Cutoff;
	const fl scoring_function::Factor = static_cast<fl>(256);
	const fl scoring_function::Factor_Inverse = 1 / Factor;
	const size_t scoring_function::Num_Samples = static_cast<size_t>(Factor * Cutoff_Sqr) + 1;

	fl scoring_function::score(const size_t t1, const size_t t2, const fl r)
	{
		BOOST_ASSERT(r <= Cutoff_Sqr);

		// Calculate the surface distance d.
		const fl d = r - (xs_vdw_radius(t1) + xs_vdw_radius(t2));

		// The scoring function is a weighted sum of 5 terms.
		// The first 3 terms depend on d only, while the latter 2 terms depend on t1, t2 and d.
		return (-0.035579) * exp(-sqr(d * 2))
			+  (-0.005156) * exp(-sqr((d - 3.0) * 0.5))
			+  ( 0.840245) * (d > 0 ? 0.0 : d * d)
			+  (-0.035069) * ((xs_is_hydrophobic(t1) && xs_is_hydrophobic(t2)) ? ((d >= 1.5) ? 0.0 : ((d <= 0.5) ? 1.0 : 1.5 - d)) : 0.0)
			+  (-0.587439) * ((xs_hbond(t1, t2)) ? ((d >= 0) ? 0.0 : ((d <= -0.7) ? 1 : d * (-1.428571))): 0.0);
	}

	void scoring_function::precalculate(const size_t t1, const size_t t2, const vector<fl>& rs)
	{
		vector<scoring_function_element>& p = (*this)[triangular_matrix_restrictive_index(t1, t2)];
		BOOST_ASSERT(p.size() == Num_Samples);

		// Calculate the value of scoring function evaluated at (t1, t2, d).
		for (size_t i = 0; i < Num_Samples; ++i)
		{
			p[i].e = score(t1, t2, rs[i]);
		}

		// Calculate the dor of scoring function evaluated at (t1, t2, d).
		for (size_t i = 1; i < Num_Samples - 1; ++i)
		{
			p[i].dor = (p[i + 1].e - p[i].e) / ((rs[i + 1] - rs[i]) * rs[i]);
		}
		p.front().dor = 0;
		p.back().dor = 0;
	}

	scoring_function_element scoring_function::evaluate(const size_t type_pair_index, const fl r2) const
	{
		BOOST_ASSERT(r2 <= Cutoff_Sqr);
		return (*this)[type_pair_index][static_cast<size_t>(Factor * r2)];
	}
}
<commit_msg>Added more digits to a factor in the scoring function<commit_after>/*

	Copyright (c) 2011, The Chinese University of Hong Kong

	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 "scoring_function.hpp"

namespace idock
{
	const fl scoring_function::Cutoff = static_cast<fl>(8);
	const fl scoring_function::Cutoff_Sqr = Cutoff * Cutoff;
	const fl scoring_function::Factor = static_cast<fl>(256);
	const fl scoring_function::Factor_Inverse = 1 / Factor;
	const size_t scoring_function::Num_Samples = static_cast<size_t>(Factor * Cutoff_Sqr) + 1;

	fl scoring_function::score(const size_t t1, const size_t t2, const fl r)
	{
		BOOST_ASSERT(r <= Cutoff_Sqr);

		// Calculate the surface distance d.
		const fl d = r - (xs_vdw_radius(t1) + xs_vdw_radius(t2));

		// The scoring function is a weighted sum of 5 terms.
		// The first 3 terms depend on d only, while the latter 2 terms depend on t1, t2 and d.
		return (-0.035579) * exp(-sqr(d * 2))
			+  (-0.005156) * exp(-sqr((d - 3.0) * 0.5))
			+  ( 0.840245) * (d > 0 ? 0.0 : d * d)
			+  (-0.035069) * ((xs_is_hydrophobic(t1) && xs_is_hydrophobic(t2)) ? ((d >= 1.5) ? 0.0 : ((d <= 0.5) ? 1.0 : 1.5 - d)) : 0.0)
			+  (-0.587439) * ((xs_hbond(t1, t2)) ? ((d >= 0) ? 0.0 : ((d <= -0.7) ? 1 : d * (-1.4285714285714286))): 0.0);
	}

	void scoring_function::precalculate(const size_t t1, const size_t t2, const vector<fl>& rs)
	{
		vector<scoring_function_element>& p = (*this)[triangular_matrix_restrictive_index(t1, t2)];
		BOOST_ASSERT(p.size() == Num_Samples);

		// Calculate the value of scoring function evaluated at (t1, t2, d).
		for (size_t i = 0; i < Num_Samples; ++i)
		{
			p[i].e = score(t1, t2, rs[i]);
		}

		// Calculate the dor of scoring function evaluated at (t1, t2, d).
		for (size_t i = 1; i < Num_Samples - 1; ++i)
		{
			p[i].dor = (p[i + 1].e - p[i].e) / ((rs[i + 1] - rs[i]) * rs[i]);
		}
		p.front().dor = 0;
		p.back().dor = 0;
	}

	scoring_function_element scoring_function::evaluate(const size_t type_pair_index, const fl r2) const
	{
		BOOST_ASSERT(r2 <= Cutoff_Sqr);
		return (*this)[type_pair_index][static_cast<size_t>(Factor * r2)];
	}
}
<|endoftext|>


<commit_before>// Minimal example, Windows platform
#include <iostream>

#include "qpp.h"

int main()
{
	using namespace qpp;
	std::cout << "Hello, Quantum++!\nThis is the |0> state:\n";
	std::cout << disp(st.z0) << '\n';
}
<commit_msg>Update qpp.cpp<commit_after>// Minimal example, Windows platform
#include <iostream>

#include "qpp.h"

int main()
{
	using namespace qpp;
	std::cout << "Hello, Quantum++!\nThis is the |0> state:\n";
	std::cout << disp(0_ket) << '\n';
}
<|endoftext|>


<commit_before>#ifndef DEF_LAMBDARANK_H
#define DEF_LAMBDARANK_H
/**
 * @file
 * @author  David Nemeskey
 * @version 0.1
 *
 * @section LICENSE
 *
 * Copyright [2013] [MTA SZTAKI]
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * The LambdaRank algorithm. Since it is very closely related to RankNet, we
 * derive it from that class.
 */

#include <cmath>

#include "ranknet_lambda.hpp"
#include "lambdarank_optimize.hpp"

class LambdaRank : public RankNetLambda {
public:
  /** @param[in] sigma parameter of the sigmoid. */
  LambdaRank(MlModel* model, EvaluationMeasure* eval,
             StoppingCondition stop, LtrRunningPhase phase=TRAINING,
             double sigma=1)
      : RankNetLambda(model, eval, stop, phase, sigma) {
  }

  /****************************** GraphChi stuff ******************************/

  /** The actual RankNet implementation. */
  virtual void compute_gradients(
      graphchi_vertex<TypeVertex, FeatureEdge> &query, Gradient* umodel) {
    std::vector<double> lambdas(query.num_outedges());
    std::vector<double> s_is(query.num_outedges());

    /* First, we compute all the outputs... */
    for (int i = 0; i < query.num_outedges(); i++) {
      s_is[i] = get_score(query.outedge(i));
//      std::cout << "s[" << i << "] == " << s_is[i] << std::endl;
    }
    /* ...and the retrieval measure scores. */
    opt.compute(query);

    /* Now, we compute the errors (lambdas). */
    for (int i = 0; i < query.num_outedges() - 1; i++) {
      int rel_i = get_relevance(query.outedge(i));
      for (int j = i + 1; j < query.num_outedges(); j++) {
        int rel_j = get_relevance(query.outedge(j));
        if (rel_i != rel_j) {
          double S_ij = rel_i > rel_j ? 1 : -1;
          double lambda_ij = dC_per_ds_i(S_ij, s_is[i], s_is[j]) *
                             opt.delta(query, i, j) * 5;
          /* lambda_ij = -lambda_ji */
          lambdas[i] += lambda_ij;
          lambdas[j] -= lambda_ij;
        }
      }
    }

    /* Finally, the model update. */
    for (int i = 0; i < query.num_outedges(); i++) {
      // -lambdas[i], as C is a utility function in this case
      umodel->update(query.outedge(i)->get_data().features, s_is[i], -lambdas[i]);
    }
  }

private:
  /**
   * The information retrieval measure we are optimizing for.
   * @todo add more measures.
   */
  NdcgOptimizer opt;
};

#endif
<commit_msg>Fixed the error in the lambdarank formula. 	modified:   lambdarank.hpp<commit_after>#ifndef DEF_LAMBDARANK_H
#define DEF_LAMBDARANK_H
/**
 * @file
 * @author  David Nemeskey
 * @version 0.1
 *
 * @section LICENSE
 *
 * Copyright [2013] [MTA SZTAKI]
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * The LambdaRank algorithm. Since it is very closely related to RankNet, we
 * derive it from that class.
 */

#include <cmath>

#include "ranknet_lambda.hpp"
#include "lambdarank_optimize.hpp"

class LambdaRank : public RankNetLambda {
public:
  /** @param[in] sigma parameter of the sigmoid. */
  LambdaRank(MlModel* model, EvaluationMeasure* eval,
             StoppingCondition stop, LtrRunningPhase phase=TRAINING,
             double sigma=1)
      : RankNetLambda(model, eval, stop, phase, sigma) {
  }

  /****************************** GraphChi stuff ******************************/

  /** The actual RankNet implementation. */
  virtual void compute_gradients(
      graphchi_vertex<TypeVertex, FeatureEdge> &query, Gradient* umodel) {
    std::vector<double> lambdas(query.num_outedges());
    std::vector<double> s_is(query.num_outedges());

    /* First, we compute all the outputs... */
    for (int i = 0; i < query.num_outedges(); i++) {
      s_is[i] = get_score(query.outedge(i));
//      std::cout << "s[" << i << "] == " << s_is[i] << std::endl;
    }
    /* ...and the retrieval measure scores. */
    opt.compute(query);

    /* Now, we compute the errors (lambdas). */
    for (int i = 0; i < query.num_outedges() - 1; i++) {
      int rel_i = get_relevance(query.outedge(i));
      for (int j = i + 1; j < query.num_outedges(); j++) {
        int rel_j = get_relevance(query.outedge(j));
        if (rel_i != rel_j) {
          double S_ij = rel_i > rel_j ? 1 : -1;
          double lambda_ij = dC_per_ds_i(S_ij, s_is[i], s_is[j]) *
                             fabs(opt.delta(query, i, j));
          /* lambda_ij = -lambda_ji */
          lambdas[i] += lambda_ij;
          lambdas[j] -= lambda_ij;
        }
      }
    }

    /* Finally, the model update. */
    for (int i = 0; i < query.num_outedges(); i++) {
      // -lambdas[i], as C is a utility function in this case
      umodel->update(query.outedge(i)->get_data().features, s_is[i], lambdas[i]);
    }
  }

private:
  /**
   * The information retrieval measure we are optimizing for.
   * @todo add more measures.
   */
  NdcgOptimizer opt;
};

#endif
<|endoftext|>


<commit_before>#include <core/stdafx.h>
#include <core/smartview/SearchFolderDefinition.h>
#include <core/smartview/RestrictionStruct.h>
#include <core/smartview/PropertiesStruct.h>
#include <core/mapi/extraPropTags.h>
#include <core/smartview/SmartView.h>

namespace smartview
{
	AddressListEntryStruct::AddressListEntryStruct(std::shared_ptr<binaryParser> parser)
	{
		PropertyCount = blockT<DWORD>::parse(parser);
		Pad = blockT<DWORD>::parse(parser);
		if (*PropertyCount)
		{
			Props.SetMaxEntries(*PropertyCount);
			Props.SmartViewParser::parse(parser, false);
		}
	}

	void SearchFolderDefinition::Parse()
	{
		m_Version = blockT<DWORD>::parse(m_Parser);
		m_Flags = blockT<DWORD>::parse(m_Parser);
		m_NumericSearch = blockT<DWORD>::parse(m_Parser);

		m_TextSearchLength = blockT<BYTE>::parse(m_Parser);
		size_t cchTextSearch = *m_TextSearchLength;
		if (*m_TextSearchLength == 255)
		{
			m_TextSearchLengthExtended = blockT<WORD>::parse(m_Parser);
			cchTextSearch = *m_TextSearchLengthExtended;
		}

		if (cchTextSearch)
		{
			m_TextSearch = blockStringW::parse(m_Parser, cchTextSearch);
		}

		m_SkipLen1 = blockT<DWORD>::parse(m_Parser);
		m_SkipBytes1 = blockBytes::parse(m_Parser, *m_SkipLen1, _MaxBytes);

		m_DeepSearch = blockT<DWORD>::parse(m_Parser);

		m_FolderList1Length = blockT<BYTE>::parse(m_Parser);
		size_t cchFolderList1 = *m_FolderList1Length;
		if (*m_FolderList1Length == 255)
		{
			m_FolderList1LengthExtended = blockT<WORD>::parse(m_Parser);
			cchFolderList1 = *m_FolderList1LengthExtended;
		}

		if (cchFolderList1)
		{
			m_FolderList1 = blockStringW::parse(m_Parser, cchFolderList1);
		}

		m_FolderList2Length = blockT<DWORD>::parse(m_Parser);

		if (m_FolderList2Length)
		{
			m_FolderList2.parse(m_Parser, *m_FolderList2Length, true);
		}

		if (*m_Flags & SFST_BINARY)
		{
			m_AddressCount = blockT<DWORD>::parse(m_Parser);
			if (*m_AddressCount)
			{
				if (*m_AddressCount < _MaxEntriesSmall)
				{
					m_Addresses.reserve(*m_AddressCount);
					for (DWORD i = 0; i < *m_AddressCount; i++)
					{
						m_Addresses.emplace_back(std::make_shared<AddressListEntryStruct>(m_Parser));
					}
				}
			}
		}

		m_SkipLen2 = blockT<DWORD>::parse(m_Parser);
		m_SkipBytes2 = blockBytes::parse(m_Parser, *m_SkipLen2, _MaxBytes);

		if (*m_Flags & SFST_MRES)
		{
			m_Restriction = std::make_shared<RestrictionStruct>(false, true);
			m_Restriction->SmartViewParser::parse(m_Parser, false);
		}

		if (*m_Flags & SFST_FILTERSTREAM)
		{
			const auto cbRemainingBytes = m_Parser->RemainingBytes();
			// Since the format for SFST_FILTERSTREAM isn't documented, just assume that everything remaining
			// is part of this bucket. We leave DWORD space for the final skip block, which should be empty
			if (cbRemainingBytes > sizeof DWORD)
			{
				m_AdvancedSearchBytes = blockBytes::parse(m_Parser, cbRemainingBytes - sizeof DWORD);
			}
		}

		m_SkipLen3 = blockT<DWORD>::parse(m_Parser);
		if (m_SkipLen3)
		{
			m_SkipBytes3 = blockBytes::parse(m_Parser, *m_SkipLen3, _MaxBytes);
		}
	}

	void SearchFolderDefinition::ParseBlocks()
	{
		setRoot(L"Search Folder Definition:\r\n");
		addChild(m_Version, L"Version = 0x%1!08X!\r\n", m_Version->getData());
		addChild(
			m_Flags,
			L"Flags = 0x%1!08X! = %2!ws!\r\n",
			m_Flags->getData(),
			InterpretNumberAsStringProp(*m_Flags, PR_WB_SF_STORAGE_TYPE).c_str());
		addChild(m_NumericSearch, L"Numeric Search = 0x%1!08X!\r\n", m_NumericSearch->getData());
		addChild(m_TextSearchLength, L"Text Search Length = 0x%1!02X!", m_TextSearchLength->getData());

		if (m_TextSearchLength)
		{
			terminateBlock();
			addChild(
				m_TextSearchLengthExtended,
				L"Text Search Length Extended = 0x%1!04X!\r\n",
				m_TextSearchLengthExtended->getData());
			addHeader(L"Text Search = ");
			if (!m_TextSearch->empty())
			{
				addChild(m_TextSearch, m_TextSearch->c_str());
			}
		}

		terminateBlock();
		addChild(m_SkipLen1, L"SkipLen1 = 0x%1!08X!", m_SkipLen1->getData());

		if (m_SkipLen1)
		{
			terminateBlock();
			addHeader(L"SkipBytes1 = ");

			addChild(m_SkipBytes1);
		}

		terminateBlock();
		addChild(m_DeepSearch, L"Deep Search = 0x%1!08X!\r\n", m_DeepSearch->getData());
		addChild(m_FolderList1Length, L"Folder List 1 Length = 0x%1!02X!", m_FolderList1Length->getData());

		if (m_FolderList1Length)
		{
			terminateBlock();
			addChild(
				m_FolderList1LengthExtended,
				L"Folder List 1 Length Extended = 0x%1!04X!\r\n",
				m_FolderList1LengthExtended->getData());
			addHeader(L"Folder List 1 = ");

			if (!m_FolderList1->empty())
			{
				addChild(m_FolderList1, m_FolderList1->c_str());
			}
		}

		terminateBlock();
		addChild(m_FolderList2Length, L"Folder List 2 Length = 0x%1!08X!", m_FolderList2Length->getData());

		if (m_FolderList2Length)
		{
			terminateBlock();
			addHeader(L"FolderList2 = \r\n");
			addChild(m_FolderList2.getBlock());
		}

		if (*m_Flags & SFST_BINARY)
		{
			terminateBlock();
			addChild(m_AddressCount, L"AddressCount = 0x%1!08X!", m_AddressCount->getData());

			auto i = DWORD{};
			for (const auto& address : m_Addresses)
			{
				terminateBlock();
				addChild(
					address->PropertyCount,
					L"Addresses[%1!d!].PropertyCount = 0x%2!08X!\r\n",
					i,
					address->PropertyCount->getData());
				addChild(address->Pad, L"Addresses[%1!d!].Pad = 0x%2!08X!\r\n", i, address->Pad->getData());

				addHeader(L"Properties[%1!d!]:\r\n", i);
				addChild(address->Props.getBlock());
				i++;
			}
		}

		terminateBlock();
		addChild(m_SkipLen2, L"SkipLen2 = 0x%1!08X!", m_SkipLen2->getData());

		if (m_SkipLen2)
		{
			terminateBlock();
			addHeader(L"SkipBytes2 = ");
			addChild(m_SkipBytes2);
		}

		if (m_Restriction && m_Restriction->hasData())
		{
			terminateBlock();
			addChild(m_Restriction->getBlock());
		}

		if (*m_Flags & SFST_FILTERSTREAM)
		{
			terminateBlock();
			addHeader(L"AdvancedSearchLen = 0x%1!08X!", m_AdvancedSearchBytes->size());

			if (!m_AdvancedSearchBytes->empty())
			{
				terminateBlock();
				addHeader(L"AdvancedSearchBytes = ");
				addChild(m_AdvancedSearchBytes);
			}
		}

		terminateBlock();
		addChild(m_SkipLen3, L"SkipLen3 = 0x%1!08X!", m_SkipLen3->getData());

		if (m_SkipLen3)
		{
			terminateBlock();
			addHeader(L"SkipBytes3 = ");
			addChild(m_SkipBytes3);
		}
	}
} // namespace smartview<commit_msg>fix it<commit_after>#include <core/stdafx.h>
#include <core/smartview/SearchFolderDefinition.h>
#include <core/smartview/RestrictionStruct.h>
#include <core/smartview/PropertiesStruct.h>
#include <core/mapi/extraPropTags.h>
#include <core/smartview/SmartView.h>

namespace smartview
{
	AddressListEntryStruct::AddressListEntryStruct(std::shared_ptr<binaryParser> parser)
	{
		PropertyCount = blockT<DWORD>::parse(parser);
		Pad = blockT<DWORD>::parse(parser);
		if (*PropertyCount)
		{
			Props.SetMaxEntries(*PropertyCount);
			Props.SmartViewParser::parse(parser, false);
		}
	}

	void SearchFolderDefinition::Parse()
	{
		m_Version = blockT<DWORD>::parse(m_Parser);
		m_Flags = blockT<DWORD>::parse(m_Parser);
		m_NumericSearch = blockT<DWORD>::parse(m_Parser);

		m_TextSearchLength = blockT<BYTE>::parse(m_Parser);
		size_t cchTextSearch = *m_TextSearchLength;
		if (*m_TextSearchLength == 255)
		{
			m_TextSearchLengthExtended = blockT<WORD>::parse(m_Parser);
			cchTextSearch = *m_TextSearchLengthExtended;
		}

		if (cchTextSearch)
		{
			m_TextSearch = blockStringW::parse(m_Parser, cchTextSearch);
		}

		m_SkipLen1 = blockT<DWORD>::parse(m_Parser);
		m_SkipBytes1 = blockBytes::parse(m_Parser, *m_SkipLen1, _MaxBytes);

		m_DeepSearch = blockT<DWORD>::parse(m_Parser);

		m_FolderList1Length = blockT<BYTE>::parse(m_Parser);
		size_t cchFolderList1 = *m_FolderList1Length;
		if (*m_FolderList1Length == 255)
		{
			m_FolderList1LengthExtended = blockT<WORD>::parse(m_Parser);
			cchFolderList1 = *m_FolderList1LengthExtended;
		}

		if (cchFolderList1)
		{
			m_FolderList1 = blockStringW::parse(m_Parser, cchFolderList1);
		}

		m_FolderList2Length = blockT<DWORD>::parse(m_Parser);

		if (m_FolderList2Length)
		{
			m_FolderList2.parse(m_Parser, *m_FolderList2Length, true);
		}

		if (*m_Flags & SFST_BINARY)
		{
			m_AddressCount = blockT<DWORD>::parse(m_Parser);
			if (*m_AddressCount)
			{
				if (*m_AddressCount < _MaxEntriesSmall)
				{
					m_Addresses.reserve(*m_AddressCount);
					for (DWORD i = 0; i < *m_AddressCount; i++)
					{
						m_Addresses.emplace_back(std::make_shared<AddressListEntryStruct>(m_Parser));
					}
				}
			}
		}

		m_SkipLen2 = blockT<DWORD>::parse(m_Parser);
		m_SkipBytes2 = blockBytes::parse(m_Parser, *m_SkipLen2, _MaxBytes);

		if (*m_Flags & SFST_MRES)
		{
			m_Restriction = std::make_shared<RestrictionStruct>(false, true);
			m_Restriction->SmartViewParser::parse(m_Parser, false);
		}

		if (*m_Flags & SFST_FILTERSTREAM)
		{
			const auto cbRemainingBytes = m_Parser->RemainingBytes();
			// Since the format for SFST_FILTERSTREAM isn't documented, just assume that everything remaining
			// is part of this bucket. We leave DWORD space for the final skip block, which should be empty
			if (cbRemainingBytes > sizeof DWORD)
			{
				m_AdvancedSearchBytes = blockBytes::parse(m_Parser, cbRemainingBytes - sizeof DWORD);
			}
		}

		m_SkipLen3 = blockT<DWORD>::parse(m_Parser);
		if (m_SkipLen3)
		{
			m_SkipBytes3 = blockBytes::parse(m_Parser, *m_SkipLen3, _MaxBytes);
		}
	}

	void SearchFolderDefinition::ParseBlocks()
	{
		setRoot(L"Search Folder Definition:\r\n");
		addChild(m_Version, L"Version = 0x%1!08X!\r\n", m_Version->getData());
		addChild(
			m_Flags,
			L"Flags = 0x%1!08X! = %2!ws!\r\n",
			m_Flags->getData(),
			InterpretNumberAsStringProp(*m_Flags, PR_WB_SF_STORAGE_TYPE).c_str());
		addChild(m_NumericSearch, L"Numeric Search = 0x%1!08X!\r\n", m_NumericSearch->getData());
		addChild(m_TextSearchLength, L"Text Search Length = 0x%1!02X!", m_TextSearchLength->getData());

		if (*m_TextSearchLength)
		{
			terminateBlock();
			addChild(
				m_TextSearchLengthExtended,
				L"Text Search Length Extended = 0x%1!04X!\r\n",
				m_TextSearchLengthExtended->getData());
			addHeader(L"Text Search = ");
			if (!m_TextSearch->empty())
			{
				addChild(m_TextSearch, m_TextSearch->c_str());
			}
		}

		terminateBlock();
		addChild(m_SkipLen1, L"SkipLen1 = 0x%1!08X!", m_SkipLen1->getData());

		if (*m_SkipLen1)
		{
			terminateBlock();
			addHeader(L"SkipBytes1 = ");

			addChild(m_SkipBytes1);
		}

		terminateBlock();
		addChild(m_DeepSearch, L"Deep Search = 0x%1!08X!\r\n", m_DeepSearch->getData());
		addChild(m_FolderList1Length, L"Folder List 1 Length = 0x%1!02X!", m_FolderList1Length->getData());

		if (*m_FolderList1Length)
		{
			terminateBlock();
			addChild(
				m_FolderList1LengthExtended,
				L"Folder List 1 Length Extended = 0x%1!04X!\r\n",
				m_FolderList1LengthExtended->getData());
			addHeader(L"Folder List 1 = ");

			if (!m_FolderList1->empty())
			{
				addChild(m_FolderList1, m_FolderList1->c_str());
			}
		}

		terminateBlock();
		addChild(m_FolderList2Length, L"Folder List 2 Length = 0x%1!08X!", m_FolderList2Length->getData());

		if (*m_FolderList2Length)
		{
			terminateBlock();
			addHeader(L"FolderList2 = \r\n");
			addChild(m_FolderList2.getBlock());
		}

		if (*m_Flags & SFST_BINARY)
		{
			terminateBlock();
			addChild(m_AddressCount, L"AddressCount = 0x%1!08X!", m_AddressCount->getData());

			auto i = DWORD{};
			for (const auto& address : m_Addresses)
			{
				terminateBlock();
				addChild(
					address->PropertyCount,
					L"Addresses[%1!d!].PropertyCount = 0x%2!08X!\r\n",
					i,
					address->PropertyCount->getData());
				addChild(address->Pad, L"Addresses[%1!d!].Pad = 0x%2!08X!\r\n", i, address->Pad->getData());

				addHeader(L"Properties[%1!d!]:\r\n", i);
				addChild(address->Props.getBlock());
				i++;
			}
		}

		terminateBlock();
		addChild(m_SkipLen2, L"SkipLen2 = 0x%1!08X!", m_SkipLen2->getData());

		if (*m_SkipLen2)
		{
			terminateBlock();
			addHeader(L"SkipBytes2 = ");
			addChild(m_SkipBytes2);
		}

		if (m_Restriction && m_Restriction->hasData())
		{
			terminateBlock();
			addChild(m_Restriction->getBlock());
		}

		if (*m_Flags & SFST_FILTERSTREAM)
		{
			terminateBlock();
			addHeader(L"AdvancedSearchLen = 0x%1!08X!", m_AdvancedSearchBytes->size());

			if (!m_AdvancedSearchBytes->empty())
			{
				terminateBlock();
				addHeader(L"AdvancedSearchBytes = ");
				addChild(m_AdvancedSearchBytes);
			}
		}

		terminateBlock();
		addChild(m_SkipLen3, L"SkipLen3 = 0x%1!08X!", m_SkipLen3->getData());

		if (*m_SkipLen3)
		{
			terminateBlock();
			addHeader(L"SkipBytes3 = ");
			addChild(m_SkipBytes3);
		}
	}
} // namespace smartview<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkConeSource.cc
  Language:  C++
  Date:      09 Oct 1995
  Version:   1.22

Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
//
// Methods for Cone generator
//
#include <math.h>
#include "vtkConeSource.h"
#include "vtkMath.h"

// Description:
// Construct with default resolution 6, height 1.0, radius 0.5, and capping
// on.
vtkConeSource::vtkConeSource(int res)
{
  res = (res < 0 ? 0 : res);
  this->Resolution = res;
  this->Height = 1.0;
  this->Radius = 0.5;
  this->Capping = 1;
}

void vtkConeSource::Execute()
{
  float angle;
  int numLines, numPolys, numPts;
  float x[3], xbot;
  int i;
  int pts[VTK_CELL_SIZE];
  vtkFloatPoints *newPoints;
  vtkCellArray *newLines=0;
  vtkCellArray *newPolys=0;
  vtkPolyData *output = this->GetOutput();

  if( this->Resolution ) angle= 2.0*3.141592654/this->Resolution;
  //
  // Set things up; allocate memory
  //

  switch ( this->Resolution )
  {
  case 0:
    numPts = 2;
    numLines =  1;
    newLines = new vtkCellArray;
    newLines->Allocate(newLines->EstimateSize(numLines,numPts));

  case 1: case 2:
    numPts = 2*this->Resolution + 1;
    numPolys = this->Resolution;
    newPolys = new vtkCellArray;
    newPolys->Allocate(newPolys->EstimateSize(numPolys,3));
    break;

  default:
    numPts = this->Resolution + 1;
    numPolys = this->Resolution + 1;
    newPolys = new vtkCellArray;
    newPolys->Allocate(newPolys->EstimateSize(numPolys,this->Resolution));
    break;
  }
  newPoints = new vtkFloatPoints(numPts);
//
// Create cone
//
  x[0] = this->Height / 2.0; // zero-centered
  x[1] = 0.0;
  x[2] = 0.0;
  pts[0] = newPoints->InsertNextPoint(x);

  xbot = -this->Height / 2.0;

  switch (this->Resolution)
  {
  case 0:
    x[0] = xbot;
    x[1] = 0.0;
    x[2] = 0.0;
    pts[1] = newPoints->InsertNextPoint(x);
    newLines->InsertNextCell(2,pts);
    break;

  case 2:  // fall through this case to use the code in case 1
    x[0] = xbot;
    x[1] = 0.0;
    x[2] = -this->Radius;
    pts[1] = newPoints->InsertNextPoint(x);
    x[0] = xbot;
    x[1] = 0.0;
    x[2] = this->Radius;
    pts[2] = newPoints->InsertNextPoint(x);

    newPolys->InsertNextCell(3,pts);

  case 1:
    x[0] = xbot;
    x[1] = -this->Radius;
    x[2] = 0.0;
    pts[1] = newPoints->InsertNextPoint(x);
    x[0] = xbot;
    x[1] = this->Radius;
    x[2] = 0.0;
    pts[2] = newPoints->InsertNextPoint(x);

    newPolys->InsertNextCell(3,pts);

    break;

  default: // General case: create Resolution triangles and single cap

    for (i=0; i<this->Resolution; i++)
      {
      x[0] = xbot;
      x[1] = this->Radius * cos ((double)i*angle);
      x[2] = this->Radius * sin ((double)i*angle);
      pts[1] = newPoints->InsertNextPoint(x);
      pts[2] = (pts[1] % this->Resolution) + 1;
      newPolys->InsertNextCell(3,pts);
      }
//
// If capping, create last polygon
//
    if ( this->Capping )
      {
      for (i=0; i<this->Resolution; i++) pts[this->Resolution - i - 1] = i+1;
      newPolys->InsertNextCell(this->Resolution,pts);
      }
  } //switch
//
// Update ourselves
//
  output->SetPoints(newPoints);
  newPoints->Delete();

  if ( newPolys )
    {
    newPolys->Squeeze(); // we may have estimated size; reclaim some space
    output->SetPolys(newPolys);
    newPolys->Delete();
    }
  else
    {
    output->SetLines(newLines);
    newLines->Delete();
    }
}

void vtkConeSource::SetAngle(float angle)
{
  this->SetRadius (this->Height * tan ((double) angle*vtkMath::DegreesToRadians()));
}

float vtkConeSource::GetAngle()
{
  return atan2 (this->Radius, this->Height) / vtkMath::DegreesToRadians();
}

void vtkConeSource::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkSource::PrintSelf(os,indent);

  os << indent << "Resolution: " << this->Resolution << "\n";
  os << indent << "Height: " << this->Height << "\n";
  os << indent << "Radius: " << this->Radius << "\n";
  os << indent << "Capping: " << (this->Capping ? "On\n" : "Off\n");
}
<commit_msg>ERR: Wasn't generating lines at resolution 0<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkConeSource.cc
  Language:  C++
  Date:      09 Oct 1995
  Version:   1.22

Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
//
// Methods for Cone generator
//
#include <math.h>
#include "vtkConeSource.h"
#include "vtkMath.h"

// Description:
// Construct with default resolution 6, height 1.0, radius 0.5, and capping
// on.
vtkConeSource::vtkConeSource(int res)
{
  res = (res < 0 ? 0 : res);
  this->Resolution = res;
  this->Height = 1.0;
  this->Radius = 0.5;
  this->Capping = 1;
}

void vtkConeSource::Execute()
{
  float angle;
  int numLines, numPolys, numPts;
  float x[3], xbot;
  int i;
  int pts[VTK_CELL_SIZE];
  vtkFloatPoints *newPoints;
  vtkCellArray *newLines=0;
  vtkCellArray *newPolys=0;
  vtkPolyData *output = this->GetOutput();

  if ( this->Resolution ) angle = 2.0*3.141592654/this->Resolution;
  //
  // Set things up; allocate memory
  //

  switch ( this->Resolution )
  {
  case 0:
    numPts = 2;
    numLines =  1;
    newLines = new vtkCellArray;
    newLines->Allocate(newLines->EstimateSize(numLines,numPts));
    break;

  case 1: case 2:
    numPts = 2*this->Resolution + 1;
    numPolys = this->Resolution;
    newPolys = new vtkCellArray;
    newPolys->Allocate(newPolys->EstimateSize(numPolys,3));
    break;

  default:
    numPts = this->Resolution + 1;
    numPolys = this->Resolution + 1;
    newPolys = new vtkCellArray;
    newPolys->Allocate(newPolys->EstimateSize(numPolys,this->Resolution));
    break;
  }
  newPoints = new vtkFloatPoints(numPts);
//
// Create cone
//
  x[0] = this->Height / 2.0; // zero-centered
  x[1] = 0.0;
  x[2] = 0.0;
  pts[0] = newPoints->InsertNextPoint(x);

  xbot = -this->Height / 2.0;

  switch (this->Resolution)
  {
  case 0:
    x[0] = xbot;
    x[1] = 0.0;
    x[2] = 0.0;
    pts[1] = newPoints->InsertNextPoint(x);
    newLines->InsertNextCell(2,pts);
    break;

  case 2:  // fall through this case to use the code in case 1
    x[0] = xbot;
    x[1] = 0.0;
    x[2] = -this->Radius;
    pts[1] = newPoints->InsertNextPoint(x);
    x[0] = xbot;
    x[1] = 0.0;
    x[2] = this->Radius;
    pts[2] = newPoints->InsertNextPoint(x);

    newPolys->InsertNextCell(3,pts);

  case 1:
    x[0] = xbot;
    x[1] = -this->Radius;
    x[2] = 0.0;
    pts[1] = newPoints->InsertNextPoint(x);
    x[0] = xbot;
    x[1] = this->Radius;
    x[2] = 0.0;
    pts[2] = newPoints->InsertNextPoint(x);

    newPolys->InsertNextCell(3,pts);

    break;

  default: // General case: create Resolution triangles and single cap

    for (i=0; i<this->Resolution; i++)
      {
      x[0] = xbot;
      x[1] = this->Radius * cos ((double)i*angle);
      x[2] = this->Radius * sin ((double)i*angle);
      pts[1] = newPoints->InsertNextPoint(x);
      pts[2] = (pts[1] % this->Resolution) + 1;
      newPolys->InsertNextCell(3,pts);
      }
//
// If capping, create last polygon
//
    if ( this->Capping )
      {
      for (i=0; i<this->Resolution; i++) pts[this->Resolution - i - 1] = i+1;
      newPolys->InsertNextCell(this->Resolution,pts);
      }
  } //switch
//
// Update ourselves
//
  output->SetPoints(newPoints);
  newPoints->Delete();

  if ( newPolys )
    {
    newPolys->Squeeze(); // we may have estimated size; reclaim some space
    output->SetPolys(newPolys);
    newPolys->Delete();
    }
  else
    {
    output->SetLines(newLines);
    newLines->Delete();
    }
}

void vtkConeSource::SetAngle(float angle)
{
  this->SetRadius (this->Height * tan ((double) angle*vtkMath::DegreesToRadians()));
}

float vtkConeSource::GetAngle()
{
  return atan2 (this->Radius, this->Height) / vtkMath::DegreesToRadians();
}

void vtkConeSource::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkSource::PrintSelf(os,indent);

  os << indent << "Resolution: " << this->Resolution << "\n";
  os << indent << "Height: " << this->Height << "\n";
  os << indent << "Radius: " << this->Radius << "\n";
  os << indent << "Capping: " << (this->Capping ? "On\n" : "Off\n");
}
<|endoftext|>