<commit_before>/*
 * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published by the
 * Free Software Foundation; either version 3 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/* ScriptData
SDName: Westfall
SD%Complete: 90
SDComment: Quest support: 155
SDCategory: Westfall
EndScriptData */

/* ContentData
npc_daphne_stilwell
EndContentData */

#include "Player.h"
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "ScriptedEscortAI.h"

/*######
## npc_daphne_stilwell
######*/

enum DaphneStilwell
{
    // Yells
    SAY_DS_START        = 0,
    SAY_DS_DOWN_1       = 1,
    SAY_DS_DOWN_2       = 2,
    SAY_DS_DOWN_3       = 3,
    SAY_DS_PROLOGUE     = 4,

    // Spells
    SPELL_SHOOT         = 6660,

    // Quests
    QUEST_TOME_VALOR    = 1651,

    // Creatures
    NPC_DEFIAS_RAIDER   = 6180,

    // Equips
    EQUIP_ID_RIFLE      = 2511
};

class npc_daphne_stilwell : public CreatureScript
{
public:
    npc_daphne_stilwell() : CreatureScript("npc_daphne_stilwell") { }

    bool OnQuestAccept(Player* player, Creature* creature, const Quest* quest) override
    {
        if (quest->GetQuestId() == QUEST_TOME_VALOR)
        {
            creature->AI()->Talk(SAY_DS_START);

            if (npc_escortAI* pEscortAI = CAST_AI(npc_daphne_stilwell::npc_daphne_stilwellAI, creature->AI()))
                pEscortAI->Start(true, true, player->GetGUID());
        }

        return true;
    }

    CreatureAI* GetAI(Creature* creature) const override
    {
        return new npc_daphne_stilwellAI(creature);
    }

    struct npc_daphne_stilwellAI : public npc_escortAI
    {
        npc_daphne_stilwellAI(Creature* creature) : npc_escortAI(creature), summons(me) { }

        SummonList summons;
        uint8 textCounter;

        void Reset() override
        {
            summons.DespawnAll();
            textCounter = SAY_DS_DOWN_1;
        }

        void WaypointReached(uint32 waypointId) override
        {
            Player* player = GetPlayerForEscort();

            if (!player)
                return;

            switch (waypointId)
            {
                case 4:
                    SetEquipmentSlots(false, EQUIP_NO_CHANGE, EQUIP_NO_CHANGE, EQUIP_ID_RIFLE);
                    me->SetSheath(SHEATH_STATE_RANGED);
                    me->HandleEmoteCommand(EMOTE_STATE_USE_STANDING_NO_SHEATHE);
                    break;
                case 7:
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11435.52f, 1601.26f, 68.06f, 4.1f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11440.96f, 1599.69f, 66.35f, 4.09f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11433.44f, 1594.24f, 66.99f, 4.05f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    break;
                case 8:
                    me->SetSheath(SHEATH_STATE_RANGED);
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11435.52f, 1601.26f, 68.06f, 4.1f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11440.96f, 1599.69f, 66.35f, 4.09f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11433.44f, 1594.24f, 66.99f, 4.05f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11428.29f, 1598.37f, 70.90f, 3.9f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    break;
                case 9:
                    me->SetSheath(SHEATH_STATE_RANGED);
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11435.52f, 1601.26f, 68.06f, 4.1f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11440.96f, 1599.69f, 66.35f, 4.09f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11433.44f, 1594.24f, 66.99f, 4.05f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11428.29f, 1598.37f, 70.90f, 3.9f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11438.14f, 1607.6f, 70.94f, 4.38f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    break;
                case 10:
                    SetRun(false);
                    break;
                case 11:
                    Talk(SAY_DS_PROLOGUE);
                    break;
                case 13:
                    SetEquipmentSlots(true);
                    me->SetSheath(SHEATH_STATE_UNARMED);
                    me->HandleEmoteCommand(EMOTE_STATE_USE_STANDING_NO_SHEATHE);
                    break;
                case 17:
                    SetEscortPaused(true);
                    player->GroupEventHappens(QUEST_TOME_VALOR, me);
                    me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_QUESTGIVER);
                    me->DespawnOrUnsummon(60000);
                    break;
            }
        }

        void AttackStart(Unit* who) override
        {
            if (me->Attack(who, false))
            {
                me->SetInCombatWith(who);
                who->SetInCombatWith(me);
            }
        }

        void JustSummoned(Creature* creature) override
        {
            creature->SetHomePosition(me->GetHomePosition());
            creature->GetMotionMaster()->MoveChase(me);
            creature->GetMotionMaster()->MovePoint(0, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ());
            creature->AI()->AttackStart(me);
            creature->AddThreat(me, 0.0f);
            summons.Summon(creature);
        }

        void SummonedCreatureDies(Creature* creature, Unit*) override
        {
            summons.Despawn(creature);
            if (summons.empty())
                Talk(textCounter++, GetPlayerForEscort());
        }

        void Update(const uint32 diff)
        {
            npc_escortAI::UpdateAI(diff);

            if (!UpdateVictim())
                return;

            if (me->isAttackReady(BASE_ATTACK))
            {
                if (!me->IsWithinDist(me->GetVictim(), ATTACK_DISTANCE))
                    DoCastVictim(SPELL_SHOOT, true);
                else
                {
                    me->SetSheath(SHEATH_STATE_MELEE);
                    me->AttackerStateUpdate(me->GetVictim());
                }

                me->resetAttackTimer();
            }
        }
    };
};

void AddSC_westfall()
{
    new npc_daphne_stilwell();
}
<commit_msg>fix(Core/Quest): Daphne Stillwater respawn for quest Tome of Valor (#9469)<commit_after>/*
 * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published by the
 * Free Software Foundation; either version 3 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/* ScriptData
SDName: Westfall
SD%Complete: 90
SDComment: Quest support: 155
SDCategory: Westfall
EndScriptData */

/* ContentData
npc_daphne_stilwell
EndContentData */

#include "Player.h"
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "ScriptedEscortAI.h"

/*######
## npc_daphne_stilwell
######*/

enum DaphneStilwell
{
    // Yells
    SAY_DS_START        = 0,
    SAY_DS_DOWN_1       = 1,
    SAY_DS_DOWN_2       = 2,
    SAY_DS_DOWN_3       = 3,
    SAY_DS_PROLOGUE     = 4,

    // Spells
    SPELL_SHOOT         = 6660,

    // Quests
    QUEST_TOME_VALOR    = 1651,

    // Creatures
    NPC_DEFIAS_RAIDER   = 6180,

    // Equips
    EQUIP_ID_RIFLE      = 2511
};

class npc_daphne_stilwell : public CreatureScript
{
public:
    npc_daphne_stilwell() : CreatureScript("npc_daphne_stilwell") { }

    bool OnQuestAccept(Player* player, Creature* creature, const Quest* quest) override
    {
        if (quest->GetQuestId() == QUEST_TOME_VALOR)
        {
            creature->AI()->Talk(SAY_DS_START);

            if (npc_escortAI* pEscortAI = CAST_AI(npc_daphne_stilwell::npc_daphne_stilwellAI, creature->AI()))
                pEscortAI->Start(true, true, player->GetGUID());
        }

        return true;
    }

    CreatureAI* GetAI(Creature* creature) const override
    {
        return new npc_daphne_stilwellAI(creature);
    }

    struct npc_daphne_stilwellAI : public npc_escortAI
    {
        npc_daphne_stilwellAI(Creature* creature) : npc_escortAI(creature), summons(me) { }

        SummonList summons;
        uint8 textCounter;

        void Reset() override
        {
            summons.DespawnAll();
            textCounter = SAY_DS_DOWN_1;
        }

        void WaypointReached(uint32 waypointId) override
        {
            Player* player = GetPlayerForEscort();

            if (!player)
                return;

            switch (waypointId)
            {
                case 4:
                    SetEquipmentSlots(false, EQUIP_NO_CHANGE, EQUIP_NO_CHANGE, EQUIP_ID_RIFLE);
                    me->SetSheath(SHEATH_STATE_RANGED);
                    me->HandleEmoteCommand(EMOTE_STATE_USE_STANDING_NO_SHEATHE);
                    break;
                case 7:
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11435.52f, 1601.26f, 68.06f, 4.1f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11440.96f, 1599.69f, 66.35f, 4.09f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11433.44f, 1594.24f, 66.99f, 4.05f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    break;
                case 8:
                    me->SetSheath(SHEATH_STATE_RANGED);
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11435.52f, 1601.26f, 68.06f, 4.1f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11440.96f, 1599.69f, 66.35f, 4.09f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11433.44f, 1594.24f, 66.99f, 4.05f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11428.29f, 1598.37f, 70.90f, 3.9f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    break;
                case 9:
                    me->SetSheath(SHEATH_STATE_RANGED);
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11435.52f, 1601.26f, 68.06f, 4.1f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11440.96f, 1599.69f, 66.35f, 4.09f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11433.44f, 1594.24f, 66.99f, 4.05f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11428.29f, 1598.37f, 70.90f, 3.9f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    me->SummonCreature(NPC_DEFIAS_RAIDER, -11438.14f, 1607.6f, 70.94f, 4.38f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000);
                    break;
                case 10:
                    SetRun(false);
                    break;
                case 11:
                    Talk(SAY_DS_PROLOGUE);
                    break;
                case 13:
                    SetEquipmentSlots(true);
                    me->SetSheath(SHEATH_STATE_UNARMED);
                    me->HandleEmoteCommand(EMOTE_STATE_USE_STANDING_NO_SHEATHE);
                    break;
                case 17:
                    SetEscortPaused(true);
                    player->GroupEventHappens(QUEST_TOME_VALOR, me);
                    me->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_QUESTGIVER);
                    me->DespawnOrUnsummon(1s, 1s);
                    break;
            }
        }

        void AttackStart(Unit* who) override
        {
            if (me->Attack(who, false))
            {
                me->SetInCombatWith(who);
                who->SetInCombatWith(me);
            }
        }

        void JustSummoned(Creature* creature) override
        {
            creature->SetHomePosition(me->GetHomePosition());
            creature->GetMotionMaster()->MoveChase(me);
            creature->GetMotionMaster()->MovePoint(0, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ());
            creature->AI()->AttackStart(me);
            creature->AddThreat(me, 0.0f);
            summons.Summon(creature);
        }

        void SummonedCreatureDies(Creature* creature, Unit*) override
        {
            summons.Despawn(creature);
            if (summons.empty())
                Talk(textCounter++, GetPlayerForEscort());
        }

        void Update(const uint32 diff)
        {
            npc_escortAI::UpdateAI(diff);

            if (!UpdateVictim())
                return;

            if (me->isAttackReady(BASE_ATTACK))
            {
                if (!me->IsWithinDist(me->GetVictim(), ATTACK_DISTANCE))
                    DoCastVictim(SPELL_SHOOT, true);
                else
                {
                    me->SetSheath(SHEATH_STATE_MELEE);
                    me->AttackerStateUpdate(me->GetVictim());
                }

                me->resetAttackTimer();
            }
        }
    };
};

