FastJet 3.0alpha3
ClusterSequence.cc
00001 //STARTHEADER
00002 // $Id: ClusterSequence.cc 2215 2011-06-02 21:32:36Z soyez $
00003 //
00004 // Copyright (c) 2005-2011, Matteo Cacciari, Gavin Salam and Gregory Soyez
00005 //
00006 //----------------------------------------------------------------------
00007 // This file is part of FastJet.
00008 //
00009 //  FastJet is free software; you can redistribute it and/or modify
00010 //  it under the terms of the GNU General Public License as published by
00011 //  the Free Software Foundation; either version 2 of the License, or
00012 //  (at your option) any later version.
00013 //
00014 //  The algorithms that underlie FastJet have required considerable
00015 //  development and are described in hep-ph/0512210. If you use
00016 //  FastJet as part of work towards a scientific publication, please
00017 //  include a citation to the FastJet paper.
00018 //
00019 //  FastJet is distributed in the hope that it will be useful,
00020 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
00021 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00022 //  GNU General Public License for more details.
00023 //
00024 //  You should have received a copy of the GNU General Public License
00025 //  along with FastJet; if not, write to the Free Software
00026 //  Foundation, Inc.:
00027 //      59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
00028 //----------------------------------------------------------------------
00029 //ENDHEADER
00030 
00031 #include "fastjet/Error.hh"
00032 #include "fastjet/PseudoJet.hh"
00033 #include "fastjet/ClusterSequence.hh"
00034 #include "fastjet/ClusterSequenceStructure.hh"
00035 #include "fastjet/version.hh" // stores the current version number
00036 #include<iostream>
00037 #include<sstream>
00038 #include<fstream>
00039 #include<cmath>
00040 #include<cstdlib>
00041 #include<cassert>
00042 #include<string>
00043 #include<set>
00044 
00045 FASTJET_BEGIN_NAMESPACE      // defined in fastjet/internal/base.hh
00046 
00047 using namespace std;
00048 
00049 //// initialised static member has to go in the .cc code
00050 JetAlgorithm ClusterSequence::_default_jet_algorithm = kt_algorithm;
00051 //
00052 
00053 
00054 // destructor that guarantees proper bookkeeping for the CS Structure
00055 ClusterSequence::~ClusterSequence () {
00056   // set the pointer in the wrapper to this object to NULL to say that
00057   // we're going out of scope
00058   if (_structure_shared_ptr()){
00059     ClusterSequenceStructure* csi = dynamic_cast<ClusterSequenceStructure*>(_structure_shared_ptr()); 
00060     // normally the csi is purely internal so it really should not be
00061     // NULL i.e assert should be OK
00062     // (we assert rather than throw an error, since failure here is a
00063     // sign of major internal problems)
00064     assert(csi != NULL);
00065     csi->set_associated_cs(NULL);
00066 
00067     // if the user had given the CS responsibility to delete itself,
00068     // but then deletes the CS themselves, the following lines of
00069     // code will ensure that the structure_shared_ptr will have
00070     // a proper object count (so that jets associated with the CS will
00071     // throw the correct error if the user tries to access their
00072     // constituents).
00073     if (_deletes_self_when_unused) {
00074       _structure_shared_ptr.set_count(_structure_shared_ptr.use_count() 
00075                                         + _structure_use_count_after_construction);
00076     }
00077   }
00078 }
00079 
00080 //-----------
00081 void ClusterSequence::signal_imminent_self_deletion() const {
00082   // normally if the destructor is called when
00083   // _deletes_self_when_unused is true, it assumes that it's been
00084   // called by the user (and it therefore resets the shared pointer
00085   // count to the true count).
00086   //
00087   // for self deletion (called from the destructor of the CSstructure,
00088   // the shared_ptr to which has just had its pointer -> 0) you do
00089   // _not_ want to reset the pointer count (otherwise you will end up
00090   // with a double delete on the shared pointer once you start
00091   // deleting the internal structure of the CS).
00092   //
00093   // the following modification ensures that the count reset will not
00094   // take place in the destructor
00095   assert(_deletes_self_when_unused);
00096   _deletes_self_when_unused = false;
00097 }
00098 
00099 //----------------------------------------------------------------------
00100 void ClusterSequence::_initialise_and_run (
00101                                   const double & R,
00102                                   const Strategy & strategy,
00103                                   const bool & writeout_combinations) {
00104 
00105   JetDefinition jet_def(_default_jet_algorithm, R, strategy);
00106   _initialise_and_run(jet_def, writeout_combinations);
00107 }
00108 
00109 
00110 //----------------------------------------------------------------------
00111 void ClusterSequence::_initialise_and_run (
00112                                   const JetDefinition & jet_def,
00113                                   const bool & writeout_combinations) {
00114 
00115   // transfer all relevant info into internal variables
00116   _decant_options(jet_def, writeout_combinations);
00117 
00118   // set up the history entries for the initial particles (those
00119   // currently in _jets)
00120   _fill_initial_history();
00121 
00122   // don't run anything if the event is empty
00123   if (n_particles() == 0) return;
00124 
00125   // ----- deal with special cases: plugins & e+e- ------
00126   if (_jet_algorithm == plugin_algorithm) {
00127     // allows plugin_xyz() functions to modify cluster sequence
00128     _plugin_activated = true;
00129     // let the plugin do its work here
00130     _jet_def.plugin()->run_clustering( (*this) );
00131     _plugin_activated = false;
00132     _update_structure_use_count();
00133     return;
00134   } else if (_jet_algorithm == ee_kt_algorithm ||
00135              _jet_algorithm == ee_genkt_algorithm) {
00136     // ignore requested strategy
00137     _strategy = N2Plain;
00138     if (_jet_algorithm == ee_kt_algorithm) {
00139       // make sure that R is large enough so that "beam" recomb only
00140       // occurs when a single particle is left
00141       // Normally, this should be automatically set to 4 from JetDefinition
00142       assert(_Rparam > 2.0); 
00143       // this is used to renormalise the dij to get a "standard" form
00144       // and our convention in e+e- will be different from that
00145       // in long.inv case; NB: _invR2 name should be changed -> _renorm_dij?
00146       _invR2 = 1.0;
00147     } else {
00148       // as of 2009-01-09, choose R to be an angular distance, in
00149       // radians.  Since the algorithm uses 2(1-cos(theta)) as its
00150       // squared angular measure, make sure that the _R2 is defined
00151       // in a similar way.
00152       if (_Rparam > pi) {
00153         // choose a value that ensures that back-to-back particles will
00154         // always recombine 
00155         //_R2 = 4.0000000000001;
00156         _R2 = 2 * ( 3.0 + cos(_Rparam) );
00157       } else {
00158         _R2    = 2 * ( 1.0 - cos(_Rparam) );
00159       }
00160       _invR2 = 1.0/_R2;
00161     }
00162     _simple_N2_cluster_EEBriefJet();
00163     return;
00164   } else if (_jet_algorithm == undefined_jet_algorithm) {
00165     throw Error("A ClusterSequence cannot be created with an uninitialised JetDefinition");
00166   }
00167 
00168 
00169   // automatically redefine the strategy according to N if that is
00170   // what the user requested -- transition points (and especially
00171   // their R-dependence) are based on empirical observations for a
00172   // R=0.4, 0.7 and 1.0, running on toth (3.4GHz, Pentium IV D [dual
00173   // core] with 2MB of cache).
00174   if (_strategy == Best) {
00175     int N = _jets.size();
00176     if (N <= 55*max(0.5,min(1.0,_Rparam))) {// empirical scaling with R
00177       _strategy = N2Plain;
00178     } else if (N > 6200/pow(_Rparam,2.0) && jet_def.jet_algorithm() == cambridge_algorithm) {
00179       _strategy = NlnNCam;
00180 #ifndef DROP_CGAL
00181     } else if ((N > 16000/pow(_Rparam,1.15) && jet_def.jet_algorithm() != antikt_algorithm)
00182                || N > 35000/pow(_Rparam,1.15)) {
00183       _strategy = NlnN;
00184 #endif  // DROP_CGAL
00185     } else if (N <= 450) {
00186       _strategy = N2Tiled;
00187     } else {                   
00188       _strategy = N2MinHeapTiled;
00189     }
00190   }
00191 
00192   // R >= 2pi is not supported by all clustering strategies owing to
00193   // periodicity issues (a particle might cluster with itself). When
00194   // R>=2pi, we therefore automatically switch to a strategy that is
00195   // known to work.
00196   if (_Rparam >= twopi) {
00197     if (   _strategy == NlnN
00198         || _strategy == NlnN3pi
00199         || _strategy == NlnNCam
00200         || _strategy == NlnNCam2pi2R
00201         || _strategy == NlnNCam4pi) {
00202 #ifdef DROP_CGAL
00203       _strategy = N2MinHeapTiled;
00204 #else
00205       _strategy = NlnN4pi;
00206 #endif    
00207     }
00208     if (jet_def.strategy() != Best && _strategy != jet_def.strategy()) {
00209       ostringstream oss;
00210       oss << "Cluster strategy " << strategy_string(jet_def.strategy())
00211           << " automatically changed to " << strategy_string()
00212           << " because the former is not supported for R = " << _Rparam
00213           << " >= 2pi";
00214       _changed_strategy_warning.warn(oss.str());
00215     }
00216   }
00217 
00218 
00219   // run the code containing the selected strategy
00220   // 
00221   // We order the strategies stqrting from the ones used by the Best
00222   // strategy in the order of increasing N, then the remaining ones
00223   // again in the order of increasing N.
00224   if (_strategy == N2Plain) {
00225     // BriefJet provides standard long.invariant kt alg.
00226     this->_simple_N2_cluster_BriefJet();
00227   } else if (_strategy == N2Tiled) {
00228     this->_faster_tiled_N2_cluster();
00229   } else if (_strategy == N2MinHeapTiled) {
00230     this->_minheap_faster_tiled_N2_cluster();
00231   } else if (_strategy == NlnN) {
00232     this->_delaunay_cluster();
00233   } else if (_strategy == NlnNCam) {
00234     this->_CP2DChan_cluster_2piMultD();
00235   } else if (_strategy == NlnN3pi || _strategy == NlnN4pi ) {
00236     this->_delaunay_cluster();
00237   } else if (_strategy ==  N3Dumb ) {
00238     this->_really_dumb_cluster();
00239   } else if (_strategy == N2PoorTiled) {
00240     this->_tiled_N2_cluster();
00241   } else if (_strategy == NlnNCam4pi) {
00242     this->_CP2DChan_cluster();
00243   } else if (_strategy == NlnNCam2pi2R) {
00244     this->_CP2DChan_cluster_2pi2R();
00245   } else {
00246     ostringstream err;
00247     err << "Unrecognised value for strategy: "<<_strategy;
00248     throw Error(err.str());
00249   }
00250 
00251 }
00252 
00253 
00254 // these needs to be defined outside the class definition.
00255 bool ClusterSequence::_first_time = true;
00256 int ClusterSequence::_n_exclusive_warnings = 0;
00257 
00258 
00259 //----------------------------------------------------------------------
00260 // the version string
00261 string fastjet_version_string() {
00262   return "FastJet version "+string(fastjet_version);
00263 }
00264 
00265 
00266 //----------------------------------------------------------------------
00267 // prints a banner on the first call
00268 void ClusterSequence::_print_banner() {
00269 
00270   if (!_first_time) {return;}
00271   _first_time = false;
00272   
00273   
00274   //Symp. Discr. Alg, p.472 (2002) and  CGAL (http://www.cgal.org);
00275 
00276   cout << "#--------------------------------------------------------------------------\n";
00277   cout << "#                         FastJet release " << fastjet_version << endl;
00278   cout << "#            Written by M. Cacciari, G.P. Salam and G. Soyez            \n"; 
00279   cout << "#                         http://www.fastjet.fr                         \n"; 
00280   cout << "#                                                                       \n";
00281   cout << "# Longitudinally invariant Kt, anti-Kt, and inclusive Cambridge/Aachen  \n";
00282   cout << "# clustering using fast geometric algorithms, with jet areas and optional\n";
00283   cout << "# external jet-finder plugins. If you use this code towards a scientific \n";
00284   cout << "# publication please cite Phys. Lett. B641 (2006) [hep-ph/0512210] and   \n";
00285   cout << "# M. Cacciari, G.P. Salam and G. Soyez, http://fastjet.fr/              \n";
00286   cout << "#                                                                       \n";
00287   cout << "# This package uses T.Chan's closest pair algorithm, Proc.13th ACM-SIAM \n";
00288   cout << "# Symp. Discr. Alg, p.472 (2002), S.Fortune's Voronoi algorithm and code" ;
00289 #ifndef DROP_CGAL
00290   cout << endl << "# and CGAL: http://www.cgal.org/";
00291 #endif  // DROP_CGAL
00292   cout << ".\n";
00293   cout << "#-------------------------------------------------------------------------\n";
00294   // make sure we really have the output done.
00295   cout.flush();
00296 }
00297 
00298 //----------------------------------------------------------------------
00299 // transfer all relevant info into internal variables
00300 void ClusterSequence::_decant_options(const JetDefinition & jet_def,
00301                                       const bool & writeout_combinations) {
00302   // let the user know what's going on
00303   _print_banner();
00304 
00305   // make a local copy of the jet definition (for future use?)
00306   _jet_def = jet_def;
00307   
00308   _writeout_combinations = writeout_combinations;
00309   _jet_algorithm = jet_def.jet_algorithm();
00310   _Rparam = jet_def.R();  _R2 = _Rparam*_Rparam; _invR2 = 1.0/_R2;
00311   _strategy = jet_def.strategy();
00312 
00313   // disallow interference from the plugin
00314   _plugin_activated = false;
00315 
00316   // initialised the wrapper to the current CS
00317   _structure_shared_ptr.reset(new ClusterSequenceStructure(this));
00318   _update_structure_use_count(); // make sure it's correct already here
00319 }
00320 
00321 
00322 //----------------------------------------------------------------------
00323 // initialise the history in a standard way
00324 void ClusterSequence::_fill_initial_history () {
00325 
00326   //if (_jets.size() == 0) {throw Error("Cannot run jet-finder on empty event");}
00327 
00328   // reserve sufficient space for everything
00329   _jets.reserve(_jets.size()*2);
00330   _history.reserve(_jets.size()*2);
00331 
00332   _Qtot = 0;
00333 
00334   for (int i = 0; i < static_cast<int>(_jets.size()) ; i++) {
00335     history_element element;
00336     element.parent1 = InexistentParent;
00337     element.parent2 = InexistentParent;
00338     element.child   = Invalid;
00339     element.jetp_index = i;
00340     element.dij     = 0.0;
00341     element.max_dij_so_far = 0.0;
00342 
00343     _history.push_back(element);
00344     
00345     // do any momentum preprocessing needed by the recombination scheme
00346     _jet_def.recombiner()->preprocess(_jets[i]);
00347 
00348     // get cross-referencing right from PseudoJets
00349     _jets[i].set_cluster_hist_index(i);
00350     _set_structure_shared_ptr(_jets[i]);
00351 
00352     // determine the total energy in the event
00353     _Qtot += _jets[i].E();
00354   }
00355   _initial_n = _jets.size();
00356   _deletes_self_when_unused = false;
00357 }
00358 
00359 
00360 //----------------------------------------------------------------------
00361 // Return the component corresponding to the specified index.
00362 // taken from CLHEP
00363 string ClusterSequence::strategy_string (Strategy strategy_in)  const {
00364   string strategy;
00365   switch(strategy_in) {
00366   case NlnN:
00367     strategy = "NlnN"; break;
00368   case NlnN3pi:
00369     strategy = "NlnN3pi"; break;
00370   case NlnN4pi:
00371     strategy = "NlnN4pi"; break;
00372   case N2Plain:
00373     strategy = "N2Plain"; break;
00374   case N2Tiled:
00375     strategy = "N2Tiled"; break;
00376   case N2MinHeapTiled:
00377     strategy = "N2MinHeapTiled"; break;
00378   case N2PoorTiled:
00379     strategy = "N2PoorTiled"; break;
00380   case N3Dumb:
00381     strategy = "N3Dumb"; break;
00382   case NlnNCam4pi:
00383     strategy = "NlnNCam4pi"; break;
00384   case NlnNCam2pi2R:
00385     strategy = "NlnNCam2pi2R"; break;
00386   case NlnNCam:
00387     strategy = "NlnNCam"; break; // 2piMultD
00388   case plugin_strategy:
00389     strategy = "plugin strategy"; break;
00390   default:
00391     strategy = "Unrecognized";
00392   }
00393   return strategy;
00394 }  
00395 
00396 
00397 double ClusterSequence::jet_scale_for_algorithm(
00398                                   const PseudoJet & jet) const {
00399   if (_jet_algorithm == kt_algorithm)             {return jet.kt2();}
00400   else if (_jet_algorithm == cambridge_algorithm) {return 1.0;}
00401   else if (_jet_algorithm == antikt_algorithm) {
00402     double kt2=jet.kt2();
00403     return kt2 > 1e-300 ? 1.0/kt2 : 1e300;
00404   } else if (_jet_algorithm == genkt_algorithm) {
00405     double kt2 = jet.kt2();
00406     double p   = jet_def().extra_param();
00407     if (p <= 0 && kt2 < 1e-300) kt2 = 1e-300; // dodgy safety check
00408     return pow(kt2, p);
00409   } else if (_jet_algorithm == cambridge_for_passive_algorithm) {
00410     double kt2 = jet.kt2();
00411     double lim = _jet_def.extra_param();
00412     if (kt2 < lim*lim && kt2 != 0.0) {
00413       return 1.0/kt2;
00414     } else {return 1.0;}
00415   } else {throw Error("Unrecognised jet algorithm");}
00416 }
00417 
00418 
00419 // //----------------------------------------------------------------------
00420 // /// transfer the sequence contained in other_seq into our own;
00421 // /// any plugin "extras" contained in the from_seq will be lost
00422 // /// from there.
00423 // void ClusterSequence::transfer_from_sequence(ClusterSequence & from_seq) {
00424 // 
00425 //   if (will_delete_self_when_unused()) 
00426 //     throw(Error("cannot use CS::transfer_from_sequence after a call to delete_self_when_unused()"));
00427 // 
00428 //   // the metadata
00429 //   _jet_def                 = from_seq._jet_def                ;
00430 //   _writeout_combinations   = from_seq._writeout_combinations  ;
00431 //   _initial_n               = from_seq._initial_n              ;
00432 //   _Rparam                  = from_seq._Rparam                 ;
00433 //   _R2                      = from_seq._R2                     ;
00434 //   _invR2                   = from_seq._invR2                  ;
00435 //   _strategy                = from_seq._strategy               ;
00436 //   _jet_algorithm           = from_seq._jet_algorithm          ;
00437 //   _plugin_activated        = from_seq._plugin_activated       ;
00438 // 
00439 //   // the data
00440 //   _jets     = from_seq._jets;
00441 //   _history  = from_seq._history;
00442 //   // the following transfers ownership of the extras from the from_seq
00443 //   _extras   = from_seq._extras;
00444 // 
00445 //   // transfer of ownership
00446 //   if (_structure_shared_ptr()) {
00447 //     // anything that is currently associated with the cluster sequence
00448 //     // should be told that its cluster sequence no longer exists
00449 //     ClusterSequenceStructure* csi = dynamic_cast<ClusterSequenceStructure*>(_structure_shared_ptr()); 
00450 //     assert(csi != NULL);
00451 //     csi->set_associated_cs(NULL);
00452 //   }
00453 //   // create a new _structure_shared_ptr to reflect the fact that
00454 //   // this CS is essentially a new one
00455 //   _structure_shared_ptr.reset(new ClusterSequenceStructure(this));
00456 //   _update_structure_use_count();
00457 //   
00458 //   for (vector<PseudoJet>::iterator jit = _jets.begin(); jit != _jets.end(); jit++)
00459 //     _set_structure_shared_ptr(*jit);
00460 // }
00461 
00462 
00463 //----------------------------------------------------------------------
00464 // transfer the sequence contained in other_seq into our own;
00465 // any plugin "extras" contained in the from_seq will be lost
00466 // from there.
00467 //
00468 // It also sets the ClusterSequence pointers of the PseudoJets in
00469 // the history to point to this ClusterSequence
00470 //
00471 // The second argument is an action that will be applied on every
00472 // jets in the resulting ClusterSequence
00473 void ClusterSequence::transfer_from_sequence(ClusterSequence & from_seq,
00474                                              const FunctionOfPseudoJet<PseudoJet> * action_on_jets){
00475 
00476   if (will_delete_self_when_unused()) 
00477     throw(Error("cannot use CS::transfer_from_sequence after a call to delete_self_when_unused()"));
00478 
00479   // the metadata
00480   _jet_def                 = from_seq._jet_def                ;
00481   _writeout_combinations   = from_seq._writeout_combinations  ;
00482   _initial_n               = from_seq._initial_n              ;
00483   _Rparam                  = from_seq._Rparam                 ;
00484   _R2                      = from_seq._R2                     ;
00485   _invR2                   = from_seq._invR2                  ;
00486   _strategy                = from_seq._strategy               ;
00487   _jet_algorithm           = from_seq._jet_algorithm          ;
00488   _plugin_activated        = from_seq._plugin_activated       ;
00489 
00490   // the data
00491 
00492   // apply the transformation on the jets if needed
00493   if (action_on_jets)
00494     _jets     = (*action_on_jets)(from_seq._jets);
00495   else
00496     _jets     = from_seq._jets;
00497   _history  = from_seq._history;
00498   // the following transfers ownership of the extras from the from_seq
00499   _extras   = from_seq._extras;
00500 
00501   // transfer of ownership
00502   if (_structure_shared_ptr()) {
00503     // If there are jets associated with an old version of the CS and
00504     // a new one, keeping track of when to delete the CS becomes more
00505     // complex; so we don't allow this situation to occur.
00506     if (_deletes_self_when_unused) throw Error("transfer_from_sequence cannot be used for a cluster sequence that deletes self when unused");
00507     
00508     // anything that is currently associated with the cluster sequence
00509     // should be told that its cluster sequence no longer exists
00510     ClusterSequenceStructure* csi = dynamic_cast<ClusterSequenceStructure*>(_structure_shared_ptr()); 
00511     assert(csi != NULL);
00512     csi->set_associated_cs(NULL);
00513   }
00514   // create a new _structure_shared_ptr to reflect the fact that
00515   // this CS is essentially a new one
00516   _structure_shared_ptr.reset(new ClusterSequenceStructure(this));
00517   _update_structure_use_count();
00518   
00519   for (unsigned int i=0; i<_jets.size(); i++){
00520     // we reset the cluster history index in case action_on_jets
00521     // messed up with it
00522     _jets[i].set_cluster_hist_index(from_seq._jets[i].cluster_hist_index());
00523 
00524     // reset the structure pointer
00525     _set_structure_shared_ptr(_jets[i]);
00526   }
00527 }
00528 
00529 
00530 //----------------------------------------------------------------------
00531 // record an ij recombination and reset the _jets[newjet_k] momentum and
00532 // user index to be those of newjet
00533 void ClusterSequence::plugin_record_ij_recombination(
00534            int jet_i, int jet_j, double dij, 
00535            const PseudoJet & newjet, int & newjet_k) {
00536 
00537   plugin_record_ij_recombination(jet_i, jet_j, dij, newjet_k);
00538 
00539   // now transfer newjet into place
00540   int tmp_index = _jets[newjet_k].cluster_hist_index();
00541   _jets[newjet_k] = newjet;
00542   _jets[newjet_k].set_cluster_hist_index(tmp_index);
00543   _set_structure_shared_ptr(_jets[newjet_k]);
00544 }
00545 
00546 
00547 //----------------------------------------------------------------------
00548 // return all inclusive jets with pt > ptmin
00549 vector<PseudoJet> ClusterSequence::inclusive_jets (const double & ptmin) const{
00550   double dcut = ptmin*ptmin;
00551   int i = _history.size() - 1; // last jet
00552   vector<PseudoJet> jets;
00553   if (_jet_algorithm == kt_algorithm) {
00554     while (i >= 0) {
00555       // with our specific definition of dij and diB (i.e. R appears only in 
00556       // dij), then dij==diB is the same as the jet.perp2() and we can exploit
00557       // this in selecting the jets...
00558       if (_history[i].max_dij_so_far < dcut) {break;}
00559       if (_history[i].parent2 == BeamJet && _history[i].dij >= dcut) {
00560         // for beam jets
00561         int parent1 = _history[i].parent1;
00562         jets.push_back(_jets[_history[parent1].jetp_index]);}
00563       i--;
00564     }
00565   } else if (_jet_algorithm == cambridge_algorithm) {
00566     while (i >= 0) {
00567       // inclusive jets are all at end of clustering sequence in the
00568       // Cambridge algorithm -- so if we find a non-exclusive jet, then
00569       // we can exit
00570       if (_history[i].parent2 != BeamJet) {break;}
00571       int parent1 = _history[i].parent1;
00572       const PseudoJet & jet = _jets[_history[parent1].jetp_index];
00573       if (jet.perp2() >= dcut) {jets.push_back(jet);}
00574       i--;
00575     }
00576   } else if (_jet_algorithm == plugin_algorithm 
00577              || _jet_algorithm == ee_kt_algorithm
00578              || _jet_algorithm == antikt_algorithm
00579              || _jet_algorithm == genkt_algorithm
00580              || _jet_algorithm == ee_genkt_algorithm
00581              || _jet_algorithm == cambridge_for_passive_algorithm) {
00582     // for inclusive jets with a plugin algorithm, we make no
00583     // assumptions about anything (relation of dij to momenta,
00584     // ordering of the dij, etc.)
00585     while (i >= 0) {
00586       if (_history[i].parent2 == BeamJet) {
00587         int parent1 = _history[i].parent1;
00588         const PseudoJet & jet = _jets[_history[parent1].jetp_index];
00589         if (jet.perp2() >= dcut) {jets.push_back(jet);}
00590       }
00591       i--;
00592     }
00593   } else {throw Error("cs::inclusive_jets(...): Unrecognized jet algorithm");}
00594   return jets;
00595 }
00596 
00597 
00598 //----------------------------------------------------------------------
00599 // return the number of exclusive jets that would have been obtained
00600 // running the algorithm in exclusive mode with the given dcut
00601 int ClusterSequence::n_exclusive_jets (const double & dcut) const {
00602 
00603   // first locate the point where clustering would have stopped (i.e. the
00604   // first time max_dij_so_far > dcut)
00605   int i = _history.size() - 1; // last jet
00606   while (i >= 0) {
00607     if (_history[i].max_dij_so_far <= dcut) {break;}
00608     i--;
00609   }
00610   int stop_point = i + 1;
00611   // relation between stop_point, njets assumes one extra jet disappears
00612   // at each clustering.
00613   int njets = 2*_initial_n - stop_point;
00614   return njets;
00615 }
00616 
00617 //----------------------------------------------------------------------
00618 // return all exclusive jets that would have been obtained running
00619 // the algorithm in exclusive mode with the given dcut
00620 vector<PseudoJet> ClusterSequence::exclusive_jets (const double & dcut) const {
00621   int njets = n_exclusive_jets(dcut);
00622   return exclusive_jets(njets);
00623 }
00624 
00625 
00626 //----------------------------------------------------------------------
00627 // return the jets obtained by clustering the event to n jets.
00628 vector<PseudoJet> ClusterSequence::exclusive_jets (const int & njets) const {
00629 
00630   // make sure the user does not ask for more than jets than there
00631   // were particles in the first place.
00632   assert (njets <= _initial_n);
00633 
00634   // provide a warning when extracting exclusive jets for algorithms 
00635   // that does not support it explicitly.
00636   // Native algorithm that support it are: kt, ee_kt, cambridge, 
00637   //   genkt and ee_genkt (both with p>=0)
00638   // For plugins, we check Plugin::exclusive_sequence_meaningful()
00639   if (( _jet_def.jet_algorithm() != kt_algorithm) &&
00640       ( _jet_def.jet_algorithm() != cambridge_algorithm) &&
00641       ( _jet_def.jet_algorithm() != ee_kt_algorithm) &&
00642       (((_jet_def.jet_algorithm() != genkt_algorithm) && 
00643         (_jet_def.jet_algorithm() != ee_genkt_algorithm)) || 
00644        (_jet_def.extra_param() <0)) &&
00645       ((_jet_def.jet_algorithm() != plugin_algorithm) ||
00646        (!_jet_def.plugin()->exclusive_sequence_meaningful())) &&
00647       (_n_exclusive_warnings < 5)) {
00648     _n_exclusive_warnings++;
00649     cerr << "FastJet WARNING: dcut and exclusive jets for jet-finders other than kt should be interpreted with care." << endl;
00650   }
00651 
00652 
00653   // calculate the point where we have to stop the clustering.
00654   // relation between stop_point, njets assumes one extra jet disappears
00655   // at each clustering.
00656   int stop_point = 2*_initial_n - njets;
00657 
00658   // some sanity checking to make sure that e+e- does not give us
00659   // surprises (should we ever implement e+e-)...
00660   if (2*_initial_n != static_cast<int>(_history.size())) {
00661     ostringstream err;
00662     err << "2*_initial_n != _history.size() -- this endangers internal assumptions!\n";
00663     throw Error(err.str());
00664     //assert(false);
00665   }
00666 
00667   // now go forwards and reconstitute the jets that we have --
00668   // basically for any history element, see if the parent jets to
00669   // which it refers were created before the stopping point -- if they
00670   // were then add them to the list, otherwise they are subsequent
00671   // recombinations of the jets that we are looking for.
00672   vector<PseudoJet> jets;
00673   for (unsigned int i = stop_point; i < _history.size(); i++) {
00674     int parent1 = _history[i].parent1;
00675     if (parent1 < stop_point) {
00676       jets.push_back(_jets[_history[parent1].jetp_index]);
00677     }
00678     int parent2 = _history[i].parent2;
00679     if (parent2 < stop_point && parent2 > 0) {
00680       jets.push_back(_jets[_history[parent2].jetp_index]);
00681     }
00682     
00683   }
00684 
00685   // sanity check...
00686   if (static_cast<int>(jets.size()) != njets) {
00687     ostringstream err;
00688     err << "ClusterSequence::exclusive_jets: size of returned vector ("
00689          <<jets.size()<<") does not coincide with requested number of jets ("
00690          <<njets<<")";
00691     throw Error(err.str());
00692   }
00693 
00694   return jets;
00695 }
00696 
00697 //----------------------------------------------------------------------
00698 /// return the dmin corresponding to the recombination that went from
00699 /// n+1 to n jets
00700 double ClusterSequence::exclusive_dmerge (const int & njets) const {
00701   assert(njets >= 0);
00702   if (njets >= _initial_n) {return 0.0;}
00703   return _history[2*_initial_n-njets-1].dij;
00704 }
00705 
00706 
00707 //----------------------------------------------------------------------
00708 /// return the maximum of the dmin encountered during all recombinations 
00709 /// up to the one that led to an n-jet final state; identical to
00710 /// exclusive_dmerge, except in cases where the dmin do not increase
00711 /// monotonically.
00712 double ClusterSequence::exclusive_dmerge_max (const int & njets) const {
00713   assert(njets >= 0);
00714   if (njets >= _initial_n) {return 0.0;}
00715   return _history[2*_initial_n-njets-1].max_dij_so_far;
00716 }
00717 
00718 
00719 //----------------------------------------------------------------------
00720 /// return a vector of all subjets of the current jet (in the sense
00721 /// of the exclusive algorithm) that would be obtained when running
00722 /// the algorithm with the given dcut.
00723 std::vector<PseudoJet> ClusterSequence::exclusive_subjets 
00724    (const PseudoJet & jet, const double & dcut) const {
00725 
00726   set<const history_element*> subhist;
00727 
00728   // get the set of history elements that correspond to subjets at
00729   // scale dcut
00730   get_subhist_set(subhist, jet, dcut, 0);
00731 
00732   // now transfer this into a sequence of jets
00733   vector<PseudoJet> subjets;
00734   subjets.reserve(subhist.size());
00735   for (set<const history_element*>::iterator elem = subhist.begin(); 
00736        elem != subhist.end(); elem++) {
00737     subjets.push_back(_jets[(*elem)->jetp_index]);
00738   }
00739   return subjets;
00740 }
00741 
00742 //----------------------------------------------------------------------
00743 /// return the size of exclusive_subjets(...); still n ln n with same
00744 /// coefficient, but marginally more efficient than manually taking
00745 /// exclusive_subjets.size()
00746 int ClusterSequence::n_exclusive_subjets(const PseudoJet & jet, 
00747                         const double & dcut) const {
00748   set<const history_element*> subhist;
00749   // get the set of history elements that correspond to subjets at
00750   // scale dcut
00751   get_subhist_set(subhist, jet, dcut, 0);
00752   return subhist.size();
00753 }
00754 
00755 //----------------------------------------------------------------------
00756 /// return the list of subjets obtained by unclustering the supplied
00757 /// jet down to n subjets (or all constituents if there are fewer
00758 /// than n).
00759 std::vector<PseudoJet> ClusterSequence::exclusive_subjets 
00760    (const PseudoJet & jet, int n) const {
00761 
00762   set<const history_element*> subhist;
00763 
00764   // get the set of history elements that correspond to subjets at
00765   // scale dcut
00766   get_subhist_set(subhist, jet, -1.0, n);
00767 
00768   // now transfer this into a sequence of jets
00769   vector<PseudoJet> subjets;
00770   subjets.reserve(subhist.size());
00771   for (set<const history_element*>::iterator elem = subhist.begin(); 
00772        elem != subhist.end(); elem++) {
00773     subjets.push_back(_jets[(*elem)->jetp_index]);
00774   }
00775   return subjets;
00776 }
00777 
00778 
00779 //----------------------------------------------------------------------
00780 /// return the dij that was present in the merging nsub+1 -> nsub 
00781 /// subjets inside this jet.
00782 /// 
00783 /// If the jet has nsub or fewer constituents, it will return 0.
00784 double ClusterSequence::exclusive_subdmerge(const PseudoJet & jet, int nsub) const {
00785   set<const history_element*> subhist;
00786 
00787   // get the set of history elements that correspond to subjets at
00788   // scale dcut
00789   get_subhist_set(subhist, jet, -1.0, nsub);
00790   
00791   set<const history_element*>::iterator highest = subhist.end();
00792   highest--;
00793   /// will be zero if nconst <= nsub, since highest will be an original 
00794   /// particle have zero dij
00795   return (*highest)->dij;
00796 }
00797 
00798 
00799 //----------------------------------------------------------------------
00800 /// return the maximum dij that occurred in the whole event at the
00801 /// stage that the nsub+1 -> nsub merge of subjets occurred inside 
00802 /// this jet.
00803 ///
00804 /// If the jet has nsub or fewer constituents, it will return 0.
00805 double ClusterSequence::exclusive_subdmerge_max(const PseudoJet & jet, int nsub) const {
00806 
00807   set<const history_element*> subhist;
00808 
00809   // get the set of history elements that correspond to subjets at
00810   // scale dcut
00811   get_subhist_set(subhist, jet, -1.0, nsub);
00812   
00813   set<const history_element*>::iterator highest = subhist.end();
00814   highest--;
00815   /// will be zero if nconst <= nsub, since highest will be an original 
00816   /// particle have zero dij
00817   return (*highest)->max_dij_so_far;
00818 }
00819 
00820 
00821 
00822 //----------------------------------------------------------------------
00823 /// return a set of pointers to history entries corresponding to the
00824 /// subjets of this jet; one stops going working down through the
00825 /// subjets either when 
00826 ///   - there is no further to go
00827 ///   - one has found maxjet entries
00828 ///   - max_dij_so_far <= dcut
00829 void ClusterSequence::get_subhist_set(set<const history_element*> & subhist,
00830                                      const  PseudoJet & jet, 
00831                                      double dcut, int maxjet) const {
00832   assert(contains(jet));
00833   
00834   subhist.clear();
00835   subhist.insert(&(_history[jet.cluster_hist_index()]));
00836 
00837   // establish the set of jets that are relevant
00838   int njet = 1;
00839   while (true) {
00840     // first find out if we need to probe deeper into jet.
00841     // Get history element closest to end of sequence
00842     set<const history_element*>::iterator highest = subhist.end();
00843     assert (highest != subhist.begin()); 
00844     highest--;
00845     const history_element* elem = *highest;
00846     // make sure we haven't got too many jets
00847     if (njet == maxjet) break;
00848     // make sure it has parents
00849     if (elem->parent1 < 0)            break;
00850     // make sure that we still resolve it at scale dcut
00851     if (elem->max_dij_so_far <= dcut) break;
00852 
00853     // then do so: replace "highest" with its two parents
00854     subhist.erase(highest);
00855     subhist.insert(&(_history[elem->parent1]));
00856     subhist.insert(&(_history[elem->parent2]));
00857     njet++;
00858   }
00859 }
00860 
00861 //----------------------------------------------------------------------
00862 // work through the object's history until
00863 bool ClusterSequence::object_in_jet(const PseudoJet & object, 
00864                                     const PseudoJet & jet) const {
00865 
00866   // make sure the object conceivably belongs to this clustering
00867   // sequence
00868   assert(contains(object) && contains(jet));
00869 
00870   const PseudoJet * this_object = &object;
00871   const PseudoJet * childp;
00872   while(true) {
00873     if (this_object->cluster_hist_index() == jet.cluster_hist_index()) {
00874       return true;
00875     } else if (has_child(*this_object, childp)) {
00876       this_object = childp;
00877     } else {
00878       return false;
00879     }
00880   }
00881 }
00882 
00883 //----------------------------------------------------------------------
00884 /// if the jet has parents in the clustering, it returns true
00885 /// and sets parent1 and parent2 equal to them.
00886 ///
00887 /// if it has no parents it returns false and sets parent1 and
00888 /// parent2 to zero
00889 bool ClusterSequence::has_parents(const PseudoJet & jet, PseudoJet & parent1, 
00890                               PseudoJet & parent2) const {
00891 
00892   const history_element & hist = _history[jet.cluster_hist_index()];
00893 
00894   // make sure we do not run into any unexpected situations --
00895   // i.e. both parents valid, or neither
00896   assert ((hist.parent1 >= 0 && hist.parent2 >= 0) || 
00897           (hist.parent1 < 0 && hist.parent2 < 0));
00898 
00899   if (hist.parent1 < 0) {
00900     parent1 = PseudoJet(0.0,0.0,0.0,0.0);
00901     parent2 = parent1;
00902     return false;
00903   } else {
00904     parent1 = _jets[_history[hist.parent1].jetp_index];
00905     parent2 = _jets[_history[hist.parent2].jetp_index];
00906     // order the parents in decreasing pt
00907     if (parent1.perp2() < parent2.perp2()) std::swap(parent1,parent2);
00908     return true;
00909   }
00910 }
00911 
00912 //----------------------------------------------------------------------
00913 /// if the jet has a child then return true and give the child jet
00914 /// otherwise return false and set the child to zero
00915 bool ClusterSequence::has_child(const PseudoJet & jet, PseudoJet & child) const {
00916 
00917   //const history_element & hist = _history[jet.cluster_hist_index()];
00918   //
00919   //if (hist.child >= 0) {
00920   //  child = _jets[_history[hist.child].jetp_index];
00921   //  return true;
00922   //} else {
00923   //  child = PseudoJet(0.0,0.0,0.0,0.0);
00924   //  return false;
00925   //}
00926   const PseudoJet * childp;
00927   bool res = has_child(jet, childp);
00928   if (res) {
00929     child = *childp;
00930     return true;
00931   } else {
00932     child = PseudoJet(0.0,0.0,0.0,0.0);
00933     return false;
00934   }
00935 }
00936 
00937 bool ClusterSequence::has_child(const PseudoJet & jet, const PseudoJet * & childp) const {
00938 
00939   const history_element & hist = _history[jet.cluster_hist_index()];
00940 
00941   // check that this jet has a child and that the child corresponds to
00942   // a true jet [RETHINK-IF-CHANGE-NUMBERING: what is the right
00943   // behaviour if the child is the same jet but made inclusive...?]
00944   if (hist.child >= 0 && _history[hist.child].jetp_index >= 0) {
00945     childp = &(_jets[_history[hist.child].jetp_index]);
00946     return true;
00947   } else {
00948     childp = NULL;
00949     return false;
00950   }
00951 }
00952 
00953 
00954 //----------------------------------------------------------------------
00955 /// if this jet has a child (and so a partner) return true
00956 /// and give the partner, otherwise return false and set the
00957 /// partner to zero
00958 bool ClusterSequence::has_partner(const PseudoJet & jet, 
00959                               PseudoJet & partner) const {
00960 
00961   const history_element & hist = _history[jet.cluster_hist_index()];
00962 
00963   // make sure we have a child and that the child does not correspond
00964   // to a clustering with the beam (or some other invalid quantity)
00965   if (hist.child >= 0 && _history[hist.child].parent2 >= 0) {
00966     const history_element & child_hist = _history[hist.child];
00967     if (child_hist.parent1 == jet.cluster_hist_index()) {
00968       // partner will be child's parent2 -- for iB clustering
00969       // parent2 will not be valid
00970       partner = _jets[_history[child_hist.parent2].jetp_index];
00971     } else {
00972       // partner will be child's parent1
00973       partner = _jets[_history[child_hist.parent1].jetp_index];
00974     }
00975     return true;
00976   } else {
00977     partner = PseudoJet(0.0,0.0,0.0,0.0);
00978     return false;
00979   }
00980 }
00981 
00982 
00983 //----------------------------------------------------------------------
00984 // return a vector of the particles that make up a jet
00985 vector<PseudoJet> ClusterSequence::constituents (const PseudoJet & jet) const {
00986   vector<PseudoJet> subjets;
00987   add_constituents(jet, subjets);
00988   return subjets;
00989 }
00990 
00991 //----------------------------------------------------------------------
00992 /// output the supplied vector of jets in a format that can be read
00993 /// by an appropriate root script; the format is:
00994 /// jet-n jet-px jet-py jet-pz jet-E 
00995 ///   particle-n particle-rap particle-phi particle-pt
00996 ///   particle-n particle-rap particle-phi particle-pt
00997 ///   ...
00998 /// #END
00999 /// ... [i.e. above repeated]
01000 void ClusterSequence::print_jets_for_root(const std::vector<PseudoJet> & jets, 
01001                                           ostream & ostr) const {
01002   for (unsigned i = 0; i < jets.size(); i++) {
01003     ostr << i  << " "
01004          << jets[i].px() << " "
01005          << jets[i].py() << " "
01006          << jets[i].pz() << " "
01007          << jets[i].E() << endl;
01008     vector<PseudoJet> cst = constituents(jets[i]);
01009     for (unsigned j = 0; j < cst.size() ; j++) {
01010       ostr << " " << j << " "
01011            << cst[j].rap() << " "
01012            << cst[j].phi() << " "
01013            << cst[j].perp() << endl;
01014     }
01015     ostr << "#END" << endl;
01016   }
01017 }
01018 
01019 void ClusterSequence::print_jets_for_root(const std::vector<PseudoJet> & jets, 
01020                                           const std::string & filename,
01021                                           const std::string & comment ) const {
01022   std::ofstream ostr(filename.c_str());
01023   if (comment != "") ostr << "# " << comment << endl;
01024   print_jets_for_root(jets, ostr);
01025 }
01026 
01027 
01028 // Not yet. Perhaps in a future release
01029 // //----------------------------------------------------------------------
01030 // // print out all inclusive jets with pt > ptmin
01031 // void ClusterSequence::print_jets (const double & ptmin) const{
01032 //     vector<PseudoJet> jets = sorted_by_pt(inclusive_jets(ptmin));
01033 // 
01034 //     for (size_t j = 0; j < jets.size(); j++) {
01035 //        printf("%5u %7.3f %7.3f %9.3f\n",
01036 //        j,jets[j].rap(),jets[j].phi(),jets[j].perp());
01037 //     }
01038 // }
01039 
01040 //----------------------------------------------------------------------
01041 /// returns a vector of size n_particles() which indicates, for 
01042 /// each of the initial particles (in the order in which they were
01043 /// supplied), which of the supplied jets it belongs to; if it does
01044 /// not belong to any of the supplied jets, the index is set to -1;
01045 vector<int> ClusterSequence::particle_jet_indices(
01046                         const vector<PseudoJet> & jets) const {
01047 
01048   vector<int> indices(n_particles());
01049 
01050   // first label all particles as not belonging to any jets
01051   for (unsigned ipart = 0; ipart < n_particles(); ipart++) 
01052     indices[ipart] = -1;
01053 
01054   // then for each of the jets relabel its consituents as belonging to
01055   // that jet
01056   for (unsigned ijet = 0; ijet < jets.size(); ijet++) {
01057 
01058     vector<PseudoJet> jet_constituents(constituents(jets[ijet]));
01059 
01060     for (unsigned ip = 0; ip < jet_constituents.size(); ip++) {
01061       // a safe (if slightly redundant) way of getting the particle
01062       // index (for initial particles it is actually safe to assume
01063       // ipart=iclust).
01064       unsigned iclust = jet_constituents[ip].cluster_hist_index();
01065       unsigned ipart = history()[iclust].jetp_index;
01066       indices[ipart] = ijet;
01067     }
01068   }
01069 
01070   return indices;
01071 }
01072 
01073 
01074 //----------------------------------------------------------------------
01075 // recursive routine that adds on constituents of jet to the subjet_vector
01076 void ClusterSequence::add_constituents (
01077            const PseudoJet & jet, vector<PseudoJet> & subjet_vector) const {
01078   // find out position in cluster history
01079   int i = jet.cluster_hist_index();
01080   int parent1 = _history[i].parent1;
01081   int parent2 = _history[i].parent2;
01082 
01083   if (parent1 == InexistentParent) {
01084     // It is an original particle (labelled by its parent having value
01085     // InexistentParent), therefore add it on to the subjet vector
01086     // Note: we add the initial particle and not simply 'jet' so that
01087     //       calling add_constituents with a subtracted jet containing
01088     //       only one particle will work.
01089     subjet_vector.push_back(_jets[i]);
01090     return;
01091   } 
01092 
01093   // add parent 1
01094   add_constituents(_jets[_history[parent1].jetp_index], subjet_vector);
01095 
01096   // see if parent2 is a real jet; if it is then add its constituents
01097   if (parent2 != BeamJet) {
01098     add_constituents(_jets[_history[parent2].jetp_index], subjet_vector);
01099   }
01100 }
01101 
01102 
01103 
01104 //----------------------------------------------------------------------
01105 // initialise the history in a standard way
01106 void ClusterSequence::_add_step_to_history (
01107                const int & step_number, const int & parent1, 
01108                const int & parent2, const int & jetp_index,
01109                const double & dij) {
01110 
01111   history_element element;
01112   element.parent1 = parent1;
01113   element.parent2 = parent2;
01114   element.jetp_index = jetp_index;
01115   element.child = Invalid;
01116   element.dij   = dij;
01117   element.max_dij_so_far = max(dij,_history[_history.size()-1].max_dij_so_far);
01118   _history.push_back(element);
01119 
01120   int local_step = _history.size()-1;
01121   assert(local_step == step_number);
01122 
01123   assert(parent1 >= 0);
01124   _history[parent1].child = local_step;
01125   if (parent2 >= 0) {_history[parent2].child = local_step;}
01126 
01127   // get cross-referencing right from PseudoJets
01128   if (jetp_index != Invalid) {
01129     assert(jetp_index >= 0);
01130     //cout << _jets.size() <<" "<<jetp_index<<"\n";
01131     _jets[jetp_index].set_cluster_hist_index(local_step);
01132     _set_structure_shared_ptr(_jets[jetp_index]);
01133   }
01134 
01135   if (_writeout_combinations) {
01136     cout << local_step << ": " 
01137          << parent1 << " with " << parent2
01138          << "; y = "<< dij<<endl;
01139   }
01140 
01141 }
01142 
01143 
01144 
01145 
01146 //======================================================================
01147 // Return an order in which to read the history such that _history[order[i]] 
01148 // will always correspond to the same set of consituent particles if 
01149 // two branching histories are equivalent in terms of the particles
01150 // contained in any given pseudojet.
01151 vector<int> ClusterSequence::unique_history_order() const {
01152 
01153   // first construct an array that will tell us the lowest constituent
01154   // of a given jet -- this will always be one of the original
01155   // particles, whose order is well defined and so will help us to
01156   // follow the tree in a unique manner.
01157   valarray<int> lowest_constituent(_history.size());
01158   int hist_n = _history.size();
01159   lowest_constituent = hist_n; // give it a large number
01160   for (int i = 0; i < hist_n; i++) {
01161     // sets things up for the initial partons
01162     lowest_constituent[i] = min(lowest_constituent[i],i); 
01163     // propagates them through to the children of this parton
01164     if (_history[i].child > 0) lowest_constituent[_history[i].child] 
01165       = min(lowest_constituent[_history[i].child],lowest_constituent[i]);
01166   }
01167 
01168   // establish an array for what we have and have not extracted so far
01169   valarray<bool> extracted(_history.size()); extracted = false;
01170   vector<int> unique_tree;
01171   unique_tree.reserve(_history.size());
01172 
01173   // now work our way through the tree
01174   for (unsigned i = 0; i < n_particles(); i++) {
01175     if (!extracted[i]) {
01176       unique_tree.push_back(i);
01177       extracted[i] = true;
01178       _extract_tree_children(i, extracted, lowest_constituent, unique_tree);
01179     }
01180   }
01181 
01182   return unique_tree;
01183 }
01184 
01185 //======================================================================
01186 // helper for unique_history_order
01187 void ClusterSequence::_extract_tree_children(
01188        int position, 
01189        valarray<bool> & extracted, 
01190        const valarray<int> & lowest_constituent,
01191        vector<int> & unique_tree) const {
01192   if (!extracted[position]) {
01193     // that means we may have unidentified parents around, so go and
01194     // collect them (extracted[position]) will then be made true)
01195     _extract_tree_parents(position,extracted,lowest_constituent,unique_tree);
01196   } 
01197   
01198   // now look after the children...
01199   int child = _history[position].child;
01200   if (child  >= 0) _extract_tree_children(child,extracted,lowest_constituent,unique_tree);
01201 }
01202 
01203 
01204 //======================================================================
01205 // return the list of unclustered particles
01206 vector<PseudoJet> ClusterSequence::unclustered_particles() const {
01207   vector<PseudoJet> unclustered;
01208   for (unsigned i = 0; i < n_particles() ; i++) {
01209     if (_history[i].child == Invalid) 
01210       unclustered.push_back(_jets[_history[i].jetp_index]);
01211   }
01212   return unclustered;
01213 }
01214 
01215 
01216 
01217 //----------------------------------------------------------------------
01218 // returns true if the cluster sequence contains this jet (i.e. jet's
01219 // structure is this cluster sequence's and the cluster history index
01220 // is in a consistent range)
01221 bool ClusterSequence::contains(const PseudoJet & jet) const {
01222   return jet.cluster_hist_index() >= 0 
01223     &&   jet.cluster_hist_index() < int(_history.size())
01224     &&   jet.has_valid_cluster_sequence()
01225     &&   jet.associated_cluster_sequence() == this;
01226 }
01227 
01228 
01229 
01230 //======================================================================
01231 // helper for unique_history_order
01232 void ClusterSequence::_extract_tree_parents(
01233        int position, 
01234        valarray<bool> & extracted, 
01235        const valarray<int> & lowest_constituent,
01236        vector<int> & unique_tree) const {
01237 
01238   if (!extracted[position]) {
01239     int parent1 = _history[position].parent1;
01240     int parent2 = _history[position].parent2;
01241     // where relevant order parents so that we will first treat the
01242     // one containing the smaller "lowest_constituent"
01243     if (parent1 >= 0 && parent2 >= 0) {
01244       if (lowest_constituent[parent1] > lowest_constituent[parent2]) 
01245         std::swap(parent1, parent2);
01246     }
01247     // then actually run through the parents to extract the constituents...
01248     if (parent1 >= 0 && !extracted[parent1]) 
01249       _extract_tree_parents(parent1,extracted,lowest_constituent,unique_tree);
01250     if (parent2 >= 0 && !extracted[parent2]) 
01251       _extract_tree_parents(parent2,extracted,lowest_constituent,unique_tree);
01252     // finally declare this position to be accounted for and push it
01253     // onto our list.
01254     unique_tree.push_back(position);
01255     extracted[position] = true;
01256   }
01257 }
01258 
01259 
01260 //======================================================================
01261 /// carries out the bookkeeping associated with the step of recombining
01262 /// jet_i and jet_j (assuming a distance dij) and returns the index
01263 /// of the recombined jet, newjet_k.
01264 void ClusterSequence::_do_ij_recombination_step(
01265                                const int & jet_i, const int & jet_j, 
01266                                const double & dij, 
01267                                int & newjet_k) {
01268 
01269   // create the new jet by recombining the first two
01270   PseudoJet newjet;
01271   _jet_def.recombiner()->recombine(_jets[jet_i], _jets[jet_j], newjet);
01272   _jets.push_back(newjet);
01273   // original version...
01274   //_jets.push_back(_jets[jet_i] + _jets[jet_j]);
01275 
01276   // get its index
01277   newjet_k = _jets.size()-1;
01278 
01279   // get history index
01280   int newstep_k = _history.size();
01281   // and provide jet with the info
01282   _jets[newjet_k].set_cluster_hist_index(newstep_k);
01283 
01284   // finally sort out the history 
01285   int hist_i = _jets[jet_i].cluster_hist_index();
01286   int hist_j = _jets[jet_j].cluster_hist_index();
01287 
01288   _add_step_to_history(newstep_k, min(hist_i, hist_j), max(hist_i,hist_j),
01289                        newjet_k, dij);
01290 
01291 }
01292 
01293 
01294 //======================================================================
01295 /// carries out the bookkeeping associated with the step of recombining
01296 /// jet_i with the beam
01297 void ClusterSequence::_do_iB_recombination_step(
01298                                   const int & jet_i, const double & diB) {
01299   // get history index
01300   int newstep_k = _history.size();
01301 
01302   // recombine the jet with the beam
01303   _add_step_to_history(newstep_k,_jets[jet_i].cluster_hist_index(),BeamJet,
01304                        Invalid, diB);
01305 
01306 }
01307 
01308 
01309 // make sure the static member _changed_strategy_warning is defined. 
01310 LimitedWarning ClusterSequence::_changed_strategy_warning;
01311 
01312 
01313 //----------------------------------------------------------------------
01314 void ClusterSequence::_set_structure_shared_ptr(PseudoJet & j) {
01315   j.set_structure_shared_ptr(_structure_shared_ptr);
01316   // record the use count of the structure shared point to help
01317   // in case we want to ask the CS to handle its own memory
01318   _update_structure_use_count();
01319 }
01320 
01321 
01322 //----------------------------------------------------------------------
01323 void ClusterSequence::_update_structure_use_count() {
01324   // record the use count of the structure shared point to help
01325   // in case we want to ask the CS to handle its own memory
01326   _structure_use_count_after_construction = _structure_shared_ptr.use_count();
01327 }
01328 
01329 //----------------------------------------------------------------------
01330 /// by calling this routine you tell the ClusterSequence to delete
01331 /// itself when all the Pseudojets associated with it have gone out
01332 /// of scope. 
01333 void ClusterSequence::delete_self_when_unused() {
01334   // the trick we use to handle this is to modify the use count; 
01335   // that way the structure will be deleted when there are no external
01336   // objects left associated the CS and the structure's destructor will then
01337   // look after deleting the cluster sequence
01338   
01339   // first make sure that there is at least one other object
01340   // associated with the CS
01341   int new_count = _structure_shared_ptr.use_count() - _structure_use_count_after_construction;
01342   if (new_count <= 0) {
01343     throw Error("delete_self_when_unused may only be called if at least one object outside the CS (e.g. a jet) is already associated with the CS");
01344   }
01345 
01346   _structure_shared_ptr.set_count(new_count);
01347   _deletes_self_when_unused = true;
01348 }
01349 
01350 
01351 FASTJET_END_NAMESPACE
01352 
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends