<commit_before>#include "TChain.h"
#include "TH1.h"
#include "TH2.h"
#include "TH3.h"
#include "TList.h"
#include "AliAnalysisTask.h"
#include "AliAnalysisManager.h"
#include "AliAODEvent.h"
#include "AliAODInputHandler.h"
#include "AliAnalysisTaskParticleYieldRatioCorrelationsEfficiency.h"
#include "AliAODMCParticle.h"
#include "AliMultSelection.h"

using namespace std;

ClassImp(AliAnalysisTaskParticleYieldRatioCorrelationsEfficiency)

    AliAnalysisTaskParticleYieldRatioCorrelationsEfficiency::AliAnalysisTaskParticleYieldRatioCorrelationsEfficiency() : AliAnalysisTaskSE(),
                                                     fAOD(0), fOutputList(0)
{
    // default constructor, don't allocate memory here!
    // this is used by root for IO purposes, it needs to remain empty
}
//_____________________________________________________________________________
AliAnalysisTaskParticleYieldRatioCorrelationsEfficiency::AliAnalysisTaskParticleYieldRatioCorrelationsEfficiency(const char *name) : AliAnalysisTaskSE(name),
                                                                 fAOD(0), fOutputList(0)
{
    // constructor
    DefineInput(0, TChain::Class());
    DefineOutput(1, TList::Class());
}
//_____________________________________________________________________________
AliAnalysisTaskParticleYieldRatioCorrelationsEfficiency::~AliAnalysisTaskParticleYieldRatioCorrelationsEfficiency()
{
    // destructor
    if (fOutputList)
    {
        delete fOutputList;
    }
}
//_____________________________________________________________________________
void AliAnalysisTaskParticleYieldRatioCorrelationsEfficiency::UserCreateOutputObjects()
{
    fOutputList = new TList();
    fOutputList->SetOwner(kTRUE);

    AliAnalysisManager *man = AliAnalysisManager::GetAnalysisManager();
    if (man)
    {
        AliInputEventHandler *inputHandler = dynamic_cast<AliInputEventHandler *>(man->GetInputEventHandler());
        if (inputHandler)
            fPIDResponse = inputHandler->GetPIDResponse();
        else
            AliFatal("Input handler needed");
    }
    PostData(1, fOutputList);
}
//_____________________________________________________________________________
void AliAnalysisTaskParticleYieldRatioCorrelationsEfficiency::UserExec(Option_t *)
{
    fAOD = dynamic_cast<AliAODEvent *>(InputEvent());

    if (!fAOD)
    {
        PostData(1, fOutputList);
        return;
    }
    PostData(1, fOutputList);
}
//_____________________________________________________________________________
void AliAnalysisTaskParticleYieldRatioCorrelationsEfficiency::Terminate(Option_t *)
{
    // terminate
    // called at the END of the analysis (when all events are processed)
}
//_____________________________________________________________________________
<commit_msg>Update AliAnalysisTaskParticleYieldRatioCorrelationsEfficiency.cxx<commit_after>#include "TChain.h"
#include "TH1.h"
#include "TH2.h"
#include "TH3.h"
#include "TList.h"
#include "AliAnalysisTask.h"
#include "AliAnalysisManager.h"
#include "AliAODEvent.h"
#include "AliAODInputHandler.h"
#include "AliAnalysisTaskParticleYieldRatioCorrelationsEfficiency.h"
#include "AliAODMCParticle.h"
#include "AliMultSelection.h"

using namespace std;

ClassImp(AliAnalysisTaskParticleYieldRatioCorrelationsEfficiency)

    AliAnalysisTaskParticleYieldRatioCorrelationsEfficiency::AliAnalysisTaskParticleYieldRatioCorrelationsEfficiency() : AliAnalysisTaskSE(),
                                                                                fAOD(0), fOutputList(0), fDeDx(0), fTOF(0), fHistEventsCut(0), fAliEventCuts(0), fHistTracksCut(0)
{
    // default constructor, don't allocate memory here!
    // this is used by root for IO purposes, it needs to remain empty
}
//_____________________________________________________________________________
AliAnalysisTaskParticleYieldRatioCorrelationsEfficiency::AliAnalysisTaskParticleYieldRatioCorrelationsEfficiency(const char *name) : AliAnalysisTaskSE(name),
                                                                                fAOD(0), fOutputList(0), fDeDx(0), fTOF(0), fHistEventsCut(0), fAliEventCuts(0), fHistTracksCut(0)
{
    // constructor
    DefineInput(0, TChain::Class());
    DefineOutput(1, TList::Class());
}
//_____________________________________________________________________________
AliAnalysisTaskParticleYieldRatioCorrelationsEfficiency::~AliAnalysisTaskParticleYieldRatioCorrelationsEfficiency()
{
    // destructor
    if (fOutputList)
    {
        delete fOutputList;
    }
}
//_____________________________________________________________________________
void AliAnalysisTaskParticleYieldRatioCorrelationsEfficiency::UserCreateOutputObjects()
{
    fOutputList = new TList();
    fOutputList->SetOwner(kTRUE);

    fHistEventsCut = new TH1F("fHistEventsCut", ";NEvents", 6, 0, 6);
    fHistTracksCut = new TH1F("fHistTracksCut", ";Ntracks", 6, 0, 5);
    fHistEventsCut->GetXaxis()->SetBinLabel(1, "minBias");
    fHistEventsCut->GetXaxis()->SetBinLabel(2, "centrality");
    fHistEventsCut->GetXaxis()->SetBinLabel(3, "NContributors");
    fHistEventsCut->GetXaxis()->SetBinLabel(4, "vertex");
    fHistEventsCut->GetXaxis()->SetBinLabel(5, "AliEventCuts");
    fHistTracksCut->GetXaxis()->SetBinLabel(1, "minBias");
    fHistTracksCut->GetXaxis()->SetBinLabel(2, "FilterBit");
    fHistTracksCut->GetXaxis()->SetBinLabel(3, "Eta");
    fHistTracksCut->GetXaxis()->SetBinLabel(4, "pT");
    fHistTracksCut->GetXaxis()->SetBinLabel(5, "TOF");
    fDeDx = new TH2D("DeDx", ";p_{TPC};dE/dx (a.u.)", 200, 0.2, 2, 250, 0, 2000);
    fTOF = new TH2D("fTOF", ";p_{TPC};t", 200, 0.2, 2, 200, -4000, 4000);
    fOutputList->Add(fDeDx);
    fOutputList->Add(fTOF);
    for (int iSort = 0; iSort < 4; iSort++)
    {
        fDeDxSorts[iSort] = new TH2D(Form("DeDxSort%d", iSort), ";p_{TPC};dE/dx (a.u.)", 200, 0.2, 2, 250, 0, 2000);
        fTOFSorts[iSort] = new TH2D(Form("fTOFSort%d", iSort), ";p_{TPC};t", 200, 0.2, 2, 200, -4000, 4000);
        fOutputList->Add(fDeDxSorts[iSort]);
        fOutputList->Add(fTOFSorts[iSort]);
    }
    fOutputList->Add(fHistEventsCut);
    fOutputList->Add(fHistTracksCut);

    for (int iCent = 0; iCent < nCentrClasses; iCent++)
    {
        for (int iEta = 0; iEta < nEtaClasses; iEta++)
        {
            for (int iSort = 0; iSort < nSorts; iSort++)
            {
                NGenTracks[iCent][iEta][iSort] = new TH3D(Form("NGenTracksC%dEta%dSort%d", iCent, iEta, iSort), ";P_{T};Ntracks",
                                                          nPBins, minP, maxP, nPhiBins, 0, TMath::TwoPi(), nVertexBins, Vertexmin, Vertexmax);
                EfficiencyTracking[iCent][iEta][iSort] = new TH3D(Form("EfficiencyTrackingC%dEta%dSort%d", iCent, iEta, iSort), ";P_{T};EfficiencyTracking",
                                                                  nPBins, minP, maxP, nPhiBins, 0, TMath::TwoPi(), nVertexBins, Vertexmin, Vertexmax);
                ContaminationTracking[iCent][iEta][iSort] = new TH3D(Form("ContaminationTrackingC%dEta%dSort%d", iCent, iEta, iSort), ";P_{T};ContaminationTracking",
                                                                     nPBins, minP, maxP, nPhiBins, 0, TMath::TwoPi(), nVertexBins, Vertexmin, Vertexmax);
                NReconstTracks[iCent][iEta][iSort] = new TH3D(Form("NReconstTracksC%dEta%dSort%d", iCent, iEta, iSort), ";P_{T};Ntracks",
                                                              nPBins, minP, maxP, nPhiBins, 0, TMath::TwoPi(), nVertexBins, Vertexmin, Vertexmax);

                NTrueTracks[iCent][iEta][iSort] = new TH3D(Form("NTrueTracksC%dEta%dSort%d", iCent, iEta, iSort), ";P_{T};Ntracks",
                                                           nPBins, minP, maxP, nPhiBins, 0, TMath::TwoPi(), nVertexBins, Vertexmin, Vertexmax);
                EfficiencyPID[iCent][iEta][iSort] = new TH3D(Form("EfficiencyPIDC%dEta%dSort%d", iCent, iEta, iSort), ";P_{T};EfficiencyPID",
                                                             nPBins, minP, maxP, nPhiBins, 0, TMath::TwoPi(), nVertexBins, Vertexmin, Vertexmax);
                ContaminationPID[iCent][iEta][iSort] = new TH3D(Form("ContaminationPIDC%dEta%dSort%d", iCent, iEta, iSort), ";P_{T};ContaminationPID",
                                                                nPBins, minP, maxP, nPhiBins, 0, TMath::TwoPi(), nVertexBins, Vertexmin, Vertexmax);
                NTracksInCut[iCent][iEta][iSort] = new TH3D(Form("NTracksInCutC%dEta%dSort%d", iCent, iEta, iSort), ";P_{T};Ntracks",
                                                            nPBins, minP, maxP, nPhiBins, 0, TMath::TwoPi(), nVertexBins, Vertexmin, Vertexmax);

                fOutputList->Add(NGenTracks[iCent][iEta][iSort]);
                fOutputList->Add(EfficiencyTracking[iCent][iEta][iSort]);
                fOutputList->Add(ContaminationTracking[iCent][iEta][iSort]);
                fOutputList->Add(NReconstTracks[iCent][iEta][iSort]);

                fOutputList->Add(NTrueTracks[iCent][iEta][iSort]);
                fOutputList->Add(EfficiencyPID[iCent][iEta][iSort]);
                fOutputList->Add(ContaminationPID[iCent][iEta][iSort]);
                fOutputList->Add(NTracksInCut[iCent][iEta][iSort]);
            }
        }
    }

    for (int iSort = 0; iSort < nSorts; iSort++)
    {
        purityAll[iSort] = new TH1D(Form("pur%d", iSort), "", nPBins, minP, maxP);
        fOutputList->Add(purityAll[iSort]);
        for (int jSort = 0; jSort < nSorts; jSort++)
        {
            purity[iSort][jSort] = new TH1D(Form("pur%din%d", jSort, iSort), "", nPBins, minP, maxP);
            fOutputList->Add(purity[iSort][jSort]);
        }
    }
    fHistQASPDTrackletsvsV0MCent = new TH2D("fHistQASPDTrackletsvsV0MCent", ";V0M Percentile;N Tracklets in SPD", 100, 0, 100, 400, 0, 1e4);
    fOutputList->Add(fHistQASPDTrackletsvsV0MCent);
    if (!pbpb)
    {
        fAliEventCuts = new AliEventCuts();
        fAliEventCuts->SetupRun2pp();
    }
    AliAnalysisManager *man = AliAnalysisManager::GetAnalysisManager();
    if (man)
    {
        AliInputEventHandler *inputHandler = dynamic_cast<AliInputEventHandler *>(man->GetInputEventHandler());
        if (inputHandler)
            fPIDResponse = inputHandler->GetPIDResponse();
        else
            AliFatal("Input handler needed");
    }
    PostData(1, fOutputList);
}
//_____________________________________________________________________________
void AliAnalysisTaskParticleYieldRatioCorrelationsEfficiency::UserExec(Option_t *)
{
    fAOD = dynamic_cast<AliAODEvent *>(InputEvent());

    if (!fAOD)
    {
        PostData(1, fOutputList);
        return;
    }
    fHistEventsCut->Fill("minBias", 1);
    if (!pbpb && !fAliEventCuts->AcceptEvent(fAOD))
    {
        PostData(1, fOutputList);
        return;
    }

    Float_t centr;
    Int_t NTrackletsSPD;
    if (0)
    {
        AliCentrality *centrality = fAOD->GetCentrality();
        centr = centrality->GetCentralityPercentile("V0M");
    }
    else
    {
        AliMultSelection *MultSelection = 0x0;
        MultSelection = (AliMultSelection *)fAOD->FindListObject("MultSelection");
        if (MultSelection)
        {
            centr = MultSelection->GetMultiplicityPercentile("V0M");
            NTrackletsSPD = MultSelection->GetEstimator("SPDTracklets")->GetValue();
        }
        else
        {
            fHistEventsCut->Fill("AliEventCuts", 1);
            PostData(1, fOutputList);
            return;
        }
    }
    //centrality cut:
    if (centr < minCent || centr > maxCent)
    {
        PostData(1, fOutputList);
        return;
    }
    fHistEventsCut->Fill("centrality", 1);
    fHistQASPDTrackletsvsV0MCent->Fill(centr, NTrackletsSPD);
    if (1)
    {
        TF1 *fSPDvsV0M_DownLimit = new TF1("fSPDvsV0M_DownLimit", "exp(8.1456-0.0354*x-3.8e-04*x*x)", 0, 80);
        TF1 *fSPDvsV0M_UperLimit = new TF1("fSPDvsV0M_UperLimit", "exp(8.58-0.036*x-4.4e-05*x*x)", 0, 80);
        if (NTrackletsSPD < fSPDvsV0M_DownLimit->Eval(centr) || NTrackletsSPD > fSPDvsV0M_UperLimit->Eval(centr))
        {
            PostData(1, fOutputList);
            return;
        }
        fHistEventsCut->Fill("SPDvsV0M", 1);
    }
    const AliAODVertex *vtx = fAOD->GetPrimaryVertex();
    if (vtx->GetNContributors() < 1)
    {
        PostData(1, fOutputList);
        return;
    }
    fHistEventsCut->Fill("NContributors", 1);
    if (fabs((Float_t)vtx->GetZ()) > 8)
    {
        PostData(1, fOutputList);
        return;
    }
    fHistEventsCut->Fill("vertex", 1);
    Float_t vertex = (Float_t)vtx->GetZ();
    Int_t nTracks(fAOD->GetNumberOfTracks());
    Int_t EtaBin, CentrBin;
    int sort = 20;
    CentrBin = (centr - minCent) / ((maxCent - minCent) / nCentrClasses);
    //CentrBin = centr<=5?0:(centr<=10?1: 2+(centr-10)/((maxCent-10)/(nCentrClasses-2)) ); //if first bins are 0-5 & 5-10
    int NAcceptedtracks = 0;
    fHistTracksCut->Fill("minBias", nTracks);

    AliAODInputHandler *eventHandler = dynamic_cast<AliAODInputHandler *>(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());
    AliMCEvent *fMC = eventHandler->MCEvent();
    Int_t nMCTracks(fMC->GetNumberOfTracks());
    Float_t PtCut[3] = {0.2, 0.5, 0.5};
    Float_t nSigmaBoundary[3] = {0.5, 0.32, 0.7};

    //Track loop:
    for (Int_t i(0); i < nTracks; i++)
    {
        AliAODTrack *track = static_cast<AliAODTrack *>(fAOD->GetTrack(i));
        if (!track || !track->TestFilterBit(filterBit))
            continue;
        fHistTracksCut->Fill("FilterBit", 1);
        if (fabs(track->Eta()) >= 0.8)
            continue;
        fHistTracksCut->Fill("Eta", 1);
        if (track->Pt() < minP || track->Pt() > maxP)
            continue;
        fHistTracksCut->Fill("pT", 1);
        EtaBin = (0.8 + track->Eta()) / (1.6 / nEtaClasses);

        Float_t nOfSigmasTPC_el = fPIDResponse->NumberOfSigmasTPC(track, AliPID::kElectron);
        Float_t nOfSigmasTPC_pi = fPIDResponse->NumberOfSigmasTPC(track, AliPID::kPion);
        Float_t nOfSigmasTPC_K = fPIDResponse->NumberOfSigmasTPC(track, AliPID::kKaon);
        Float_t nOfSigmasTPC_p = fPIDResponse->NumberOfSigmasTPC(track, AliPID::kProton);

        Float_t nOfSigmasTOF_pi = fPIDResponse->NumberOfSigmasTOF(track, AliPID::kPion, fPIDResponse->GetTOFResponse().GetTimeZero());
        Float_t nOfSigmasTOF_K = fPIDResponse->NumberOfSigmasTOF(track, AliPID::kKaon, fPIDResponse->GetTOFResponse().GetTimeZero());
        Float_t nOfSigmasTOF_p = fPIDResponse->NumberOfSigmasTOF(track, AliPID::kProton, fPIDResponse->GetTOFResponse().GetTimeZero());

        if (fabs(nOfSigmasTOF_pi > 900))
        {
            fHistTracksCut->Fill("TOF", 1);
            continue;
        }
        if (fabs(nOfSigmasTOF_K > 900))
        {
            continue;
        }
        if (fabs(nOfSigmasTOF_p > 900))
        {
            continue;
        }
        if (track->GetTPCCrossedRows() <= nCrossedRows)
        {
            continue;
        }

        Float_t Pt = track->Pt();
        Float_t Px = track->Px();
        Float_t Py = track->Py();
        Float_t Pz = track->Pz();
        Float_t Moment = track->GetTPCmomentum();
        Float_t Phi = track->Phi();
        Float_t Eta = track->Eta();
        Float_t DeDx = track->GetTPCsignal();
        Float_t Charge = track->Charge();
        fDeDx->Fill(Moment, DeDx);
        fTOF->Fill(Moment, track->GetTOFsignal());

        if (IsMC && fMC)
        {
            int label = track->GetLabel();
            AliAODMCParticle *part = (AliAODMCParticle *)fMC->GetTrack(abs(label));
            if (part)
            {

                if (fabs(part->GetPdgCode()) == 211)
                    sort = 0;
                if (fabs(part->GetPdgCode()) == 321)
                    sort = 1;
                if (fabs(part->GetPdgCode()) == 2212)
                    sort = 2;
                if (fabs(part->GetPdgCode()) == 11)
                    sort = 3;
                if (fabs(part->GetPdgCode()) == 1000010020)
                    sort = 4;

                if ((sort >= 0 && sort <= 3) && Pt > PtCut[sort])
                {
                    if (part->IsPhysicalPrimary())
                        EfficiencyTracking[CentrBin][EtaBin][sort * 2 + (Charge < 0 ? 0 : 1)]->Fill(Pt, Phi, vertex);
                    else
                        ContaminationTracking[CentrBin][EtaBin][sort * 2 + (Charge < 0 ? 0 : 1)]->Fill(Pt, Phi, vertex);
                    NReconstTracks[CentrBin][EtaBin][sort * 2 + (Charge < 0 ? 0 : 1)]->Fill(Pt, Phi, vertex);
                }
            }
        }

        Float_t nSigma_comb_pi = sqrt(nOfSigmasTPC_pi * nOfSigmasTPC_pi + nOfSigmasTOF_pi * nOfSigmasTOF_pi);
        Float_t nSigma_comb_K = sqrt(nOfSigmasTPC_K * nOfSigmasTPC_K + nOfSigmasTOF_K * nOfSigmasTOF_K);
        Float_t nSigma_comb_p = sqrt(nOfSigmasTPC_p * nOfSigmasTPC_p + nOfSigmasTOF_p * nOfSigmasTOF_p);

        //Fill TH3D hists for maps
        bool selected_pi = false;
        if (Pt < nSigmaBoundary[0] && fabs(nOfSigmasTPC_pi) < nSigma && fabs(nOfSigmasTPC_K) > 3 && fabs(nOfSigmasTPC_p) > 3 && fabs(nOfSigmasTPC_el) > 1)
            selected_pi = true;
        if (Pt > nSigmaBoundary[0] && nSigma_comb_pi < nSigma && nSigma_comb_K > 3 && nSigma_comb_p > 3)
            selected_pi = true;
        if (selected_pi)
        {
            if (Charge < 0)
            {
                NTracksInCut[CentrBin][EtaBin][0]->Fill(Pt, Phi, vertex);
                if (sort == 0)
                    EfficiencyPID[CentrBin][EtaBin][0]->Fill(Pt, Phi, vertex);
                else
                    ContaminationPID[CentrBin][EtaBin][0]->Fill(Pt, Phi, vertex);
                purity[0][sort * 2 + (Charge < 0 ? 0 : 1)]->Fill(Pt);
                purityAll[0]->Fill(Pt);
            }
            if (Charge > 0)
            {
                NTracksInCut[CentrBin][EtaBin][1]->Fill(Pt, Phi, vertex);
                if (sort == 0)
                    EfficiencyPID[CentrBin][EtaBin][1]->Fill(Pt, Phi, vertex);
                else
                    ContaminationPID[CentrBin][EtaBin][1]->Fill(Pt, Phi, vertex);
                purity[1][sort * 2 + (Charge < 0 ? 0 : 1)]->Fill(Pt);
                purityAll[1]->Fill(Pt);
            }
            fDeDxSorts[0]->Fill(Moment, DeDx);
            fTOFSorts[0]->Fill(Moment, track->GetTOFsignal());
        }

        bool selected_K = false;
        if (Pt < nSigmaBoundary[1] && fabs(nOfSigmasTPC_K) < nSigma && fabs(nOfSigmasTPC_pi) > 3 && fabs(nOfSigmasTPC_p) > 3) // && fabs( nOfSigmasTPC_el)>1 )
            selected_K = true;
        if (Pt > nSigmaBoundary[1] && nSigma_comb_K < nSigma && nSigma_comb_pi > 3 && nSigma_comb_p > 3)
            selected_K = true;
        if (selected_K && Pt > PtCut[1])
        {
            if (Charge < 0)
            {
                NTracksInCut[CentrBin][EtaBin][2]->Fill(Pt, Phi, vertex);
                if (sort == 1)
                    EfficiencyPID[CentrBin][EtaBin][2]->Fill(Pt, Phi, vertex);
                else
                    ContaminationPID[CentrBin][EtaBin][2]->Fill(Pt, Phi, vertex);
                purity[2][sort * 2 + (Charge < 0 ? 0 : 1)]->Fill(Pt);
                purityAll[2]->Fill(Pt);
            }
            if (Charge > 0)
            {
                NTracksInCut[CentrBin][EtaBin][3]->Fill(Pt, Phi, vertex);
                if (sort == 1)
                    EfficiencyPID[CentrBin][EtaBin][3]->Fill(Pt, Phi, vertex);
                else
                    ContaminationPID[CentrBin][EtaBin][3]->Fill(Pt, Phi, vertex);
                purity[3][sort * 2 + (Charge < 0 ? 0 : 1)]->Fill(Pt);
                purityAll[3]->Fill(Pt);
            }
            fDeDxSorts[1]->Fill(Moment, DeDx);
            fTOFSorts[1]->Fill(Moment, track->GetTOFsignal());
        }

        bool selected_p = false;
        if (Pt < nSigmaBoundary[2] && fabs(nOfSigmasTPC_p) < nSigma && fabs(nOfSigmasTPC_pi) > 3 && fabs(nOfSigmasTPC_K) > 3 && fabs(nOfSigmasTPC_el) > 1)
            selected_p = true;
        if (Pt > nSigmaBoundary[2] && nSigma_comb_p < nSigma && nSigma_comb_pi > 3 && nSigma_comb_K > 3)
            selected_p = true;
        if (selected_p && Pt > PtCut[2])
        {
            if (Charge < 0)
            {
                NTracksInCut[CentrBin][EtaBin][4]->Fill(Pt, Phi, vertex);
                if (sort == 2)
                    EfficiencyPID[CentrBin][EtaBin][4]->Fill(Pt, Phi, vertex);
                else
                    ContaminationPID[CentrBin][EtaBin][4]->Fill(Pt, Phi, vertex);
                purity[4][sort * 2 + (Charge < 0 ? 0 : 1)]->Fill(Pt);
                purityAll[4]->Fill(Pt);
            }
            if (Charge > 0)
            {
                NTracksInCut[CentrBin][EtaBin][5]->Fill(Pt, Phi, vertex);
                if (sort == 2)
                    EfficiencyPID[CentrBin][EtaBin][5]->Fill(Pt, Phi, vertex);
                else
                    ContaminationPID[CentrBin][EtaBin][5]->Fill(Pt, Phi, vertex);
                purity[5][sort * 2 + (Charge < 0 ? 0 : 1)]->Fill(Pt);
                purityAll[5]->Fill(Pt);
            }
            fDeDxSorts[2]->Fill(Moment, DeDx);
            fTOFSorts[2]->Fill(Moment, track->GetTOFsignal());
        }

        bool selected_el = false;
        if (fabs(nOfSigmasTPC_p) > 3 && fabs(nOfSigmasTPC_pi) > 3 && fabs(nOfSigmasTPC_K) > 3 && fabs(nOfSigmasTPC_el) < 2)
            selected_el = true;
        if (selected_el)
        {
            if (Charge < 0)
            {
                NTracksInCut[CentrBin][EtaBin][6]->Fill(Pt, Phi, vertex);
                if (sort == 3)
                    EfficiencyPID[CentrBin][EtaBin][6]->Fill(Pt, Phi, vertex);
                else
                    ContaminationPID[CentrBin][EtaBin][6]->Fill(Pt, Phi, vertex);
                purity[6][sort * 2 + (Charge < 0 ? 0 : 1)]->Fill(Pt);
                purityAll[6]->Fill(Pt);
            }
            if (Charge > 0)
            {
                NTracksInCut[CentrBin][EtaBin][7]->Fill(Pt, Phi, vertex);
                if (sort == 3)
                    EfficiencyPID[CentrBin][EtaBin][7]->Fill(Pt, Phi, vertex);
                else
                    ContaminationPID[CentrBin][EtaBin][7]->Fill(Pt, Phi, vertex);
                purity[7][sort * 2 + (Charge < 0 ? 0 : 1)]->Fill(Pt);
                purityAll[7]->Fill(Pt);
            }
            fDeDxSorts[3]->Fill(Moment, DeDx);
            fTOFSorts[3]->Fill(Moment, track->GetTOFsignal());
        }
        if ((sort >= 0 && sort <= 3) && Pt > PtCut[sort])
            NTrueTracks[CentrBin][EtaBin][sort * 2 + (Charge < 0 ? 0 : 1)]->Fill(Pt, Phi, vertex);
        //end of filling TH3D hists for maps

        NAcceptedtracks++;
    }
    // end of track loop

    int nAcceptedGenTracks = 0;

    if (IsMC && fMC)
    {
        //Generated particles track loop
        for (Int_t i(0); i < nMCTracks; i++)
        {
            AliAODMCParticle *trackMC = (AliAODMCParticle *)fMC->GetTrack(i);

            if (trackMC && trackMC->IsPhysicalPrimary() && fabs(trackMC->Eta()) < 0.8 && trackMC->Pt() >= minP && trackMC->Pt() <= maxP)
            {
                Float_t GenPt = trackMC->Pt();
                Float_t GenPhi = trackMC->Phi();
                Float_t GenEta = trackMC->Eta();
                Float_t GenCharge = trackMC->Charge();

                if (fabs(trackMC->GetPdgCode()) == 211)
                    sort = 0;
                if (fabs(trackMC->GetPdgCode()) == 321)
                    sort = 1;
                if (fabs(trackMC->GetPdgCode()) == 2212)
                    sort = 2;
                if (fabs(trackMC->GetPdgCode()) == 11)
                    sort = 3;
                if (fabs(trackMC->GetPdgCode()) == 1000010020)
                    sort = 4;
                nAcceptedGenTracks++;

                if ((sort >= 0 && sort <= 3) && GenPt > PtCut[sort] && GenCharge != 0)
                {
                    EtaBin = (0.8 + GenEta) / (1.6 / nEtaClasses);
                    NGenTracks[CentrBin][EtaBin][sort * 2 + (GenCharge < 0 ? 0 : 1)]->Fill(GenPt, GenPhi, vertex);
                }
            }
        }
    }
    PostData(1, fOutputList);
}
//_____________________________________________________________________________
void AliAnalysisTaskParticleYieldRatioCorrelationsEfficiency::Terminate(Option_t *)
{
    // terminate
    // called at the END of the analysis (when all events are processed)
}
//_____________________________________________________________________________
<|endoftext|>