void AddSC_westfall()
{
    new npc_daphne_stilwell();
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * 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 "otbOGRExtendedFilenameToOptions.h"
#include <iostream>
#include <fstream>

using namespace otb;

typedef OGRExtendedFilenameToOptions FilenameHelperType;

int otbOGRExtendedFileName(int , char* argv[])
{
  // Verify the number of parameters in the command line
  const char * inputExtendedFilename  = argv[1];
  const char * outputFilename = argv[2];

  std::cout<< argv[1] <<"  "<<argv[2]<<std::endl;
  FilenameHelperType::Pointer helper = FilenameHelperType::New();

  helper->SetExtendedFileName(inputExtendedFilename);

  std::ofstream file;
  file.open(outputFilename);

  file << helper->SimpleFileNameIsSet() << std::endl;
  file << helper->GetSimpleFileName() << std::endl;

  file << "Open option :"<<std::endl;
  FilenameHelperType::GDALOptionType open = helper->GetGDALOpenOptions();
  for ( auto option : open )
    {
    file<< option << std::endl;
    }

  file << "Create option :"<<std::endl;
  FilenameHelperType::GDALOptionType create = helper->GetGDALOptions("creation");
  for ( auto option : create )
    {
    file<< option << std::endl;
    }

  file << "Layer option :"<<std::endl;
  FilenameHelperType::GDALOptionType layer = helper->GetGDALOptions("layer");
  for ( auto option : layer )
    {
    file<< option << std::endl;
    }

  file<< "End of classic helper."<<std::endl;

  layer.push_back("TOTO=first");
  FilenameHelperType::Pointer layerHelper =
    FilenameHelperType::GetGDALLayerOptionsHelper ( layer );
  std::cout<< layerHelper->GetGDALLayerOptions()[0] <<std::endl;
  FilenameHelperType::GDALOptionType newOptions;
    // std::vector< std::string> newOptions;
  newOptions.push_back("TOTO=second");
  newOptions.push_back("TiTi=option");
  layerHelper->AddGDALLayerOptions( newOptions );

  file << layerHelper->SimpleFileNameIsSet() << std::endl;
  file << layerHelper->HasGDALLayerOption() << std::endl;
  file << "Layer option from layer helper:"<<std::endl;
  FilenameHelperType::GDALOptionType latestOptions = layerHelper->GetGDALOptions("layer");
  for ( auto option : latestOptions )
    {
    file<< option << std::endl;
    }
  // test

  file.close();
  return EXIT_SUCCESS;
}

<commit_msg>TEST: ordered vector of string to get the same output on every OS<commit_after>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * 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 "otbOGRExtendedFilenameToOptions.h"
#include <algorithm>
#include <iostream>
#include <fstream>

using namespace otb;

typedef OGRExtendedFilenameToOptions FilenameHelperType;

int otbOGRExtendedFileName(int , char* argv[])
{
  // Verify the number of parameters in the command line
  const char * inputExtendedFilename  = argv[1];
  const char * outputFilename = argv[2];

  std::cout<< argv[1] <<"  "<<argv[2]<<std::endl;
  FilenameHelperType::Pointer helper = FilenameHelperType::New();

  helper->SetExtendedFileName(inputExtendedFilename);

  std::ofstream file;
  file.open(outputFilename);

  file << helper->SimpleFileNameIsSet() << std::endl;
  file << helper->GetSimpleFileName() << std::endl;

  file << "Open option :"<<std::endl;
  FilenameHelperType::GDALOptionType open = helper->GetGDALOpenOptions();
  for ( auto option : open )
    {
    file<< option << std::endl;
    }

  file << "Create option :"<<std::endl;
  FilenameHelperType::GDALOptionType create = helper->GetGDALOptions("creation");
  for ( auto option : create )
    {
    file<< option << std::endl;
    }

  file << "Layer option :"<<std::endl;
  FilenameHelperType::GDALOptionType layer = helper->GetGDALOptions("layer");
  for ( auto option : layer )
    {
    file<< option << std::endl;
    }

  file<< "End of classic helper."<<std::endl;

  layer.push_back("TOTO=first");
  FilenameHelperType::Pointer layerHelper =
    FilenameHelperType::GetGDALLayerOptionsHelper ( layer );
  std::cout<< layerHelper->GetGDALLayerOptions()[0] <<std::endl;
  FilenameHelperType::GDALOptionType newOptions;
    // std::vector< std::string> newOptions;
  newOptions.push_back("TOTO=second");
  newOptions.push_back("TiTi=option");
  layerHelper->AddGDALLayerOptions( newOptions );

  file << layerHelper->SimpleFileNameIsSet() << std::endl;
  file << layerHelper->HasGDALLayerOption() << std::endl;
  file << "Layer option from layer helper:"<<std::endl;
  FilenameHelperType::GDALOptionType latestOptions = layerHelper->GetGDALOptions("layer");
  // need to sort for dummy windows
  std::sort( latestOptions.begin() , latestOptions.end() );
  for ( auto option : latestOptions )
    {
    file<< option << std::endl;
    }

  file.close();
  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>class PowerSpectrum:public SplineFunction {
public:
    PowerSpectrum(int n): SplineFunction(n) {};
    int fixed_power;
    double normalization;
    double Pk_smooth2;   // param.Pk_smooth squared
    double Rnorm;
    double sigmaR_integrand(double k) {
        double x=k*Rnorm;
        double w;
        if (x<=1e-3) w = 1-x*x/10.0;
        else w = 3.0*(sin(x)-x*cos(x))/x/x/x;
        return 0.5/M_PI/M_PI*k*k*w*w*this->power(k);
    }
    double sigmaR(double R) {
        double target_prec = 1e-11;  // 1e-12 was causing divergence in certain cases
        double precision = 1.0;
        Rnorm = R;
        double retval = sqrt(Romberg(&PowerSpectrum::sigmaR_integrand,0,10.0,target_prec,&precision));
        if(precision > target_prec){
            printf("Error: actual Romberg integration precision (%g) is greater than the target precision (%g); halting.\n", precision, target_prec);
            exit(1);
        }
        return retval;
    }
    // Do Romberg integration with up to 25 bisections.
    // Give a precision 'prec'.  Also return the estimated precision in 'obtprec'.

    #define MAXITER  25
    double Romberg(double (PowerSpectrum::*func)(double), double a, double b,
    double prec, double *obtprec) {
        int  jj;
        double h, s, fourtokm1, TT[MAXITER+1][MAXITER+1];

        h = 0.5*(b-a);
        TT[0][1] = h * ( (this->*func)(a) + (this->*func)(b) );
        jj = 0;
        do {
            jj++;
            s = 0; for(int k=1; k<=(1<<(jj-1)); k++) s += (this->*func)(a + (2*k-1)*h);
            TT[jj][1] = 0.5*TT[jj-1][1] + h * s;
            fourtokm1 = 1;
            for(int k=2; k<=jj; k++) {
                fourtokm1 *=4;
                TT[jj][k] = TT[jj][k-1] + ( TT[jj][k-1] - TT[jj-1][k-1])/(fourtokm1 -1);
            }
            h *= 0.5;
            //printf("TT[%d] = %g\n", jj, TT[jj][jj]);
            if(jj>1 && fabs(TT[jj][jj]-TT[jj-1][jj-1])<prec*fabs(TT[jj][jj])) break;
        } while(jj<MAXITER);

        *obtprec = (TT[jj][jj]-TT[jj-1][jj-1])/TT[jj][jj];
        return TT[jj][jj];
    }

    int LoadPower(char filename[], Parameters& param) {
        // Read the file and load/compile the spline function
        // Return 0 if ok
        // Read the file
        // Rescale the given wavenumbers to match to simulation units
        // Renormalize the power spectrum
        // Divide the power spectrum by the box volume, so that the
        //    inverse FFT is normalized properly.
        char line[200];
        FILE *fp;
        double k,P;
        int nn;
        Pk_smooth2 = 0.0;
        normalization = 1.0;
        fp = fopen(filename,"r");
        if(fp == NULL){
            printf("Power spectrum file \"%s\" not found; exiting.\n", filename);
            exit(1);
        }
        nn=0;

        int jj = 0;
        while (fgets(line,200,fp)!=NULL) {
            jj++;
            if (line[0]=='#') continue;
            sscanf(line,"%lf %lf",&k,&P);
            if (k<0.0) continue;
            if (P<0.0) continue;
            k*=param.Pk_scale;
            if (k>0.0) {
                this->load(log(k),log(P));
            } else {
                this->load(-1e3,log(P));
            }
            nn++;
        }
        this->spline();

        // Might still have to normalize things!
        if (param.Pk_norm>0.0) { // Do a normalization
            printf("Input sigma(%f) = %f\n", param.Pk_norm, sigmaR(param.Pk_norm));
            normalization = param.Pk_sigma/sigmaR(param.Pk_norm);
            normalization *= normalization;
            printf("Final sigma(%f) = %f\n", param.Pk_norm, sigmaR(param.Pk_norm));
        }
        // Might need to normalize to the box volume.  This is appropriate
        // if the iFFT is like FFTW, i.e., not dividing by N.
        // This is because integrals over k bring in a phase space volume
        // per cell of (2*pi/L)^3
        normalization /= param.boxsize*param.boxsize*param.boxsize;
        Pk_smooth2 = param.Pk_smooth*param.Pk_smooth;

        fixed_power = param.qPk_fix_to_mean;
        if (fixed_power)
            printf("Fixing density mode amplitudes to sqrt(P(k))\n");
        return 0;
    }

    double power(double wavenumber) {
        // Evaluate the power spectrum and apply a smoothing.
        // Probably we should force P(k=0) to be 0.
        // The smoothing should be exp(-k^2 sig^2/2) for the density,
        // which is exp(-k^2 sig^2) for the power
        if (wavenumber<=0.0) return 0.0;
        return exp(this->val(log(wavenumber))-wavenumber*wavenumber*this->Pk_smooth2)*normalization;
    }

    double one_rand(int i) {
        return gsl_rng_uniform(rng[i]);
    }
    Complx cgauss(double wavenumber, int rng) {
        // Return a gaussian complex deviate scaled to the sqrt of the power
        // Box-Muller, adapted from Numerical Recipes
        // If fixed_power is set, the complex deviate always has amplitude sqrt(P(k))
        double Pk = this->power(wavenumber);
        double phase1, phase2, r2;
        // printf("P(%f) = %g\n",wavenumber,Pk);
        do {
            phase1 = one_rand(rng)*2.0-1.0;
            phase2 = one_rand(rng)*2.0-1.0;
            r2 = phase1*phase1+phase2*phase2;
        } while (!(r2<1.0&&r2>0.0));
        if (fixed_power){
            r2 = sqrt(Pk/r2);
        } else {
            r2 = sqrt(-Pk*log(r2)/r2);   // Drop the factor of 2, so these Gaussians
                                         // have variance of 1/2.
        }
        // printf("cgauss: %f %f\n", phase1*r2, phase2*r2);
        return Complx(phase1*r2,phase2*r2);
    }
};
<commit_msg>Add extrapolation warning<commit_after>class PowerSpectrum:public SplineFunction {
public:
    PowerSpectrum(int n): SplineFunction(n) {};
    int fixed_power;
    double normalization;
    double Pk_smooth2;   // param.Pk_smooth squared
    double Rnorm;
    double kmax;  // max k in the input PS
    double sigmaR_integrand(double k) {
        double x=k*Rnorm;
        double w;
        if (x<=1e-3) w = 1-x*x/10.0;
        else w = 3.0*(sin(x)-x*cos(x))/x/x/x;
        return 0.5/M_PI/M_PI*k*k*w*w*this->power(k);
    }
    double sigmaR(double R) {
        double target_prec = 1e-11;  // 1e-12 was causing divergence in certain cases
        double precision = 1.0;
        Rnorm = R;
        double retval = sqrt(Romberg(&PowerSpectrum::sigmaR_integrand,0,10.0,target_prec,&precision));
        if(precision > target_prec){
            printf("Error: actual Romberg integration precision (%g) is greater than the target precision (%g); halting.\n", precision, target_prec);
            exit(1);
        }
        return retval;
    }
    // Do Romberg integration with up to 25 bisections.
    // Give a precision 'prec'.  Also return the estimated precision in 'obtprec'.

    #define MAXITER  25
    double Romberg(double (PowerSpectrum::*func)(double), double a, double b,
    double prec, double *obtprec) {
        int  jj;
        double h, s, fourtokm1, TT[MAXITER+1][MAXITER+1];

        h = 0.5*(b-a);
        TT[0][1] = h * ( (this->*func)(a) + (this->*func)(b) );
        jj = 0;
        do {
            jj++;
            s = 0; for(int k=1; k<=(1<<(jj-1)); k++) s += (this->*func)(a + (2*k-1)*h);
            TT[jj][1] = 0.5*TT[jj-1][1] + h * s;
            fourtokm1 = 1;
            for(int k=2; k<=jj; k++) {
                fourtokm1 *=4;
                TT[jj][k] = TT[jj][k-1] + ( TT[jj][k-1] - TT[jj-1][k-1])/(fourtokm1 -1);
            }
            h *= 0.5;
            //printf("TT[%d] = %g\n", jj, TT[jj][jj]);
            if(jj>1 && fabs(TT[jj][jj]-TT[jj-1][jj-1])<prec*fabs(TT[jj][jj])) break;
        } while(jj<MAXITER);

        *obtprec = (TT[jj][jj]-TT[jj-1][jj-1])/TT[jj][jj];
        return TT[jj][jj];
    }

    int LoadPower(char filename[], Parameters& param) {
        // Read the file and load/compile the spline function
        // Return 0 if ok
        // Read the file
        // Rescale the given wavenumbers to match to simulation units
        // Renormalize the power spectrum
        // Divide the power spectrum by the box volume, so that the
        //    inverse FFT is normalized properly.
        char line[200];
        FILE *fp;
        double k,P;
        int nn;
        Pk_smooth2 = 0.0;
        normalization = 1.0;
        fp = fopen(filename,"r");
        if(fp == NULL){
            printf("Power spectrum file \"%s\" not found; exiting.\n", filename);
            exit(1);
        }
        nn=0;

        int jj = 0;
        while (fgets(line,200,fp)!=NULL) {
            jj++;
            if (line[0]=='#') continue;
            sscanf(line,"%lf %lf",&k,&P);
            if (k<0.0) continue;
            if (P<0.0) continue;
            k*=param.Pk_scale;
            if (k>0.0) {
                this->load(log(k),log(P));
            } else {
                this->load(-1e3,log(P));
            }
            kmax = std::max(k,kmax);
            nn++;
        }
        this->spline();

        // Might still have to normalize things!
        if (param.Pk_norm>0.0) { // Do a normalization
            printf("Input sigma(%f) = %f\n", param.Pk_norm, sigmaR(param.Pk_norm));
            normalization = param.Pk_sigma/sigmaR(param.Pk_norm);
            normalization *= normalization;
            printf("Final sigma(%f) = %f\n", param.Pk_norm, sigmaR(param.Pk_norm));
        }
        // Might need to normalize to the box volume.  This is appropriate
        // if the iFFT is like FFTW, i.e., not dividing by N.
        // This is because integrals over k bring in a phase space volume
        // per cell of (2*pi/L)^3
        normalization /= param.boxsize*param.boxsize*param.boxsize;
        Pk_smooth2 = param.Pk_smooth*param.Pk_smooth;

        fixed_power = param.qPk_fix_to_mean;
        if (fixed_power)
            printf("Fixing density mode amplitudes to sqrt(P(k))\n");
        return 0;
    }

    double power(double wavenumber) {
        // Evaluate the power spectrum and apply a smoothing.
        // Probably we should force P(k=0) to be 0.
        // The smoothing should be exp(-k^2 sig^2/2) for the density,
        // which is exp(-k^2 sig^2) for the power
        static bool already_warned = false;
        if (wavenumber > kmax && !already_warned) {
            fprintf(stderr, "\n*** WARNING: power spectrum spline interpolation was requested\n"
                            "    past the maximum k (%f) that was provided in the input power\n"
                            "    spectrum file.  The extrapolation should be well-behaved, but\n"
                            "    make sure that this was expected.  Provide a power spectrum\n"
                            "    that goes to k=10 to get rid of this warning.\n", wavenumber, kmax);
            already_warned = true;
        }
        if (wavenumber<=0.0) return 0.0;
        return exp(this->val(log(wavenumber))-wavenumber*wavenumber*this->Pk_smooth2)*normalization;
    }

    double one_rand(int i) {
        return gsl_rng_uniform(rng[i]);
    }
    Complx cgauss(double wavenumber, int rng) {
        // Return a gaussian complex deviate scaled to the sqrt of the power
        // Box-Muller, adapted from Numerical Recipes
        // If fixed_power is set, the complex deviate always has amplitude sqrt(P(k))
        double Pk = this->power(wavenumber);
        double phase1, phase2, r2;
        // printf("P(%f) = %g\n",wavenumber,Pk);
        do {
            phase1 = one_rand(rng)*2.0-1.0;
            phase2 = one_rand(rng)*2.0-1.0;
            r2 = phase1*phase1+phase2*phase2;
        } while (!(r2<1.0&&r2>0.0));
        if (fixed_power){
            r2 = sqrt(Pk/r2);
        } else {
            r2 = sqrt(-Pk*log(r2)/r2);   // Drop the factor of 2, so these Gaussians
                                         // have variance of 1/2.
        }
        // printf("cgauss: %f %f\n", phase1*r2, phase2*r2);
        return Complx(phase1*r2,phase2*r2);
    }
};
<|endoftext|>


<commit_before>// Copyright (C) 2013 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

/*
 * SEDMLUtils.cpp
 *
 *  Created on: 15 Jul 2013
 *      Author: dada
 */

//#include <zip.h>
#include <sstream>
#include <iostream>
#include <vector>
#include "SEDMLUtils.h"

#include <sedml/SedTypes.h>
#include <sbml/SBMLTypes.h>

#include <copasi/model/CModel.h>
#include <copasi/report/CCopasiObject.h>
#include <copasi/CopasiDataModel/CCopasiDataModel.h>

std::string SEDMLUtils::findIdByNameAndType(
  const std::map<const CCopasiObject*, SBase*>& map,
  int typeCode,
  const std::string& name)
{
  std::map<const CCopasiObject*, SBase*>::const_iterator it = map.begin();

  std::string::size_type compartmentStart = name.find("{");

  std::string compId = "";

  if (compartmentStart != std::string::npos)
    {
      std::string compName = name.substr(compartmentStart + 1, name.size() - compartmentStart - 2);
      SEDMLUtils::removeCharactersFromString(compName, "\"");

      compId = findIdByNameAndType(map, SBML_COMPARTMENT, compName);
    }

  while (it != map.end())
    {
      SBase* current = it->second;
      const CCopasiObject* object = it->first;
      std::string displayName = object->getObjectDisplayName();

      if (((current->getTypeCode() & typeCode) != typeCode))
        {
          ++it;
          continue;
        }

      if (current->getName() == name)
        return current->getId();

      if (typeCode == SBML_SPECIES  && compartmentStart != std::string::npos)
        {
          if (displayName == name)
            {
              Species* species = (Species*)current;

              if (species->getCompartment() == compId)
                return species->getId();
            }
        }

      ++it;
    }

  return "";
}

std::string
SEDMLUtils::getXPathAndName(std::string& sbmlId,
                            const std::string &type,
                            const CModel *pModel,
                            const CCopasiDataModel& dataModel)
{
  std::vector<std::string> stringsContainer;
  std::string targetXPathString;
  const std::map<const CCopasiObject*, SBase*>& copasi2sbmlmap =
    const_cast<CCopasiDataModel&>(dataModel).getCopasi2SBMLMap();
  std::string displayName = sbmlId;

  if (copasi2sbmlmap.size() == 0)
    {
      // this should not be happening, as this is used to verify the element.
      return "";
    }

  std::map<CCopasiObject*, SBase*>::const_iterator pos;

  if (type == "Concentration" || type == "InitialConcentration")
    {
      targetXPathString = "/sbml:sbml/sbml:model/sbml:listOfSpecies/sbml:species[@id=\'";
      //remove unwanted characters from the plot item object name
      removeCharactersFromString(displayName, "[]");

      if (type == "InitialConcentration")
        {
          displayName = displayName.substr(0, displayName.length() - 2);
        }

      sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_SPECIES, displayName);

      if (!sbmlId.empty())
        {
          return targetXPathString + sbmlId + "\']";
        }
      else
        return "";
    }

  else if (type == "Flux")
    {
      targetXPathString = "/sbml:sbml/sbml:model/sbml:listOfReactions/sbml:reaction[@id=\'";
      splitStrings(displayName, ')', stringsContainer);
      displayName = stringsContainer[0];

      removeCharactersFromString(displayName, "(");

      sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_REACTION, displayName);

      if (!sbmlId.empty())
        {
          return targetXPathString + sbmlId + "\']";
        }
      else
        return "";
    }
  else if (type == "Value" || type == "InitialValue")
    {
      if (type == "InitialValue")
        {
          displayName = displayName.substr(0, displayName.find(".InitialValue"));
        }

      targetXPathString = "/sbml:sbml/sbml:model/sbml:listOfParameters/sbml:parameter[@id=\'";
      splitStrings(displayName, '[', stringsContainer);

      if (stringsContainer.size() == 1)
        {
          // not found ... might be a local parameter
          removeCharactersFromString(displayName, "()");
          splitStrings(displayName, '.', stringsContainer);

          if (stringsContainer.size() == 2)
            {
              sbmlId = stringsContainer[0] + "_" + stringsContainer[1];
              std::stringstream xpath;
              xpath << "/sbml:sbml/sbml:model/sbml:listOfReactions/sbml:reaction[@id=\'";
              xpath << stringsContainer[0];
              xpath << "\']/sbml:kineticLaw/sbml:listOfParameters/sbml:parameter[@id=\'";
              xpath << stringsContainer[1];
              xpath << "\']";
              return xpath.str();
            }
        }

      displayName = stringsContainer[1];

      removeCharactersFromString(displayName, "]");

      sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_PARAMETER , displayName);

      if (sbmlId.empty())
        sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_LOCAL_PARAMETER , displayName);

      if (!sbmlId.empty())
        {
          return targetXPathString + sbmlId + "\']";
        }
      else
        return "";
    }
  else if (type == "Volume" || type == "InitialVolume")
    {
      targetXPathString = "/sbml:sbml/sbml:model/sbml:listOfCompartments/sbml:compartment[@id=\'";
      splitStrings(displayName, '[', stringsContainer);
      displayName = stringsContainer[1];

      if (type == "InitialVolume")
        {
          displayName = displayName.substr(0, displayName.find(".InitialVolume"));
        }

      if (type == "Volume")
        {
          displayName = displayName.substr(0, displayName.find(".Volume"));
        }

      removeCharactersFromString(displayName, "]");

      sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_COMPARTMENT, displayName);

      if (!sbmlId.empty())
        {
          return targetXPathString + sbmlId + "\']";
        }
      else
        return "";
    }
  else if (type == "Time" || type == "Initial Time")
    return SEDML_TIME_URN;

  sbmlId = "";
  return targetXPathString;
}

