<commit_before>/*
 * Copyright 2009-2018 The VOTCA Development Team (http://www.votca.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 <votca/xtp/kmccalculator.h>
#include <votca/xtp/gnode.h>
#include <votca/tools/constants.h>
#include <boost/format.hpp>
#include <votca/ctp/topology.h>
#include <locale>

using namespace std;

namespace votca {
    namespace xtp {
        KMCCalculator::KMCCalculator(){};

    void KMCCalculator::LoadGraph(ctp::Topology *top) {

        std::vector< ctp::Segment* >& seg = top->Segments();

        if(seg.size()<1){
          throw std::runtime_error("Your sql file contains no segments!");
        }

        for (unsigned i = 0; i < seg.size(); i++) {
            GNode *newNode = new GNode();
            newNode->ReadfromSegment(seg[i], _carriertype);
            if (tools::wildcmp(_injection_name.c_str(), seg[i]->getName().c_str())) {
                newNode->injectable = true;
            } else {
                newNode->injectable = false;
            }
            _nodes.push_back(newNode);
        }

        ctp::QMNBList &nblist = top->NBList();
        if(nblist.size()<1){
          throw std::runtime_error("Your sql file contains no pairs!");
        }

        for (ctp::QMNBList::iterator it = nblist.begin(); it < nblist.end(); ++it) {
            _nodes[(*it)->Seg1()->getId()-1]->AddEventfromQmPair(*it, _carriertype);
            _nodes[(*it)->Seg2()->getId()-1]->AddEventfromQmPair(*it, _carriertype);
        }

        unsigned events=0;
        unsigned max=std::numeric_limits<unsigned>::min();
        unsigned min=std::numeric_limits<unsigned>::max();
        minlength=std::numeric_limits<double>::max();
        double maxlength=0;
        for(const auto& node:_nodes){

            unsigned size=node->events.size();
            for( const auto& event:node->events){
                if(event.decayevent){continue;}
                double dist=abs(event.dr);
                if(dist>maxlength){
                    maxlength=dist;
                } else if(dist<minlength){
                    minlength=dist;
                }
            }

            events+=size;
            if(size==0){
                cout<<"Node "<<node->id<<" has 0 jumps"<<endl;
            }
            else if(size<min){
                min=size;
            }
            else if(size>max){
                max=size;
            }
        }
        double avg=double(events)/double(_nodes.size());
        double deviation=0.0;
        for(const auto& node:_nodes){
            double size=node->events.size();
            deviation+=(size-avg)*(size-avg);
        }
        deviation=std::sqrt(deviation/double(_nodes.size()));

        cout<<"Nblist has "<<nblist.size()<<" pairs. Nodes contain "<<events<<" jump events"<<endl;
        cout<<"with avg="<<avg<<" std="<<deviation<<" max="<<max<<" min="<<min<<endl;
        cout<<"Minimum jumpdistance ="<<minlength<<" nm Maximum distance ="<<maxlength<<" nm"<<endl;
        cout<<"Grouping into "<<lengthdistribution<<" boxes"<<endl;
        lengthresolution=(1.00001*maxlength-minlength)/double(lengthdistribution);
        cout<<"Resolution is "<<lengthresolution<<" nm"<<endl;

        _jumplengthdistro=std::vector<long unsigned>(lengthdistribution,0);
        _jumplengthdistro_weighted=std::vector<double>(lengthdistribution,0);

        cout << "spatial density: " << _numberofcharges / top->BoxVolume() << " nm^-3" << endl;

        for (unsigned int i = 0; i < _nodes.size(); i++) {
            _nodes[i]->InitEscapeRate();
            _nodes[i]->MakeHuffTree();
        }

        return;
    }

        void KMCCalculator::ResetForbiddenlist(std::vector<int> &forbiddenid) {
            forbiddenid.clear();
            return;
        }

        void KMCCalculator::AddtoForbiddenlist(int id, std::vector<int> &forbiddenid) {
            forbiddenid.push_back(id);
            return;
        }

        bool KMCCalculator::CheckForbidden(int id,const std::vector<int> &forbiddenlist) {
            bool forbidden = false;
            for (unsigned int i = 0; i < forbiddenlist.size(); i++) {
                if (id == forbiddenlist[i]) {
                    forbidden = true;
                    break;
                }
            }
            return forbidden;
        }

        bool KMCCalculator::CheckSurrounded(GNode* node,const std::vector<int> & forbiddendests) {
            bool surrounded = true;
            for (unsigned  i = 0; i < node->events.size(); i++) {
                bool thisevent_possible = true;
                for (unsigned int j = 0; j < forbiddendests.size(); j++) {
                    if (node->events[i].destination == forbiddendests[j]) {
                        thisevent_possible = false;
                        break;
                    }
                }
                if (thisevent_possible == true) {
                    surrounded = false;
                    break;
                }
            }
            return surrounded;
        }

        std::string KMCCalculator::CarrierInttoLongString(int carriertype){
            std::string name="";
            if (carriertype==-1){
                name="electron";
            }
            else if(carriertype==1){
                name="hole";
            }
            else if(carriertype==2){
                name="singlet";
            }
            else if(carriertype==3){
                name="triplet";
            }
            else{
                throw runtime_error((boost::format("Carriertype %i not known") % carriertype).str());
            }
            return name;
        }

        std::string KMCCalculator::CarrierInttoShortString(int carriertype){
            std::string name="";
            if (carriertype==-1){
                name="e";
            }
            else if(carriertype==1){
                name="h";
            }
            else if(carriertype==2){
                name="s";
            }
            else if(carriertype==3){
                name="t";
            }
            else{
                throw runtime_error((boost::format("Carriertype %i not known") % carriertype).str());
            }
            return name;
        }

         int KMCCalculator::StringtoCarriertype(std::string name){
             char firstcharacter=std::tolower(name.at(0), std::locale());
             int carriertype=0;
            if (firstcharacter=='e'){
                carriertype=-1;
            }
            else if(firstcharacter=='h'){
                carriertype=1;
            }
            else if(firstcharacter=='s'){
                carriertype=2;
            }
            else if(firstcharacter=='t'){
                carriertype=3;
            }
            else{
                throw runtime_error((boost::format("Carriername %s not known") % name).str());
            }
            return carriertype;
        }

         void KMCCalculator::RandomlyCreateCharges(){

        cout << "looking for injectable nodes..." << endl;
        for (unsigned int i = 0; i < _numberofcharges; i++) {
            Chargecarrier *newCharge = new Chargecarrier;
            newCharge->id = i;
            RandomlyAssignCarriertoSite(newCharge);

            cout << "starting position for charge " << i + 1 << ": segment " << newCharge->getCurrentNodeId()+1 << endl;
            _carriers.push_back(newCharge);
        }
        return;
         }

         void KMCCalculator::RandomlyAssignCarriertoSite(Chargecarrier* Charge){
            int nodeId_guess=-1;
            do{
            nodeId_guess=_RandomVariable.rand_uniform_int(_nodes.size());
            }
            while (_nodes[nodeId_guess]->occupied || _nodes[nodeId_guess]->injectable==false ); // maybe already occupied? or maybe not injectable?
            if (Charge->hasNode()){
                Charge->jumpfromCurrentNodetoNode(_nodes[nodeId_guess]);
            }
            else{
            Charge->settoNote(_nodes[nodeId_guess]);
            }
             return;
         }

        void KMCCalculator::InitialRates() {

            cout << endl << "Calculating initial Marcus rates." << endl;
            cout << "    Temperature T = " << _temperature << " K." << endl;

            cout << "    carriertype: " << CarrierInttoLongString(_carriertype) << endl;
            unsigned numberofsites = _nodes.size();
            cout << "    Rates for " << numberofsites << " sites are computed." << endl;
            double charge=0.0;
            if (_carriertype == -1)
            {
                charge = -1.0;
            }
            else if (_carriertype == 1)
            {
                charge = 1.0;
            }
            cout<<"electric field ="<<_field<<" V/nm"<<endl;

            double maxreldiff = 0;
            double maxrate=0;
            double minrate=std::numeric_limits<double>::max();
            int totalnumberofrates = 0;
            for (unsigned int i = 0; i < numberofsites; i++) {
                unsigned numberofneighbours = _nodes[i]->events.size();
                for (unsigned int j = 0; j < numberofneighbours; j++) {
                    if(_nodes[i]->events[j].decayevent){
                        //if event is a decay event there is no point in calculating its rate, because it already has that from the reading in.
                        continue;
                    }

                    double destindex = _nodes[i]->events[j].destination;
                    double reorg = _nodes[i]->reorg_intorig + _nodes[destindex]->reorg_intdest + _nodes[i]->events[j].reorg_out;
                     if(std::abs(reorg)<1e-12){
                        throw std::runtime_error("Reorganisation energy for a pair is extremly close to zero,\n"
                                " you probably forgot to import reorganisation energies into your sql file.");
                    }
                    double dG_Field =0.0;
                    if(charge!=0.0){
                        dG_Field=charge * (_nodes[i]->events[j].dr*_field);
                    }
                    double dG_Site = _nodes[destindex]->siteenergy - _nodes[i]->siteenergy;
                    double dG=dG_Site-dG_Field;
                    double J2 = _nodes[i]->events[j].Jeff2;

                    double rate = 2 * tools::conv::Pi / tools::conv::hbar * J2 / sqrt(4 * tools::conv::Pi * reorg * tools::conv::kB * _temperature)
                    * exp(-(dG + reorg)*(dG + reorg) / (4 * reorg * tools::conv::kB * _temperature));

                    // calculate relative difference compared to values in the table
                    double reldiff = (_nodes[i]->events[j].rate - rate) / _nodes[i]->events[j].rate;
                    if (reldiff > maxreldiff) {
                        maxreldiff = reldiff;
                    }
                    reldiff = (_nodes[i]->events[j].rate - rate) / rate;
                    if (reldiff > maxreldiff) {
                        maxreldiff = reldiff;
                    }

                    // set rates to calculated values
                    _nodes[i]->events[j].rate = rate;
                    _nodes[i]->events[j].initialrate = rate;

                    if(rate>maxrate){
                        maxrate=rate;
                    }
                    else if(rate<minrate){
                        minrate=rate;
                    }

                    totalnumberofrates++;
                }

            }
             // Initialise escape rates
                for (auto* node:_nodes) {
                    node->InitEscapeRate();
                    node->MakeHuffTree();
                }

            cout << "    " << totalnumberofrates << " rates have been calculated." << endl;
            cout<< " Largest rate="<<maxrate<<" 1/s  Smallest rate="<<minrate<<" 1/s"<<endl;
            if (maxreldiff < 0.01) {
                cout << "    Good agreement with rates in the state file. Maximal relative difference: " << maxreldiff * 100 << " %" << endl;
            } else {
                cout << "    WARNING: Rates differ from those in the state file up to " << maxreldiff * 100 << " %." << " If the rates in the state file are calculated for a different temperature/field or if they are not Marcus rates, this is fine. Otherwise something might be wrong here." << endl;
            }

            return;
        }

        double KMCCalculator::Promotetime(double cumulated_rate){
            double dt = 0;
                double rand_u = 1 - _RandomVariable.rand_uniform();
                while (rand_u == 0) {
                    cout << "WARNING: encountered 0 as a random variable! New try." << endl;
                    rand_u = 1 - _RandomVariable.rand_uniform();
                }
                dt = -1 / cumulated_rate * log(rand_u);
            return dt;
        }

        GLink* KMCCalculator::ChooseHoppingDest(GNode* node){
            double u = 1 - _RandomVariable.rand_uniform();
            return node->findHoppingDestination(u);
        }

        Chargecarrier* KMCCalculator::ChooseAffectedCarrier(double cumulated_rate){
            if(_carriers.size()==1){
                return _carriers[0];
            }
            Chargecarrier* carrier=NULL;
            double u = 1 - _RandomVariable.rand_uniform();
            for (unsigned int i = 0; i < _numberofcharges; i++) {
                u -= _carriers[i]->getCurrentEscapeRate() / cumulated_rate;

                if (u <= 0 || i==_numberofcharges-1) {

                    carrier = _carriers[i];
                    break;}

            }
            return carrier;
        }

        void KMCCalculator::AddtoJumplengthdistro(const GLink* event,double dt){
            if(dolengthdistributon){
            double dist=abs(event->dr)-minlength;
            int index=int(dist/lengthresolution);

            _jumplengthdistro[index]++;
            _jumplengthdistro_weighted[index]+=dt;

            }
            return;
        }

        void KMCCalculator::PrintJumplengthdistro(){
            if(dolengthdistributon){
            long unsigned noofjumps=0;

            double weightedintegral=0;
            for(unsigned i=0;i<_jumplengthdistro.size();++i){
                noofjumps+=_jumplengthdistro[i];
                weightedintegral+=_jumplengthdistro_weighted[i];
            }
            double noofjumps_double=double(noofjumps);
            cout<<"Total number of jumps: "<<noofjumps<<endl;
            cout<<" distance[nm] |   # of jumps   | # of jumps [%] | .w. by dist [nm] | w. by timestep [%]"<<endl;
            cout<<"------------------------------------------------------------------------------------"<<endl;
            for(unsigned i=0;i<_jumplengthdistro.size();++i){
                double dist=lengthresolution*(i+0.5)+minlength;
                double percent=_jumplengthdistro[i]/noofjumps_double;
                double rtimespercent=percent*dist;
                cout<<(boost::format("    %4.3f    | %15d |    %04.2f    |     %4.3e     |     %04.2f")
                            % (dist) % (_jumplengthdistro[i]) % (percent*100) %(rtimespercent) % (_jumplengthdistro_weighted[i]/weightedintegral*100)).str()<<endl;
            }
            cout<<"------------------------------------------------------------------------------------"<<endl;

            }
            return;
        }

    }
}
<commit_msg>Update kmccalculator.cc<commit_after>/*
 * Copyright 2009-2018 The VOTCA Development Team (http://www.votca.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 <votca/xtp/kmccalculator.h>
#include <votca/xtp/gnode.h>
#include <votca/tools/constants.h>
#include <boost/format.hpp>
#include <votca/ctp/topology.h>
#include <locale>

using namespace std;

namespace votca {
    namespace xtp {
        KMCCalculator::KMCCalculator(){};

    void KMCCalculator::LoadGraph(ctp::Topology *top) {

        std::vector< ctp::Segment* >& seg = top->Segments();

        if(seg.size()<1){
          throw std::runtime_error("Your sql file contains no segments!");
        }

        for (unsigned i = 0; i < seg.size(); i++) {
            GNode *newNode = new GNode();
            newNode->ReadfromSegment(seg[i], _carriertype);
            if (tools::wildcmp(_injection_name.c_str(), seg[i]->getName().c_str())) {
                newNode->injectable = true;
            } else {
                newNode->injectable = false;
            }
            _nodes.push_back(newNode);
        }

        ctp::QMNBList &nblist = top->NBList();
        if(nblist.size()<1){
          throw std::runtime_error("Your sql file contains no pairs!");
        }

        for (ctp::QMNBList::iterator it = nblist.begin(); it < nblist.end(); ++it) {
            _nodes[(*it)->Seg1()->getId()-1]->AddEventfromQmPair(*it, _carriertype);
            _nodes[(*it)->Seg2()->getId()-1]->AddEventfromQmPair(*it, _carriertype);
        }

        unsigned events=0;
        unsigned max=std::numeric_limits<unsigned>::min();
        unsigned min=std::numeric_limits<unsigned>::max();
        minlength=std::numeric_limits<double>::max();
        double maxlength=0;
        for(const auto& node:_nodes){

            unsigned size=node->events.size();
            for( const auto& event:node->events){
                if(event.decayevent){continue;}
                double dist=abs(event.dr);
                if(dist>maxlength){
                    maxlength=dist;
                } else if(dist<minlength){
                    minlength=dist;
                }
            }

            events+=size;
            if(size==0){
                cout<<"Node "<<node->id<<" has 0 jumps"<<endl;
            }
            else if(size<min){
                min=size;
            }
            else if(size>max){
                max=size;
            }
        }
        double avg=double(events)/double(_nodes.size());
        double deviation=0.0;
        for(const auto& node:_nodes){
            double size=node->events.size();
            deviation+=(size-avg)*(size-avg);
        }
        deviation=std::sqrt(deviation/double(_nodes.size()));

        cout<<"Nblist has "<<nblist.size()<<" pairs. Nodes contain "<<events<<" jump events"<<endl;
        cout<<"with avg="<<avg<<" std="<<deviation<<" max="<<max<<" min="<<min<<endl;
        cout<<"Minimum jumpdistance ="<<minlength<<" nm Maximum distance ="<<maxlength<<" nm"<<endl;
        cout<<"Grouping into "<<lengthdistribution<<" boxes"<<endl;
        lengthresolution=(1.00001*maxlength-minlength)/double(lengthdistribution);
        cout<<"Resolution is "<<lengthresolution<<" nm"<<endl;

        _jumplengthdistro=std::vector<long unsigned>(lengthdistribution,0);
        _jumplengthdistro_weighted=std::vector<double>(lengthdistribution,0);

        cout << "spatial density: " << _numberofcharges / top->BoxVolume() << " nm^-3" << endl;

        for (unsigned int i = 0; i < _nodes.size(); i++) {
            _nodes[i]->InitEscapeRate();
            _nodes[i]->MakeHuffTree();
        }

        return;
    }

        void KMCCalculator::ResetForbiddenlist(std::vector<int> &forbiddenid) {
            forbiddenid.clear();
            return;
        }

        void KMCCalculator::AddtoForbiddenlist(int id, std::vector<int> &forbiddenid) {
            forbiddenid.push_back(id);
            return;
        }

        bool KMCCalculator::CheckForbidden(int id,const std::vector<int> &forbiddenlist) {
            // cout << "forbidden list has " << forbiddenlist.size() << " entries" << endl;
            bool forbidden = false;
            for (unsigned int i = 0; i < forbiddenlist.size(); i++) {
                if (id == forbiddenlist[i]) {
                    forbidden = true;
                    //cout << "ID " << id << " has been found as element " << i << " (" << forbiddenlist[i]<< ") in the forbidden list." << endl;
                    break;
                }
            }
            return forbidden;
        }

        bool KMCCalculator::CheckSurrounded(GNode* node,const std::vector<int> & forbiddendests) {
            bool surrounded = true;
            for (unsigned  i = 0; i < node->events.size(); i++) {
                bool thisevent_possible = true;
                for (unsigned int j = 0; j < forbiddendests.size(); j++) {
                    if (node->events[i].destination == forbiddendests[j]) {
                        thisevent_possible = false;
                        break;
                    }
                }
                if (thisevent_possible == true) {
                    surrounded = false;
                    break;
                }
            }
            return surrounded;
        }

        std::string KMCCalculator::CarrierInttoLongString(int carriertype){
            std::string name="";
            if (carriertype==-1){
                name="electron";
            }
            else if(carriertype==1){
                name="hole";
            }
            else if(carriertype==2){
                name="singlet";
            }
            else if(carriertype==3){
                name="triplet";
            }
            else{
                throw runtime_error((boost::format("Carriertype %i not known") % carriertype).str());
            }
            return name;
        }

        std::string KMCCalculator::CarrierInttoShortString(int carriertype){
            std::string name="";
            if (carriertype==-1){
                name="e";
            }
            else if(carriertype==1){
                name="h";
            }
            else if(carriertype==2){
                name="s";
            }
            else if(carriertype==3){
                name="t";
            }
            else{
                throw runtime_error((boost::format("Carriertype %i not known") % carriertype).str());
            }
            return name;
        }

         int KMCCalculator::StringtoCarriertype(std::string name){
             char firstcharacter=std::tolower(name.at(0), std::locale());
             int carriertype=0;
            if (firstcharacter=='e'){
                carriertype=-1;
            }
            else if(firstcharacter=='h'){
                carriertype=1;
            }
            else if(firstcharacter=='s'){
                carriertype=2;
            }
            else if(firstcharacter=='t'){
                carriertype=3;
            }
            else{
                throw runtime_error((boost::format("Carriername %s not known") % name).str());
            }
            return carriertype;
        }

         void KMCCalculator::RandomlyCreateCharges(){

        cout << "looking for injectable nodes..." << endl;
        for (unsigned int i = 0; i < _numberofcharges; i++) {
            Chargecarrier *newCharge = new Chargecarrier;
            newCharge->id = i;
            RandomlyAssignCarriertoSite(newCharge);

            cout << "starting position for charge " << i + 1 << ": segment " << newCharge->getCurrentNodeId()+1 << endl;
            _carriers.push_back(newCharge);
        }
        return;
         }

         void KMCCalculator::RandomlyAssignCarriertoSite(Chargecarrier* Charge){
            int nodeId_guess=-1;
            do{
            nodeId_guess=_RandomVariable.rand_uniform_int(_nodes.size());
            }
            while (_nodes[nodeId_guess]->occupied || _nodes[nodeId_guess]->injectable==false ); // maybe already occupied? or maybe not injectable?
            if (Charge->hasNode()){
                Charge->jumpfromCurrentNodetoNode(_nodes[nodeId_guess]);
            }
            else{
            Charge->settoNote(_nodes[nodeId_guess]);
            }
             return;
         }

        void KMCCalculator::InitialRates() {

            cout << endl << "Calculating initial Marcus rates." << endl;
            cout << "    Temperature T = " << _temperature << " K." << endl;

            cout << "    carriertype: " << CarrierInttoLongString(_carriertype) << endl;
            unsigned numberofsites = _nodes.size();
            cout << "    Rates for " << numberofsites << " sites are computed." << endl;
            double charge=0.0;
            if (_carriertype == -1)
            {
                charge = -1.0;
            }
            else if (_carriertype == 1)
            {
                charge = 1.0;
            }
            cout<<"electric field ="<<_field<<" V/nm"<<endl;

            double maxreldiff = 0;
            double maxrate=0;
            double minrate=std::numeric_limits<double>::max();
            int totalnumberofrates = 0;
            for (unsigned int i = 0; i < numberofsites; i++) {
                unsigned numberofneighbours = _nodes[i]->events.size();
                for (unsigned int j = 0; j < numberofneighbours; j++) {
                    if(_nodes[i]->events[j].decayevent){
                        //if event is a decay event there is no point in calculating its rate, because it already has that from the reading in.
                        continue;
                    }

                    double destindex = _nodes[i]->events[j].destination;
                    double reorg = _nodes[i]->reorg_intorig + _nodes[destindex]->reorg_intdest + _nodes[i]->events[j].reorg_out;
                     if(std::abs(reorg)<1e-12){
                        throw std::runtime_error("Reorganisation energy for a pair is extremly close to zero,\n"
                                " you probably forgot to import reorganisation energies into your sql file.");
                    }
                    double dG_Field =0.0;
                    if(charge!=0.0){
                        dG_Field=charge * (_nodes[i]->events[j].dr*_field);
                    }
                    double dG_Site = _nodes[destindex]->siteenergy - _nodes[i]->siteenergy;
                    double dG=dG_Site-dG_Field;
                    double J2 = _nodes[i]->events[j].Jeff2;

                    double rate = 2 * tools::conv::Pi / tools::conv::hbar * J2 / sqrt(4 * tools::conv::Pi * reorg * tools::conv::kB * _temperature)
                    * exp(-(dG + reorg)*(dG + reorg) / (4 * reorg * tools::conv::kB * _temperature));

                    // calculate relative difference compared to values in the table
                    double reldiff = (_nodes[i]->events[j].rate - rate) / _nodes[i]->events[j].rate;
                    if (reldiff > maxreldiff) {
                        maxreldiff = reldiff;
                    }
                    reldiff = (_nodes[i]->events[j].rate - rate) / rate;
                    if (reldiff > maxreldiff) {
                        maxreldiff = reldiff;
                    }

                    // set rates to calculated values
                    _nodes[i]->events[j].rate = rate;
                    _nodes[i]->events[j].initialrate = rate;

                    if(rate>maxrate){
                        maxrate=rate;
                    }
                    else if(rate<minrate){
                        minrate=rate;
                    }

                    totalnumberofrates++;
                }

            }
             // Initialise escape rates
                for (auto* node:_nodes) {
                    node->InitEscapeRate();
                    node->MakeHuffTree();
                }

            cout << "    " << totalnumberofrates << " rates have been calculated." << endl;
            cout<< " Largest rate="<<maxrate<<" 1/s  Smallest rate="<<minrate<<" 1/s"<<endl;
            if (maxreldiff < 0.01) {
                cout << "    Good agreement with rates in the state file. Maximal relative difference: " << maxreldiff * 100 << " %" << endl;
            } else {
                cout << "    WARNING: Rates differ from those in the state file up to " << maxreldiff * 100 << " %." << " If the rates in the state file are calculated for a different temperature/field or if they are not Marcus rates, this is fine. Otherwise something might be wrong here." << endl;
            }

            return;
        }

        double KMCCalculator::Promotetime(double cumulated_rate){
            double dt = 0;
                double rand_u = 1 - _RandomVariable.rand_uniform();
                while (rand_u == 0) {
                    cout << "WARNING: encountered 0 as a random variable! New try." << endl;
                    rand_u = 1 - _RandomVariable.rand_uniform();
                }
                dt = -1 / cumulated_rate * log(rand_u);
            return dt;
        }

        GLink* KMCCalculator::ChooseHoppingDest(GNode* node){
            double u = 1 - _RandomVariable.rand_uniform();
            return node->findHoppingDestination(u);
        }

        Chargecarrier* KMCCalculator::ChooseAffectedCarrier(double cumulated_rate){
            if(_carriers.size()==1){
                return _carriers[0];
            }
            Chargecarrier* carrier=NULL;
            double u = 1 - _RandomVariable.rand_uniform();
            for (unsigned int i = 0; i < _numberofcharges; i++) {
                u -= _carriers[i]->getCurrentEscapeRate() / cumulated_rate;

                if (u <= 0 || i==_numberofcharges-1) {

                    carrier = _carriers[i];
                    break;}

            }
            return carrier;
        }

        void KMCCalculator::AddtoJumplengthdistro(const GLink* event,double dt){
            if(dolengthdistributon){
            double dist=abs(event->dr)-minlength;
            int index=int(dist/lengthresolution);

            _jumplengthdistro[index]++;
            _jumplengthdistro_weighted[index]+=dt;

            }
            return;
        }

        void KMCCalculator::PrintJumplengthdistro(){
            if(dolengthdistributon){
            long unsigned noofjumps=0;

            double weightedintegral=0;
            for(unsigned i=0;i<_jumplengthdistro.size();++i){
                noofjumps+=_jumplengthdistro[i];
                weightedintegral+=_jumplengthdistro_weighted[i];
            }
            double noofjumps_double=double(noofjumps);
            cout<<"Total number of jumps: "<<noofjumps<<endl;
            cout<<" distance[nm] |   # of jumps   | # of jumps [%] | .w. by dist [nm] | w. by timestep [%]"<<endl;
            cout<<"------------------------------------------------------------------------------------"<<endl;
            for(unsigned i=0;i<_jumplengthdistro.size();++i){
                double dist=lengthresolution*(i+0.5)+minlength;
                double percent=_jumplengthdistro[i]/noofjumps_double;
                double rtimespercent=percent*dist;
                cout<<(boost::format("    %4.3f    | %15d |    %04.2f    |     %4.3e     |     %04.2f")
                            % (dist) % (_jumplengthdistro[i]) % (percent*100) %(rtimespercent) % (_jumplengthdistro_weighted[i]/weightedintegral*100)).str()<<endl;
            }
            cout<<"------------------------------------------------------------------------------------"<<endl;

            }
            return;
        }

    }
}
<|endoftext|>


<commit_before>#include <iostream>

using namespace std;

int main() {
	cout << "Hola mundo" << endl;
}<commit_msg>Ahora pregunta el nombre.<commit_after>#include <iostream>
#include <string>

using namespace std;

int main() {
	string nombre;

	cout << "¿Como te llamas? " << endl;
	cin >> nombre;
	cout << "Hola " << nombre << endl;
}<|endoftext|>


<commit_before><commit_msg>Missing include<commit_after><|endoftext|>


<commit_before>#include "flDisplayObjectContainer.h"

namespace fl2d {

    //==============================================================
    // Constructor / Destructor
    //==============================================================

    //--------------------------------------------------------------
    flDisplayObjectContainer::flDisplayObjectContainer() {
        _typeID = FL_TYPE_DISPLAY_OBJECT_CONTAINER;
        _target = this;
        name("flDisplayObjectContainer");

        _mouseChildren = true;
        //_tabChildren = false;
    }

    //--------------------------------------------------------------
    flDisplayObjectContainer::~flDisplayObjectContainer() {
        _target = NULL;

        children.clear();

        _mouseChildren = false;
        //_tabChildren = false;
    }

    //==============================================================
    // Setup / Update / Draw
    //==============================================================

    //--------------------------------------------------------------
    void flDisplayObjectContainer::update() {
        //    float tempLeft = _rect->left();
        //    float tempRight = _rect->right();
        //    float tempTop = _rect->top();
        //    float tempBottom = _rect->bottom();
        //
        //    _rect->_setToPoint(0, 0);

        //        int i; int l;
        //        flDisplayObject* child;
        //
        //        l = children.size();
        //        for(i = 0; i < l; i++) {
        //            child = children[i];
        //            float n1 = child->x();
        //            float n2 = child->y();
        //            _rect->__expandTo(n1, n2);
        //            _rect->__expandTo(n1 + child->width(), n2 + child->height());
        //        }
        //    _rect->__expandTo(tempLeft, tempTop);
        //    _rect->__expandTo(tempRight, tempBottom);

        flDisplayObject::update();
    }

    //--------------------------------------------------------------
    void flDisplayObjectContainer::draw(bool applyMatrix) {
        if(!visible() && applyMatrix) return;

        // save off current state of blend enabled
        GLboolean blendEnabled;
        glGetBooleanv(GL_BLEND, &blendEnabled);
        // save off current state of src / dst blend functions
        GLint blendSrc; GLint blendDst;
        glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrc);
        glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDst);
        ofEnableAlphaBlending();

        GLboolean preLighting = glIsEnabled(GL_LIGHTING);
        GLboolean preDepthTest = glIsEnabled(GL_DEPTH_TEST);
        GLboolean preLineSmooth = glIsEnabled(GL_LINE_SMOOTH);
        GLboolean preMultiSample = glIsEnabled(GL_MULTISAMPLE);
        ofDisableLighting();
        glDisable(GL_DEPTH_TEST);
        if(_enabledSmoothing) { ofEnableSmoothing(); } else { ofDisableSmoothing(); }
        if(_enabledAntiAliasing) { ofEnableAntiAliasing(); } else { ofDisableAntiAliasing(); }

        //------------------------------------------
        //-- matrix transform.
        //        bool bIdentity = true;
        //        bIdentity = matrix().isIdentity();
        //        bIdentity = false;

        if(applyMatrix){
            //            glPushMatrix();
            ofPushMatrix();
            //            glMultMatrixf(matrix().getPtr());
            ofMultMatrix(_transform.matrix().getPtr());
        }

        ofPushStyle();
        //        ofSetColor(255, 255, 255, 255 * _compoundAlpha);
        _draw();

        for(int i = 0; i < children.size(); i++) {
            flDisplayObject* child;
            child = children[i];
            //child->drawOnFrame();
            child->draw();
        }
        ofPopStyle();

        if(applyMatrix){
//            glPopMatrix();
            ofPopMatrix();
        }
        //------------------------------------------

        if(preMultiSample == GL_TRUE) { ofEnableAntiAliasing(); } else { ofDisableAntiAliasing(); }
        if(preLineSmooth == GL_TRUE) { ofEnableSmoothing(); } else { ofDisableSmoothing(); }
        if(preDepthTest == GL_TRUE) { glEnable(GL_DEPTH_TEST); } else { glDisable(GL_DEPTH_TEST); }
        if(preLighting == GL_TRUE) { ofEnableLighting(); } else { ofDisableLighting(); }

        // restore saved state of blend enabled and blend functions
        if (blendEnabled) { glEnable(GL_BLEND); } else { glDisable(GL_BLEND); }
        glBlendFunc(blendSrc, blendDst);
    }

    //==============================================================
    // Public Method
    //==============================================================

    //--------------------------------------------------------------
    bool flDisplayObjectContainer::mouseChildren() { return _mouseChildren; }
    void flDisplayObjectContainer::mouseChildren(bool value) { _mouseChildren = value; }

    //--------------------------------------------------------------
    int flDisplayObjectContainer::numChildren() { return children.size(); }

    //--------------------------------------------------------------
    bool flDisplayObjectContainer::contains(flDisplayObject* child) {
        for(int i = 0; i < children.size(); i++) {
            if(children[i] == child) return true;
        }
        return false;
    }

    //--------------------------------------------------------------
    flDisplayObject* flDisplayObjectContainer::stage() { return _stage; }
    void flDisplayObjectContainer::stage(flDisplayObject* value) {
        //cout << "[flDisplayObjectContainer]stage(" << value << ")" << name() << endl;

        //΁valueL΁
        if(!_stage && value) {
            _stage = value;

            flEvent* event = new flEvent(flEvent::ADDED_TO_STAGE);
//            event->target(_target);
            dispatchEvent(event);
        }
        //L΁valueL΁
        if(_stage && !value) {
            _stage = value;

            flEvent* event = new flEvent(flEvent::REMOVED_FROM_STAGE);
//            event->target(_target);
            dispatchEvent(event);
        }

        for(int i = 0; i < children.size(); i++) {
            flDisplayObject* displayObject = children[i];
            displayObject->stage(_stage);
        }
    }

    //--------------------------------------------------------------
    flDisplayObject* flDisplayObjectContainer::addChild(flDisplayObject* child) {
        //    cout << "[flDisplayObjectContainer]addChild((" << child->name() << ")" << endl;
        //if(child == NULL) throw "TypeError: Error #2007:  child  null 񁘁";

        if(child->parent()){
            ((flDisplayObjectContainer*)(child->parent()))->removeChild(child);
        }

        children.push_back(child);
        child->stage(this->_stage);
        child->parent(this);
        child->level(this->level()+1);

        _updateRect();

        return child;
    }
    //--------------------------------------------------------------
    flDisplayObject* flDisplayObjectContainer::addChild(flDisplayObject* child, int x, int y) {
        //    cout << "[flDisplayObjectContainer]addChild(" << child->name() << ", " << x << ", " << y << ")" << endl;
        //if(child == NULL) throw "TypeError: Error #2007:  child  null 񁘁";

        if(child->parent()){
            ((flDisplayObjectContainer*)(child->parent()))->removeChild(child);
        }

        children.push_back(child);
        child->x(x);
        child->y(y);
        child->stage(this->_stage);
        child->parent(this);
        child->level(this->level()+1);

        _updateRect();

        return child;
    }

    //--------------------------------------------------------------
    flDisplayObject* flDisplayObjectContainer::addChildAt(flDisplayObject* child, int index) {
        //if(child == NULL) throw "TypeError: Error #2007:  child  null 񁘁";

        if(index < 0 || index > children.size() - 1) return NULL;
        if(child->parent()) {
            ((flDisplayObjectContainer*)(child->parent()))->removeChild(child);
        }
        children.insert(children.begin() + index, child);
        child->stage(this->_stage);
        child->parent(this);
        child->level(this->level() + 1);

        _updateRect();

        return child;
    }

    //--------------------------------------------------------------
    flDisplayObject* flDisplayObjectContainer::removeChild(flDisplayObject* child) {
        //if(child == NULL) throw "TypeError: Error #2007:  child  null 񁘁";

        //children()̉ӏ̓t@N^OƂŊOɏo_
        for(int i = 0; i < children.size(); i++){
            if(children[i] == child){
                child->stage(NULL);
                child->parent(NULL);
                child->level(-1);
                children.erase(children.begin() + i);

                _updateRect();

                return child;
            }
        }

        throw "flDisplayObjectContainer::removeChild\n";
    }

    //--------------------------------------------------------------
    flDisplayObject* flDisplayObjectContainer::removeChildAt(int index) {

        //children()̉ӏ̓t@N^OƂŊOɏo_
        if(index < 0 || index > children.size() - 1) return NULL;
        flDisplayObject* child;
        child = children[index];
        child->stage(NULL);
        child->parent(NULL);
        child->level(-1);
        children.erase(children.begin() + index);

        _updateRect();

        return child;
    }

    //--------------------------------------------------------------
    void flDisplayObjectContainer::removeAllChildren() {
        int i = 0;
        int t = children.size();

        flDisplayObject* child;

        for(i; i < t; i++){
            child = children[i];
            child->stage(NULL);
            child->parent(NULL);
            child->level(-1);
            children.erase(children.begin() + i);
            --i;
            --t;
        }

        _updateRect();
    }

    //--------------------------------------------------------------
    flDisplayObject* flDisplayObjectContainer::getChildAt(int index) {
        if(index < 0 || index > children.size() - 1) return NULL;
        return children[index];
    }

    //--------------------------------------------------------------
    flDisplayObject* flDisplayObjectContainer::getChildByName(string name) {
        for(int i = 0; i < children.size(); i++){
            if(children[i]->name() == name) return children[i];
        }

        return NULL;
    }

    //--------------------------------------------------------------
    int flDisplayObjectContainer::getChildIndex(flDisplayObject* child) {
        for(int i = 0; i < children.size(); i++){
            if(children[i] == child) return i;
        }

        return -1;
    }

    //--------------------------------------------------------------
    vector<flDisplayObject*> flDisplayObjectContainer::getObjectsUnderPoint(ofPoint point) {
        // TODO
        return children;
    }

    //--------------------------------------------------------------
    void flDisplayObjectContainer::setChildIndex(flDisplayObject* child, int index) {
        if(index < 0 || index > children.size() - 1) return;

        for(int i = 0; i < children.size(); i++){
            if(children[i] == child){
                children.erase(children.begin() + i);
                children.insert(children.begin() + index, child);
                return;
            }
        }
    }

    //--------------------------------------------------------------
    void flDisplayObjectContainer::swapChildren(flDisplayObject* child1, flDisplayObject* child2) {
        int index1 = getChildIndex(child1);
        int index2 = getChildIndex(child2);

        if(index1 == -1 || index2 == -1) return;

        for(int i = 0; i < children.size(); i++){
            if(children[i] == child1 || children[i] == child2) {
                children.erase(children.begin() + i--);
            }
        }

        if(index1 < index2){
            children.insert(children.begin() + index1, child2);
            children.insert(children.begin() + index2, child1);
        } else {
            children.insert(children.begin() + index2, child1);
            children.insert(children.begin() + index1, child2);
        }
    }

    //--------------------------------------------------------------
    void flDisplayObjectContainer::swapChildrenAt(int index1, int index2) {
        if(index1 == index2) return;

        flDisplayObject* child1 = getChildAt(index1);
        flDisplayObject* child2 = getChildAt(index2);

        if(child1 == NULL || child2 == NULL) return;

        if(index2 > index1){
            children.erase(children.begin() + index2);
            children.erase(children.begin() + index1);
        } else {
            children.erase(children.begin() + index1);
            children.erase(children.begin() + index2);
        }

        if(index1 < index2){
            children.insert(children.begin() + index1, child2);
            children.insert(children.begin() + index2, child1);
        } else {
            children.insert(children.begin() + index2, child1);
            children.insert(children.begin() + index1, child2);
        }
    }

    //==============================================================
    // Protected / Private Method
    //==============================================================

    //--------------------------------------------------------------
    void flDisplayObjectContainer::_updateRect() {
//        _hitAreaRect->__setNull();
        _rect->__setZero();

        int i; int l;
        l = children.size();
        for(i = 0; i < l; i++) {
            flDisplayObject* child = children[i];

            //=========================================== Matrix.
            //This the code is moved here from flStage._updateChildrenOne().
            //transform child matrix by world matrix.
            flMatrix worldMatrix;
            worldMatrix = transform().concatenatedMatrix();
            worldMatrix.concat(child->transform().matrix());
            child->__updateTransform(worldMatrix);

            if(!child->visible()) continue;
            flRectangle childRect = child->__getRect(this);
            _rect->__expandTo(childRect.left(), childRect.top());
            _rect->__expandTo(childRect.right(), childRect.bottom());
        }

        _realWidth = _rect->width();
        _realHeight = _rect->height();

        if(_realWidth != 0.0 && !isnan(_targetWidth)) scaleX(_targetWidth / _realWidth);
        if(_realHeight != 0.0 && !isnan(_targetHeight)) scaleY(_targetHeight / _realHeight);

//        if(!isnan(_targetWidth)) scaleX(_targetWidth / _realWidth);
//        if(!isnan(_targetHeight)) scaleY(_targetHeight / _realHeight);
//        if(_targetWidth != -9999.0) scaleX(_targetWidth / _realWidth);
//        if(_targetHeight != -9999.0) scaleY(_targetHeight / _realHeight);
    }

    //--------------------------------------------------------------
    bool flDisplayObjectContainer::_hasChildren(flDisplayObject* displayObject) {
        bool b;
        b = false;
        b = b || (displayObject->typeID() == FL_TYPE_DISPLAY_OBJECT_CONTAINER);
        b = b || (displayObject->typeID() == FL_TYPE_SPRITE);
        b = b || (displayObject->typeID() == FL_TYPE_MOVIE_CLIP);
        b = b || (displayObject->typeID() == FL_TYPE_UIBASE);

        return b;
    }

}
<commit_msg>no message<commit_after>#include "flDisplayObjectContainer.h"

namespace fl2d {

    //==============================================================
    // Constructor / Destructor
    //==============================================================

    //--------------------------------------------------------------
    flDisplayObjectContainer::flDisplayObjectContainer() {
        _typeID = FL_TYPE_DISPLAY_OBJECT_CONTAINER;
        _target = this;
        name("flDisplayObjectContainer");

        _mouseChildren = true;
        //_tabChildren = false;
    }

    //--------------------------------------------------------------
    flDisplayObjectContainer::~flDisplayObjectContainer() {
        _target = NULL;

        children.clear();

        _mouseChildren = false;
        //_tabChildren = false;
    }

    //==============================================================
    // Setup / Update / Draw
    //==============================================================

    //--------------------------------------------------------------
    void flDisplayObjectContainer::update() {
        //    float tempLeft = _rect->left();
        //    float tempRight = _rect->right();
        //    float tempTop = _rect->top();
        //    float tempBottom = _rect->bottom();
        //
        //    _rect->_setToPoint(0, 0);

        //        int i; int l;
        //        flDisplayObject* child;
        //
        //        l = children.size();
        //        for(i = 0; i < l; i++) {
        //            child = children[i];
        //            float n1 = child->x();
        //            float n2 = child->y();
        //            _rect->__expandTo(n1, n2);
        //            _rect->__expandTo(n1 + child->width(), n2 + child->height());
        //        }
        //    _rect->__expandTo(tempLeft, tempTop);
        //    _rect->__expandTo(tempRight, tempBottom);

        flDisplayObject::update();
    }

    //--------------------------------------------------------------
    void flDisplayObjectContainer::draw(bool applyMatrix) {
        if(!visible() && applyMatrix) return;

        // save off current state of blend enabled
        GLboolean blendEnabled;
        glGetBooleanv(GL_BLEND, &blendEnabled);
        // save off current state of src / dst blend functions
        GLint blendSrc; GLint blendDst;
        glGetIntegerv(GL_BLEND_SRC_ALPHA, &blendSrc);
        glGetIntegerv(GL_BLEND_DST_ALPHA, &blendDst);
        ofEnableAlphaBlending();

        GLboolean preLighting = glIsEnabled(GL_LIGHTING);
        GLboolean preDepthTest = glIsEnabled(GL_DEPTH_TEST);
        GLboolean preLineSmooth = glIsEnabled(GL_LINE_SMOOTH);
        GLboolean preMultiSample = glIsEnabled(GL_MULTISAMPLE);
        ofDisableLighting();
        glDisable(GL_DEPTH_TEST);
        if(_enabledSmoothing) { ofEnableSmoothing(); } else { ofDisableSmoothing(); }
        if(_enabledAntiAliasing) { ofEnableAntiAliasing(); } else { ofDisableAntiAliasing(); }

        //------------------------------------------
        //-- matrix transform.
        //        bool bIdentity = true;
        //        bIdentity = matrix().isIdentity();
        //        bIdentity = false;

        if(applyMatrix){
            //            glPushMatrix();
            ofPushMatrix();
            //            glMultMatrixf(matrix().getPtr());
            ofMultMatrix(_transform.matrix().getPtr());
        }

        ofPushStyle();
        //        ofSetColor(255, 255, 255, 255 * _compoundAlpha);
        _draw();

        for(int i = 0; i < children.size(); i++) {
            flDisplayObject* child;
            child = children[i];
            //child->drawOnFrame();
            child->draw();
        }
        ofPopStyle();

        if(applyMatrix){
//            glPopMatrix();
            ofPopMatrix();
        }
        //------------------------------------------

        if(preMultiSample == GL_TRUE) { ofEnableAntiAliasing(); } else { ofDisableAntiAliasing(); }
        if(preLineSmooth == GL_TRUE) { ofEnableSmoothing(); } else { ofDisableSmoothing(); }
        if(preDepthTest == GL_TRUE) { glEnable(GL_DEPTH_TEST); } else { glDisable(GL_DEPTH_TEST); }
        if(preLighting == GL_TRUE) { ofEnableLighting(); } else { ofDisableLighting(); }

        // restore saved state of blend enabled and blend functions
        if (blendEnabled) { glEnable(GL_BLEND); } else { glDisable(GL_BLEND); }
        glBlendFunc(blendSrc, blendDst);
    }

    //==============================================================
    // Public Method
    //==============================================================

    //--------------------------------------------------------------
    bool flDisplayObjectContainer::mouseChildren() { return _mouseChildren; }
    void flDisplayObjectContainer::mouseChildren(bool value) { _mouseChildren = value; }

    //--------------------------------------------------------------
    int flDisplayObjectContainer::numChildren() { return children.size(); }

    //--------------------------------------------------------------
    bool flDisplayObjectContainer::contains(flDisplayObject* child) {
        for(int i = 0; i < children.size(); i++) {
            if(children[i] == child) return true;
        }
        return false;
    }

    //--------------------------------------------------------------
    flDisplayObject* flDisplayObjectContainer::stage() { return _stage; }
    void flDisplayObjectContainer::stage(flDisplayObject* value) {
        //cout << "[flDisplayObjectContainer]stage(" << value << ")" << name() << endl;

        //΁valueL΁
        if(!_stage && value) {
            _stage = value;

            flEvent* event = new flEvent(flEvent::ADDED_TO_STAGE);
//            event->target(_target);
            dispatchEvent(event);
        }
        //L΁valueL΁
        if(_stage && !value) {
            _stage = value;

            flEvent* event = new flEvent(flEvent::REMOVED_FROM_STAGE);
//            event->target(_target);
            dispatchEvent(event);
        }

        for(int i = 0; i < children.size(); i++) {
            flDisplayObject* displayObject = children[i];
            displayObject->stage(_stage);
        }
    }

    //--------------------------------------------------------------
    flDisplayObject* flDisplayObjectContainer::addChild(flDisplayObject* child) {
        //    cout << "[flDisplayObjectContainer]addChild((" << child->name() << ")" << endl;
        //if(child == NULL) throw "TypeError: Error #2007:  child  null 񁘁";

        if(child->parent()){
            ((flDisplayObjectContainer*)(child->parent()))->removeChild(child);
        }

        children.push_back(child);
        child->stage(this->_stage);
        child->parent(this);
        child->level(this->level()+1);

        _updateRect();

        return child;
    }
    //--------------------------------------------------------------
    flDisplayObject* flDisplayObjectContainer::addChild(flDisplayObject* child, int x, int y) {
        //    cout << "[flDisplayObjectContainer]addChild(" << child->name() << ", " << x << ", " << y << ")" << endl;
        //if(child == NULL) throw "TypeError: Error #2007:  child  null 񁘁";

        if(child->parent()){
            ((flDisplayObjectContainer*)(child->parent()))->removeChild(child);
        }

        children.push_back(child);
        child->x(x);
        child->y(y);
        child->stage(this->_stage);
        child->parent(this);
        child->level(this->level()+1);

        _updateRect();

        return child;
    }

    //--------------------------------------------------------------
    flDisplayObject* flDisplayObjectContainer::addChildAt(flDisplayObject* child, int index) {
        //if(child == NULL) throw "TypeError: Error #2007:  child  null 񁘁";

        if(index < 0 || index > children.size() - 1) return NULL;
        if(child->parent()) {
            ((flDisplayObjectContainer*)(child->parent()))->removeChild(child);
        }
        children.insert(children.begin() + index, child);
        child->stage(this->_stage);
        child->parent(this);
        child->level(this->level() + 1);

        _updateRect();

        return child;
    }

    //--------------------------------------------------------------
    flDisplayObject* flDisplayObjectContainer::removeChild(flDisplayObject* child) {
        //if(child == NULL) throw "TypeError: Error #2007:  child  null 񁘁";

        //children.size()̉ӏ̓t@N^OƂŊOɏo_
        for(int i = 0; i < children.size(); i++){
            if(children[i] == child){
                child->stage(NULL);
                child->parent(NULL);
                child->level(-1);
                children.erase(children.begin() + i);

                _updateRect();

                return child;
            }
        }

        throw "flDisplayObjectContainer::removeChild\n";
    }

    //--------------------------------------------------------------
    flDisplayObject* flDisplayObjectContainer::removeChildAt(int index) {

        //children.size()̉ӏ̓t@N^OƂŊOɏo_
        if(index < 0 || index > children.size() - 1) return NULL;
        flDisplayObject* child;
        child = children[index];
        child->stage(NULL);
        child->parent(NULL);
        child->level(-1);
        children.erase(children.begin() + index);

        _updateRect();

        return child;
    }

    //--------------------------------------------------------------
    void flDisplayObjectContainer::removeAllChildren() {
        int i = 0;
        int t = children.size();

        flDisplayObject* child;

        for(i; i < t; i++){
            child = children[i];
            child->stage(NULL);
            child->parent(NULL);
            child->level(-1);
            children.erase(children.begin() + i);
            --i;
            --t;
        }

        _updateRect();
    }

    //--------------------------------------------------------------
    flDisplayObject* flDisplayObjectContainer::getChildAt(int index) {
        if(index < 0 || index > children.size() - 1) return NULL;
        return children[index];
    }

    //--------------------------------------------------------------
    flDisplayObject* flDisplayObjectContainer::getChildByName(string name) {
        for(int i = 0; i < children.size(); i++){
            if(children[i]->name() == name) return children[i];
        }

        return NULL;
    }

    //--------------------------------------------------------------
    int flDisplayObjectContainer::getChildIndex(flDisplayObject* child) {
        for(int i = 0; i < children.size(); i++){
            if(children[i] == child) return i;
        }

        return -1;
    }

    //--------------------------------------------------------------
    vector<flDisplayObject*> flDisplayObjectContainer::getObjectsUnderPoint(ofPoint point) {
        // TODO
        return children;
    }

    //--------------------------------------------------------------
    void flDisplayObjectContainer::setChildIndex(flDisplayObject* child, int index) {
        if(index < 0 || index > children.size() - 1) return;

        for(int i = 0; i < children.size(); i++){
            if(children[i] == child){
                children.erase(children.begin() + i);
                children.insert(children.begin() + index, child);
                return;
            }
        }
    }

    //--------------------------------------------------------------
    void flDisplayObjectContainer::swapChildren(flDisplayObject* child1, flDisplayObject* child2) {
        int index1 = getChildIndex(child1);
        int index2 = getChildIndex(child2);

        if(index1 == -1 || index2 == -1) return;

        for(int i = 0; i < children.size(); i++){
            if(children[i] == child1 || children[i] == child2) {
                children.erase(children.begin() + i--);
            }
        }

        if(index1 < index2){
            children.insert(children.begin() + index1, child2);
            children.insert(children.begin() + index2, child1);
        } else {
            children.insert(children.begin() + index2, child1);
            children.insert(children.begin() + index1, child2);
        }
    }

    //--------------------------------------------------------------
    void flDisplayObjectContainer::swapChildrenAt(int index1, int index2) {
        if(index1 == index2) return;

        flDisplayObject* child1 = getChildAt(index1);
        flDisplayObject* child2 = getChildAt(index2);

        if(child1 == NULL || child2 == NULL) return;

        if(index2 > index1){
            children.erase(children.begin() + index2);
            children.erase(children.begin() + index1);
        } else {
            children.erase(children.begin() + index1);
            children.erase(children.begin() + index2);
        }

        if(index1 < index2){
            children.insert(children.begin() + index1, child2);
            children.insert(children.begin() + index2, child1);
        } else {
            children.insert(children.begin() + index2, child1);
            children.insert(children.begin() + index1, child2);
        }
    }

    //==============================================================
    // Protected / Private Method
    //==============================================================

    //--------------------------------------------------------------
    void flDisplayObjectContainer::_updateRect() {
//        _hitAreaRect->__setNull();
        _rect->__setZero();

        int i; int l;
        l = children.size();
        for(i = 0; i < l; i++) {
            flDisplayObject* child = children[i];

            //=========================================== Matrix.
            //This the code is moved here from flStage._updateChildrenOne().
            //transform child matrix by world matrix.
            flMatrix worldMatrix;
            worldMatrix = transform().concatenatedMatrix();
            worldMatrix.concat(child->transform().matrix());
            child->__updateTransform(worldMatrix);

            if(!child->visible()) continue;
            flRectangle childRect = child->__getRect(this);
            _rect->__expandTo(childRect.left(), childRect.top());
            _rect->__expandTo(childRect.right(), childRect.bottom());
        }

        _realWidth = _rect->width();
        _realHeight = _rect->height();

        if(_realWidth != 0.0 && !isnan(_targetWidth)) scaleX(_targetWidth / _realWidth);
        if(_realHeight != 0.0 && !isnan(_targetHeight)) scaleY(_targetHeight / _realHeight);

//        if(!isnan(_targetWidth)) scaleX(_targetWidth / _realWidth);
//        if(!isnan(_targetHeight)) scaleY(_targetHeight / _realHeight);
//        if(_targetWidth != -9999.0) scaleX(_targetWidth / _realWidth);
//        if(_targetHeight != -9999.0) scaleY(_targetHeight / _realHeight);
    }

    //--------------------------------------------------------------
    bool flDisplayObjectContainer::_hasChildren(flDisplayObject* displayObject) {
        bool b;
        b = false;
        b = b || (displayObject->typeID() == FL_TYPE_DISPLAY_OBJECT_CONTAINER);
        b = b || (displayObject->typeID() == FL_TYPE_SPRITE);
        b = b || (displayObject->typeID() == FL_TYPE_MOVIE_CLIP);
        b = b || (displayObject->typeID() == FL_TYPE_UIBASE);

        return b;
    }

}
<|endoftext|>


<commit_before>//(c) 2016 by Authors
//This file is a part of ABruijn program.
//Released under the BSD license (see LICENSE file)

#include <chrono>
#include <thread>

#include "bubble_processor.h"

namespace
{
	size_t fileSize(const std::string& filename)
	{
		std::ifstream in(filename);
		in.ignore(std::numeric_limits<std::streamsize>::max());
	    return in.gcount();
	}
}

BubbleProcessor::BubbleProcessor(const std::string& subsMatPath,
								 const std::string& hopoMatrixPath):
	_subsMatrix(subsMatPath),
	_hopoMatrix(hopoMatrixPath),
	_generalPolisher(_subsMatrix),
	_homoPolisher(_subsMatrix, _hopoMatrix),
	_verbose(false)
{
}

void BubbleProcessor::polishAll(const std::string& inBubbles,
								const std::string& outConsensus,
			   					int numThreads)
{
	_cachedBubbles.clear();
	_cachedBubbles.reserve(BUBBLES_CACHE);

	size_t fileLength = fileSize(inBubbles);
	_bubblesFile.open(inBubbles);
	if (!_bubblesFile.is_open())
	{
		throw std::runtime_error("Error opening bubbles file");
	}

	_progress.setFinalCount(fileLength);

	_consensusFile.open(outConsensus);
	if (!_consensusFile.is_open())
	{
		throw std::runtime_error("Error opening consensus file");
	}

	std::vector<std::thread> threads(numThreads);
	for (size_t i = 0; i < threads.size(); ++i)
	{
		threads[i] = std::thread(&BubbleProcessor::parallelWorker, this);
	}
	for (size_t i = 0; i < threads.size(); ++i)
	{
		threads[i].join();
	}
	_progress.setDone();
}

void BubbleProcessor::parallelWorker()
{
	_stateMutex.lock();
	while (true)
	{
		if (_cachedBubbles.empty())
		{
			if(_bubblesFile.eof())
			{
				_stateMutex.unlock();
				return;
			}
			else
			{
				this->cacheBubbles(BUBBLES_CACHE);
			}
		}

		Bubble bubble = _cachedBubbles.back();
		_cachedBubbles.pop_back();

		_stateMutex.unlock();
		_generalPolisher.polishBubble(bubble);
		_homoPolisher.polishBubble(bubble);
		_stateMutex.lock();

		this->writeBubbles({bubble});
		if (_verbose) this->writeLog({bubble});
	}
}

void BubbleProcessor::writeBubbles(const std::vector<Bubble>& bubbles)
{
	for (auto& bubble : bubbles)
	{
		_consensusFile << ">" << bubble.header << " " << bubble.position
			 		   << " " << bubble.branches.size() << std::endl
			 		   << bubble.candidate << std::endl;
	}
}

void BubbleProcessor::enableVerboseOutput(const std::string& filename)
{
	_verbose = true;
	_logFile.open(filename);
	if (!_logFile.is_open())
	{
		throw std::runtime_error("Error opening log file");
	}
}

void BubbleProcessor::writeLog(const std::vector<Bubble>& bubbles)
{
	std::vector<std::string> methods = {"None", "Insertion", "Substitution",
										"Deletion", "Homopolymer"};

	for (auto& bubble : bubbles)
	{
		for (auto& stepInfo : bubble.polishSteps)
		{
			 _logFile << std::fixed
				 << std::setw(22) << std::left << "Consensus: "
				 << std::right << stepInfo.sequence << std::endl
				 << std::setw(22) << std::left << "Score: " << std::right
				 << std::setprecision(2) << stepInfo.score << std::endl
				 << std::setw(22) << std::left << "Last method applied: "
				 << std::right << methods[stepInfo.methodUsed] << std::endl;

			if (stepInfo.methodUsed == StepDel)
				_logFile << "Char at pos: " << stepInfo.changedIndex << " was deleted. \n";
			else if (stepInfo.methodUsed == StepSub)
				_logFile << "Char at pos " << stepInfo.changedIndex << " was substituted with "
					<< "'" << stepInfo.changedLetter << "'.\n";
			else if (stepInfo.methodUsed == StepIns)
				_logFile << "'"<< stepInfo.changedLetter << "'"
					 << " was inserted at pos " << stepInfo.changedIndex << ".\n";

			_logFile << std::endl;
		}
		_logFile << "-----------------\n";
	}
}

void BubbleProcessor::cacheBubbles(int maxRead)
{
	std::string buffer;
	std::string candidate;

	int readBubbles = 0;
	while (!_bubblesFile.eof() && readBubbles < maxRead)
	{
		std::getline(_bubblesFile, buffer);
		if (buffer.empty()) break;

		std::vector<std::string> elems = splitString(buffer, ' ');
		if (elems.size() < 3 || elems[0][0] != '>')
		{
			throw std::runtime_error("Error parsing bubbles file");
		}
		std::getline(_bubblesFile, candidate);
		std::transform(candidate.begin(), candidate.end(),
				       candidate.begin(), ::toupper);

		Bubble bubble;
		bubble.candidate = candidate;
		bubble.header = elems[0].substr(1, std::string::npos);
		bubble.position = std::stoi(elems[1]);
		int numOfReads = std::stoi(elems[2]);

		int count = 0;
		while (count < numOfReads)
		{
			if (buffer.empty()) break;

			std::getline(_bubblesFile, buffer);
			std::getline(_bubblesFile, buffer);
			std::transform(buffer.begin(), buffer.end(),
				       	   buffer.begin(), ::toupper);
			bubble.branches.push_back(buffer);
			count++;
		}
		if (count != numOfReads)
		{
			throw std::runtime_error("Error parsing bubbles file");
		}

		_cachedBubbles.push_back(std::move(bubble));
		++readBubbles;
	}

	int filePos = _bubblesFile.tellg();
	if (filePos > 0)
	{
		_progress.setValue(filePos);
	}
}
<commit_msg>a fix for large bubbles progress bar<commit_after>//(c) 2016 by Authors
//This file is a part of ABruijn program.
//Released under the BSD license (see LICENSE file)

#include <chrono>
#include <thread>

#include "bubble_processor.h"

namespace
{
	size_t fileSize(const std::string& filename)
	{
		std::ifstream in(filename);
		in.ignore(std::numeric_limits<std::streamsize>::max());
	    return in.gcount();
	}
}

BubbleProcessor::BubbleProcessor(const std::string& subsMatPath,
								 const std::string& hopoMatrixPath):
	_subsMatrix(subsMatPath),
	_hopoMatrix(hopoMatrixPath),
	_generalPolisher(_subsMatrix),
	_homoPolisher(_subsMatrix, _hopoMatrix),
	_verbose(false)
{
}

void BubbleProcessor::polishAll(const std::string& inBubbles,
								const std::string& outConsensus,
			   					int numThreads)
{
	_cachedBubbles.clear();
	_cachedBubbles.reserve(BUBBLES_CACHE);

	size_t fileLength = fileSize(inBubbles);
	_bubblesFile.open(inBubbles);
	if (!_bubblesFile.is_open())
	{
		throw std::runtime_error("Error opening bubbles file");
	}

	_progress.setFinalCount(fileLength);

	_consensusFile.open(outConsensus);
	if (!_consensusFile.is_open())
	{
		throw std::runtime_error("Error opening consensus file");
	}

	std::vector<std::thread> threads(numThreads);
	for (size_t i = 0; i < threads.size(); ++i)
	{
		threads[i] = std::thread(&BubbleProcessor::parallelWorker, this);
	}
	for (size_t i = 0; i < threads.size(); ++i)
	{
		threads[i].join();
	}
	_progress.setDone();
}

void BubbleProcessor::parallelWorker()
{
	_stateMutex.lock();
	while (true)
	{
		if (_cachedBubbles.empty())
		{
			if(_bubblesFile.eof())
			{
				_stateMutex.unlock();
				return;
			}
			else
			{
				this->cacheBubbles(BUBBLES_CACHE);
			}
		}

		Bubble bubble = _cachedBubbles.back();
		_cachedBubbles.pop_back();

		_stateMutex.unlock();
		_generalPolisher.polishBubble(bubble);
		_homoPolisher.polishBubble(bubble);
		_stateMutex.lock();

		this->writeBubbles({bubble});
		if (_verbose) this->writeLog({bubble});
	}
}

void BubbleProcessor::writeBubbles(const std::vector<Bubble>& bubbles)
{
	for (auto& bubble : bubbles)
	{
		_consensusFile << ">" << bubble.header << " " << bubble.position
			 		   << " " << bubble.branches.size() << std::endl
			 		   << bubble.candidate << std::endl;
	}
}

void BubbleProcessor::enableVerboseOutput(const std::string& filename)
{
	_verbose = true;
	_logFile.open(filename);
	if (!_logFile.is_open())
	{
		throw std::runtime_error("Error opening log file");
	}
}

void BubbleProcessor::writeLog(const std::vector<Bubble>& bubbles)
{
	std::vector<std::string> methods = {"None", "Insertion", "Substitution",
										"Deletion", "Homopolymer"};

	for (auto& bubble : bubbles)
	{
		for (auto& stepInfo : bubble.polishSteps)
		{
			 _logFile << std::fixed
				 << std::setw(22) << std::left << "Consensus: "
				 << std::right << stepInfo.sequence << std::endl
				 << std::setw(22) << std::left << "Score: " << std::right
				 << std::setprecision(2) << stepInfo.score << std::endl
				 << std::setw(22) << std::left << "Last method applied: "
				 << std::right << methods[stepInfo.methodUsed] << std::endl;

			if (stepInfo.methodUsed == StepDel)
				_logFile << "Char at pos: " << stepInfo.changedIndex << " was deleted. \n";
			else if (stepInfo.methodUsed == StepSub)
				_logFile << "Char at pos " << stepInfo.changedIndex << " was substituted with "
					<< "'" << stepInfo.changedLetter << "'.\n";
			else if (stepInfo.methodUsed == StepIns)
				_logFile << "'"<< stepInfo.changedLetter << "'"
					 << " was inserted at pos " << stepInfo.changedIndex << ".\n";

			_logFile << std::endl;
		}
		_logFile << "-----------------\n";
	}
}

void BubbleProcessor::cacheBubbles(int maxRead)
{
	std::string buffer;
	std::string candidate;

	int readBubbles = 0;
	while (!_bubblesFile.eof() && readBubbles < maxRead)
	{
		std::getline(_bubblesFile, buffer);
		if (buffer.empty()) break;

		std::vector<std::string> elems = splitString(buffer, ' ');
		if (elems.size() < 3 || elems[0][0] != '>')
		{
			throw std::runtime_error("Error parsing bubbles file");
		}
		std::getline(_bubblesFile, candidate);
		std::transform(candidate.begin(), candidate.end(),
				       candidate.begin(), ::toupper);

		Bubble bubble;
		bubble.candidate = candidate;
		bubble.header = elems[0].substr(1, std::string::npos);
		bubble.position = std::stoi(elems[1]);
		int numOfReads = std::stoi(elems[2]);

		int count = 0;
		while (count < numOfReads)
		{
			if (buffer.empty()) break;

			std::getline(_bubblesFile, buffer);
			std::getline(_bubblesFile, buffer);
			std::transform(buffer.begin(), buffer.end(),
				       	   buffer.begin(), ::toupper);
			bubble.branches.push_back(buffer);
			count++;
		}
		if (count != numOfReads)
		{
			throw std::runtime_error("Error parsing bubbles file");
		}

		_cachedBubbles.push_back(std::move(bubble));
		++readBubbles;
	}

	int64_t filePos = _bubblesFile.tellg();
	if (filePos > 0)
	{
		_progress.setValue(filePos);
	}
}
<|endoftext|>


<commit_before>#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iterator>
#include <tuple>
#include <regex>
#include <array>
#include <valarray>
#define all(v)begin(v),end(v)
#define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,"\n"))
#define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i)
#define fr(i,n)for(int i=0,i##e=n;i<i##e;++i)
#define rf(i,n)for(int i=n-1;i>=0;--i)
#define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1)
#define sz(v)int(v.size())
#define sr(v)sort(all(v))
#define rs(v)sort(all(v),greater<int>())
#define rev(v)reverse(all(v))
#define eb emplace_back
#define stst stringstream
#define big numeric_limits<int>::max()
#define g(t,i)get<i>(t)
#define cb(v,w)copy(all(v),back_inserter(w))
#define uni(v)sort(all(v));v.erase(unique(all(v)),end(v))
#define vt(...)vector<tuple<__VA_ARGS__>>
#define smx(a,b)a=max(a,b)
#define smn(a,b)a=min(a,b)
#define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q);
#define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m/=s;}(n);
typedef long long ll;
using namespace std;

struct TheBestName {
	vector <string> sort(vector <string> names) {
		vt(int, string) v;
		auto sum = [](const string & s) {
			int r = 0;
			ei(a, s) r += a - 'A';
			return r;
		};
		ei(a, names) {
			v.eb(a == "JOHN" ? big : sum(a), a);
		}
		sr(v);
		ei(a, v) names[ai] = g(a,1);
		return names;
	}
};

// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit-pf 2.3.0
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cmath>
using namespace std;
bool KawigiEdit_RunTest(int testNum, vector <string> p0, bool hasAnswer, vector <string> p1) {
	cout << "Test " << testNum << ": [" << "{";
	for (int i = 0; int(p0.size()) > i; ++i) {
		if (i > 0) {
			cout << ",";
		}
		cout << "\"" << p0[i] << "\"";
	}
	cout << "}";
	cout << "]" << endl;
	TheBestName *obj;
	vector <string> answer;
	obj = new TheBestName();
	clock_t startTime = clock();
	answer = obj->sort(p0);
	clock_t endTime = clock();
	delete obj;
	bool res;
	res = true;
	cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
	if (hasAnswer) {
		cout << "Desired answer:" << endl;
		cout << "\t" << "{";
		for (int i = 0; int(p1.size()) > i; ++i) {
			if (i > 0) {
				cout << ",";
			}
			cout << "\"" << p1[i] << "\"";
		}
		cout << "}" << endl;
	}
	cout << "Your answer:" << endl;
	cout << "\t" << "{";
	for (int i = 0; int(answer.size()) > i; ++i) {
		if (i > 0) {
			cout << ",";
		}
		cout << "\"" << answer[i] << "\"";
	}
	cout << "}" << endl;
	if (hasAnswer) {
		if (answer.size() != p1.size()) {
			res = false;
		} else {
			for (int i = 0; int(answer.size()) > i; ++i) {
				if (answer[i] != p1[i]) {
					res = false;
				}
			}
		}
	}
	if (!res) {
		cout << "DOESN'T MATCH!!!!" << endl;
	} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
		cout << "FAIL the timeout" << endl;
		res = false;
	} else if (hasAnswer) {
		cout << "Match :-)" << endl;
	} else {
		cout << "OK, but is it right?" << endl;
	}
	cout << "" << endl;
	return res;
}
int main() {
	bool all_right;
	bool disabled;
	bool tests_disabled;
	all_right = true;
	tests_disabled = false;

	vector <string> p0;
	vector <string> p1;

	// ----- test 0 -----
	disabled = false;
	p0 = {"JOHN","PETR","ACRUSH"};
	p1 = {"JOHN","ACRUSH","PETR"};
	all_right = (disabled || KawigiEdit_RunTest(0, p0, true, p1) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 1 -----
	disabled = false;
	p0 = {"GLUK","MARGARITKA"};
	p1 = {"MARGARITKA","GLUK"};
	all_right = (disabled || KawigiEdit_RunTest(1, p0, true, p1) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 2 -----
	disabled = false;
	p0 = {"JOHN","A","AA","AAA","JOHN","B","BB","BBB","JOHN","C","CC","CCC","JOHN"};
	p1 = {"JOHN","JOHN","JOHN","JOHN","CCC","BBB","CC","BB","AAA","C","AA","B","A"};
	all_right = (disabled || KawigiEdit_RunTest(2, p0, true, p1) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 3 -----
	disabled = false;
	p0 = {"BATMAN","SUPERMAN","SPIDERMAN","TERMINATOR"};
	p1 = {"TERMINATOR","SUPERMAN","SPIDERMAN","BATMAN"};
	all_right = (disabled || KawigiEdit_RunTest(3, p0, true, p1) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	if (all_right) {
		if (tests_disabled) {
			cout << "You're a stud (but some test cases were disabled)!" << endl;
		} else {
			cout << "You're a stud (at least on given cases)!" << endl;
		}
	} else {
		cout << "Some of the test cases had errors." << endl;
	}
	return 0;
}
// END KAWIGIEDIT TESTING
<commit_msg>TheBestName<commit_after>#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iterator>
#include <tuple>
#include <regex>
#include <array>
#include <valarray>
#define all(v)begin(v),end(v)
#define dump(v)copy(all(v),ostream_iterator<decltype(*v.begin())>(cout,"\n"))
#define rg(i,a,b)for(int i=a,i##e=b;i<i##e;++i)
#define fr(i,n)for(int i=0,i##e=n;i<i##e;++i)
#define rf(i,n)for(int i=n-1;i>=0;--i)
#define ei(a,m)for(auto&a:m)if(int a##i=&a-&*begin(m)+1)if(--a##i,1)
#define sz(v)int(v.size())
#define sr(v)sort(all(v))
#define rs(v)sort(all(v),greater<int>())
#define rev(v)reverse(all(v))
#define eb emplace_back
#define stst stringstream
#define big numeric_limits<int>::max()
#define g(t,i)get<i>(t)
#define cb(v,w)copy(all(v),back_inserter(w))
#define uni(v)sort(all(v));v.erase(unique(all(v)),end(v))
#define vt(...)vector<tuple<__VA_ARGS__>>
#define smx(a,b)a=max(a,b)
#define smn(a,b)a=min(a,b)
#define words(w,q)vector<string>w;[&w](string&&s){stringstream u(s);string r;while(u>>r)w.eb(r);}(q);
#define digits(d,n,s)vector<int>d;[&d](int m){while(m)d.eb(m%s),m/=s;}(n);
typedef long long ll;
using namespace std;

struct TheBestName {
	vector <string> sort(vector <string> names) {
		vector<pair<int, string>> v;
		auto sum = [](const string & s) {
			int r = 0;
			ei(a, s) r += a - 'A';
			return r;
		};
		ei(a, names) {
			v.eb(a == "JOHN" ? big : sum(a), a);
		}
		sr(v);
		ei(a, v) names[ai] = s.second;
		return names;
	}
};

// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit-pf 2.3.0
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <cmath>
using namespace std;
bool KawigiEdit_RunTest(int testNum, vector <string> p0, bool hasAnswer, vector <string> p1) {
	cout << "Test " << testNum << ": [" << "{";
	for (int i = 0; int(p0.size()) > i; ++i) {
		if (i > 0) {
			cout << ",";
		}
		cout << "\"" << p0[i] << "\"";
	}
	cout << "}";
	cout << "]" << endl;
	TheBestName *obj;
	vector <string> answer;
	obj = new TheBestName();
	clock_t startTime = clock();
	answer = obj->sort(p0);
	clock_t endTime = clock();
	delete obj;
	bool res;
	res = true;
	cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
	if (hasAnswer) {
		cout << "Desired answer:" << endl;
		cout << "\t" << "{";
		for (int i = 0; int(p1.size()) > i; ++i) {
			if (i > 0) {
				cout << ",";
			}
			cout << "\"" << p1[i] << "\"";
		}
		cout << "}" << endl;
	}
	cout << "Your answer:" << endl;
	cout << "\t" << "{";
	for (int i = 0; int(answer.size()) > i; ++i) {
		if (i > 0) {
			cout << ",";
		}
		cout << "\"" << answer[i] << "\"";
	}
	cout << "}" << endl;
	if (hasAnswer) {
		if (answer.size() != p1.size()) {
			res = false;
		} else {
			for (int i = 0; int(answer.size()) > i; ++i) {
				if (answer[i] != p1[i]) {
					res = false;
				}
			}
		}
	}
	if (!res) {
		cout << "DOESN'T MATCH!!!!" << endl;
	} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
		cout << "FAIL the timeout" << endl;
		res = false;
	} else if (hasAnswer) {
		cout << "Match :-)" << endl;
	} else {
		cout << "OK, but is it right?" << endl;
	}
	cout << "" << endl;
	return res;
}
int main() {
	bool all_right;
	bool disabled;
	bool tests_disabled;
	all_right = true;
	tests_disabled = false;

	vector <string> p0;
	vector <string> p1;

	// ----- test 0 -----
	disabled = false;
	p0 = {"JOHN","PETR","ACRUSH"};
	p1 = {"JOHN","ACRUSH","PETR"};
	all_right = (disabled || KawigiEdit_RunTest(0, p0, true, p1) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 1 -----
	disabled = false;
	p0 = {"GLUK","MARGARITKA"};
	p1 = {"MARGARITKA","GLUK"};
	all_right = (disabled || KawigiEdit_RunTest(1, p0, true, p1) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 2 -----
	disabled = false;
	p0 = {"JOHN","A","AA","AAA","JOHN","B","BB","BBB","JOHN","C","CC","CCC","JOHN"};
	p1 = {"JOHN","JOHN","JOHN","JOHN","CCC","BBB","CC","BB","AAA","C","AA","B","A"};
	all_right = (disabled || KawigiEdit_RunTest(2, p0, true, p1) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	// ----- test 3 -----
	disabled = false;
	p0 = {"BATMAN","SUPERMAN","SPIDERMAN","TERMINATOR"};
	p1 = {"TERMINATOR","SUPERMAN","SPIDERMAN","BATMAN"};
	all_right = (disabled || KawigiEdit_RunTest(3, p0, true, p1) ) && all_right;
	tests_disabled = tests_disabled || disabled;
	// ------------------

	if (all_right) {
		if (tests_disabled) {
			cout << "You're a stud (but some test cases were disabled)!" << endl;
		} else {
			cout << "You're a stud (at least on given cases)!" << endl;
		}
	} else {
		cout << "Some of the test cases had errors." << endl;
	}
	return 0;
}
// END KAWIGIEDIT TESTING
<|endoftext|>