<commit_before><commit_msg>Add analysis for correction maps<commit_after><|endoftext|>


<commit_before>// Scintilla source code edit control
/** @file LexSpice.cxx
 ** Lexer for Spice
 **/
// Copyright 2006 by Fabien Proriol <proriol.fabien.dev@saint-pal.com>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdio.h>

#include "Platform.h"

#include "Accessor.h"
#include "StyleContext.h"
#include "PropSet.h"
#include "KeyWords.h"
#include "SciLexer.h"
#include "SString.h"

/*
 * Interface
 */

static void ColouriseDocument(
    unsigned int startPos,
    int length,
    int initStyle,
    WordList *keywordlists[],
    Accessor &styler);

static const char * const spiceWordListDesc[] = {
    "Keywords",        // SPICE command
    "Keywords2",    // SPICE functions
    "Keywords3",    // SPICE params
    0
};

LexerModule lmSpice(SCLEX_SPICE, ColouriseDocument, "spice", NULL, spiceWordListDesc);

/*
 * Implementation
 */

static void ColouriseComment(StyleContext& sc, bool& apostropheStartsAttribute);
static void ColouriseDelimiter(StyleContext& sc, bool& apostropheStartsAttribute);
static void ColouriseNumber(StyleContext& sc, bool& apostropheStartsAttribute);
static void ColouriseWhiteSpace(StyleContext& sc, bool& apostropheStartsAttribute);
static void ColouriseWord(StyleContext& sc, WordList& keywords, WordList& keywords2, WordList& keywords3, bool& apostropheStartsAttribute);

static inline bool IsDelimiterCharacter(int ch);
static inline bool IsNumberStartCharacter(int ch);
static inline bool IsNumberCharacter(int ch);
static inline bool IsSeparatorOrDelimiterCharacter(int ch);
static inline bool IsWordStartCharacter(int ch);
static inline bool IsWordCharacter(int ch);

static void ColouriseComment(StyleContext& sc, bool&) {
    sc.SetState(SCE_SPICE_COMMENTLINE);
    while (!sc.atLineEnd) {
        sc.Forward();
    }
}

static void ColouriseDelimiter(StyleContext& sc, bool& apostropheStartsAttribute) {
    apostropheStartsAttribute = sc.Match (')');
    sc.SetState(SCE_SPICE_DELIMITER);
    sc.ForwardSetState(SCE_SPICE_DEFAULT);
}

static void ColouriseNumber(StyleContext& sc, bool& apostropheStartsAttribute) {
    apostropheStartsAttribute = true;
    SString number;
    sc.SetState(SCE_SPICE_NUMBER);
    // Get all characters up to a delimiter or a separator, including points, but excluding
    // double points (ranges).
    while (!IsSeparatorOrDelimiterCharacter(sc.ch) || (sc.ch == '.' && sc.chNext != '.')) {
        number += static_cast<char>(sc.ch);
        sc.Forward();
    }
    // Special case: exponent with sign
    if ((sc.chPrev == 'e' || sc.chPrev == 'E') &&
            (sc.ch == '+' || sc.ch == '-')) {
        number += static_cast<char>(sc.ch);
        sc.Forward ();
        while (!IsSeparatorOrDelimiterCharacter(sc.ch)) {
            number += static_cast<char>(sc.ch);
            sc.Forward();
        }
    }
    sc.SetState(SCE_SPICE_DEFAULT);
}

static void ColouriseWhiteSpace(StyleContext& sc, bool& ) {
    sc.SetState(SCE_SPICE_DEFAULT);
    sc.ForwardSetState(SCE_SPICE_DEFAULT);
}

static void ColouriseWord(StyleContext& sc, WordList& keywords, WordList& keywords2, WordList& keywords3, bool& apostropheStartsAttribute) {
    apostropheStartsAttribute = true;
    sc.SetState(SCE_SPICE_IDENTIFIER);
    SString word;
    while (!sc.atLineEnd && !IsSeparatorOrDelimiterCharacter(sc.ch)) {
        word += static_cast<char>(tolower(sc.ch));
        sc.Forward();
    }
    if (keywords.InList(word.c_str())) {
        sc.ChangeState(SCE_SPICE_KEYWORD);
        if (word != "all") {
            apostropheStartsAttribute = false;
        }
    }
    else if (keywords2.InList(word.c_str())) {
        sc.ChangeState(SCE_SPICE_KEYWORD2);
        if (word != "all") {
            apostropheStartsAttribute = false;
        }
    }
    else if (keywords3.InList(word.c_str())) {
        sc.ChangeState(SCE_SPICE_KEYWORD3);
        if (word != "all") {
            apostropheStartsAttribute = false;
        }
    }
    sc.SetState(SCE_SPICE_DEFAULT);
}

//
// ColouriseDocument
//
static void ColouriseDocument(
    unsigned int startPos,
    int length,
    int initStyle,
    WordList *keywordlists[],
    Accessor &styler) {
    WordList &keywords = *keywordlists[0];
    WordList &keywords2 = *keywordlists[1];
    WordList &keywords3 = *keywordlists[2];
    StyleContext sc(startPos, length, initStyle, styler);
    int lineCurrent = styler.GetLine(startPos);
    bool apostropheStartsAttribute = (styler.GetLineState(lineCurrent) & 1) != 0;
    while (sc.More()) {
        if (sc.atLineEnd) {
            // Go to the next line
            sc.Forward();
            lineCurrent++;
            // Remember the line state for future incremental lexing
            styler.SetLineState(lineCurrent, apostropheStartsAttribute);
            // Don't continue any styles on the next line
            sc.SetState(SCE_SPICE_DEFAULT);
        }
        // Comments
        if ((sc.Match('*') && sc.atLineStart) || sc.Match('*','~')) {
            ColouriseComment(sc, apostropheStartsAttribute);
        // Whitespace
        } else if (IsASpace(sc.ch)) {
            ColouriseWhiteSpace(sc, apostropheStartsAttribute);
        // Delimiters
        } else if (IsDelimiterCharacter(sc.ch)) {
            ColouriseDelimiter(sc, apostropheStartsAttribute);
        // Numbers
        } else if (IsADigit(sc.ch) || sc.ch == '#') {
            ColouriseNumber(sc, apostropheStartsAttribute);
        // Keywords or identifiers
        } else {
            ColouriseWord(sc, keywords, keywords2, keywords3, apostropheStartsAttribute);
        }
    }
    sc.Complete();
}

static inline bool IsDelimiterCharacter(int ch) {
    switch (ch) {
    case '&':
    case '\'':
    case '(':
    case ')':
    case '*':
    case '+':
    case ',':
    case '-':
    case '.':
    case '/':
    case ':':
    case ';':
    case '<':
    case '=':
    case '>':
    case '|':
        return true;
    default:
        return false;
    }
}

static inline bool IsNumberCharacter(int ch) {
    return IsNumberStartCharacter(ch) ||
           ch == '_' ||
           ch == '.' ||
           ch == '#' ||
           (ch >= 'a' && ch <= 'f') ||
           (ch >= 'A' && ch <= 'F');
}

static inline bool IsNumberStartCharacter(int ch) {
    return IsADigit(ch);
}

static inline bool IsSeparatorOrDelimiterCharacter(int ch) {
    return IsASpace(ch) || IsDelimiterCharacter(ch);
}

static inline bool IsWordCharacter(int ch) {
    return IsWordStartCharacter(ch) || IsADigit(ch);
}

static inline bool IsWordStartCharacter(int ch) {
    return (isascii(ch) && isalpha(ch)) || ch == '_';
}
<commit_msg>Removed email address.<commit_after>// Scintilla source code edit control
/** @file LexSpice.cxx
 ** Lexer for Spice
 **/
// Copyright 2006 by Fabien Proriol
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdio.h>

#include "Platform.h"

#include "Accessor.h"
#include "StyleContext.h"
#include "PropSet.h"
#include "KeyWords.h"
#include "SciLexer.h"
#include "SString.h"