const CCopasiObject*
SEDMLUtils::resolveDatagenerator(const CModel *model, const SedDataGenerator* dataReference)
{
  // for now one variable only
  if (dataReference == NULL || dataReference->getNumVariables() < 1) return NULL;

  const SedVariable* var = dataReference->getVariable(0);

  if (var->isSetSymbol() && var->getSymbol() == SEDML_TIME_URN)
    {
      return static_cast<const CCopasiObject *>(model->getObject(CCopasiObjectName("Reference=Time")));
    }

  return resolveXPath(model, var->getTarget());
}

std::string
SEDMLUtils::translateTargetXpathInSBMLId(const std::string &xpath, std::string& SBMLType)
{
  std::vector<std::string> xpathStrings;
  std::string id, nextString;

  splitStrings(xpath, ':', xpathStrings);
  nextString = xpathStrings[xpathStrings.size() - 1];

  splitStrings(nextString, '[', xpathStrings);
  SBMLType = xpathStrings[0];
  nextString = xpathStrings[xpathStrings.size() - 1];

  splitStrings(nextString, '=', xpathStrings);
  nextString = xpathStrings[xpathStrings.size() - 1];
  splitStrings(nextString, ']', xpathStrings);
  id = xpathStrings[0];

  //remove the remaining unwanted characters
  removeCharactersFromString(id, "\"']");
  return id;
}

const CCopasiObject*
SEDMLUtils::resolveXPath(const CModel *model,  const std::string& xpath,
                         bool initial /* = false*/)
{
  std::string SBMLType;
  std::string id = translateTargetXpathInSBMLId(xpath, SBMLType);
  const CCopasiObject* result = getObjectForSbmlId(model, id, SBMLType, initial);

  if (result == NULL)
    {
      // old method fails here, possibly a local parameter
      size_t pos = xpath.find("/sbml:kineticLaw/sbml:listOfParameters/");

      if (pos != std::string::npos)
        {
          std::string reactionType;
          std::string reactionId = translateTargetXpathInSBMLId(xpath.substr(0, pos), reactionType);
          const CCopasiObject* flux = getObjectForSbmlId(model, reactionId, reactionType);

          if (flux != NULL)
            {
              const CCopasiObject* reactionObj = flux->getObjectParent();
              std::string cn = "ParameterGroup=Parameters,Parameter=" + id + ",Reference=Value";
              return dynamic_cast<const CCopasiObject*>(reactionObj->getObject(cn));
            }
        }
    }

  return result;
}

std::string&
SEDMLUtils::removeCharactersFromString(std::string& str, const std::string& characters)
{
  for (unsigned int ii = 0; ii < characters.length(); ++ii)
    {
      str.erase(std::remove(str.begin(), str.end(), characters[ii]), str.end());
    }

  return str;
}

std::string
SEDMLUtils::getXPathForObject(const CCopasiObject& object)
{
  const std::string& type = object.getObjectName();
  const CCopasiDataModel* dm = object.getObjectDataModel();
  std::string yAxis = object.getObjectDisplayName();
  std::string targetXPathString = getXPathAndName(yAxis, type,
                                  dm->getModel(), *dm);
  return targetXPathString;
}

std::string SEDMLUtils::getNextId(const std::string& base, int count)
{
  std::stringstream str; str << base << count;
  return str.str();
}

int SEDMLUtils::processArchive(const std::string & archiveFile,
                               std::string &fileName, std::string &fileContent)
{

  int err = 0;
  /*
  const char * cArchive = archiveFile.c_str();

    //Open the ZIP archive
    zip *zip = zip_open(cArchive, 0, &err);

    //Search for file using its given name
    const char *nameOfFile = fileName.c_str();
    struct zip_stat st;
    zip_stat_init(&st);
    zip_stat(zip, nameOfFile, 0, &st);

    //Alloc memory for its uncompressed contents
    char *fileCont = new char[st.size];

    //Read the compressed file
  zip_file *file = zip_fopen(zip, nameOfFile, 0);
  zip_fread(file, fileCont, st.size);

  std::ostringstream fileContentStream;
  size_t i, iMax = st.size;
  for(i = 0; i<iMax; ++i){
    fileContentStream << fileCont[i];
  }
  fileContent = fileContentStream.str();

  //close the file and archive
  zip_fclose(file);
  zip_close(zip);
  */

  return err;
}

//split: receives a char delimiter and string and a vector of strings that will contain the splited strings
//this is presently a hack to parse the XPath based target attribute in SEDML. A better solution may be
//necessary in the future.

void
SEDMLUtils::splitStrings(const std::string &xpath, char delim,
                         std::vector<std::string> &xpathStrings)
{
  std::string myPath = xpath;
  xpathStrings.clear();
  std::string next;

  // For each character in the string
  for (std::string::const_iterator it = xpath.begin(); it != xpath.end(); it++)
    {
      // check delimeter character
      if (*it == delim)
        {
          if (!next.empty())
            {
              // Add them to the xpathStrings vector
              xpathStrings.push_back(next);
              next.clear();
            }
        }
      else
        {
          next += *it;
        }
    }

  if (!next.empty())
    xpathStrings.push_back(next);
}

const CCopasiObject *
SEDMLUtils::getObjectForSbmlId(const CModel* pModel, const std::string& id, const std::string& SBMLType, bool initial/* = false*/)
{
  if (SBMLType == "Time")
    return static_cast<const CCopasiObject *>(pModel->getObject(CCopasiObjectName("Reference=Time")));

  if (SBMLType == "species")
    {
      size_t iMet, imax = pModel->getMetabolites().size();

      for (iMet = 0; iMet < imax; ++iMet)
        {
          // the importer should not need to change the initial concentration
          // pModel->getMetabolites()[iMet].setInitialConcentration(0.896901);

          if (pModel->getMetabolites()[iMet].getSBMLId() == id)
            {
              if (initial)
                return pModel->getMetabolites()[iMet].getInitialConcentrationReference();

              return pModel->getMetabolites()[iMet].getConcentrationReference();
            }
        }
    }
  else if (SBMLType == "reaction")
    {
      size_t iMet, imax = pModel->getReactions().size();

      for (iMet = 0; iMet < imax; ++iMet)
        {
          if (pModel->getReactions()[iMet].getSBMLId() == id)
            {
              if (initial)
                return NULL;

              return pModel->getReactions()[iMet].getFluxReference();
            }
        }
    }
  else if (SBMLType == "parameter")
    {
      size_t iMet, imax = pModel->getModelValues().size();

      for (iMet = 0; iMet < imax; ++iMet)
        {
          if (pModel->getModelValues()[iMet].getSBMLId() == id)
            {
              if (initial)
                return pModel->getModelValues()[iMet].getInitialValueReference();

              return pModel->getModelValues()[iMet].getValueReference();
            }
        }
    }

  else if (SBMLType == "compartment")
    {
      size_t iComp, imax = pModel->getCompartments().size();

      for (iComp = 0; iComp < imax; ++iComp)
        {
          if (pModel->getCompartments()[iComp].getSBMLId() == id)
            {
              if (initial)
                return pModel->getCompartments()[iComp].getInitialValueReference();

              return pModel->getCompartments()[iComp].getValueReference();
            }
        }
    }

  return NULL;
}

/*void SEDMLUtils::resmoveUnwantedChars(std::string & str, char chars[]) {
  for (unsigned int i = 0; i < strlen(chars); ++i) {

    str.erase(std::remove(str.begin(), str.end(), chars[i]), str.end());
  }
}
 */
SEDMLUtils::SEDMLUtils()
{
  // TODO Auto-generated constructor stub
}

SEDMLUtils::~SEDMLUtils()
{
  // TODO Auto-generated destructor stub
}
<commit_msg>- issue 2360: fix xpath generation for reactions<commit_after>// Copyright (C) 2017 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and University of
// of Connecticut School of Medicine.
// All rights reserved.

// Copyright (C) 2013 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

/*
 * SEDMLUtils.cpp
 *
 *  Created on: 15 Jul 2013
 *      Author: dada
 */

//#include <zip.h>
#include <sstream>
#include <iostream>
#include <vector>
#include "SEDMLUtils.h"

#include <sedml/SedTypes.h>
#include <sbml/SBMLTypes.h>

#include <copasi/model/CModel.h>
#include <copasi/report/CCopasiObject.h>
#include <copasi/CopasiDataModel/CCopasiDataModel.h>

std::string SEDMLUtils::findIdByNameAndType(
  const std::map<const CCopasiObject*, SBase*>& map,
  int typeCode,
  const std::string& name)
{
  std::map<const CCopasiObject*, SBase*>::const_iterator it = map.begin();

  std::string::size_type compartmentStart = name.find("{");

  std::string compId = "";

  if (compartmentStart != std::string::npos)
    {
      std::string compName = name.substr(compartmentStart + 1, name.size() - compartmentStart - 2);
      SEDMLUtils::removeCharactersFromString(compName, "\"");

      compId = findIdByNameAndType(map, SBML_COMPARTMENT, compName);
    }

  while (it != map.end())
    {
      SBase* current = it->second;
      const CCopasiObject* object = it->first;
      std::string displayName = object->getObjectDisplayName();

      if (((current->getTypeCode() & typeCode) != typeCode))
        {
          ++it;
          continue;
        }

      if (current->getName() == name)
        return current->getId();

      if (typeCode == SBML_SPECIES  && compartmentStart != std::string::npos)
        {
          if (displayName == name)
            {
              Species* species = (Species*)current;

              if (species->getCompartment() == compId)
                return species->getId();
            }
        }

      ++it;
    }

  return "";
}