/*
 * Interface
 */

static void ColouriseDocument(
    unsigned int startPos,
    int length,
    int initStyle,
    WordList *keywordlists[],
    Accessor &styler);

static const char * const spiceWordListDesc[] = {
    "Keywords",        // SPICE command
    "Keywords2",    // SPICE functions
    "Keywords3",    // SPICE params
    0
};

LexerModule lmSpice(SCLEX_SPICE, ColouriseDocument, "spice", NULL, spiceWordListDesc);

/*
 * Implementation
 */

static void ColouriseComment(StyleContext& sc, bool& apostropheStartsAttribute);
static void ColouriseDelimiter(StyleContext& sc, bool& apostropheStartsAttribute);
static void ColouriseNumber(StyleContext& sc, bool& apostropheStartsAttribute);
static void ColouriseWhiteSpace(StyleContext& sc, bool& apostropheStartsAttribute);
static void ColouriseWord(StyleContext& sc, WordList& keywords, WordList& keywords2, WordList& keywords3, bool& apostropheStartsAttribute);

static inline bool IsDelimiterCharacter(int ch);
static inline bool IsNumberStartCharacter(int ch);
static inline bool IsNumberCharacter(int ch);
static inline bool IsSeparatorOrDelimiterCharacter(int ch);
static inline bool IsWordStartCharacter(int ch);
static inline bool IsWordCharacter(int ch);

static void ColouriseComment(StyleContext& sc, bool&) {
    sc.SetState(SCE_SPICE_COMMENTLINE);
    while (!sc.atLineEnd) {
        sc.Forward();
    }
}

static void ColouriseDelimiter(StyleContext& sc, bool& apostropheStartsAttribute) {
    apostropheStartsAttribute = sc.Match (')');
    sc.SetState(SCE_SPICE_DELIMITER);
    sc.ForwardSetState(SCE_SPICE_DEFAULT);
}

static void ColouriseNumber(StyleContext& sc, bool& apostropheStartsAttribute) {
    apostropheStartsAttribute = true;
    SString number;
    sc.SetState(SCE_SPICE_NUMBER);
    // Get all characters up to a delimiter or a separator, including points, but excluding
    // double points (ranges).
    while (!IsSeparatorOrDelimiterCharacter(sc.ch) || (sc.ch == '.' && sc.chNext != '.')) {
        number += static_cast<char>(sc.ch);
        sc.Forward();
    }
    // Special case: exponent with sign
    if ((sc.chPrev == 'e' || sc.chPrev == 'E') &&
            (sc.ch == '+' || sc.ch == '-')) {
        number += static_cast<char>(sc.ch);
        sc.Forward ();
        while (!IsSeparatorOrDelimiterCharacter(sc.ch)) {
            number += static_cast<char>(sc.ch);
            sc.Forward();
        }
    }
    sc.SetState(SCE_SPICE_DEFAULT);
}

static void ColouriseWhiteSpace(StyleContext& sc, bool& ) {
    sc.SetState(SCE_SPICE_DEFAULT);
    sc.ForwardSetState(SCE_SPICE_DEFAULT);
}

static void ColouriseWord(StyleContext& sc, WordList& keywords, WordList& keywords2, WordList& keywords3, bool& apostropheStartsAttribute) {
    apostropheStartsAttribute = true;
    sc.SetState(SCE_SPICE_IDENTIFIER);
    SString word;
    while (!sc.atLineEnd && !IsSeparatorOrDelimiterCharacter(sc.ch)) {
        word += static_cast<char>(tolower(sc.ch));
        sc.Forward();
    }
    if (keywords.InList(word.c_str())) {
        sc.ChangeState(SCE_SPICE_KEYWORD);
        if (word != "all") {
            apostropheStartsAttribute = false;
        }
    }
    else if (keywords2.InList(word.c_str())) {
        sc.ChangeState(SCE_SPICE_KEYWORD2);
        if (word != "all") {
            apostropheStartsAttribute = false;
        }
    }
    else if (keywords3.InList(word.c_str())) {
        sc.ChangeState(SCE_SPICE_KEYWORD3);
        if (word != "all") {
            apostropheStartsAttribute = false;
        }
    }
    sc.SetState(SCE_SPICE_DEFAULT);
}

//
// ColouriseDocument
//
static void ColouriseDocument(
    unsigned int startPos,
    int length,
    int initStyle,
    WordList *keywordlists[],
    Accessor &styler) {
    WordList &keywords = *keywordlists[0];
    WordList &keywords2 = *keywordlists[1];
    WordList &keywords3 = *keywordlists[2];
    StyleContext sc(startPos, length, initStyle, styler);
    int lineCurrent = styler.GetLine(startPos);
    bool apostropheStartsAttribute = (styler.GetLineState(lineCurrent) & 1) != 0;
    while (sc.More()) {
        if (sc.atLineEnd) {
            // Go to the next line
            sc.Forward();
            lineCurrent++;
            // Remember the line state for future incremental lexing
            styler.SetLineState(lineCurrent, apostropheStartsAttribute);
            // Don't continue any styles on the next line
            sc.SetState(SCE_SPICE_DEFAULT);
        }
        // Comments
        if ((sc.Match('*') && sc.atLineStart) || sc.Match('*','~')) {
            ColouriseComment(sc, apostropheStartsAttribute);
        // Whitespace
        } else if (IsASpace(sc.ch)) {
            ColouriseWhiteSpace(sc, apostropheStartsAttribute);
        // Delimiters
        } else if (IsDelimiterCharacter(sc.ch)) {
            ColouriseDelimiter(sc, apostropheStartsAttribute);
        // Numbers
        } else if (IsADigit(sc.ch) || sc.ch == '#') {
            ColouriseNumber(sc, apostropheStartsAttribute);
        // Keywords or identifiers
        } else {
            ColouriseWord(sc, keywords, keywords2, keywords3, apostropheStartsAttribute);
        }
    }
    sc.Complete();
}

static inline bool IsDelimiterCharacter(int ch) {
    switch (ch) {
    case '&':
    case '\'':
    case '(':
    case ')':
    case '*':
    case '+':
    case ',':
    case '-':
    case '.':
    case '/':
    case ':':
    case ';':
    case '<':
    case '=':
    case '>':
    case '|':
        return true;
    default:
        return false;
    }
}

static inline bool IsNumberCharacter(int ch) {
    return IsNumberStartCharacter(ch) ||
           ch == '_' ||
           ch == '.' ||
           ch == '#' ||
           (ch >= 'a' && ch <= 'f') ||
           (ch >= 'A' && ch <= 'F');
}

static inline bool IsNumberStartCharacter(int ch) {
    return IsADigit(ch);
}

static inline bool IsSeparatorOrDelimiterCharacter(int ch) {
    return IsASpace(ch) || IsDelimiterCharacter(ch);
}

static inline bool IsWordCharacter(int ch) {
    return IsWordStartCharacter(ch) || IsADigit(ch);
}

static inline bool IsWordStartCharacter(int ch) {
    return (isascii(ch) && isalpha(ch)) || ch == '_';
}
<|endoftext|>


<commit_before>#include "LuaCpp/LuaException.hpp"
#include "LuaCpp/LuaTable.hpp"

namespace luacpp
{
	LuaTable LuaTable::create(lua_State* state)
	{
		LuaTable table;

		lua_newtable(state);

		table.setReference(LuaReference::create(state));

		lua_pop(state, 1);

		return table;
	}

	LuaTable::LuaTable() : LuaValue()
	{
	}

	LuaTable::LuaTable(const LuaTable& other) : LuaValue(other)
	{
	}

	LuaTable::~LuaTable()
	{
	}

	bool LuaTable::setMetatable(const LuaTable& table)
	{
		if (!table.getReference()->isValid())
		{
			throw LuaException("Meta table reference is not valid!");
		}

		this->pushValue();
		table.pushValue();

		lua_setmetatable(luaState, -2);

		lua_pop(luaState, 1);

		return true;
	}

	void LuaTable::setReference(luacpp::LuaReferencePtr reference)
	{
		reference->pushValue();

		lua_State* L = reference->getState();

		if (lua_type(L, -1) != LUA_TTABLE)
		{
			lua_pop(L, 1);
			throw LuaException("Reference does not refere to a table!");
		}
		else
		{
			lua_pop(L, 1);
			LuaValue::setReference(reference);
		}
	}

	size_t LuaTable::getLength()
	{
		this->pushValue();

		size_t length = lua_objlen(luaState, -1);

		lua_pop(luaState, 1);

		return length;
	}

	LuaTableIterator LuaTable::iterator()
	{
		this->pushValue();

		return LuaTableIterator(this);
	}

	LuaTableIterator::LuaTableIterator(LuaTable* parent) : parent(parent)
	{
		// Prepare the iteration
		lua_pushnil(parent->luaState);
	}

	bool LuaTableIterator::toNext()
	{
		return lua_next(parent->luaState, -2) != 0;
	}
}<commit_msg>Clean up the stack when we are done iterating<commit_after>#include "LuaCpp/LuaException.hpp"
#include "LuaCpp/LuaTable.hpp"

namespace luacpp
{
	LuaTable LuaTable::create(lua_State* state)
	{
		LuaTable table;

		lua_newtable(state);

		table.setReference(LuaReference::create(state));

		lua_pop(state, 1);

		return table;
	}

	LuaTable::LuaTable() : LuaValue()
	{
	}

	LuaTable::LuaTable(const LuaTable& other) : LuaValue(other)
	{
	}

	LuaTable::~LuaTable()
	{
	}

	bool LuaTable::setMetatable(const LuaTable& table)
	{
		if (!table.getReference()->isValid())
		{
			throw LuaException("Meta table reference is not valid!");
		}

		this->pushValue();
		table.pushValue();

		lua_setmetatable(luaState, -2);

		lua_pop(luaState, 1);

		return true;
	}

	void LuaTable::setReference(luacpp::LuaReferencePtr reference)
	{
		reference->pushValue();

		lua_State* L = reference->getState();

		if (lua_type(L, -1) != LUA_TTABLE)
		{
			lua_pop(L, 1);
			throw LuaException("Reference does not refere to a table!");
		}
		else
		{
			lua_pop(L, 1);
			LuaValue::setReference(reference);
		}
	}

	size_t LuaTable::getLength()
	{
		this->pushValue();

		size_t length = lua_objlen(luaState, -1);

		lua_pop(luaState, 1);

		return length;
	}

	LuaTableIterator LuaTable::iterator()
	{
		this->pushValue();

		return LuaTableIterator(this);
	}

	LuaTableIterator::LuaTableIterator(LuaTable* parent) : parent(parent)
	{
		// Prepare the iteration
		lua_pushnil(parent->luaState);
	}

	bool LuaTableIterator::toNext()
	{
		if (lua_next(parent->luaState, -2) == 0)
		{
			// Pop the table we are iterating
			lua_pop(parent->luaState, 1);
			return false;
		}
		else
		{
			return true;
		}
	}
}<|endoftext|>


<commit_before>/*! \file MatTools.cpp
    \brief Implements the MatTools class used by the Generic Repository
    \author Kathryn D. Huff
 */
#include <iostream>
#include <fstream>
#include <deque>
#include <time.h>
#include <assert.h>

#include "CycException.h"
#include "CycLimits.h"
#include "MatTools.h"
#include "Material.h"
#include "Logger.h"
#include "Timer.h"