std::string
SEDMLUtils::getXPathAndName(std::string& sbmlId,
                            const std::string &type,
                            const CModel *pModel,
                            const CCopasiDataModel& dataModel)
{
  std::vector<std::string> stringsContainer;
  std::string targetXPathString;
  const std::map<const CCopasiObject*, SBase*>& copasi2sbmlmap =
    const_cast<CCopasiDataModel&>(dataModel).getCopasi2SBMLMap();
  std::string displayName = sbmlId;

  if (copasi2sbmlmap.size() == 0)
    {
      // this should not be happening, as this is used to verify the element.
      return "";
    }

  std::map<CCopasiObject*, SBase*>::const_iterator pos;

  if (type == "Concentration" || type == "InitialConcentration")
    {
      targetXPathString = "/sbml:sbml/sbml:model/sbml:listOfSpecies/sbml:species[@id=\'";
      //remove unwanted characters from the plot item object name
      removeCharactersFromString(displayName, "[]");

      if (type == "InitialConcentration")
        {
          displayName = displayName.substr(0, displayName.length() - 2);
        }

      sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_SPECIES, displayName);

      if (!sbmlId.empty())
        {
          return targetXPathString + sbmlId + "\']";
        }
      else
        return "";
    }

  else if (type == "Flux")
    {
      targetXPathString = "/sbml:sbml/sbml:model/sbml:listOfReactions/sbml:reaction[@id=\'";

      std::string::size_type pos = displayName.rfind(".Flux");
      displayName = displayName.substr(1, pos - 2);

      sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_REACTION, displayName);

      if (!sbmlId.empty())
        {
          return targetXPathString + sbmlId + "\']";
        }
      else
        return "";
    }
  else if (type == "Value" || type == "InitialValue")
    {
      if (type == "InitialValue")
        {
          displayName = displayName.substr(0, displayName.find(".InitialValue"));
        }

      targetXPathString = "/sbml:sbml/sbml:model/sbml:listOfParameters/sbml:parameter[@id=\'";
      splitStrings(displayName, '[', stringsContainer);

      if (stringsContainer.size() == 1)
        {
          // not found ... might be a local parameter
          removeCharactersFromString(displayName, "()");
          splitStrings(displayName, '.', stringsContainer);

          if (stringsContainer.size() == 2)
            {
              sbmlId = stringsContainer[0] + "_" + stringsContainer[1];
              std::stringstream xpath;
              xpath << "/sbml:sbml/sbml:model/sbml:listOfReactions/sbml:reaction[@id=\'";
              xpath << stringsContainer[0];
              xpath << "\']/sbml:kineticLaw/sbml:listOfParameters/sbml:parameter[@id=\'";
              xpath << stringsContainer[1];
              xpath << "\']";
              return xpath.str();
            }
        }

      displayName = stringsContainer[1];

      removeCharactersFromString(displayName, "]");

      sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_PARAMETER , displayName);

      if (sbmlId.empty())
        sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_LOCAL_PARAMETER , displayName);

      if (!sbmlId.empty())
        {
          return targetXPathString + sbmlId + "\']";
        }
      else
        return "";
    }
  else if (type == "Volume" || type == "InitialVolume")
    {
      targetXPathString = "/sbml:sbml/sbml:model/sbml:listOfCompartments/sbml:compartment[@id=\'";
      splitStrings(displayName, '[', stringsContainer);
      displayName = stringsContainer[1];

      if (type == "InitialVolume")
        {
          displayName = displayName.substr(0, displayName.find(".InitialVolume"));
        }

      if (type == "Volume")
        {
          displayName = displayName.substr(0, displayName.find(".Volume"));
        }

      removeCharactersFromString(displayName, "]");

      sbmlId = findIdByNameAndType(copasi2sbmlmap, SBML_COMPARTMENT, displayName);

      if (!sbmlId.empty())
        {
          return targetXPathString + sbmlId + "\']";
        }
      else
        return "";
    }
  else if (type == "Time" || type == "Initial Time")
    return SEDML_TIME_URN;

  sbmlId = "";
  return targetXPathString;
}

const CCopasiObject*
SEDMLUtils::resolveDatagenerator(const CModel *model, const SedDataGenerator* dataReference)
{
  // for now one variable only
  if (dataReference == NULL || dataReference->getNumVariables() < 1) return NULL;

  const SedVariable* var = dataReference->getVariable(0);

  if (var->isSetSymbol() && var->getSymbol() == SEDML_TIME_URN)
    {
      return static_cast<const CCopasiObject *>(model->getObject(CCopasiObjectName("Reference=Time")));
    }

  return resolveXPath(model, var->getTarget());
}

std::string
SEDMLUtils::translateTargetXpathInSBMLId(const std::string &xpath, std::string& SBMLType)
{
  std::vector<std::string> xpathStrings;
  std::string id, nextString;

  splitStrings(xpath, ':', xpathStrings);
  nextString = xpathStrings[xpathStrings.size() - 1];

  splitStrings(nextString, '[', xpathStrings);
  SBMLType = xpathStrings[0];
  nextString = xpathStrings[xpathStrings.size() - 1];

  splitStrings(nextString, '=', xpathStrings);
  nextString = xpathStrings[xpathStrings.size() - 1];
  splitStrings(nextString, ']', xpathStrings);
  id = xpathStrings[0];

  //remove the remaining unwanted characters
  removeCharactersFromString(id, "\"']");
  return id;
}

const CCopasiObject*
SEDMLUtils::resolveXPath(const CModel *model,  const std::string& xpath,
                         bool initial /* = false*/)
{
  std::string SBMLType;
  std::string id = translateTargetXpathInSBMLId(xpath, SBMLType);
  const CCopasiObject* result = getObjectForSbmlId(model, id, SBMLType, initial);

  if (result == NULL)
    {
      // old method fails here, possibly a local parameter
      size_t pos = xpath.find("/sbml:kineticLaw/sbml:listOfParameters/");

      if (pos != std::string::npos)
        {
          std::string reactionType;
          std::string reactionId = translateTargetXpathInSBMLId(xpath.substr(0, pos), reactionType);
          const CCopasiObject* flux = getObjectForSbmlId(model, reactionId, reactionType);

          if (flux != NULL)
            {
              const CCopasiObject* reactionObj = flux->getObjectParent();
              std::string cn = "ParameterGroup=Parameters,Parameter=" + id + ",Reference=Value";
              return dynamic_cast<const CCopasiObject*>(reactionObj->getObject(cn));
            }
        }
    }

  return result;
}

std::string&
SEDMLUtils::removeCharactersFromString(std::string& str, const std::string& characters)
{
  for (unsigned int ii = 0; ii < characters.length(); ++ii)
    {
      str.erase(std::remove(str.begin(), str.end(), characters[ii]), str.end());
    }

  return str;
}

std::string
SEDMLUtils::getXPathForObject(const CCopasiObject& object)
{
  const std::string& type = object.getObjectName();
  const CCopasiDataModel* dm = object.getObjectDataModel();
  std::string yAxis = object.getObjectDisplayName();
  std::string targetXPathString = getXPathAndName(yAxis, type,
                                  dm->getModel(), *dm);
  return targetXPathString;
}

std::string SEDMLUtils::getNextId(const std::string& base, int count)
{
  std::stringstream str; str << base << count;
  return str.str();
}

int SEDMLUtils::processArchive(const std::string & archiveFile,
                               std::string &fileName, std::string &fileContent)
{

  int err = 0;
  /*
  const char * cArchive = archiveFile.c_str();

    //Open the ZIP archive
    zip *zip = zip_open(cArchive, 0, &err);

    //Search for file using its given name
    const char *nameOfFile = fileName.c_str();
    struct zip_stat st;
    zip_stat_init(&st);
    zip_stat(zip, nameOfFile, 0, &st);

    //Alloc memory for its uncompressed contents
    char *fileCont = new char[st.size];

    //Read the compressed file
  zip_file *file = zip_fopen(zip, nameOfFile, 0);
  zip_fread(file, fileCont, st.size);

  std::ostringstream fileContentStream;
  size_t i, iMax = st.size;
  for(i = 0; i<iMax; ++i){
    fileContentStream << fileCont[i];
  }
  fileContent = fileContentStream.str();

  //close the file and archive
  zip_fclose(file);
  zip_close(zip);
  */

  return err;
}

//split: receives a char delimiter and string and a vector of strings that will contain the splited strings
//this is presently a hack to parse the XPath based target attribute in SEDML. A better solution may be
//necessary in the future.

void
SEDMLUtils::splitStrings(const std::string &xpath, char delim,
                         std::vector<std::string> &xpathStrings)
{
  std::string myPath = xpath;
  xpathStrings.clear();
  std::string next;

  // For each character in the string
  for (std::string::const_iterator it = xpath.begin(); it != xpath.end(); it++)
    {
      // check delimeter character
      if (*it == delim)
        {
          if (!next.empty())
            {
              // Add them to the xpathStrings vector
              xpathStrings.push_back(next);
              next.clear();
            }
        }
      else
        {
          next += *it;
        }
    }

  if (!next.empty())
    xpathStrings.push_back(next);
}

const CCopasiObject *
SEDMLUtils::getObjectForSbmlId(const CModel* pModel, const std::string& id, const std::string& SBMLType, bool initial/* = false*/)
{
  if (SBMLType == "Time")
    return static_cast<const CCopasiObject *>(pModel->getObject(CCopasiObjectName("Reference=Time")));

  if (SBMLType == "species")
    {
      size_t iMet, imax = pModel->getMetabolites().size();

      for (iMet = 0; iMet < imax; ++iMet)
        {
          // the importer should not need to change the initial concentration
          // pModel->getMetabolites()[iMet].setInitialConcentration(0.896901);

          if (pModel->getMetabolites()[iMet].getSBMLId() == id)
            {
              if (initial)
                return pModel->getMetabolites()[iMet].getInitialConcentrationReference();

              return pModel->getMetabolites()[iMet].getConcentrationReference();
            }
        }
    }
  else if (SBMLType == "reaction")
    {
      size_t iMet, imax = pModel->getReactions().size();

      for (iMet = 0; iMet < imax; ++iMet)
        {
          if (pModel->getReactions()[iMet].getSBMLId() == id)
            {
              if (initial)
                return NULL;

              return pModel->getReactions()[iMet].getFluxReference();
            }
        }
    }
  else if (SBMLType == "parameter")
    {
      size_t iMet, imax = pModel->getModelValues().size();

      for (iMet = 0; iMet < imax; ++iMet)
        {
          if (pModel->getModelValues()[iMet].getSBMLId() == id)
            {
              if (initial)
                return pModel->getModelValues()[iMet].getInitialValueReference();

              return pModel->getModelValues()[iMet].getValueReference();
            }
        }
    }

  else if (SBMLType == "compartment")
    {
      size_t iComp, imax = pModel->getCompartments().size();

      for (iComp = 0; iComp < imax; ++iComp)
        {
          if (pModel->getCompartments()[iComp].getSBMLId() == id)
            {
              if (initial)
                return pModel->getCompartments()[iComp].getInitialValueReference();

              return pModel->getCompartments()[iComp].getValueReference();
            }
        }
    }

  return NULL;
}

/*void SEDMLUtils::resmoveUnwantedChars(std::string & str, char chars[]) {
  for (unsigned int i = 0; i < strlen(chars); ++i) {

    str.erase(std::remove(str.begin(), str.end(), chars[i]), str.end());
  }
}
 */
SEDMLUtils::SEDMLUtils()
{
  // TODO Auto-generated constructor stub
}

SEDMLUtils::~SEDMLUtils()
{
  // TODO Auto-generated destructor stub
}
<|endoftext|>


<commit_before>/*
 *
 * Last modified: July 20 2015
 * By: Edgar Perez Lezama <eperezle@cern.ch>, GSI-Darmstadt
 *
 *
 */

void AddTask_eperezl_dNdPtpp_TPCITS()
{
/*
CheckLoadLibrary("libPWG0base");
CheckLoadLibrary("libPWG0dep");
CheckLoadLibrary("libPWG0selectors");
*/

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();

  if (!mgr) {
    Error("AddTask_dNdPtAnalysis_TPCITS", "No analysis manager found.");
    return 0;
  }

  // Switch off all AliInfo (too much output!!!)
  AliLog::SetGlobalLogLevel(AliLog::kError);
  mgr->SetDebugLevel(0);

  //
  // Create physics trigger selection class
  //
  //AliPhysicsSelection *physTrigSel =  new AliPhysicsSelection();
  //physTrigSel->AddBackgroundIdentification(new AliBackgroundSelection());

  //
  // Create event cuts
  //
  Float_t zvWindow =10. ;

  AlidNdPtEventCuts *evtCuts = new AlidNdPtEventCuts("AlidNdPtEventCuts","Event cuts");
  evtCuts->SetZvRange(-zvWindow,zvWindow);
  evtCuts->SetMeanXYZv(0.0,0.0,0.0);
  evtCuts->SetSigmaMeanXYZv(1.0,1.0,10.0);
  evtCuts->SetTriggerRequired(kTRUE);

  //
  // Create geom. acceptance cuts
  //
  Float_t etaWindow = 1.0 ;
  Float_t ptMin = 0.10;

  AlidNdPtAcceptanceCuts *accCuts = new AlidNdPtAcceptanceCuts("AlidNdPtAcceptanceCuts","Geom. acceptance cuts");
  accCuts->SetEtaRange(-etaWindow,etaWindow);
  accCuts->SetPtRange(ptMin,1.e10);

  //
  // Create standard esd track cuts
  //
  Int_t cutMode = 222;
 gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/SPECTRA/ChargedHadrons/dNdPt/macros/CreatedNdPtTrackCuts.C");
  AliESDtrackCuts* esdTrackCuts = CreatedNdPtTrackCuts(cutMode);
  if (!esdTrackCuts) {
    printf("ERROR: esdTrackCuts could not be created\n");
    return;
  } else {
    //esdTrackCuts->SetHistogramsOn(kTRUE);
    esdTrackCuts->SetHistogramsOn(kTRUE);
  }

  Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);

  //
  // Create task
  //
  AlidNdPtTask *task = new AlidNdPtTask("AlidNdPtTask_TPCITS");
  task->SetUseMCInfo(hasMC);

  // trigger
  task->SelectCollisionCandidates(AliVEvent::kMB);

  //
  // set analysis options from the Helper here !!!
  //

  //AliTriggerAnalysis::Trigger trigger = AliTriggerAnalysis::kMB1;
  AlidNdPtHelper::AnalysisMode analysisMode = AlidNdPtHelper::kTPCITS;
  AlidNdPtHelper::ParticleMode particleMode = AlidNdPtHelper::kAllPart ;

  //
  // Create analysis object
  //

  AlidNdPtAnalysis *fdNdPtAnalysis = new AlidNdPtAnalysis("dNdPtAnalysis","dN/dPt Analysis with TPC-ITS tracking");
  fdNdPtAnalysis->SetEventCuts(evtCuts);
  fdNdPtAnalysis->SetAcceptanceCuts(accCuts);
  fdNdPtAnalysis->SetTrackCuts(esdTrackCuts);
  //fdNdPtAnalysis->SetBackgroundCuts(backCuts);
  fdNdPtAnalysis->SetAnalysisMode(analysisMode);
  fdNdPtAnalysis->SetParticleMode(particleMode);
  //fdNdPtAnalysis->SetTrigger(trigger);
  fdNdPtAnalysis->SetTriggerMask(AliVEvent::kMB);
  //fdNdPtAnalysis->SetTriggerMask(AliVEvent::kEMC1);
  if(hasMC)
  {
    //physTrigSel->SetAnalyzeMC();
    //fdNdPtAnalysis->SetPhysicsTriggerSelection(physTrigSel);
    fdNdPtAnalysis->SetUseMCInfo(kTRUE);
    fdNdPtAnalysis->SetHistogramsOn(kTRUE);
    //fdNdPtAnalysis->SetHistogramsOn(kFALSE);
  }
  else { // online trigger
//     physTrigSel->SetUseBXNumbers();
//     physTrigSel->SetComputeBG();
//     fdNdPtAnalysis->SetPhysicsTriggerSelection(physTrigSel);
  }

    // change binning
    Int_t multNbins = 252;
    Double_t binsMult[253];
    for (int i=0; i<=multNbins; i++) { binsMult[i] = -0.5 + i; }
    binsMult[252] = 1000.;
    // change binning
    const Int_t ptNbins = 81;
    Double_t bins[82] = {0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 18.0, 20.0, 22.0, 24.0, 26.0, 28.0, 30.0, 32.0, 34.0, 36.0, 40.0, 45.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 110.0, 120.0, 130.0, 140.0, 150.0, 160.0, 180.0, 200.0};
    Double_t* binsPt = new Double_t[82];
    for (int i=0; i<82; i++) {binsPt[i] = bins[i];}
    fdNdPtAnalysis->SetBinsPt(ptNbins, binsPt);
    fdNdPtAnalysis->SetBinsPtCorr(ptNbins, binsPt);
    fdNdPtAnalysis->SetBinsMult(multNbins, binsMult);

    // for mean pt use tpc tracks as mult. estimator
    AlidNdPtAcceptanceCuts *multAccCuts = new AlidNdPtAcceptanceCuts("MultaccCuts","Geom. acceptance cuts");
    multAccCuts->SetEtaRange(-0.3,0.3);
    multAccCuts->SetPtRange(0.0,1.e10);
    AliESDtrackCuts* multTrackCuts = CreatedNdPtTrackCuts(222);
    fdNdPtAnalysis->SetMultAcceptanceCuts(multAccCuts);
    fdNdPtAnalysis->SetMultTrackCuts(multTrackCuts);

  // Add analysis object
  task->AddAnalysisObject( fdNdPtAnalysis );

  // Add task
  mgr->AddTask(task);

  // Create containers for input
  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
  mgr->ConnectInput(task, 0, cinput);

  AliAnalysisDataContainer *coutput = mgr->CreateContainer("eperezl_dNdPtpp_TPCITS",
                                                           TList::Class(),
                                                           AliAnalysisManager::kOutputContainer,
                                                           Form("%s:dNdPtHistos", mgr->GetCommonFileName()));

  mgr->ConnectOutput(task, 1, coutput);

}

<commit_msg>update of AddTask for Edgar<commit_after>/*
 *
 * Last modified: July 20 2015
 * By: Edgar Perez Lezama <eperezle@cern.ch>, GSI-Darmstadt
 *
 *
 */