using namespace std;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pair<IsoVector, double> MatTools::sum_mats(deque<mat_rsrc_ptr> mats){
  IsoVector vec;
  CompMapPtr sum_comp = CompMapPtr(new CompMap(MASS));
  double tot = 0;
  double kg = 0;
  map<Iso, vector<double> > to_sum;
  vector<double> tot_vec;

  if( !mats.empty() ){
    CompMapPtr comp_to_add;
    deque<mat_rsrc_ptr>::iterator mat;
    int iso;
    CompMap::const_iterator comp;
    for(mat = mats.begin(); mat != mats.end(); ++mat){
      comp_to_add = (*mat)->unnormalizeComp(MASS, KG);
      for(comp = (*comp_to_add).begin(); comp != (*comp_to_add).end(); ++comp) {
        iso = comp->first;
        if(to_sum.find(iso)==to_sum.end()) {
          to_sum.insert(make_pair(iso, vector<double>()));
        }
        to_sum[iso].push_back(comp->second);
      }
    }
    map<Iso, vector<double> >::const_iterator it;
    for(it=to_sum.begin(); it!=to_sum.end(); ++it) {
      (*sum_comp)[(*it).first] = KahanSum((*it).second);
      tot_vec.push_back((*sum_comp)[iso]);
    }
    tot = KahanSum(tot_vec);
  } else {
    (*sum_comp)[92235] = 0;
  }
  vec = IsoVector(sum_comp);
  return make_pair(vec, tot);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::KahanSum(vector<double> input){
  // http://en.wikipedia.org/wiki/Kahan_summation_algorithm
  double y, t;
  double sum = 0.0;
  //A running compensation for lost low-order bits.
  double c = 0.0;
  for(vector<double>::iterator i = input.begin(); i!=input.end(); ++i){
    y = *i - c;
    //So far, so good: c is zero.
    t = sum + y;
    //Alas, sum is big, y small, so low-order digits of y are lost.
    c = (t - sum) - y;
    //(t - sum) recovers the high-order part of y; subtracting y recovers -(low part of y)
    sum = t;
    //Algebraically, c should always be zero. Beware eagerly optimising compilers!
    //Next time around, the lost low part will be added to y in a fresh attempt.
  }
  return sum;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
mat_rsrc_ptr MatTools::extract(const CompMapPtr comp_to_rem, double kg_to_rem,
    deque<mat_rsrc_ptr>& mat_list, double threshold){
  comp_to_rem->massify();
  mat_rsrc_ptr left_over = mat_rsrc_ptr(new Material(comp_to_rem));
  left_over->setQuantity(0);
  // absorb them together.
  while(!mat_list.empty()) {
    left_over->absorb(mat_list.back());
    mat_list.pop_back();
  }
  mat_rsrc_ptr to_ret;
  if( left_over->mass(KG) >= threshold ) {
    to_ret = left_over->extract(comp_to_rem, kg_to_rem, KG, threshold);
    mat_list.push_back(left_over);
  } else {
    to_ret = mat_rsrc_ptr(left_over);
  }
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoConcMap MatTools::comp_to_conc_map(CompMapPtr comp, double mass, double vol){
  MatTools::validate_finite_pos(vol);
  MatTools::validate_finite_pos(mass);
  comp->massify();

  IsoConcMap to_ret;
  if( vol==0 ) {
    to_ret = zeroConcMap();
  } else {
    int iso;
    double m_iso;
    CompMap::const_iterator it;
    it=(*comp).begin();
    while(it!= (*comp).end() ){
      iso = (*it).first;
      m_iso=((*it).second)*mass;
      to_ret.insert(make_pair(iso, m_iso/vol));
      ++it;
    }
  }
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoConcMap MatTools::zeroConcMap(){
  IsoConcMap to_ret;
  to_ret[92235] = 0;
  return to_ret;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pair<CompMapPtr, double> MatTools::conc_to_comp_map(IsoConcMap conc, double vol){
  MatTools::validate_finite_pos(vol);

  CompMapPtr comp = CompMapPtr(new CompMap(MASS));
  double mass(0);
  int iso;
  double c_iso;
  double m_iso;
  CompMap::const_iterator it;
  it=conc.begin();
  while(it!= conc.end() ){
    iso = (*it).first;
    c_iso=((*it).second);
    m_iso = c_iso*vol;
    (*comp)[iso] = m_iso;
    mass+=m_iso;
    ++it;
  }
  (*comp).normalize();
  pair<CompMapPtr, double> to_ret = make_pair(CompMapPtr(comp), mass);
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_f(double V_T, double theta){
  validate_percent(theta);
  validate_finite_pos(V_T);
  return theta*V_T;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_ff(double V_T, double theta, double d){
  validate_percent(d);
  return d*V_f(V_T, theta);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_mf(double V_T, double theta, double d){
  return (V_f(V_T,theta) - V_ff(V_T, theta, d));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_s(double V_T, double theta){
  return (V_T - V_f(V_T, theta));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_ds(double V_T, double theta, double d){
  validate_percent(d);
  return d*V_s(V_T, theta);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_ms(double V_T, double theta, double d){
  return (V_s(V_T, theta) - V_ds(V_T, theta, d));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void MatTools::validate_percent(double per){
  if( per <= 1 && per >= 0 ){
    return;
  } else if ( per < 0) {
    throw CycRangeException("The value is not a valid percent. It is less than zero.");
  } else if ( per > 1) {
    throw CycRangeException("The value is not a valid percent. It is greater than one.");
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void MatTools::validate_finite_pos(double pos){
  if ( pos >= numeric_limits<double>::infinity() ) {
    throw CycRangeException("The value is not positive and finite. It is infinite.");
  }
  validate_pos(pos);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void MatTools::validate_pos(double pos){
  if ( pos < 0) {
    std::stringstream ss;
    ss << "The value "
       << pos
       << " is not positive and finite. It is less than zero." ;;
    throw CycRangeException(ss.str());
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void MatTools::validate_nonzero(double nonzero){
  if ( nonzero == 0 )
    throw CycRangeException("The value is zero.");
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoConcMap MatTools::scaleConcMap(IsoConcMap C_0, double scalar){
  MatTools::validate_finite_pos(scalar);
  double orig;
  IsoConcMap::const_iterator it;
  for(it = C_0.begin(); it != C_0.end(); ++it) {
    orig = C_0[(*it).first];
    C_0[(*it).first] = orig*scalar;
  }
  return C_0;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoConcMap MatTools::addConcMaps(IsoConcMap orig, IsoConcMap to_add){
  IsoConcMap to_ret;
  IsoConcMap::const_iterator it;
  for(it = orig.begin(); it != orig.end(); ++it) {
    Iso iso=(*it).first;
    if(to_add.find(iso) != to_add.end()) {
      to_ret[iso] = (*it).second + to_add[iso];
    } else {
      to_ret[iso] = (*it).second;
    }
  }
  for(it = to_add.begin(); it != to_add.end(); ++it) {
    Iso iso=(*it).first;
    if(orig.find(iso) == orig.end()) {
      to_ret[iso] = (*it).second;
    }
  }
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pair<CompMapPtr, double> MatTools::subtractCompMaps(pair<CompMapPtr, double> orig_pair, pair<CompMapPtr, double> to_subtract_pair){
  CompMapPtr orig = CompMapPtr(orig_pair.first);
  double o_kg = orig_pair.second;
  CompMapPtr to_subtract = CompMapPtr(to_subtract_pair.first);
  double s_kg = to_subtract_pair.second;
  CompMapPtr to_ret = CompMapPtr(new CompMap(MASS));
  double to_ret_kg = 0;

  CompMap::const_iterator it;
  for(it = (*orig).begin(); it != (*orig).end(); ++it) {
    Iso iso=(*it).first;
    if(to_subtract->map().find(iso) != to_subtract->map().end()) {
      (*to_ret)[iso] = (*it).second*o_kg - (*to_subtract)[iso]*s_kg;
    } else {
      (*to_ret)[iso] = (*it).second*o_kg;
    }
    to_ret_kg += (*to_ret)[iso];
  }
  for(it = (*to_subtract).begin(); it != (*to_subtract).end(); ++it) {
    Iso iso=(*it).first;
    if(orig->map().find(iso) == orig->map().end()) {
      std::stringstream msg_ss;
      msg_ss << "Cannot subtract a superset of isotopes from a subset";
      LOG(LEV_ERROR, "GRDRNuc") <<msg_ss.str();;
      throw CycNegativeValueException(msg_ss.str());
    }
  }
  return make_pair(CompMapPtr(to_ret), to_ret_kg);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int MatTools::isoToElem(int iso) {
  int N = iso % 1000;
  return (iso-N)/1000;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
vector<double> MatTools::linspace(double a, double b, int n) {
  vector<double> array(0);  // optional preallocation
  double step = (b-a)/(n-1);
  while(a <= b) {
    array.push_back(a);
    a += step;           // could recode to better handle rounding errors
  }
  return array;
}

<commit_msg>iso had no meaning where I was using it. better now.<commit_after>/*! \file MatTools.cpp
    \brief Implements the MatTools class used by the Generic Repository
    \author Kathryn D. Huff
 */
#include <iostream>
#include <fstream>
#include <deque>
#include <time.h>
#include <assert.h>

#include "CycException.h"
#include "CycLimits.h"
#include "MatTools.h"
#include "Material.h"
#include "Logger.h"
#include "Timer.h"

using namespace std;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pair<IsoVector, double> MatTools::sum_mats(deque<mat_rsrc_ptr> mats){
  IsoVector vec;
  CompMapPtr sum_comp = CompMapPtr(new CompMap(MASS));
  double tot = 0;
  double kg = 0;
  map<Iso, vector<double> > to_sum;
  vector<double> tot_vec;

  if( !mats.empty() ){
    CompMapPtr comp_to_add;
    deque<mat_rsrc_ptr>::iterator mat;
    int iso;
    CompMap::const_iterator comp;
    for(mat = mats.begin(); mat != mats.end(); ++mat){
      comp_to_add = (*mat)->unnormalizeComp(MASS, KG);
      for(comp = (*comp_to_add).begin(); comp != (*comp_to_add).end(); ++comp) {
        iso = comp->first;
        if(to_sum.find(iso)==to_sum.end()) {
          to_sum.insert(make_pair(iso, vector<double>()));
        }
        to_sum[iso].push_back(comp->second);
      }
    }
    map<Iso, vector<double> >::const_iterator it;
    for(it=to_sum.begin(); it!=to_sum.end(); ++it) {
      iso = (*it).first;
      (*sum_comp)[iso] = KahanSum((*it).second);
      tot_vec.push_back((*sum_comp)[iso]);
    }
    tot = KahanSum(tot_vec);
  } else {
    (*sum_comp)[92235] = 0;
  }
  vec = IsoVector(sum_comp);
  return make_pair(vec, tot);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::KahanSum(vector<double> input){
  // http://en.wikipedia.org/wiki/Kahan_summation_algorithm
  double y, t;
  double sum = 0.0;
  //A running compensation for lost low-order bits.
  double c = 0.0;
  for(vector<double>::iterator i = input.begin(); i!=input.end(); ++i){
    y = *i - c;
    //So far, so good: c is zero.
    t = sum + y;
    //Alas, sum is big, y small, so low-order digits of y are lost.
    c = (t - sum) - y;
    //(t - sum) recovers the high-order part of y; subtracting y recovers -(low part of y)
    sum = t;
    //Algebraically, c should always be zero. Beware eagerly optimising compilers!
    //Next time around, the lost low part will be added to y in a fresh attempt.
  }
  return sum;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
mat_rsrc_ptr MatTools::extract(const CompMapPtr comp_to_rem, double kg_to_rem,
    deque<mat_rsrc_ptr>& mat_list, double threshold){
  comp_to_rem->massify();
  mat_rsrc_ptr left_over = mat_rsrc_ptr(new Material(comp_to_rem));
  left_over->setQuantity(0);
  // absorb them together.
  while(!mat_list.empty()) {
    left_over->absorb(mat_list.back());
    mat_list.pop_back();
  }
  mat_rsrc_ptr to_ret;
  if( left_over->mass(KG) >= threshold ) {
    to_ret = left_over->extract(comp_to_rem, kg_to_rem, KG, threshold);
    mat_list.push_back(left_over);
  } else {
    to_ret = mat_rsrc_ptr(left_over);
  }
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoConcMap MatTools::comp_to_conc_map(CompMapPtr comp, double mass, double vol){
  MatTools::validate_finite_pos(vol);
  MatTools::validate_finite_pos(mass);
  comp->massify();

  IsoConcMap to_ret;
  if( vol==0 ) {
    to_ret = zeroConcMap();
  } else {
    int iso;
    double m_iso;
    CompMap::const_iterator it;
    it=(*comp).begin();
    while(it!= (*comp).end() ){
      iso = (*it).first;
      m_iso=((*it).second)*mass;
      to_ret.insert(make_pair(iso, m_iso/vol));
      ++it;
    }
  }
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoConcMap MatTools::zeroConcMap(){
  IsoConcMap to_ret;
  to_ret[92235] = 0;
  return to_ret;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pair<CompMapPtr, double> MatTools::conc_to_comp_map(IsoConcMap conc, double vol){
  MatTools::validate_finite_pos(vol);

  CompMapPtr comp = CompMapPtr(new CompMap(MASS));
  double mass(0);
  int iso;
  double c_iso;
  double m_iso;
  CompMap::const_iterator it;
  it=conc.begin();
  while(it!= conc.end() ){
    iso = (*it).first;
    c_iso=((*it).second);
    m_iso = c_iso*vol;
    (*comp)[iso] = m_iso;
    mass+=m_iso;
    ++it;
  }
  (*comp).normalize();
  pair<CompMapPtr, double> to_ret = make_pair(CompMapPtr(comp), mass);
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_f(double V_T, double theta){
  validate_percent(theta);
  validate_finite_pos(V_T);
  return theta*V_T;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_ff(double V_T, double theta, double d){
  validate_percent(d);
  return d*V_f(V_T, theta);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_mf(double V_T, double theta, double d){
  return (V_f(V_T,theta) - V_ff(V_T, theta, d));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_s(double V_T, double theta){
  return (V_T - V_f(V_T, theta));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_ds(double V_T, double theta, double d){
  validate_percent(d);
  return d*V_s(V_T, theta);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_ms(double V_T, double theta, double d){
  return (V_s(V_T, theta) - V_ds(V_T, theta, d));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void MatTools::validate_percent(double per){
  if( per <= 1 && per >= 0 ){
    return;
  } else if ( per < 0) {
    throw CycRangeException("The value is not a valid percent. It is less than zero.");
  } else if ( per > 1) {
    throw CycRangeException("The value is not a valid percent. It is greater than one.");
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void MatTools::validate_finite_pos(double pos){
  if ( pos >= numeric_limits<double>::infinity() ) {
    throw CycRangeException("The value is not positive and finite. It is infinite.");
  }
  validate_pos(pos);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void MatTools::validate_pos(double pos){
  if ( pos < 0) {
    std::stringstream ss;
    ss << "The value "
       << pos
       << " is not positive and finite. It is less than zero." ;;
    throw CycRangeException(ss.str());
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void MatTools::validate_nonzero(double nonzero){
  if ( nonzero == 0 )
    throw CycRangeException("The value is zero.");
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoConcMap MatTools::scaleConcMap(IsoConcMap C_0, double scalar){
  MatTools::validate_finite_pos(scalar);
  double orig;
  IsoConcMap::const_iterator it;
  for(it = C_0.begin(); it != C_0.end(); ++it) {
    orig = C_0[(*it).first];
    C_0[(*it).first] = orig*scalar;
  }
  return C_0;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoConcMap MatTools::addConcMaps(IsoConcMap orig, IsoConcMap to_add){
  IsoConcMap to_ret;
  IsoConcMap::const_iterator it;
  for(it = orig.begin(); it != orig.end(); ++it) {
    Iso iso=(*it).first;
    if(to_add.find(iso) != to_add.end()) {
      to_ret[iso] = (*it).second + to_add[iso];
    } else {
      to_ret[iso] = (*it).second;
    }
  }
  for(it = to_add.begin(); it != to_add.end(); ++it) {
    Iso iso=(*it).first;
    if(orig.find(iso) == orig.end()) {
      to_ret[iso] = (*it).second;
    }
  }
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pair<CompMapPtr, double> MatTools::subtractCompMaps(pair<CompMapPtr, double> orig_pair, pair<CompMapPtr, double> to_subtract_pair){
  CompMapPtr orig = CompMapPtr(orig_pair.first);
  double o_kg = orig_pair.second;
  CompMapPtr to_subtract = CompMapPtr(to_subtract_pair.first);
  double s_kg = to_subtract_pair.second;
  CompMapPtr to_ret = CompMapPtr(new CompMap(MASS));
  double to_ret_kg = 0;

  CompMap::const_iterator it;
  for(it = (*orig).begin(); it != (*orig).end(); ++it) {
    Iso iso=(*it).first;
    if(to_subtract->map().find(iso) != to_subtract->map().end()) {
      (*to_ret)[iso] = (*it).second*o_kg - (*to_subtract)[iso]*s_kg;
    } else {
      (*to_ret)[iso] = (*it).second*o_kg;
    }
    to_ret_kg += (*to_ret)[iso];
  }
  for(it = (*to_subtract).begin(); it != (*to_subtract).end(); ++it) {
    Iso iso=(*it).first;
    if(orig->map().find(iso) == orig->map().end()) {
      std::stringstream msg_ss;
      msg_ss << "Cannot subtract a superset of isotopes from a subset";
      LOG(LEV_ERROR, "GRDRNuc") <<msg_ss.str();;
      throw CycNegativeValueException(msg_ss.str());
    }
  }
  return make_pair(CompMapPtr(to_ret), to_ret_kg);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
int MatTools::isoToElem(int iso) {
  int N = iso % 1000;
  return (iso-N)/1000;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
vector<double> MatTools::linspace(double a, double b, int n) {
  vector<double> array(0);  // optional preallocation
  double step = (b-a)/(n-1);
  while(a <= b) {
    array.push_back(a);
    a += step;           // could recode to better handle rounding errors
  }
  return array;
}

<|endoftext|>


<commit_before>/*! \file MatTools.cpp
    \brief Implements the MatTools class used by the Generic Repository
    \author Kathryn D. Huff
 */
#include <iostream>
#include <fstream>
#include <deque>
#include <time.h>
#include <assert.h>

#include "CycException.h"
#include "Logger.h"
#include "Timer.h"
#include "MatTools.h"
#include "Material.h"

using namespace std;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pair<IsoVector, double> MatTools::sum_mats(deque<mat_rsrc_ptr> mats){
  IsoVector vec;
  CompMapPtr sum_comp = CompMapPtr(new CompMap(MASS));
  double kg = 0;

  if( !mats.empty() ){
    CompMapPtr comp_to_add;
    deque<mat_rsrc_ptr>::iterator mat;
    int iso;
    CompMap::const_iterator comp;

    for(mat = mats.begin(); mat != mats.end(); ++mat){
      kg += (*mat)->mass(MassUnit(KG));
      comp_to_add = (*mat)->isoVector().comp();
      comp_to_add->massify();
      for(comp = (*comp_to_add).begin(); comp != (*comp_to_add).end(); ++comp) {
        iso = comp->first;
        if(sum_comp->count(iso)!=0) {
          (*sum_comp)[iso] = (*sum_comp)[iso] + (comp->second)*kg;
        } else {
          (*sum_comp)[iso] = (comp->second)*kg;
        }
      }
    }
  } else {
    (*sum_comp)[92235] = 0;
  }
  vec = IsoVector(sum_comp);
  return make_pair(vec, kg);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
mat_rsrc_ptr MatTools::extract(const CompMapPtr comp_to_rem, double kg_to_rem, deque<mat_rsrc_ptr>& mat_list){
  mat_rsrc_ptr left_over = mat_rsrc_ptr(new Material(comp_to_rem));
  left_over->setQuantity(0);
  while(!mat_list.empty()) {
    left_over->absorb(mat_list.back());
    mat_list.pop_back();
  }
  mat_rsrc_ptr to_ret = left_over->extract(comp_to_rem, kg_to_rem);
  mat_list.push_back(left_over);
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoConcMap MatTools::comp_to_conc_map(CompMapPtr comp, double mass, double vol){
  MatTools::validate_finite_pos(vol);
  MatTools::validate_finite_pos(mass);

  IsoConcMap to_ret;
  int iso;
  double m_iso;
  CompMap::const_iterator it;
  it=(*comp).begin();
  while(it!= (*comp).end() ){
    iso = (*it).first;
    m_iso=((*it).second)*mass;
    to_ret.insert(make_pair(iso, m_iso/vol));
    ++it;
  }
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pair<CompMapPtr, double> MatTools::conc_to_comp_map(IsoConcMap conc, double vol){
  MatTools::validate_finite_pos(vol);

  CompMapPtr comp = CompMapPtr(new CompMap(MASS));
  double mass;
  int iso;
  double c_iso;
  double m_iso;
  CompMap::const_iterator it;
  it=conc.begin();
  while(it!= conc.end() ){
    iso = (*it).first;
    c_iso=((*it).second);
    m_iso = c_iso*vol;
    (*comp)[iso] = m_iso;
    mass+=m_iso;
    ++it;
  }
  (*comp).normalize();
  pair<CompMapPtr, double> to_ret = make_pair(comp, mass);
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_f(double V_T, double theta){
  validate_percent(theta);
  validate_finite_pos(V_T);
  return theta*V_T;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_ff(double V_T, double theta, double d){
  validate_percent(d);
  return d*V_f(V_T, theta);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_mf(double V_T, double theta, double d){
  return (V_f(V_T,theta) - V_ff(V_T, theta, d));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_s(double V_T, double theta){
  return (V_T - V_f(V_T, theta));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_ds(double V_T, double theta, double d){
  validate_percent(d);
  return d*V_s(V_T, theta);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_ms(double V_T, double theta, double d){
  return (V_s(V_T, theta) - V_ds(V_T, theta, d));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void MatTools::validate_percent(double per){
  if( per <= 1 && per >= 0 ){
    return;
  } else if ( per < 0) {
    throw CycRangeException("The value is not a valid percent. It is less than zero.");
  } else if ( per > 1) {
    throw CycRangeException("The value is not a valid percent. It is greater than one.");
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void MatTools::validate_finite_pos(double pos){
  if( pos >= 0 ){
    return;
  } else if ( pos < 0) {
    throw CycRangeException("The value is not positive and finite. It is less than zero.");
  } else if ( pos >= numeric_limits<double>::infinity() ) {
    throw CycRangeException("The value is not positive and finite. It is greater than infty.");
  }

}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoConcMap MatTools::scaleConcMap(IsoConcMap C_0, double scalar){
  double orig;
  IsoConcMap::iterator it;
  for(it = C_0.begin(); it != C_0.end(); ++it) {
    orig = C_0[(*it).first];
    C_0[(*it).first] = orig*scalar;
  }
  return C_0;
}
<commit_msg>uninitialized variable<commit_after>/*! \file MatTools.cpp
    \brief Implements the MatTools class used by the Generic Repository
    \author Kathryn D. Huff
 */
#include <iostream>
#include <fstream>
#include <deque>
#include <time.h>
#include <assert.h>

#include "CycException.h"
#include "Logger.h"
#include "Timer.h"
#include "MatTools.h"
#include "Material.h"

using namespace std;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pair<IsoVector, double> MatTools::sum_mats(deque<mat_rsrc_ptr> mats){
  IsoVector vec;
  CompMapPtr sum_comp = CompMapPtr(new CompMap(MASS));
  double kg = 0;

  if( !mats.empty() ){
    CompMapPtr comp_to_add;
    deque<mat_rsrc_ptr>::iterator mat;
    int iso;
    CompMap::const_iterator comp;

    for(mat = mats.begin(); mat != mats.end(); ++mat){
      kg += (*mat)->mass(MassUnit(KG));
      comp_to_add = (*mat)->isoVector().comp();
      comp_to_add->massify();
      for(comp = (*comp_to_add).begin(); comp != (*comp_to_add).end(); ++comp) {
        iso = comp->first;
        if(sum_comp->count(iso)!=0) {
          (*sum_comp)[iso] = (*sum_comp)[iso] + (comp->second)*kg;
        } else {
          (*sum_comp)[iso] = (comp->second)*kg;
        }
      }
    }
  } else {
    (*sum_comp)[92235] = 0;
  }
  vec = IsoVector(sum_comp);
  return make_pair(vec, kg);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
mat_rsrc_ptr MatTools::extract(const CompMapPtr comp_to_rem, double kg_to_rem, deque<mat_rsrc_ptr>& mat_list){
  mat_rsrc_ptr left_over = mat_rsrc_ptr(new Material(comp_to_rem));
  left_over->setQuantity(0);
  while(!mat_list.empty()) {
    left_over->absorb(mat_list.back());
    mat_list.pop_back();
  }
  mat_rsrc_ptr to_ret = left_over->extract(comp_to_rem, kg_to_rem);
  mat_list.push_back(left_over);
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoConcMap MatTools::comp_to_conc_map(CompMapPtr comp, double mass, double vol){
  MatTools::validate_finite_pos(vol);
  MatTools::validate_finite_pos(mass);

  IsoConcMap to_ret;
  int iso;
  double m_iso;
  CompMap::const_iterator it;
  it=(*comp).begin();
  while(it!= (*comp).end() ){
    iso = (*it).first;
    m_iso=((*it).second)*mass;
    to_ret.insert(make_pair(iso, m_iso/vol));
    ++it;
  }
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
pair<CompMapPtr, double> MatTools::conc_to_comp_map(IsoConcMap conc, double vol){
  MatTools::validate_finite_pos(vol);

  CompMapPtr comp = CompMapPtr(new CompMap(MASS));
  double mass(0);
  int iso;
  double c_iso;
  double m_iso;
  CompMap::const_iterator it;
  it=conc.begin();
  while(it!= conc.end() ){
    iso = (*it).first;
    c_iso=((*it).second);
    m_iso = c_iso*vol;
    (*comp)[iso] = m_iso;
    mass+=m_iso;
    ++it;
  }
  (*comp).normalize();
  pair<CompMapPtr, double> to_ret = make_pair(comp, mass);
  return to_ret;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_f(double V_T, double theta){
  validate_percent(theta);
  validate_finite_pos(V_T);
  return theta*V_T;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_ff(double V_T, double theta, double d){
  validate_percent(d);
  return d*V_f(V_T, theta);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_mf(double V_T, double theta, double d){
  return (V_f(V_T,theta) - V_ff(V_T, theta, d));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_s(double V_T, double theta){
  return (V_T - V_f(V_T, theta));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_ds(double V_T, double theta, double d){
  validate_percent(d);
  return d*V_s(V_T, theta);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
double MatTools::V_ms(double V_T, double theta, double d){
  return (V_s(V_T, theta) - V_ds(V_T, theta, d));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void MatTools::validate_percent(double per){
  if( per <= 1 && per >= 0 ){
    return;
  } else if ( per < 0) {
    throw CycRangeException("The value is not a valid percent. It is less than zero.");
  } else if ( per > 1) {
    throw CycRangeException("The value is not a valid percent. It is greater than one.");
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void MatTools::validate_finite_pos(double pos){
  if( pos >= 0 ){
    return;
  } else if ( pos < 0) {
    throw CycRangeException("The value is not positive and finite. It is less than zero.");
  } else if ( pos >= numeric_limits<double>::infinity() ) {
    throw CycRangeException("The value is not positive and finite. It is greater than infty.");
  }

}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IsoConcMap MatTools::scaleConcMap(IsoConcMap C_0, double scalar){
  double orig;
  IsoConcMap::iterator it;
  for(it = C_0.begin(); it != C_0.end(); ++it) {
    orig = C_0[(*it).first];
    C_0[(*it).first] = orig*scalar;
  }
  return C_0;
}
<|endoftext|>


<commit_before>#include "Material.h"
#include "Filesystem.h"
#include "kit/log/log.h"
#include <boost/filesystem.hpp>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
using namespace std;
namespace fs = boost::filesystem;

const std::vector<std::string> Material :: s_ExtraMapNames = {
    "NRM",
    "DISP",
    "SPEC",
    "OCC"
};

Material :: Material(
    const std::string& fn,
    Cache<Resource, std::string>* cache
):
    m_Filename(fn),
    m_pCache(cache)
{
    string fn_real = Filesystem::cutInternal(fn);
    string ext = Filesystem::getExtension(fn_real);
    string cut = Filesystem::cutExtension(fn_real);
    string emb = Filesystem::getInternal(fn);
    if(ext == "mtl")
        load_mtllib(fn_real, emb);
    else if(ext == "json")
        load_json(fn);
    else {
        static unsigned class_id = cache->class_id("texture");
        m_Textures.push_back(make_shared<Texture>(
            tuple<string, ICache*>(fn, cache)
        ));
        for(auto&& t: s_ExtraMapNames) {
            auto tfn = cut + "_" + t + "." + ext;
            tfn = cache->transform(tfn);
            if(fs::exists(
                fs::path(tfn)
            )){
                m_Textures.push_back(make_shared<Texture>(
                    tuple<string, ICache*>(tfn, cache)
                ));
            }else{
                //break;
            }
        }
    }
}

void Material :: load_json(string fn)
{
    // ??? m_bComposite = true;
}

void Material :: load_mtllib(string fn, string material)
{
    m_bComposite = true;

    fstream f(fn);
    if(!f.good()) {
        ERROR(READ, Filesystem::getFileName(fn) + ":" + material);
    }

    string itr_material;
    string line;
    while(getline(f, line))
    {
        istringstream ss(line);
        string nothing;
        ss >> nothing;
        if(boost::starts_with(line, "newmtl")) {
            ss >> itr_material;
            continue;
        }
        if(material != itr_material)
            continue;
        if(boost::starts_with(line, "map_Kd"))
        {
            string tfn;
            ss >> tfn;
            tfn = Filesystem::getFileName(tfn);

            auto tex = m_pCache->cache_as<ITexture>(tfn);
            // should throw instead of returning null
            assert(tex);
            m_Textures.push_back(tex);
        }
    }
}

Material :: ~Material()
{
}

//unsigned int Material :: id(Pass* pass) const
//{
//    return 0;
//}

void Material :: bind(Pass* pass, unsigned slot) const
{
    //const unsigned sz = m_Textures.size();
    const unsigned sz = min<unsigned>(1, m_Textures.size());
    // prevents pointless texture_slots state change for proxy material
    if(!m_bComposite) {
        pass->texture_slots(0);
        //unsigned slot_bits = 0;
        //for(unsigned i=0; i<sz; ++i) {
        //    if(m_Textures[i])
        //        slot_bits |= 1 << i;
        //}
        //pass->texture_slots(slot_bits);
    }
    if(sz){
        for(unsigned i=0; i<sz; ++i) {
            if(m_Textures[i])
                m_Textures[i]->bind(pass, i);
            else {
                pass->texture(0,i);
                break;
            }
        }
    }else{
        pass->texture(0,0);
    }
}

/*static*/ bool Material :: supported(
    string fn,
    Cache<Resource, std::string>* cache
){
    string fn_real = Filesystem::cutInternal(Filesystem::getFileName(fn));
    string ext = Filesystem::getExtension(fn_real);
    string cut = Filesystem::cutExtension(fn_real);
    string emb = Filesystem::getInternal(fn);

    if(ext=="mtllib")
        return true;
    else if(ext=="json")
        return true;

    unsigned compat = 0U;
    for(auto&& t: s_ExtraMapNames) {
        auto tfn = cut + "_" + t + "." + ext;
        tfn = cache->transform(tfn);
        if(fs::exists(
            fs::path(tfn)
        )){
            ++compat;
        }
    }
    // all detail maps exist
    return compat;
    //if(compat == s_ExtraMapNames.size())
    //    return true;
    // partial compatibility probably means user forgot one, so we'll warn
    //if(compat)
    //{
    //    // TODO: remove this warning
    //    //WARNINGf("Material \"%s\" is missing %s out of %s detail maps",
    //    //    Filesystem::getFileName(fn) %
    //    //    (s_ExtraMapNames.size() - compat) %
    //    //    s_ExtraMapNames.size()
    //    //);
    //}
    //return false;
}

<commit_msg>fixed incorrect size check<commit_after>#include "Material.h"
#include "Filesystem.h"
#include "kit/log/log.h"
#include <boost/filesystem.hpp>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
using namespace std;
namespace fs = boost::filesystem;

const std::vector<std::string> Material :: s_ExtraMapNames = {
    "NRM",
    "DISP",
    "SPEC",
    "OCC"
};

Material :: Material(
    const std::string& fn,
    Cache<Resource, std::string>* cache
):
    m_Filename(fn),
    m_pCache(cache)
{
    string fn_real = Filesystem::cutInternal(fn);
    string ext = Filesystem::getExtension(fn_real);
    string cut = Filesystem::cutExtension(fn_real);
    string emb = Filesystem::getInternal(fn);
    if(ext == "mtl")
        load_mtllib(fn_real, emb);
    else if(ext == "json")
        load_json(fn);
    else {
        static unsigned class_id = cache->class_id("texture");
        m_Textures.push_back(make_shared<Texture>(
            tuple<string, ICache*>(fn, cache)
        ));
        for(auto&& t: s_ExtraMapNames) {
            auto tfn = cut + "_" + t + "." + ext;
            tfn = cache->transform(tfn);
            if(fs::exists(
                fs::path(tfn)
            )){
                m_Textures.push_back(make_shared<Texture>(
                    tuple<string, ICache*>(tfn, cache)
                ));
            }else{
                //break;
            }
        }
    }
}

void Material :: load_json(string fn)
{
    // ??? m_bComposite = true;
}

void Material :: load_mtllib(string fn, string material)
{
    m_bComposite = true;

    fstream f(fn);
    if(!f.good()) {
        ERROR(READ, Filesystem::getFileName(fn) + ":" + material);
    }

    string itr_material;
    string line;
    while(getline(f, line))
    {
        istringstream ss(line);
        string nothing;
        ss >> nothing;
        if(boost::starts_with(line, "newmtl")) {
            ss >> itr_material;
            continue;
        }
        if(material != itr_material)
            continue;
        if(boost::starts_with(line, "map_Kd"))
        {
            string tfn;
            ss >> tfn;
            tfn = Filesystem::getFileName(tfn);

            auto tex = m_pCache->cache_as<ITexture>(tfn);
            // should throw instead of returning null
            assert(tex);
            m_Textures.push_back(tex);
        }
    }
}

Material :: ~Material()
{
}

//unsigned int Material :: id(Pass* pass) const
//{
//    return 0;
//}

void Material :: bind(Pass* pass, unsigned slot) const
{
    //const unsigned sz = m_Textures.size();
    const unsigned sz = max<unsigned>(1, m_Textures.size());
    // prevents pointless texture_slots state change for proxy material
    if(!m_bComposite) {
        pass->texture_slots(0);
        //unsigned slot_bits = 0;
        //for(unsigned i=0; i<sz; ++i) {
        //    if(m_Textures[i])
        //        slot_bits |= 1 << i;
        //}
        //pass->texture_slots(slot_bits);
    }
    //if(sz){
        for(unsigned i=0; i<sz; ++i) {
            if(m_Textures[i])
                m_Textures[i]->bind(pass, i);
            else {
                pass->texture(0,i);
                break;
            }
        }
    //}else{
    //    pass->texture(0,0);
    //}
}

/*static*/ bool Material :: supported(
    string fn,
    Cache<Resource, std::string>* cache
){
    string fn_real = Filesystem::cutInternal(Filesystem::getFileName(fn));
    string ext = Filesystem::getExtension(fn_real);
    string cut = Filesystem::cutExtension(fn_real);
    string emb = Filesystem::getInternal(fn);

    if(ext=="mtllib")
        return true;
    else if(ext=="json")
        return true;

    unsigned compat = 0U;
    for(auto&& t: s_ExtraMapNames) {
        auto tfn = cut + "_" + t + "." + ext;
        tfn = cache->transform(tfn);
        if(fs::exists(
            fs::path(tfn)
        )){
            ++compat;
        }
    }
    // all detail maps exist
    return compat;
    //if(compat == s_ExtraMapNames.size())
    //    return true;
    // partial compatibility probably means user forgot one, so we'll warn
    //if(compat)
    //{
    //    // TODO: remove this warning
    //    //WARNINGf("Material \"%s\" is missing %s out of %s detail maps",
    //    //    Filesystem::getFileName(fn) %
    //    //    (s_ExtraMapNames.size() - compat) %
    //    //    s_ExtraMapNames.size()
    //    //);
    //}
    //return false;
}

<|endoftext|>


<commit_before>#include "Odometry.h"
#include <cstdint>
#include "WProgram.h"
#include "Device.h"
#include "config.h"

namespace tamproxy {
    Odometer::Odometer(Encoder& lEncoder, Encoder& rEncoder, Gyro& gyro, float alpha)
        : _encL(lEncoder),
          _encR(rEncoder),
          _gyro(gyro),
          _alpha(alpha),
          _lastTime(micros()),
          _lastMeanEnc(0),
          _gyroTot(0) { }

    std::vector<uint8_t> Odometer::handleRequest(std::vector<uint8_t> &request)
    {
        if (request[0] == ODOMETER_READ_CODE) {
            if (request.size() != 1) return {REQUEST_LENGTH_INVALID_CODE};

            std::vector<uint8_t> res(3*4 + 1);
            size_t i = 0;
            for(float f : {_angle, _x, _y}) {
                // here be dragons
                uint32_t val = *reinterpret_cast<uint32_t*>(&f);
                res[i++] = static_cast<uint8_t>(val>>24);
                res[i++] = static_cast<uint8_t>(val>>16);
                res[i++] = static_cast<uint8_t>(val>>8);
                res[i++] = static_cast<uint8_t>(val);
            }
            res[i++] = _gyroOk;
            return res;
        }
        else {
            return {REQUEST_BODY_INVALID_CODE};
        }
    }

    void Odometer::update()
    {
        const float ticksPerRev = 3200.0;
        const float wheelRadius = 3.78125 / 2;
        const float baseWidth = 15.3; //inches
        const float ticksPerRad = ticksPerRev / (2*M_PI);

        uint32_t lEncVal = _encL.read();
        uint32_t rEncVal = _encR.read();

        // be careful about overflow here
        int32_t diffEnc = rEncVal - lEncVal;
        uint32_t meanEnc = lEncVal + diffEnc/2;

        float encAngle = (diffEnc/ticksPerRad) * wheelRadius/baseWidth;

        // Use the gyro, if possible
        int16_t rawGyro = _gyro.read(_gyroOk);
        if(_gyroOk) {
            float gyroRead = Gyro::toRadians(rawGyro);

            _gyroTot += gyroRead*(micros() - _lastTime) / 1e6;
            _angle = _alpha*_gyroTot + (1-_alpha)*encAngle;
        }
        else {
            _angle = encAngle;
        }

        float dr = static_cast<int32_t>(meanEnc - _lastMeanEnc)/ticksPerRad * wheelRadius;
        _x += dr * cos(_angle);
        _y += dr * sin(_angle);

        _lastTime = micros();
        _lastMeanEnc = meanEnc;
    }
}<commit_msg>Make sure that we use the same value of micros() when integrating and updating!<commit_after>#include "Odometry.h"
#include <cstdint>
#include "WProgram.h"
#include "Device.h"
#include "config.h"

namespace tamproxy {
    Odometer::Odometer(Encoder& lEncoder, Encoder& rEncoder, Gyro& gyro, float alpha)
        : _encL(lEncoder),
          _encR(rEncoder),
          _gyro(gyro),
          _alpha(alpha),
          _lastTime(micros()),
          _lastMeanEnc(0),
          _gyroTot(0) { }

    std::vector<uint8_t> Odometer::handleRequest(std::vector<uint8_t> &request)
    {
        if (request[0] == ODOMETER_READ_CODE) {
            if (request.size() != 1) return {REQUEST_LENGTH_INVALID_CODE};

            std::vector<uint8_t> res(3*4 + 1);
            size_t i = 0;
            for(float f : {_angle, _x, _y}) {
                // here be dragons
                uint32_t val = *reinterpret_cast<uint32_t*>(&f);
                res[i++] = static_cast<uint8_t>(val>>24);
                res[i++] = static_cast<uint8_t>(val>>16);
                res[i++] = static_cast<uint8_t>(val>>8);
                res[i++] = static_cast<uint8_t>(val);
            }
            res[i++] = _gyroOk;
            return res;
        }
        else {
            return {REQUEST_BODY_INVALID_CODE};
        }
    }

    void Odometer::update()
    {
        const float ticksPerRev = 3200.0;
        const float wheelRadius = 3.78125 / 2;
        const float baseWidth = 15.3; //inches
        const float ticksPerRad = ticksPerRev / (2*M_PI);

        uint32_t lEncVal = _encL.read();
        uint32_t rEncVal = _encR.read();

        // be careful about overflow here
        int32_t diffEnc = rEncVal - lEncVal;
        uint32_t meanEnc = lEncVal + diffEnc/2;

        float encAngle = (diffEnc/ticksPerRad) * wheelRadius/baseWidth;

        // Use the gyro, if possible
        int16_t rawGyro = _gyro.read(_gyroOk);
        uint32_t currTime = micros();

        if(_gyroOk) {
            float gyroRead = Gyro::toRadians(rawGyro);

            _gyroTot += gyroRead*(currTime - _lastTime) / 1e6;
            _angle = _alpha*_gyroTot + (1-_alpha)*encAngle;
        }
        else {
            _angle = encAngle;
        }

        float dr = static_cast<int32_t>(meanEnc - _lastMeanEnc)/ticksPerRad * wheelRadius;
        _x += dr * cos(_angle);
        _y += dr * sin(_angle);

        _lastTime = currTime;
        _lastMeanEnc = meanEnc;
    }
}<|endoftext|>


<commit_before>// Copyright 2015 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <ReadData.hpp>

namespace AstroData {

RingBufferError::RingBufferError() {}

RingBufferError::~RingBufferError() throw () {}

const char * RingBufferError::what() const throw() {
    return ("Impossible to read from the PSRDada ring buffer.");
}

void readZappedChannels(Observation & observation, const std::string & inputFileName, std::vector< uint8_t > & zappedChannels) {
  unsigned int nrChannels = 0;
  std::ifstream input;

  input.open(inputFileName);
  while ( !input.eof() ) {
    unsigned int channel = 0;

    input >> channel;
    if ( channel < observation.getNrChannels() ) {
      zappedChannels[channel] = 1;
      nrChannels++;
    }
  }
  input.close();
  observation.setNrZappedChannels(nrChannels);
}

} // AstroData

<commit_msg>Fix to avoid empty files. Could still be improved, but it is enough for now.<commit_after>// Copyright 2015 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <ReadData.hpp>

namespace AstroData {

RingBufferError::RingBufferError() {}

RingBufferError::~RingBufferError() throw () {}

const char * RingBufferError::what() const throw() {
    return ("Impossible to read from the PSRDada ring buffer.");
}

void readZappedChannels(Observation & observation, const std::string & inputFileName, std::vector< uint8_t > & zappedChannels) {
  unsigned int nrChannels = 0;
  std::ifstream input;

  input.open(inputFileName);
  while ( !input.eof() ) {
    unsigned int channel = observation.getNrChannels();

    input >> channel;
    if ( channel < observation.getNrChannels() ) {
      zappedChannels[channel] = 1;
      nrChannels++;
    }
  }
  input.close();
  observation.setNrZappedChannels(nrChannels);
}

} // AstroData

<|endoftext|>


<commit_before>#include "Renderer.h"
#include <sstream>
#include <GL/glu.h>
#include <FTGL/ftgl.h>
#include <cmath>
#include "GLFW.h"
#include "Universe.h"
#include "DataStore.h"

namespace
{
  double rad2deg(double rad)
  {
    return 57.29577951308232087721 * rad;
  }

  unsigned int createStarDisplayList(const TextureManager& textures)
  {
    unsigned int index = glGenLists(1);

    glNewList(index, GL_COMPILE);

    glBindTexture(GL_TEXTURE_2D, textures.getTextureHandle("star"));

    glBegin(GL_QUADS);
    glTexCoord2f(0.0f, 0.0f); glVertex2f(-1.0, -1.0);
    glTexCoord2f(0.0f, 1.0f); glVertex2f(-1.0, 1.0);
    glTexCoord2f(1.0f, 1.0f); glVertex2f(1.0, 1.0);
    glTexCoord2f(1.0f, 0.0f); glVertex2f(1.0, -1.0);
    glEnd();

    glEndList();

    return index;
  }
}

Renderer::Renderer(DataStore& datastore):
  m_datastore(datastore)
{
}

void Renderer::init()
{
  glfw::swapInterval(0);

  glClearColor(0.0, 0.0, 0.0, 0.0);
  glShadeModel(GL_SMOOTH);
  glEnable(GL_TEXTURE_2D);
  glEnable(GL_BLEND);

  glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
  glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD);

  const double minX = m_datastore.get<double>("viewport-min-x");
  const double minY = m_datastore.get<double>("viewport-min-y");
  const double maxX = m_datastore.get<double>("viewport-max-x");
  const double maxY = m_datastore.get<double>("viewport-max-y");

  set_viewport(0, 0, maxX - minX, maxY - minY);
  set_projection(minX, maxX, minY, maxY);

  load_texture(m_datastore.get<std::string>("images-star"), "star");

  m_starDisplayList = createStarDisplayList(m_textures);
}

void Renderer::set_viewport(int x, int y, int w, int h) {
  glViewport(x, y, w, h);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
}

void Renderer::set_projection(double left, double right, double bottom, double top) {
  glOrtho(left, right, bottom, top, -1, 1);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
}

void Renderer::load_texture(const std::string& path, const std::string& key) {
  m_textures.loadTexture(path, key);
}

void Renderer::render(const Universe& universe) const
{
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glLoadIdentity();

  const StarList& stars = universe.stars();
  for(StarList::const_iterator it = stars.begin(); it != stars.end(); it++){
    const Star* star = *it;
    glColor3f(star->cr, star->cg, star->cb);
    glPushMatrix();
    glTranslatef(star->x, star->y, 0.0);
    glScalef(star->r, star->r, star->r);
    glCallList(m_starDisplayList);
    glPopMatrix();
  }
}

void Renderer::render_text(int x, int y, const std::string& text) const
{
  FTPixmapFont font(m_datastore.get<std::string>("debug-font-family").c_str());

  font.FaceSize(m_datastore.get<int>("debug-font-size"));
  font.Render(text.c_str(), -1, FTPoint(x, y));
}

<commit_msg>use polygon to represent stars<commit_after>#include "Renderer.h"
#include <sstream>
#include <GL/glu.h>
#include <FTGL/ftgl.h>
#include <cmath>
#include "GLFW.h"
#include "Universe.h"
#include "DataStore.h"

namespace
{
  double rad2deg(double rad)
  {
    return 57.29577951308232087721 * rad;
  }

  unsigned int createStarDisplayList(const TextureManager& textures)
  {
    unsigned int index = glGenLists(1);

    glNewList(index, GL_COMPILE);

    glBegin(GL_TRIANGLE_FAN);
    glColor3f(1,0,1);
    glVertex2f(0.0f, 0.0f);
    glColor3f(1,1,1);

    const float pi = M_PI;

    const int n = 36;
    for(int i = 0; i <= n; ++i) {
      const float x = cos(2 * pi * i / n);
      const float y = sin(2 * pi * i / n);
      glVertex2f(x, y);
    }

    glEnd();

    glEndList();

    return index;
  }
}

Renderer::Renderer(DataStore& datastore):
  m_datastore(datastore)
{
}

void Renderer::init()
{
  glfw::swapInterval(0);

  glClearColor(0.0, 0.0, 0.0, 0.0);

  const double minX = m_datastore.get<double>("viewport-min-x");
  const double minY = m_datastore.get<double>("viewport-min-y");
  const double maxX = m_datastore.get<double>("viewport-max-x");
  const double maxY = m_datastore.get<double>("viewport-max-y");

  set_viewport(0, 0, maxX - minX, maxY - minY);
  set_projection(minX, maxX, minY, maxY);

  load_texture(m_datastore.get<std::string>("images-star"), "star");

  m_starDisplayList = createStarDisplayList(m_textures);
}

void Renderer::set_viewport(int x, int y, int w, int h) {
  glViewport(x, y, w, h);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
}

void Renderer::set_projection(double left, double right, double bottom, double top) {
  glOrtho(left, right, bottom, top, -1, 1);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
}

void Renderer::load_texture(const std::string& path, const std::string& key) {
  m_textures.loadTexture(path, key);
}

void Renderer::render(const Universe& universe) const
{
  glClear(GL_COLOR_BUFFER_BIT);
  glLoadIdentity();

  const StarList& stars = universe.stars();
  for(StarList::const_iterator it = stars.begin(); it != stars.end(); it++){
    const Star* star = *it;
    glColor3f(star->cr, star->cg, star->cb);
    glPushMatrix();
    glTranslatef(star->x, star->y, 0.0);
    glScalef(star->r, star->r, star->r);
    glCallList(m_starDisplayList);
    glPopMatrix();
  }
}

void Renderer::render_text(int x, int y, const std::string& text) const
{
  FTPixmapFont font(m_datastore.get<std::string>("debug-font-family").c_str());

  font.FaceSize(m_datastore.get<int>("debug-font-size"));
  font.Render(text.c_str(), -1, FTPoint(x, y));
}

<|endoftext|>