void AddTask_eperezl_dNdPtpp_TPCITS()
{
/*
CheckLoadLibrary("libPWG0base");
CheckLoadLibrary("libPWG0dep");
CheckLoadLibrary("libPWG0selectors");
*/

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();

  if (!mgr) {
    Error("AddTask_dNdPtAnalysis_TPCITS", "No analysis manager found.");
    return 0;
  }

  // Switch off all AliInfo (too much output!!!)
  AliLog::SetGlobalLogLevel(AliLog::kError);
  mgr->SetDebugLevel(0);

  //
  // Create physics trigger selection class
  //
  //AliPhysicsSelection *physTrigSel =  new AliPhysicsSelection();
  //physTrigSel->AddBackgroundIdentification(new AliBackgroundSelection());

  //
  // Create event cuts
  //
  Float_t zvWindow =30. ;

  AlidNdPtEventCuts *evtCuts = new AlidNdPtEventCuts("AlidNdPtEventCuts","Event cuts");
  evtCuts->SetZvRange(-zvWindow,zvWindow);
  evtCuts->SetMeanXYZv(0.0,0.0,0.0);
  evtCuts->SetSigmaMeanXYZv(1.0,1.0,10.0);
  evtCuts->SetTriggerRequired(kTRUE);

  //
  // Create geom. acceptance cuts
  //
  Float_t etaWindow = 1.0 ;
  Float_t ptMin = 0.10;

  AlidNdPtAcceptanceCuts *accCuts = new AlidNdPtAcceptanceCuts("AlidNdPtAcceptanceCuts","Geom. acceptance cuts");
  accCuts->SetEtaRange(-etaWindow,etaWindow);
  accCuts->SetPtRange(ptMin,1.e10);

  //
  // Create standard esd track cuts
  //
  Int_t cutMode = 222;
 gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/SPECTRA/ChargedHadrons/dNdPt/macros/CreatedNdPtTrackCuts.C");
  AliESDtrackCuts* esdTrackCuts = CreatedNdPtTrackCuts(cutMode);
  if (!esdTrackCuts) {
    printf("ERROR: esdTrackCuts could not be created\n");
    return;
  } else {
    //esdTrackCuts->SetHistogramsOn(kTRUE);
    esdTrackCuts->SetHistogramsOn(kTRUE);
  }

  Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);

  //
  // Create task
  //
  AlidNdPtTask *task = new AlidNdPtTask("AlidNdPtTask_TPCITS");
  task->SetUseMCInfo(hasMC);

  // trigger
  task->SelectCollisionCandidates(AliVEvent::kMB);

  //
  // set analysis options from the Helper here !!!
  //

  //AliTriggerAnalysis::Trigger trigger = AliTriggerAnalysis::kMB1;
  AlidNdPtHelper::AnalysisMode analysisMode = AlidNdPtHelper::kTPCITS;
  AlidNdPtHelper::ParticleMode particleMode = AlidNdPtHelper::kAllPart ;

  //
  // Create analysis object
  //

  AlidNdPtAnalysis *fdNdPtAnalysis = new AlidNdPtAnalysis("dNdPtAnalysis","dN/dPt Analysis with TPC-ITS tracking");
  fdNdPtAnalysis->SetEventCuts(evtCuts);
  fdNdPtAnalysis->SetAcceptanceCuts(accCuts);
  fdNdPtAnalysis->SetTrackCuts(esdTrackCuts);
  //fdNdPtAnalysis->SetBackgroundCuts(backCuts);
  fdNdPtAnalysis->SetAnalysisMode(analysisMode);
  fdNdPtAnalysis->SetParticleMode(particleMode);
  //fdNdPtAnalysis->SetTrigger(trigger);
  fdNdPtAnalysis->SetTriggerMask(AliVEvent::kMB);
  //fdNdPtAnalysis->SetTriggerMask(AliVEvent::kEMC1);
  if(hasMC)
  {
    //physTrigSel->SetAnalyzeMC();
    //fdNdPtAnalysis->SetPhysicsTriggerSelection(physTrigSel);
    fdNdPtAnalysis->SetUseMCInfo(kTRUE);
    fdNdPtAnalysis->SetHistogramsOn(kTRUE);
    //fdNdPtAnalysis->SetHistogramsOn(kFALSE);
  }
  else { // online trigger
//     physTrigSel->SetUseBXNumbers();
//     physTrigSel->SetComputeBG();
//     fdNdPtAnalysis->SetPhysicsTriggerSelection(physTrigSel);
  }

    // change binning
    Int_t multNbins = 252;
    Double_t binsMult[253];
    for (int i=0; i<=multNbins; i++) { binsMult[i] = -0.5 + i; }
    binsMult[252] = 1000.;
    // change binning
    const Int_t ptNbins = 81;
    Double_t bins[82] = {0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 18.0, 20.0, 22.0, 24.0, 26.0, 28.0, 30.0, 32.0, 34.0, 36.0, 40.0, 45.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 110.0, 120.0, 130.0, 140.0, 150.0, 160.0, 180.0, 200.0};
    Double_t* binsPt = new Double_t[82];
    for (int i=0; i<82; i++) {binsPt[i] = bins[i];}
    fdNdPtAnalysis->SetBinsPt(ptNbins, binsPt);
    fdNdPtAnalysis->SetBinsPtCorr(ptNbins, binsPt);
    fdNdPtAnalysis->SetBinsMult(multNbins, binsMult);

    // for mean pt use tpc tracks as mult. estimator
    AlidNdPtAcceptanceCuts *multAccCuts = new AlidNdPtAcceptanceCuts("MultaccCuts","Geom. acceptance cuts");
    multAccCuts->SetEtaRange(-0.3,0.3);
    multAccCuts->SetPtRange(0.0,1.e10);
    AliESDtrackCuts* multTrackCuts = CreatedNdPtTrackCuts(222);
    fdNdPtAnalysis->SetMultAcceptanceCuts(multAccCuts);
    fdNdPtAnalysis->SetMultTrackCuts(multTrackCuts);

  // Add analysis object
  task->AddAnalysisObject( fdNdPtAnalysis );

  // Add task
  mgr->AddTask(task);

  // Create containers for input
  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
  mgr->ConnectInput(task, 0, cinput);

  AliAnalysisDataContainer *coutput = mgr->CreateContainer("eperezl_dNdPtpp_TPCITS",
                                                           TList::Class(),
                                                           AliAnalysisManager::kOutputContainer,
                                                           Form("%s:dNdPtHistos", mgr->GetCommonFileName()));

  mgr->ConnectOutput(task, 1, coutput);

}

<|endoftext|>


<commit_before><commit_msg>Library names have changed thanks to the "layer" changes<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2014-2016 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/

#ifndef PEGTL_PARSE_HH
#define PEGTL_PARSE_HH

#include <string>
#include <cstring>
#include <sstream>

#include "normal.hh"
#include "nothing.hh"
#include "apply_mode.hh"
#include "memory_input.hh"
#include "buffer_input.hh"

#include "internal/cstream_reader.hh"
#include "internal/cstring_reader.hh"
#include "internal/istream_reader.hh"

namespace pegtl
{
   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Input, typename ... States >
   bool parse_input( Input & in, States && ... st )
   {
      return Control< Rule >::template match< apply_mode::ACTION, Action, Control >( in, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >
   bool parse_arg( const int argn, char ** argv, States && ... st )
   {
      std::ostringstream os;
      os << "argv[" << argn << ']';
      const std::string source = os.str();
      memory_input in( 1, 0, argv[ argn ], argv[ argn ] + ::strlen( argv[ argn ] ), source.c_str() );
      return parse_input< Rule, Action, Control >( in, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >
   bool parse_memory( const char * data, const char * dend, const char * source, States && ... st )
   {
      memory_input in( 1, 0, data, dend, source );
      return parse_input< Rule, Action, Control >( in, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >
   bool parse_memory( const char * data, const std::size_t size, const char * source, States && ... st )
   {
      return parse_memory< Rule, Action, Control >( data, data + size, source, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >
   bool parse_string( const std::string & data, const std::string & source, States && ... st )
   {
      return parse_memory< Rule, Action, Control >( data.data(), data.data() + data.size(), source.c_str(), st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >
   bool parse_cstream( std::FILE * stream, const char * source, const std::size_t maximum, States && ... st )
   {
      buffer_input< internal::cstream_reader > in( source, maximum, stream );
      return parse_input< Rule, Action, Control >( in, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >
   bool parse_stdin( const std::size_t maximum, States && ... st )
   {
      return parse_cstream< Rule, Action, Control >( stdin, "stdin", maximum, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >
   bool parse_cstring( const char * string, const char * source, const std::size_t maximum, States && ... st )
   {
      buffer_input< internal::cstring_reader > in( source, maximum, string );
      return parse_input< Rule, Action, Control >( in, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >
   bool parse_istream( std::istream & stream, const std::string & source, const std::size_t maximum, States && ... st )
   {
      buffer_input< internal::istream_reader > in( source.c_str(), maximum, stream );
      return parse_input< Rule, Action, Control >( in, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename Input, typename ... States >
   bool parse_input_nested( const Outer & oi, Input & in, States && ... st )
   {
      try {
         return Control< Rule >::template match< apply_mode::ACTION, Action, Control >( in, st ... );
      }
      catch ( parse_error & e ) {
         e.positions.push_back( position_info( oi ) );
         throw;
      }
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >
   bool parse_memory_nested( const Outer & oi, const char * data, const char * dend, const char * source, States && ... st )
   {
      memory_input in( 1, 0, data, dend, source );
      return parse_input_nested< Rule, Action, Control >( oi, in, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >
   bool parse_memory_nested( const Outer & oi, const char * data, const std::size_t size, const char * source, States && ... st )
   {
      return parse_memory_nested< Rule, Action, Control >( oi, data, data + size, source, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >
   bool parse_string_nested( const Outer & oi, const std::string & data, const std::string & source, States && ... st )
   {
      return parse_memory_nested< Rule, Action, Control >( oi, data.data(), data.data() + data.size(), source.c_str(), st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >
   bool parse_cstream_nested( const Outer & oi, std::FILE * stream, const char * source, const std::size_t maximum, States && ... st )
   {
      buffer_input< internal::cstream_reader > in( source, maximum, stream );
      return parse_input_nested< Rule, Action, Control >( oi, in, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >
   bool parse_cstring_nested( const Outer & oi, const char * string, const char * source, const std::size_t maximum, States && ... st )
   {
      buffer_input< internal::cstring_reader > in( source, maximum, string );
      return parse_input_nested< Rule, Action, Control >( oi, in, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >
   bool parse_istream( const Outer & oi, std::istream & stream, const std::string & source, const std::size_t maximum, States && ... st )
   {
      buffer_input< internal::istream_reader > in( source.c_str(), maximum, stream );
      return parse_input_nested< Rule, Action, Control >( oi, in, st ... );
   }

} // pegtl

#endif
<commit_msg>Add assert() to assist clang-tidy<commit_after>// Copyright (c) 2014-2016 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/

#ifndef PEGTL_PARSE_HH
#define PEGTL_PARSE_HH

#include <string>
#include <cstring>
#include <sstream>

#include "normal.hh"
#include "nothing.hh"
#include "apply_mode.hh"
#include "memory_input.hh"
#include "buffer_input.hh"

#include "internal/cstream_reader.hh"
#include "internal/cstring_reader.hh"
#include "internal/istream_reader.hh"

namespace pegtl
{
   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Input, typename ... States >
   bool parse_input( Input & in, States && ... st )
   {
      return Control< Rule >::template match< apply_mode::ACTION, Action, Control >( in, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >
   bool parse_arg( const int argn, char ** argv, States && ... st )
   {
      std::ostringstream os;
      os << "argv[" << argn << ']';
      const std::string source = os.str();
      assert( argv[ argn ] );
      memory_input in( 1, 0, argv[ argn ], argv[ argn ] + std::strlen( argv[ argn ] ), source.c_str() );
      return parse_input< Rule, Action, Control >( in, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >
   bool parse_memory( const char * data, const char * dend, const char * source, States && ... st )
   {
      memory_input in( 1, 0, data, dend, source );
      return parse_input< Rule, Action, Control >( in, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >
   bool parse_memory( const char * data, const std::size_t size, const char * source, States && ... st )
   {
      return parse_memory< Rule, Action, Control >( data, data + size, source, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >
   bool parse_string( const std::string & data, const std::string & source, States && ... st )
   {
      return parse_memory< Rule, Action, Control >( data.data(), data.data() + data.size(), source.c_str(), st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >
   bool parse_cstream( std::FILE * stream, const char * source, const std::size_t maximum, States && ... st )
   {
      buffer_input< internal::cstream_reader > in( source, maximum, stream );
      return parse_input< Rule, Action, Control >( in, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >
   bool parse_stdin( const std::size_t maximum, States && ... st )
   {
      return parse_cstream< Rule, Action, Control >( stdin, "stdin", maximum, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >
   bool parse_cstring( const char * string, const char * source, const std::size_t maximum, States && ... st )
   {
      buffer_input< internal::cstring_reader > in( source, maximum, string );
      return parse_input< Rule, Action, Control >( in, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename ... States >
   bool parse_istream( std::istream & stream, const std::string & source, const std::size_t maximum, States && ... st )
   {
      buffer_input< internal::istream_reader > in( source.c_str(), maximum, stream );
      return parse_input< Rule, Action, Control >( in, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename Input, typename ... States >
   bool parse_input_nested( const Outer & oi, Input & in, States && ... st )
   {
      try {
         return Control< Rule >::template match< apply_mode::ACTION, Action, Control >( in, st ... );
      }
      catch ( parse_error & e ) {
         e.positions.push_back( position_info( oi ) );
         throw;
      }
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >
   bool parse_memory_nested( const Outer & oi, const char * data, const char * dend, const char * source, States && ... st )
   {
      memory_input in( 1, 0, data, dend, source );
      return parse_input_nested< Rule, Action, Control >( oi, in, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >
   bool parse_memory_nested( const Outer & oi, const char * data, const std::size_t size, const char * source, States && ... st )
   {
      return parse_memory_nested< Rule, Action, Control >( oi, data, data + size, source, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >
   bool parse_string_nested( const Outer & oi, const std::string & data, const std::string & source, States && ... st )
   {
      return parse_memory_nested< Rule, Action, Control >( oi, data.data(), data.data() + data.size(), source.c_str(), st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >
   bool parse_cstream_nested( const Outer & oi, std::FILE * stream, const char * source, const std::size_t maximum, States && ... st )
   {
      buffer_input< internal::cstream_reader > in( source, maximum, stream );
      return parse_input_nested< Rule, Action, Control >( oi, in, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >
   bool parse_cstring_nested( const Outer & oi, const char * string, const char * source, const std::size_t maximum, States && ... st )
   {
      buffer_input< internal::cstring_reader > in( source, maximum, string );
      return parse_input_nested< Rule, Action, Control >( oi, in, st ... );
   }

   template< typename Rule, template< typename ... > class Action = nothing, template< typename ... > class Control = normal, typename Outer, typename ... States >
   bool parse_istream( const Outer & oi, std::istream & stream, const std::string & source, const std::size_t maximum, States && ... st )
   {
      buffer_input< internal::istream_reader > in( source.c_str(), maximum, stream );
      return parse_input_nested< Rule, Action, Control >( oi, in, st ... );
   }

} // pegtl

#endif
<|endoftext|>


<commit_before> /**
 * \file      main.cc
 * \brief     Program for giving an indication when a rfid card has been detected, a database connection has been made and a string has been encrypted
 * \author    Tim IJntema, Stefan de Beer, Arco Gelderblom, Rik Honcoop, Koen de Groot, Ricardo Bouwman, Philippe Zwietering, Luuk Steeman, Leo Jenneskens, Jeremy Ruijzenaars
 * \copyright Copyright (c) 2017, The R2D2 Team
 * \license   See LICENSE
 */

#include "mysql.hh"
#include "mfrc522.hh"
#include "led-controller.hh"
#include "matrix-keypad.hh"
#include "config-file-parser.hh"
#include "databasemanager.hh"

#include <wiringPi.h>
#include <wiringPiSPI.h>

#include <iostream>

struct MFAuthentData {
    uint8_t command_code;
    uint8_t blockAddress;
    uint8_t sectorKey[5];
    uint8_t serialNumber[4];
};

int main(int argc, char **argv) {
#define USING_PIN           // Comment out this rule if not using a pincode on your application
    try {

        std::string ip;
        std::string username;
        std::string password;

        //int encryptionKey;

        ConfigFileParser factory("database-config.txt");
        factory.loadDatabaseSettings(ip, username, password);

        MySql connection;

        connection.connectTo(ip, username, password);
        connection.selectDatabase("R2D2");

        std::cout << "Made connection to the database\n";
        wiringPiSetup();
        wiringPiSPISetup(0, 10000000);//max speed for mfrc522 is 10Mhz
        MFRC522 rfid;
        rfid.PCD_Init();

        //Keypad pinSetup
        const int keypadRow[] = {15, 16, 1, 4};
        const int keypadColumn[] = {8, 9, 7, 2};

        //Keypad objects
        MatrixKeypad keypad(keypadRow, keypadColumn, 4);

        LedController led(0);
std::cerr<<"lukkie" ;
        while (true) {
            delay(1000);
            std::cout << "\n\nWaiting for rfid tag: \n";

             if(!rfid.PICC_IsNewCardPresent())
                continue;

            if(!rfid.PICC_ReadCardSerial())
                continue;
                std::cerr<<"rickaerdotje" ;

            // Hier moet het database gedeelte komen om te checken of je ID al in de database staat

#ifdef USING_PIN
            MFRC522::MIFARE_Key key = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
            if( 1 !=rfid.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, (byte)0x05, &key, &rfid.uid))
                continue;
            //read pincode
            std::string id;
            for(byte i = 0; i < rfid.uid.size; ++i){
                std::cerr <<"0";
                if(rfid.uid.uidByte[i] < 0x10){
                    id +=(char)rfid.uid.uidByte[i];
                    std::cerr<<"1" ;
                }
                else{
                    id += (char)rfid.uid.uidByte[i];
                        std::cerr<<"2" ;
                }
            }
                std::cerr<<"philips " ;
            DatabaseManager information;
            information.connectTo(ip,username,password);
            information.selectDatabase("R2D2");
            if ( information.isCardInDatabase(id)){
                std::cout << " id in database";
            }

            byte bufferSize = (byte)18;
            byte readArray[18] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
            rfid.MIFARE_Read((byte)0x05,readArray, &bufferSize);
            std::cout << "Readarray contains: \n";
            for (int i = 0; i < 18; i++){
                std::cout <<(int)readArray[i] << '\n';
            }

            //pincode invoeren
            std::cout << "Input PIN and finish with #\n";
            std::string value = keypad.getString();

            // write pincode
	       	byte  writeArray[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
		    int index = 0;
            for(auto c :value){
                if (c >47 && c < 58 ){
                    int number = c - 48;
                    writeArray[index++] = (byte)number;
		        }
	        }
            rfid.MIFARE_Write((byte)0x05, writeArray, (byte)16);
            for (int i = 0; i < 16; i++){
                std::cout <<(int)writeArray[i] << '\n';
            }

#endif

            rfid.PCD_StopCrypto1();

            for(byte i = 0; i < rfid.uid.size; ++i){
                if(rfid.uid.uidByte[i] < 0x10){
                    printf(" 0");
                    printf("%X",rfid.uid.uidByte[i]);
                }
                else{
                    printf(" ");
                    printf("%X", rfid.uid.uidByte[i]);
                }
            }

            connection.executeQuery("SELECT * FROM RFID");

//            std::cout << "Database information: "
//                      << database.getAllCardIdFromDatabase()
//                      << '\n';

            led.blinkLed(1000);
        }
    } catch (const std::string &error) {
        std::cerr << error << '\n';
        exit(EXIT_FAILURE);
    } catch (...) {
        std::cerr << "Something went wrong\n";
        exit(EXIT_FAILURE);
    }
    return 0;
}

<commit_msg> [RFID-03] debuging database<commit_after> /**
 * \file      main.cc
 * \brief     Program for giving an indication when a rfid card has been detected, a database connection has been made and a string has been encrypted
 * \author    Tim IJntema, Stefan de Beer, Arco Gelderblom, Rik Honcoop, Koen de Groot, Ricardo Bouwman, Philippe Zwietering, Luuk Steeman, Leo Jenneskens, Jeremy Ruijzenaars
 * \copyright Copyright (c) 2017, The R2D2 Team
 * \license   See LICENSE
 */

#include "mysql.hh"
#include "mfrc522.hh"
#include "led-controller.hh"
#include "matrix-keypad.hh"
#include "config-file-parser.hh"
#include "databasemanager.hh"

#include <wiringPi.h>
#include <wiringPiSPI.h>

#include <iostream>

struct MFAuthentData {
    uint8_t command_code;
    uint8_t blockAddress;
    uint8_t sectorKey[5];
    uint8_t serialNumber[4];
};

int main(int argc, char **argv) {
#define USING_PIN           // Comment out this rule if not using a pincode on your application
    try {

        std::string ip;
        std::string username;
        std::string password;

        //int encryptionKey;

        ConfigFileParser factory("database-config.txt");
        factory.loadDatabaseSettings(ip, username, password);

        MySql connection;

        connection.connectTo(ip, username, password);
        connection.selectDatabase("R2D2");

        std::cout << "Made connection to the database\n";
        wiringPiSetup();
        wiringPiSPISetup(0, 10000000);//max speed for mfrc522 is 10Mhz
        MFRC522 rfid;
        rfid.PCD_Init();

        //Keypad pinSetup
        const int keypadRow[] = {15, 16, 1, 4};
        const int keypadColumn[] = {8, 9, 7, 2};

        //Keypad objects
        MatrixKeypad keypad(keypadRow, keypadColumn, 4);

        LedController led(0);
        DatabaseManager information;
        information.connectTo(ip,username,password);
        information.selectDatabase("R2D2");
        while (true) {
            delay(1000);
            std::cout << "\n\nWaiting for rfid tag: \n";

             if(!rfid.PICC_IsNewCardPresent())
                continue;

            if(!rfid.PICC_ReadCardSerial())
                continue;

            // Hier moet het database gedeelte komen om te checken of je ID al in de database staat
            std::string id;
            for(byte i = 0; i < rfid.uid.size; ++i){

                if(rfid.uid.uidByte[i] < 0x10){
                    id +=(char)rfid.uid.uidByte[i];

                }
                else{
                    id += (char)rfid.uid.uidByte[i];

                }
            }
            if ( information.isCardInDatabase(id)){
                std::cout << " id in database";
            }

#ifdef USING_PIN
            MFRC522::MIFARE_Key key = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
            if( 1 !=rfid.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, (byte)0x05, &key, &rfid.uid))
                continue;
            //read pincode

            byte bufferSize = (byte)18;
            byte readArray[18] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
            rfid.MIFARE_Read((byte)0x05,readArray, &bufferSize);
            std::cout << "Readarray contains: \n";
            for (int i = 0; i < 18; i++){
                std::cout <<(int)readArray[i] << '\n';
            }

            //pincode invoeren
            std::cout << "Input PIN and finish with #\n";
            std::string value = keypad.getString();

            // write pincode
	       	byte  writeArray[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
		    int index = 0;
            for(auto c :value){
                if (c >47 && c < 58 ){
                    int number = c - 48;
                    writeArray[index++] = (byte)number;
		        }
	        }
            rfid.MIFARE_Write((byte)0x05, writeArray, (byte)16);
            for (int i = 0; i < 16; i++){
                std::cout <<(int)writeArray[i] << '\n';
            }

#endif

            rfid.PCD_StopCrypto1();

            for(byte i = 0; i < rfid.uid.size; ++i){
                if(rfid.uid.uidByte[i] < 0x10){
                    printf(" 0");
                    printf("%X",rfid.uid.uidByte[i]);
                }
                else{
                    printf(" ");
                    printf("%X", rfid.uid.uidByte[i]);
                }
            }

            connection.executeQuery("SELECT * FROM RFID");

//            std::cout << "Database information: "
//                      << database.getAllCardIdFromDatabase()
//                      << '\n';

            led.blinkLed(1000);
        }
    } catch (const std::string &error) {
        std::cerr << error << '\n';
        exit(EXIT_FAILURE);
    } catch (...) {
        std::cerr << "Something went wrong\n";
        exit(EXIT_FAILURE);
    }
    return 0;
}

<|endoftext|>