Fork me on GitHub

Changes in / [83ee320:2d7ff18] in git


Ignore:
Files:
25 deleted
40 edited

Legend:

Unmodified
Added
Removed
  • .circleci/config.yml

    r83ee320 r2d7ff18  
    88        command: |
    99          make distclean
    10           make -j 8 HAS_PYTHIA8=true
     10          make -j `nproc` HAS_PYTHIA8=true
    1111    - run:
    1212        name: Build Delphes using cmake
     
    1616          cd build
    1717          cmake ..
    18           make -j 8
     18          make -j `nproc`
    1919
    2020jobs:
     
    2727    docker:
    2828      - image: delphes/ubuntu:18.04
    29   fedora-30:
     29  fedora-28:
    3030    <<: *shared
    3131    docker:
    32       - image: delphes/fedora:30
     32      - image: delphes/fedora:28
    3333
    3434workflows:
     
    3838      - ubuntu-1404
    3939      - ubuntu-1804
    40       - fedora-30
     40      - fedora-28
  • CHANGELOG

    r83ee320 r2d7ff18  
    113.4.2:
    22- added DenseTrackFilter for modelling tracking inefficiencies in boosted, dense environments
    3 - added detector cards for CLIC, HL-LHC and IDEA detectors
     3- added detector cards for CLIC and HL-LHC detectors
    44- added muons to Tower collection used for jets reconstruction and MET calculation in the ATLAS card (#1118)
    55- added Weight branch to HepMC
  • Makefile

    r83ee320 r2d7ff18  
    413413        modules/DenseTrackFilter.h \
    414414        modules/Calorimeter.h \
    415         modules/DualReadoutCalorimeter.h \
    416415        modules/OldCalorimeter.h \
    417416        modules/Isolation.h \
     
    428427        modules/JetPileUpSubtractor.h \
    429428        modules/TrackPileUpSubtractor.h \
    430         modules/TrackTimingPileUpSubtractor.h \
    431429        modules/TaggingParticlesSkimmer.h \
    432430        modules/PileUpJetID.h \
     
    445443        modules/VertexFinder.h \
    446444        modules/VertexFinderDA4D.h \
    447         modules/HighMassVertexRecover.h \
    448         modules/DecayFilter.h \
    449445        modules/ExampleModule.h
    450446tmp/modules/ModulesDict$(PcmSuf): \
     
    698694        external/ExRootAnalysis/ExRootFilter.h \
    699695        external/ExRootAnalysis/ExRootResult.h
    700 tmp/modules/DecayFilter.$(ObjSuf): \
    701         modules/DecayFilter.$(SrcSuf) \
    702         modules/DecayFilter.h \
    703         classes/DelphesClasses.h \
    704         classes/DelphesFactory.h \
    705         classes/DelphesFormula.h \
    706         external/ExRootAnalysis/ExRootClassifier.h \
    707         external/ExRootAnalysis/ExRootFilter.h \
    708         external/ExRootAnalysis/ExRootResult.h
    709696tmp/modules/Delphes.$(ObjSuf): \
    710697        modules/Delphes.$(SrcSuf) \
     
    727714        external/ExRootAnalysis/ExRootFilter.h \
    728715        external/ExRootAnalysis/ExRootResult.h
    729 tmp/modules/DualReadoutCalorimeter.$(ObjSuf): \
    730         modules/DualReadoutCalorimeter.$(SrcSuf) \
    731         modules/DualReadoutCalorimeter.h \
    732         classes/DelphesClasses.h \
    733         classes/DelphesFactory.h \
    734         classes/DelphesFormula.h \
    735         external/ExRootAnalysis/ExRootResult.h \
    736         external/ExRootAnalysis/ExRootFilter.h \
    737         external/ExRootAnalysis/ExRootClassifier.h
    738716tmp/modules/Efficiency.$(ObjSuf): \
    739717        modules/Efficiency.$(SrcSuf) \
     
    784762        external/Hector/H_BeamParticle.h \
    785763        external/Hector/H_RecRPObject.h
    786 tmp/modules/HighMassVertexRecover.$(ObjSuf): \
    787         modules/HighMassVertexRecover.$(SrcSuf) \
    788         modules/HighMassVertexRecover.h \
    789         classes/DelphesClasses.h \
    790         classes/DelphesFactory.h \
    791         classes/DelphesFormula.h \
    792         external/ExRootAnalysis/ExRootResult.h \
    793         external/ExRootAnalysis/ExRootFilter.h \
    794         external/ExRootAnalysis/ExRootClassifier.h
    795764tmp/modules/IdentificationMap.$(ObjSuf): \
    796765        modules/IdentificationMap.$(SrcSuf) \
     
    1027996        modules/TrackSmearing.$(SrcSuf) \
    1028997        modules/TrackSmearing.h \
    1029         classes/DelphesClasses.h \
    1030         classes/DelphesFactory.h \
    1031         classes/DelphesFormula.h \
    1032         external/ExRootAnalysis/ExRootClassifier.h \
    1033         external/ExRootAnalysis/ExRootFilter.h \
    1034         external/ExRootAnalysis/ExRootResult.h
    1035 tmp/modules/TrackTimingPileUpSubtractor.$(ObjSuf): \
    1036         modules/TrackTimingPileUpSubtractor.$(SrcSuf) \
    1037         modules/TrackTimingPileUpSubtractor.h \
    1038998        classes/DelphesClasses.h \
    1039999        classes/DelphesFactory.h \
     
    10781038        classes/DelphesFormula.h \
    10791039        classes/DelphesPileUpReader.h \
    1080         external/ExRootAnalysis/ExRootResult.h \
    1081         external/ExRootAnalysis/ExRootFilter.h \
    1082         external/ExRootAnalysis/ExRootClassifier.h
     1040        external/ExRootAnalysis/ExRootClassifier.h \
     1041        external/ExRootAnalysis/ExRootFilter.h \
     1042        external/ExRootAnalysis/ExRootResult.h
    10831043tmp/modules/VertexSorter.$(ObjSuf): \
    10841044        modules/VertexSorter.$(SrcSuf) \
     
    11571117        tmp/modules/Cloner.$(ObjSuf) \
    11581118        tmp/modules/ConstituentFilter.$(ObjSuf) \
    1159         tmp/modules/DecayFilter.$(ObjSuf) \
    11601119        tmp/modules/Delphes.$(ObjSuf) \
    11611120        tmp/modules/DenseTrackFilter.$(ObjSuf) \
    1162         tmp/modules/DualReadoutCalorimeter.$(ObjSuf) \
    11631121        tmp/modules/Efficiency.$(ObjSuf) \
    11641122        tmp/modules/EnergyScale.$(ObjSuf) \
     
    11661124        tmp/modules/ExampleModule.$(ObjSuf) \
    11671125        tmp/modules/Hector.$(ObjSuf) \
    1168         tmp/modules/HighMassVertexRecover.$(ObjSuf) \
    11691126        tmp/modules/IdentificationMap.$(ObjSuf) \
    11701127        tmp/modules/ImpactParameterSmearing.$(ObjSuf) \
     
    11931150        tmp/modules/TrackPileUpSubtractor.$(ObjSuf) \
    11941151        tmp/modules/TrackSmearing.$(ObjSuf) \
    1195         tmp/modules/TrackTimingPileUpSubtractor.$(ObjSuf) \
    11961152        tmp/modules/TreeWriter.$(ObjSuf) \
    11971153        tmp/modules/UniqueObjectFinder.$(ObjSuf) \
     
    19551911        @touch $@
    19561912
    1957 modules/DecayFilter.h: \
    1958         classes/DelphesModule.h
    1959         @touch $@
    1960 
    19611913external/fastjet/internal/TilingExtent.hh: \
    19621914        external/fastjet/ClusterSequence.hh
     
    21152067        @touch $@
    21162068
    2117 modules/TrackTimingPileUpSubtractor.h: \
    2118         classes/DelphesModule.h
    2119         @touch $@
    2120 
    21212069modules/Delphes.h: \
    21222070        classes/DelphesModule.h
     
    22952243        @touch $@
    22962244
    2297 modules/HighMassVertexRecover.h: \
    2298         classes/DelphesModule.h \
    2299         classes/DelphesClasses.h
    2300         @touch $@
    2301 
    23022245classes/DelphesClasses.h: \
    23032246        classes/SortableObject.h
     
    23142257
    23152258modules/BeamSpotFilter.h: \
    2316         classes/DelphesModule.h
    2317         @touch $@
    2318 
    2319 modules/DualReadoutCalorimeter.h: \
    23202259        classes/DelphesModule.h
    23212260        @touch $@
  • README

    r83ee320 r2d7ff18  
    6666Open ROOT file and do some basic analysis using Draw or TBrowser:
    6767
    68    TFile *f = TFile::Open("delphes_output.root");
    69    f->Get("Delphes")->Draw("Electron.PT");
     68   TFile::Open("delphes_output.root");
     69   Delphes->Draw("Electron.PT");
    7070   TBrowser browser;
    7171
  • README.md

    r83ee320 r2d7ff18  
    8989
    9090```
    91    TFile *f = TFile::Open("delphes_output.root");
    92    f->Get("Delphes")->Draw("Electron.PT");
     91   TFile::Open("delphes_output.root");
     92   Delphes->Draw("Electron.PT");
    9393   TBrowser browser;
    9494```
  • cards/FCC/FCChh.tcl

    r83ee320 r2d7ff18  
    12391239
    12401240  (pt <= 10.0)                                                       * (0.00) +
    1241   (abs(eta) < 2.5) * (pt > 10.0 && pt < 5000.0)                      * (0.8)                      + \
    1242   (abs(eta) < 2.5) * (pt > 5000.0 && pt < 34000.0)                   * (0.8) *(8./9. - pt/30000.) + \
     1241  (abs(eta) < 2.5) * (pt > 10.0 && pt < 5000.0)                      * (0.6)                      + \
     1242  (abs(eta) < 2.5) * (pt > 5000.0 && pt < 34000.0)                   * (0.6) *(8./9. - pt/30000.) + \
    12431243  (abs(eta) < 2.5)                   * (pt > 34000.0)                * (0.000) + \
    1244   (abs(eta) > 2.5 && abs(eta) < 4.0) * (pt > 10.0 && pt < 5000.0)    * (0.65) + \
    1245   (abs(eta) > 2.5 && abs(eta) < 4.0) * (pt > 5000.0 && pt < 34000.0) * (0.65)*(8./9. - pt/30000.) + \
     1244  (abs(eta) > 2.5 && abs(eta) < 4.0) * (pt > 10.0 && pt < 5000.0)    * (0.45) + \
     1245  (abs(eta) > 2.5 && abs(eta) < 4.0) * (pt > 5000.0 && pt < 34000.0) * (0.45)*(8./9. - pt/30000.) + \
    12461246  (abs(eta) > 2.5 && abs(eta) < 4.0) * (pt > 34000.0)                * (0.00) + \
    12471247  (abs(eta) > 4.0)                                                   * (0.00)}
  • cards/delphes_card_CLICdet_Stage1.tcl

    r83ee320 r2d7ff18  
    11#######################################
    22# CLICdet model
    3 # based on arXiv:1812.07337 and
    4 # CLICdp-Note-2017-001
    5 #
     3# based on CLICdp-Note-2017-001
    64# Ulrike Schnoor ulrike.schnoor@cern.ch
    75#
     
    1311# according to final state
    1412#
    15 # c-tagging capabilities of CLICdet are
    16 # not yet implemented here. Please
    17 # contact us if you want to use it.
    18 #######################################
    19 
    2013#######################################
    2114# Order of execution of various modules
     
    714707    set OutputArray photons
    715708
    716     set DeltaRMax 0.1
     709    set DeltaRMax 0.5
    717710
    718711    set PTMin 0.5
    719712
    720     set PTRatioMax 0.2
     713    set PTRatioMax 0.12
    721714}
    722715
     
    812805    set OutputArray electrons
    813806
    814     set DeltaRMax 0.1
     807    set DeltaRMax 0.5
    815808
    816809    set PTMin 0.5
    817810
    818     set PTRatioMax 0.2
     811    set PTRatioMax 0.12
    819812}
    820813
     
    851844    set OutputArray muons
    852845
    853     set DeltaRMax 0.1
     846    set DeltaRMax 0.5
    854847
    855848    set PTMin 0.5
    856849
    857     set PTRatioMax 0.2
     850    set PTRatioMax 0.25
    858851}
    859852
  • cards/delphes_card_CLICdet_Stage2.tcl

    r83ee320 r2d7ff18  
    11#######################################
    22# CLICdet model
    3 # based on arXiv:1812.07337 and
    4 # CLICdp-Note-2017-001
    5 #
     3# based on CLICdp-Note-2017-001
    64# Ulrike Schnoor ulrike.schnoor@cern.ch
    75#
     
    1311# according to final state
    1412#
    15 # c-tagging capabilities of CLICdet are
    16 # not yet implemented here. Please
    17 # contact us if you want to use it.
    18 #######################################
    19 
    2013#######################################
    2114# Order of execution of various modules
     
    131124
    132125    JetFlavorAssociation_R05N2
    133     JetFlavorAssociation_R05N3
    134     JetFlavorAssociation_R05N4
    135     JetFlavorAssociation_R05N5
    136     JetFlavorAssociation_R05N6
    137    
    138     JetFlavorAssociation_R07N2
    139     JetFlavorAssociation_R07N3
    140     JetFlavorAssociation_R07N4
    141     JetFlavorAssociation_R07N5
    142     JetFlavorAssociation_R07N6
    143    
    144     JetFlavorAssociation_R10N2
    145     JetFlavorAssociation_R10N3
    146     JetFlavorAssociation_R10N4
    147     JetFlavorAssociation_R10N5
    148     JetFlavorAssociation_R10N6
    149    
    150     JetFlavorAssociation_R12N2
    151     JetFlavorAssociation_R12N3
    152     JetFlavorAssociation_R12N4
    153     JetFlavorAssociation_R12N5
    154     JetFlavorAssociation_R12N6
    155    
    156     JetFlavorAssociation_R15N2
    157     JetFlavorAssociation_R15N3
    158     JetFlavorAssociation_R15N4
    159     JetFlavorAssociation_R15N5
    160     JetFlavorAssociation_R15N6
    161    
    162     JetFlavorAssociation_R05_inclusive
    163     JetFlavorAssociation_R07_inclusive
    164     JetFlavorAssociation_R10_inclusive
    165     JetFlavorAssociation_R12_inclusive
    166     JetFlavorAssociation_R15_inclusive
    167 
    168 
    169     JetFlavorAssociation_JER_R05N2
    170     JetFlavorAssociation_JER_R05N3
    171     JetFlavorAssociation_JER_R05N4
    172     JetFlavorAssociation_JER_R05N5
    173     JetFlavorAssociation_JER_R05N6
    174    
    175     JetFlavorAssociation_JER_R07N2
    176     JetFlavorAssociation_JER_R07N3
    177     JetFlavorAssociation_JER_R07N4
    178     JetFlavorAssociation_JER_R07N5
    179     JetFlavorAssociation_JER_R07N6
    180    
    181     JetFlavorAssociation_JER_R10N2
    182     JetFlavorAssociation_JER_R10N3
    183     JetFlavorAssociation_JER_R10N4
    184     JetFlavorAssociation_JER_R10N5
    185     JetFlavorAssociation_JER_R10N6
    186    
    187     JetFlavorAssociation_JER_R12N2
    188     JetFlavorAssociation_JER_R12N3
    189     JetFlavorAssociation_JER_R12N4
    190     JetFlavorAssociation_JER_R12N5
    191     JetFlavorAssociation_JER_R12N6
    192    
    193     JetFlavorAssociation_JER_R15N2
    194     JetFlavorAssociation_JER_R15N3
    195     JetFlavorAssociation_JER_R15N4
    196     JetFlavorAssociation_JER_R15N5
    197     JetFlavorAssociation_JER_R15N6
    198    
    199     JetFlavorAssociation_JER_R05_inclusive
    200     JetFlavorAssociation_JER_R07_inclusive
    201     JetFlavorAssociation_JER_R10_inclusive
    202     JetFlavorAssociation_JER_R12_inclusive
    203     JetFlavorAssociation_JER_R15_inclusive
    204    
    205    
    206     BTaggingWP50_R05N2
    207     BTaggingWP70_R05N2
    208     BTaggingWP90_R05N2
    209     BTaggingWP50_R05N3
    210     BTaggingWP70_R05N3
    211     BTaggingWP90_R05N3
    212     BTaggingWP50_R05N4
    213     BTaggingWP70_R05N4
    214     BTaggingWP90_R05N4
    215     BTaggingWP50_R05N5
    216     BTaggingWP70_R05N5
    217     BTaggingWP90_R05N5
    218     BTaggingWP50_R05N6
    219     BTaggingWP70_R05N6
    220     BTaggingWP90_R05N6
    221     BTaggingWP50_R07N2
    222     BTaggingWP70_R07N2
    223     BTaggingWP90_R07N2
    224     BTaggingWP50_R07N3
    225     BTaggingWP70_R07N3
    226     BTaggingWP90_R07N3
    227     BTaggingWP50_R07N4
    228     BTaggingWP70_R07N4
    229     BTaggingWP90_R07N4
    230     BTaggingWP50_R07N5
    231     BTaggingWP70_R07N5
    232     BTaggingWP90_R07N5
    233     BTaggingWP50_R07N6
    234     BTaggingWP70_R07N6
    235     BTaggingWP90_R07N6
    236     BTaggingWP50_R10N2
    237     BTaggingWP70_R10N2
    238     BTaggingWP90_R10N2
    239     BTaggingWP50_R10N3
    240     BTaggingWP70_R10N3
    241     BTaggingWP90_R10N3
    242     BTaggingWP50_R10N4
    243     BTaggingWP70_R10N4
    244     BTaggingWP90_R10N4
    245     BTaggingWP50_R10N5
    246     BTaggingWP70_R10N5
    247     BTaggingWP90_R10N5
    248     BTaggingWP50_R10N6
    249     BTaggingWP70_R10N6
    250     BTaggingWP90_R10N6
    251     BTaggingWP50_R12N2
    252     BTaggingWP70_R12N2
    253     BTaggingWP90_R12N2
    254     BTaggingWP50_R12N3
    255     BTaggingWP70_R12N3
    256     BTaggingWP90_R12N3
    257     BTaggingWP50_R12N4
    258     BTaggingWP70_R12N4
    259     BTaggingWP90_R12N4
    260     BTaggingWP50_R12N5
    261     BTaggingWP70_R12N5
    262     BTaggingWP90_R12N5
    263     BTaggingWP50_R12N6
    264     BTaggingWP70_R12N6
    265     BTaggingWP90_R12N6
    266     BTaggingWP50_R15N2
    267     BTaggingWP70_R15N2
    268     BTaggingWP90_R15N2
    269     BTaggingWP50_R15N3
    270     BTaggingWP70_R15N3
    271     BTaggingWP90_R15N3
    272     BTaggingWP50_R15N4
    273     BTaggingWP70_R15N4
    274     BTaggingWP90_R15N4
    275     BTaggingWP50_R15N5
    276     BTaggingWP70_R15N5
    277     BTaggingWP90_R15N5
    278     BTaggingWP50_R15N6
    279     BTaggingWP70_R15N6
    280     BTaggingWP90_R15N6
     126        JetFlavorAssociation_R05N3
     127        JetFlavorAssociation_R05N4
     128        JetFlavorAssociation_R05N5
     129        JetFlavorAssociation_R05N6
     130       
     131        JetFlavorAssociation_R07N2
     132        JetFlavorAssociation_R07N3
     133        JetFlavorAssociation_R07N4
     134        JetFlavorAssociation_R07N5
     135        JetFlavorAssociation_R07N6
     136
     137        JetFlavorAssociation_R10N2
     138        JetFlavorAssociation_R10N3
     139        JetFlavorAssociation_R10N4
     140        JetFlavorAssociation_R10N5
     141        JetFlavorAssociation_R10N6
     142
     143        JetFlavorAssociation_R12N2
     144        JetFlavorAssociation_R12N3
     145        JetFlavorAssociation_R12N4
     146        JetFlavorAssociation_R12N5
     147        JetFlavorAssociation_R12N6
     148
     149        JetFlavorAssociation_R15N2
     150        JetFlavorAssociation_R15N3
     151        JetFlavorAssociation_R15N4
     152        JetFlavorAssociation_R15N5
     153        JetFlavorAssociation_R15N6
     154
     155        JetFlavorAssociation_R05_inclusive
     156        JetFlavorAssociation_R07_inclusive
     157        JetFlavorAssociation_R10_inclusive
     158        JetFlavorAssociation_R12_inclusive
     159        JetFlavorAssociation_R15_inclusive
     160
     161   
     162        BTaggingWP50_R05N2
     163        BTaggingWP70_R05N2
     164        BTaggingWP90_R05N2
     165        BTaggingWP50_R05N3
     166        BTaggingWP70_R05N3
     167        BTaggingWP90_R05N3
     168        BTaggingWP50_R05N4
     169        BTaggingWP70_R05N4
     170        BTaggingWP90_R05N4
     171        BTaggingWP50_R05N5
     172        BTaggingWP70_R05N5
     173        BTaggingWP90_R05N5
     174        BTaggingWP50_R05N6
     175        BTaggingWP70_R05N6
     176        BTaggingWP90_R05N6
     177        BTaggingWP50_R07N2
     178        BTaggingWP70_R07N2
     179        BTaggingWP90_R07N2
     180        BTaggingWP50_R07N3
     181        BTaggingWP70_R07N3
     182        BTaggingWP90_R07N3
     183        BTaggingWP50_R07N4
     184        BTaggingWP70_R07N4
     185        BTaggingWP90_R07N4
     186        BTaggingWP50_R07N5
     187        BTaggingWP70_R07N5
     188        BTaggingWP90_R07N5
     189        BTaggingWP50_R07N6
     190        BTaggingWP70_R07N6
     191        BTaggingWP90_R07N6
     192        BTaggingWP50_R10N2
     193        BTaggingWP70_R10N2
     194        BTaggingWP90_R10N2
     195        BTaggingWP50_R10N3
     196        BTaggingWP70_R10N3
     197        BTaggingWP90_R10N3
     198        BTaggingWP50_R10N4
     199        BTaggingWP70_R10N4
     200        BTaggingWP90_R10N4
     201        BTaggingWP50_R10N5
     202        BTaggingWP70_R10N5
     203        BTaggingWP90_R10N5
     204        BTaggingWP50_R10N6
     205        BTaggingWP70_R10N6
     206        BTaggingWP90_R10N6
     207        BTaggingWP50_R12N2
     208        BTaggingWP70_R12N2
     209        BTaggingWP90_R12N2
     210        BTaggingWP50_R12N3
     211        BTaggingWP70_R12N3
     212        BTaggingWP90_R12N3
     213        BTaggingWP50_R12N4
     214        BTaggingWP70_R12N4
     215        BTaggingWP90_R12N4
     216        BTaggingWP50_R12N5
     217        BTaggingWP70_R12N5
     218        BTaggingWP90_R12N5
     219        BTaggingWP50_R12N6
     220        BTaggingWP70_R12N6
     221        BTaggingWP90_R12N6
     222        BTaggingWP50_R15N2
     223        BTaggingWP70_R15N2
     224        BTaggingWP90_R15N2
     225        BTaggingWP50_R15N3
     226        BTaggingWP70_R15N3
     227        BTaggingWP90_R15N3
     228        BTaggingWP50_R15N4
     229        BTaggingWP70_R15N4
     230        BTaggingWP90_R15N4
     231        BTaggingWP50_R15N5
     232        BTaggingWP70_R15N5
     233        BTaggingWP90_R15N5
     234        BTaggingWP50_R15N6
     235        BTaggingWP70_R15N6
     236        BTaggingWP90_R15N6
    281237    BTaggingWP50_R05_inclusive
    282238    BTaggingWP70_R05_inclusive
     
    295251    BTaggingWP90_R15_inclusive
    296252
    297 
    298 
    299     BTagging_JER_WP50_R05N2
    300     BTagging_JER_WP70_R05N2
    301     BTagging_JER_WP90_R05N2
    302     BTagging_JER_WP50_R05N3
    303     BTagging_JER_WP70_R05N3
    304     BTagging_JER_WP90_R05N3
    305     BTagging_JER_WP50_R05N4
    306     BTagging_JER_WP70_R05N4
    307     BTagging_JER_WP90_R05N4
    308     BTagging_JER_WP50_R05N5
    309     BTagging_JER_WP70_R05N5
    310     BTagging_JER_WP90_R05N5
    311     BTagging_JER_WP50_R05N6
    312     BTagging_JER_WP70_R05N6
    313     BTagging_JER_WP90_R05N6
    314     BTagging_JER_WP50_R07N2
    315     BTagging_JER_WP70_R07N2
    316     BTagging_JER_WP90_R07N2
    317     BTagging_JER_WP50_R07N3
    318     BTagging_JER_WP70_R07N3
    319     BTagging_JER_WP90_R07N3
    320     BTagging_JER_WP50_R07N4
    321     BTagging_JER_WP70_R07N4
    322     BTagging_JER_WP90_R07N4
    323     BTagging_JER_WP50_R07N5
    324     BTagging_JER_WP70_R07N5
    325     BTagging_JER_WP90_R07N5
    326     BTagging_JER_WP50_R07N6
    327     BTagging_JER_WP70_R07N6
    328     BTagging_JER_WP90_R07N6
    329     BTagging_JER_WP50_R10N2
    330     BTagging_JER_WP70_R10N2
    331     BTagging_JER_WP90_R10N2
    332     BTagging_JER_WP50_R10N3
    333     BTagging_JER_WP70_R10N3
    334     BTagging_JER_WP90_R10N3
    335     BTagging_JER_WP50_R10N4
    336     BTagging_JER_WP70_R10N4
    337     BTagging_JER_WP90_R10N4
    338     BTagging_JER_WP50_R10N5
    339     BTagging_JER_WP70_R10N5
    340     BTagging_JER_WP90_R10N5
    341     BTagging_JER_WP50_R10N6
    342     BTagging_JER_WP70_R10N6
    343     BTagging_JER_WP90_R10N6
    344     BTagging_JER_WP50_R12N2
    345     BTagging_JER_WP70_R12N2
    346     BTagging_JER_WP90_R12N2
    347     BTagging_JER_WP50_R12N3
    348     BTagging_JER_WP70_R12N3
    349     BTagging_JER_WP90_R12N3
    350     BTagging_JER_WP50_R12N4
    351     BTagging_JER_WP70_R12N4
    352     BTagging_JER_WP90_R12N4
    353     BTagging_JER_WP50_R12N5
    354     BTagging_JER_WP70_R12N5
    355     BTagging_JER_WP90_R12N5
    356     BTagging_JER_WP50_R12N6
    357     BTagging_JER_WP70_R12N6
    358     BTagging_JER_WP90_R12N6
    359     BTagging_JER_WP50_R15N2
    360     BTagging_JER_WP70_R15N2
    361     BTagging_JER_WP90_R15N2
    362     BTagging_JER_WP50_R15N3
    363     BTagging_JER_WP70_R15N3
    364     BTagging_JER_WP90_R15N3
    365     BTagging_JER_WP50_R15N4
    366     BTagging_JER_WP70_R15N4
    367     BTagging_JER_WP90_R15N4
    368     BTagging_JER_WP50_R15N5
    369     BTagging_JER_WP70_R15N5
    370     BTagging_JER_WP90_R15N5
    371     BTagging_JER_WP50_R15N6
    372     BTagging_JER_WP70_R15N6
    373     BTagging_JER_WP90_R15N6
    374     BTagging_JER_WP50_R05_inclusive
    375     BTagging_JER_WP70_R05_inclusive
    376     BTagging_JER_WP90_R05_inclusive
    377     BTagging_JER_WP50_R07_inclusive
    378     BTagging_JER_WP70_R07_inclusive
    379     BTagging_JER_WP90_R07_inclusive
    380     BTagging_JER_WP50_R10_inclusive
    381     BTagging_JER_WP70_R10_inclusive
    382     BTagging_JER_WP90_R10_inclusive
    383     BTagging_JER_WP50_R12_inclusive
    384     BTagging_JER_WP70_R12_inclusive
    385     BTagging_JER_WP90_R12_inclusive
    386     BTagging_JER_WP50_R15_inclusive
    387     BTagging_JER_WP70_R15_inclusive
    388     BTagging_JER_WP90_R15_inclusive
    389    
    390253   
    391254    TauTagging_R05N2
     
    414277    TauTagging_R15N5
    415278    TauTagging_R15N6
     279
    416280    TauTagging_R05_inclusive
    417281    TauTagging_R07_inclusive
     
    419283    TauTagging_R12_inclusive
    420284    TauTagging_R15_inclusive
    421 
    422     TauTagging_JER_R05N2
    423     TauTagging_JER_R05N3
    424     TauTagging_JER_R05N4
    425     TauTagging_JER_R05N5
    426     TauTagging_JER_R05N6
    427     TauTagging_JER_R07N2
    428     TauTagging_JER_R07N3
    429     TauTagging_JER_R07N4
    430     TauTagging_JER_R07N5
    431     TauTagging_JER_R07N6
    432     TauTagging_JER_R10N2
    433     TauTagging_JER_R10N3
    434     TauTagging_JER_R10N4
    435     TauTagging_JER_R10N5
    436     TauTagging_JER_R10N6
    437     TauTagging_JER_R12N2
    438     TauTagging_JER_R12N3
    439     TauTagging_JER_R12N4
    440     TauTagging_JER_R12N5
    441     TauTagging_JER_R12N6
    442     TauTagging_JER_R15N2
    443     TauTagging_JER_R15N3
    444     TauTagging_JER_R15N4
    445     TauTagging_JER_R15N5
    446     TauTagging_JER_R15N6
    447     TauTagging_JER_R05_inclusive
    448     TauTagging_JER_R07_inclusive
    449     TauTagging_JER_R10_inclusive
    450     TauTagging_JER_R12_inclusive
    451     TauTagging_JER_R15_inclusive
    452285
    453286
     
    906739    set OutputArray photons
    907740
    908     set DeltaRMax 0.1
     741    set DeltaRMax 0.5
    909742
    910743    set PTMin 0.5
    911744
    912     set PTRatioMax 0.2
     745    set PTRatioMax 0.12
    913746}
    914747
     
    1004837    set OutputArray electrons
    1005838
    1006     set DeltaRMax 0.1
     839    set DeltaRMax 0.5
    1007840
    1008841    set PTMin 0.5
    1009842
    1010     set PTRatioMax 0.2
     843    set PTRatioMax 0.12
    1011844}
    1012845
     
    1042875    set OutputArray muons
    1043876
    1044     set DeltaRMax 0.1
     877    set DeltaRMax 0.5
    1045878
    1046879    set PTMin 0.5
    1047880
    1048     set PTRatioMax 0.2
     881    set PTRatioMax 0.25
    1049882}
    1050883
     
    11671000
    11681001source  CLIC/CLICdet_JetFlavorAssociation.tcl
    1169 source  CLIC/CLICdet_JetFlavorAssociation_JER.tcl
    11701002
    11711003###########
     
    11751007
    11761008source  CLIC/CLICdet_BTagging.tcl
    1177 source  CLIC/CLICdet_BTagging_JER.tcl
    11781009
    11791010
     
    11841015
    11851016source CLIC/CLICdet_TauTagging.tcl
    1186 source CLIC/CLICdet_TauTagging_JER.tcl
    11871017
    11881018
  • cards/delphes_card_CLICdet_Stage3.tcl

    r83ee320 r2d7ff18  
    11#######################################
    22# CLICdet model
    3 # based on arXiv:1812.07337 and
    4 # CLICdp-Note-2017-001
    5 #
     3# based on CLICdp-Note-2017-001
    64# Ulrike Schnoor ulrike.schnoor@cern.ch
     5#
    76#
    87# For the high energy stage of
     
    1211# use exclusive clustering with njets
    1312# according to final state
    14 #
    15 # c-tagging capabilities of CLICdet are
    16 # not yet implemented here. Please
    17 # contact us if you want to use it.
    18 #######################################
    19 
     13#
    2014#######################################
    2115# Order of execution of various modules
     
    131125
    132126    JetFlavorAssociation_R05N2
    133     JetFlavorAssociation_R05N3
    134     JetFlavorAssociation_R05N4
    135     JetFlavorAssociation_R05N5
    136     JetFlavorAssociation_R05N6
    137    
    138     JetFlavorAssociation_R07N2
    139     JetFlavorAssociation_R07N3
    140     JetFlavorAssociation_R07N4
    141     JetFlavorAssociation_R07N5
    142     JetFlavorAssociation_R07N6
    143 
    144     JetFlavorAssociation_R10N2
    145     JetFlavorAssociation_R10N3
    146     JetFlavorAssociation_R10N4
    147     JetFlavorAssociation_R10N5
    148     JetFlavorAssociation_R10N6
    149 
    150     JetFlavorAssociation_R12N2
    151     JetFlavorAssociation_R12N3
    152     JetFlavorAssociation_R12N4
    153     JetFlavorAssociation_R12N5
    154     JetFlavorAssociation_R12N6
    155 
    156     JetFlavorAssociation_R15N2
    157     JetFlavorAssociation_R15N3
    158     JetFlavorAssociation_R15N4
    159     JetFlavorAssociation_R15N5
    160     JetFlavorAssociation_R15N6
    161 
    162     JetFlavorAssociation_R05_inclusive
    163     JetFlavorAssociation_R07_inclusive
    164     JetFlavorAssociation_R10_inclusive
    165     JetFlavorAssociation_R12_inclusive
    166     JetFlavorAssociation_R15_inclusive
    167 
    168     JetFlavorAssociation_JER_R05N2
    169     JetFlavorAssociation_JER_R05N3
    170     JetFlavorAssociation_JER_R05N4
    171     JetFlavorAssociation_JER_R05N5
    172     JetFlavorAssociation_JER_R05N6
    173    
    174     JetFlavorAssociation_JER_R07N2
    175     JetFlavorAssociation_JER_R07N3
    176     JetFlavorAssociation_JER_R07N4
    177     JetFlavorAssociation_JER_R07N5
    178     JetFlavorAssociation_JER_R07N6
    179    
    180     JetFlavorAssociation_JER_R10N2
    181     JetFlavorAssociation_JER_R10N3
    182     JetFlavorAssociation_JER_R10N4
    183     JetFlavorAssociation_JER_R10N5
    184     JetFlavorAssociation_JER_R10N6
    185    
    186     JetFlavorAssociation_JER_R12N2
    187     JetFlavorAssociation_JER_R12N3
    188     JetFlavorAssociation_JER_R12N4
    189     JetFlavorAssociation_JER_R12N5
    190     JetFlavorAssociation_JER_R12N6
    191    
    192     JetFlavorAssociation_JER_R15N2
    193     JetFlavorAssociation_JER_R15N3
    194     JetFlavorAssociation_JER_R15N4
    195     JetFlavorAssociation_JER_R15N5
    196     JetFlavorAssociation_JER_R15N6
    197    
    198     JetFlavorAssociation_JER_R05_inclusive
    199     JetFlavorAssociation_JER_R07_inclusive
    200     JetFlavorAssociation_JER_R10_inclusive
    201     JetFlavorAssociation_JER_R12_inclusive
    202     JetFlavorAssociation_JER_R15_inclusive
    203    
    204     BTaggingWP50_R05N2
    205     BTaggingWP70_R05N2
    206     BTaggingWP90_R05N2
    207     BTaggingWP50_R05N3
    208     BTaggingWP70_R05N3
    209     BTaggingWP90_R05N3
    210     BTaggingWP50_R05N4
    211     BTaggingWP70_R05N4
    212     BTaggingWP90_R05N4
    213     BTaggingWP50_R05N5
    214     BTaggingWP70_R05N5
    215     BTaggingWP90_R05N5
    216     BTaggingWP50_R05N6
    217     BTaggingWP70_R05N6
    218     BTaggingWP90_R05N6
    219     BTaggingWP50_R07N2
    220     BTaggingWP70_R07N2
    221     BTaggingWP90_R07N2
    222     BTaggingWP50_R07N3
    223     BTaggingWP70_R07N3
    224     BTaggingWP90_R07N3
    225     BTaggingWP50_R07N4
    226     BTaggingWP70_R07N4
    227     BTaggingWP90_R07N4
    228     BTaggingWP50_R07N5
    229     BTaggingWP70_R07N5
    230     BTaggingWP90_R07N5
    231     BTaggingWP50_R07N6
    232     BTaggingWP70_R07N6
    233     BTaggingWP90_R07N6
    234     BTaggingWP50_R10N2
    235     BTaggingWP70_R10N2
    236     BTaggingWP90_R10N2
    237     BTaggingWP50_R10N3
    238     BTaggingWP70_R10N3
    239     BTaggingWP90_R10N3
    240     BTaggingWP50_R10N4
    241     BTaggingWP70_R10N4
    242     BTaggingWP90_R10N4
    243     BTaggingWP50_R10N5
    244     BTaggingWP70_R10N5
    245     BTaggingWP90_R10N5
    246     BTaggingWP50_R10N6
    247     BTaggingWP70_R10N6
    248     BTaggingWP90_R10N6
    249     BTaggingWP50_R12N2
    250     BTaggingWP70_R12N2
    251     BTaggingWP90_R12N2
    252     BTaggingWP50_R12N3
    253     BTaggingWP70_R12N3
    254     BTaggingWP90_R12N3
    255     BTaggingWP50_R12N4
    256     BTaggingWP70_R12N4
    257     BTaggingWP90_R12N4
    258     BTaggingWP50_R12N5
    259     BTaggingWP70_R12N5
    260     BTaggingWP90_R12N5
    261     BTaggingWP50_R12N6
    262     BTaggingWP70_R12N6
    263     BTaggingWP90_R12N6
    264     BTaggingWP50_R15N2
    265     BTaggingWP70_R15N2
    266     BTaggingWP90_R15N2
    267     BTaggingWP50_R15N3
    268     BTaggingWP70_R15N3
    269     BTaggingWP90_R15N3
    270     BTaggingWP50_R15N4
    271     BTaggingWP70_R15N4
    272     BTaggingWP90_R15N4
    273     BTaggingWP50_R15N5
    274     BTaggingWP70_R15N5
    275     BTaggingWP90_R15N5
    276     BTaggingWP50_R15N6
    277     BTaggingWP70_R15N6
    278     BTaggingWP90_R15N6
     127        JetFlavorAssociation_R05N3
     128        JetFlavorAssociation_R05N4
     129        JetFlavorAssociation_R05N5
     130        JetFlavorAssociation_R05N6
     131       
     132        JetFlavorAssociation_R07N2
     133        JetFlavorAssociation_R07N3
     134        JetFlavorAssociation_R07N4
     135        JetFlavorAssociation_R07N5
     136        JetFlavorAssociation_R07N6
     137
     138        JetFlavorAssociation_R10N2
     139        JetFlavorAssociation_R10N3
     140        JetFlavorAssociation_R10N4
     141        JetFlavorAssociation_R10N5
     142        JetFlavorAssociation_R10N6
     143
     144        JetFlavorAssociation_R12N2
     145        JetFlavorAssociation_R12N3
     146        JetFlavorAssociation_R12N4
     147        JetFlavorAssociation_R12N5
     148        JetFlavorAssociation_R12N6
     149
     150        JetFlavorAssociation_R15N2
     151        JetFlavorAssociation_R15N3
     152        JetFlavorAssociation_R15N4
     153        JetFlavorAssociation_R15N5
     154        JetFlavorAssociation_R15N6
     155
     156        JetFlavorAssociation_R05_inclusive
     157        JetFlavorAssociation_R07_inclusive
     158        JetFlavorAssociation_R10_inclusive
     159        JetFlavorAssociation_R12_inclusive
     160        JetFlavorAssociation_R15_inclusive
     161
     162   
     163        BTaggingWP50_R05N2
     164        BTaggingWP70_R05N2
     165        BTaggingWP90_R05N2
     166        BTaggingWP50_R05N3
     167        BTaggingWP70_R05N3
     168        BTaggingWP90_R05N3
     169        BTaggingWP50_R05N4
     170        BTaggingWP70_R05N4
     171        BTaggingWP90_R05N4
     172        BTaggingWP50_R05N5
     173        BTaggingWP70_R05N5
     174        BTaggingWP90_R05N5
     175        BTaggingWP50_R05N6
     176        BTaggingWP70_R05N6
     177        BTaggingWP90_R05N6
     178        BTaggingWP50_R07N2
     179        BTaggingWP70_R07N2
     180        BTaggingWP90_R07N2
     181        BTaggingWP50_R07N3
     182        BTaggingWP70_R07N3
     183        BTaggingWP90_R07N3
     184        BTaggingWP50_R07N4
     185        BTaggingWP70_R07N4
     186        BTaggingWP90_R07N4
     187        BTaggingWP50_R07N5
     188        BTaggingWP70_R07N5
     189        BTaggingWP90_R07N5
     190        BTaggingWP50_R07N6
     191        BTaggingWP70_R07N6
     192        BTaggingWP90_R07N6
     193        BTaggingWP50_R10N2
     194        BTaggingWP70_R10N2
     195        BTaggingWP90_R10N2
     196        BTaggingWP50_R10N3
     197        BTaggingWP70_R10N3
     198        BTaggingWP90_R10N3
     199        BTaggingWP50_R10N4
     200        BTaggingWP70_R10N4
     201        BTaggingWP90_R10N4
     202        BTaggingWP50_R10N5
     203        BTaggingWP70_R10N5
     204        BTaggingWP90_R10N5
     205        BTaggingWP50_R10N6
     206        BTaggingWP70_R10N6
     207        BTaggingWP90_R10N6
     208        BTaggingWP50_R12N2
     209        BTaggingWP70_R12N2
     210        BTaggingWP90_R12N2
     211        BTaggingWP50_R12N3
     212        BTaggingWP70_R12N3
     213        BTaggingWP90_R12N3
     214        BTaggingWP50_R12N4
     215        BTaggingWP70_R12N4
     216        BTaggingWP90_R12N4
     217        BTaggingWP50_R12N5
     218        BTaggingWP70_R12N5
     219        BTaggingWP90_R12N5
     220        BTaggingWP50_R12N6
     221        BTaggingWP70_R12N6
     222        BTaggingWP90_R12N6
     223        BTaggingWP50_R15N2
     224        BTaggingWP70_R15N2
     225        BTaggingWP90_R15N2
     226        BTaggingWP50_R15N3
     227        BTaggingWP70_R15N3
     228        BTaggingWP90_R15N3
     229        BTaggingWP50_R15N4
     230        BTaggingWP70_R15N4
     231        BTaggingWP90_R15N4
     232        BTaggingWP50_R15N5
     233        BTaggingWP70_R15N5
     234        BTaggingWP90_R15N5
     235        BTaggingWP50_R15N6
     236        BTaggingWP70_R15N6
     237        BTaggingWP90_R15N6
    279238    BTaggingWP50_R05_inclusive
    280239    BTaggingWP70_R05_inclusive
     
    293252    BTaggingWP90_R15_inclusive
    294253
    295     BTagging_JER_WP50_R05N2
    296     BTagging_JER_WP70_R05N2
    297     BTagging_JER_WP90_R05N2
    298     BTagging_JER_WP50_R05N3
    299     BTagging_JER_WP70_R05N3
    300     BTagging_JER_WP90_R05N3
    301     BTagging_JER_WP50_R05N4
    302     BTagging_JER_WP70_R05N4
    303     BTagging_JER_WP90_R05N4
    304     BTagging_JER_WP50_R05N5
    305     BTagging_JER_WP70_R05N5
    306     BTagging_JER_WP90_R05N5
    307     BTagging_JER_WP50_R05N6
    308     BTagging_JER_WP70_R05N6
    309     BTagging_JER_WP90_R05N6
    310     BTagging_JER_WP50_R07N2
    311     BTagging_JER_WP70_R07N2
    312     BTagging_JER_WP90_R07N2
    313     BTagging_JER_WP50_R07N3
    314     BTagging_JER_WP70_R07N3
    315     BTagging_JER_WP90_R07N3
    316     BTagging_JER_WP50_R07N4
    317     BTagging_JER_WP70_R07N4
    318     BTagging_JER_WP90_R07N4
    319     BTagging_JER_WP50_R07N5
    320     BTagging_JER_WP70_R07N5
    321     BTagging_JER_WP90_R07N5
    322     BTagging_JER_WP50_R07N6
    323     BTagging_JER_WP70_R07N6
    324     BTagging_JER_WP90_R07N6
    325     BTagging_JER_WP50_R10N2
    326     BTagging_JER_WP70_R10N2
    327     BTagging_JER_WP90_R10N2
    328     BTagging_JER_WP50_R10N3
    329     BTagging_JER_WP70_R10N3
    330     BTagging_JER_WP90_R10N3
    331     BTagging_JER_WP50_R10N4
    332     BTagging_JER_WP70_R10N4
    333     BTagging_JER_WP90_R10N4
    334     BTagging_JER_WP50_R10N5
    335     BTagging_JER_WP70_R10N5
    336     BTagging_JER_WP90_R10N5
    337     BTagging_JER_WP50_R10N6
    338     BTagging_JER_WP70_R10N6
    339     BTagging_JER_WP90_R10N6
    340     BTagging_JER_WP50_R12N2
    341     BTagging_JER_WP70_R12N2
    342     BTagging_JER_WP90_R12N2
    343     BTagging_JER_WP50_R12N3
    344     BTagging_JER_WP70_R12N3
    345     BTagging_JER_WP90_R12N3
    346     BTagging_JER_WP50_R12N4
    347     BTagging_JER_WP70_R12N4
    348     BTagging_JER_WP90_R12N4
    349     BTagging_JER_WP50_R12N5
    350     BTagging_JER_WP70_R12N5
    351     BTagging_JER_WP90_R12N5
    352     BTagging_JER_WP50_R12N6
    353     BTagging_JER_WP70_R12N6
    354     BTagging_JER_WP90_R12N6
    355     BTagging_JER_WP50_R15N2
    356     BTagging_JER_WP70_R15N2
    357     BTagging_JER_WP90_R15N2
    358     BTagging_JER_WP50_R15N3
    359     BTagging_JER_WP70_R15N3
    360     BTagging_JER_WP90_R15N3
    361     BTagging_JER_WP50_R15N4
    362     BTagging_JER_WP70_R15N4
    363     BTagging_JER_WP90_R15N4
    364     BTagging_JER_WP50_R15N5
    365     BTagging_JER_WP70_R15N5
    366     BTagging_JER_WP90_R15N5
    367     BTagging_JER_WP50_R15N6
    368     BTagging_JER_WP70_R15N6
    369     BTagging_JER_WP90_R15N6
    370     BTagging_JER_WP50_R05_inclusive
    371     BTagging_JER_WP70_R05_inclusive
    372     BTagging_JER_WP90_R05_inclusive
    373     BTagging_JER_WP50_R07_inclusive
    374     BTagging_JER_WP70_R07_inclusive
    375     BTagging_JER_WP90_R07_inclusive
    376     BTagging_JER_WP50_R10_inclusive
    377     BTagging_JER_WP70_R10_inclusive
    378     BTagging_JER_WP90_R10_inclusive
    379     BTagging_JER_WP50_R12_inclusive
    380     BTagging_JER_WP70_R12_inclusive
    381     BTagging_JER_WP90_R12_inclusive
    382     BTagging_JER_WP50_R15_inclusive
    383     BTagging_JER_WP70_R15_inclusive
    384     BTagging_JER_WP90_R15_inclusive
    385      
     254   
    386255    TauTagging_R05N2
    387256    TauTagging_R05N3
     
    409278    TauTagging_R15N5
    410279    TauTagging_R15N6
     280
    411281    TauTagging_R05_inclusive
    412282    TauTagging_R07_inclusive
     
    415285    TauTagging_R15_inclusive
    416286
    417     TauTagging_JER_R05N2
    418     TauTagging_JER_R05N3
    419     TauTagging_JER_R05N4
    420     TauTagging_JER_R05N5
    421     TauTagging_JER_R05N6
    422     TauTagging_JER_R07N2
    423     TauTagging_JER_R07N3
    424     TauTagging_JER_R07N4
    425     TauTagging_JER_R07N5
    426     TauTagging_JER_R07N6
    427     TauTagging_JER_R10N2
    428     TauTagging_JER_R10N3
    429     TauTagging_JER_R10N4
    430     TauTagging_JER_R10N5
    431     TauTagging_JER_R10N6
    432     TauTagging_JER_R12N2
    433     TauTagging_JER_R12N3
    434     TauTagging_JER_R12N4
    435     TauTagging_JER_R12N5
    436     TauTagging_JER_R12N6
    437     TauTagging_JER_R15N2
    438     TauTagging_JER_R15N3
    439     TauTagging_JER_R15N4
    440     TauTagging_JER_R15N5
    441     TauTagging_JER_R15N6
    442     TauTagging_JER_R05_inclusive
    443     TauTagging_JER_R07_inclusive
    444     TauTagging_JER_R10_inclusive
    445     TauTagging_JER_R12_inclusive
    446     TauTagging_JER_R15_inclusive
    447287
    448288
     
    890730}
    891731
    892 
    893732##################
    894733# Photon isolation
     
    901740    set OutputArray photons
    902741
    903     set DeltaRMax 0.1
     742    set DeltaRMax 0.5
    904743
    905744    set PTMin 0.5
    906745
    907     set PTRatioMax 0.2
    908 }
    909 
     746    set PTRatioMax 0.12
     747}
    910748
    911749#####################
     
    1000838    set OutputArray electrons
    1001839
    1002     set DeltaRMax 0.1
     840    set DeltaRMax 0.5
    1003841
    1004842    set PTMin 0.5
    1005843
    1006     set PTRatioMax 0.2
     844    set PTRatioMax 0.12
    1007845}
    1008846
     
    1038876    set OutputArray muons
    1039877
    1040     set DeltaRMax 0.1
     878    set DeltaRMax 0.5
    1041879
    1042880    set PTMin 0.5
    1043881
    1044     set PTRatioMax 0.2
     882    set PTRatioMax 0.25
    1045883}
    1046884
     
    11651003
    11661004source  CLIC/CLICdet_JetFlavorAssociation.tcl
    1167 source  CLIC/CLICdet_JetFlavorAssociation_JER.tcl
    11681005
    11691006###########
     
    11731010
    11741011source  CLIC/CLICdet_BTagging.tcl
    1175 source  CLIC/CLICdet_BTagging_JER.tcl
    11761012
    11771013
     
    11821018
    11831019source CLIC/CLICdet_TauTagging.tcl
    1184 source CLIC/CLICdet_TauTagging_JER.tcl
    11851020
    11861021
  • classes/ClassesLinkDef.h

    r83ee320 r2d7ff18  
    6060#pragma link C++ class Track+;
    6161#pragma link C++ class Tower+;
    62 #pragma link C++ class ParticleFlowCandidate+;
    6362#pragma link C++ class HectorHit+;
    6463
  • classes/DelphesClasses.cc

    r83ee320 r2d7ff18  
    3939CompBase *Track::fgCompare = CompPT<Track>::Instance();
    4040CompBase *Tower::fgCompare = CompE<Tower>::Instance();
    41 CompBase *ParticleFlowCandidate::fgCompare = CompE<ParticleFlowCandidate>::Instance();
    4241CompBase *HectorHit::fgCompare = CompE<HectorHit>::Instance();
    4342CompBase *Vertex::fgCompare = CompSumPT2<Vertex>::Instance();
     
    113112  TLorentzVector vec;
    114113  vec.SetPtEtaPhiM(ET, Eta, Phi, 0.0);
    115   return vec;
    116 }
    117 
    118 //------------------------------------------------------------------------------
    119 
    120 TLorentzVector ParticleFlowCandidate::P4() const
    121 {
    122   TLorentzVector vec;
    123   vec.SetPtEtaPhiM(PT, Eta, Phi, 0.0);
    124114  return vec;
    125115}
     
    131121  Charge(0), Mass(0.0),
    132122  IsPU(0), IsRecoPU(0), IsConstituent(0), IsFromConversion(0),
     123  ClusterIndex(-1), ClusterNDF(0), ClusterSigma(0), SumPT2(0), BTVSumPT2(0), GenDeltaZ(0), GenSumPT2(0),
    133124  Flavor(0), FlavorAlgo(0), FlavorPhys(0),
    134125  BTag(0), BTagAlgo(0), BTagPhys(0),
     
    137128  Momentum(0.0, 0.0, 0.0, 0.0),
    138129  Position(0.0, 0.0, 0.0, 0.0),
     130  PositionError(0.0, 0.0, 0.0, 0.0),
    139131  InitialPosition(0.0, 0.0, 0.0, 0.0),
    140   PositionError(0.0, 0.0, 0.0, 0.0),
    141132  Area(0.0, 0.0, 0.0, 0.0),
    142133  L(0),
     
    147138  CtgTheta(0), ErrorCtgTheta(0),
    148139  Phi(0), ErrorPhi(0),
    149   Xd(0), Yd(0), Zd(0), Td(0),
    150   VertexingWeight(0),
     140  Xd(0), Yd(0), Zd(0),
    151141  TrackResolution(0),
    152142  NCharged(0),
    153143  NNeutrals(0),
    154   NeutralEnergyFraction(0),  // charged energy fraction
    155   ChargedEnergyFraction(0),  // neutral energy fraction
    156144  Beta(0),
    157145  BetaStar(0),
     
    165153  SumPtChargedPU(-999),
    166154  SumPt(-999),
    167   ClusterIndex(-1), ClusterNDF(0), ClusterSigma(0), SumPT2(0), BTVSumPT2(0), GenDeltaZ(0), GenSumPT2(0),
    168155  NSubJetsTrimmed(0),
    169156  NSubJetsPruned(0),
     
    319306  object.Phi = Phi;
    320307  object.ErrorPhi = ErrorPhi;
    321   object.Td = Td;
    322308  object.Xd = Xd;
    323309  object.Yd = Yd;
    324310  object.Zd = Zd;
    325   object.VertexingWeight = Zd;
    326311  object.TrackResolution = TrackResolution;
    327312  object.NCharged = NCharged;
    328313  object.NNeutrals = NNeutrals;
    329   object.NeutralEnergyFraction = NeutralEnergyFraction;
    330   object.ChargedEnergyFraction = ChargedEnergyFraction;
    331314  object.Beta = Beta;
    332315  object.BetaStar = BetaStar;
     
    450433  Phi = 0.0;
    451434  ErrorPhi = 0.0;
    452   Td = 0.0;
    453435  Xd = 0.0;
    454436  Yd = 0.0;
    455437  Zd = 0.0;
    456   VertexingWeight = 0.0;
    457438  TrackResolution = 0.0;
    458439  NCharged = 0;
  • classes/DelphesClasses.h

    r83ee320 r2d7ff18  
    387387  Int_t NCharged; // number of charged constituents
    388388  Int_t NNeutrals; // number of neutral constituents
    389 
    390   Float_t NeutralEnergyFraction;  // charged energy fraction
    391   Float_t ChargedEnergyFraction;  // neutral energy fraction
    392 
    393389  Float_t Beta; // (sum pt of charged pile-up constituents)/(sum pt of charged constituents)
    394390  Float_t BetaStar; // (sum pt of charged constituents coming from hard interaction)/(sum pt of charged constituents)
     
    456452  Float_t ZOuter; // track position (z component) at the tracker edge
    457453
    458   Float_t Td; // T coordinate of point of closest approach to vertex
    459454  Float_t Xd; // X coordinate of point of closest approach to vertex
    460455  Float_t Yd; // Y coordinate of point of closest approach to vertex
    461456  Float_t Zd; // Z coordinate of point of closest approach to vertex
    462 
    463   Float_t TOFreco; // reconstructed time of flight
    464   Float_t TOFgen; // gen time of flight
    465457
    466458  Float_t L; // track path length
     
    486478  TLorentzVector P4() const;
    487479
    488   ClassDef(Track, 4)
     480  ClassDef(Track, 3)
    489481};
    490482
     
    516508
    517509  ClassDef(Tower, 2)
    518 };
    519 
    520 //---------------------------------------------------------------------------
    521 
    522 class ParticleFlowCandidate: public SortableObject
    523 {
    524 
    525 public:
    526   Int_t PID; // HEP ID number
    527 
    528   Int_t Charge; // track charge
    529 
    530   Float_t E; // reconstructed energy [GeV]
    531   Float_t P; // track momentum
    532   Float_t PT; // track transverse momentum
    533   Float_t Eta; // track pseudorapidity
    534   Float_t Phi; // track azimuthal angle
    535   Float_t CtgTheta; // track cotangent of theta
    536 
    537   Float_t EtaOuter; // track pseudorapidity at the tracker edge
    538   Float_t PhiOuter; // track azimuthal angle at the tracker edge
    539 
    540   Float_t T; // track vertex position (t component)
    541   Float_t X; // track vertex position (x component)
    542   Float_t Y; // track vertex position (y component)
    543   Float_t Z; // track vertex position (z component)
    544 
    545   Float_t TOuter; // track position (t component) at the tracker edge
    546   Float_t XOuter; // track position (x component) at the tracker edge
    547   Float_t YOuter; // track position (y component) at the tracker edge
    548   Float_t ZOuter; // track position (z component) at the tracker edge
    549 
    550   Float_t Td; // X coordinate of point of closest approach to vertex
    551   Float_t Xd; // X coordinate of point of closest approach to vertex
    552   Float_t Yd; // Y coordinate of point of closest approach to vertex
    553   Float_t Zd; // Z coordinate of point of closest approach to vertex
    554 
    555   Float_t L; // track path length
    556   Float_t D0; // track transverse impact parameter
    557   Float_t DZ; // track longitudinal impact parameter
    558 
    559   Float_t ErrorP; // track momentum error
    560   Float_t ErrorPT; // track transverse momentum error
    561   Float_t ErrorPhi; // track azimuthal angle error
    562   Float_t ErrorCtgTheta; // track cotangent of theta error
    563 
    564   Float_t ErrorT; // time measurement error
    565   Float_t ErrorD0; // track transverse impact parameter error
    566   Float_t ErrorDZ; // track longitudinal impact parameter error
    567 
    568   Int_t VertexIndex; // reference to vertex
    569 
    570   static CompBase *fgCompare; //!
    571   const CompBase *GetCompare() const { return fgCompare; }
    572 
    573   TLorentzVector P4() const;
    574 
    575   Int_t NTimeHits; // number of hits contributing to time measurement
    576 
    577   Float_t Eem; // calorimeter tower electromagnetic energy
    578   Float_t Ehad; // calorimeter tower hadronic energy
    579 
    580   Float_t Edges[4]; // calorimeter tower edges
    581 
    582   TRefArray Particles; // references to generated particles
    583 
    584   ClassDef(ParticleFlowCandidate, 1)
    585 
    586510};
    587511
     
    669593  Float_t ErrorPhi;
    670594
    671   Float_t Td;
    672595  Float_t Xd;
    673596  Float_t Yd;
    674597  Float_t Zd;
    675598
    676   // Vertexing variables
    677   Float_t VertexingWeight;
    678 
    679599  // tracking resolution
     600
    680601  Float_t TrackResolution;
    681602
     
    689610  Float_t PTD;
    690611  Float_t FracPt[5];
    691   Float_t NeutralEnergyFraction;  // charged energy fraction
    692   Float_t ChargedEnergyFraction;  // neutral energy fraction
    693 
    694612
    695613  // Timing information
  • external/Hector/H_Beam.h

    r83ee320 r2d7ff18  
    107107        //@{
    108108                inline const float getEmittanceX() const {
    109                     if(x_disp * tx_disp == 0) cout<<"Warning : Degenerate Beam : x-emittance = 0"<<endl;       
     109                    if(!x_disp*tx_disp) cout<<"Warning : Degenerate Beam : x-emittance = 0"<<endl;     
    110110                        return x_disp * tan(tx_disp/URAD)/URAD;
    111111                }
    112112        inline const float getEmittanceY() const {
    113                     if(y_disp * ty_disp == 0) cout<<"Warning : Degenerate Beam : y-emittance = 0"<<endl;
     113                        if(!y_disp*ty_disp) cout<<"Warning : Degenerate Beam : y-emittance = 0"<<endl;
    114114                        return y_disp * tan(ty_disp/URAD)/URAD;
    115115                }
  • external/fastjet/plugins/SISCone/split_merge.h

    r83ee320 r2d7ff18  
    446446  // jet information
    447447  /// list of jet candidates
    448 #if __cplusplus < 201103L
     448#ifdef SISCONE_USES_UNIQUE_PTR_AS_AUTO_PTR
     449  std::unique_ptr<std::multiset<Cjet,Csplit_merge_ptcomparison> > candidates;
     450#else
    449451  std::auto_ptr<std::multiset<Cjet,Csplit_merge_ptcomparison> > candidates;
    450 #else
    451   std::unique_ptr<std::multiset<Cjet,Csplit_merge_ptcomparison> > candidates;
    452452#endif
    453453 
  • external/tcl/tcl.h

    r83ee320 r2d7ff18  
    488488EXTERN int              Tcl_IsShared _ANSI_ARGS_((Tcl_Obj *objPtr));
    489489
     490#ifdef TCL_MEM_DEBUG
     491#   define Tcl_IncrRefCount(objPtr) \
     492        Tcl_DbIncrRefCount(objPtr, __FILE__, __LINE__)
     493#   define Tcl_DecrRefCount(objPtr) \
     494        Tcl_DbDecrRefCount(objPtr, __FILE__, __LINE__)
     495#   define Tcl_IsShared(objPtr) \
     496        Tcl_DbIsShared(objPtr, __FILE__, __LINE__)
     497#else
    490498#   define Tcl_IncrRefCount(objPtr) \
    491499        ++(objPtr)->refCount
     
    494502#   define Tcl_IsShared(objPtr) \
    495503        ((objPtr)->refCount > 1)
     504#endif
    496505
    497506/*
    498507 * Macros and definitions that help to debug the use of Tcl objects.
     508 * When TCL_MEM_DEBUG is defined, the Tcl_New* declarations are
     509 * overridden to call debugging versions of the object creation procedures.
    499510 */
    500511
     
    508519EXTERN Tcl_Obj *        Tcl_NewStringObj _ANSI_ARGS_((char *bytes,
    509520                            int length));
     521
     522#ifdef TCL_MEM_DEBUG
     523#  define Tcl_NewBooleanObj(val) \
     524     Tcl_DbNewBooleanObj(val, __FILE__, __LINE__)
     525#  define Tcl_NewDoubleObj(val) \
     526     Tcl_DbNewDoubleObj(val, __FILE__, __LINE__)
     527#  define Tcl_NewIntObj(val) \
     528     Tcl_DbNewLongObj(val, __FILE__, __LINE__)
     529#  define Tcl_NewListObj(objc, objv) \
     530     Tcl_DbNewListObj(objc, objv, __FILE__, __LINE__)
     531#  define Tcl_NewLongObj(val) \
     532     Tcl_DbNewLongObj(val, __FILE__, __LINE__)
     533#  define Tcl_NewObj() \
     534     Tcl_DbNewObj(__FILE__, __LINE__)
     535#  define Tcl_NewStringObj(bytes, len) \
     536     Tcl_DbNewStringObj(bytes, len, __FILE__, __LINE__)
     537#endif /* TCL_MEM_DEBUG */
    510538
    511539/*
     
    698726                            unsigned int size));
    699727
     728#ifdef TCL_MEM_DEBUG
     729
     730#  define Tcl_Alloc(x) Tcl_DbCkalloc(x, __FILE__, __LINE__)
     731#  define Tcl_Free(x)  Tcl_DbCkfree(x, __FILE__, __LINE__)
     732#  define Tcl_Realloc(x,y) Tcl_DbCkrealloc((x), (y),__FILE__, __LINE__)
     733#  define ckalloc(x) Tcl_DbCkalloc(x, __FILE__, __LINE__)
     734#  define ckfree(x)  Tcl_DbCkfree(x, __FILE__, __LINE__)
     735#  define ckrealloc(x,y) Tcl_DbCkrealloc((x), (y),__FILE__, __LINE__)
     736
     737EXTERN int              Tcl_DumpActiveMemory _ANSI_ARGS_((char *fileName));
     738EXTERN void             Tcl_ValidateAllMemory _ANSI_ARGS_((char *file,
     739                            int line));
     740
     741#else
     742
    700743/*
    701744 * If USE_TCLALLOC is true, then we need to call Tcl_Alloc instead of
     
    717760#  define Tcl_DumpActiveMemory(x)
    718761#  define Tcl_ValidateAllMemory(x,y)
     762
     763#endif /* TCL_MEM_DEBUG */
    719764
    720765/*
  • external/tcl/tclBasic.c

    r83ee320 r2d7ff18  
    32873287            TclInitByteCodeObj(objPtr, &compEnv);
    32883288            codePtr = (ByteCode *) objPtr->internalRep.otherValuePtr;
     3289            if (tclTraceCompile == 2) {
     3290                TclPrintByteCodeObj(interp, objPtr);
     3291            }
    32893292            TclFreeCompileEnv(&compEnv);
    32903293        } else {
  • external/tcl/tclCkalloc.c

    r83ee320 r2d7ff18  
    2222#define TRUE    1
    2323
    24 /*
    25  *----------------------------------------------------------------------
    26  *
    27  * Tcl_Alloc --
    28  *      Interface to TclpAlloc.
    29  *      It does check that memory was actually allocated.
    30  *
    31  *----------------------------------------------------------------------
    32  */
    33 
    34 char *
    35 Tcl_Alloc (size)
    36     unsigned int size;
    37 {
    38         char *result;
    39 
    40         result = TclpAlloc(size);
    41         if (result == NULL)
    42                 panic("unable to alloc %d bytes", size);
    43         return result;
    44 }
    45 
     24#ifdef TCL_MEM_DEBUG
     25
     26/*
     27 * One of the following structures is allocated each time the
     28 * "memory tag" command is invoked, to hold the current tag.
     29 */
     30
     31typedef struct MemTag {
     32    int refCount;               /* Number of mem_headers referencing
     33                                 * this tag. */
     34    char string[4];             /* Actual size of string will be as
     35                                 * large as needed for actual tag.  This
     36                                 * must be the last field in the structure. */
     37} MemTag;
     38
     39#define TAG_SIZE(bytesInString) ((unsigned) sizeof(MemTag) + bytesInString - 3)
     40
     41static MemTag *curTagPtr = NULL;/* Tag to use in all future mem_headers
     42                                 * (set by "memory tag" command). */
     43
     44/*
     45 * One of the following structures is allocated just before each
     46 * dynamically allocated chunk of memory, both to record information
     47 * about the chunk and to help detect chunk under-runs.
     48 */
     49
     50#define LOW_GUARD_SIZE (8 + (32 - (sizeof(long) + sizeof(int)))%8)
     51struct mem_header {
     52    struct mem_header *flink;
     53    struct mem_header *blink;
     54    MemTag *tagPtr;             /* Tag from "memory tag" command;  may be
     55                                 * NULL. */
     56    char *file;
     57    long length;
     58    int line;
     59    unsigned char low_guard[LOW_GUARD_SIZE];
     60                                /* Aligns body on 8-byte boundary, plus
     61                                 * provides at least 8 additional guard bytes
     62                                 * to detect underruns. */
     63    char body[1];               /* First byte of client's space.  Actual
     64                                 * size of this field will be larger than
     65                                 * one. */
     66};
     67
     68static struct mem_header *allocHead = NULL;  /* List of allocated structures */
     69
     70#define GUARD_VALUE  0141
     71
     72/*
     73 * The following macro determines the amount of guard space *above* each
     74 * chunk of memory.
     75 */
     76
     77#define HIGH_GUARD_SIZE 8
     78
     79/*
     80 * The following macro computes the offset of the "body" field within
     81 * mem_header.  It is used to get back to the header pointer from the
     82 * body pointer that's used by clients.
     83 */
     84
     85#define BODY_OFFSET \
     86        ((unsigned long) (&((struct mem_header *) 0)->body))
     87
     88static int total_mallocs = 0;
     89static int total_frees = 0;
     90static int current_bytes_malloced = 0;
     91static int maximum_bytes_malloced = 0;
     92static int current_malloc_packets = 0;
     93static int maximum_malloc_packets = 0;
     94static int break_on_malloc = 0;
     95static int trace_on_at_malloc = 0;
     96static int  alloc_tracing = FALSE;
     97static int  init_malloced_bodies = TRUE;
     98#ifdef MEM_VALIDATE
     99    static int  validate_memory = TRUE;
     100#else
     101    static int  validate_memory = FALSE;
     102#endif
     103
     104/*
     105 * Prototypes for procedures defined in this file:
     106 */
     107
     108static int              MemoryCmd _ANSI_ARGS_((ClientData clientData,
     109                            Tcl_Interp *interp, int argc, char **argv));
     110static void             ValidateMemory _ANSI_ARGS_((
     111                            struct mem_header *memHeaderP, char *file,
     112                            int line, int nukeGuards));
     113
     114
     115/*
     116 *----------------------------------------------------------------------
     117 *
     118 * TclDumpMemoryInfo --
     119 *     Display the global memory management statistics.
     120 *
     121 *----------------------------------------------------------------------
     122 */
     123void
     124TclDumpMemoryInfo(outFile)
     125    FILE *outFile;
     126{
     127        fprintf(outFile,"total mallocs             %10d\n",
     128                total_mallocs);
     129        fprintf(outFile,"total frees               %10d\n",
     130                total_frees);
     131        fprintf(outFile,"current packets allocated %10d\n",
     132                current_malloc_packets);
     133        fprintf(outFile,"current bytes allocated   %10d\n",
     134                current_bytes_malloced);
     135        fprintf(outFile,"maximum packets allocated %10d\n",
     136                maximum_malloc_packets);
     137        fprintf(outFile,"maximum bytes allocated   %10d\n",
     138                maximum_bytes_malloced);
     139}
     140
     141
     142/*
     143 *----------------------------------------------------------------------
     144 *
     145 * ValidateMemory --
     146 *     Procedure to validate allocted memory guard zones.
     147 *
     148 *----------------------------------------------------------------------
     149 */
     150static void
     151ValidateMemory(memHeaderP, file, line, nukeGuards)
     152    struct mem_header *memHeaderP;
     153    char              *file;
     154    int                line;
     155    int                nukeGuards;
     156{
     157    unsigned char *hiPtr;
     158    int   idx;
     159    int   guard_failed = FALSE;
     160    int byte;
     161   
     162    for (idx = 0; idx < LOW_GUARD_SIZE; idx++) {
     163        byte = *(memHeaderP->low_guard + idx);
     164        if (byte != GUARD_VALUE) {
     165            guard_failed = TRUE;
     166            fflush(stdout);
     167            byte &= 0xff;
     168            fprintf(stderr, "low guard byte %d is 0x%x  \t%c\n", idx, byte,
     169                    (isprint(UCHAR(byte)) ? byte : ' '));
     170        }
     171    }
     172    if (guard_failed) {
     173        TclDumpMemoryInfo (stderr);
     174        fprintf(stderr, "low guard failed at %lx, %s %d\n",
     175                 (long unsigned int) memHeaderP->body, file, line);
     176        fflush(stderr);  /* In case name pointer is bad. */
     177        fprintf(stderr, "%ld bytes allocated at (%s %d)\n", memHeaderP->length,
     178                memHeaderP->file, memHeaderP->line);
     179        panic ("Memory validation failure");
     180    }
     181
     182    hiPtr = (unsigned char *)memHeaderP->body + memHeaderP->length;
     183    for (idx = 0; idx < HIGH_GUARD_SIZE; idx++) {
     184        byte = *(hiPtr + idx);
     185        if (byte != GUARD_VALUE) {
     186            guard_failed = TRUE;
     187            fflush (stdout);
     188            byte &= 0xff;
     189            fprintf(stderr, "hi guard byte %d is 0x%x  \t%c\n", idx, byte,
     190                    (isprint(UCHAR(byte)) ? byte : ' '));
     191        }
     192    }
     193
     194    if (guard_failed) {
     195        TclDumpMemoryInfo (stderr);
     196        fprintf(stderr, "high guard failed at %lx, %s %d\n",
     197                 (long unsigned int) memHeaderP->body, file, line);
     198        fflush(stderr);  /* In case name pointer is bad. */
     199        fprintf(stderr, "%ld bytes allocated at (%s %d)\n",
     200                memHeaderP->length, memHeaderP->file,
     201                memHeaderP->line);
     202        panic("Memory validation failure");
     203    }
     204
     205    if (nukeGuards) {
     206        memset ((char *) memHeaderP->low_guard, 0, LOW_GUARD_SIZE);
     207        memset ((char *) hiPtr, 0, HIGH_GUARD_SIZE);
     208    }
     209
     210}
     211
     212
     213/*
     214 *----------------------------------------------------------------------
     215 *
     216 * Tcl_ValidateAllMemory --
     217 *     Validates guard regions for all allocated memory.
     218 *
     219 *----------------------------------------------------------------------
     220 */
     221void
     222Tcl_ValidateAllMemory (file, line)
     223    char  *file;
     224    int    line;
     225{
     226    struct mem_header *memScanP;
     227
     228    for (memScanP = allocHead; memScanP != NULL; memScanP = memScanP->flink)
     229        ValidateMemory(memScanP, file, line, FALSE);
     230
     231}
     232
     233
     234/*
     235 *----------------------------------------------------------------------
     236 *
     237 * Tcl_DumpActiveMemory --
     238 *     Displays all allocated memory to stderr.
     239 *
     240 * Results:
     241 *     Return TCL_ERROR if an error accessing the file occures, `errno'
     242 *     will have the file error number left in it.
     243 *----------------------------------------------------------------------
     244 */
     245int
     246Tcl_DumpActiveMemory (fileName)
     247    char *fileName;
     248{
     249    FILE              *fileP;
     250    struct mem_header *memScanP;
     251    char              *address;
     252
     253    fileP = fopen(fileName, "w");
     254    if (fileP == NULL)
     255        return TCL_ERROR;
     256
     257    for (memScanP = allocHead; memScanP != NULL; memScanP = memScanP->flink) {
     258        address = &memScanP->body [0];
     259        fprintf(fileP, "%8lx - %8lx  %7ld @ %s %d %s",
     260                (long unsigned int) address,
     261                 (long unsigned int) address + memScanP->length - 1,
     262                 memScanP->length, memScanP->file, memScanP->line,
     263                 (memScanP->tagPtr == NULL) ? "" : memScanP->tagPtr->string);
     264        (void) fputc('\n', fileP);
     265    }
     266    fclose (fileP);
     267    return TCL_OK;
     268}
     269
     270
     271/*
     272 *----------------------------------------------------------------------
     273 *
     274 * Tcl_DbCkalloc - debugging ckalloc
     275 *
     276 *        Allocate the requested amount of space plus some extra for
     277 *        guard bands at both ends of the request, plus a size, panicing
     278 *        if there isn't enough space, then write in the guard bands
     279 *        and return the address of the space in the middle that the
     280 *        user asked for.
     281 *
     282 *        The second and third arguments are file and line, these contain
     283 *        the filename and line number corresponding to the caller.
     284 *        These are sent by the ckalloc macro; it uses the preprocessor
     285 *        autodefines __FILE__ and __LINE__.
     286 *
     287 *----------------------------------------------------------------------
     288 */
    46289char *
    47290Tcl_DbCkalloc(size, file, line)
     
    50293    int          line;
    51294{
    52     char *result;
    53 
    54     result = (char *) TclpAlloc(size);
    55 
     295    struct mem_header *result;
     296
     297    if (validate_memory)
     298        Tcl_ValidateAllMemory (file, line);
     299
     300    result = (struct mem_header *) TclpAlloc((unsigned)size +
     301                              sizeof(struct mem_header) + HIGH_GUARD_SIZE);
    56302    if (result == NULL) {
    57303        fflush(stdout);
     304        TclDumpMemoryInfo(stderr);
    58305        panic("unable to alloc %d bytes, %s line %d", size, file,
    59306              line);
    60307    }
    61     return result;
    62 }
    63 
    64 
    65 
    66 /*
    67  *----------------------------------------------------------------------
    68  *
    69  * Tcl_Realloc --
    70  *      Interface to TclpRealloc.
    71  *      It does check that memory was actually allocated.
    72  *
    73  *----------------------------------------------------------------------
    74  */
    75 
    76 char *
    77 Tcl_Realloc(ptr, size)
    78     char *ptr;
    79     unsigned int size;
    80 {
    81     char *result;
    82 
    83     result = TclpRealloc(ptr, size);
    84     if (result == NULL)
    85         panic("unable to realloc %d bytes", size);
    86     return result;
    87 }
    88 
     308
     309    /*
     310     * Fill in guard zones and size.  Also initialize the contents of
     311     * the block with bogus bytes to detect uses of initialized data.
     312     * Link into allocated list.
     313     */
     314    if (init_malloced_bodies) {
     315        memset ((VOID *) result, GUARD_VALUE,
     316                size + sizeof(struct mem_header) + HIGH_GUARD_SIZE);
     317    } else {
     318        memset ((char *) result->low_guard, GUARD_VALUE, LOW_GUARD_SIZE);
     319        memset (result->body + size, GUARD_VALUE, HIGH_GUARD_SIZE);
     320    }
     321    result->length = size;
     322    result->tagPtr = curTagPtr;
     323    if (curTagPtr != NULL) {
     324        curTagPtr->refCount++;
     325    }
     326    result->file = file;
     327    result->line = line;
     328    result->flink = allocHead;
     329    result->blink = NULL;
     330    if (allocHead != NULL)
     331        allocHead->blink = result;
     332    allocHead = result;
     333
     334    total_mallocs++;
     335    if (trace_on_at_malloc && (total_mallocs >= trace_on_at_malloc)) {
     336        (void) fflush(stdout);
     337        fprintf(stderr, "reached malloc trace enable point (%d)\n",
     338                total_mallocs);
     339        fflush(stderr);
     340        alloc_tracing = TRUE;
     341        trace_on_at_malloc = 0;
     342    }
     343
     344    if (alloc_tracing)
     345        fprintf(stderr,"ckalloc %lx %d %s %d\n",
     346                (long unsigned int) result->body, size, file, line);
     347
     348    if (break_on_malloc && (total_mallocs >= break_on_malloc)) {
     349        break_on_malloc = 0;
     350        (void) fflush(stdout);
     351        fprintf(stderr,"reached malloc break limit (%d)\n",
     352                total_mallocs);
     353        fprintf(stderr, "program will now enter C debugger\n");
     354        (void) fflush(stderr);
     355        abort();
     356    }
     357
     358    current_malloc_packets++;
     359    if (current_malloc_packets > maximum_malloc_packets)
     360        maximum_malloc_packets = current_malloc_packets;
     361    current_bytes_malloced += size;
     362    if (current_bytes_malloced > maximum_bytes_malloced)
     363        maximum_bytes_malloced = current_bytes_malloced;
     364
     365    return result->body;
     366}
     367
     368
     369/*
     370 *----------------------------------------------------------------------
     371 *
     372 * Tcl_DbCkfree - debugging ckfree
     373 *
     374 *        Verify that the low and high guards are intact, and if so
     375 *        then free the buffer else panic.
     376 *
     377 *        The guards are erased after being checked to catch duplicate
     378 *        frees.
     379 *
     380 *        The second and third arguments are file and line, these contain
     381 *        the filename and line number corresponding to the caller.
     382 *        These are sent by the ckfree macro; it uses the preprocessor
     383 *        autodefines __FILE__ and __LINE__.
     384 *
     385 *----------------------------------------------------------------------
     386 */
     387
     388int
     389Tcl_DbCkfree(ptr, file, line)
     390    char *  ptr;
     391    char     *file;
     392    int       line;
     393{
     394    /*
     395     * The following cast is *very* tricky.  Must convert the pointer
     396     * to an integer before doing arithmetic on it, because otherwise
     397     * the arithmetic will be done differently (and incorrectly) on
     398     * word-addressed machines such as Crays (will subtract only bytes,
     399     * even though BODY_OFFSET is in words on these machines).
     400     */
     401
     402    struct mem_header *memp = (struct mem_header *)
     403            (((unsigned long) ptr) - BODY_OFFSET);
     404
     405    if (alloc_tracing)
     406        fprintf(stderr, "ckfree %lx %ld %s %d\n",
     407                (long unsigned int) memp->body, memp->length, file, line);
     408
     409    if (validate_memory)
     410        Tcl_ValidateAllMemory(file, line);
     411
     412    ValidateMemory(memp, file, line, TRUE);
     413    if (init_malloced_bodies) {
     414        memset((VOID *) ptr, GUARD_VALUE, (size_t) memp->length);
     415    }
     416
     417    total_frees++;
     418    current_malloc_packets--;
     419    current_bytes_malloced -= memp->length;
     420
     421    if (memp->tagPtr != NULL) {
     422        memp->tagPtr->refCount--;
     423        if ((memp->tagPtr->refCount == 0) && (curTagPtr != memp->tagPtr)) {
     424            TclpFree((char *) memp->tagPtr);
     425        }
     426    }
     427
     428    /*
     429     * Delink from allocated list
     430     */
     431    if (memp->flink != NULL)
     432        memp->flink->blink = memp->blink;
     433    if (memp->blink != NULL)
     434        memp->blink->flink = memp->flink;
     435    if (allocHead == memp)
     436        allocHead = memp->flink;
     437    TclpFree((char *) memp);
     438    return 0;
     439}
     440
     441
     442/*
     443 *--------------------------------------------------------------------
     444 *
     445 * Tcl_DbCkrealloc - debugging ckrealloc
     446 *
     447 *      Reallocate a chunk of memory by allocating a new one of the
     448 *      right size, copying the old data to the new location, and then
     449 *      freeing the old memory space, using all the memory checking
     450 *      features of this package.
     451 *
     452 *--------------------------------------------------------------------
     453 */
    89454char *
    90455Tcl_DbCkrealloc(ptr, size, file, line)
     
    94459    int line;
    95460{
     461    char *new;
     462    unsigned int copySize;
     463
     464    /*
     465     * See comment from Tcl_DbCkfree before you change the following
     466     * line.
     467     */
     468
     469    struct mem_header *memp = (struct mem_header *)
     470            (((unsigned long) ptr) - BODY_OFFSET);
     471
     472    copySize = size;
     473    if (copySize > (unsigned int) memp->length) {
     474        copySize = memp->length;
     475    }
     476    new = Tcl_DbCkalloc(size, file, line);
     477    memcpy((VOID *) new, (VOID *) ptr, (size_t) copySize);
     478    Tcl_DbCkfree(ptr, file, line);
     479    return(new);
     480}
     481
     482
     483
     484/*
     485 *----------------------------------------------------------------------
     486 *
     487 * Tcl_Alloc, et al. --
     488 *
     489 *      These functions are defined in terms of the debugging versions
     490 *      when TCL_MEM_DEBUG is set.
     491 *
     492 * Results:
     493 *      Same as the debug versions.
     494 *
     495 * Side effects:
     496 *      Same as the debug versions.
     497 *
     498 *----------------------------------------------------------------------
     499 */
     500
     501#undef Tcl_Alloc
     502#undef Tcl_Free
     503#undef Tcl_Realloc
     504
     505char *
     506Tcl_Alloc(size)
     507    unsigned int size;
     508{
     509    return Tcl_DbCkalloc(size, "unknown", 0);
     510}
     511
     512void
     513Tcl_Free(ptr)
     514    char *ptr;
     515{
     516    Tcl_DbCkfree(ptr, "unknown", 0);
     517}
     518
     519char *
     520Tcl_Realloc(ptr, size)
     521    char *ptr;
     522    unsigned int size;
     523{
     524    return Tcl_DbCkrealloc(ptr, size, "unknown", 0);
     525}
     526
     527
     528/*
     529 *----------------------------------------------------------------------
     530 *
     531 * MemoryCmd --
     532 *     Implements the TCL memory command:
     533 *       memory info
     534 *       memory display
     535 *       break_on_malloc count
     536 *       trace_on_at_malloc count
     537 *       trace on|off
     538 *       validate on|off
     539 *
     540 * Results:
     541 *     Standard TCL results.
     542 *
     543 *----------------------------------------------------------------------
     544 */
     545        /* ARGSUSED */
     546static int
     547MemoryCmd (clientData, interp, argc, argv)
     548    ClientData  clientData;
     549    Tcl_Interp *interp;
     550    int         argc;
     551    char      **argv;
     552{
     553    char *fileName;
     554    Tcl_DString buffer;
     555    int result;
     556
     557    if (argc < 2) {
     558        Tcl_AppendResult(interp, "wrong # args: should be \"",
     559                argv[0], " option [args..]\"", (char *) NULL);
     560        return TCL_ERROR;
     561    }
     562
     563    if (strcmp(argv[1],"active") == 0) {
     564        if (argc != 3) {
     565            Tcl_AppendResult(interp, "wrong # args: should be \"",
     566                    argv[0], " active file\"", (char *) NULL);
     567            return TCL_ERROR;
     568        }
     569        fileName = Tcl_TranslateFileName(interp, argv[2], &buffer);
     570        if (fileName == NULL) {
     571            return TCL_ERROR;
     572        }
     573        result = Tcl_DumpActiveMemory (fileName);
     574        Tcl_DStringFree(&buffer);
     575        if (result != TCL_OK) {
     576            Tcl_AppendResult(interp, "error accessing ", argv[2],
     577                    (char *) NULL);
     578            return TCL_ERROR;
     579        }
     580        return TCL_OK;
     581    }
     582    if (strcmp(argv[1],"break_on_malloc") == 0) {
     583        if (argc != 3) {
     584            goto argError;
     585        }
     586        if (Tcl_GetInt(interp, argv[2], &break_on_malloc) != TCL_OK) {
     587            return TCL_ERROR;
     588        }
     589        return TCL_OK;
     590    }
     591    if (strcmp(argv[1],"info") == 0) {
     592        TclDumpMemoryInfo(stdout);
     593        return TCL_OK;
     594    }
     595    if (strcmp(argv[1],"init") == 0) {
     596        if (argc != 3) {
     597            goto bad_suboption;
     598        }
     599        init_malloced_bodies = (strcmp(argv[2],"on") == 0);
     600        return TCL_OK;
     601    }
     602    if (strcmp(argv[1],"tag") == 0) {
     603        if (argc != 3) {
     604            Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
     605                    " tag string\"", (char *) NULL);
     606            return TCL_ERROR;
     607        }
     608        if ((curTagPtr != NULL) && (curTagPtr->refCount == 0)) {
     609            TclpFree((char *) curTagPtr);
     610        }
     611        curTagPtr = (MemTag *) TclpAlloc(TAG_SIZE(strlen(argv[2])));
     612        curTagPtr->refCount = 0;
     613        strcpy(curTagPtr->string, argv[2]);
     614        return TCL_OK;
     615    }
     616    if (strcmp(argv[1],"trace") == 0) {
     617        if (argc != 3) {
     618            goto bad_suboption;
     619        }
     620        alloc_tracing = (strcmp(argv[2],"on") == 0);
     621        return TCL_OK;
     622    }
     623
     624    if (strcmp(argv[1],"trace_on_at_malloc") == 0) {
     625        if (argc != 3) {
     626            goto argError;
     627        }
     628        if (Tcl_GetInt(interp, argv[2], &trace_on_at_malloc) != TCL_OK) {
     629            return TCL_ERROR;
     630        }
     631        return TCL_OK;
     632    }
     633    if (strcmp(argv[1],"validate") == 0) {
     634        if (argc != 3) {
     635            goto bad_suboption;
     636        }
     637        validate_memory = (strcmp(argv[2],"on") == 0);
     638        return TCL_OK;
     639    }
     640
     641    Tcl_AppendResult(interp, "bad option \"", argv[1],
     642            "\": should be active, break_on_malloc, info, init, ",
     643            "tag, trace, trace_on_at_malloc, or validate", (char *) NULL);
     644    return TCL_ERROR;
     645
     646argError:
     647    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
     648            " ", argv[1], " count\"", (char *) NULL);
     649    return TCL_ERROR;
     650
     651bad_suboption:
     652    Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
     653            " ", argv[1], " on|off\"", (char *) NULL);
     654    return TCL_ERROR;
     655}
     656
     657
     658/*
     659 *----------------------------------------------------------------------
     660 *
     661 * Tcl_InitMemory --
     662 *     Initialize the memory command.
     663 *
     664 *----------------------------------------------------------------------
     665 */
     666void
     667Tcl_InitMemory(interp)
     668    Tcl_Interp *interp;
     669{
     670    Tcl_CreateCommand (interp, "memory", MemoryCmd, (ClientData) NULL,
     671            (Tcl_CmdDeleteProc *) NULL);
     672}
     673
     674#else
     675
     676
     677
     678/*
     679 *----------------------------------------------------------------------
     680 *
     681 * Tcl_Alloc --
     682 *     Interface to TclpAlloc when TCL_MEM_DEBUG is disabled.  It does check
     683 *     that memory was actually allocated.
     684 *
     685 *----------------------------------------------------------------------
     686 */
     687
     688char *
     689Tcl_Alloc (size)
     690    unsigned int size;
     691{
     692        char *result;
     693
     694        result = TclpAlloc(size);
     695        if (result == NULL)
     696                panic("unable to alloc %d bytes", size);
     697        return result;
     698}
     699
     700char *
     701Tcl_DbCkalloc(size, file, line)
     702    unsigned int size;
     703    char        *file;
     704    int          line;
     705{
     706    char *result;
     707
     708    result = (char *) TclpAlloc(size);
     709
     710    if (result == NULL) {
     711        fflush(stdout);
     712        panic("unable to alloc %d bytes, %s line %d", size, file,
     713              line);
     714    }
     715    return result;
     716}
     717
     718
     719
     720/*
     721 *----------------------------------------------------------------------
     722 *
     723 * Tcl_Realloc --
     724 *     Interface to TclpRealloc when TCL_MEM_DEBUG is disabled.  It does
     725 *     check that memory was actually allocated.
     726 *
     727 *----------------------------------------------------------------------
     728 */
     729
     730char *
     731Tcl_Realloc(ptr, size)
     732    char *ptr;
     733    unsigned int size;
     734{
     735    char *result;
     736
     737    result = TclpRealloc(ptr, size);
     738    if (result == NULL)
     739        panic("unable to realloc %d bytes", size);
     740    return result;
     741}
     742
     743char *
     744Tcl_DbCkrealloc(ptr, size, file, line)
     745    char *ptr;
     746    unsigned int size;
     747    char *file;
     748    int line;
     749{
    96750    char *result;
    97751
     
    111765 *
    112766 * Tcl_Free --
    113  *      Interface to TclpFree.
     767 *     Interface to TclpFree when TCL_MEM_DEBUG is disabled.  Done here
     768 *     rather in the macro to keep some modules from being compiled with
     769 *     TCL_MEM_DEBUG enabled and some with it disabled.
    114770 *
    115771 *----------------------------------------------------------------------
     
    122778        TclpFree(ptr);
    123779}
     780
     781int
     782Tcl_DbCkfree(ptr, file, line)
     783    char *  ptr;
     784    char     *file;
     785    int       line;
     786{
     787    TclpFree(ptr);
     788    return 0;
     789}
     790
     791
     792/*
     793 *----------------------------------------------------------------------
     794 *
     795 * Tcl_InitMemory --
     796 *     Dummy initialization for memory command, which is only available
     797 *     if TCL_MEM_DEBUG is on.
     798 *
     799 *----------------------------------------------------------------------
     800 */
     801        /* ARGSUSED */
     802void
     803Tcl_InitMemory(interp)
     804    Tcl_Interp *interp;
     805{
     806}
     807
     808#undef Tcl_DumpActiveMemory
     809#undef Tcl_ValidateAllMemory
     810
     811extern int              Tcl_DumpActiveMemory _ANSI_ARGS_((char *fileName));
     812extern void             Tcl_ValidateAllMemory _ANSI_ARGS_((char *file,
     813                            int line));
     814
     815int
     816Tcl_DumpActiveMemory(fileName)
     817    char *fileName;
     818{
     819    return TCL_OK;
     820}
     821
     822void
     823Tcl_ValidateAllMemory(file, line)
     824    char  *file;
     825    int    line;
     826{
     827}
     828
     829#endif
  • external/tcl/tclCompExpr.c

    r83ee320 r2d7ff18  
    3131#define ERANGE 34
    3232#endif
     33
     34/*
     35 * Boolean variable that controls whether expression compilation tracing
     36 * is enabled.
     37 */
     38
     39#ifdef TCL_COMPILE_DEBUG
     40static int traceCompileExpr = 0;
     41#endif /* TCL_COMPILE_DEBUG */
    3342
    3443/*
     
    123132#define NOT             (COLON + 1)
    124133#define BIT_NOT         (NOT + 1)
     134
     135/*
     136 * Mapping from tokens to strings; used for debugging messages. These
     137 * entries must match the order and number of the token definitions above.
     138 */
     139
     140#ifdef TCL_COMPILE_DEBUG
     141static char *tokenStrings[] = {
     142    "LITERAL", "FUNCNAME",
     143    "[", "]", "(", ")", "$", "\"", ",", "END", "UNKNOWN",
     144    "*", "/", "%", "+", "-",
     145    "<<", ">>", "<", ">", "<=", ">=", "==", "!=",
     146    "&", "^", "|", "&&", "||", "?", ":",
     147    "!", "~"
     148};
     149#endif /* TCL_COMPILE_DEBUG */
    125150
    126151/*
     
    173198                            ExprInfo *infoPtr, CompileEnv *envPtr));
    174199
     200/*
     201 * Macro used to debug the execution of the recursive descent parser used
     202 * to compile expressions.
     203 */
     204
     205#ifdef TCL_COMPILE_DEBUG
     206#define HERE(production, level) \
     207    if (traceCompileExpr) { \
     208        fprintf(stderr, "%*s%s: token=%s, next=\"%.20s\"\n", \
     209                (level), " ", (production), tokenStrings[infoPtr->token], \
     210                infoPtr->next); \
     211    }
     212#else
     213#define HERE(production, level)
     214#endif /* TCL_COMPILE_DEBUG */
    175215
    176216
     
    237277                                 * to execute the expression. */
    238278    int result;
     279
     280#ifdef TCL_COMPILE_DEBUG
     281    if (traceCompileExpr) {
     282        fprintf(stderr, "expr: string=\"%.30s\"\n", string);
     283    }
     284#endif /* TCL_COMPILE_DEBUG */
    239285
    240286    /*
     
    363409    int elseCodeOffset, currCodeOffset, jumpDist, result;
    364410   
     411    HERE("condExpr", 1);
    365412    result = CompileLorExpr(interp, infoPtr, flags, envPtr);
    366413    if (result != TCL_OK) {
     
    524571    Tcl_Obj *objPtr;
    525572   
     573    HERE("lorExpr", 2);
    526574    result = CompileLandExpr(interp, infoPtr, flags, envPtr);
    527575    if ((result != TCL_OK) || (infoPtr->token != OR)) {
     
    691739    Tcl_Obj *objPtr;
    692740
     741    HERE("landExpr", 3);
    693742    result = CompileBitOrExpr(interp, infoPtr, flags, envPtr);
    694743    if ((result != TCL_OK) || (infoPtr->token != AND)) {
     
    850899    int result;
    851900
     901    HERE("bitOrExpr", 4);
    852902    result = CompileBitXorExpr(interp, infoPtr, flags, envPtr);
    853903    if (result != TCL_OK) {
     
    920970    int result;
    921971
     972    HERE("bitXorExpr", 5);
    922973    result = CompileBitAndExpr(interp, infoPtr, flags, envPtr);
    923974    if (result != TCL_OK) {
     
    9901041    int result;
    9911042
     1043    HERE("bitAndExpr", 6);
    9921044    result = CompileEqualityExpr(interp, infoPtr, flags, envPtr);
    9931045    if (result != TCL_OK) {
     
    10601112    int op, result;
    10611113
     1114    HERE("equalityExpr", 7);
    10621115    result = CompileRelationalExpr(interp, infoPtr, flags, envPtr);
    10631116    if (result != TCL_OK) {
     
    11371190    int op, result;
    11381191
     1192    HERE("relationalExpr", 8);
    11391193    result = CompileShiftExpr(interp, infoPtr, flags, envPtr);
    11401194    if (result != TCL_OK) {
     
    12231277    int op, result;
    12241278
     1279    HERE("shiftExpr", 9);
    12251280    result = CompileAddExpr(interp, infoPtr, flags, envPtr);
    12261281    if (result != TCL_OK) {
     
    13001355    int op, result;
    13011356
     1357    HERE("addExpr", 10);
    13021358    result = CompileMultiplyExpr(interp, infoPtr, flags, envPtr);
    13031359    if (result != TCL_OK) {
     
    13771433    int op, result;
    13781434
     1435    HERE("multiplyExpr", 11);
    13791436    result = CompileUnaryExpr(interp, infoPtr, flags, envPtr);
    13801437    if (result != TCL_OK) {
     
    14561513    int op, result;
    14571514
     1515    HERE("unaryExpr", 12);
    14581516    op = infoPtr->token;
    14591517    if ((op == PLUS) || (op == MINUS) || (op == BIT_NOT) || (op == NOT)) {
     
    15501608     */
    15511609
     1610    HERE("primaryExpr", 13);
    15521611    theToken = infoPtr->token;
    15531612
  • external/tcl/tclCompile.c

    r83ee320 r2d7ff18  
    1717#include "tclInt.h"
    1818#include "tclCompile.h"
     19
     20/*
     21 * Variable that controls whether compilation tracing is enabled and, if so,
     22 * what level of tracing is desired:
     23 *    0: no compilation tracing
     24 *    1: summarize compilation of top level cmds and proc bodies
     25 *    2: display all instructions of each ByteCode compiled
     26 * This variable is linked to the Tcl variable "tcl_traceCompile".
     27 */
     28
     29int tclTraceCompile = 0;
     30static int traceInitialized = 0;
     31
     32/*
     33 * Count of the number of compilations and various other compilation-
     34 * related statistics.
     35 */
     36
     37#ifdef TCL_COMPILE_STATS
     38long tclNumCompilations = 0;
     39double tclTotalSourceBytes = 0.0;
     40double tclTotalCodeBytes = 0.0;
     41
     42double tclTotalInstBytes = 0.0;
     43double tclTotalObjBytes = 0.0;
     44double tclTotalExceptBytes = 0.0;
     45double tclTotalAuxBytes = 0.0;
     46double tclTotalCmdMapBytes = 0.0;
     47
     48double tclCurrentSourceBytes = 0.0;
     49double tclCurrentCodeBytes = 0.0;
     50
     51int tclSourceCount[32];
     52int tclByteCodeCount[32];
     53#endif /* TCL_COMPILE_STATS */
    1954
    2055/*
     
    408443 *----------------------------------------------------------------------
    409444 *
     445 * TclPrintByteCodeObj --
     446 *
     447 *      This procedure prints ("disassembles") the instructions of a
     448 *      bytecode object to stdout.
     449 *
     450 * Results:
     451 *      None.
     452 *
     453 * Side effects:
     454 *      None.
     455 *
     456 *----------------------------------------------------------------------
     457 */
     458
     459void
     460TclPrintByteCodeObj(interp, objPtr)
     461    Tcl_Interp *interp;         /* Used only for Tcl_GetStringFromObj. */
     462    Tcl_Obj *objPtr;            /* The bytecode object to disassemble. */
     463{
     464    ByteCode* codePtr = (ByteCode *) objPtr->internalRep.otherValuePtr;
     465    unsigned char *codeStart, *codeLimit, *pc;
     466    unsigned char *codeDeltaNext, *codeLengthNext;
     467    unsigned char *srcDeltaNext, *srcLengthNext;
     468    int codeOffset, codeLen, srcOffset, srcLen;
     469    int numCmds, numObjs, delta, objBytes, i;
     470
     471    if (codePtr->refCount <= 0) {
     472        return;                 /* already freed */
     473    }
     474
     475    codeStart = codePtr->codeStart;
     476    codeLimit = (codeStart + codePtr->numCodeBytes);
     477    numCmds = codePtr->numCommands;
     478    numObjs = codePtr->numObjects;
     479
     480    objBytes = (numObjs * sizeof(Tcl_Obj));
     481    for (i = 0;  i < numObjs;  i++) {
     482        Tcl_Obj *litObjPtr = codePtr->objArrayPtr[i];
     483        if (litObjPtr->bytes != NULL) {
     484            objBytes += litObjPtr->length;
     485        }
     486    }
     487
     488    /*
     489     * Print header lines describing the ByteCode.
     490     */
     491
     492    fprintf(stdout, "\nByteCode 0x%x, ref ct %u, epoch %u, interp 0x%x(epoch %u)\n",
     493            (unsigned int) codePtr, codePtr->refCount,
     494            codePtr->compileEpoch, (unsigned int) codePtr->iPtr,
     495            codePtr->iPtr->compileEpoch);
     496    fprintf(stdout, "  Source ");
     497    TclPrintSource(stdout, codePtr->source,
     498            TclMin(codePtr->numSrcChars, 70));
     499    fprintf(stdout, "\n  Cmds %d, chars %d, inst %d, objs %u, aux %d, stk depth %u, code/src %.2f\n",
     500            numCmds, codePtr->numSrcChars, codePtr->numCodeBytes, numObjs,
     501            codePtr->numAuxDataItems, codePtr->maxStackDepth,
     502            (codePtr->numSrcChars?
     503                    ((float)codePtr->totalSize)/((float)codePtr->numSrcChars) : 0.0));
     504    fprintf(stdout, "  Code %zu = %u(header)+%d(inst)+%d(objs)+%u(exc)+%u(aux)+%d(cmd map)\n",
     505            codePtr->totalSize, sizeof(ByteCode), codePtr->numCodeBytes,
     506            objBytes, (codePtr->numExcRanges * sizeof(ExceptionRange)),
     507            (codePtr->numAuxDataItems * sizeof(AuxData)),
     508            codePtr->numCmdLocBytes);
     509
     510    /*
     511     * If the ByteCode is the compiled body of a Tcl procedure, print
     512     * information about that procedure. Note that we don't know the
     513     * procedure's name since ByteCode's can be shared among procedures.
     514     */
     515   
     516    if (codePtr->procPtr != NULL) {
     517        Proc *procPtr = codePtr->procPtr;
     518        int numCompiledLocals = procPtr->numCompiledLocals;
     519        fprintf(stdout,
     520                "  Proc 0x%x, ref ct %d, args %d, compiled locals %d\n",
     521                (unsigned int) procPtr, procPtr->refCount, procPtr->numArgs,
     522                numCompiledLocals);
     523        if (numCompiledLocals > 0) {
     524            CompiledLocal *localPtr = procPtr->firstLocalPtr;
     525            for (i = 0;  i < numCompiledLocals;  i++) {
     526                fprintf(stdout, "      %d: slot %d%s%s%s%s%s%s",
     527                        i, localPtr->frameIndex,
     528                        ((localPtr->flags & VAR_SCALAR)?  ", scalar"  : ""),
     529                        ((localPtr->flags & VAR_ARRAY)?  ", array"  : ""),
     530                        ((localPtr->flags & VAR_LINK)?  ", link"  : ""),
     531                        ((localPtr->flags & VAR_ARGUMENT)?  ", arg"  : ""),
     532                        ((localPtr->flags & VAR_TEMPORARY)? ", temp" : ""),
     533                        ((localPtr->flags & VAR_RESOLVED)? ", resolved" : ""));
     534                if (TclIsVarTemporary(localPtr)) {
     535                    fprintf(stdout,     "\n");
     536                } else {
     537                    fprintf(stdout,     ", name=\"%s\"\n", localPtr->name);
     538                }
     539                localPtr = localPtr->nextPtr;
     540            }
     541        }
     542    }
     543
     544    /*
     545     * Print the ExceptionRange array.
     546     */
     547
     548    if (codePtr->numExcRanges > 0) {
     549        fprintf(stdout, "  Exception ranges %d, depth %d:\n",
     550                codePtr->numExcRanges, codePtr->maxExcRangeDepth);
     551        for (i = 0;  i < codePtr->numExcRanges;  i++) {
     552            ExceptionRange *rangePtr = &(codePtr->excRangeArrayPtr[i]);
     553            fprintf(stdout, "      %d: level %d, %s, pc %d-%d, ",
     554                    i, rangePtr->nestingLevel,
     555                    ((rangePtr->type == LOOP_EXCEPTION_RANGE)? "loop":"catch"),
     556                    rangePtr->codeOffset,
     557                    (rangePtr->codeOffset + rangePtr->numCodeBytes - 1));
     558            switch (rangePtr->type) {
     559            case LOOP_EXCEPTION_RANGE:
     560                fprintf(stdout, "continue %d, break %d\n",
     561                        rangePtr->continueOffset, rangePtr->breakOffset);
     562                break;
     563            case CATCH_EXCEPTION_RANGE:
     564                fprintf(stdout, "catch %d\n", rangePtr->catchOffset);
     565                break;
     566            default:
     567                panic("TclPrintSource: unrecognized ExceptionRange type %d\n",
     568                        rangePtr->type);
     569            }
     570        }
     571    }
     572   
     573    /*
     574     * If there were no commands (e.g., an expression or an empty string
     575     * was compiled), just print all instructions and return.
     576     */
     577
     578    if (numCmds == 0) {
     579        pc = codeStart;
     580        while (pc < codeLimit) {
     581            fprintf(stdout, "    ");
     582            pc += TclPrintInstruction(codePtr, pc);
     583        }
     584        return;
     585    }
     586   
     587    /*
     588     * Print table showing the code offset, source offset, and source
     589     * length for each command. These are encoded as a sequence of bytes.
     590     */
     591
     592    fprintf(stdout, "  Commands %d:", numCmds);
     593    codeDeltaNext = codePtr->codeDeltaStart;
     594    codeLengthNext = codePtr->codeLengthStart;
     595    srcDeltaNext  = codePtr->srcDeltaStart;
     596    srcLengthNext = codePtr->srcLengthStart;
     597    codeOffset = srcOffset = 0;
     598    for (i = 0;  i < numCmds;  i++) {
     599        if ((unsigned int) (*codeDeltaNext) == (unsigned int) 0xFF) {
     600            codeDeltaNext++;
     601            delta = TclGetInt4AtPtr(codeDeltaNext);
     602            codeDeltaNext += 4;
     603        } else {
     604            delta = TclGetInt1AtPtr(codeDeltaNext);
     605            codeDeltaNext++;
     606        }
     607        codeOffset += delta;
     608
     609        if ((unsigned int) (*codeLengthNext) == (unsigned int) 0xFF) {
     610            codeLengthNext++;
     611            codeLen = TclGetInt4AtPtr(codeLengthNext);
     612            codeLengthNext += 4;
     613        } else {
     614            codeLen = TclGetInt1AtPtr(codeLengthNext);
     615            codeLengthNext++;
     616        }
     617       
     618        if ((unsigned int) (*srcDeltaNext) == (unsigned int) 0xFF) {
     619            srcDeltaNext++;
     620            delta = TclGetInt4AtPtr(srcDeltaNext);
     621            srcDeltaNext += 4;
     622        } else {
     623            delta = TclGetInt1AtPtr(srcDeltaNext);
     624            srcDeltaNext++;
     625        }
     626        srcOffset += delta;
     627
     628        if ((unsigned int) (*srcLengthNext) == (unsigned int) 0xFF) {
     629            srcLengthNext++;
     630            srcLen = TclGetInt4AtPtr(srcLengthNext);
     631            srcLengthNext += 4;
     632        } else {
     633            srcLen = TclGetInt1AtPtr(srcLengthNext);
     634            srcLengthNext++;
     635        }
     636       
     637        fprintf(stdout, "%s%4d: pc %d-%d, source %d-%d",
     638                ((i % 2)? "     " : "\n   "),
     639                (i+1), codeOffset, (codeOffset + codeLen - 1),
     640                srcOffset, (srcOffset + srcLen - 1));
     641    }
     642    if ((numCmds > 0) && ((numCmds % 2) != 0)) {
     643        fprintf(stdout, "\n");
     644    }
     645   
     646    /*
     647     * Print each instruction. If the instruction corresponds to the start
     648     * of a command, print the command's source. Note that we don't need
     649     * the code length here.
     650     */
     651
     652    codeDeltaNext = codePtr->codeDeltaStart;
     653    srcDeltaNext  = codePtr->srcDeltaStart;
     654    srcLengthNext = codePtr->srcLengthStart;
     655    codeOffset = srcOffset = 0;
     656    pc = codeStart;
     657    for (i = 0;  i < numCmds;  i++) {
     658        if ((unsigned int) (*codeDeltaNext) == (unsigned int) 0xFF) {
     659            codeDeltaNext++;
     660            delta = TclGetInt4AtPtr(codeDeltaNext);
     661            codeDeltaNext += 4;
     662        } else {
     663            delta = TclGetInt1AtPtr(codeDeltaNext);
     664            codeDeltaNext++;
     665        }
     666        codeOffset += delta;
     667
     668        if ((unsigned int) (*srcDeltaNext) == (unsigned int) 0xFF) {
     669            srcDeltaNext++;
     670            delta = TclGetInt4AtPtr(srcDeltaNext);
     671            srcDeltaNext += 4;
     672        } else {
     673            delta = TclGetInt1AtPtr(srcDeltaNext);
     674            srcDeltaNext++;
     675        }
     676        srcOffset += delta;
     677
     678        if ((unsigned int) (*srcLengthNext) == (unsigned int) 0xFF) {
     679            srcLengthNext++;
     680            srcLen = TclGetInt4AtPtr(srcLengthNext);
     681            srcLengthNext += 4;
     682        } else {
     683            srcLen = TclGetInt1AtPtr(srcLengthNext);
     684            srcLengthNext++;
     685        }
     686
     687        /*
     688         * Print instructions before command i.
     689         */
     690       
     691        while ((pc-codeStart) < codeOffset) {
     692            fprintf(stdout, "    ");
     693            pc += TclPrintInstruction(codePtr, pc);
     694        }
     695
     696        fprintf(stdout, "  Command %d: ", (i+1));
     697        TclPrintSource(stdout, (codePtr->source + srcOffset),
     698                TclMin(srcLen, 70));
     699        fprintf(stdout, "\n");
     700    }
     701    if (pc < codeLimit) {
     702        /*
     703         * Print instructions after the last command.
     704         */
     705
     706        while (pc < codeLimit) {
     707            fprintf(stdout, "    ");
     708            pc += TclPrintInstruction(codePtr, pc);
     709        }
     710    }
     711}
     712
     713
     714/*
     715 *----------------------------------------------------------------------
     716 *
     717 * TclPrintInstruction --
     718 *
     719 *      This procedure prints ("disassembles") one instruction from a
     720 *      bytecode object to stdout.
     721 *
     722 * Results:
     723 *      Returns the length in bytes of the current instruiction.
     724 *
     725 * Side effects:
     726 *      None.
     727 *
     728 *----------------------------------------------------------------------
     729 */
     730
     731int
     732TclPrintInstruction(codePtr, pc)
     733    ByteCode* codePtr;          /* Bytecode containing the instruction. */
     734    unsigned char *pc;          /* Points to first byte of instruction. */
     735{
     736    Proc *procPtr = codePtr->procPtr;
     737    unsigned char opCode = *pc;
     738    register InstructionDesc *instDesc = &instructionTable[opCode];
     739    unsigned char *codeStart = codePtr->codeStart;
     740    unsigned int pcOffset = (pc - codeStart);
     741    int opnd, elemLen, i, j;
     742    Tcl_Obj *elemPtr;
     743    char *string;
     744   
     745    fprintf(stdout, "(%u) %s ", pcOffset, instDesc->name);
     746    for (i = 0;  i < instDesc->numOperands;  i++) {
     747        switch (instDesc->opTypes[i]) {
     748        case OPERAND_INT1:
     749            opnd = TclGetInt1AtPtr(pc+1+i);
     750            if ((i == 0) && ((opCode == INST_JUMP1)
     751                             || (opCode == INST_JUMP_TRUE1)
     752                             || (opCode == INST_JUMP_FALSE1))) {
     753                fprintf(stdout, "%d     # pc %u", opnd, (pcOffset + opnd));
     754            } else {
     755                fprintf(stdout, "%d", opnd);
     756            }
     757            break;
     758        case OPERAND_INT4:
     759            opnd = TclGetInt4AtPtr(pc+1+i);
     760            if ((i == 0) && ((opCode == INST_JUMP4)
     761                             || (opCode == INST_JUMP_TRUE4)
     762                             || (opCode == INST_JUMP_FALSE4))) {
     763                fprintf(stdout, "%d     # pc %u", opnd, (pcOffset + opnd));
     764            } else {
     765                fprintf(stdout, "%d", opnd);
     766            }
     767            break;
     768        case OPERAND_UINT1:
     769            opnd = TclGetUInt1AtPtr(pc+1+i);
     770            if ((i == 0) && (opCode == INST_PUSH1)) {
     771                elemPtr = codePtr->objArrayPtr[opnd];
     772                string = Tcl_GetStringFromObj(elemPtr, &elemLen);
     773                fprintf(stdout, "%u     # ", (unsigned int) opnd);
     774                TclPrintSource(stdout, string, TclMin(elemLen, 40));
     775            } else if ((i == 0) && ((opCode == INST_LOAD_SCALAR1)
     776                                    || (opCode == INST_LOAD_ARRAY1)
     777                                    || (opCode == INST_STORE_SCALAR1)
     778                                    || (opCode == INST_STORE_ARRAY1))) {
     779                int localCt = procPtr->numCompiledLocals;
     780                CompiledLocal *localPtr = procPtr->firstLocalPtr;
     781                if (opnd >= localCt) {
     782                    panic("TclPrintInstruction: bad local var index %u (%u locals)\n",
     783                             (unsigned int) opnd, localCt);
     784                    return instDesc->numBytes;
     785                }
     786                for (j = 0;  j < opnd;  j++) {
     787                    localPtr = localPtr->nextPtr;
     788                }
     789                if (TclIsVarTemporary(localPtr)) {
     790                    fprintf(stdout, "%u # temp var %u",
     791                            (unsigned int) opnd, (unsigned int) opnd);
     792                } else {
     793                    fprintf(stdout, "%u # var ", (unsigned int) opnd);
     794                    TclPrintSource(stdout, localPtr->name, 40);
     795                }
     796            } else {
     797                fprintf(stdout, "%u ", (unsigned int) opnd);
     798            }
     799            break;
     800        case OPERAND_UINT4:
     801            opnd = TclGetUInt4AtPtr(pc+1+i);
     802            if (opCode == INST_PUSH4) {
     803                elemPtr = codePtr->objArrayPtr[opnd];
     804                string = Tcl_GetStringFromObj(elemPtr, &elemLen);
     805                fprintf(stdout, "%u     # ", opnd);
     806                TclPrintSource(stdout, string, TclMin(elemLen, 40));
     807            } else if ((i == 0) && ((opCode == INST_LOAD_SCALAR4)
     808                                    || (opCode == INST_LOAD_ARRAY4)
     809                                    || (opCode == INST_STORE_SCALAR4)
     810                                    || (opCode == INST_STORE_ARRAY4))) {
     811                int localCt = procPtr->numCompiledLocals;
     812                CompiledLocal *localPtr = procPtr->firstLocalPtr;
     813                if (opnd >= localCt) {
     814                    panic("TclPrintInstruction: bad local var index %u (%u locals)\n",
     815                             (unsigned int) opnd, localCt);
     816                    return instDesc->numBytes;
     817                }
     818                for (j = 0;  j < opnd;  j++) {
     819                    localPtr = localPtr->nextPtr;
     820                }
     821                if (TclIsVarTemporary(localPtr)) {
     822                    fprintf(stdout, "%u # temp var %u",
     823                            (unsigned int) opnd, (unsigned int) opnd);
     824                } else {
     825                    fprintf(stdout, "%u # var ", (unsigned int) opnd);
     826                    TclPrintSource(stdout, localPtr->name, 40);
     827                }
     828            } else {
     829                fprintf(stdout, "%u ", (unsigned int) opnd);
     830            }
     831            break;
     832        case OPERAND_NONE:
     833        default:
     834            break;
     835        }
     836    }
     837    fprintf(stdout, "\n");
     838    return instDesc->numBytes;
     839}
     840
     841
     842/*
     843 *----------------------------------------------------------------------
     844 *
    410845 * TclPrintSource --
    411846 *
     
    537972    register int i;
    538973
     974#ifdef TCL_COMPILE_STATS   
     975    tclCurrentSourceBytes -= (double) codePtr->numSrcChars;
     976    tclCurrentCodeBytes -= (double) codePtr->totalSize;
     977#endif /* TCL_COMPILE_STATS */
     978
    539979    /*
    540980     * A single heap object holds the ByteCode structure and its code,
     
    6271067    int length, result;
    6281068
     1069    if (!traceInitialized) {
     1070        if (Tcl_LinkVar(interp, "tcl_traceCompile",
     1071                    (char *) &tclTraceCompile,  TCL_LINK_INT) != TCL_OK) {
     1072            panic("SetByteCodeFromAny: unable to create link for tcl_traceCompile variable");
     1073        }
     1074        traceInitialized = 1;
     1075    }
     1076   
    6291077    string = Tcl_GetStringFromObj(objPtr, &length);
    6301078    TclInitCompileEnv(interp, &compEnv, string);
     
    6651113    TclFreeCompileEnv(&compEnv);
    6661114
     1115    if (result == TCL_OK) {
     1116        if (tclTraceCompile == 2) {
     1117            TclPrintByteCodeObj(interp, objPtr);
     1118        }
     1119    }
    6671120    return result;
    6681121}
     
    8581311    int numObjects, i;
    8591312    Namespace *namespacePtr;
     1313#ifdef TCL_COMPILE_STATS
     1314    int srcLenLog2, sizeLog2;
     1315#endif /*TCL_COMPILE_STATS*/
    8601316
    8611317    codeBytes = (envPtr->codeNext - envPtr->codeStart);
     
    8861342    }
    8871343    totalSize = (size + objBytes);
     1344
     1345#ifdef TCL_COMPILE_STATS
     1346    tclNumCompilations++;
     1347    tclTotalSourceBytes += (double) srcLen;
     1348    tclTotalCodeBytes += (double) totalSize;
     1349   
     1350    tclTotalInstBytes += (double) codeBytes;
     1351    tclTotalObjBytes += (double) objBytes;
     1352    tclTotalExceptBytes += exceptArrayBytes;
     1353    tclTotalAuxBytes += (double) auxDataArrayBytes;
     1354    tclTotalCmdMapBytes += (double) cmdLocBytes;
     1355
     1356    tclCurrentSourceBytes += (double) srcLen;
     1357    tclCurrentCodeBytes += (double) totalSize;
     1358
     1359    srcLenLog2 = TclLog2(srcLen);
     1360    sizeLog2 = TclLog2((int) totalSize);
     1361    if ((srcLenLog2 > 31) || (sizeLog2 > 31)) {
     1362        panic("TclInitByteCodeObj: bad source or code sizes\n");
     1363    }
     1364    tclSourceCount[srcLenLog2]++;
     1365    tclByteCodeCount[sizeLog2]++;
     1366#endif /* TCL_COMPILE_STATS */   
    8881367
    8891368    if (envPtr->iPtr->varFramePtr != NULL) {
     
    13411820                cmdCodeOffset);
    13421821           
     1822        if ((!(flags & TCL_BRACKET_TERM))
     1823                && (tclTraceCompile >= 1) && (envPtr->procPtr == NULL)) {
     1824            /*
     1825             * Display a line summarizing the top level command we are about
     1826             * to compile.
     1827             */
     1828           
     1829            char *p = cmdSrcStart;
     1830            int numChars, complete;
     1831           
     1832            while ((CHAR_TYPE(p, lastChar) != TCL_COMMAND_END)
     1833                   || ((*p == ']') && !(flags & TCL_BRACKET_TERM))) {
     1834                p++;
     1835            }
     1836            numChars = (p - cmdSrcStart);
     1837            complete = 1;
     1838            if (numChars > 60) {
     1839                numChars = 60;
     1840                complete = 0;
     1841            } else if ((numChars >= 2) && (*p == '\n') && (*(p-1) == '{')) {
     1842                complete = 0;
     1843            }
     1844            fprintf(stdout, "Compiling: %.*s%s\n",
     1845                    numChars, cmdSrcStart, (complete? "" : " ..."));
     1846        }
     1847       
    13431848        while ((type != TCL_COMMAND_END)
    13441849                || ((c == ']') && !(flags & TCL_BRACKET_TERM))) {
  • external/tcl/tclCompile.h

    r83ee320 r2d7ff18  
    3636
    3737extern Tcl_ObjType      tclCmdNameType;
     38
     39/*
     40 * Variable that controls whether compilation tracing is enabled and, if so,
     41 * what level of tracing is desired:
     42 *    0: no compilation tracing
     43 *    1: summarize compilation of top level cmds and proc bodies
     44 *    2: display all instructions of each ByteCode compiled
     45 * This variable is linked to the Tcl variable "tcl_traceCompile".
     46 */
     47
     48extern int              tclTraceCompile;
     49
     50/*
     51 * Variable that controls whether execution tracing is enabled and, if so,
     52 * what level of tracing is desired:
     53 *    0: no execution tracing
     54 *    1: trace invocations of Tcl procs only
     55 *    2: trace invocations of all (not compiled away) commands
     56 *    3: display each instruction executed
     57 * This variable is linked to the Tcl variable "tcl_traceExec".
     58 */
     59
     60extern int              tclTraceExec;
     61
     62/*
     63 * The number of bytecode compilations and various other compilation-related
     64 * statistics. The tclByteCodeCount and tclSourceCount arrays are used to
     65 * hold the count of ByteCodes and sources whose sizes fall into various
     66 * binary decades; e.g., tclByteCodeCount[5] is a count of the ByteCodes
     67 * with size larger than 2**4 and less than or equal to 2**5.
     68 */
     69
     70#ifdef TCL_COMPILE_STATS
     71extern long             tclNumCompilations;
     72extern double           tclTotalSourceBytes;
     73extern double           tclTotalCodeBytes;
     74
     75extern double           tclTotalInstBytes;
     76extern double           tclTotalObjBytes;
     77extern double           tclTotalExceptBytes;
     78extern double           tclTotalAuxBytes;
     79extern double           tclTotalCmdMapBytes;
     80
     81extern double           tclCurrentSourceBytes;
     82extern double           tclCurrentCodeBytes;
     83
     84extern int              tclSourceCount[32];
     85extern int              tclByteCodeCount[32];
     86#endif /* TCL_COMPILE_STATS */
    3887
    3988/*
     
    767816EXTERN void             TclInitJumpFixupArray _ANSI_ARGS_((
    768817                            JumpFixupArray *fixupArrayPtr));
     818#ifdef TCL_COMPILE_STATS
     819EXTERN int              TclLog2 _ANSI_ARGS_((int value));
     820#endif /*TCL_COMPILE_STATS*/
    769821EXTERN int              TclObjIndexForString _ANSI_ARGS_((char *start,
    770822                            int length, int allocStrRep, int inHeap,
    771823                            CompileEnv *envPtr));
     824EXTERN int              TclPrintInstruction _ANSI_ARGS_((ByteCode* codePtr,
     825                            unsigned char *pc));
    772826EXTERN void             TclPrintSource _ANSI_ARGS_((FILE *outFile,
    773827                            char *string, int maxChars));
  • external/tcl/tclExecute.c

    r83ee320 r2d7ff18  
    5151
    5252/*
     53 * Variable that controls whether execution tracing is enabled and, if so,
     54 * what level of tracing is desired:
     55 *    0: no execution tracing
     56 *    1: trace invocations of Tcl procs only
     57 *    2: trace invocations of all (not compiled away) commands
     58 *    3: display each instruction executed
     59 * This variable is linked to the Tcl variable "tcl_traceExec".
     60 */
     61
     62int tclTraceExec = 0;
     63
     64/*
    5365 * The following global variable is use to signal matherr that Tcl
    5466 * is responsible for the arithmetic, so errors can be handled in a
     
    90102};
    91103   
     104/*
     105 * Mapping from Tcl result codes to strings; used for error and debugging
     106 * messages.
     107 */
     108
     109#ifdef TCL_COMPILE_DEBUG
     110static char *resultStrings[] = {
     111    "TCL_OK", "TCL_ERROR", "TCL_RETURN", "TCL_BREAK", "TCL_CONTINUE"
     112};
     113#endif /* TCL_COMPILE_DEBUG */
     114
     115/*
     116 * The following are statistics-related variables that record information
     117 * about the bytecode compiler and interpreter's operation. This includes
     118 * an array that records for each instruction how often it is executed.
     119 */
     120
     121#ifdef TCL_COMPILE_STATS
     122static long numExecutions = 0;
     123static int instructionCount[256];
     124#endif /* TCL_COMPILE_STATS */
     125
    92126/*
    93127 * Macros for testing floating-point values for certain special cases. Test
     
    153187#define POP_OBJECT() \
    154188    (stackPtr[stackTop--].o)
     189
     190/*
     191 * Macros used to trace instruction execution. The macros TRACE,
     192 * TRACE_WITH_OBJ, and O2S are only used inside TclExecuteByteCode.
     193 * O2S is only used in TRACE* calls to get a string from an object.
     194 *
     195 * NOTE THAT CLIENTS OF O2S ARE LIKELY TO FAIL IF THE OBJECT'S
     196 * STRING REP CONTAINS NULLS.
     197 */
     198
     199#ifdef TCL_COMPILE_DEBUG
     200       
     201#define O2S(objPtr) \
     202    Tcl_GetStringFromObj((objPtr), &length)
     203       
     204#ifdef TCL_COMPILE_STATS
     205#define TRACE(a) \
     206    if (traceInstructions) { \
     207        fprintf(stdout, "%d: %d,%ld (%u) ", iPtr->numLevels, \
     208               stackTop, (tclObjsAlloced - tclObjsFreed), \
     209               (unsigned int)(pc - codePtr->codeStart)); \
     210        printf a; \
     211        fflush(stdout); \
     212    }
     213#define TRACE_WITH_OBJ(a, objPtr) \
     214    if (traceInstructions) { \
     215        fprintf(stdout, "%d: %d,%ld (%u) ", iPtr->numLevels, \
     216               stackTop, (tclObjsAlloced - tclObjsFreed), \
     217               (unsigned int)(pc - codePtr->codeStart)); \
     218        printf a; \
     219        bytes = Tcl_GetStringFromObj((objPtr), &length); \
     220        TclPrintSource(stdout, bytes, TclMin(length, 30)); \
     221        fprintf(stdout, "\n"); \
     222        fflush(stdout); \
     223    }
     224#else  /* not TCL_COMPILE_STATS */
     225#define TRACE(a) \
     226    if (traceInstructions) { \
     227        fprintf(stdout, "%d: %d (%u) ", iPtr->numLevels, stackTop, \
     228               (unsigned int)(pc - codePtr->codeStart)); \
     229        printf a; \
     230        fflush(stdout); \
     231    }
     232#define TRACE_WITH_OBJ(a, objPtr) \
     233    if (traceInstructions) { \
     234        fprintf(stdout, "%d: %d (%u) ", iPtr->numLevels, stackTop, \
     235               (unsigned int)(pc - codePtr->codeStart)); \
     236        printf a; \
     237        bytes = Tcl_GetStringFromObj((objPtr), &length); \
     238        TclPrintSource(stdout, bytes, TclMin(length, 30)); \
     239        fprintf(stdout, "\n"); \
     240        fflush(stdout); \
     241    }
     242#endif /* TCL_COMPILE_STATS */
     243
     244#else  /* not TCL_COMPILE_DEBUG */
     245       
     246#define TRACE(a)
     247#define TRACE_WITH_OBJ(a, objPtr)
     248#define O2S(objPtr)
     249       
     250#endif /* TCL_COMPILE_DEBUG */
    155251
    156252/*
     
    178274static int              ExprUnaryFunc _ANSI_ARGS_((Tcl_Interp *interp,
    179275                            ExecEnv *eePtr, ClientData clientData));
     276#ifdef TCL_COMPILE_STATS
     277static int              EvalStatsCmd _ANSI_ARGS_((ClientData clientData,
     278                            Tcl_Interp *interp, int argc, char **argv));
     279#endif /* TCL_COMPILE_STATS */
    180280static void             FreeCmdNameInternalRep _ANSI_ARGS_((
    181281                            Tcl_Obj *objPtr));
     
    193293static int              SetCmdNameFromAny _ANSI_ARGS_((Tcl_Interp *interp,
    194294                            Tcl_Obj *objPtr));
     295#ifdef TCL_COMPILE_DEBUG
     296static char *           StringForResultCode _ANSI_ARGS_((int result));
     297#endif /* TCL_COMPILE_DEBUG */
    195298static void             UpdateStringOfCmdName _ANSI_ARGS_((Tcl_Obj *objPtr));
     299#ifdef TCL_COMPILE_DEBUG
     300static void             ValidatePcAndStackTop _ANSI_ARGS_((
     301                            ByteCode *codePtr, unsigned char *pc,
     302                            int stackTop, int stackLowerBound,
     303                            int stackUpperBound));
     304#endif /* TCL_COMPILE_DEBUG */
    196305
    197306/*
     
    259368 *
    260369 * Side effects:
    261  *      This procedure initializes the array of instruction names.
     370 *      This procedure initializes the array of instruction names. If
     371 *      compiling with the TCL_COMPILE_STATS flag, it initializes the
     372 *      array that counts the executions of each instruction and it
     373 *      creates the "evalstats" command. It also registers the command name
     374 *      Tcl_ObjType. It also establishes the link between the Tcl
     375 *      "tcl_traceExec" and C "tclTraceExec" variables.
    262376 *
    263377 *----------------------------------------------------------------------
     
    277391    for (i = 0;  instructionTable[i].name != NULL;  i++) {
    278392        opName[i] = instructionTable[i].name;
     393    }
     394
     395#ifdef TCL_COMPILE_STATS   
     396    (VOID *) memset(instructionCount, 0, sizeof(instructionCount));
     397    (VOID *) memset(tclByteCodeCount, 0, sizeof(tclByteCodeCount));
     398    (VOID *) memset(tclSourceCount, 0, sizeof(tclSourceCount));
     399
     400    Tcl_CreateCommand(interp, "evalstats", EvalStatsCmd,
     401                      (ClientData) NULL, (Tcl_CmdDeleteProc *) NULL);
     402#endif /* TCL_COMPILE_STATS */
     403   
     404    if (Tcl_LinkVar(interp, "tcl_traceExec", (char *) &tclTraceExec,
     405                    TCL_LINK_INT) != TCL_OK) {
     406        panic("InitByteCodeExecution: can't create link for tcl_traceExec variable");
    279407    }
    280408}
     
    470598                                 * process break, continue, and errors. */
    471599    int result = TCL_OK;        /* Return code returned after execution. */
     600    int traceInstructions = (tclTraceExec == 3);
    472601    Tcl_Obj *valuePtr, *value2Ptr, *namePtr, *objPtr;
    473602    char *bytes;
    474603    int length;
    475604    long i;
     605    Tcl_DString command;        /* Used for debugging. If tclTraceExec >= 2
     606                                 * holds a string representing the last
     607                                 * command invoked. */
    476608
    477609    /*
     
    488620
    489621    /*
     622     * THIS PROC FAILS IF AN OBJECT'S STRING REP HAS A NULL BYTE.
     623     */
     624
     625    if (tclTraceExec >= 2) {
     626        PrintByteCodeInfo(codePtr);
     627#ifdef TCL_COMPILE_STATS
     628        fprintf(stdout, "  Starting stack top=%d, system objects=%ld\n",
     629                eePtr->stackTop, (tclObjsAlloced - tclObjsFreed));
     630#else
     631        fprintf(stdout, "  Starting stack top=%d\n", eePtr->stackTop);
     632#endif /* TCL_COMPILE_STATS */
     633        fflush(stdout);
     634    }
     635
     636#ifdef TCL_COMPILE_STATS
     637    numExecutions++;
     638#endif /* TCL_COMPILE_STATS */
     639
     640    /*
    490641     * Make sure the catch stack is large enough to hold the maximum number
    491642     * of catch commands that could ever be executing at the same time. This
     
    508659
    509660    /*
     661     * Initialize the buffer that holds a string containing the name and
     662     * arguments for the last invoked command.
     663     */
     664
     665    Tcl_DStringInit(&command);
     666
     667    /*
    510668     * Loop executing instructions until a "done" instruction, a TCL_RETURN,
    511669     * or some error.
     
    513671
    514672    for (;;) {
     673#ifdef TCL_COMPILE_DEBUG
     674        ValidatePcAndStackTop(codePtr, pc, stackTop, initStackTop,
     675                eePtr->stackEnd);
     676#else /* not TCL_COMPILE_DEBUG */
     677        if (traceInstructions) {
     678#ifdef TCL_COMPILE_STATS
     679            fprintf(stdout, "%d: %d,%ld ", iPtr->numLevels, stackTop,
     680                    (tclObjsAlloced - tclObjsFreed));
     681#else /* TCL_COMPILE_STATS */
     682            fprintf(stdout, "%d: %d ", iPtr->numLevels, stackTop);
     683#endif /* TCL_COMPILE_STATS */
     684            TclPrintInstruction(codePtr, pc);
     685            fflush(stdout);
     686        }
     687#endif /* TCL_COMPILE_DEBUG */
     688       
    515689        opCode = *pc;
     690#ifdef TCL_COMPILE_STATS   
     691        instructionCount[opCode]++;
     692#endif /* TCL_COMPILE_STATS */
    516693
    517694        switch (opCode) {
     
    533710                panic("TclExecuteByteCode execution failure: end stack top != start stack top");
    534711            }
     712            TRACE_WITH_OBJ(("done => return code=%d, result is ", result),
     713                    iPtr->objResultPtr);
    535714            goto done;
    536715           
     
    538717            valuePtr = objArrayPtr[TclGetUInt1AtPtr(pc+1)];
    539718            PUSH_OBJECT(valuePtr);
     719            TRACE_WITH_OBJ(("push1 %u => ", TclGetUInt1AtPtr(pc+1)),
     720                    valuePtr);
    540721            ADJUST_PC(2);
    541722           
     
    543724            valuePtr = objArrayPtr[TclGetUInt4AtPtr(pc+1)];
    544725            PUSH_OBJECT(valuePtr);
     726            TRACE_WITH_OBJ(("push4 %u => ", TclGetUInt4AtPtr(pc+1)),
     727                    valuePtr);
    545728            ADJUST_PC(5);
    546729           
    547730        case INST_POP:
    548731            valuePtr = POP_OBJECT();
     732            TRACE_WITH_OBJ(("pop => discarding "), valuePtr);
    549733            TclDecrRefCount(valuePtr); /* finished with pop'ed object. */
    550734            ADJUST_PC(1);
     
    553737            valuePtr = stackPtr[stackTop].o;
    554738            PUSH_OBJECT(Tcl_DuplicateObj(valuePtr));
     739            TRACE_WITH_OBJ(("dup => "), valuePtr);
    555740            ADJUST_PC(1);
    556741
     
    605790               
    606791                PUSH_OBJECT(concatObjPtr);
     792                TRACE_WITH_OBJ(("concat %u => ", opnd), concatObjPtr);
    607793                ADJUST_PC(2);
    608794            }
     
    629815                                    * Init. to avoid compiler warning. */
    630816                Tcl_Command cmd;
     817#ifdef TCL_COMPILE_DEBUG
     818                int isUnknownCmd = 0;
     819                char cmdNameBuf[30];
     820#endif /* TCL_COMPILE_DEBUG */
    631821               
    632822                /*
     
    677867                                "invalid command name \"", cmdName, "\"",
    678868                                (char *) NULL);
     869                        TRACE(("%s %u => unknown proc not found: ",
     870                               opName[opCode], objc));
    679871                        result = TCL_ERROR;
    680872                        goto checkForCatch;
    681873                    }
    682874                    cmdPtr = (Command *) cmd;
     875#ifdef TCL_COMPILE_DEBUG
     876                    isUnknownCmd = 1;
     877#endif /*TCL_COMPILE_DEBUG*/                   
    683878                    stackTop++; /* need room for new inserted objv[0] */
    684879                    for (i = objc;  i >= 0;  i--) {
     
    723918                Tcl_ResetResult(interp);
    724919
     920                if (tclTraceExec >= 2) {
     921                    char buffer[50];
     922
     923                    sprintf(buffer, "%d: (%u) invoking ", iPtr->numLevels,
     924                            (unsigned int)(pc - codePtr->codeStart));
     925                    Tcl_DStringAppend(&command, buffer, -1);
     926                   
     927#ifdef TCL_COMPILE_DEBUG
     928                    if (traceInstructions) { /* tclTraceExec == 3 */
     929                        strncpy(cmdNameBuf, cmdName, 20);
     930                        TRACE(("%s %u => call ", opName[opCode],
     931                               (isUnknownCmd? objc-1 : objc)));
     932                    } else {
     933                        fprintf(stdout, "%s", buffer);
     934                    }
     935#else /* TCL_COMPILE_DEBUG */
     936                    fprintf(stdout, "%s", buffer);
     937#endif /*TCL_COMPILE_DEBUG*/
     938
     939                    for (i = 0;  i < objc;  i++) {
     940                        bytes = TclGetStringFromObj(objv[i], &length);
     941                        TclPrintSource(stdout, bytes, TclMin(length, 15));
     942                        fprintf(stdout, " ");
     943
     944                        sprintf(buffer, "\"%.*s\" ", TclMin(length, 15), bytes);
     945                        Tcl_DStringAppend(&command, buffer, -1);
     946                    }
     947                    fprintf(stdout, "\n");
     948                    fflush(stdout);
     949
     950                    Tcl_DStringFree(&command);
     951                }
     952
    725953                iPtr->cmdCount++;
    726954                DECACHE_STACK_INFO();
     
    768996                     */
    769997                    PUSH_OBJECT(Tcl_GetObjResult(interp));
     998                    TRACE_WITH_OBJ(("%s %u => ...after \"%.20s\", result=",
     999                            opName[opCode], objc, cmdNameBuf),
     1000                            Tcl_GetObjResult(interp));
    7701001                    ADJUST_PC(pcAdjustment);
    7711002                   
     
    7841015                            /*catchOnly*/ 0, codePtr);
    7851016                    if (rangePtr == NULL) {
     1017                        TRACE(("%s %u => ... after \"%.20s\", no encl. loop or catch, returning %s\n",
     1018                                opName[opCode], objc, cmdNameBuf,
     1019                                StringForResultCode(result)));
    7861020                        goto abnormalReturn; /* no catch exists to check */
    7871021                    }
     
    7911025                            newPcOffset = rangePtr->breakOffset;
    7921026                        } else if (rangePtr->continueOffset == -1) {
     1027                            TRACE(("%s %u => ... after \"%.20s\", %s, loop w/o continue, checking for catch\n",
     1028                                   opName[opCode], objc, cmdNameBuf,
     1029                                   StringForResultCode(result)));
    7931030                            goto checkForCatch;
    7941031                        } else {
    7951032                            newPcOffset = rangePtr->continueOffset;
    7961033                        }
     1034                        TRACE(("%s %u => ... after \"%.20s\", %s, range at %d, new pc %d\n",
     1035                               opName[opCode], objc, cmdNameBuf,
     1036                               StringForResultCode(result),
     1037                               rangePtr->codeOffset, newPcOffset));
    7971038                        break;
    7981039                    case CATCH_EXCEPTION_RANGE:
     1040                        TRACE(("%s %u => ... after \"%.20s\", %s...\n",
     1041                               opName[opCode], objc, cmdNameBuf,
     1042                               StringForResultCode(result)));
    7991043                        goto processCatch; /* it will use rangePtr */
    8001044                    default:
     
    8101054                     * enclosing catch exception range, if any.
    8111055                     */
     1056                    TRACE_WITH_OBJ(("%s %u => ... after \"%.20s\", TCL_ERROR ",
     1057                            opName[opCode], objc, cmdNameBuf),
     1058                            Tcl_GetObjResult(interp));
    8121059                    goto checkForCatch;
    8131060
     
    8181065                     * for an enclosing catch exception range, if any.
    8191066                     */
     1067                    TRACE(("%s %u => ... after \"%.20s\", TCL_RETURN\n",
     1068                            opName[opCode], objc, cmdNameBuf));
    8201069                    goto checkForCatch;
    8211070
    8221071                default:
     1072                    TRACE_WITH_OBJ(("%s %u => ... after \"%.20s\", OTHER RETURN CODE %d ",
     1073                            opName[opCode], objc, cmdNameBuf, result),
     1074                            Tcl_GetObjResult(interp));
    8231075                    goto checkForCatch;
    8241076                } /* end of switch on result from invoke instruction */
     
    8361088               
    8371089                PUSH_OBJECT(Tcl_GetObjResult(interp));
     1090                TRACE_WITH_OBJ(("evalStk \"%.30s\" => ", O2S(objPtr)),
     1091                        Tcl_GetObjResult(interp));
    8381092                TclDecrRefCount(objPtr);
    8391093                ADJUST_PC(1);
     
    8551109                        codePtr);
    8561110                if (rangePtr == NULL) {
     1111                    TRACE(("evalStk \"%.30s\" => no encl. loop or catch, returning %s\n",
     1112                            O2S(objPtr), StringForResultCode(result)));
    8571113                    Tcl_DecrRefCount(objPtr);
    8581114                    goto abnormalReturn;    /* no catch exists to check */
     
    8631119                        newPcOffset = rangePtr->breakOffset;
    8641120                    } else if (rangePtr->continueOffset == -1) {
     1121                        TRACE(("evalStk \"%.30s\" => %s, loop w/o continue, checking for catch\n",
     1122                               O2S(objPtr), StringForResultCode(result)));
    8651123                        Tcl_DecrRefCount(objPtr);
    8661124                        goto checkForCatch;
     
    8691127                    }
    8701128                    result = TCL_OK;
     1129                    TRACE_WITH_OBJ(("evalStk \"%.30s\" => %s, range at %d, new pc %d ",
     1130                            O2S(objPtr), StringForResultCode(result),
     1131                            rangePtr->codeOffset, newPcOffset), valuePtr);
    8711132                    break;
    8721133                case CATCH_EXCEPTION_RANGE:
     1134                    TRACE_WITH_OBJ(("evalStk \"%.30s\" => %s ",
     1135                            O2S(objPtr), StringForResultCode(result)),
     1136                            valuePtr);
    8731137                    Tcl_DecrRefCount(objPtr);
    8741138                    goto processCatch;  /* it will use rangePtr */
     
    8801144                continue;       /* restart outer instruction loop at pc */
    8811145            } else { /* eval returned TCL_ERROR, TCL_RETURN, unknown code */
     1146                TRACE_WITH_OBJ(("evalStk \"%.30s\" => ERROR: ", O2S(objPtr)),
     1147                        Tcl_GetObjResult(interp));
    8821148                Tcl_DecrRefCount(objPtr);
    8831149                goto checkForCatch;
     
    8911157            CACHE_STACK_INFO();
    8921158            if (result != TCL_OK) {
     1159                TRACE_WITH_OBJ(("exprStk \"%.30s\" => ERROR: ",
     1160                        O2S(objPtr)), Tcl_GetObjResult(interp));
    8931161                Tcl_DecrRefCount(objPtr);
    8941162                goto checkForCatch;
    8951163            }
    8961164            stackPtr[++stackTop].o = valuePtr; /* already has right refct */
     1165            TRACE_WITH_OBJ(("exprStk \"%.30s\" => ", O2S(objPtr)), valuePtr);
    8971166            TclDecrRefCount(objPtr);
    8981167            ADJUST_PC(1);
     
    9131182            CACHE_STACK_INFO();
    9141183            if (valuePtr == NULL) {
     1184                TRACE_WITH_OBJ(("%s %u => ERROR: ", opName[opCode], opnd),
     1185                        Tcl_GetObjResult(interp));
    9151186                result = TCL_ERROR;
    9161187                goto checkForCatch;
    9171188            }
    9181189            PUSH_OBJECT(valuePtr);
     1190            TRACE_WITH_OBJ(("%s %u => ", opName[opCode], opnd), valuePtr);
    9191191            ADJUST_PC(pcAdjustment);
    9201192
     
    9261198            CACHE_STACK_INFO();
    9271199            if (valuePtr == NULL) {
     1200                TRACE_WITH_OBJ(("loadScalarStk \"%.30s\" => ERROR: ",
     1201                        O2S(namePtr)), Tcl_GetObjResult(interp));
    9281202                Tcl_DecrRefCount(namePtr);
    9291203                result = TCL_ERROR;
     
    9311205            }
    9321206            PUSH_OBJECT(valuePtr);
     1207            TRACE_WITH_OBJ(("loadScalarStk \"%.30s\" => ",
     1208                    O2S(namePtr)), valuePtr);
    9331209            TclDecrRefCount(namePtr);
    9341210            ADJUST_PC(1);
     
    9521228                CACHE_STACK_INFO();
    9531229                if (valuePtr == NULL) {
     1230                    TRACE_WITH_OBJ(("%s %u \"%.30s\" => ERROR: ",
     1231                            opName[opCode], opnd, O2S(elemPtr)),
     1232                            Tcl_GetObjResult(interp));
    9541233                    Tcl_DecrRefCount(elemPtr);
    9551234                    result = TCL_ERROR;
     
    9571236                }
    9581237                PUSH_OBJECT(valuePtr);
     1238                TRACE_WITH_OBJ(("%s %u \"%.30s\" => ",
     1239                        opName[opCode], opnd, O2S(elemPtr)), valuePtr);
    9591240                TclDecrRefCount(elemPtr);
    9601241            }
     
    9711252                CACHE_STACK_INFO();
    9721253                if (valuePtr == NULL) {
     1254                    TRACE_WITH_OBJ(("loadArrayStk \"%.30s(%.30s)\" => ERROR: ",
     1255                            O2S(namePtr), O2S(elemPtr)),
     1256                            Tcl_GetObjResult(interp));
    9731257                    Tcl_DecrRefCount(namePtr);
    9741258                    Tcl_DecrRefCount(elemPtr);
     
    9771261                }
    9781262                PUSH_OBJECT(valuePtr);
     1263                TRACE_WITH_OBJ(("loadArrayStk \"%.30s(%.30s)\" => ",
     1264                        O2S(namePtr), O2S(elemPtr)), valuePtr);
    9791265                TclDecrRefCount(namePtr);
    9801266                TclDecrRefCount(elemPtr);
     
    9891275            CACHE_STACK_INFO();
    9901276            if (valuePtr == NULL) {
     1277                TRACE_WITH_OBJ(("loadStk \"%.30s\" => ERROR: ",
     1278                        O2S(namePtr)), Tcl_GetObjResult(interp));
    9911279                Tcl_DecrRefCount(namePtr);
    9921280                result = TCL_ERROR;
     
    9941282            }
    9951283            PUSH_OBJECT(valuePtr);
     1284            TRACE_WITH_OBJ(("loadStk \"%.30s\" => ", O2S(namePtr)),
     1285                    valuePtr);
    9961286            TclDecrRefCount(namePtr);
    9971287            ADJUST_PC(1);
     
    10131303            CACHE_STACK_INFO();
    10141304            if (value2Ptr == NULL) {
     1305                TRACE_WITH_OBJ(("%s %u <- \"%.30s\" => ERROR: ",
     1306                        opName[opCode], opnd, O2S(valuePtr)),
     1307                        Tcl_GetObjResult(interp));
    10151308                Tcl_DecrRefCount(valuePtr);
    10161309                result = TCL_ERROR;
     
    10181311            }
    10191312            PUSH_OBJECT(value2Ptr);
     1313            TRACE_WITH_OBJ(("%s %u <- \"%.30s\" => ",
     1314                    opName[opCode], opnd, O2S(valuePtr)), value2Ptr);
    10201315            TclDecrRefCount(valuePtr);
    10211316            ADJUST_PC(pcAdjustment);
     
    10291324            CACHE_STACK_INFO();
    10301325            if (value2Ptr == NULL) {
     1326                TRACE_WITH_OBJ(
     1327                        ("storeScalarStk \"%.30s\" <- \"%.30s\" => ERROR: ",
     1328                        O2S(namePtr), O2S(valuePtr)),
     1329                        Tcl_GetObjResult(interp));
    10311330                Tcl_DecrRefCount(namePtr);
    10321331                Tcl_DecrRefCount(valuePtr);
     
    10351334            }
    10361335            PUSH_OBJECT(value2Ptr);
     1336            TRACE_WITH_OBJ(
     1337                    ("storeScalarStk \"%.30s\" <- \"%.30s\" => ",
     1338                    O2S(namePtr),
     1339                    O2S(valuePtr)),
     1340                    value2Ptr);
    10371341            TclDecrRefCount(namePtr);
    10381342            TclDecrRefCount(valuePtr);
     
    10591363                CACHE_STACK_INFO();
    10601364                if (value2Ptr == NULL) {
     1365                    TRACE_WITH_OBJ(
     1366                            ("%s %u \"%.30s\" <- \"%.30s\" => ERROR: ",
     1367                            opName[opCode], opnd, O2S(elemPtr),
     1368                            O2S(valuePtr)), Tcl_GetObjResult(interp));
    10611369                    Tcl_DecrRefCount(elemPtr);
    10621370                    Tcl_DecrRefCount(valuePtr);
     
    10651373                }
    10661374                PUSH_OBJECT(value2Ptr);
     1375                TRACE_WITH_OBJ(("%s %u \"%.30s\" <- \"%.30s\" => ",
     1376                        opName[opCode], opnd, O2S(elemPtr), O2S(valuePtr)),
     1377                        value2Ptr);
    10671378                TclDecrRefCount(elemPtr);
    10681379                TclDecrRefCount(valuePtr);
     
    10821393                CACHE_STACK_INFO();
    10831394                if (value2Ptr == NULL) {
     1395                    TRACE_WITH_OBJ(("storeArrayStk \"%.30s(%.30s)\" <- \"%.30s\" => ERROR: ",
     1396                            O2S(namePtr), O2S(elemPtr), O2S(valuePtr)),
     1397                            Tcl_GetObjResult(interp));
    10841398                    Tcl_DecrRefCount(namePtr);
    10851399                    Tcl_DecrRefCount(elemPtr);
     
    10891403                }
    10901404                PUSH_OBJECT(value2Ptr);
     1405                TRACE_WITH_OBJ(("storeArrayStk \"%.30s(%.30s)\" <- \"%.30s\" => ",
     1406                        O2S(namePtr), O2S(elemPtr), O2S(valuePtr)),
     1407                        value2Ptr);
    10911408                TclDecrRefCount(namePtr);
    10921409                TclDecrRefCount(elemPtr);
     
    11031420            CACHE_STACK_INFO();
    11041421            if (value2Ptr == NULL) {
     1422                TRACE_WITH_OBJ(("storeStk \"%.30s\" <- \"%.30s\" => ERROR: ",
     1423                        O2S(namePtr), O2S(valuePtr)),
     1424                        Tcl_GetObjResult(interp));
    11051425                Tcl_DecrRefCount(namePtr);
    11061426                Tcl_DecrRefCount(valuePtr);
     
    11091429            }
    11101430            PUSH_OBJECT(value2Ptr);
     1431            TRACE_WITH_OBJ(("storeStk \"%.30s\" <- \"%.30s\" => ",
     1432                    O2S(namePtr), O2S(valuePtr)), value2Ptr);
    11111433            TclDecrRefCount(namePtr);
    11121434            TclDecrRefCount(valuePtr);
     
    11191441                result = tclIntType.setFromAnyProc(interp, valuePtr);
    11201442                if (result != TCL_OK) {
     1443                    TRACE_WITH_OBJ(("incrScalar1 %u (by %s) => ERROR converting increment amount to int: ",
     1444                            opnd, O2S(valuePtr)), Tcl_GetObjResult(interp));
    11211445                    Tcl_DecrRefCount(valuePtr);
    11221446                    goto checkForCatch;
     
    11281452            CACHE_STACK_INFO();
    11291453            if (value2Ptr == NULL) {
     1454                TRACE_WITH_OBJ(("incrScalar1 %u (by %ld) => ERROR: ",
     1455                        opnd, i), Tcl_GetObjResult(interp));
    11301456                Tcl_DecrRefCount(valuePtr);
    11311457                result = TCL_ERROR;
     
    11331459            }
    11341460            PUSH_OBJECT(value2Ptr);
     1461            TRACE_WITH_OBJ(("incrScalar1 %u (by %ld) => ", opnd, i),
     1462                    value2Ptr);
    11351463            TclDecrRefCount(valuePtr);
    11361464            ADJUST_PC(2);
     
    11431471                result = tclIntType.setFromAnyProc(interp, valuePtr);
    11441472                if (result != TCL_OK) {
     1473                    TRACE_WITH_OBJ(("%s \"%.30s\" (by %s) => ERROR converting increment amount to int: ",
     1474                            opName[opCode], O2S(namePtr), O2S(valuePtr)),
     1475                            Tcl_GetObjResult(interp));
    11451476                    Tcl_DecrRefCount(namePtr);
    11461477                    Tcl_DecrRefCount(valuePtr);
     
    11541485            CACHE_STACK_INFO();
    11551486            if (value2Ptr == NULL) {
     1487                TRACE_WITH_OBJ(("%s \"%.30s\" (by %ld) => ERROR: ",
     1488                        opName[opCode], O2S(namePtr), i),
     1489                        Tcl_GetObjResult(interp));
    11561490                Tcl_DecrRefCount(namePtr);
    11571491                Tcl_DecrRefCount(valuePtr);
     
    11601494            }
    11611495            PUSH_OBJECT(value2Ptr);
     1496            TRACE_WITH_OBJ(("%s \"%.30s\" (by %ld) => ",
     1497                    opName[opCode], O2S(namePtr), i), value2Ptr);
    11621498            Tcl_DecrRefCount(namePtr);
    11631499            Tcl_DecrRefCount(valuePtr);
     
    11741510                    result = tclIntType.setFromAnyProc(interp, valuePtr);
    11751511                    if (result != TCL_OK) {
     1512                        TRACE_WITH_OBJ(("incrArray1 %u \"%.30s\" (by %s) => ERROR converting increment amount to int: ",
     1513                                opnd, O2S(elemPtr), O2S(valuePtr)),
     1514                                Tcl_GetObjResult(interp));
    11761515                        Tcl_DecrRefCount(elemPtr);
    11771516                        Tcl_DecrRefCount(valuePtr);
     
    11851524                CACHE_STACK_INFO();
    11861525                if (value2Ptr == NULL) {
     1526                    TRACE_WITH_OBJ(("incrArray1 %u \"%.30s\" (by %ld) => ERROR: ",
     1527                            opnd, O2S(elemPtr), i),
     1528                            Tcl_GetObjResult(interp));
    11871529                    Tcl_DecrRefCount(elemPtr);
    11881530                    Tcl_DecrRefCount(valuePtr);
     
    11911533                }
    11921534                PUSH_OBJECT(value2Ptr);
     1535                TRACE_WITH_OBJ(("incrArray1 %u \"%.30s\" (by %ld) => ",
     1536                        opnd, O2S(elemPtr), i), value2Ptr);
    11931537                Tcl_DecrRefCount(elemPtr);
    11941538                Tcl_DecrRefCount(valuePtr);
     
    12061550                    result = tclIntType.setFromAnyProc(interp, valuePtr);
    12071551                    if (result != TCL_OK) {
     1552                        TRACE_WITH_OBJ(("incrArrayStk \"%.30s(%.30s)\" (by %s) => ERROR converting increment amount to int: ",
     1553                                O2S(namePtr), O2S(elemPtr), O2S(valuePtr)),
     1554                                Tcl_GetObjResult(interp));
    12081555                        Tcl_DecrRefCount(namePtr);
    12091556                        Tcl_DecrRefCount(elemPtr);
     
    12181565                CACHE_STACK_INFO();
    12191566                if (value2Ptr == NULL) {
     1567                    TRACE_WITH_OBJ(("incrArrayStk \"%.30s(%.30s)\" (by %ld) => ERROR: ",
     1568                            O2S(namePtr), O2S(elemPtr), i),
     1569                            Tcl_GetObjResult(interp));
    12201570                    Tcl_DecrRefCount(namePtr);
    12211571                    Tcl_DecrRefCount(elemPtr);
     
    12251575                }
    12261576                PUSH_OBJECT(value2Ptr);
     1577                TRACE_WITH_OBJ(("incrArrayStk \"%.30s(%.30s)\" (by %ld) => ",
     1578                        O2S(namePtr), O2S(elemPtr), i), value2Ptr);
    12271579                Tcl_DecrRefCount(namePtr);
    12281580                Tcl_DecrRefCount(elemPtr);
     
    12381590            CACHE_STACK_INFO();
    12391591            if (value2Ptr == NULL) {
     1592                TRACE_WITH_OBJ(("incrScalar1Imm %u %ld => ERROR: ",
     1593                        opnd, i), Tcl_GetObjResult(interp));
    12401594                result = TCL_ERROR;
    12411595                goto checkForCatch;
    12421596            }
    12431597            PUSH_OBJECT(value2Ptr);
     1598            TRACE_WITH_OBJ(("incrScalar1Imm %u %ld => ", opnd, i),
     1599                    value2Ptr);
    12441600            ADJUST_PC(3);
    12451601
     
    12531609            CACHE_STACK_INFO();
    12541610            if (value2Ptr == NULL) {
     1611                TRACE_WITH_OBJ(("%s \"%.30s\" %ld => ERROR: ",
     1612                        opName[opCode], O2S(namePtr), i),
     1613                        Tcl_GetObjResult(interp));
    12551614                result = TCL_ERROR;
    12561615                Tcl_DecrRefCount(namePtr);
     
    12581617            }
    12591618            PUSH_OBJECT(value2Ptr);
     1619            TRACE_WITH_OBJ(("%s \"%.30s\" %ld => ",
     1620                    opName[opCode], O2S(namePtr), i), value2Ptr);
    12601621            TclDecrRefCount(namePtr);
    12611622            ADJUST_PC(2);
     
    12731634                CACHE_STACK_INFO();
    12741635                if (value2Ptr == NULL) {
     1636                    TRACE_WITH_OBJ(("incrArray1Imm %u \"%.30s\" (by %ld) => ERROR: ",
     1637                            opnd, O2S(elemPtr), i),
     1638                            Tcl_GetObjResult(interp));
    12751639                    Tcl_DecrRefCount(elemPtr);
    12761640                    result = TCL_ERROR;
     
    12781642                }
    12791643                PUSH_OBJECT(value2Ptr);
     1644                TRACE_WITH_OBJ(("incrArray1Imm %u \"%.30s\" (by %ld) => ",
     1645                        opnd, O2S(elemPtr), i), value2Ptr);
    12801646                Tcl_DecrRefCount(elemPtr);
    12811647            }
     
    12941660                CACHE_STACK_INFO();
    12951661                if (value2Ptr == NULL) {
     1662                    TRACE_WITH_OBJ(("incrArrayStkImm \"%.30s(%.30s)\" (by %ld) => ERROR: ",
     1663                            O2S(namePtr), O2S(elemPtr), i),
     1664                            Tcl_GetObjResult(interp));
    12961665                    Tcl_DecrRefCount(namePtr);
    12971666                    Tcl_DecrRefCount(elemPtr);
     
    13001669                }
    13011670                PUSH_OBJECT(value2Ptr);
     1671                TRACE_WITH_OBJ(("incrArrayStkImm \"%.30s(%.30s)\" (by %ld) => ",
     1672                        O2S(namePtr), O2S(elemPtr), i), value2Ptr);
    13021673                Tcl_DecrRefCount(namePtr);
    13031674                Tcl_DecrRefCount(elemPtr);
     
    13071678        case INST_JUMP1:
    13081679            opnd = TclGetInt1AtPtr(pc+1);
     1680            TRACE(("jump1 %d => new pc %u\n", opnd,
     1681                   (unsigned int)(pc + opnd - codePtr->codeStart)));
    13091682            ADJUST_PC(opnd);
    13101683
    13111684        case INST_JUMP4:
    13121685            opnd = TclGetInt4AtPtr(pc+1);
     1686            TRACE(("jump4 %d => new pc %u\n", opnd,
     1687                   (unsigned int)(pc + opnd - codePtr->codeStart)));
    13131688            ADJUST_PC(opnd);
    13141689
     
    13341709                    result = Tcl_GetBooleanFromObj(interp, valuePtr, &b);
    13351710                    if (result != TCL_OK) {
     1711                        TRACE_WITH_OBJ(("%s %d => ERROR: ", opName[opCode],
     1712                                opnd), Tcl_GetObjResult(interp));
    13361713                        Tcl_DecrRefCount(valuePtr);
    13371714                        goto checkForCatch;
     
    13391716                }
    13401717                if (b) {
     1718                    TRACE(("%s %d => %.20s true, new pc %u\n",
     1719                            opName[opCode], opnd, O2S(valuePtr),
     1720                            (unsigned int)(pc+opnd - codePtr->codeStart)));
    13411721                    TclDecrRefCount(valuePtr);
    13421722                    ADJUST_PC(opnd);
    13431723                } else {
     1724                    TRACE(("%s %d => %.20s false\n", opName[opCode], opnd,
     1725                            O2S(valuePtr)));
    13441726                    TclDecrRefCount(valuePtr);
    13451727                    ADJUST_PC(pcAdjustment);
     
    13681750                    result = Tcl_GetBooleanFromObj(interp, valuePtr, &b);
    13691751                    if (result != TCL_OK) {
     1752                        TRACE_WITH_OBJ(("%s %d => ERROR: ", opName[opCode],
     1753                                opnd), Tcl_GetObjResult(interp));
    13701754                        Tcl_DecrRefCount(valuePtr);
    13711755                        goto checkForCatch;
     
    13731757                }
    13741758                if (b) {
     1759                    TRACE(("%s %d => %.20s true\n", opName[opCode], opnd,
     1760                            O2S(valuePtr)));
    13751761                    TclDecrRefCount(valuePtr);
    13761762                    ADJUST_PC(pcAdjustment);
    13771763                } else {
     1764                    TRACE(("%s %d => %.20s false, new pc %u\n",
     1765                            opName[opCode], opnd, O2S(valuePtr),
     1766                           (unsigned int)(pc + opnd - codePtr->codeStart)));
    13781767                    TclDecrRefCount(valuePtr);
    13791768                    ADJUST_PC(opnd);
     
    14151804                    }
    14161805                    if (result != TCL_OK) {
     1806                        TRACE(("%s \"%.20s\" => ILLEGAL TYPE %s \n",
     1807                                opName[opCode], O2S(valuePtr),
     1808                                (t1Ptr? t1Ptr->name : "null")));
    14171809                        IllegalExprOperandType(interp, opCode, valuePtr);
    14181810                        Tcl_DecrRefCount(valuePtr);
     
    14381830                    }
    14391831                    if (result != TCL_OK) {
     1832                        TRACE(("%s \"%.20s\" => ILLEGAL TYPE %s \n",
     1833                                opName[opCode], O2S(value2Ptr),
     1834                                (t2Ptr? t2Ptr->name : "null")));
    14401835                        IllegalExprOperandType(interp, opCode, value2Ptr);
    14411836                        Tcl_DecrRefCount(valuePtr);
     
    14561851                if (Tcl_IsShared(valuePtr)) {
    14571852                    PUSH_OBJECT(Tcl_NewLongObj(iResult));
     1853                    TRACE(("%s %.20s %.20s => %d\n", opName[opCode],
     1854                           O2S(valuePtr), O2S(value2Ptr), iResult));
    14581855                    TclDecrRefCount(valuePtr);
    14591856                } else {        /* reuse the valuePtr object */
     1857                    TRACE(("%s %.20s %.20s => %d\n",
     1858                           opName[opCode], /* NB: stack top is off by 1 */
     1859                           O2S(valuePtr), O2S(value2Ptr), iResult));
    14601860                    Tcl_SetLongObj(valuePtr, iResult);
    14611861                    ++stackTop; /* valuePtr now on stk top has right r.c. */
     
    16132013                if (Tcl_IsShared(valuePtr)) {
    16142014                    PUSH_OBJECT(Tcl_NewLongObj(iResult));
     2015                    TRACE(("%s %.20s %.20s => %ld\n", opName[opCode],
     2016                        O2S(valuePtr), O2S(value2Ptr), iResult));
    16152017                    TclDecrRefCount(valuePtr);
    16162018                } else {        /* reuse the valuePtr object */
     2019                    TRACE(("%s %.20s %.20s => %ld\n",
     2020                        opName[opCode], /* NB: stack top is off by 1 */
     2021                        O2S(valuePtr), O2S(value2Ptr), iResult));
    16172022                    Tcl_SetLongObj(valuePtr, iResult);
    16182023                    ++stackTop; /* valuePtr now on stk top has right r.c. */
     
    16442049                            valuePtr, &i);
    16452050                    if (result != TCL_OK) {
     2051                        TRACE(("%s %.20s %.20s => ILLEGAL 1st TYPE %s\n",
     2052                              opName[opCode], O2S(valuePtr), O2S(value2Ptr),
     2053                              (valuePtr->typePtr?
     2054                                   valuePtr->typePtr->name : "null")));
    16462055                        IllegalExprOperandType(interp, opCode, valuePtr);
    16472056                        Tcl_DecrRefCount(valuePtr);
     
    16562065                            value2Ptr, &i2);
    16572066                    if (result != TCL_OK) {
     2067                        TRACE(("%s %.20s %.20s => ILLEGAL 2nd TYPE %s\n",
     2068                              opName[opCode], O2S(valuePtr), O2S(value2Ptr),
     2069                              (value2Ptr->typePtr?
     2070                                   value2Ptr->typePtr->name : "null")));
    16582071                        IllegalExprOperandType(interp, opCode, value2Ptr);
    16592072                        Tcl_DecrRefCount(valuePtr);
     
    16722085                     */
    16732086                    if (i2 == 0) {
     2087                        TRACE(("mod %ld %ld => DIVIDE BY ZERO\n", i, i2));
    16742088                        Tcl_DecrRefCount(valuePtr);
    16752089                        Tcl_DecrRefCount(value2Ptr);
     
    17232137                if (Tcl_IsShared(valuePtr)) {
    17242138                    PUSH_OBJECT(Tcl_NewLongObj(iResult));
     2139                    TRACE(("%s %ld %ld => %ld\n", opName[opCode], i, i2,
     2140                           iResult));
    17252141                    TclDecrRefCount(valuePtr);
    17262142                } else {        /* reuse the valuePtr object */
     2143                    TRACE(("%s %ld %ld => %ld\n", opName[opCode], i, i2,
     2144                        iResult)); /* NB: stack top is off by 1 */
    17272145                    Tcl_SetLongObj(valuePtr, iResult);
    17282146                    ++stackTop; /* valuePtr now on stk top has right r.c. */
     
    17682186                    }
    17692187                    if (result != TCL_OK) {
     2188                        TRACE(("%s %.20s %.20s => ILLEGAL 1st TYPE %s\n",
     2189                               opName[opCode], s, O2S(value2Ptr),
     2190                               (valuePtr->typePtr?
     2191                                    valuePtr->typePtr->name : "null")));
    17702192                        IllegalExprOperandType(interp, opCode, valuePtr);
    17712193                        Tcl_DecrRefCount(valuePtr);
     
    17902212                    }
    17912213                    if (result != TCL_OK) {
     2214                        TRACE(("%s %.20s %.20s => ILLEGAL 2nd TYPE %s\n",
     2215                               opName[opCode], O2S(valuePtr), s,
     2216                               (value2Ptr->typePtr?
     2217                                    value2Ptr->typePtr->name : "null")));
    17922218                        IllegalExprOperandType(interp, opCode, value2Ptr);
    17932219                        Tcl_DecrRefCount(valuePtr);
     
    18202246                    case INST_DIV:
    18212247                        if (d2 == 0.0) {
     2248                            TRACE(("div %.6g %.6g => DIVIDE BY ZERO\n",
     2249                                   d1, d2));
    18222250                            Tcl_DecrRefCount(valuePtr);
    18232251                            Tcl_DecrRefCount(value2Ptr);
     
    18332261                   
    18342262                    if (IS_NAN(dResult) || IS_INF(dResult)) {
     2263                        TRACE(("%s %.20s %.20s => IEEE FLOATING PT ERROR\n",
     2264                               opName[opCode], O2S(valuePtr), O2S(value2Ptr)));
    18352265                        TclExprFloatError(interp, dResult);
    18362266                        result = TCL_ERROR;
     
    18612291                         */
    18622292                        if (i2 == 0) {
     2293                            TRACE(("div %ld %ld => DIVIDE BY ZERO\n",
     2294                                    i, i2));
    18632295                            Tcl_DecrRefCount(valuePtr);
    18642296                            Tcl_DecrRefCount(value2Ptr);
     
    18862318                    if (doDouble) {
    18872319                        PUSH_OBJECT(Tcl_NewDoubleObj(dResult));
     2320                        TRACE(("%s %.6g %.6g => %.6g\n", opName[opCode],
     2321                               d1, d2, dResult));
    18882322                    } else {
    18892323                        PUSH_OBJECT(Tcl_NewLongObj(iResult));
     2324                        TRACE(("%s %ld %ld => %ld\n", opName[opCode],
     2325                               i, i2, iResult));
    18902326                    }
    18912327                    TclDecrRefCount(valuePtr);
    18922328                } else {            /* reuse the valuePtr object */
    18932329                    if (doDouble) { /* NB: stack top is off by 1 */
     2330                        TRACE(("%s %.6g %.6g => %.6g\n", opName[opCode],
     2331                               d1, d2, dResult));
    18942332                        Tcl_SetDoubleObj(valuePtr, dResult);
    18952333                    } else {
     2334                        TRACE(("%s %ld %ld => %ld\n", opName[opCode],
     2335                               i, i2, iResult));
    18962336                        Tcl_SetLongObj(valuePtr, iResult);
    18972337                    }
     
    19232363                    }
    19242364                    if (result != TCL_OK) {
     2365                        TRACE(("%s \"%.20s\" => ILLEGAL TYPE %s \n",
     2366                                opName[opCode], s,
     2367                                (tPtr? tPtr->name : "null")));
    19252368                        IllegalExprOperandType(interp, opCode, valuePtr);
    19262369                        goto checkForCatch;
    19272370                    }
    19282371                }
     2372                TRACE_WITH_OBJ(("uplus %s => ", O2S(valuePtr)), valuePtr);
    19292373            }
    19302374            ADJUST_PC(1);
     
    19552399                    }
    19562400                    if (result != TCL_OK) {
     2401                        TRACE(("%s \"%.20s\" => ILLEGAL TYPE %s\n",
     2402                                opName[opCode], s,
     2403                               (tPtr? tPtr->name : "null")));
    19572404                        IllegalExprOperandType(interp, opCode, valuePtr);
    19582405                        Tcl_DecrRefCount(valuePtr);
     
    19702417                        objPtr = Tcl_NewLongObj(
    19712418                                (opCode == INST_UMINUS)? -i : !i);
     2419                        TRACE_WITH_OBJ(("%s %ld => ", opName[opCode], i),
     2420                                objPtr); /* NB: stack top is off by 1 */
    19722421                    } else {
    19732422                        d = valuePtr->internalRep.doubleValue;
     
    19812430                            objPtr = Tcl_NewLongObj((d==0.0)? 1 : 0);
    19822431                        }
     2432                        TRACE_WITH_OBJ(("%s %.6g => ", opName[opCode], d),
     2433                                objPtr); /* NB: stack top is off by 1 */
    19832434                    }
    19842435                    PUSH_OBJECT(objPtr);
     
    19922443                        Tcl_SetLongObj(valuePtr,
    19932444                                (opCode == INST_UMINUS)? -i : !i);
     2445                        TRACE_WITH_OBJ(("%s %ld => ", opName[opCode], i),
     2446                                valuePtr); /* NB: stack top is off by 1 */
    19942447                    } else {
    19952448                        d = valuePtr->internalRep.doubleValue;
     
    20032456                            Tcl_SetLongObj(valuePtr, (d==0.0)? 1 : 0);
    20042457                        }
     2458                        TRACE_WITH_OBJ(("%s %.6g => ", opName[opCode], d),
     2459                                valuePtr); /* NB: stack top is off by 1 */
    20052460                    }
    20062461                    ++stackTop; /* valuePtr now on stk top has right r.c. */
     
    20262481                            valuePtr, &i);
    20272482                    if (result != TCL_OK) {   /* try to convert to double */
     2483                        TRACE(("bitnot \"%.20s\" => ILLEGAL TYPE %s\n",
     2484                               O2S(valuePtr), (tPtr? tPtr->name : "null")));
    20282485                        IllegalExprOperandType(interp, opCode, valuePtr);
    20292486                        Tcl_DecrRefCount(valuePtr);
     
    20352492                if (Tcl_IsShared(valuePtr)) {
    20362493                    PUSH_OBJECT(Tcl_NewLongObj(~i));
     2494                    TRACE(("bitnot 0x%lx => (%lu)\n", i, ~i));
    20372495                    TclDecrRefCount(valuePtr);
    20382496                } else {
     
    20422500                    Tcl_SetLongObj(valuePtr, ~i);
    20432501                    ++stackTop; /* valuePtr now on stk top has right r.c. */
     2502                    TRACE(("bitnot 0x%lx => (%lu)\n", i, ~i));
    20442503                }
    20452504            }
     
    20562515
    20572516                if ((opnd < 0) || (opnd > LAST_BUILTIN_FUNC)) {
     2517                    TRACE(("UNRECOGNIZED BUILTIN FUNC CODE %d\n", opnd));
    20582518                    panic("TclExecuteByteCode: unrecognized builtin function code %d", opnd);
    20592519                }
     
    20682528                    goto checkForCatch;
    20692529                }
     2530                TRACE_WITH_OBJ(("callBuiltinFunc1 %d => ", opnd),
     2531                        stackPtr[stackTop].o);
    20702532            }
    20712533            ADJUST_PC(2);
     
    20932555                    goto checkForCatch;
    20942556                }
     2557                TRACE_WITH_OBJ(("callFunc1 %d => ", objc),
     2558                        stackPtr[stackTop].o);
    20952559                ADJUST_PC(2);
    20962560            }
     
    21632627                        d = valuePtr->internalRep.doubleValue;
    21642628                        if (IS_NAN(d) || IS_INF(d)) {
     2629                            TRACE(("tryCvtToNumeric \"%.20s\" => IEEE FLOATING PT ERROR\n",
     2630                                   O2S(valuePtr)));
    21652631                            TclExprFloatError(interp, d);
    21662632                            result = TCL_ERROR;
     
    21702636                    shared = shared;            /* lint, shared not used. */
    21712637                    converted = converted;      /* lint, converted not used. */
     2638                    TRACE(("tryCvtToNumeric \"%.20s\" => numeric, %s, %s\n",
     2639                           O2S(valuePtr),
     2640                           (converted? "converted" : "not converted"),
     2641                           (shared? "shared" : "not shared")));
     2642                } else {
     2643                    TRACE(("tryCvtToNumeric \"%.20s\" => not numeric\n",
     2644                           O2S(valuePtr)));
    21722645                }
    21732646            }
     
    21872660                    codePtr);
    21882661            if (rangePtr == NULL) {
     2662                TRACE(("break => no encl. loop or catch, returning TCL_BREAK\n"));
    21892663                result = TCL_BREAK;
    21902664                goto abnormalReturn; /* no catch exists to check */
     
    21932667            case LOOP_EXCEPTION_RANGE:
    21942668                result = TCL_OK;
     2669                TRACE(("break => range at %d, new pc %d\n",
     2670                       rangePtr->codeOffset, rangePtr->breakOffset));
    21952671                break;
    21962672            case CATCH_EXCEPTION_RANGE:
    21972673                result = TCL_BREAK;
     2674                TRACE(("break => ...\n"));
    21982675                goto processCatch; /* it will use rangePtr */
    21992676            default:
     
    22162693                    codePtr);
    22172694            if (rangePtr == NULL) {
     2695                TRACE(("continue => no encl. loop or catch, returning TCL_CONTINUE\n"));
    22182696                result = TCL_CONTINUE;
    22192697                goto abnormalReturn;
     
    22222700            case LOOP_EXCEPTION_RANGE:
    22232701                if (rangePtr->continueOffset == -1) {
     2702                    TRACE(("continue => loop w/o continue, checking for catch\n"));
    22242703                    goto checkForCatch;
    22252704                } else {
    22262705                    result = TCL_OK;
     2706                    TRACE(("continue => range at %d, new pc %d\n",
     2707                           rangePtr->codeOffset, rangePtr->continueOffset));
    22272708                }
    22282709                break;
    22292710            case CATCH_EXCEPTION_RANGE:
    22302711                result = TCL_CONTINUE;
     2712                TRACE(("continue => ...\n"));
    22312713                goto processCatch; /* it will use rangePtr */
    22322714            default:
     
    22622744                TclSetVarScalar(iterVarPtr);
    22632745                TclClearVarUndefined(iterVarPtr);
     2746                TRACE(("foreach_start4 %u => loop iter count temp %d\n",
     2747                        opnd, iterTmpIndex));
    22642748            }
    22652749            ADJUST_PC(5);
     
    23102794                    result = Tcl_ListObjLength(interp, listPtr, &listLen);
    23112795                    if (result != TCL_OK) {
     2796                        TRACE_WITH_OBJ(("foreach_step4 %u => ERROR converting list %ld, \"%s\": ",
     2797                                opnd, i, O2S(listPtr)),
     2798                                Tcl_GetObjResult(interp));
    23122799                        goto checkForCatch;
    23132800                    }
     
    23532840                            CACHE_STACK_INFO();
    23542841                            if (value2Ptr == NULL) {
     2842                                TRACE_WITH_OBJ(("foreach_step4 %u => ERROR init. index temp %d: ",
     2843                                       opnd, varIndex),
     2844                                       Tcl_GetObjResult(interp));
    23552845                                if (setEmptyStr) {
    23562846                                    Tcl_DecrRefCount(elemPtr); /* unneeded */
     
    23722862
    23732863                PUSH_OBJECT(Tcl_NewLongObj(continueLoop));
     2864                TRACE(("foreach_step4 %u => %d lists, iter %d, %s loop\n",
     2865                        opnd, numLists, iterNum,
     2866                        (continueLoop? "continue" : "exit")));
    23742867            }
    23752868            ADJUST_PC(5);
     
    23822875             */
    23832876            catchStackPtr[++catchTop] = stackTop;
     2877            TRACE(("beginCatch4 %u => catchTop=%d, stackTop=%d\n",
     2878                    TclGetUInt4AtPtr(pc+1), catchTop, stackTop));
    23842879            ADJUST_PC(5);
    23852880
     
    23872882            catchTop--;
    23882883            result = TCL_OK;
     2884            TRACE(("endCatch => catchTop=%d\n", catchTop));
    23892885            ADJUST_PC(1);
    23902886
    23912887        case INST_PUSH_RESULT:
    23922888            PUSH_OBJECT(Tcl_GetObjResult(interp));
     2889            TRACE_WITH_OBJ(("pushResult => "), Tcl_GetObjResult(interp));
    23932890            ADJUST_PC(1);
    23942891
    23952892        case INST_PUSH_RETURN_CODE:
    23962893            PUSH_OBJECT(Tcl_NewLongObj(result));
     2894            TRACE(("pushReturnCode => %u\n", result));
    23972895            ADJUST_PC(1);
    23982896
    23992897        default:
     2898            TRACE(("UNRECOGNIZED INSTRUCTION %u\n", opCode));
    24002899            panic("TclExecuteByteCode: unrecognized opCode %u", opCode);
    24012900        } /* end of switch on opCode */
     
    24272926        rangePtr = TclGetExceptionRangeForPc(pc, /*catchOnly*/ 1, codePtr);
    24282927        if (rangePtr == NULL) {
     2928            TRACE(("   ... no enclosing catch, returning %s\n",
     2929                    StringForResultCode(result)));
    24292930            goto abnormalReturn;
    24302931        }
     
    24442945            TclDecrRefCount(valuePtr);
    24452946        }
     2947        TRACE(("  ... found catch at %d, catchTop=%d, unwound to %d, new pc %u\n",
     2948                rangePtr->codeOffset, catchTop, catchStackPtr[catchTop],
     2949                (unsigned int)(rangePtr->catchOffset)));
    24462950        pc = (codePtr->codeStart + rangePtr->catchOffset);
    24472951        continue;               /* restart the execution loop at pc */
     
    24712975#undef STATIC_CATCH_STACK_SIZE
    24722976}
     2977
     2978
     2979/*
     2980 *----------------------------------------------------------------------
     2981 *
     2982 * PrintByteCodeInfo --
     2983 *
     2984 *      This procedure prints a summary about a bytecode object to stdout.
     2985 *      It is called by TclExecuteByteCode when starting to execute the
     2986 *      bytecode object if tclTraceExec has the value 2 or more.
     2987 *
     2988 * Results:
     2989 *      None.
     2990 *
     2991 * Side effects:
     2992 *      None.
     2993 *
     2994 *----------------------------------------------------------------------
     2995 */
     2996
     2997static void
     2998PrintByteCodeInfo(codePtr)
     2999    register ByteCode *codePtr; /* The bytecode whose summary is printed
     3000                                 * to stdout. */
     3001{
     3002    Proc *procPtr = codePtr->procPtr;
     3003    int numCmds = codePtr->numCommands;
     3004    int numObjs = codePtr->numObjects;
     3005    int objBytes, i;
     3006
     3007    objBytes = (numObjs * sizeof(Tcl_Obj));
     3008    for (i = 0;  i < numObjs;  i++) {
     3009        Tcl_Obj *litObjPtr = codePtr->objArrayPtr[i];
     3010        if (litObjPtr->bytes != NULL) {
     3011            objBytes += litObjPtr->length;
     3012        }
     3013    }
     3014   
     3015    fprintf(stdout, "\nExecuting ByteCode 0x%x, ref ct %u, epoch %u, interp 0x%x(epoch %u)\n",
     3016            (unsigned int) codePtr, codePtr->refCount,
     3017            codePtr->compileEpoch, (unsigned int) codePtr->iPtr,
     3018            codePtr->iPtr->compileEpoch);
     3019   
     3020    fprintf(stdout, "  Source: ");
     3021    TclPrintSource(stdout, codePtr->source, 70);
     3022
     3023    fprintf(stdout, "\n  Cmds %d, chars %d, inst %u, objs %u, aux %d, stk depth %u, code/src %.2fn",
     3024            numCmds, codePtr->numSrcChars, codePtr->numCodeBytes, numObjs,
     3025            codePtr->numAuxDataItems, codePtr->maxStackDepth,
     3026            (codePtr->numSrcChars?
     3027                    ((float)codePtr->totalSize)/((float)codePtr->numSrcChars) : 0.0));
     3028
     3029    fprintf(stdout, "  Code %zu = %u(header)+%d(inst)+%d(objs)+%u(exc)+%u(aux)+%d(cmd map)\n",
     3030            codePtr->totalSize, sizeof(ByteCode), codePtr->numCodeBytes,
     3031            objBytes, (codePtr->numExcRanges * sizeof(ExceptionRange)),
     3032            (codePtr->numAuxDataItems * sizeof(AuxData)),
     3033            codePtr->numCmdLocBytes);
     3034
     3035    if (procPtr != NULL) {
     3036        fprintf(stdout,
     3037                "  Proc 0x%x, ref ct %d, args %d, compiled locals %d\n",
     3038                (unsigned int) procPtr, procPtr->refCount,
     3039                procPtr->numArgs, procPtr->numCompiledLocals);
     3040    }
     3041}
     3042
     3043
     3044/*
     3045 *----------------------------------------------------------------------
     3046 *
     3047 * ValidatePcAndStackTop --
     3048 *
     3049 *      This procedure is called by TclExecuteByteCode when debugging to
     3050 *      verify that the program counter and stack top are valid during
     3051 *      execution.
     3052 *
     3053 * Results:
     3054 *      None.
     3055 *
     3056 * Side effects:
     3057 *      Prints a message to stderr and panics if either the pc or stack
     3058 *      top are invalid.
     3059 *
     3060 *----------------------------------------------------------------------
     3061 */
     3062
     3063#ifdef TCL_COMPILE_DEBUG
     3064static void
     3065ValidatePcAndStackTop(codePtr, pc, stackTop, stackLowerBound, stackUpperBound)
     3066    register ByteCode *codePtr; /* The bytecode whose summary is printed
     3067                                 * to stdout. */
     3068    unsigned char *pc;          /* Points to first byte of a bytecode
     3069                                 * instruction. The program counter. */
     3070    int stackTop;               /* Current stack top. Must be between
     3071                                 * stackLowerBound and stackUpperBound
     3072                                 * (inclusive). */
     3073    int stackLowerBound;        /* Smallest legal value for stackTop. */
     3074    int stackUpperBound;        /* Greatest legal value for stackTop. */
     3075{
     3076    unsigned int relativePc = (unsigned int) (pc - codePtr->codeStart);
     3077    unsigned int codeStart = (unsigned int) codePtr->codeStart;
     3078    unsigned int codeEnd = (unsigned int)
     3079            (codePtr->codeStart + codePtr->numCodeBytes);
     3080    unsigned char opCode = *pc;
     3081
     3082    if (((unsigned int) pc < codeStart) || ((unsigned int) pc > codeEnd)) {
     3083        fprintf(stderr, "\nBad instruction pc 0x%x in TclExecuteByteCode\n",
     3084                (unsigned int) pc);
     3085        panic("TclExecuteByteCode execution failure: bad pc");
     3086    }
     3087    if ((unsigned int) opCode > LAST_INST_OPCODE) {
     3088        fprintf(stderr, "\nBad opcode %d at pc %u in TclExecuteByteCode\n",
     3089                (unsigned int) opCode, relativePc);
     3090        panic("TclExecuteByteCode execution failure: bad opcode");
     3091    }
     3092    if ((stackTop < stackLowerBound) || (stackTop > stackUpperBound)) {
     3093        int numChars;
     3094        char *cmd = GetSrcInfoForPc(pc, codePtr, &numChars);
     3095        char *ellipsis = "";
     3096       
     3097        fprintf(stderr, "\nBad stack top %d at pc %u in TclExecuteByteCode",
     3098                stackTop, relativePc);
     3099        if (cmd != NULL) {
     3100            if (numChars > 100) {
     3101                numChars = 100;
     3102                ellipsis = "...";
     3103            }
     3104            fprintf(stderr, "\n executing %.*s%s\n", numChars, cmd,
     3105                    ellipsis);
     3106        } else {
     3107            fprintf(stderr, "\n");
     3108        }
     3109        panic("TclExecuteByteCode execution failure: bad stack top");
     3110    }
     3111}
     3112#endif /* TCL_COMPILE_DEBUG */
    24733113
    24743114
     
    36314271
    36324272
     4273#ifdef TCL_COMPILE_STATS
     4274/*
     4275 *----------------------------------------------------------------------
     4276 *
     4277 * TclLog2 --
     4278 *
     4279 *      Procedure used while collecting compilation statistics to determine
     4280 *      the log base 2 of an integer.
     4281 *
     4282 * Results:
     4283 *      Returns the log base 2 of the operand. If the argument is less
     4284 *      than or equal to zero, a zero is returned.
     4285 *
     4286 * Side effects:
     4287 *      None.
     4288 *
     4289 *----------------------------------------------------------------------
     4290 */
     4291
     4292int
     4293TclLog2(value)
     4294    register int value;         /* The integer for which to compute the
     4295                                 * log base 2. */
     4296{
     4297    register int n = value;
     4298    register int result = 0;
     4299
     4300    while (n > 1) {
     4301        n = n >> 1;
     4302        result++;
     4303    }
     4304    return result;
     4305}
     4306
     4307
     4308/*
     4309 *----------------------------------------------------------------------
     4310 *
     4311 * EvalStatsCmd --
     4312 *
     4313 *      Implements the "evalstats" command that prints instruction execution
     4314 *      counts to stdout.
     4315 *
     4316 * Results:
     4317 *      Standard Tcl results.
     4318 *
     4319 * Side effects:
     4320 *      None.
     4321 *
     4322 *----------------------------------------------------------------------
     4323 */
     4324
     4325static int
     4326EvalStatsCmd(unused, interp, argc, argv)
     4327    ClientData unused;          /* Unused. */
     4328    Tcl_Interp *interp;         /* The current interpreter. */
     4329    int argc;                   /* The number of arguments. */
     4330    char **argv;                /* The argument strings. */
     4331{
     4332    register double total = 0.0;
     4333    register int i;
     4334    int maxSizeDecade = 0;
     4335    double totalHeaderBytes = (tclNumCompilations * sizeof(ByteCode));
     4336
     4337    for (i = 0;  i < 256;  i++) {
     4338        if (instructionCount[i] != 0) {
     4339            total += instructionCount[i];
     4340        }
     4341    }
     4342
     4343    for (i = 31;  i >= 0;  i--) {
     4344        if ((tclSourceCount[i] > 0) && (tclByteCodeCount[i] > 0)) {
     4345            maxSizeDecade = i;
     4346            break;
     4347        }
     4348    }
     4349
     4350    fprintf(stdout, "\nNumber of compilations           %ld\n",
     4351            tclNumCompilations);
     4352    fprintf(stdout, "Number of executions               %ld\n",
     4353            numExecutions);
     4354    fprintf(stdout, "Average executions/compilation     %.0f\n",
     4355            ((float) numExecutions/tclNumCompilations));
     4356   
     4357    fprintf(stdout, "\nInstructions executed            %.0f\n",
     4358            total);
     4359    fprintf(stdout, "Average instructions/compile       %.0f\n",
     4360            total/tclNumCompilations);
     4361    fprintf(stdout, "Average instructions/execution     %.0f\n",
     4362            total/numExecutions);
     4363   
     4364    fprintf(stdout, "\nTotal source bytes               %.6g\n",
     4365            tclTotalSourceBytes);
     4366    fprintf(stdout, "Total code bytes           %.6g\n",
     4367            tclTotalCodeBytes);
     4368    fprintf(stdout, "Average code/compilation   %.0f\n",
     4369            tclTotalCodeBytes/tclNumCompilations);
     4370    fprintf(stdout, "Average code/source                %.2f\n",
     4371            tclTotalCodeBytes/tclTotalSourceBytes);
     4372    fprintf(stdout, "Current source bytes               %.6g\n",
     4373            tclCurrentSourceBytes);
     4374    fprintf(stdout, "Current code bytes         %.6g\n",
     4375            tclCurrentCodeBytes);
     4376    fprintf(stdout, "Current code/source                %.2f\n",
     4377            tclCurrentCodeBytes/tclCurrentSourceBytes);
     4378   
     4379    fprintf(stdout, "\nTotal objects allocated          %ld\n",
     4380            tclObjsAlloced);
     4381    fprintf(stdout, "Total objects freed                %ld\n",
     4382            tclObjsFreed);
     4383    fprintf(stdout, "Current objects:           %ld\n",
     4384            (tclObjsAlloced - tclObjsFreed));
     4385
     4386    fprintf(stdout, "\nBreakdown of code byte requirements:\n");
     4387    fprintf(stdout, "                   Total bytes      Pct of    Avg per\n");
     4388    fprintf(stdout, "                                  all code    compile\n");
     4389    fprintf(stdout, "Total code        %12.6g        100%%   %8.2f\n",
     4390            tclTotalCodeBytes, tclTotalCodeBytes/tclNumCompilations);
     4391    fprintf(stdout, "Header            %12.6g   %8.2f%%   %8.2f\n",
     4392            totalHeaderBytes,
     4393            ((totalHeaderBytes * 100.0) / tclTotalCodeBytes),
     4394            totalHeaderBytes/tclNumCompilations);
     4395    fprintf(stdout, "Instructions      %12.6g   %8.2f%%   %8.2f\n",
     4396            tclTotalInstBytes,
     4397            ((tclTotalInstBytes * 100.0) / tclTotalCodeBytes),
     4398            tclTotalInstBytes/tclNumCompilations);
     4399    fprintf(stdout, "Objects           %12.6g   %8.2f%%   %8.2f\n",
     4400            tclTotalObjBytes,
     4401            ((tclTotalObjBytes * 100.0) / tclTotalCodeBytes),
     4402            tclTotalObjBytes/tclNumCompilations);
     4403    fprintf(stdout, "Exception table   %12.6g   %8.2f%%   %8.2f\n",
     4404            tclTotalExceptBytes,
     4405            ((tclTotalExceptBytes * 100.0) / tclTotalCodeBytes),
     4406            tclTotalExceptBytes/tclNumCompilations);
     4407    fprintf(stdout, "Auxiliary data    %12.6g   %8.2f%%   %8.2f\n",
     4408            tclTotalAuxBytes,
     4409            ((tclTotalAuxBytes * 100.0) / tclTotalCodeBytes),
     4410            tclTotalAuxBytes/tclNumCompilations);
     4411    fprintf(stdout, "Command map       %12.6g   %8.2f%%   %8.2f\n",
     4412            tclTotalCmdMapBytes,
     4413            ((tclTotalCmdMapBytes * 100.0) / tclTotalCodeBytes),
     4414            tclTotalCmdMapBytes/tclNumCompilations);
     4415   
     4416    fprintf(stdout, "\nSource and ByteCode size distributions:\n");
     4417    fprintf(stdout, "    binary decade          source    code\n");
     4418    for (i = 0;  i <= maxSizeDecade;  i++) {
     4419        int decadeLow, decadeHigh;
     4420
     4421        if (i == 0) {
     4422            decadeLow = 0;
     4423        } else {
     4424            decadeLow = 1 << i;
     4425        }
     4426        decadeHigh = (1 << (i+1)) - 1;
     4427        fprintf(stdout, "       %6d -%6d                %6d     %6d\n",
     4428                decadeLow, decadeHigh,
     4429                tclSourceCount[i], tclByteCodeCount[i]);
     4430    }
     4431
     4432    fprintf(stdout, "\nInstruction counts:\n");
     4433    for (i = 0;  i < 256;  i++) {
     4434        if (instructionCount[i]) {
     4435            fprintf(stdout, "%20s %8d %6.2f%%\n",
     4436                    opName[i], instructionCount[i],
     4437                    (instructionCount[i] * 100.0)/total);
     4438        }
     4439    }
     4440
     4441#ifdef TCL_MEM_DEBUG
     4442    fprintf(stdout, "\nHeap Statistics:\n");
     4443    TclDumpMemoryInfo(stdout);
     4444#endif /* TCL_MEM_DEBUG */
     4445
     4446    return TCL_OK;
     4447}
     4448#endif /* TCL_COMPILE_STATS */
     4449
     4450
    36334451/*
    36344452 *----------------------------------------------------------------------
     
    39404758    panic("UpdateStringOfCmdName should never be invoked");
    39414759}
     4760
     4761
     4762#ifdef TCL_COMPILE_DEBUG
     4763/*
     4764 *----------------------------------------------------------------------
     4765 *
     4766 * StringForResultCode --
     4767 *
     4768 *      Procedure that returns a human-readable string representing a
     4769 *      Tcl result code such as TCL_ERROR.
     4770 *
     4771 * Results:
     4772 *      If the result code is one of the standard Tcl return codes, the
     4773 *      result is a string representing that code such as "TCL_ERROR".
     4774 *      Otherwise, the result string is that code formatted as a
     4775 *      sequence of decimal digit characters. Note that the resulting
     4776 *      string must not be modified by the caller.
     4777 *
     4778 * Side effects:
     4779 *      None.
     4780 *
     4781 *----------------------------------------------------------------------
     4782 */
     4783
     4784static char *
     4785StringForResultCode(result)
     4786    int result;                 /* The Tcl result code for which to
     4787                                 * generate a string. */
     4788{
     4789    static char buf[20];
     4790   
     4791    if ((result >= TCL_OK) && (result <= TCL_CONTINUE)) {
     4792        return resultStrings[result];
     4793    }
     4794    TclFormatInt(buf, result);
     4795    return buf;
     4796}
     4797#endif /* TCL_COMPILE_DEBUG */
  • external/tcl/tclInt.h

    r83ee320 r2d7ff18  
    13261326
    13271327extern Tcl_Obj *        tclFreeObjList;
     1328
     1329#ifdef TCL_COMPILE_STATS
     1330extern long             tclObjsAlloced;
     1331extern long             tclObjsFreed;
     1332#endif /* TCL_COMPILE_STATS */
    13281333
    13291334/*
     
    14401445                            int objc, Tcl_Obj *CONST objv[], int flags));
    14411446EXTERN char *           TclpAlloc _ANSI_ARGS_((unsigned int size));
    1442 EXTERN void             TclpFree(char *cp);
     1447
    14431448EXTERN char *           TclpRealloc _ANSI_ARGS_((char *ptr,
    14441449                            unsigned int size));
     
    14671472EXTERN int              TclPreventAliasLoop _ANSI_ARGS_((Tcl_Interp *interp,
    14681473                            Tcl_Interp *cmdInterp, Tcl_Command cmd));
     1474EXTERN void             TclPrintByteCodeObj _ANSI_ARGS_((Tcl_Interp *interp,
     1475                            Tcl_Obj *objPtr));
    14691476EXTERN void             TclProcCleanupProc _ANSI_ARGS_((Proc *procPtr));
    14701477EXTERN int              TclProcCompileProc _ANSI_ARGS_((Tcl_Interp *interp,
     
    16811688 */
    16821689
     1690#ifdef TCL_COMPILE_STATS
     1691#  define TclIncrObjsAllocated() \
     1692    tclObjsAlloced++
     1693#  define TclIncrObjsFreed() \
     1694    tclObjsFreed++
     1695#else
     1696#  define TclIncrObjsAllocated()
     1697#  define TclIncrObjsFreed()
     1698#endif /* TCL_COMPILE_STATS */
     1699
     1700#ifdef TCL_MEM_DEBUG
     1701#  define TclNewObj(objPtr) \
     1702    (objPtr) = (Tcl_Obj *) Tcl_DbCkalloc(sizeof(Tcl_Obj), __FILE__, __LINE__); \
     1703    (objPtr)->refCount = 0; \
     1704    (objPtr)->bytes    = tclEmptyStringRep; \
     1705    (objPtr)->length   = 0; \
     1706    (objPtr)->typePtr  = NULL; \
     1707    TclIncrObjsAllocated()
     1708#  define TclDbNewObj(objPtr, file, line) \
     1709    (objPtr) = (Tcl_Obj *) Tcl_DbCkalloc(sizeof(Tcl_Obj), (file), (line)); \
     1710    (objPtr)->refCount = 0; \
     1711    (objPtr)->bytes    = tclEmptyStringRep; \
     1712    (objPtr)->length   = 0; \
     1713    (objPtr)->typePtr  = NULL; \
     1714    TclIncrObjsAllocated()
     1715#  define TclDecrRefCount(objPtr) \
     1716    if (--(objPtr)->refCount <= 0) { \
     1717        if ((objPtr)->refCount < -1) \
     1718            panic("Reference count for %lx was negative: %s line %d", \
     1719                  (objPtr), __FILE__, __LINE__); \
     1720        if (((objPtr)->bytes != NULL) \
     1721                && ((objPtr)->bytes != tclEmptyStringRep)) { \
     1722            ckfree((char *) (objPtr)->bytes); \
     1723        } \
     1724        if (((objPtr)->typePtr != NULL) \
     1725                && ((objPtr)->typePtr->freeIntRepProc != NULL)) { \
     1726            (objPtr)->typePtr->freeIntRepProc(objPtr); \
     1727        } \
     1728        ckfree((char *) (objPtr)); \
     1729        TclIncrObjsFreed(); \
     1730    }
     1731#else /* not TCL_MEM_DEBUG */
    16831732#  define TclNewObj(objPtr) \
    16841733    if (tclFreeObjList == NULL) { \
     
    16911740    (objPtr)->bytes    = tclEmptyStringRep; \
    16921741    (objPtr)->length   = 0; \
    1693     (objPtr)->typePtr  = NULL;
     1742    (objPtr)->typePtr  = NULL; \
     1743    TclIncrObjsAllocated()
    16941744#  define TclDecrRefCount(objPtr) \
    16951745    if (--(objPtr)->refCount <= 0) { \
     
    17041754        (objPtr)->internalRep.otherValuePtr = (VOID *) tclFreeObjList; \
    17051755        tclFreeObjList = (objPtr); \
     1756        TclIncrObjsFreed(); \
    17061757    }
     1758#endif /* TCL_MEM_DEBUG */
    17071759
    17081760/*
  • external/tcl/tclListObj.c

    r83ee320 r2d7ff18  
    4646 * Tcl_NewListObj --
    4747 *
    48  *      This procedure creates a new list object from an (objc,objv) array:
    49  *      that is, each of the objc elements of the array referenced by objv
    50  *      is inserted as an element into a new Tcl object.
     48 *      This procedure is normally called when not debugging: i.e., when
     49 *      TCL_MEM_DEBUG is not defined. It creates a new list object from an
     50 *      (objc,objv) array: that is, each of the objc elements of the array
     51 *      referenced by objv is inserted as an element into a new Tcl object.
     52 *
     53 *      When TCL_MEM_DEBUG is defined, this procedure just returns the
     54 *      result of calling the debugging version Tcl_DbNewListObj.
    5155 *
    5256 * Results:
     
    6266 *----------------------------------------------------------------------
    6367 */
     68
     69#ifdef TCL_MEM_DEBUG
     70#undef Tcl_NewListObj
     71
     72Tcl_Obj *
     73Tcl_NewListObj(objc, objv)
     74    int objc;                   /* Count of objects referenced by objv. */
     75    Tcl_Obj *CONST objv[];      /* An array of pointers to Tcl objects. */
     76{
     77    return Tcl_DbNewListObj(objc, objv, "unknown", 0);
     78}
     79
     80#else /* if not TCL_MEM_DEBUG */
    6481
    6582Tcl_Obj *
     
    95112    return listPtr;
    96113}
     114#endif /* if TCL_MEM_DEBUG */
     115
     116
     117/*
     118 *----------------------------------------------------------------------
     119 *
     120 * Tcl_DbNewListObj --
     121 *
     122 *      This procedure is normally called when debugging: i.e., when
     123 *      TCL_MEM_DEBUG is defined. It creates new list objects. It is the
     124 *      same as the Tcl_NewListObj procedure above except that it calls
     125 *      Tcl_DbCkalloc directly with the file name and line number from its
     126 *      caller. This simplifies debugging since then the checkmem command
     127 *      will report the correct file name and line number when reporting
     128 *      objects that haven't been freed.
     129 *
     130 *      When TCL_MEM_DEBUG is not defined, this procedure just returns the
     131 *      result of calling Tcl_NewListObj.
     132 *
     133 * Results:
     134 *      A new list object is returned that is initialized from the object
     135 *      pointers in objv. If objc is less than or equal to zero, an empty
     136 *      object is returned. The new object's string representation
     137 *      is left NULL. The new list object has ref count 0.
     138 *
     139 * Side effects:
     140 *      The ref counts of the elements in objv are incremented since the
     141 *      resulting list now refers to them.
     142 *
     143 *----------------------------------------------------------------------
     144 */
     145
     146#ifdef TCL_MEM_DEBUG
     147
     148Tcl_Obj *
     149Tcl_DbNewListObj(objc, objv, file, line)
     150    int objc;                   /* Count of objects referenced by objv. */
     151    Tcl_Obj *CONST objv[];      /* An array of pointers to Tcl objects. */
     152    char *file;                 /* The name of the source file calling this
     153                                 * procedure; used for debugging. */
     154    int line;                   /* Line number in the source file; used
     155                                 * for debugging. */
     156{
     157    register Tcl_Obj *listPtr;
     158    register Tcl_Obj **elemPtrs;
     159    register List *listRepPtr;
     160    int i;
     161   
     162    TclDbNewObj(listPtr, file, line);
     163   
     164    if (objc > 0) {
     165        Tcl_InvalidateStringRep(listPtr);
     166       
     167        elemPtrs = (Tcl_Obj **)
     168            ckalloc((unsigned) (objc * sizeof(Tcl_Obj *)));
     169        for (i = 0;  i < objc;  i++) {
     170            elemPtrs[i] = objv[i];
     171            Tcl_IncrRefCount(elemPtrs[i]);
     172        }
     173       
     174        listRepPtr = (List *) ckalloc(sizeof(List));
     175        listRepPtr->maxElemCount = objc;
     176        listRepPtr->elemCount    = objc;
     177        listRepPtr->elements     = elemPtrs;
     178       
     179        listPtr->internalRep.otherValuePtr = (VOID *) listRepPtr;
     180        listPtr->typePtr = &tclListType;
     181    }
     182    return listPtr;
     183}
     184
     185#else /* if not TCL_MEM_DEBUG */
     186
     187Tcl_Obj *
     188Tcl_DbNewListObj(objc, objv, file, line)
     189    int objc;                   /* Count of objects referenced by objv. */
     190    Tcl_Obj *CONST objv[];      /* An array of pointers to Tcl objects. */
     191    char *file;                 /* The name of the source file calling this
     192                                 * procedure; used for debugging. */
     193    int line;                   /* Line number in the source file; used
     194                                 * for debugging. */
     195{
     196    return Tcl_NewListObj(objc, objv);
     197}
     198#endif /* TCL_MEM_DEBUG */
    97199
    98200
  • external/tcl/tclObj.c

    r83ee320 r2d7ff18  
    3636
    3737char *tclEmptyStringRep = NULL;
     38
     39/*
     40 * Count of the number of Tcl objects every allocated (by Tcl_NewObj) and
     41 * freed (by TclFreeObj).
     42 */
     43
     44#ifdef TCL_COMPILE_STATS
     45long tclObjsAlloced = 0;
     46long tclObjsFreed = 0;
     47#endif /* TCL_COMPILE_STATS */
    3848
    3949/*
     
    407417 * Tcl_NewObj --
    408418 *
    409  *      This procedure creates new Tcl objects that denote the empty string.
    410  *      These objects have a NULL object type and NULL string representation
    411  *      byte pointer. Type managers call this routine to allocate new objects
    412  *      that they further initialize.
     419 *      This procedure is normally called when not debugging: i.e., when
     420 *      TCL_MEM_DEBUG is not defined. It creates new Tcl objects that denote
     421 *      the empty string. These objects have a NULL object type and NULL
     422 *      string representation byte pointer. Type managers call this routine
     423 *      to allocate new objects that they further initialize.
     424 *
     425 *      When TCL_MEM_DEBUG is defined, this procedure just returns the
     426 *      result of calling the debugging version Tcl_DbNewObj.
    413427 *
    414428 * Results:
     
    417431 *      is set to 0.
    418432 *
    419  *----------------------------------------------------------------------
    420  */
     433 * Side effects:
     434 *      If compiling with TCL_COMPILE_STATS, this procedure increments
     435 *      the global count of allocated objects (tclObjsAlloced).
     436 *
     437 *----------------------------------------------------------------------
     438 */
     439
     440#ifdef TCL_MEM_DEBUG
     441#undef Tcl_NewObj
     442
     443Tcl_Obj *
     444Tcl_NewObj()
     445{
     446    return Tcl_DbNewObj("unknown", 0);
     447}
     448
     449#else /* if not TCL_MEM_DEBUG */
    421450
    422451Tcl_Obj *
     
    439468    objPtr->length   = 0;
    440469    objPtr->typePtr  = NULL;
     470#ifdef TCL_COMPILE_STATS
     471    tclObjsAlloced++;
     472#endif /* TCL_COMPILE_STATS */
    441473    return objPtr;
    442474}
     475#endif /* TCL_MEM_DEBUG */
     476
     477
     478/*
     479 *----------------------------------------------------------------------
     480 *
     481 * Tcl_DbNewObj --
     482 *
     483 *      This procedure is normally called when debugging: i.e., when
     484 *      TCL_MEM_DEBUG is defined. It creates new Tcl objects that denote the
     485 *      empty string. It is the same as the Tcl_NewObj procedure above
     486 *      except that it calls Tcl_DbCkalloc directly with the file name and
     487 *      line number from its caller. This simplifies debugging since then
     488 *      the checkmem command will report the correct file name and line
     489 *      number when reporting objects that haven't been freed.
     490 *
     491 *      When TCL_MEM_DEBUG is not defined, this procedure just returns the
     492 *      result of calling Tcl_NewObj.
     493 *
     494 * Results:
     495 *      The result is a newly allocated that represents the empty string.
     496 *      The new object's typePtr is set NULL and its ref count is set to 0.
     497 *
     498 * Side effects:
     499 *      If compiling with TCL_COMPILE_STATS, this procedure increments
     500 *      the global count of allocated objects (tclObjsAlloced).
     501 *
     502 *----------------------------------------------------------------------
     503 */
     504
     505#ifdef TCL_MEM_DEBUG
     506
     507Tcl_Obj *
     508Tcl_DbNewObj(file, line)
     509    register char *file;        /* The name of the source file calling this
     510                                 * procedure; used for debugging. */
     511    register int line;          /* Line number in the source file; used
     512                                 * for debugging. */
     513{
     514    register Tcl_Obj *objPtr;
     515
     516    /*
     517     * If debugging Tcl's memory usage, allocate the object using ckalloc.
     518     * Otherwise, allocate it using the list of free Tcl_Objs we maintain.
     519     */
     520
     521    objPtr = (Tcl_Obj *) Tcl_DbCkalloc(sizeof(Tcl_Obj), file, line);
     522    objPtr->refCount = 0;
     523    objPtr->bytes    = tclEmptyStringRep;
     524    objPtr->length   = 0;
     525    objPtr->typePtr  = NULL;
     526#ifdef TCL_COMPILE_STATS
     527    tclObjsAlloced++;
     528#endif /* TCL_COMPILE_STATS */
     529    return objPtr;
     530}
     531
     532#else /* if not TCL_MEM_DEBUG */
     533
     534Tcl_Obj *
     535Tcl_DbNewObj(file, line)
     536    char *file;                 /* The name of the source file calling this
     537                                 * procedure; used for debugging. */
     538    int line;                   /* Line number in the source file; used
     539                                 * for debugging. */
     540{
     541    return Tcl_NewObj();
     542}
     543#endif /* TCL_MEM_DEBUG */
    443544
    444545
     
    508609 *      after deallocating the string representation and calling the
    509610 *      type-specific Tcl_FreeInternalRepProc to deallocate the object's
    510  *      internal representation.
     611 *      internal representation. If compiling with TCL_COMPILE_STATS,
     612 *      this procedure increments the global count of freed objects
     613 *      (tclObjsFreed).
    511614 *
    512615 *----------------------------------------------------------------------
     
    519622    register Tcl_ObjType *typePtr = objPtr->typePtr;
    520623   
     624#ifdef TCL_MEM_DEBUG
     625    if ((objPtr)->refCount < -1) {
     626        panic("Reference count for %lx was negative", objPtr);
     627    }
     628#endif /* TCL_MEM_DEBUG */
     629
    521630    Tcl_InvalidateStringRep(objPtr);
    522631    if ((typePtr != NULL) && (typePtr->freeIntRepProc != NULL)) {
     
    525634
    526635    /*
    527      * Deallocate the object by adding it onto the list of free
     636     * If debugging Tcl's memory usage, deallocate the object using ckfree.
     637     * Otherwise, deallocate it by adding it onto the list of free
    528638     * Tcl_Objs we maintain.
    529639     */
    530640   
     641#ifdef TCL_MEM_DEBUG
     642    ckfree((char *) objPtr);
     643#else
    531644    objPtr->internalRep.otherValuePtr = (VOID *) tclFreeObjList;
    532645    tclFreeObjList = objPtr;
     646#endif /* TCL_MEM_DEBUG */
     647
     648#ifdef TCL_COMPILE_STATS   
     649    tclObjsFreed++;
     650#endif /* TCL_COMPILE_STATS */   
    533651}
    534652
     
    676794 * Tcl_NewBooleanObj --
    677795 *
    678  *      This procedure creates a new boolean object and initializes it from
    679  *      the argument boolean value. A nonzero "boolValue" is coerced to 1.
     796 *      This procedure is normally called when not debugging: i.e., when
     797 *      TCL_MEM_DEBUG is not defined. It creates a new boolean object and
     798 *      initializes it from the argument boolean value. A nonzero
     799 *      "boolValue" is coerced to 1.
     800 *
     801 *      When TCL_MEM_DEBUG is defined, this procedure just returns the
     802 *      result of calling the debugging version Tcl_DbNewBooleanObj.
    680803 *
    681804 * Results:
     
    688811 *----------------------------------------------------------------------
    689812 */
     813
     814#ifdef TCL_MEM_DEBUG
     815#undef Tcl_NewBooleanObj
    690816
    691817Tcl_Obj *
     
    693819    register int boolValue;     /* Boolean used to initialize new object. */
    694820{
     821    return Tcl_DbNewBooleanObj(boolValue, "unknown", 0);
     822}
     823
     824#else /* if not TCL_MEM_DEBUG */
     825
     826Tcl_Obj *
     827Tcl_NewBooleanObj(boolValue)
     828    register int boolValue;     /* Boolean used to initialize new object. */
     829{
    695830    register Tcl_Obj *objPtr;
    696831
     
    702837    return objPtr;
    703838}
     839#endif /* TCL_MEM_DEBUG */
     840
     841
     842/*
     843 *----------------------------------------------------------------------
     844 *
     845 * Tcl_DbNewBooleanObj --
     846 *
     847 *      This procedure is normally called when debugging: i.e., when
     848 *      TCL_MEM_DEBUG is defined. It creates new boolean objects. It is the
     849 *      same as the Tcl_NewBooleanObj procedure above except that it calls
     850 *      Tcl_DbCkalloc directly with the file name and line number from its
     851 *      caller. This simplifies debugging since then the checkmem command
     852 *      will report the correct file name and line number when reporting
     853 *      objects that haven't been freed.
     854 *
     855 *      When TCL_MEM_DEBUG is not defined, this procedure just returns the
     856 *      result of calling Tcl_NewBooleanObj.
     857 *
     858 * Results:
     859 *      The newly created object is returned. This object will have an
     860 *      invalid string representation. The returned object has ref count 0.
     861 *
     862 * Side effects:
     863 *      None.
     864 *
     865 *----------------------------------------------------------------------
     866 */
     867
     868#ifdef TCL_MEM_DEBUG
     869
     870Tcl_Obj *
     871Tcl_DbNewBooleanObj(boolValue, file, line)
     872    register int boolValue;     /* Boolean used to initialize new object. */
     873    char *file;                 /* The name of the source file calling this
     874                                 * procedure; used for debugging. */
     875    int line;                   /* Line number in the source file; used
     876                                 * for debugging. */
     877{
     878    register Tcl_Obj *objPtr;
     879
     880    TclDbNewObj(objPtr, file, line);
     881    objPtr->bytes = NULL;
     882   
     883    objPtr->internalRep.longValue = (boolValue? 1 : 0);
     884    objPtr->typePtr = &tclBooleanType;
     885    return objPtr;
     886}
     887
     888#else /* if not TCL_MEM_DEBUG */
     889
     890Tcl_Obj *
     891Tcl_DbNewBooleanObj(boolValue, file, line)
     892    register int boolValue;     /* Boolean used to initialize new object. */
     893    char *file;                 /* The name of the source file calling this
     894                                 * procedure; used for debugging. */
     895    int line;                   /* Line number in the source file; used
     896                                 * for debugging. */
     897{
     898    return Tcl_NewBooleanObj(boolValue);
     899}
     900#endif /* TCL_MEM_DEBUG */
    704901
    705902
     
    9811178 * Tcl_NewDoubleObj --
    9821179 *
    983  *      This procedure creates a new double object and initializes it from
    984  *      the argument double value.
     1180 *      This procedure is normally called when not debugging: i.e., when
     1181 *      TCL_MEM_DEBUG is not defined. It creates a new double object and
     1182 *      initializes it from the argument double value.
     1183 *
     1184 *      When TCL_MEM_DEBUG is defined, this procedure just returns the
     1185 *      result of calling the debugging version Tcl_DbNewDoubleObj.
    9851186 *
    9861187 * Results:
     
    9931194 *----------------------------------------------------------------------
    9941195 */
     1196
     1197#ifdef TCL_MEM_DEBUG
     1198#undef Tcl_NewDoubleObj
    9951199
    9961200Tcl_Obj *
     
    9981202    register double dblValue;   /* Double used to initialize the object. */
    9991203{
     1204    return Tcl_DbNewDoubleObj(dblValue, "unknown", 0);
     1205}
     1206
     1207#else /* if not TCL_MEM_DEBUG */
     1208
     1209Tcl_Obj *
     1210Tcl_NewDoubleObj(dblValue)
     1211    register double dblValue;   /* Double used to initialize the object. */
     1212{
    10001213    register Tcl_Obj *objPtr;
    10011214
     
    10071220    return objPtr;
    10081221}
     1222#endif /* if TCL_MEM_DEBUG */
     1223
     1224
     1225/*
     1226 *----------------------------------------------------------------------
     1227 *
     1228 * Tcl_DbNewDoubleObj --
     1229 *
     1230 *      This procedure is normally called when debugging: i.e., when
     1231 *      TCL_MEM_DEBUG is defined. It creates new double objects. It is the
     1232 *      same as the Tcl_NewDoubleObj procedure above except that it calls
     1233 *      Tcl_DbCkalloc directly with the file name and line number from its
     1234 *      caller. This simplifies debugging since then the checkmem command
     1235 *      will report the correct file name and line number when reporting
     1236 *      objects that haven't been freed.
     1237 *
     1238 *      When TCL_MEM_DEBUG is not defined, this procedure just returns the
     1239 *      result of calling Tcl_NewDoubleObj.
     1240 *
     1241 * Results:
     1242 *      The newly created object is returned. This object will have an
     1243 *      invalid string representation. The returned object has ref count 0.
     1244 *
     1245 * Side effects:
     1246 *      None.
     1247 *
     1248 *----------------------------------------------------------------------
     1249 */
     1250
     1251#ifdef TCL_MEM_DEBUG
     1252
     1253Tcl_Obj *
     1254Tcl_DbNewDoubleObj(dblValue, file, line)
     1255    register double dblValue;   /* Double used to initialize the object. */
     1256    char *file;                 /* The name of the source file calling this
     1257                                 * procedure; used for debugging. */
     1258    int line;                   /* Line number in the source file; used
     1259                                 * for debugging. */
     1260{
     1261    register Tcl_Obj *objPtr;
     1262
     1263    TclDbNewObj(objPtr, file, line);
     1264    objPtr->bytes = NULL;
     1265   
     1266    objPtr->internalRep.doubleValue = dblValue;
     1267    objPtr->typePtr = &tclDoubleType;
     1268    return objPtr;
     1269}
     1270
     1271#else /* if not TCL_MEM_DEBUG */
     1272
     1273Tcl_Obj *
     1274Tcl_DbNewDoubleObj(dblValue, file, line)
     1275    register double dblValue;   /* Double used to initialize the object. */
     1276    char *file;                 /* The name of the source file calling this
     1277                                 * procedure; used for debugging. */
     1278    int line;                   /* Line number in the source file; used
     1279                                 * for debugging. */
     1280{
     1281    return Tcl_NewDoubleObj(dblValue);
     1282}
     1283#endif /* TCL_MEM_DEBUG */
    10091284
    10101285
     
    12561531 * Tcl_NewIntObj --
    12571532 *
    1258  *      Calls to Tcl_NewIntObj result in a call to one of the two
     1533 *      If a client is compiled with TCL_MEM_DEBUG defined, calls to
     1534 *      Tcl_NewIntObj to create a new integer object end up calling the
     1535 *      debugging procedure Tcl_DbNewLongObj instead.
     1536 *
     1537 *      Otherwise, if the client is compiled without TCL_MEM_DEBUG defined,
     1538 *      calls to Tcl_NewIntObj result in a call to one of the two
    12591539 *      Tcl_NewIntObj implementations below. We provide two implementations
    12601540 *      so that the Tcl core can be compiled to do memory debugging of the
     
    12761556 */
    12771557
     1558#ifdef TCL_MEM_DEBUG
     1559#undef Tcl_NewIntObj
     1560
    12781561Tcl_Obj *
    12791562Tcl_NewIntObj(intValue)
    12801563    register int intValue;      /* Int used to initialize the new object. */
    12811564{
     1565    return Tcl_DbNewLongObj((long)intValue, "unknown", 0);
     1566}
     1567
     1568#else /* if not TCL_MEM_DEBUG */
     1569
     1570Tcl_Obj *
     1571Tcl_NewIntObj(intValue)
     1572    register int intValue;      /* Int used to initialize the new object. */
     1573{
    12821574    register Tcl_Obj *objPtr;
    12831575
     
    12891581    return objPtr;
    12901582}
     1583#endif /* if TCL_MEM_DEBUG */
    12911584
    12921585
     
    15631856 * Tcl_NewLongObj --
    15641857 *
    1565  *      Calls to Tcl_NewLongObj result in a call to one of the two
     1858 *      If a client is compiled with TCL_MEM_DEBUG defined, calls to
     1859 *      Tcl_NewLongObj to create a new long integer object end up calling
     1860 *      the debugging procedure Tcl_DbNewLongObj instead.
     1861 *
     1862 *      Otherwise, if the client is compiled without TCL_MEM_DEBUG defined,
     1863 *      calls to Tcl_NewLongObj result in a call to one of the two
    15661864 *      Tcl_NewLongObj implementations below. We provide two implementations
    15671865 *      so that the Tcl core can be compiled to do memory debugging of the
     
    15831881 */
    15841882
     1883#ifdef TCL_MEM_DEBUG
     1884#undef Tcl_NewLongObj
     1885
    15851886Tcl_Obj *
    15861887Tcl_NewLongObj(longValue)
     
    15881889                                 * new object. */
    15891890{
     1891    return Tcl_DbNewLongObj(longValue, "unknown", 0);
     1892}
     1893
     1894#else /* if not TCL_MEM_DEBUG */
     1895
     1896Tcl_Obj *
     1897Tcl_NewLongObj(longValue)
     1898    register long longValue;    /* Long integer used to initialize the
     1899                                 * new object. */
     1900{
    15901901    register Tcl_Obj *objPtr;
    15911902
     
    15971908    return objPtr;
    15981909}
     1910#endif /* if TCL_MEM_DEBUG */
    15991911
    16001912
     
    16041916 * Tcl_DbNewLongObj --
    16051917 *
    1606  *      This procedure just returns the result of calling Tcl_NewLongObj.
     1918 *      If a client is compiled with TCL_MEM_DEBUG defined, calls to
     1919 *      Tcl_NewIntObj and Tcl_NewLongObj to create new integer or
     1920 *      long integer objects end up calling the debugging procedure
     1921 *      Tcl_DbNewLongObj instead. We provide two implementations of
     1922 *      Tcl_DbNewLongObj so that whether the Tcl core is compiled to do
     1923 *      memory debugging of the core is independent of whether a client
     1924 *      requests debugging for itself.
     1925 *
     1926 *      When the core is compiled with TCL_MEM_DEBUG defined,
     1927 *      Tcl_DbNewLongObj calls Tcl_DbCkalloc directly with the file name and
     1928 *      line number from its caller. This simplifies debugging since then
     1929 *      the checkmem command will report the caller's file name and line
     1930 *      number when reporting objects that haven't been freed.
     1931 *
     1932 *      Otherwise, when the core is compiled without TCL_MEM_DEBUG defined,
     1933 *      this procedure just returns the result of calling Tcl_NewLongObj.
    16071934 *
    16081935 * Results:
     
    16161943 *----------------------------------------------------------------------
    16171944 */
     1945
     1946#ifdef TCL_MEM_DEBUG
    16181947
    16191948Tcl_Obj *
     
    16261955                                 * for debugging. */
    16271956{
     1957    register Tcl_Obj *objPtr;
     1958
     1959    TclDbNewObj(objPtr, file, line);
     1960    objPtr->bytes = NULL;
     1961   
     1962    objPtr->internalRep.longValue = longValue;
     1963    objPtr->typePtr = &tclIntType;
     1964    return objPtr;
     1965}
     1966
     1967#else /* if not TCL_MEM_DEBUG */
     1968
     1969Tcl_Obj *
     1970Tcl_DbNewLongObj(longValue, file, line)
     1971    register long longValue;    /* Long integer used to initialize the
     1972                                 * new object. */
     1973    char *file;                 /* The name of the source file calling this
     1974                                 * procedure; used for debugging. */
     1975    int line;                   /* Line number in the source file; used
     1976                                 * for debugging. */
     1977{
    16281978    return Tcl_NewLongObj(longValue);
    16291979}
     1980#endif /* TCL_MEM_DEBUG */
    16301981
    16311982
     
    17092060    return result;
    17102061}
     2062
     2063
     2064/*
     2065 *----------------------------------------------------------------------
     2066 *
     2067 * Tcl_DbIncrRefCount --
     2068 *
     2069 *      This procedure is normally called when debugging: i.e., when
     2070 *      TCL_MEM_DEBUG is defined. This checks to see whether or not
     2071 *      the memory has been freed before incrementing the ref count.
     2072 *
     2073 *      When TCL_MEM_DEBUG is not defined, this procedure just increments
     2074 *      the reference count of the object.
     2075 *
     2076 * Results:
     2077 *      None.
     2078 *
     2079 * Side effects:
     2080 *      The object's ref count is incremented.
     2081 *
     2082 *----------------------------------------------------------------------
     2083 */
     2084
     2085void
     2086Tcl_DbIncrRefCount(objPtr, file, line)
     2087    register Tcl_Obj *objPtr;   /* The object we are adding a reference to. */
     2088    char *file;                 /* The name of the source file calling this
     2089                                 * procedure; used for debugging. */
     2090    int line;                   /* Line number in the source file; used
     2091                                 * for debugging. */
     2092{
     2093#ifdef TCL_MEM_DEBUG
     2094    if (objPtr->refCount == 0x61616161) {
     2095        fprintf(stderr, "file = %s, line = %d\n", file, line);
     2096        fflush(stderr);
     2097        panic("Trying to increment refCount of previously disposed object.");
     2098    }
     2099#endif
     2100    ++(objPtr)->refCount;
     2101}
     2102
     2103
     2104/*
     2105 *----------------------------------------------------------------------
     2106 *
     2107 * Tcl_DbDecrRefCount --
     2108 *
     2109 *      This procedure is normally called when debugging: i.e., when
     2110 *      TCL_MEM_DEBUG is defined. This checks to see whether or not
     2111 *      the memory has been freed before incrementing the ref count.
     2112 *
     2113 *      When TCL_MEM_DEBUG is not defined, this procedure just increments
     2114 *      the reference count of the object.
     2115 *
     2116 * Results:
     2117 *      None.
     2118 *
     2119 * Side effects:
     2120 *      The object's ref count is incremented.
     2121 *
     2122 *----------------------------------------------------------------------
     2123 */
     2124
     2125void
     2126Tcl_DbDecrRefCount(objPtr, file, line)
     2127    register Tcl_Obj *objPtr;   /* The object we are adding a reference to. */
     2128    char *file;                 /* The name of the source file calling this
     2129                                 * procedure; used for debugging. */
     2130    int line;                   /* Line number in the source file; used
     2131                                 * for debugging. */
     2132{
     2133#ifdef TCL_MEM_DEBUG
     2134    if (objPtr->refCount == 0x61616161) {
     2135        fprintf(stderr, "file = %s, line = %d\n", file, line);
     2136        fflush(stderr);
     2137        panic("Trying to decrement refCount of previously disposed object.");
     2138    }
     2139#endif
     2140    if (--(objPtr)->refCount <= 0) {
     2141        TclFreeObj(objPtr);
     2142    }
     2143}
     2144
     2145
     2146/*
     2147 *----------------------------------------------------------------------
     2148 *
     2149 * Tcl_DbIsShared --
     2150 *
     2151 *      This procedure is normally called when debugging: i.e., when
     2152 *      TCL_MEM_DEBUG is defined. This checks to see whether or not
     2153 *      the memory has been freed before incrementing the ref count.
     2154 *
     2155 *      When TCL_MEM_DEBUG is not defined, this procedure just decrements
     2156 *      the reference count of the object and throws it away if the count
     2157 *      is 0 or less.
     2158 *
     2159 * Results:
     2160 *      None.
     2161 *
     2162 * Side effects:
     2163 *      The object's ref count is incremented.
     2164 *
     2165 *----------------------------------------------------------------------
     2166 */
     2167
     2168int
     2169Tcl_DbIsShared(objPtr, file, line)
     2170    register Tcl_Obj *objPtr;   /* The object we are adding a reference to. */
     2171    char *file;                 /* The name of the source file calling this
     2172                                 * procedure; used for debugging. */
     2173    int line;                   /* Line number in the source file; used
     2174                                 * for debugging. */
     2175{
     2176#ifdef TCL_MEM_DEBUG
     2177    if (objPtr->refCount == 0x61616161) {
     2178        fprintf(stderr, "file = %s, line = %d\n", file, line);
     2179        fflush(stderr);
     2180        panic("Trying to check whether previously disposed object is shared.");
     2181    }
     2182#endif
     2183    return ((objPtr)->refCount > 1);
     2184}
  • external/tcl/tclProc.c

    r83ee320 r2d7ff18  
    985985     */
    986986
     987    if (tclTraceExec >= 1) {
     988        fprintf(stdout, "Calling proc ");
     989        for (i = 0;  i < objc;  i++) {
     990            bytes = Tcl_GetStringFromObj(objv[i], &length);
     991            TclPrintSource(stdout, bytes, TclMin(length, 15));
     992            fprintf(stdout, " ");
     993        }
     994        fprintf(stdout, "\n");
     995        fflush(stdout);
     996    }
     997
    987998    iPtr->returnCode = TCL_OK;
    988999    procPtr->refCount++;
     
    11081119        int numChars;
    11091120        char *ellipsis;
     1121       
     1122        if (tclTraceCompile >= 1) {
     1123            /*
     1124             * Display a line summarizing the top level command we
     1125             * are about to compile.
     1126             */
     1127 
     1128            numChars = strlen(procName);
     1129            ellipsis = "";
     1130            if (numChars > 50) {
     1131                numChars = 50;
     1132                ellipsis = "...";
     1133            }
     1134            fprintf(stdout, "Compiling %s \"%.*s%s\"\n",
     1135                    description, numChars, procName, ellipsis);
     1136        }
    11101137       
    11111138        /*
  • external/tcl/tclStringObj.c

    r83ee320 r2d7ff18  
    5050 * Tcl_NewStringObj --
    5151 *
    52  *      This procedure creates a new string object and initializes it from
    53  *      the byte pointer and length arguments.
     52 *      This procedure is normally called when not debugging: i.e., when
     53 *      TCL_MEM_DEBUG is not defined. It creates a new string object and
     54 *      initializes it from the byte pointer and length arguments.
     55 *
     56 *      When TCL_MEM_DEBUG is defined, this procedure just returns the
     57 *      result of calling the debugging version Tcl_DbNewStringObj.
    5458 *
    5559 * Results:
     
    6670 *----------------------------------------------------------------------
    6771 */
     72
     73#ifdef TCL_MEM_DEBUG
     74#undef Tcl_NewStringObj
    6875
    6976Tcl_Obj *
     
    7683                                 * NULL byte. */
    7784{
     85    return Tcl_DbNewStringObj(bytes, length, "unknown", 0);
     86}
     87
     88#else /* if not TCL_MEM_DEBUG */
     89
     90Tcl_Obj *
     91Tcl_NewStringObj(bytes, length)
     92    register char *bytes;       /* Points to the first of the length bytes
     93                                 * used to initialize the new object. */
     94    register int length;        /* The number of bytes to copy from "bytes"
     95                                 * when initializing the new object. If
     96                                 * negative, use bytes up to the first
     97                                 * NULL byte. */
     98{
    7899    register Tcl_Obj *objPtr;
    79100
     
    85106    return objPtr;
    86107}
     108#endif /* TCL_MEM_DEBUG */
     109
     110
     111/*
     112 *----------------------------------------------------------------------
     113 *
     114 * Tcl_DbNewStringObj --
     115 *
     116 *      This procedure is normally called when debugging: i.e., when
     117 *      TCL_MEM_DEBUG is defined. It creates new string objects. It is the
     118 *      same as the Tcl_NewStringObj procedure above except that it calls
     119 *      Tcl_DbCkalloc directly with the file name and line number from its
     120 *      caller. This simplifies debugging since then the checkmem command
     121 *      will report the correct file name and line number when reporting
     122 *      objects that haven't been freed.
     123 *
     124 *      When TCL_MEM_DEBUG is not defined, this procedure just returns the
     125 *      result of calling Tcl_NewStringObj.
     126 *
     127 * Results:
     128 *      A newly created string object is returned that has ref count zero.
     129 *
     130 * Side effects:
     131 *      The new object's internal string representation will be set to a
     132 *      copy of the length bytes starting at "bytes". If "length" is
     133 *      negative, use bytes up to the first NULL byte; i.e., assume "bytes"
     134 *      points to a C-style NULL-terminated string. The object's type is set
     135 *      to NULL. An extra NULL is added to the end of the new object's byte
     136 *      array.
     137 *
     138 *----------------------------------------------------------------------
     139 */
     140
     141#ifdef TCL_MEM_DEBUG
     142
     143Tcl_Obj *
     144Tcl_DbNewStringObj(bytes, length, file, line)
     145    register char *bytes;       /* Points to the first of the length bytes
     146                                 * used to initialize the new object. */
     147    register int length;        /* The number of bytes to copy from "bytes"
     148                                 * when initializing the new object. If
     149                                 * negative, use bytes up to the first
     150                                 * NULL byte. */
     151    char *file;                 /* The name of the source file calling this
     152                                 * procedure; used for debugging. */
     153    int line;                   /* Line number in the source file; used
     154                                 * for debugging. */
     155{
     156    register Tcl_Obj *objPtr;
     157
     158    if (length < 0) {
     159        length = (bytes? strlen(bytes) : 0);
     160    }
     161    TclDbNewObj(objPtr, file, line);
     162    TclInitStringRep(objPtr, bytes, length);
     163    return objPtr;
     164}
     165
     166#else /* if not TCL_MEM_DEBUG */
     167
     168Tcl_Obj *
     169Tcl_DbNewStringObj(bytes, length, file, line)
     170    register char *bytes;       /* Points to the first of the length bytes
     171                                 * used to initialize the new object. */
     172    register int length;        /* The number of bytes to copy from "bytes"
     173                                 * when initializing the new object. If
     174                                 * negative, use bytes up to the first
     175                                 * NULL byte. */
     176    char *file;                 /* The name of the source file calling this
     177                                 * procedure; used for debugging. */
     178    int line;                   /* Line number in the source file; used
     179                                 * for debugging. */
     180{
     181    return Tcl_NewStringObj(bytes, length);
     182}
     183#endif /* TCL_MEM_DEBUG */
    87184
    88185
  • external/tcl/tclVar.c

    r83ee320 r2d7ff18  
    711711    char *msg;
    712712
     713#ifdef TCL_COMPILE_DEBUG
     714    Proc *procPtr = varFramePtr->procPtr;
     715    int localCt = procPtr->numCompiledLocals;
     716
     717    if (compiledLocals == NULL) {
     718        fprintf(stderr, "\nTclGetIndexedScalar: can't get local %i in frame 0x%x, no compiled locals\n",
     719                localIndex, (unsigned int) varFramePtr);
     720        panic("TclGetIndexedScalar: no compiled locals in frame 0x%x",
     721                (unsigned int) varFramePtr);
     722    }
     723    if ((localIndex < 0) || (localIndex >= localCt)) {
     724        fprintf(stderr, "\nTclGetIndexedScalar: can't get local %i in frame 0x%x with %i locals\n",
     725                localIndex, (unsigned int) varFramePtr, localCt);
     726        panic("TclGetIndexedScalar: bad local index %i in frame 0x%x",
     727                localIndex, (unsigned int) varFramePtr);
     728    }
     729#endif /* TCL_COMPILE_DEBUG */
     730   
    713731    varPtr = &(compiledLocals[localIndex]);
    714732    varName = varPtr->name;
     
    814832    int new;
    815833
     834#ifdef TCL_COMPILE_DEBUG
     835    Proc *procPtr = varFramePtr->procPtr;
     836    int localCt = procPtr->numCompiledLocals;
     837
     838    if (compiledLocals == NULL) {
     839        fprintf(stderr, "\nTclGetElementOfIndexedArray: can't get element of local %i in frame 0x%x, no compiled locals\n",
     840                localIndex, (unsigned int) varFramePtr);
     841        panic("TclGetIndexedScalar: no compiled locals in frame 0x%x",
     842                (unsigned int) varFramePtr);
     843    }
     844    if ((localIndex < 0) || (localIndex >= localCt)) {
     845        fprintf(stderr, "\nTclGetIndexedScalar: can't get element of local %i in frame 0x%x with %i locals\n",
     846                localIndex, (unsigned int) varFramePtr, localCt);
     847        panic("TclGetElementOfIndexedArray: bad local index %i in frame 0x%x",
     848                localIndex, (unsigned int) varFramePtr);
     849    }
     850#endif /* TCL_COMPILE_DEBUG */
     851
    816852    /*
    817853     * THIS FAILS IF THE ELEMENT NAME OBJECT'S STRING REP HAS A NULL BYTE.
     
    14131449    Tcl_Obj *resultPtr = NULL;
    14141450
     1451#ifdef TCL_COMPILE_DEBUG
     1452    Proc *procPtr = varFramePtr->procPtr;
     1453    int localCt = procPtr->numCompiledLocals;
     1454
     1455    if (compiledLocals == NULL) {
     1456        fprintf(stderr, "\nTclSetIndexedScalar: can't set local %i in frame 0x%x, no compiled locals\n",
     1457                localIndex, (unsigned int) varFramePtr);
     1458        panic("TclSetIndexedScalar: no compiled locals in frame 0x%x",
     1459                (unsigned int) varFramePtr);
     1460    }
     1461    if ((localIndex < 0) || (localIndex >= localCt)) {
     1462        fprintf(stderr, "\nTclSetIndexedScalar: can't set local %i in frame 0x%x with %i locals\n",
     1463                localIndex, (unsigned int) varFramePtr, localCt);
     1464        panic("TclSetIndexedScalar: bad local index %i in frame 0x%x",
     1465                localIndex, (unsigned int) varFramePtr);
     1466    }
     1467#endif /* TCL_COMPILE_DEBUG */
     1468   
    14151469    varPtr = &(compiledLocals[localIndex]);
    14161470    varName = varPtr->name;
     
    15811635    int new;
    15821636   
     1637#ifdef TCL_COMPILE_DEBUG
     1638    Proc *procPtr = varFramePtr->procPtr;
     1639    int localCt = procPtr->numCompiledLocals;
     1640
     1641    if (compiledLocals == NULL) {
     1642        fprintf(stderr, "\nTclSetElementOfIndexedArray: can't set element of local %i in frame 0x%x, no compiled locals\n",
     1643                localIndex, (unsigned int) varFramePtr);
     1644        panic("TclSetIndexedScalar: no compiled locals in frame 0x%x",
     1645                (unsigned int) varFramePtr);
     1646    }
     1647    if ((localIndex < 0) || (localIndex >= localCt)) {
     1648        fprintf(stderr, "\nTclSetIndexedScalar: can't set elememt of local %i in frame 0x%x with %i locals\n",
     1649                localIndex, (unsigned int) varFramePtr, localCt);
     1650        panic("TclSetElementOfIndexedArray: bad local index %i in frame 0x%x",
     1651                localIndex, (unsigned int) varFramePtr);
     1652    }
     1653#endif /* TCL_COMPILE_DEBUG */
     1654
    15831655    /*
    15841656     * THIS FAILS IF THE ELEMENT NAME OBJECT'S STRING REP HAS A NULL BYTE.
  • modules/FastJetFinder.cc

    r83ee320 r2d7ff18  
    316316  Double_t deta, dphi, detaMax, dphiMax;
    317317  Double_t time, timeWeight;
    318   Double_t neutralEnergyFraction, chargedEnergyFraction;
    319 
    320318  Int_t number, ncharged, nneutrals;
    321319  Int_t charge;
     
    420418    nneutrals = 0;
    421419
    422     neutralEnergyFraction =0.;
    423     chargedEnergyFraction =0.;
    424 
    425420    inputList.clear();
    426421    inputList = sequence->constituents(*itOutputList);
     
    437432
    438433      if(constituent->Charge == 0)
    439       {
    440434        nneutrals++;
    441         neutralEnergyFraction += constituent->Momentum.E();
    442       }
    443435      else
    444       {
    445436        ncharged++;
    446         chargedEnergyFraction += constituent->Momentum.E();
    447       }
    448      
     437
    449438      time += TMath::Sqrt(constituent->Momentum.E()) * (constituent->Position.T());
    450439      timeWeight += TMath::Sqrt(constituent->Momentum.E());
     
    465454    candidate->NNeutrals = nneutrals;
    466455    candidate->NCharged = ncharged;
    467 
    468     candidate->NeutralEnergyFraction = (momentum.E() > 0 ) ? neutralEnergyFraction/momentum.E() : 0.0;
    469     candidate->ChargedEnergyFraction = (momentum.E() > 0 ) ? chargedEnergyFraction/momentum.E() : 0.0;
    470456
    471457    //for exclusive clustering, access y_n,n+1 as exclusive_ymerge (fNJets);
  • modules/ModulesLinkDef.h

    r83ee320 r2d7ff18  
    4141#include "modules/DenseTrackFilter.h"
    4242#include "modules/Calorimeter.h"
    43 #include "modules/DualReadoutCalorimeter.h"
    4443#include "modules/OldCalorimeter.h"
    4544#include "modules/Isolation.h"
     
    5655#include "modules/JetPileUpSubtractor.h"
    5756#include "modules/TrackPileUpSubtractor.h"
    58 #include "modules/TrackTimingPileUpSubtractor.h"
    5957#include "modules/TaggingParticlesSkimmer.h"
    6058#include "modules/PileUpJetID.h"
     
    7371#include "modules/VertexFinder.h"
    7472#include "modules/VertexFinderDA4D.h"
    75 #include "modules/HighMassVertexRecover.h"
    76 #include "modules/DecayFilter.h"
    7773#include "modules/ExampleModule.h"
    7874
     
    9894#pragma link C++ class DenseTrackFilter+;
    9995#pragma link C++ class Calorimeter+;
    100 #pragma link C++ class DualReadoutCalorimeter+;
    10196#pragma link C++ class OldCalorimeter+;
    10297#pragma link C++ class Isolation+;
     
    113108#pragma link C++ class JetPileUpSubtractor+;
    114109#pragma link C++ class TrackPileUpSubtractor+;
    115 #pragma link C++ class TrackTimingPileUpSubtractor+;
    116110#pragma link C++ class TaggingParticlesSkimmer+;
    117111#pragma link C++ class PileUpJetID+;
     
    130124#pragma link C++ class VertexFinder+;
    131125#pragma link C++ class VertexFinderDA4D+;
    132 #pragma link C++ class HighMassVertexRecover+;
    133 #pragma link C++ class DecayFilter+;
    134126#pragma link C++ class ExampleModule+;
    135127
  • modules/MomentumSmearing.cc

    r83ee320 r2d7ff18  
    9595{
    9696  Candidate *candidate, *mother;
    97   Double_t pt, eta, phi, e, m, res;
     97  Double_t pt, eta, phi, e, res;
    9898
    9999  fItInputArray->Reset();
     
    106106    pt = candidateMomentum.Pt();
    107107    e = candidateMomentum.E();
    108     m = candidateMomentum.M();
     108    res = fFormula->Eval(pt, eta, phi, e);
    109109
    110     res = fFormula->Eval(pt, eta, phi, e);
     110    // apply smearing formula
     111    //pt = gRandom->Gaus(pt, fFormula->Eval(pt, eta, phi, e) * pt);
     112
    111113    res = (res > 1.0) ? 1.0 : res;
    112114
    113115    pt = LogNormal(pt, res * pt);
     116
     117    //if(pt <= 0.0) continue;
    114118
    115119    mother = candidate;
     
    117121    eta = candidateMomentum.Eta();
    118122    phi = candidateMomentum.Phi();
    119     candidate->Momentum.SetPtEtaPhiM(pt, eta, phi, m);
    120     candidate->ErrorPT = res*pt;
    121     candidate->PT = pt;
    122    
     123    candidate->Momentum.SetPtEtaPhiE(pt, eta, phi, pt * TMath::CosH(eta));
     124    //candidate->TrackResolution = fFormula->Eval(pt, eta, phi, e);
    123125    candidate->TrackResolution = res;
    124126    candidate->AddCandidate(mother);
  • modules/TaggingParticlesSkimmer.cc

    r83ee320 r2d7ff18  
    5757
    5858TaggingParticlesSkimmer::TaggingParticlesSkimmer() :
    59   fClassifier(0), fFilter(0), fItPartonInputArray(0),
    60   fPartonInputArray(0), fParticleInputArray(0), fOutputArray(0)
     59  fItPartonInputArray(0), fFilter(0), fClassifier(0)
    6160{
    6261}
  • modules/TimeSmearing.cc

    r83ee320 r2d7ff18  
    5353
    5454TimeSmearing::TimeSmearing() :
    55   fFormula(0), fItInputArray(0)
     55  fItInputArray(0)
    5656{
    57   fFormula = new DelphesFormula;
    5857}
    5958
     
    6261TimeSmearing::~TimeSmearing()
    6362{
    64   if(fFormula) delete fFormula;
    6563}
    6664
     
    7169  // read resolution formula
    7270
    73   fFormula->Compile(GetString("TimeResolution", "1.0"));
     71  fTimeResolution = GetDouble("TimeResolution", 1.0E-10);
     72  // import input array
    7473
    75   // import input array
    76   fEtaMax = GetDouble("EtaMax", 6.);
    7774  fInputArray = ImportArray(GetString("InputArray", "MuonMomentumSmearing/muons"));
    7875  fItInputArray = fInputArray->MakeIterator();
     
    9592{
    9693  Candidate *candidate, *mother;
    97   Double_t ti, tf_smeared, tf, timeResolution;
    98   Double_t pt, eta, phi, e, d0, dz, ctgTheta;
    99 
    100 
     94  Double_t ti, tf_smeared, tf;
    10195  const Double_t c_light = 2.99792458E8;
    10296
    10397  fItInputArray->Reset();
    104   while((candidate = static_cast<Candidate*>(fItInputArray->Next())))
     98  while((candidate = static_cast<Candidate *>(fItInputArray->Next())))
    10599  {
    106     ti = candidate->InitialPosition.T()*1.0E-3/c_light;
    107     tf = candidate->Position.T()*1.0E-3/c_light;
    108    
    109     // dummy, only need to properly call TFormula
    110     const TLorentzVector &candidatePosition = candidate->Position;
    111     const TLorentzVector &candidateMomentum = candidate->Momentum;
    112     eta = candidatePosition.Eta();
    113     phi = candidatePosition.Phi();
    114     pt = candidateMomentum.Pt();
    115     e = candidateMomentum.E();
    116     d0 = candidate->D0;
    117     dz = candidate->DZ;
    118     ctgTheta = candidate->CtgTheta;
     100    const TLorentzVector &candidateInitialPosition = candidate->InitialPosition;
     101    const TLorentzVector &candidateFinalPosition = candidate->Position;
     102
     103    ti = candidateInitialPosition.T() * 1.0E-3 / c_light;
     104    tf = candidateFinalPosition.T() * 1.0E-3 / c_light;
    119105
    120106    // apply smearing formula
    121    
    122     timeResolution = fFormula->Eval(pt, eta, phi, e, d0, dz, ctgTheta);
    123     if(fabs(candidate->Position.Eta())<fEtaMax)
    124     {
    125       tf_smeared = tf + timeResolution*gRandom->Gaus(0, 1);
    126     }
    127     else continue;
    128 
    129     // double beta_particle = candidate->Momentum.P()/candidate->Momentum.E();
    130     // ti = tf_smeared - candidate->Ld*1.0E-3/(c_light*beta_particle);
     107    tf_smeared = gRandom->Gaus(tf, fTimeResolution);
     108    ti = ti + tf_smeared - tf;
     109    tf = tf_smeared;
    131110
    132111    mother = candidate;
    133     candidate = static_cast<Candidate*>(candidate->Clone());
     112    candidate = static_cast<Candidate *>(candidate->Clone());
     113    candidate->InitialPosition.SetT(ti * 1.0E3 * c_light);
     114    candidate->Position.SetT(tf * 1.0E3 * c_light);
     115
     116    candidate->ErrorT = fTimeResolution * 1.0E3 * c_light;
     117
    134118    candidate->AddCandidate(mother);
    135     candidate->InitialPosition.SetT((100+ti)*1.0E3*c_light);
    136     candidate->Position.SetT(tf_smeared*1.0E3*c_light);
    137     candidate->ErrorT = timeResolution*1.0E3*c_light;
    138119
    139120    fOutputArray->Add(candidate);
  • modules/TimeSmearing.h

    r83ee320 r2d7ff18  
    3232class TIterator;
    3333class TObjArray;
    34 class DelphesFormula;
    3534
    3635class TimeSmearing: public DelphesModule
     
    4544
    4645private:
    47   DelphesFormula *fFormula; //!
    48   Double_t fEtaMax;
     46  Double_t fTimeResolution;
    4947
    5048  TIterator *fItInputArray; //!
  • modules/TrackPileUpSubtractor.cc

    r83ee320 r2d7ff18  
    117117void TrackPileUpSubtractor::Process()
    118118{
    119   Candidate *candidate, *particle, *particleTest;
     119  Candidate *candidate, *particle;
    120120  map<TIterator *, TObjArray *>::iterator itInputMap;
    121121  TIterator *iterator;
     
    123123  Double_t z, zvtx = 0;
    124124  Double_t pt, eta, phi, e;
    125   Double_t sumPT2 = 0;
    126   Double_t sumSquare = 0;
    127   int counter = 0;
    128   Double_t tempPTSquare = 0;
    129   Double_t tempZVertex = 0;
     125
    130126  // find z position of primary vertex
    131127
    132   cout << " ---------- NEW EVENT --------- " << endl;
    133 
    134128  fItVertexInputArray->Reset();
    135   cout << " NUMBER OF VERTICES : " << fVertexInputArray->GetEntriesFast() << endl;
    136129  while((candidate = static_cast<Candidate *>(fItVertexInputArray->Next())))
    137130  {
    138       cout << " ---------- NEW VERTEX --------- " << candidate->IsPU << endl;
    139       tempZVertex = candidate->Position.Z();
    140       tempPTSquare = candidate->SumPT2;
    141       if(tempPTSquare > sumSquare)
    142       {
    143         sumSquare = tempPTSquare;
    144         zvtx = tempZVertex;
    145         cout << " Sum Square : " << sumSquare << " Z of Vertex : " << zvtx << "  Is PileUp : " << candidate->IsPU << endl;
    146       }
    147      
    148       /*
    149       for(int i = 0; i < candidate->GetCandidates()->GetEntriesFast(); i++)
    150       {
    151         particleTest = static_cast<Candidate *>(candidate->GetCandidates()->At(i));
    152         TLorentzVector &candidateMomentumNew = particleTest->Momentum;
    153         if(candidateMomentumNew.Pt() > 1.0)
    154           sumSquare += (candidateMomentumNew.Pt()*candidateMomentumNew.Pt());
    155         cout << candidateMomentumNew.Pt() << "  " << candidate->SumPT2 << " counter : " << candidate->GetCandidates()->GetEntriesFast() << endl;
    156       } 
    157       */
     131    if(!candidate->IsPU)
     132    {
     133      zvtx = candidate->Position.Z();
     134      // break;
     135    }
    158136  }
    159137
     
    169147    {
    170148      particle = static_cast<Candidate *>(candidate->GetCandidates()->At(0));
    171       const TLorentzVector &candidateMomentum = candidate->Momentum;
     149      const TLorentzVector &candidateMomentum = particle->Momentum;
    172150
    173151      eta = candidateMomentum.Eta();
     
    176154      e = candidateMomentum.E();
    177155
    178       z = candidate->Position.Z();
    179       counter ++;
    180       //sum = pt*pt;
    181       if(pt > 1.0)
    182         sumPT2 += pt*pt;
     156      z = particle->Position.Z();
    183157
    184158      // apply pile-up subtraction
    185159      // assume perfect pile-up subtraction for tracks outside fZVertexResolution
    186       // cout << particle->IsRecoPU << " ParticleSumSquare : " << sumPT2 << " VertexResult : " << sumSquare << " Added SumSquare : " << zvtx << endl;
    187       //cout << pt << "  " << candidate->IsPU << "  " <<  TMath::Abs(z - zvtx) << "   " << sumPT2 << "   " << sumPT2 << endl;
    188160
    189      
    190       if(particle->Charge != 0 && TMath::Abs(z - zvtx) > fFormula->Eval(pt, eta, phi, e) * 1.0e3)
     161      if(candidate->Charge != 0 && candidate->IsPU && TMath::Abs(z - zvtx) > fFormula->Eval(pt, eta, phi, e) * 1.0e3)
    191162      {
    192163        candidate->IsRecoPU = 1;
    193         //cout <<  TMath::Abs(z - zvtx) << "   " << fFormula->Eval(pt, eta, phi, e) * 1.0e3 << endl;
    194164      }
    195165      else
  • modules/TrackSmearing.cc

    r83ee320 r2d7ff18  
    158158  TLorentzVector beamSpotPosition;
    159159  Candidate *candidate, *mother;
    160   Double_t pt, eta, d0, d0Error, trueD0, dz, dzError, trueDZ, p, pError, trueP, ctgTheta, ctgThetaError, trueCtgTheta, phi, phiError, truePhi, m;
     160  Double_t pt, eta, d0, d0Error, trueD0, dz, dzError, trueDZ, p, pError, trueP, ctgTheta, ctgThetaError, trueCtgTheta, phi, phiError, truePhi;
    161161  Double_t x, y, z, t, px, py, pz, theta;
    162162  Double_t q, r;
     
    328328
    329329    theta = TMath::ACos(ctgTheta / TMath::Sqrt(1.0 + ctgTheta * ctgTheta));
    330     m = candidate->Momentum.M();
    331    
    332330    candidate->Momentum.SetPx(p * TMath::Cos(phi) * TMath::Sin(theta));
    333331    candidate->Momentum.SetPy(p * TMath::Sin(phi) * TMath::Sin(theta));
    334332    candidate->Momentum.SetPz(p * TMath::Cos(theta));
    335     //candidate->Momentum.SetE(candidate->Momentum.Pt() * TMath::CosH(eta));
    336     candidate->Momentum.SetE( TMath::Sqrt(m*m + p*p) );
     333    candidate->Momentum.SetE(candidate->Momentum.Pt() * TMath::CosH(eta));
    337334    candidate->PT = candidate->Momentum.Pt();
    338335
     
    385382    candidate->Yd = yd * 1.0E3;
    386383    candidate->Zd = zd * 1.0E3;
    387     candidate->Td = -9999*c_light*1E-3;
    388    
     384
    389385    if(fApplyToPileUp || !candidate->IsPU)
    390386    {
  • modules/TreeWriter.cc

    r83ee320 r2d7ff18  
    7272  fClassMap[Track::Class()] = &TreeWriter::ProcessTracks;
    7373  fClassMap[Tower::Class()] = &TreeWriter::ProcessTowers;
    74   fClassMap[ParticleFlowCandidate::Class()] = &TreeWriter::ProcessParticleFlowCandidates;
    7574  fClassMap[Photon::Class()] = &TreeWriter::ProcessPhotons;
    7675  fClassMap[Electron::Class()] = &TreeWriter::ProcessElectrons;
     
    138137  it1.Reset();
    139138  array->Clear();
    140  
    141139  while((candidate = static_cast<Candidate *>(it1.Next())))
    142140  {
     
    360358    entry->Yd = candidate->Yd;
    361359    entry->Zd = candidate->Zd;
    362     entry->Td = candidate->Td*1.0E-3/c_light;
    363 
    364     if(candidate->ClusterIndex != -1)
    365     {
    366       entry->TOFreco = 1E-3*(candidate->Position.T() - candidate->InitialPosition.T())/c_light;
    367     }
    368     else
    369     {
    370       entry->TOFreco =-1E6;
    371     }
    372360
    373361    const TLorentzVector &momentum = candidate->Momentum;
     
    390378
    391379    particle = static_cast<Candidate *>(candidate->GetCandidates()->At(0));
    392     entry->TOFgen  = 1E-3*particle->L/(c_light*particle->Momentum.P()/particle->Momentum.E());
    393    
    394380    const TLorentzVector &initialPosition = particle->Position;
    395381
     
    453439//------------------------------------------------------------------------------
    454440
    455 void TreeWriter::ProcessParticleFlowCandidates(ExRootTreeBranch *branch, TObjArray *array)
    456 {
    457 
    458   TIter iterator(array);
    459   Candidate *candidate = 0;
    460   Candidate *particle = 0;
    461   ParticleFlowCandidate *entry = 0;
    462   Double_t e, pt, signz, cosTheta, eta, rapidity, p, ctgTheta, phi;
    463   const Double_t c_light = 2.99792458E8;
    464 
    465   // loop over all tracks
    466   iterator.Reset();
    467   while((candidate = static_cast<Candidate *>(iterator.Next())))
    468   {
    469     const TLorentzVector &position = candidate->Position;
    470 
    471     cosTheta = TMath::Abs(position.CosTheta());
    472     signz = (position.Pz() >= 0.0) ? 1.0 : -1.0;
    473     eta = (cosTheta == 1.0 ? signz * 999.9 : position.Eta());
    474     rapidity = (cosTheta == 1.0 ? signz * 999.9 : position.Rapidity());
    475 
    476     entry = static_cast<ParticleFlowCandidate *>(branch->NewEntry());
    477 
    478     entry->SetBit(kIsReferenced);
    479     entry->SetUniqueID(candidate->GetUniqueID());
    480 
    481     entry->PID = candidate->PID;
    482 
    483     entry->Charge = candidate->Charge;
    484 
    485     entry->EtaOuter = eta;
    486     entry->PhiOuter = position.Phi();
    487 
    488     entry->XOuter = position.X();
    489     entry->YOuter = position.Y();
    490     entry->ZOuter = position.Z();
    491     entry->TOuter = position.T() * 1.0E-3 / c_light;
    492 
    493     entry->L = candidate->L;
    494 
    495     entry->D0 = candidate->D0;
    496     entry->ErrorD0 = candidate->ErrorD0;
    497     entry->DZ = candidate->DZ;
    498     entry->ErrorDZ = candidate->ErrorDZ;
    499 
    500     entry->ErrorP = candidate->ErrorP;
    501     entry->ErrorPT = candidate->ErrorPT;
    502     entry->ErrorCtgTheta = candidate->ErrorCtgTheta;
    503     entry->ErrorPhi = candidate->ErrorPhi;
    504 
    505     entry->Xd = candidate->Xd;
    506     entry->Yd = candidate->Yd;
    507     entry->Zd = candidate->Zd;
    508 
    509     const TLorentzVector &momentum = candidate->Momentum;
    510 
    511     e = momentum.E();
    512     pt = momentum.Pt();
    513     p = momentum.P();
    514     phi = momentum.Phi();
    515     ctgTheta = (TMath::Tan(momentum.Theta()) != 0) ? 1 / TMath::Tan(momentum.Theta()) : 1e10;
    516 
    517     entry->E = e;
    518     entry->P = p;
    519     entry->PT = pt;
    520     entry->Eta = eta;
    521     entry->Phi = phi;
    522     entry->CtgTheta = ctgTheta;
    523 
    524     particle = static_cast<Candidate *>(candidate->GetCandidates()->At(0));
    525     const TLorentzVector &initialPosition = particle->Position;
    526 
    527     entry->X = initialPosition.X();
    528     entry->Y = initialPosition.Y();
    529     entry->Z = initialPosition.Z();
    530     entry->T = initialPosition.T() * 1.0E-3 / c_light;
    531 
    532     entry->VertexIndex = candidate->ClusterIndex;
    533 
    534     entry->Eem = candidate->Eem;
    535     entry->Ehad = candidate->Ehad;
    536     entry->Edges[0] = candidate->Edges[0];
    537     entry->Edges[1] = candidate->Edges[1];
    538     entry->Edges[2] = candidate->Edges[2];
    539     entry->Edges[3] = candidate->Edges[3];
    540 
    541     entry->T = position.T() * 1.0E-3 / c_light;
    542     entry->NTimeHits = candidate->NTimeHits;
    543 
    544     FillParticles(candidate, &entry->Particles);
    545 
    546   }
    547 }
    548 
    549 //------------------------------------------------------------------------------
    550 
    551441void TreeWriter::ProcessPhotons(ExRootTreeBranch *branch, TObjArray *array)
    552442{
     
    787677    entry->NCharged = candidate->NCharged;
    788678    entry->NNeutrals = candidate->NNeutrals;
    789 
    790     entry->NeutralEnergyFraction = candidate->NeutralEnergyFraction;
    791     entry->ChargedEnergyFraction = candidate->ChargedEnergyFraction;
    792679    entry->Beta = candidate->Beta;
    793680    entry->BetaStar = candidate->BetaStar;
  • modules/TreeWriter.h

    r83ee320 r2d7ff18  
    5656  void ProcessTracks(ExRootTreeBranch *branch, TObjArray *array);
    5757  void ProcessTowers(ExRootTreeBranch *branch, TObjArray *array);
    58   void ProcessParticleFlowCandidates(ExRootTreeBranch *branch, TObjArray *array);
    5958  void ProcessPhotons(ExRootTreeBranch *branch, TObjArray *array);
    6059  void ProcessElectrons(ExRootTreeBranch *branch, TObjArray *array);
     
    7877#endif
    7978
    80   ClassDef(TreeWriter, 2)
     79  ClassDef(TreeWriter, 1)
    8180};
    8281
  • modules/VertexFinderDA4D.cc

    r83ee320 r2d7ff18  
    33 *  Cluster vertices from tracks using deterministic annealing and timing information
    44 *
    5  *  \authors O. Cerri
     5 *  \authors M. Selvaggi, L. Gray
    66 *
    77 */
    8 
    98
    109#include "modules/VertexFinderDA4D.h"
     
    1413#include "classes/DelphesPileUpReader.h"
    1514
     15#include "ExRootAnalysis/ExRootClassifier.h"
     16#include "ExRootAnalysis/ExRootFilter.h"
    1617#include "ExRootAnalysis/ExRootResult.h"
    17 #include "ExRootAnalysis/ExRootFilter.h"
    18 #include "ExRootAnalysis/ExRootClassifier.h"
    19 
     18
     19#include "TDatabasePDG.h"
     20#include "TFormula.h"
     21#include "TLorentzVector.h"
    2022#include "TMath.h"
     23#include "TMatrixT.h"
     24#include "TObjArray.h"
     25#include "TRandom3.h"
    2126#include "TString.h"
    22 #include "TFormula.h"
    23 #include "TRandom3.h"
    24 #include "TObjArray.h"
    25 #include "TDatabasePDG.h"
    26 #include "TLorentzVector.h"
    27 #include "TMatrixT.h"
    28 #include "TLatex.h"
    2927#include "TVector3.h"
    3028
    31 #include "TAxis.h"
    32 #include "TGraphErrors.h"
    33 #include "TCanvas.h"
    34 #include "TString.h"
    35 #include "TLegend.h"
    36 #include "TFile.h"
    37 #include "TColor.h"
    38 #include "TLegend.h"
    39 
     29#include <algorithm>
     30#include <iostream>
     31#include <stdexcept>
    4032#include <utility>
    41 #include <algorithm>
    42 #include <stdexcept>
    43 #include <iostream>
    4433#include <vector>
    4534
    4635using namespace std;
    4736
    48 namespace vtx_DAZT
    49 {
    50   static const Double_t c_light = 2.99792458e+8; // [m/s]
    51 }
    52 using namespace vtx_DAZT;
    53 
    54 //------------------------------------------------------------------------------
    55 
    56 VertexFinderDA4D::VertexFinderDA4D()
    57 {
    58   fVerbose = 0;
    59   fMaxIterations = 0;
    60   fBetaMax = 0;
    61   fBetaStop = 0;
    62   fBetaPurge = 0;
    63   fVertexZSize = 0;
    64   fVertexTSize = 0;
    65   fCoolingFactor = 0;
    66   fDzCutOff = 0;
    67   fD0CutOff = 0;
    68   fDtCutOff = 0;
    69   fPtMin = 0;
    70   fPtMax = 0;
    71   fD2Merge = 0;
    72   fMuOutlayer = 0;
    73   fMinTrackProb = 0;
     37static const Double_t mm = 1.;
     38static const Double_t m = 1000. * mm;
     39static const Double_t ns = 1.;
     40static const Double_t s = 1.e+9 * ns;
     41static const Double_t c_light = 2.99792458e+8 * m / s;
     42
     43struct track_t
     44{
     45  double z; // z-coordinate at point of closest approach to the beamline
     46  double t; // t-coordinate at point of closest approach to the beamline
     47  double dz2; // square of the error of z(pca)
     48  double dtz; // covariance of z-t
     49  double dt2; // square of the error of t(pca)
     50  Candidate *tt; // a pointer to the Candidate Track
     51  double Z; // Z[i]   for DA clustering
     52  double pi; // track weight
     53  double pt;
     54  double eta;
     55  double phi;
     56};
     57
     58struct vertex_t
     59{
     60  double z;
     61  double t;
     62  double pk; // vertex weight for "constrained" clustering
     63  // --- temporary numbers, used during update
     64  double ei;
     65  double sw;
     66  double swz;
     67  double swt;
     68  double se;
     69  // ---for Tc
     70  double swE;
     71  double Tc;
     72};
     73
     74static bool split(double beta, std::vector<track_t> &tks, std::vector<vertex_t> &y);
     75static double update1(double beta, std::vector<track_t> &tks, std::vector<vertex_t> &y);
     76static double update2(double beta, std::vector<track_t> &tks, std::vector<vertex_t> &y, double &rho0, const double dzCutOff);
     77static void dump(const double beta, const std::vector<vertex_t> &y, const std::vector<track_t> &tks);
     78static bool merge(std::vector<vertex_t> &);
     79static bool merge(std::vector<vertex_t> &, double &);
     80static bool purge(std::vector<vertex_t> &, std::vector<track_t> &, double &, const double, const double);
     81static void splitAll(std::vector<vertex_t> &y);
     82static double beta0(const double betamax, std::vector<track_t> &tks, std::vector<vertex_t> &y, const double coolingFactor);
     83static double Eik(const track_t &t, const vertex_t &k);
     84
     85static bool recTrackLessZ1(const track_t &tk1, const track_t &tk2)
     86{
     87  return tk1.z < tk2.z;
     88}
     89
     90using namespace std;
     91
     92//------------------------------------------------------------------------------
     93
     94VertexFinderDA4D::VertexFinderDA4D() :
     95  fVerbose(0), fMinPT(0), fVertexSpaceSize(0), fVertexTimeSize(0),
     96  fUseTc(0), fBetaMax(0), fBetaStop(0), fCoolingFactor(0),
     97  fMaxIterations(0), fDzCutOff(0), fD0CutOff(0), fDtCutOff(0)
     98{
    7499}
    75100
     
    84109void VertexFinderDA4D::Init()
    85110{
    86   fVerbose         = GetInt("Verbose", 0);
    87 
    88   fMaxIterations   = GetInt("MaxIterations", 100);
    89   fMaxVertexNumber = GetInt("MaxVertexNumber", 500);
    90 
    91   fBetaMax         = GetDouble("BetaMax", 1.5);
    92   fBetaPurge       = GetDouble("BetaPurge", 1.);
    93   fBetaStop        = GetDouble("BetaStop", 0.2);
    94 
    95   fVertexZSize     = GetDouble("VertexZSize", 0.1); //in mm
    96   fVertexTSize     = 1E12*GetDouble("VertexTimeSize", 15E-12); //Convert from [s] to [ps]
    97 
    98   fCoolingFactor   = GetDouble("CoolingFactor", 0.8); // Multiply T so to cooldown must be <1
    99 
    100   fDzCutOff        = GetDouble("DzCutOff", 40);      // For the moment 3*DzCutOff is hard cut off for the considered tracks
    101   fD0CutOff        = GetDouble("D0CutOff", .5);       // d0/sigma_d0, used to compute the pi (weight) of the track
    102   fDtCutOff        = GetDouble("DtCutOff", 160);     // [ps], 3*DtCutOff is hard cut off for tracks
    103   fPtMin           = GetDouble("PtMin", 0.5);        // Minimum pt accepted for tracks
    104   fPtMax           = GetDouble("PtMax", 50);        // Maximum pt accepted for tracks
    105 
    106 
    107   fD2UpdateLim     = GetDouble("D2UpdateLim", .5);   // ((dz/ZSize)^2+(dt/TSize)^2)/nv limit for merging vertices
    108   fD2Merge         = GetDouble("D2Merge", 4.0);      // (dz/ZSize)^2+(dt/TSize)^2 limit for merging vertices
    109   fMuOutlayer      = GetDouble("MuOutlayer", 4);     // Outlayer rejection exponent
    110   fMinTrackProb    = GetDouble("MinTrackProb", 0.6); // Minimum probability to be assigned at a vertex
    111   fMinNTrack       = GetInt("MinNTrack", 10);        // Minimum number of tracks per vertex
    112 
    113   fFigFolderPath   = GetString("DebugFigPath", ".");
     111
     112  fVerbose = GetBool("Verbose", 1);
     113  fMinPT = GetDouble("MinPT", 0.1);
     114  fVertexSpaceSize = GetDouble("VertexSpaceSize", 0.5); //in mm
     115  fVertexTimeSize = GetDouble("VertexTimeSize", 10E-12); //in s
     116  fUseTc = GetBool("UseTc", 1);
     117  fBetaMax = GetDouble("BetaMax ", 0.1);
     118  fBetaStop = GetDouble("BetaStop", 1.0);
     119  fCoolingFactor = GetDouble("CoolingFactor", 0.8);
     120  fMaxIterations = GetInt("MaxIterations", 100);
     121  fDzCutOff = GetDouble("DzCutOff", 40); // Adaptive Fitter uses 30 mm but that appears to be a bit tight here sometimes
     122  fD0CutOff = GetDouble("D0CutOff", 30);
     123  fDtCutOff = GetDouble("DtCutOff", 100E-12); // dummy
     124
     125  // convert stuff in cm, ns
     126  fVertexSpaceSize /= 10.0;
     127  fVertexTimeSize *= 1E9;
     128  fDzCutOff /= 10.0; // Adaptive Fitter uses 3.0 but that appears to be a bit tight here sometimes
     129  fD0CutOff /= 10.0;
    114130
    115131  fInputArray = ImportArray(GetString("InputArray", "TrackSmearing/tracks"));
    116132  fItInputArray = fInputArray->MakeIterator();
    117133
    118   fTrackOutputArray = ExportArray(GetString("TrackOutputArray", "tracks"));
     134  fOutputArray = ExportArray(GetString("OutputArray", "tracks"));
    119135  fVertexOutputArray = ExportArray(GetString("VertexOutputArray", "vertices"));
    120 
    121   fInputGenVtx = ImportArray(GetString("InputGenVtx", "PileUpMerger/vertices"));
    122   fItInputGenVtx = fInputGenVtx->MakeIterator();
    123 
    124   if (fBetaMax < fBetaPurge)
    125   {
    126     fBetaPurge = fBetaMax;
    127     if (fVerbose)
    128     {
    129       cout << "BetaPurge set to " << fBetaPurge << endl;
    130     }
    131   }
    132 
    133   if (fBetaPurge < fBetaStop)
    134   {
    135     fBetaStop = fBetaPurge;
    136     if (fVerbose)
    137     {
    138       cout << "BetaPurge set to " << fBetaPurge << endl;
    139     }
    140   }
    141136}
    142137
     
    152147void VertexFinderDA4D::Process()
    153148{
     149  Candidate *candidate, *track;
     150  TObjArray *ClusterArray;
     151  ClusterArray = new TObjArray;
     152  TIterator *ItClusterArray;
     153  Int_t ivtx = 0;
     154
    154155  fInputArray->Sort();
    155156
    156   if (fVerbose)
    157   {
    158      cout<< endl << "      Start processing vertices with VertexFinderDA4D" << endl;
    159      cout<<" Found "<<fInputArray->GetEntriesFast()<<" input tracks"<<endl;
    160   }
    161 
    162   // clusterize tracks
    163   TObjArray *ClusterArray = new TObjArray;
    164   clusterize(*ClusterArray);
    165 
    166   if(fVerbose>10)
    167   {
    168     unsigned int N = fEnergy_rec.size();
    169     TGraph* gr1 = new TGraph(N, &fBeta_rec[0], &fNvtx_rec[0]);
    170     gr1->SetName("gr1");
    171     gr1->GetXaxis()->SetTitle("beta");
    172     gr1->GetYaxis()->SetTitle("# Vtx");
    173     TGraph* gr2 = new TGraph(N, &fBeta_rec[0], &fEnergy_rec[0]);
    174     gr2->SetName("gr2");
    175     gr2->GetXaxis()->SetTitle("beta");
    176     gr2->GetYaxis()->SetTitle("Total Energy");
    177     TGraph* gr3 = new TGraph(N, &fNvtx_rec[0], &fEnergy_rec[0]);
    178     gr3->SetName("gr3");
    179     gr3->GetXaxis()->SetTitle("# Vtx");
    180     gr3->GetYaxis()->SetTitle("Total Energy");
    181 
    182     auto f = new TFile("~/Desktop/debug/EnergyStat.root", "recreate");
    183     gr1->Write("gr1");
    184     gr2->Write("gr2");
    185     gr3->Write("gr3");
    186 
    187     f->Close();
    188   }
    189 
    190   if (fVerbose){std::cout <<  " clustering returned  "<< ClusterArray->GetEntriesFast() << " clusters  from " << fInputArray->GetEntriesFast() << " input tracks" <<std::endl;}
    191 
    192   // //loop over vertex candidates
    193   TIterator * ItClusterArray = ClusterArray->MakeIterator();
     157  TLorentzVector pos, mom;
     158  if(fVerbose)
     159  {
     160    cout << " start processing vertices ..." << endl;
     161    cout << " Found " << fInputArray->GetEntriesFast() << " input tracks" << endl;
     162    //loop over input tracks
     163    fItInputArray->Reset();
     164    while((candidate = static_cast<Candidate *>(fItInputArray->Next())))
     165    {
     166      pos = candidate->InitialPosition;
     167      mom = candidate->Momentum;
     168
     169      cout << "pt: " << mom.Pt() << ", eta: " << mom.Eta() << ", phi: " << mom.Phi() << ", z: " << candidate->DZ / 10 << endl;
     170    }
     171  }
     172
     173  // clusterize tracks in Z
     174  clusterize(*fInputArray, *ClusterArray);
     175
     176  if(fVerbose)
     177  {
     178    std::cout << " clustering returned  " << ClusterArray->GetEntriesFast() << " clusters  from " << fInputArray->GetEntriesFast() << " selected tracks" << std::endl;
     179  }
     180
     181  //loop over vertex candidates
     182  ItClusterArray = ClusterArray->MakeIterator();
    194183  ItClusterArray->Reset();
     184  while((candidate = static_cast<Candidate *>(ItClusterArray->Next())))
     185  {
     186
     187    double meantime = 0.;
     188    double expv_x2 = 0.;
     189    double normw = 0.;
     190    double errtime = 0;
     191
     192    double meanpos = 0.;
     193    double meanerr2 = 0.;
     194    double normpos = 0.;
     195    double errpos = 0.;
     196
     197    double sumpt2 = 0.;
     198
     199    int itr = 0;
     200
     201    if(fVerbose) cout << "this vertex has: " << candidate->GetCandidates()->GetEntriesFast() << " tracks" << endl;
     202
     203    // loop over tracks belonging to this vertex
     204    TIter it1(candidate->GetCandidates());
     205    it1.Reset();
     206
     207    while((track = static_cast<Candidate *>(it1.Next())))
     208    {
     209
     210      itr++;
     211      // TBC: the time is in ns for now TBC
     212      double t = track->InitialPosition.T() / c_light;
     213      double dt = track->ErrorT / c_light;
     214      const double time = t;
     215      const double inverr = 1.0 / dt;
     216      meantime += time * inverr;
     217      expv_x2 += time * time * inverr;
     218      normw += inverr;
     219
     220      // compute error position TBC
     221      const double pt = track->Momentum.Pt();
     222      const double z = track->DZ / 10.0;
     223      const double err_pt = track->ErrorPT;
     224      const double err_z = track->ErrorDZ;
     225
     226      const double wi = (pt / (err_pt * err_z)) * (pt / (err_pt * err_z));
     227      meanpos += z * wi;
     228
     229      meanerr2 += err_z * err_z * wi;
     230      normpos += wi;
     231      sumpt2 += pt * pt;
     232
     233      // while we are here store cluster index in tracks
     234      track->ClusterIndex = ivtx;
     235    }
     236
     237    meantime = meantime / normw;
     238    expv_x2 = expv_x2 / normw;
     239    errtime = TMath::Sqrt((expv_x2 - meantime * meantime) / itr);
     240    meanpos = meanpos / normpos;
     241    meanerr2 = meanerr2 / normpos;
     242    errpos = TMath::Sqrt(meanerr2 / itr);
     243
     244    candidate->Position.SetXYZT(0.0, 0.0, meanpos * 10.0, meantime * c_light);
     245    candidate->PositionError.SetXYZT(0.0, 0.0, errpos * 10.0, errtime * c_light);
     246    candidate->SumPT2 = sumpt2;
     247    candidate->ClusterNDF = itr;
     248    candidate->ClusterIndex = ivtx;
     249
     250    fVertexOutputArray->Add(candidate);
     251
     252    ivtx++;
     253
     254    if(fVerbose)
     255    {
     256      std::cout << "x,y,z";
     257      std::cout << ",t";
     258      std::cout << "=" << candidate->Position.X() / 10.0 << " " << candidate->Position.Y() / 10.0 << " " << candidate->Position.Z() / 10.0;
     259      std::cout << " " << candidate->Position.T() / c_light;
     260
     261      std::cout << std::endl;
     262      std::cout << "sumpt2 " << candidate->SumPT2 << endl;
     263
     264      std::cout << "ex,ey,ez";
     265      std::cout << ",et";
     266      std::cout << "=" << candidate->PositionError.X() / 10.0 << " " << candidate->PositionError.Y() / 10.0 << " " << candidate->PositionError.Z() / 10.0;
     267      std::cout << " " << candidate->PositionError.T() / c_light;
     268      std::cout << std::endl;
     269    }
     270  } // end of cluster loop
     271
     272  if(fVerbose)
     273  {
     274    std::cout << "PrimaryVertexProducerAlgorithm::vertices candidates =" << ClusterArray->GetEntriesFast() << std::endl;
     275  }
     276
     277  //TBC maybe this can be done later
     278  // sort vertices by pt**2  vertex (aka signal vertex tagging)
     279  /*if(pvs.size()>1){
     280      sort(pvs.begin(), pvs.end(), VertexHigherPtSquared());
     281    }
     282     */
     283
     284  delete ClusterArray;
     285}
     286
     287//------------------------------------------------------------------------------
     288
     289void VertexFinderDA4D::clusterize(const TObjArray &tracks, TObjArray &clusters)
     290{
     291  if(fVerbose)
     292  {
     293    cout << "###################################################" << endl;
     294    cout << "# VertexFinderDA4D::clusterize   nt=" << tracks.GetEntriesFast() << endl;
     295    cout << "###################################################" << endl;
     296  }
     297
     298  vector<Candidate *> pv = vertices();
     299
     300  if(fVerbose)
     301  {
     302    cout << "# VertexFinderDA4D::clusterize   pv.size=" << pv.size() << endl;
     303  }
     304  if(pv.size() == 0)
     305  {
     306    return;
     307  }
     308
     309  // convert into vector of candidates
     310  //TObjArray *ClusterArray = pv.begin()->GetCandidates();
     311  //Candidate *aCluster = static_cast<Candidate*>(&(pv.at(0)));
     312  Candidate *aCluster = pv.at(0);
     313
     314  // fill into clusters and merge
     315
     316  if(fVerbose)
     317  {
     318    std::cout << '\t' << 0;
     319    std::cout << ' ' << (*pv.begin())->Position.Z() / 10.0 << ' ' << (*pv.begin())->Position.T() / c_light << std::endl;
     320  }
     321
     322  for(vector<Candidate *>::iterator k = pv.begin() + 1; k != pv.end(); k++)
     323  {
     324    if(fVerbose)
     325    {
     326      std::cout << '\t' << std::distance(pv.begin(), k);
     327      std::cout << ' ' << (*k)->Position.Z() << ' ' << (*k)->Position.T() << std::endl;
     328    }
     329
     330    // TBC - check units here
     331    if(std::abs((*k)->Position.Z() - (*(k - 1))->Position.Z()) / 10.0 > (2 * fVertexSpaceSize) || std::abs((*k)->Position.T() - (*(k - 1))->Position.Z()) / c_light > 2 * 0.010)
     332    {
     333      // close a cluster
     334      clusters.Add(aCluster);
     335      //aCluster.clear();
     336    }
     337    //for(unsigned int i=0; i<k->GetCandidates().GetEntriesFast(); i++){
     338    aCluster = *k;
     339    //}
     340  }
     341  clusters.Add(aCluster);
     342
     343  if(fVerbose)
     344  {
     345    std::cout << "# VertexFinderDA4D::clusterize clusters.size=" << clusters.GetEntriesFast() << std::endl;
     346  }
     347}
     348
     349//------------------------------------------------------------------------------
     350
     351vector<Candidate *> VertexFinderDA4D::vertices()
     352{
    195353  Candidate *candidate;
    196   unsigned int k = 0;
    197   while((candidate = static_cast<Candidate*>(ItClusterArray->Next())))
    198   {
     354  UInt_t clusterIndex = 0;
     355  vector<Candidate *> clusters;
     356
     357  vector<track_t> tks;
     358  track_t tr;
     359  Double_t z, dz, t, l, dt, d0, d0error;
     360
     361  // loop over input tracks
     362  fItInputArray->Reset();
     363  while((candidate = static_cast<Candidate *>(fItInputArray->Next())))
     364  {
     365    //TBC everything in cm
     366    z = candidate->DZ / 10;
     367    tr.z = z;
     368    dz = candidate->ErrorDZ / 10;
     369    tr.dz2 = dz * dz // track error
     370      //TBC: beamspot size induced error, take 0 for now.
     371      // + (std::pow(beamspot.BeamWidthX()*cos(phi),2.)+std::pow(beamspot.BeamWidthY()*sin(phi),2.))/std::pow(tantheta,2.) // beam-width induced
     372      + fVertexSpaceSize * fVertexSpaceSize; // intrinsic vertex size, safer for outliers and short lived decays
     373
     374    // TBC: the time is in ns for now TBC
     375    //t = candidate->Position.T()/c_light;
     376    t = candidate->InitialPosition.T() / c_light;
     377    l = candidate->L / c_light;
     378    double pt = candidate->Momentum.Pt();
     379    double eta = candidate->Momentum.Eta();
     380    double phi = candidate->Momentum.Phi();
     381
     382    tr.pt = pt;
     383    tr.eta = eta;
     384    tr.phi = phi;
     385    tr.t = t; //
     386    tr.dtz = 0.;
     387    dt = candidate->ErrorT / c_light;
     388    tr.dt2 = dt * dt + fVertexTimeSize * fVertexTimeSize; // the ~injected~ timing error plus a small minimum vertex size in time
     389    if(fD0CutOff > 0)
     390    {
     391
     392      d0 = TMath::Abs(candidate->D0) / 10.0;
     393      d0error = candidate->ErrorD0 / 10.0;
     394
     395      tr.pi = 1. / (1. + exp((d0 * d0) / (d0error * d0error) - fD0CutOff * fD0CutOff)); // reduce weight for high ip tracks
     396    }
     397    else
     398    {
     399      tr.pi = 1.;
     400    }
     401    tr.tt = &(*candidate);
     402    tr.Z = 1.;
     403
     404    // TBC now putting track selection here (> fPTMin)
     405    if(tr.pi > 1e-3 && tr.pt > fMinPT)
     406    {
     407      tks.push_back(tr);
     408    }
     409  }
     410
     411  //print out input tracks
     412
     413  if(fVerbose)
     414  {
     415    std::cout << " start processing vertices ..." << std::endl;
     416    std::cout << " Found " << tks.size() << " input tracks" << std::endl;
     417    //loop over input tracks
     418
     419    for(std::vector<track_t>::const_iterator it = tks.begin(); it != tks.end(); it++)
     420    {
     421      double z = it->z;
     422      double pt = it->pt;
     423      double eta = it->eta;
     424      double phi = it->phi;
     425      double t = it->t;
     426
     427      std::cout << "pt: " << pt << ", eta: " << eta << ", phi: " << phi << ", z: " << z << ", t: " << t << std::endl;
     428    }
     429  }
     430
     431  unsigned int nt = tks.size();
     432  double rho0 = 0.0; // start with no outlier rejection
     433
     434  if(tks.empty()) return clusters;
     435
     436  vector<vertex_t> y; // the vertex prototypes
     437
     438  // initialize:single vertex at infinite temperature
     439  vertex_t vstart;
     440  vstart.z = 0.;
     441  vstart.t = 0.;
     442  vstart.pk = 1.;
     443  y.push_back(vstart);
     444  int niter = 0; // number of iterations
     445
     446  // estimate first critical temperature
     447  double beta = beta0(fBetaMax, tks, y, fCoolingFactor);
     448  niter = 0;
     449  while((update1(beta, tks, y) > 1.e-6) && (niter++ < fMaxIterations))
     450  {
     451  }
     452
     453  // annealing loop, stop when T<Tmin  (i.e. beta>1/Tmin)
     454  while(beta < fBetaMax)
     455  {
     456
     457    if(fUseTc)
     458    {
     459      update1(beta, tks, y);
     460      while(merge(y, beta))
     461      {
     462        update1(beta, tks, y);
     463      }
     464      split(beta, tks, y);
     465      beta = beta / fCoolingFactor;
     466    }
     467    else
     468    {
     469      beta = beta / fCoolingFactor;
     470      splitAll(y);
     471    }
     472
     473    // make sure we are not too far from equilibrium before cooling further
     474    niter = 0;
     475    while((update1(beta, tks, y) > 1.e-6) && (niter++ < fMaxIterations))
     476    {
     477    }
     478  }
     479
     480  if(fUseTc)
     481  {
     482    // last round of splitting, make sure no critical clusters are left
     483    update1(beta, tks, y);
     484    while(merge(y, beta))
     485    {
     486      update1(beta, tks, y);
     487    }
     488    unsigned int ntry = 0;
     489    while(split(beta, tks, y) && (ntry++ < 10))
     490    {
     491      niter = 0;
     492      while((update1(beta, tks, y) > 1.e-6) && (niter++ < fMaxIterations))
     493      {
     494      }
     495      merge(y, beta);
     496      update1(beta, tks, y);
     497    }
     498  }
     499  else
     500  {
     501    // merge collapsed clusters
     502    while(merge(y, beta))
     503    {
     504      update1(beta, tks, y);
     505    }
    199506    if(fVerbose)
    200507    {
    201      cout << Form("Cluster %d has %d tracks ", k, candidate->GetCandidates()->GetEntriesFast()) << endl;
    202     }
    203     if(candidate->ClusterNDF>0)
    204     {
    205       // Estimate the vertex resolution
    206       // loop over tracks belonging to this vertex
    207       TIter it1(candidate->GetCandidates());
    208       it1.Reset();
    209 
    210       Candidate *track;
    211       double sum_Dt_2 = 0;
    212       double sum_Dz_2 = 0;
    213       double sum_wt = 0;
    214       double sum_wz = 0;
    215       while((track = static_cast<Candidate*>(it1.Next())))
    216       {
    217         double dz = candidate->Position.Z() - track->Zd;
    218         double dt = candidate->Position.T() - track->Td;
    219 
    220         double wz = track->VertexingWeight/(track->ErrorDZ*track->ErrorDZ);
    221         double wt = track->VertexingWeight/(track->ErrorT*track->ErrorT);
    222 
    223         sum_Dt_2 += wt*dt*dt;
    224         sum_Dz_2 += wz*dz*dz;
    225         sum_wt += wt;
    226         sum_wz += wz;
    227       }
    228 
    229       double sigma_z = sqrt(sum_Dz_2/sum_wz);
    230       double sigma_t = sqrt(sum_Dt_2/sum_wt);
    231       candidate->PositionError.SetXYZT(0.0, 0.0, sigma_z , sigma_t);
    232       if(fVerbose > 3)
    233       {
    234         cout << "k: " << k << endl;
    235         cout << "Sigma z: " << sigma_z*1E3 << " um" << endl;
    236         cout << "Sigma t: " << sigma_t*1E9/c_light << " ps" << endl;
    237       }
    238 
    239       fVertexOutputArray->Add(candidate);
    240       k++;
    241     }
    242    }// end of cluster loop
    243 
    244   delete ClusterArray;
    245 }
    246 
    247 //------------------------------------------------------------------------------
    248 
    249 void VertexFinderDA4D::clusterize(TObjArray &clusters)
    250 {
    251   tracks_t tks;
    252   fill(tks);
    253   unsigned int nt=tks.getSize();
     508      cout << "dump after 1st merging " << endl;
     509      dump(beta, y, tks);
     510    }
     511  }
     512
     513  // switch on outlier rejection
     514  rho0 = 1. / nt;
     515  for(vector<vertex_t>::iterator k = y.begin(); k != y.end(); k++)
     516  {
     517    k->pk = 1.;
     518  } // democratic
     519  niter = 0;
     520  while((update2(beta, tks, y, rho0, fDzCutOff) > 1.e-8) && (niter++ < fMaxIterations))
     521  {
     522  }
    254523  if(fVerbose)
    255524  {
    256     cout << "Tracks added: " << nt << endl;
    257   }
    258   if (nt == 0) return;
    259 
    260 
    261 
    262   vertex_t vtx; // the vertex prototypes
    263   vtx.ZSize = fVertexZSize;
    264   vtx.TSize = fVertexTSize;
    265   // initialize:single vertex at infinite temperature
    266   vtx.addItem(0, 0, 1);
    267 
    268   // Fit the vertex at T=inf and return the starting temperature
    269   double beta=beta0(tks, vtx);
    270 
    271   if( fVerbose > 1 )
    272   {
    273     cout << "Cluster position at T=inf: z = " << vtx.z[0] << " mm , t = " << vtx.t[0] << " ps" << "  pk = " << vtx.pk[0] << endl;
    274     cout << Form("Beta Start = %2.1e", beta) << endl;
    275   }
    276 
    277   if( fVerbose > 10 ) plot_status(beta, vtx, tks, 0, "Ast");
    278 
    279   if( fVerbose > 2){cout << "Cool down untill reaching the temperature to finish increasing the number of vertexes" << endl;}
    280 
    281   double rho0=0.0;  // start with no outlier rejection
    282 
    283   unsigned int last_round = 0;
    284   while(last_round < 2)
    285   {
    286 
    287     unsigned int niter=0;
    288     double delta2 = 0;
    289     do  {
    290       delta2 = update(beta, tks, vtx, rho0);
    291 
    292       if( fVerbose > 10 ) plot_status(beta, vtx, tks, niter, "Bup");
    293       if (fVerbose > 3)
    294       {
    295         cout << "Update " << niter << " : " << delta2 << endl;
    296       }
    297       niter++;
    298     }
    299     while (delta2 > fD2UpdateLim &&  niter < fMaxIterations);
    300 
    301 
    302     unsigned int n_it = 0;
    303     while(merge(vtx, fD2Merge) && n_it < fMaxIterations)
    304     {
    305       unsigned int niter=0;
    306       double delta2 = 0;
    307       do  {
    308         delta2 = update(beta, tks, vtx, rho0);
    309         niter++;
    310       }
    311       while (delta2 > fD2UpdateLim &&  niter < fMaxIterations);
    312       n_it++;
    313 
    314       if( fVerbose > 10 ) plot_status(beta, vtx, tks, n_it, "Cme");
    315     }
    316 
     525    cout << "rho0=" << rho0 << " niter=" << niter << endl;
     526    dump(beta, y, tks);
     527  }
     528
     529  // merge again  (some cluster split by outliers collapse here)
     530  while(merge(y))
     531  {
     532  }
     533  if(fVerbose)
     534  {
     535    cout << "dump after 2nd merging " << endl;
     536    dump(beta, y, tks);
     537  }
     538
     539  // continue from freeze-out to Tstop (=1) without splitting, eliminate insignificant vertices
     540  while(beta <= fBetaStop)
     541  {
     542    while(purge(y, tks, rho0, beta, fDzCutOff))
     543    {
     544      niter = 0;
     545      while((update2(beta, tks, y, rho0, fDzCutOff) > 1.e-6) && (niter++ < fMaxIterations))
     546      {
     547      }
     548    }
    317549    beta /= fCoolingFactor;
    318 
    319     if( beta < fBetaStop )
    320     {
    321       split(beta, vtx, tks);
    322       if( fVerbose > 10 ) plot_status(beta, vtx, tks, 0, "Asp");
    323     }
    324     else
    325     {
    326       beta = fBetaStop;
    327       last_round++;
    328     }
    329 
    330     if(fVerbose > 3)
    331     {
    332       cout << endl << endl << " ----- Beta = " << beta << " --------" << endl;
    333       cout << "Nv: " << vtx.getSize() << endl;
    334     }
    335   }
    336 
    337   if( fVerbose > 4)
    338   {
    339     for(unsigned int k = 0; k < vtx.getSize(); k++)
    340     {
    341       cout << Form("Vertex %d next beta_c = %.3f", k, vtx.beta_c[k]) << endl;
    342     }
    343   }
    344 
    345   if(fVerbose > 2)  {cout << "Adiabatic switch on of outlayr rejection" << endl;}
    346   rho0 = 1./nt;
    347   const double N_cycles = 10;
    348   for(unsigned int f = 1; f <= N_cycles; f++)
    349   {
    350     unsigned int niter=0;
    351     double delta2 = 0;
    352     do  {
    353       delta2 = update(beta, tks, vtx, rho0 * f/N_cycles);
    354       niter++;
    355     }
    356     while (delta2 > 0.3*fD2UpdateLim &&  niter < fMaxIterations);
    357     if( fVerbose > 10 ) plot_status(beta, vtx, tks, f, "Dadout");
    358   }
    359 
    360   do {
    361     beta /= fCoolingFactor;
    362     if(beta > fBetaPurge) beta = fBetaPurge;
    363     unsigned int i_pu = 0;
    364     for(int min_trk = 2; min_trk<=fMinNTrack; min_trk++)
    365     {
    366       while( purge(vtx, tks, rho0, beta, fMinTrackProb, min_trk) )
    367       {
    368         unsigned int niter=0;
    369         double delta2 = 0;
    370         do  {
    371           delta2 = update(beta, tks, vtx, rho0);
    372           niter++;
    373         }
    374         while (delta2 > fD2UpdateLim &&  niter < fMaxIterations);
    375         if( fVerbose > 10 ) plot_status(beta, vtx, tks, i_pu, Form("Eprg%d",min_trk));
    376         i_pu++;
    377       }
    378     }
    379 
    380     unsigned int n_it = 0;
    381     while(merge(vtx, fD2Merge) && n_it < fMaxIterations)
    382     {
    383       unsigned int niter=0;
    384       double delta2 = 0;
    385       do  {
    386         delta2 = update(beta, tks, vtx, rho0);
    387         niter++;
    388       }
    389       while (delta2 > fD2UpdateLim &&  niter < fMaxIterations);
    390       n_it++;
    391 
    392       if( fVerbose > 10 ) plot_status(beta, vtx, tks, n_it, "Cme");
    393     }
    394   } while( beta < fBetaPurge );
    395 
    396 
    397   if(fVerbose > 2){cout << "Cooldown untill the limit before assigning track to vertices" << endl;}
    398   last_round = 0;
    399   while(last_round < 2)
    400   {
    401     unsigned int niter=0;
    402     double delta2 = 0;
    403     do  {
    404       delta2 = update(beta, tks, vtx, rho0);
    405       niter++;
    406       if( fVerbose > 10 ) plot_status(beta, vtx, tks, 0, "Bup");
    407     }
    408     while (delta2 > 0.3*fD2UpdateLim &&  niter < fMaxIterations);
    409 
    410     beta /= fCoolingFactor;
    411     if ( beta >= fBetaMax )
    412     {
    413       beta = fBetaMax;
    414       last_round++;
    415     }
    416   }
    417 
    418 
    419   // Build the cluster candidates
    420   for(unsigned int k = 0; k < vtx.getSize(); k++)
    421   {
     550    niter = 0;
     551    while((update2(beta, tks, y, rho0, fDzCutOff) > 1.e-6) && (niter++ < fMaxIterations))
     552    {
     553    }
     554  }
     555
     556  //   // new, one last round of cleaning at T=Tstop
     557  //   while(purge(y,tks,rho0, beta)){
     558  //     niter=0; while((update2(beta, tks,y,rho0, fDzCutOff) > 1.e-6)  && (niter++ < fMaxIterations)){  }
     559  //   }
     560
     561  if(fVerbose)
     562  {
     563    cout << "Final result, rho0=" << rho0 << endl;
     564    dump(beta, y, tks);
     565  }
     566
     567  // select significant tracks and use a TransientVertex as a container
     568  //GlobalError dummyError;
     569
     570  // ensure correct normalization of probabilities, should make double assginment reasonably impossible
     571  for(unsigned int i = 0; i < nt; i++)
     572  {
     573    tks[i].Z = rho0 * exp(-beta * (fDzCutOff * fDzCutOff));
     574    for(vector<vertex_t>::iterator k = y.begin(); k != y.end(); k++)
     575    {
     576      tks[i].Z += k->pk * exp(-beta * Eik(tks[i], *k));
     577    }
     578  }
     579
     580  for(vector<vertex_t>::iterator k = y.begin(); k != y.end(); k++)
     581  {
     582
    422583    DelphesFactory *factory = GetFactory();
    423     Candidate * candidate = factory->NewCandidate();
    424 
    425     candidate->ClusterIndex = k;
    426     candidate->Position.SetXYZT(0.0, 0.0, vtx.z[k] , vtx.t[k]*1E-9*c_light);
    427     candidate->PositionError.SetXYZT(0.0, 0.0, fVertexZSize , fVertexTSize*1E-9*c_light);
    428     candidate->SumPT2 = 0;
    429     candidate->SumPt = 0;
    430     candidate->ClusterNDF = 0;
    431 
    432     clusters.Add(candidate);
    433   }
    434 
    435 
    436   // Assign each track to the most probable vertex
    437   double Z_init = rho0 * exp(-beta * fMuOutlayer * fMuOutlayer); // Add fDtCutOff here toghether  with this
    438   vector<double> pk_exp_mBetaE = Compute_pk_exp_mBetaE(beta, vtx, tks, Z_init);
    439   for(unsigned int i = 0; i< tks.getSize(); i++)
    440   {
    441     if(tks.w[i] <= 0) continue;
    442 
    443     double p_max = 0;
    444     unsigned int k_max = 0;
    445 
    446     for(unsigned int k = 0; k < vtx.getSize(); k++)
    447     {
    448       unsigned int idx = k*nt + i;
    449       if(pk_exp_mBetaE[idx] == 0 || tks.Z[i] == 0 || vtx.pk[k] == 0)
    450       {
    451         continue;
    452       }
    453 
    454       double pv_max = vtx.pk[k] / (vtx.pk[k] + rho0 * exp(-beta * fMuOutlayer* fMuOutlayer));
    455       double p = pk_exp_mBetaE[idx] / tks.Z[i];
    456 
    457       p /= pv_max;
    458 
    459       if(p > p_max)
    460       {
    461         p_max = p;
    462         k_max = k;
    463       }
    464     }
    465 
    466     if(p_max > fMinTrackProb)
    467     {
    468       tks.tt[i]->ClusterIndex = k_max;
    469       tks.tt[i]->InitialPosition.SetT(1E-9*vtx.t[k_max]*c_light);
    470       tks.tt[i]->InitialPosition.SetZ(vtx.z[k_max]);
    471 
    472       ((Candidate *) clusters.At(k_max))->AddCandidate(tks.tt[i]);
    473       ((Candidate *) clusters.At(k_max))->SumPT2 += tks.tt[i]->Momentum.Pt()*tks.tt[i]->Momentum.Pt();
    474       ((Candidate *) clusters.At(k_max))->SumPt += tks.tt[i]->Momentum.Pt();
    475       ((Candidate *) clusters.At(k_max))->ClusterNDF += 1;
    476     }
    477     else
    478     {
    479       tks.tt[i]->ClusterIndex = -1;
    480       tks.tt[i]->InitialPosition.SetT(1E3*1000000*c_light);
    481       tks.tt[i]->InitialPosition.SetZ(1E8);
    482     }
    483     fTrackOutputArray->Add(tks.tt[i]);
    484   }
    485 
    486   if(fVerbose > 10) plot_status_end(vtx, tks);
    487 
    488 }
    489 
    490 //------------------------------------------------------------------------------
    491 // Definition of the distance metrci between track and vertex
    492 double VertexFinderDA4D::Energy(double t_z, double v_z, double dz2_o, double t_t, double v_t, double dt2_o)
    493 {
    494   return (t_z - v_z)*(t_z - v_z)* dz2_o + (t_t - v_t)*(t_t - v_t)*dt2_o;
    495 }
    496 
    497 //------------------------------------------------------------------------------
    498 // Fill tks with the input candidates array
    499 void VertexFinderDA4D::fill(tracks_t &tks)
    500 {
    501   tks.sum_w_o_dt2 = 0;
    502   tks.sum_w_o_dz2 = 0;
    503   tks.sum_w = 0;
    504 
    505   Candidate *candidate;
    506 
    507   fItInputArray->Reset();
    508   while((candidate = static_cast<Candidate*>(fItInputArray->Next())))
    509   {
    510     unsigned int discard = 0;
    511 
    512     double pt = candidate->Momentum.Pt();
    513     if(pt<fPtMin || pt>fPtMax) discard = 1;
    514 
    515     // ------------- Compute cloasest approach Z ----------------
    516     double z = candidate->DZ; // [mm]
    517 
    518     candidate->Zd = candidate->DZ; //Set the cloasest approach z
    519     if(fabs(z) > 3*fDzCutOff) discard = 1;
    520 
    521     // ------------- Compute cloasest approach T ----------------
    522     //Asumme pion mass which is the most common particle
    523     double M = 0.139570;
    524     candidate->Mass = M;
    525     double p = pt * sqrt(1 + candidate->CtgTheta*candidate->CtgTheta);
    526     double e = sqrt(p*p + M*M);
    527 
    528     double t = candidate->Position.T()*1.E9/c_light; // from [mm] to [ps]
    529     if(t <= -9999) discard = 1;                    // Means that the time information has not been added
    530 
    531     // DEBUG Here backpropagete for the whole length and not noly for z. Could improve resolution
    532     // double bz = pt * candidate->CtgTheta/e;
    533     // t += (z - candidate->Position.Z())*1E9/(c_light*bz);
    534 
    535     // Use full path Length
    536     t -= candidate->L*1E9/(c_light*p/e);
    537 
    538     candidate->Td = t*1E-9*c_light;
    539     if(fabs(t) > 3*fDtCutOff) discard = 1;
    540 
    541     // auto genp = (Candidate*) candidate->GetCandidates()->At(0);
    542     // cout << "Eta: " << candidate->Position.Eta() << endl;
    543     // cout << genp->Momentum.Pt() << " -- " << candidate->Momentum.Pt() << endl;
    544     // cout << genp->Momentum.Pz() << " -- " << candidate->Momentum.Pz() << endl;
    545     // cout << genp->Momentum.P() << " -- " << p << endl;
    546     // cout << genp->Momentum.E() << " -- " << e << endl;
    547     // cout << Form("bz_true: %.4f -- bz_gen: %.4f", genp->Momentum.Pz()/genp->Momentum.E(), bz) << endl;
    548 
    549     double dz2_o = candidate->ErrorDZ*candidate->ErrorDZ;
    550     dz2_o += fVertexZSize*fVertexZSize;
    551     // when needed add beam spot width (x-y)?? mha?
    552     dz2_o = 1/dz2_o; //Multipling is faster than dividing all the times
    553 
    554     double dt2_o = candidate->ErrorT*1.E9/c_light; // [ps]
    555     dt2_o *= dt2_o;
    556     dt2_o += fVertexTSize*fVertexTSize; // [ps^2]
    557     // Ideally we should also add the induced uncertantiy from dz, z_out, pt, ctgthetaand all the other thing used above (total around 5ps). For the moment we compensae using a high value for vertex time.
    558     dt2_o = 1/dt2_o;
    559 
    560     double w;
    561     if(fD0CutOff > 0 && candidate->ErrorD0 > 0)
    562     {
    563       double d0_sig = fabs(candidate->D0/candidate->ErrorD0);
    564       w = exp(d0_sig*d0_sig - fD0CutOff*fD0CutOff);
    565       w = 1./(1. + w);
    566       if (w < 1E-4) discard = 1;
    567     }
    568     else
    569     {
    570       w = 1;
    571     }
    572     candidate->VertexingWeight = w;
    573 
    574 
    575     if(discard)
    576     {
    577       candidate->ClusterIndex = -1;
    578       candidate->InitialPosition.SetT(1E3*1000000*c_light);
    579       candidate->InitialPosition.SetZ(1E8);
    580       fTrackOutputArray->Add(candidate);
    581     }
    582     else
    583     {
    584       tks.sum_w_o_dt2 += w * dt2_o;
    585       tks.sum_w_o_dz2 += w * dz2_o;
    586       tks.sum_w += w;
    587       tks.addItem(z, t, dz2_o, dt2_o, &(*candidate), w, candidate->PID); //PROVA: rimuovi &(*---)
    588     }
    589 
    590   }
    591 
    592   if(fVerbose > 1)
    593   {
    594     cout << "----->Filled tracks" << endl;
    595     cout << "M        z           dz        t            dt        w" << endl;
    596     for(unsigned int i = 0; i < tks.getSize(); i++)
    597     {
    598       cout << Form("%d\t%1.1e\t%1.1e\t%1.1e\t%1.1e\t%1.1e", tks.PID[i], tks.z[i], 1/sqrt(tks.dz2_o[i]), tks.t[i], 1/sqrt(tks.dt2_o[i]), tks.w[i]) << endl;
    599     }
    600   }
    601 
    602   return;
    603 }
    604 
    605 //------------------------------------------------------------------------------
    606 // Compute higher phase transition temperature
    607 double VertexFinderDA4D::beta0(tracks_t & tks, vertex_t &vtx)
    608 {
    609   if(vtx.getSize() != 1)
    610   {
    611     throw std::invalid_argument( "Unexpected number of vertices" );
    612   }
    613 
    614   unsigned int nt = tks.getSize();
    615 
    616   //Set vertex position at T=inf as the weighted average of the tracks
    617   double sum_wz = 0, sum_wt = 0;
    618   for(unsigned int i = 0; i < nt; i++)
    619   {
    620     sum_wz += tks.w[i] * tks.z[i] * tks.dz2_o[i];
    621     sum_wt += tks.w[i] * tks.t[i] * tks.dt2_o[i];
    622   }
    623   vtx.t[0] = sum_wt / tks.sum_w_o_dt2;
    624   vtx.z[0] = sum_wz / tks.sum_w_o_dz2;
    625 
    626   // Compute the posterior distribution covariance matrix elements
    627   double s_zz = 0, s_tt = 0, s_tz = 0;
    628   for(unsigned int i = 0; i < nt; i++)
    629   {
    630     double dz = (tks.z[i] - vtx.z[0]) * tks.dz_o[i];
    631     double dt = (tks.t[i] - vtx.t[0]) * tks.dt_o[i];
    632 
    633     s_zz += tks.w[i] * dz * dz;
    634     s_tt += tks.w[i] * dt * dt;
    635     s_tz += tks.w[i] * dt * dz;
    636   }
    637   s_tt /= tks.sum_w;
    638   s_zz /= tks.sum_w;
    639   s_tz /= tks.sum_w;
    640 
    641   // Copute the max eighenvalue
    642   double beta_c = (s_tt - s_zz)*(s_tt - s_zz) + 4*s_tz*s_tz;
    643   beta_c = 1. / (s_tt + s_zz + sqrt(beta_c));
    644 
    645   double out;
    646   if (beta_c < fBetaMax)
    647   {
    648     // Cool down up to a step before the phase transition
    649     out = beta_c * sqrt(fCoolingFactor);
    650   }
    651   else
    652   {
    653     out = fBetaMax * fCoolingFactor;
    654   }
    655 
    656   return out;
    657 }
    658 
    659 //------------------------------------------------------------------------------
    660 // Compute the new vertexes position and mass (probability) -- mass constrained annealing without noise
    661 // Compute and store the posterior covariance matrix elements
    662 // Returns the squared sum of changes of vertexex position normalized by the vertex size declared in the init
    663 double VertexFinderDA4D::update(double beta, tracks_t &tks, vertex_t &vtx, double rho0)
    664 {
    665   unsigned int nt = tks.getSize();
    666   unsigned int nv = vtx.getSize();
    667 
    668   //initialize sums
    669   double Z_init = rho0 * exp(-beta * fMuOutlayer * fMuOutlayer);
    670 
    671   // Compute all the energies (aka distances) and normalization partition function
    672   vector<double> pk_exp_mBetaE = Compute_pk_exp_mBetaE(beta, vtx, tks, Z_init);
    673 
    674   double sum_pk = 0;
    675   double delta2_max = 0;
    676   for (unsigned int k = 0; k < nv; k++)
    677   {
    678     // Compute the new vertex positions and masses
    679     double pk_new = 0;
    680     double sw_z = 0, sw_t = 0;
    681     // Compute the posterior covariance matrix Elements
    682     double szz = 0, stt = 0, stz = 0;
    683     double sum_wt = 0, sum_wz = 0;
    684     double sum_ptt = 0, sum_pzz = 0, sum_ptz = 0;
    685 
    686 
    687     for (unsigned int i = 0; i < nt; i++)
    688     {
    689       unsigned int idx = k*nt + i;
    690 
    691       if(pk_exp_mBetaE[idx] == 0 || tks.Z[i] == 0)
    692       {
    693         continue;
    694       }
    695 
    696       double p_ygx = pk_exp_mBetaE[idx] / tks.Z[i];      //p(y|x), Gibbs distribution
    697       if(std::isnan(p_ygx) || std::isinf(p_ygx) || p_ygx > 1)
    698       {
    699         cout << Form("%1.6e    %1.6e", pk_exp_mBetaE[idx], tks.Z[i]);
    700         throw std::invalid_argument(Form("p_ygx is %.8f", p_ygx));
    701       }
    702       pk_new += tks.w[i] * p_ygx;
    703 
    704       double wt = tks.w[i] * p_ygx * tks.dt2_o[i];
    705       sw_t += wt * tks.t[i];
    706       sum_wt += wt;
    707 
    708       double wz = tks.w[i] * p_ygx * tks.dz2_o[i];
    709       sw_z += wz * tks.z[i];
    710       sum_wz += wz;
    711 
    712       // Add the track contribution to the covariance matrix
    713       double p_xgy = p_ygx * tks.w[i] / vtx.pk[k];
    714       double dt = (tks.t[i] - vtx.t[k]) * tks.dt_o[i];
    715       double dz = (tks.z[i] - vtx.z[k]) * tks.dz_o[i];
    716 
    717       double wtt = p_xgy * tks.dt2_o[i];
    718       double wzz = p_xgy * tks.dz2_o[i];
    719       double wtz = p_xgy * tks.dt_o[i] * tks.dz_o[i];
    720 
    721       stt += wtt * dt * dt;
    722       szz += wzz * dz * dz;
    723       stz += wtz * dt * dz;
    724 
    725       sum_ptt += wtt;
    726       sum_pzz += wzz;
    727       sum_ptz += wtz;
    728     }
    729     if(pk_new == 0)
    730     {
    731       vtx.removeItem(k);
    732       k--;
    733       // throw std::invalid_argument(Form("pk_new is %.8f", pk_new));
    734     }
    735     else
    736     {
    737       pk_new /= tks.sum_w;
    738       sum_pk += pk_new;
    739 
    740       stt /= sum_ptt;
    741       szz /= sum_pzz;
    742       stz /= sum_ptz;
    743 
    744       double new_t = sw_t/sum_wt;
    745       double new_z = sw_z/sum_wz;
    746       if(std::isnan(new_z) || std::isnan(new_t))
    747       {
    748         cout << endl << endl;
    749         cout << Form("t: %.3e   /   %.3e", sw_t, sum_wt) << endl;
    750         cout << Form("z: %.3e   /   %.3e", sw_z, sum_wz) << endl;
    751         cout << "pk " << k << "  " << vtx.pk[k] << endl;
    752         throw std::invalid_argument("new_z is nan");
    753       }
    754 
    755       double z_displ = (new_z - vtx.z[k])/fVertexZSize;
    756       double t_displ = (new_t - vtx.t[k])/fVertexTSize;
    757       double delta2 = z_displ*z_displ + t_displ*t_displ;
    758 
    759       if (delta2 > delta2_max) delta2_max =  delta2;
    760 
    761       vtx.z[k] = new_z;
    762       vtx.t[k] = new_t;
    763       vtx.pk[k] = pk_new;
    764       vtx.szz[k] = szz;
    765       vtx.stt[k] = stt;
    766       vtx.stz[k] = stz;
    767     }
    768   }
    769 
    770   if(fabs((sum_pk - 1.) > 1E-4))
    771   {
    772     cout << "sum_pk " << sum_pk << endl;
    773     for (unsigned int k = 0; k < nv; k++)
    774     {
    775       cout << Form("%d: %1.4e", k, vtx.pk[k]) << endl;
    776     }
    777     throw std::invalid_argument("Sum of masses not unitary");
    778   }
    779   // if(fVerbose > 3)
    780   // {
    781   //   cout << "===Update over" << endl;
    782   //   for (unsigned int k = 0; k < nv; k++)
    783   //   {
    784   //     cout << k << endl;
    785   //     cout << "z: " << vtx.z[k] << " , t: " << vtx.t[k] << " , p: " << vtx.pk[k] << endl;
    786   //     cout << " | " << vtx.szz[k] << "   " << vtx.stz[k] << "|" << endl;
    787   //     cout << " | " << vtx.stz[k] << "   " << vtx.stt[k] << "|" << endl << endl;
    788   //   }
    789   //   cout << "=======" << endl;
    790   // }
    791 
    792   return delta2_max;
    793 }
    794 
    795 //------------------------------------------------------------------------------
    796 // Split critical vertices (beta_c < beta)
    797 // Returns true if at least one cluster was split
    798 bool VertexFinderDA4D::split(double &beta, vertex_t &vtx, tracks_t & tks)
    799 {
    800   bool split = false;
    801 
    802   auto pair_bc_k = vtx.ComputeAllBeta_c(fVerbose);
    803 
    804   // If minimum beta_c is higher than beta, no split is necessaire
    805   if( pair_bc_k.first > beta )
    806   {
    807     split = false;
    808   }
    809   else
    810   {
    811     const unsigned int nv = vtx.getSize();
    812     for(unsigned int k = 0; k < nv; k++)
    813     {
    814       if( fVerbose > 3 )
    815       {
    816         cout << "vtx " << k << "  beta_c = " << vtx.beta_c[k] << endl;
    817       }
    818       if(vtx.beta_c[k] <= beta)
    819       {
    820         double z_old = vtx.z[k];
    821         double t_old = vtx.t[k];
    822         double pk_old = vtx.pk[k];
    823 
    824         // Compute splitting direction: given by the max eighenvalue eighenvector
    825         double zn = (vtx.szz[k] - vtx.stt[k])*(vtx.szz[k] - vtx.stt[k]) + 4*vtx.stz[k]*vtx.stz[k];
    826         zn = vtx.szz[k] - vtx.stt[k] + sqrt(zn);
    827         double tn = 2*vtx.stz[k];
    828         double norm = hypot(zn, tn);
    829         tn /= norm;
    830         zn /= norm;
    831 
    832         // Estimate subcluster positions and weight
    833         double p1=0, z1=0, t1=0, wz1=0, wt1=0;
    834         double p2=0, z2=0, t2=0, wz2=0, wt2=0;
    835         const unsigned int nt = tks.getSize();
    836         for(unsigned int i=0; i<nt; ++i)
     584    candidate = factory->NewCandidate();
     585
     586    //cout<<"new vertex"<<endl;
     587    //GlobalPoint pos(0, 0, k->z);
     588    double time = k->t;
     589    double z = k->z;
     590    //vector< reco::TransientTrack > vertexTracks;
     591    //double max_track_time_err2 = 0;
     592    double mean = 0.;
     593    double expv_x2 = 0.;
     594    double normw = 0.;
     595    for(unsigned int i = 0; i < nt; i++)
     596    {
     597      const double invdt = 1.0 / std::sqrt(tks[i].dt2);
     598      if(tks[i].Z > 0)
     599      {
     600        double p = k->pk * exp(-beta * Eik(tks[i], *k)) / tks[i].Z;
     601        if((tks[i].pi > 0) && (p > 0.5))
    837602        {
    838           if (tks.Z[i] > 0)
    839           {
    840             double lr = (tks.t[i] - vtx.t[k]) * tn + (tks.z[i]-vtx.z[k]) * zn;
    841             // winner-takes-all, usually overestimates splitting
    842             double tl = lr < 0 ? 1.: 0.;
    843             double tr = 1. - tl;
    844 
    845             // soften it, especially at low T
    846             // double arg = lr * sqrt(beta * ( zn*zn*tks.dz2_o[i] + tn*tn*tks.dt2_o[i] ) );
    847             // if(abs(arg) < 20)
    848             // {
    849             //   double t = exp(-arg);
    850             //   tl = t/(t+1.);
    851             //   tr = 1/(t+1.);
    852             // }
    853 
    854             double p = vtx.pk[k] * tks.w[i];
    855             p *= exp(-beta * Energy(tks.z[i], vtx.z[k], tks.dz2_o[i], tks.t[i], vtx.t[k], tks.dt2_o[i])) / tks.Z[i];
    856             double wt = p*tks.dt2_o[i];
    857             double wz = p*tks.dz2_o[i];
    858             p1 += p*tl;  z1 += wz*tl*tks.z[i]; t1 += wt*tl*tks.t[i]; wz1 += wz*tl; wt1 += wt*tl;
    859             p2 += p*tr;  z2 += wz*tr*tks.z[i]; t2 += wt*tr*tks.t[i]; wz2 += wz*tr; wt2 += wt*tr;
    860           }
    861         }
    862 
    863         if(wz1 > 0  && wt1 > 0 && wz2 > 0 && wt2 > 0)
     603          //std::cout << "pushing back " << i << ' ' << tks[i].tt << std::endl;
     604          //vertexTracks.push_back(*(tks[i].tt)); tks[i].Z=0;
     605
     606          candidate->AddCandidate(tks[i].tt);
     607          tks[i].Z = 0;
     608
     609          mean += tks[i].t * invdt * p;
     610          expv_x2 += tks[i].t * tks[i].t * invdt * p;
     611          normw += invdt * p;
     612        } // setting Z=0 excludes double assignment
     613      }
     614    }
     615
     616    mean = mean / normw;
     617    expv_x2 = expv_x2 / normw;
     618    const double time_var = expv_x2 - mean * mean;
     619    const double crappy_error_guess = std::sqrt(time_var);
     620    /*GlobalError dummyErrorWithTime(0,
     621                                   0,0,
     622                                   0,0,0,
     623                                   0,0,0,crappy_error_guess);*/
     624    //TransientVertex v(pos, time, dummyErrorWithTime, vertexTracks, 5);
     625
     626    candidate->ClusterIndex = clusterIndex++;
     627    ;
     628    candidate->Position.SetXYZT(0.0, 0.0, z * 10.0, time * c_light);
     629
     630    // TBC - fill error later ...
     631    candidate->PositionError.SetXYZT(0.0, 0.0, 0.0, crappy_error_guess * c_light);
     632
     633    clusterIndex++;
     634    clusters.push_back(candidate);
     635  }
     636
     637  return clusters;
     638}
     639
     640//------------------------------------------------------------------------------
     641
     642static double Eik(const track_t &t, const vertex_t &k)
     643{
     644  return std::pow(t.z - k.z, 2.) / t.dz2 + std::pow(t.t - k.t, 2.) / t.dt2;
     645}
     646
     647//------------------------------------------------------------------------------
     648
     649static void dump(const double beta, const vector<vertex_t> &y, const vector<track_t> &tks0)
     650{
     651  // copy and sort for nicer printout
     652  vector<track_t> tks;
     653  for(vector<track_t>::const_iterator t = tks0.begin(); t != tks0.end(); t++)
     654  {
     655    tks.push_back(*t);
     656  }
     657  std::stable_sort(tks.begin(), tks.end(), recTrackLessZ1);
     658
     659  cout << "-----DAClusterizerInZT::dump ----" << endl;
     660  cout << " beta=" << beta << endl;
     661  cout << "                                                               z= ";
     662  cout.precision(4);
     663  for(vector<vertex_t>::const_iterator k = y.begin(); k != y.end(); k++)
     664  {
     665    //cout  <<  setw(8) << fixed << k->z;
     666  }
     667  cout << endl
     668       << "                                                               t= ";
     669  for(vector<vertex_t>::const_iterator k = y.begin(); k != y.end(); k++)
     670  {
     671    //cout  <<  setw(8) << fixed << k->t;
     672  }
     673  //cout << endl << "T=" << setw(15) << 1./beta <<"                                             Tc= ";
     674  for(vector<vertex_t>::const_iterator k = y.begin(); k != y.end(); k++)
     675  {
     676    //cout  <<  setw(8) << fixed << k->Tc ;
     677  }
     678
     679  cout << endl
     680       << "                                                              pk=";
     681  double sumpk = 0;
     682  for(vector<vertex_t>::const_iterator k = y.begin(); k != y.end(); k++)
     683  {
     684    //cout <<  setw(8) <<  setprecision(3) <<  fixed << k->pk;
     685    sumpk += k->pk;
     686  }
     687  cout << endl;
     688
     689  double E = 0, F = 0;
     690  cout << endl;
     691  cout << "----       z +/- dz        t +/- dt        ip +/-dip       pt    phi  eta    weights  ----" << endl;
     692  cout.precision(4);
     693  for(unsigned int i = 0; i < tks.size(); i++)
     694  {
     695    if(tks[i].Z > 0)
     696    {
     697      F -= log(tks[i].Z) / beta;
     698    }
     699    double tz = tks[i].z;
     700    double tt = tks[i].t;
     701    //cout <<  setw (3)<< i << ")" <<  setw (8) << fixed << setprecision(4)<<  tz << " +/-" <<  setw (6)<< sqrt(tks[i].dz2)
     702    //     << setw(8) << fixed << setprecision(4) << tt << " +/-" << setw(6) << std::sqrt(tks[i].dt2)  ;
     703
     704    double sump = 0.;
     705    for(vector<vertex_t>::const_iterator k = y.begin(); k != y.end(); k++)
     706    {
     707      if((tks[i].pi > 0) && (tks[i].Z > 0))
     708      {
     709        //double p=pik(beta,tks[i],*k);
     710        double p = k->pk * std::exp(-beta * Eik(tks[i], *k)) / tks[i].Z;
     711        if(p > 0.0001)
    864712        {
    865           t1 /= wt1;
    866           z1 /= wz1;
    867           t2 /= wt2;
    868           z2 /= wz2;
    869 
    870           if( fVerbose > 3 )
    871           {
    872             double aux = (z1-z2)*(z1-z2)/(fVertexZSize*fVertexZSize) + (t1-t2)*(t1-t2)/(fVertexTSize*fVertexTSize);
    873             cout << "weighted split:  delta = " << sqrt(aux) << endl;
    874           }
     713          //cout <<  setw (8) <<  setprecision(3) << p;
    875714        }
    876715        else
    877716        {
    878           continue;
    879           // plot_split_crush(zn, tn, vtx, tks, k);
    880           // throw std::invalid_argument( "0 division" );
     717          cout << "    .   ";
    881718        }
    882 
    883         while(vtx.NearestCluster(t1, z1) != k || vtx.NearestCluster(t2, z2) != k)
     719        E += p * Eik(tks[i], *k);
     720        sump += p;
     721      }
     722      else
     723      {
     724        cout << "        ";
     725      }
     726    }
     727    cout << endl;
     728  }
     729  cout << endl
     730       << "T=" << 1 / beta << " E=" << E << " n=" << y.size() << "  F= " << F << endl
     731       << "----------" << endl;
     732}
     733
     734//------------------------------------------------------------------------------
     735
     736static double update1(double beta, vector<track_t> &tks, vector<vertex_t> &y)
     737{
     738  //update weights and vertex positions
     739  // mass constrained annealing without noise
     740  // returns the squared sum of changes of vertex positions
     741
     742  unsigned int nt = tks.size();
     743
     744  //initialize sums
     745  double sumpi = 0;
     746  for(vector<vertex_t>::iterator k = y.begin(); k != y.end(); ++k)
     747  {
     748    k->sw = 0.;
     749    k->swz = 0.;
     750    k->swt = 0.;
     751    k->se = 0.;
     752    k->swE = 0.;
     753    k->Tc = 0.;
     754  }
     755
     756  // loop over tracks
     757  for(unsigned int i = 0; i < nt; i++)
     758  {
     759
     760    // update pik and Zi
     761    double Zi = 0.;
     762    for(vector<vertex_t>::iterator k = y.begin(); k != y.end(); ++k)
     763    {
     764      k->ei = std::exp(-beta * Eik(tks[i], *k)); // cache exponential for one track at a time
     765      Zi += k->pk * k->ei;
     766    }
     767    tks[i].Z = Zi;
     768
     769    // normalization for pk
     770    if(tks[i].Z > 0)
     771    {
     772      sumpi += tks[i].pi;
     773      // accumulate weighted z and weights for vertex update
     774      for(vector<vertex_t>::iterator k = y.begin(); k != y.end(); ++k)
     775      {
     776        k->se += tks[i].pi * k->ei / Zi;
     777        const double w = k->pk * tks[i].pi * k->ei / (Zi * (tks[i].dz2 * tks[i].dt2));
     778        k->sw += w;
     779        k->swz += w * tks[i].z;
     780        k->swt += w * tks[i].t;
     781        k->swE += w * Eik(tks[i], *k);
     782      }
     783    }
     784    else
     785    {
     786      sumpi += tks[i].pi;
     787    }
     788
     789  } // end of track loop
     790
     791  // now update z and pk
     792  double delta = 0;
     793  for(vector<vertex_t>::iterator k = y.begin(); k != y.end(); k++)
     794  {
     795    if(k->sw > 0)
     796    {
     797      const double znew = k->swz / k->sw;
     798      const double tnew = k->swt / k->sw;
     799      delta += std::pow(k->z - znew, 2.) + std::pow(k->t - tnew, 2.);
     800      k->z = znew;
     801      k->t = tnew;
     802      k->Tc = 2. * k->swE / k->sw;
     803    }
     804    else
     805    {
     806      // cout << " a cluster melted away ?  pk=" << k->pk <<  " sumw=" << k->sw <<  endl
     807      k->Tc = -1;
     808    }
     809
     810    k->pk = k->pk * k->se / sumpi;
     811  }
     812
     813  // return how much the prototypes moved
     814  return delta;
     815}
     816
     817//------------------------------------------------------------------------------
     818
     819static double update2(double beta, vector<track_t> &tks, vector<vertex_t> &y, double &rho0, double dzCutOff)
     820{
     821  // MVF style, no more vertex weights, update tracks weights and vertex positions, with noise
     822  // returns the squared sum of changes of vertex positions
     823
     824  unsigned int nt = tks.size();
     825
     826  //initialize sums
     827  for(vector<vertex_t>::iterator k = y.begin(); k != y.end(); k++)
     828  {
     829    k->sw = 0.;
     830    k->swz = 0.;
     831    k->swt = 0.;
     832    k->se = 0.;
     833    k->swE = 0.;
     834    k->Tc = 0.;
     835  }
     836
     837  // loop over tracks
     838  for(unsigned int i = 0; i < nt; i++)
     839  {
     840
     841    // update pik and Zi and Ti
     842    double Zi = rho0 * std::exp(-beta * (dzCutOff * dzCutOff)); // cut-off (eventually add finite size in time)
     843    //double Ti = 0.; // dt0*std::exp(-beta*fDtCutOff);
     844    for(vector<vertex_t>::iterator k = y.begin(); k != y.end(); k++)
     845    {
     846      k->ei = std::exp(-beta * Eik(tks[i], *k)); // cache exponential for one track at a time
     847      Zi += k->pk * k->ei;
     848    }
     849    tks[i].Z = Zi;
     850
     851    // normalization
     852    if(tks[i].Z > 0)
     853    {
     854      // accumulate weighted z and weights for vertex update
     855      for(vector<vertex_t>::iterator k = y.begin(); k != y.end(); k++)
     856      {
     857        k->se += tks[i].pi * k->ei / Zi;
     858        double w = k->pk * tks[i].pi * k->ei / (Zi * (tks[i].dz2 * tks[i].dt2));
     859        k->sw += w;
     860        k->swz += w * tks[i].z;
     861        k->swt += w * tks[i].t;
     862        k->swE += w * Eik(tks[i], *k);
     863      }
     864    }
     865
     866  } // end of track loop
     867
     868  // now update z
     869  double delta = 0;
     870  for(vector<vertex_t>::iterator k = y.begin(); k != y.end(); k++)
     871  {
     872    if(k->sw > 0)
     873    {
     874      const double znew = k->swz / k->sw;
     875      const double tnew = k->swt / k->sw;
     876      delta += std::pow(k->z - znew, 2.) + std::pow(k->t - tnew, 2.);
     877      k->z = znew;
     878      k->t = tnew;
     879      k->Tc = 2 * k->swE / k->sw;
     880    }
     881    else
     882    {
     883      // cout << " a cluster melted away ?  pk=" << k->pk <<  " sumw=" << k->sw <<  endl;
     884      k->Tc = 0;
     885    }
     886  }
     887
     888  // return how much the prototypes moved
     889  return delta;
     890}
     891
     892//------------------------------------------------------------------------------
     893
     894static bool merge(vector<vertex_t> &y)
     895{
     896  // merge clusters that collapsed or never separated, return true if vertices were merged, false otherwise
     897
     898  if(y.size() < 2) return false;
     899
     900  for(vector<vertex_t>::iterator k = y.begin(); (k + 1) != y.end(); k++)
     901  {
     902    if(std::abs((k + 1)->z - k->z) < 1.e-3 && std::abs((k + 1)->t - k->t) < 1.e-3)
     903    { // with fabs if only called after freeze-out (splitAll() at highter T)
     904      double rho = k->pk + (k + 1)->pk;
     905      if(rho > 0)
     906      {
     907        k->z = (k->pk * k->z + (k + 1)->z * (k + 1)->pk) / rho;
     908        k->t = (k->pk * k->t + (k + 1)->t * (k + 1)->pk) / rho;
     909      }
     910      else
     911      {
     912        k->z = 0.5 * (k->z + (k + 1)->z);
     913        k->t = 0.5 * (k->t + (k + 1)->t);
     914      }
     915      k->pk = rho;
     916
     917      y.erase(k + 1);
     918      return true;
     919    }
     920  }
     921
     922  return false;
     923}
     924
     925//------------------------------------------------------------------------------
     926
     927static bool merge(vector<vertex_t> &y, double &beta)
     928{
     929  // merge clusters that collapsed or never separated,
     930  // only merge if the estimated critical temperature of the merged vertex is below the current temperature
     931  // return true if vertices were merged, false otherwise
     932  if(y.size() < 2) return false;
     933
     934  for(vector<vertex_t>::iterator k = y.begin(); (k + 1) != y.end(); k++)
     935  {
     936    if(std::abs((k + 1)->z - k->z) < 2.e-3 && std::abs((k + 1)->t - k->t) < 2.e-3)
     937    {
     938      double rho = k->pk + (k + 1)->pk;
     939      double swE = k->swE + (k + 1)->swE - k->pk * (k + 1)->pk / rho * (std::pow((k + 1)->z - k->z, 2.) + std::pow((k + 1)->t - k->t, 2.));
     940      double Tc = 2 * swE / (k->sw + (k + 1)->sw);
     941
     942      if(Tc * beta < 1)
     943      {
     944        if(rho > 0)
    884945        {
    885           t1 = 0.5 * (t1 + t_old);
    886           z1 = 0.5 * (z1 + z_old);
    887           t2 = 0.5 * (t2 + t_old);
    888           z2 = 0.5 * (z2 + z_old);
     946          k->z = (k->pk * k->z + (k + 1)->z * (k + 1)->pk) / rho;
     947          k->t = (k->pk * k->t + (k + 1)->t * (k + 1)->pk) / rho;
    889948        }
    890 
    891         // Compute final distance and split if the distance is enough
    892         double delta2 = (z1-z2)*(z1-z2)/(fVertexZSize*fVertexZSize) + (t1-t2)*(t1-t2)/(fVertexTSize*fVertexTSize);
    893         if(delta2 > fD2Merge)
     949        else
    894950        {
    895           split = true;
    896           vtx.t[k] = t1;
    897           vtx.z[k] = z1;
    898           vtx.pk[k] = p1 * pk_old/(p1+p2);
    899 
    900           double new_t = t2;
    901           double new_z = z2;
    902           double new_pk = p2 * pk_old/(p1+p2);
    903 
    904           vtx.addItem(new_z, new_t, new_pk);
    905 
    906           if( fVerbose > 3 )
    907           {
    908             cout << "===Split happened on vtx " << k << endl;
    909             cout << "OLD     z: " << z_old << " , t: " << t_old << " , pk: " << pk_old << endl;
    910             cout << "NEW+    z: " << vtx.z[k] << " , t: " << vtx.t[k] << " , pk: " << vtx.pk[k] << endl;
    911             cout << "NEW-    z: " << new_z << " , t: " << new_t << " , pk: " << new_pk <<  endl;
    912           }
     951          k->z = 0.5 * (k->z + (k + 1)->z);
     952          k->t = 0.5 * (k->t + (k + 1)->t);
    913953        }
    914       }
    915     }
    916   }
    917   return split;
    918 }
    919 
    920 
    921 //------------------------------------------------------------------------------
    922 // Merge vertexes closer than declared dimensions
    923 bool VertexFinderDA4D::merge(vertex_t & vtx, double d2_merge = 2)
    924 {
    925   bool merged = false;
    926 
    927   if(vtx.getSize() < 2) return merged;
    928 
    929   bool last_merge = false;
    930   do {
    931     double min_d2 = d2_merge;
    932     unsigned int k1_min, k2_min;
    933     for(unsigned int k1 = 0; k1 < vtx.getSize(); k1++)
    934     {
    935       for(unsigned int k2 = k1+1; k2 < vtx.getSize();k2++)
    936       {
    937         double d2_tmp = vtx.DistanceSquare(k1, k2);
    938         if(d2_tmp < min_d2)
     954        k->pk = rho;
     955        k->sw += (k + 1)->sw;
     956        k->swE = swE;
     957        k->Tc = Tc;
     958        y.erase(k + 1);
     959        return true;
     960      }
     961    }
     962  }
     963
     964  return false;
     965}
     966
     967//------------------------------------------------------------------------------
     968
     969static bool purge(vector<vertex_t> &y, vector<track_t> &tks, double &rho0, const double beta, const double dzCutOff)
     970{
     971  // eliminate clusters with only one significant/unique track
     972  if(y.size() < 2) return false;
     973
     974  unsigned int nt = tks.size();
     975  double sumpmin = nt;
     976  vector<vertex_t>::iterator k0 = y.end();
     977  for(vector<vertex_t>::iterator k = y.begin(); k != y.end(); k++)
     978  {
     979    int nUnique = 0;
     980    double sump = 0;
     981    double pmax = k->pk / (k->pk + rho0 * exp(-beta * dzCutOff * dzCutOff));
     982    for(unsigned int i = 0; i < nt; i++)
     983    {
     984      if(tks[i].Z > 0)
     985      {
     986        double p = k->pk * std::exp(-beta * Eik(tks[i], *k)) / tks[i].Z;
     987        sump += p;
     988        if((p > 0.9 * pmax) && (tks[i].pi > 0))
    939989        {
    940           min_d2 = d2_tmp;
    941           k1_min = k1;
    942           k2_min = k2;
     990          nUnique++;
    943991        }
    944992      }
    945993    }
    946994
    947     if(min_d2 < d2_merge)
    948     {
    949       vtx.mergeItems(k1_min, k2_min);
    950       last_merge = true;
    951       merged = true;
    952     }
    953     else last_merge = false;
    954   } while(last_merge);
    955 
    956   return merged;
    957 }
    958 
    959 // -----------------------------------------------------------------------------
    960 // Compute all the energies and set the partition function normalization for each track
    961 vector<double> VertexFinderDA4D::Compute_pk_exp_mBetaE(double beta, vertex_t &vtx, tracks_t &tks, double Z_init)
    962 {
    963   unsigned int nt = tks.getSize();
    964   unsigned int nv = vtx.getSize();
    965 
    966   vector<double> pk_exp_mBetaE(nt * nv);
    967   for (unsigned int k = 0; k < nv; k++)
    968   {
    969     for (unsigned int i = 0; i < nt; i++)
    970     {
    971       if(k == 0) tks.Z[i] = Z_init;
    972 
    973       double aux = Energy(tks.z[i], vtx.z[k], tks.dz2_o[i], tks.t[i], vtx.t[k], tks.dt2_o[i]);
    974       aux = vtx.pk[k] * exp(-beta * aux);
    975       // if(aux < 1E-10) continue;
    976       tks.Z[i] += aux;
    977 
    978       unsigned int idx = k*nt + i;
    979       pk_exp_mBetaE[idx] = aux;
    980     }
    981   }
    982   return pk_exp_mBetaE;
    983 }
    984 
    985 //------------------------------------------------------------------------------
    986 // Eliminate clusters with only one significant/unique track
    987 bool VertexFinderDA4D::purge(vertex_t & vtx, tracks_t & tks, double & rho0, const double beta, double min_prob, double min_trk)
    988 {
    989   const unsigned int nv = vtx.getSize();
    990   const unsigned int nt = tks.getSize();
    991 
    992   if (nv < 2)
    993     return false;
    994 
    995   double sumpmin = nt;
    996   unsigned int k0 = nv;
    997 
    998   int nUnique = 0;
    999   double sump = 0;
    1000 
    1001   double Z_init = rho0 * exp(-beta * fMuOutlayer * fMuOutlayer); // Add fDtCutOff here toghether  with this
    1002   vector<double> pk_exp_mBetaE = Compute_pk_exp_mBetaE(beta, vtx, tks, Z_init);
    1003 
    1004   for (unsigned int k = 0; k < nv; ++k) {
    1005 
    1006     nUnique = 0;
    1007     sump = 0;
    1008 
    1009     double pmax = vtx.pk[k] / (vtx.pk[k] + rho0 * exp(-beta * fMuOutlayer* fMuOutlayer));
    1010     double pcut = min_prob * pmax;
    1011 
    1012     for (unsigned int i = 0; i < nt; ++i) {
    1013       unsigned int idx = k*nt + i;
    1014 
    1015       if(pk_exp_mBetaE[idx] == 0 || tks.Z[i] == 0)
    1016       {
    1017         continue;
    1018       }
    1019 
    1020       double p = pk_exp_mBetaE[idx] / tks.Z[i];
    1021       sump += p;
    1022       if( ( p > pcut ) & ( tks.w[i] > 0 ) ) nUnique++;
    1023     }
    1024 
    1025     if ((nUnique < min_trk) && (sump < sumpmin)) {
     995    if((nUnique < 2) && (sump < sumpmin))
     996    {
    1026997      sumpmin = sump;
    1027998      k0 = k;
    1028999    }
    1029 
    1030   }
    1031 
    1032   if (k0 != nv) {
    1033     if (fVerbose > 5) {
    1034       std::cout  << Form("eliminating prototype at z = %.3f mm, t = %.0f ps", vtx.z[k0], vtx.t[k0]) << " with sump=" << sumpmin
    1035                  << "  rho*nt =" << vtx.pk[k0]*nt
    1036                  << endl;
    1037     }
    1038     vtx.removeItem(k0);
     1000  }
     1001
     1002  if(k0 != y.end())
     1003  {
     1004    //cout << "eliminating prototype at " << k0->z << "," << k0->t << " with sump=" << sumpmin << endl;
     1005    //rho0+=k0->pk;
     1006    y.erase(k0);
    10391007    return true;
    1040   } else {
     1008  }
     1009  else
     1010  {
    10411011    return false;
    10421012  }
    10431013}
    10441014
    1045 
    1046 // -----------------------------------------------------------------------------
    1047 // Plot status
    1048 void VertexFinderDA4D::plot_status(double beta, vertex_t &vtx, tracks_t &tks, int n_it, const char* flag)
    1049 {
    1050   vector<int> vtx_color = {2,4,8,1,5,6,9,14,46,3};
    1051   while(vtx.getSize() > vtx_color.size()) vtx_color.push_back(40);
    1052 
    1053   vector<double> t_PV, dt_PV, z_PV, dz_PV;
    1054   vector<double> t_PU, dt_PU, z_PU, dz_PU;
    1055 
    1056   double ETot = 0;
    1057   vector<double> pk_exp_mBetaE = Compute_pk_exp_mBetaE(beta, vtx, tks, 0);
    1058 
    1059   for(unsigned int i = 0; i < tks.getSize(); i++)
    1060   {
    1061     for(unsigned int k = 0; k < vtx.getSize(); k++)
    1062     {
    1063       unsigned int idx = k*tks.getSize() + i;
    1064       if(pk_exp_mBetaE[idx] == 0) continue;
    1065 
    1066       double p_ygx = pk_exp_mBetaE[idx] / tks.Z[i];
    1067 
    1068       ETot += tks.w[i] * p_ygx * Energy(tks.z[i], vtx.z[k], tks.dz2_o[i], tks.t[i], vtx.t[k], tks.dt2_o[i]);
    1069     }
    1070 
    1071     if(tks.tt[i]->IsPU)
    1072     {
    1073       t_PU.push_back(tks.t[i]);
    1074       dt_PU.push_back(1./tks.dt_o[i]);
    1075       z_PU.push_back(tks.z[i]);
    1076       dz_PU.push_back(1./tks.dz_o[i]);
     1015//------------------------------------------------------------------------------
     1016
     1017static double beta0(double betamax, vector<track_t> &tks, vector<vertex_t> &y, const double coolingFactor)
     1018{
     1019
     1020  double T0 = 0; // max Tc for beta=0
     1021  // estimate critical temperature from beta=0 (T=inf)
     1022  unsigned int nt = tks.size();
     1023
     1024  for(vector<vertex_t>::iterator k = y.begin(); k != y.end(); k++)
     1025  {
     1026
     1027    // vertex fit at T=inf
     1028    double sumwz = 0.;
     1029    double sumwt = 0.;
     1030    double sumw = 0.;
     1031    for(unsigned int i = 0; i < nt; i++)
     1032    {
     1033      double w = tks[i].pi / (tks[i].dz2 * tks[i].dt2);
     1034      sumwz += w * tks[i].z;
     1035      sumwt += w * tks[i].t;
     1036      sumw += w;
     1037    }
     1038    k->z = sumwz / sumw;
     1039    k->t = sumwt / sumw;
     1040
     1041    // estimate Tcrit, eventually do this in the same loop
     1042    double a = 0, b = 0;
     1043    for(unsigned int i = 0; i < nt; i++)
     1044    {
     1045      double dx = tks[i].z - (k->z);
     1046      double dt = tks[i].t - (k->t);
     1047      double w = tks[i].pi / (tks[i].dz2 * tks[i].dt2);
     1048      a += w * (std::pow(dx, 2.) / tks[i].dz2 + std::pow(dt, 2.) / tks[i].dt2);
     1049      b += w;
     1050    }
     1051    double Tc = 2. * a / b; // the critical temperature of this vertex
     1052    if(Tc > T0) T0 = Tc;
     1053  } // vertex loop (normally there should be only one vertex at beta=0)
     1054
     1055  if(T0 > 1. / betamax)
     1056  {
     1057    return betamax / pow(coolingFactor, int(std::log(T0 * betamax) / std::log(coolingFactor)) - 1);
     1058  }
     1059  else
     1060  {
     1061    // ensure at least one annealing step
     1062    return betamax / coolingFactor;
     1063  }
     1064}
     1065
     1066//------------------------------------------------------------------------------
     1067
     1068static bool split(double beta, vector<track_t> &tks, vector<vertex_t> &y)
     1069{
     1070  // split only critical vertices (Tc >~ T=1/beta   <==>   beta*Tc>~1)
     1071  // an update must have been made just before doing this (same beta, no merging)
     1072  // returns true if at least one cluster was split
     1073
     1074  const double epsilon = 1e-3; // split all single vertices by 10 um
     1075  bool split = false;
     1076
     1077  // avoid left-right biases by splitting highest Tc first
     1078
     1079  std::vector<std::pair<double, unsigned int> > critical;
     1080  for(unsigned int ik = 0; ik < y.size(); ik++)
     1081  {
     1082    if(beta * y[ik].Tc > 1.)
     1083    {
     1084      critical.push_back(make_pair(y[ik].Tc, ik));
     1085    }
     1086  }
     1087  std::stable_sort(critical.begin(), critical.end(), std::greater<std::pair<double, unsigned int> >());
     1088
     1089  for(unsigned int ic = 0; ic < critical.size(); ic++)
     1090  {
     1091    unsigned int ik = critical[ic].second;
     1092    // estimate subcluster positions and weight
     1093    double p1 = 0, z1 = 0, t1 = 0, w1 = 0;
     1094    double p2 = 0, z2 = 0, t2 = 0, w2 = 0;
     1095    //double sumpi=0;
     1096    for(unsigned int i = 0; i < tks.size(); i++)
     1097    {
     1098      if(tks[i].Z > 0)
     1099      {
     1100        //sumpi+=tks[i].pi;
     1101        double p = y[ik].pk * exp(-beta * Eik(tks[i], y[ik])) / tks[i].Z * tks[i].pi;
     1102        double w = p / (tks[i].dz2 * tks[i].dt2);
     1103        if(tks[i].z < y[ik].z)
     1104        {
     1105          p1 += p;
     1106          z1 += w * tks[i].z;
     1107          t1 += w * tks[i].t;
     1108          w1 += w;
     1109        }
     1110        else
     1111        {
     1112          p2 += p;
     1113          z2 += w * tks[i].z;
     1114          t2 += w * tks[i].t;
     1115          w2 += w;
     1116        }
     1117      }
     1118    }
     1119    if(w1 > 0)
     1120    {
     1121      z1 = z1 / w1;
     1122      t1 = t1 / w1;
    10771123    }
    10781124    else
    10791125    {
    1080       t_PV.push_back(tks.t[i]);
    1081       dt_PV.push_back(1./tks.dt_o[i]);
    1082       z_PV.push_back(tks.z[i]);
    1083       dz_PV.push_back(1./tks.dz_o[i]);
    1084     }
    1085   }
    1086 
    1087 
    1088   ETot /= tks.sum_w;
    1089   fEnergy_rec.push_back(ETot);
    1090   fBeta_rec.push_back(beta);
    1091   fNvtx_rec.push_back(vtx.getSize());
    1092 
    1093   double t_min = TMath::Min(  TMath::MinElement(t_PV.size(), &t_PV[0]), TMath::MinElement(t_PU.size(), &t_PU[0])  );
    1094   t_min = TMath::Min(t_min, TMath::MinElement(vtx.getSize(), &(vtx.t[0]))  ) - fVertexTSize;
    1095   double t_max = TMath::Max(  TMath::MaxElement(t_PV.size(), &t_PV[0]), TMath::MaxElement(t_PU.size(), &t_PU[0])  );
    1096   t_max = TMath::Max(t_max, TMath::MaxElement(vtx.getSize(), &(vtx.t[0]))  ) + fVertexTSize;
    1097 
    1098   double z_min = TMath::Min(  TMath::MinElement(z_PV.size(), &z_PV[0]), TMath::MinElement(z_PU.size(), &z_PU[0])  );
    1099   z_min = TMath::Min(z_min, TMath::MinElement(vtx.getSize(), &(vtx.z[0]))  ) - 5;
    1100   double z_max = TMath::Max(  TMath::MaxElement(z_PV.size(), &z_PV[0]), TMath::MaxElement(z_PU.size(), &z_PU[0])  );
    1101   z_max = TMath::Max(z_max, TMath::MaxElement(vtx.getSize(), &(vtx.z[0]))  ) + 5;
    1102 
    1103   auto c_2Dspace = new TCanvas("c_2Dspace", "c_2Dspace", 800, 600);
    1104 
    1105   TGraphErrors* gr_PVtks = new TGraphErrors(t_PV.size(), &t_PV[0], &z_PV[0], &dt_PV[0], &dz_PV[0]);
    1106   gr_PVtks->SetTitle(Form("Clustering space - #beta = %.6f", beta));
    1107   gr_PVtks->GetXaxis()->SetTitle("t CA [ps]");
    1108   gr_PVtks->GetXaxis()->SetLimits(t_min, t_max);
    1109   gr_PVtks->GetYaxis()->SetTitle("z CA [mm]");
    1110   gr_PVtks->GetYaxis()->SetRangeUser(z_min, z_max);
    1111   gr_PVtks->SetMarkerStyle(4);
    1112   gr_PVtks->SetMarkerColor(8);
    1113   gr_PVtks->SetLineColor(8);
    1114   gr_PVtks->Draw("APE1");
    1115 
    1116   TGraphErrors* gr_PUtks = new TGraphErrors(t_PU.size(), &t_PU[0], &z_PU[0], &dt_PU[0], &dz_PU[0]);
    1117   gr_PUtks->SetMarkerStyle(3);
    1118   gr_PUtks->Draw("PE1");
    1119 
    1120   TGraph* gr_vtx = new TGraph(vtx.getSize(), &(vtx.t[0]), &(vtx.z[0]));
    1121   gr_vtx->SetMarkerStyle(28);
    1122   gr_vtx->SetMarkerColor(2);
    1123   gr_vtx->SetMarkerSize(2.);
    1124   gr_vtx->Draw("PE1");
    1125 
    1126   fItInputGenVtx->Reset();
    1127   TGraph* gr_genvtx = new TGraph(fInputGenVtx->GetEntriesFast());
    1128   Candidate *candidate;
    1129   unsigned int k = 0;
    1130   while((candidate = static_cast<Candidate*>(fItInputGenVtx->Next())))
    1131   {
    1132     gr_genvtx->SetPoint(k, candidate->Position.T()*1E9/c_light, candidate->Position.Z());
    1133     k++;
    1134   }
    1135   gr_genvtx->SetMarkerStyle(33);
    1136   gr_genvtx->SetMarkerColor(6);
    1137   gr_genvtx->SetMarkerSize(2.);
    1138   gr_genvtx->Draw("PE1");
    1139 
    1140   // auto leg = new TLegend(0.1, 0.1);
    1141   // leg->AddEntry(gr_PVtks, "PV tks", "ep");
    1142   // leg->AddEntry(gr_PUtks, "PU tks", "ep");
    1143   // leg->AddEntry(gr_vtx, "Cluster center", "p");
    1144   // leg->Draw();
    1145 
    1146   c_2Dspace->SetGrid();
    1147   c_2Dspace->SaveAs(fFigFolderPath + Form("/c_2Dspace_beta%010.0f-%s%d.png", 1E7*beta, flag, n_it));
    1148 
    1149   delete c_2Dspace;
    1150 }
    1151 
    1152 // -----------------------------------------------------------------------------
    1153 // Plot status at the end
    1154 void VertexFinderDA4D::plot_status_end(vertex_t &vtx, tracks_t &tks)
    1155 {
    1156   unsigned int nv = vtx.getSize();
    1157 
    1158   // Define colors in a meaningfull way
    1159   vector<int> MyPalette(nv);
    1160 
    1161   const int Number = 3;
    1162   double Red[Number]    = { 1.00, 0.00, 0.00};
    1163   double Green[Number]  = { 0.00, 1.00, 0.00};
    1164   double Blue[Number]   = { 1.00, 0.00, 1.00};
    1165   double Length[Number] = { 0.00, 0.50, 1.00 };
    1166   int FI = TColor::CreateGradientColorTable(Number,Length,Red,Green,Blue,nv);
    1167   for (unsigned int i=0;i<nv;i++) MyPalette[i] = FI+i;
    1168 
    1169   TCanvas * c_out = new TCanvas("c_out", "c_out", 800, 600);
    1170   double t_min = TMath::Min( TMath::MinElement(tks.getSize(), &tks.t[0]), TMath::MinElement(vtx.getSize(), &(vtx.t[0]))  ) - 2*fVertexTSize;
    1171   double t_max = TMath::Max(TMath::MaxElement(tks.getSize(), &tks.t[0]), TMath::MaxElement(vtx.getSize(), &(vtx.t[0]))  ) + 2*fVertexTSize;
    1172 
    1173   double z_min = TMath::Min( TMath::MinElement(tks.getSize(), &tks.z[0]), TMath::MinElement(vtx.getSize(), &(vtx.z[0]))  ) - 15;
    1174   double z_max = TMath::Max( TMath::MaxElement(tks.getSize(), &tks.z[0]), TMath::MaxElement(vtx.getSize(), &(vtx.z[0]))  ) + 15;
    1175 
    1176   // Draw tracks
    1177   for(unsigned int i = 0; i < tks.getSize(); i++)
    1178   {
    1179     double dt[] = {1./tks.dt_o[i]};
    1180     double dz[] = {1./tks.dz_o[i]};
    1181     TGraphErrors* gr = new TGraphErrors(1, &(tks.t[i]), &(tks.z[i]), dt, dz);
    1182 
    1183     gr->SetNameTitle(Form("gr%d",i), Form("gr%d",i));
    1184 
    1185     int marker = tks.tt[i]->IsPU? 1 : 4;
    1186     gr->SetMarkerStyle(marker);
    1187 
    1188     int idx = tks.tt[i]->ClusterIndex;
    1189     int color = idx>=0 ? MyPalette[idx] : 13;
    1190     gr->SetMarkerColor(color);
    1191     gr->SetLineColor(color);
    1192 
    1193     int line_style = idx>=0 ? 1 : 3;
    1194     gr->SetLineStyle(line_style);
    1195 
    1196     if(i==0)
    1197     {
    1198       gr->SetTitle(Form("Clustering space - Tot Vertexes = %d", nv));
    1199       gr->GetXaxis()->SetTitle("t CA [ps]");
    1200       gr->GetXaxis()->SetLimits(t_min, t_max);
    1201       gr->GetYaxis()->SetTitle("z CA [mm]");
    1202       gr->GetYaxis()->SetRangeUser(z_min, z_max);
    1203       gr->Draw("APE1");
    1204     }
    1205     else gr->Draw("PE1");
    1206   }
    1207 
    1208   // Draw vertices
    1209   for(unsigned int k = 0; k < vtx.getSize(); k++)
    1210   {
    1211     TGraph* gr = new TGraph(1, &(vtx.t[k]), &(vtx.z[k]));
    1212 
    1213     gr->SetNameTitle(Form("grv%d",k), Form("grv%d",k));
    1214 
    1215     gr->SetMarkerStyle(41);
    1216     gr->SetMarkerSize(2.);
    1217     gr->SetMarkerColor(MyPalette[k]);
    1218 
    1219     gr->Draw("P");
    1220   }
    1221 
    1222   fItInputGenVtx->Reset();
    1223   TGraph* gr_genvtx = new TGraph(fInputGenVtx->GetEntriesFast());
    1224   TGraph* gr_genPV = new TGraph(1);
    1225   Candidate *candidate;
    1226   unsigned int k = 0;
    1227   while((candidate = static_cast<Candidate*>(fItInputGenVtx->Next())))
    1228   {
    1229     if(k == 0 ) {
    1230       gr_genPV->SetPoint(k, candidate->Position.T()*1E9/c_light, candidate->Position.Z());
    1231     }
    1232     else gr_genvtx->SetPoint(k, candidate->Position.T()*1E9/c_light, candidate->Position.Z());
    1233 
    1234     k++;
    1235   }
    1236   gr_genvtx->SetMarkerStyle(20);
    1237   gr_genvtx->SetMarkerColorAlpha(kBlack, 0.8);
    1238   gr_genvtx->SetMarkerSize(.8);
    1239   gr_genvtx->Draw("PE1");
    1240   gr_genPV->SetMarkerStyle(33);
    1241   gr_genPV->SetMarkerColorAlpha(kBlack, 1);
    1242   gr_genPV->SetMarkerSize(2.5);
    1243   gr_genPV->Draw("PE1");
    1244 
    1245   // auto note =  new TLatex();
    1246   // note->DrawLatexNDC(0.5, 0.8, Form("#splitline{Vertexes Reco = %d }{Vertexes gen = %d}", vtx.getSize(), k) );
    1247 
    1248   c_out->SetGrid();
    1249   c_out->SaveAs(fFigFolderPath + Form("/c_final.root"));
    1250   delete c_out;
    1251 }
    1252 
    1253 // -----------------------------------------------------------------------------
    1254 // Plot splitting
    1255 void VertexFinderDA4D::plot_split_crush(double zn, double tn, vertex_t &vtx, tracks_t &tks, int i_vtx)
    1256 {
    1257   vector<double> t, dt, z, dz;
    1258 
    1259   for(unsigned int i = 0; i < tks.getSize(); i++)
    1260   {
    1261       t.push_back(tks.t[i]);
    1262       dt.push_back(1./tks.dt_o[i]);
    1263       z.push_back(tks.z[i]);
    1264       dz.push_back(1./tks.dz_o[i]);
    1265   }
    1266 
    1267 
    1268   double t_min = TMath::Min(TMath::MinElement(t.size(), &t[0]), TMath::MinElement(vtx.getSize(), &(vtx.t[0]))  ) - 50;
    1269   double t_max = TMath::Max(TMath::MaxElement(t.size(), &t[0]), TMath::MaxElement(vtx.getSize(), &(vtx.t[0]))  ) + 50;
    1270 
    1271   double z_min = TMath::Min(TMath::MinElement(z.size(), &z[0]), TMath::MinElement(vtx.getSize(), &(vtx.z[0]))  ) - 5;
    1272   double z_max = TMath::Max(TMath::MaxElement(z.size(), &z[0]), TMath::MaxElement(vtx.getSize(), &(vtx.z[0]))  ) + 5;
    1273 
    1274   auto c_2Dspace = new TCanvas("c_2Dspace", "c_2Dspace", 800, 600);
    1275 
    1276   TGraphErrors* gr_PVtks = new TGraphErrors(t.size(), &t[0], &z[0], &dt[0], &dz[0]);
    1277   gr_PVtks->SetTitle(Form("Clustering space"));
    1278   gr_PVtks->GetXaxis()->SetTitle("t CA [ps]");
    1279   gr_PVtks->GetXaxis()->SetLimits(t_min, t_max);
    1280   gr_PVtks->GetYaxis()->SetTitle("z CA [mm]");
    1281   gr_PVtks->GetYaxis()->SetRangeUser(z_min, z_max);
    1282   gr_PVtks->SetMarkerStyle(4);
    1283   gr_PVtks->SetMarkerColor(1);
    1284   gr_PVtks->SetLineColor(1);
    1285   gr_PVtks->Draw("APE1");
    1286 
    1287   TGraph* gr_vtx = new TGraph(1, &(vtx.t[i_vtx]), &(vtx.z[i_vtx]));
    1288   gr_vtx->SetMarkerStyle(28);
    1289   gr_vtx->SetMarkerColor(2);
    1290   gr_vtx->SetMarkerSize(2.);
    1291   gr_vtx->Draw("PE1");
    1292 
    1293   double t_pos[] = {vtx.t[i_vtx], vtx.t[i_vtx]+100};
    1294   double t_neg[] = {vtx.t[i_vtx], vtx.t[i_vtx]-100};
    1295   double z_pos[] = {vtx.z[i_vtx], vtx.z[i_vtx]+(zn/tn)*100};
    1296   double z_neg[] = {vtx.z[i_vtx], vtx.z[i_vtx]-(zn/tn)*100};
    1297 
    1298   TGraph* gr_pos = new TGraph(2, &t_pos[0], &z_pos[0]);
    1299   gr_pos->SetLineColor(8);
    1300   gr_pos->SetMarkerColor(8);
    1301   gr_pos->Draw("PL");
    1302   TGraph* gr_neg = new TGraph(2, &t_neg[0], &z_neg[0]);
    1303   gr_neg->SetLineColor(4);
    1304   gr_neg->SetMarkerColor(4);
    1305   gr_neg->Draw("PL");
    1306 
    1307 
    1308   c_2Dspace->SetGrid();
    1309   c_2Dspace->SaveAs(fFigFolderPath + Form("/crush_splitting.png"));
    1310 
    1311   delete c_2Dspace;
    1312 }
     1126      z1 = y[ik].z - epsilon;
     1127      t1 = y[ik].t - epsilon;
     1128    }
     1129    if(w2 > 0)
     1130    {
     1131      z2 = z2 / w2;
     1132      t2 = t2 / w2;
     1133    }
     1134    else
     1135    {
     1136      z2 = y[ik].z + epsilon;
     1137      t2 = y[ik].t + epsilon;
     1138    }
     1139
     1140    // reduce split size if there is not enough room
     1141    if((ik > 0) && (y[ik - 1].z >= z1))
     1142    {
     1143      z1 = 0.5 * (y[ik].z + y[ik - 1].z);
     1144      t1 = 0.5 * (y[ik].t + y[ik - 1].t);
     1145    }
     1146    if((ik + 1 < y.size()) && (y[ik + 1].z <= z2))
     1147    {
     1148      z2 = 0.5 * (y[ik].z + y[ik + 1].z);
     1149      t2 = 0.5 * (y[ik].t + y[ik + 1].t);
     1150    }
     1151
     1152    // split if the new subclusters are significantly separated
     1153    if((z2 - z1) > epsilon || std::abs(t2 - t1) > epsilon)
     1154    {
     1155      split = true;
     1156      vertex_t vnew;
     1157      vnew.pk = p1 * y[ik].pk / (p1 + p2);
     1158      y[ik].pk = p2 * y[ik].pk / (p1 + p2);
     1159      vnew.z = z1;
     1160      vnew.t = t1;
     1161      y[ik].z = z2;
     1162      y[ik].t = t2;
     1163      y.insert(y.begin() + ik, vnew);
     1164
     1165      // adjust remaining pointers
     1166      for(unsigned int jc = ic; jc < critical.size(); jc++)
     1167      {
     1168        if(critical[jc].second > ik)
     1169        {
     1170          critical[jc].second++;
     1171        }
     1172      }
     1173    }
     1174  }
     1175
     1176  //  stable_sort(y.begin(), y.end(), clusterLessZ);
     1177  return split;
     1178}
     1179
     1180//------------------------------------------------------------------------------
     1181
     1182void splitAll(vector<vertex_t> &y)
     1183{
     1184
     1185  const double epsilon = 1e-3; // split all single vertices by 10 um
     1186  const double zsep = 2 * epsilon; // split vertices that are isolated by at least zsep (vertices that haven't collapsed)
     1187  const double tsep = 2 * epsilon; // check t as well
     1188
     1189  vector<vertex_t> y1;
     1190
     1191  for(vector<vertex_t>::iterator k = y.begin(); k != y.end(); k++)
     1192  {
     1193    if(((k == y.begin()) || (k - 1)->z < k->z - zsep) && (((k + 1) == y.end()) || (k + 1)->z > k->z + zsep))
     1194    {
     1195      // isolated prototype, split
     1196      vertex_t vnew;
     1197      vnew.z = k->z - epsilon;
     1198      vnew.t = k->t - epsilon;
     1199      (*k).z = k->z + epsilon;
     1200      (*k).t = k->t + epsilon;
     1201      vnew.pk = 0.5 * (*k).pk;
     1202      (*k).pk = 0.5 * (*k).pk;
     1203      y1.push_back(vnew);
     1204      y1.push_back(*k);
     1205    }
     1206    else if(y1.empty() || (y1.back().z < k->z - zsep) || (y1.back().t < k->t - tsep))
     1207    {
     1208      y1.push_back(*k);
     1209    }
     1210    else
     1211    {
     1212      y1.back().z -= epsilon;
     1213      y1.back().t -= epsilon;
     1214      k->z += epsilon;
     1215      k->t += epsilon;
     1216      y1.push_back(*k);
     1217    }
     1218  } // vertex loop
     1219
     1220  y = y1;
     1221}
  • modules/VertexFinderDA4D.h

    r83ee320 r2d7ff18  
    66 *  Cluster vertices from tracks using deterministic annealing and timing information
    77 *
    8  *  Author O. Cerri
     8 *  \authors M. Selvaggi, L. Gray
    99 *
    1010 */
     
    1313
    1414#include <vector>
    15 #include <iostream>
    1615
    1716class TObjArray;
     
    2120class VertexFinderDA4D: public DelphesModule
    2221{
    23   public:
     22public:
     23  VertexFinderDA4D();
     24  ~VertexFinderDA4D();
    2425
    25     class tracks_t
    26     {
    27       public:
    28         std::vector<double> z;      // z-coordinate at point of closest approach to the beamline [mm]
    29         std::vector<double> r;      // z-coordinate at point of closest approach to the beamline [mm]
     26  void Init();
     27  void Process();
     28  void Finish();
    3029
    31         std::vector<double> t;      // t-coordinate at point of closest approach to the beamline  [ps]
     30  void clusterize(const TObjArray &tracks, TObjArray &clusters);
     31  std::vector<Candidate *> vertices();
    3232
    33         std::vector<double> dz2_o;    //1 over the squared error of z(pca)
    34         std::vector<double> dz_o;
    35         std::vector<double> dt2_o;    //1 over the squared error of t(pca)
    36         std::vector<double> dt_o;
     33private:
     34  Bool_t fVerbose;
     35  Double_t fMinPT;
    3736
    38         std::vector<Candidate*> tt; // a pointer to the Candidate Track
    39         std::vector<double> Z;      // Normalization of P(y|x) = p_k * exp(-beta*E_ik)/Z_i
     37  Float_t fVertexSpaceSize;
     38  Float_t fVertexTimeSize;
     39  Bool_t fUseTc;
     40  Float_t fBetaMax;
     41  Float_t fBetaStop;
     42  Double_t fCoolingFactor;
     43  Int_t fMaxIterations;
     44  Double_t fDzCutOff;
     45  Double_t fD0CutOff;
     46  Double_t fDtCutOff; // for when the beamspot has time
    4047
    41         std::vector<double> w;     // track weight
     48  TObjArray *fInputArray;
     49  TIterator *fItInputArray;
    4250
    43         // std::vector<double> pt;
    44         // std::vector<double> pz;
     51  TObjArray *fOutputArray;
     52  TObjArray *fVertexOutputArray;
    4553
    46         std::vector<int> PID;
    47 
    48         double sum_w_o_dz2 = 0;
    49         double sum_w_o_dt2 = 0;
    50         double sum_w = 0;
    51 
    52         tracks_t(){}
    53         ~tracks_t(){}
    54 
    55         void addItem( double new_z, double new_t, double new_dz2_o, double new_dt2_o, Candidate * new_tt, double new_w, int new_PID)
    56         {
    57           z.push_back( new_z );
    58           t.push_back( new_t );
    59           dz2_o.push_back( new_dz2_o );
    60           dz_o.push_back( sqrt(new_dz2_o) );
    61           dt2_o.push_back( new_dt2_o );
    62           dt_o.push_back( sqrt(new_dt2_o) );
    63           tt.push_back( new_tt );
    64 
    65           w.push_back( new_w );
    66           Z.push_back( 1.0 );
    67 
    68           PID.push_back(new_PID);
    69         }
    70 
    71         unsigned int getSize()
    72         {
    73           return z.size();
    74         }
    75 
    76     };
    77 
    78     class vertex_t
    79     {
    80       public:
    81         std::vector<double> z;  //           z coordinate
    82         std::vector<double> t;  //           t coordinate
    83         std::vector<double> pk; //          vertex weight for "constrained" clustering
    84 
    85         // Elements of the covariance matrix of the posterior distribution
    86         std::vector<double> szz, stt, stz;
    87         std::vector<double> beta_c;
    88 
    89         double ZSize;
    90         double TSize;
    91 
    92         // Used in the tracks-cluster assignment
    93         double sum_pt;
    94         std::vector<unsigned int> i_tracks;
    95 
    96 
    97         vertex_t(){}
    98         ~vertex_t(){}
    99 
    100         void addItem( double new_z, double new_t, double new_pk)
    101         {
    102           z.push_back( new_z);
    103           t.push_back( new_t);
    104           pk.push_back( new_pk);
    105 
    106           szz.push_back(0);
    107           stt.push_back(0);
    108           stz.push_back(0);
    109           beta_c.push_back(0);
    110         }
    111 
    112         void removeItem( unsigned int i )
    113         {
    114           z.erase( z.begin() + i );
    115           t.erase( t.begin() + i );
    116           pk.erase( pk.begin() + i );
    117 
    118           szz.erase(szz.begin() + i);
    119           stt.erase(stt.begin() + i);
    120           stz.erase(stz.begin() + i);
    121           beta_c.erase(beta_c.begin() + i);
    122         }
    123 
    124         void mergeItems(unsigned int k1, unsigned int k2)
    125         {
    126           double new_pk = pk[k1] + pk[k2];
    127           double new_z = (z[k1]*pk[k1] + z[k2]*pk[k2])/new_pk;
    128           double new_t = (t[k1]*pk[k1] + t[k2]*pk[k2])/new_pk;
    129 
    130           removeItem(k2);
    131           z[k1] = new_z;
    132           t[k1] = new_t;
    133           pk[k1] = new_pk;
    134         }
    135 
    136         unsigned int getSize() const
    137         {
    138           return z.size();
    139         }
    140 
    141         double DistanceSquare(unsigned int k1, unsigned int k2)
    142         {
    143           double dz = (z[k1] - z[k2])/ZSize;
    144           double dt = (t[k1] - t[k2])/TSize;
    145 
    146           return dz*dz + dt*dt;
    147         }
    148 
    149         unsigned int NearestCluster(double t_, double z_)
    150         {
    151           unsigned int k_min = 0;
    152           double d2_min = 0;
    153 
    154           for(unsigned int k = 0; k < getSize(); k++)
    155           {
    156             double dt = (t[k] - t_)/TSize;
    157             double dz = (z[k] - z_)/ZSize;
    158             double d2 = dt*dt + dz*dz;
    159             if(k == 0 || d2 < d2_min)
    160             {
    161               k_min = k;
    162               d2_min = d2;
    163             }
    164           }
    165 
    166           return k_min;
    167         }
    168 
    169         std::pair<double, unsigned int> ComputeAllBeta_c(unsigned int verbose = 0)
    170         {
    171           unsigned int nv = getSize();
    172           unsigned int k_min = 0;
    173           double beta_c_min = 0;
    174           for(unsigned int k = 0; k < nv; k++)
    175           {
    176             if(szz[k] == 0 || stt[k] == 0)
    177             {
    178               beta_c[k] = 1000;
    179               if(verbose>5)
    180               {
    181                 std::cout << std::endl << Form("Varianca too small! beta_c set to 1000\nVertex %d:  t=%1.2e, z=%1.2e, pk=%1.2e, szz=%1.2e, stt=%1.2e, stz=%1.2e", k, t[k], z[k], pk[k], szz[k], stt[k], stz[k]);
    182                 // throw std::invalid_argument( "Attempting to compute beta c for uninitialized vertex" );
    183               }
    184             }
    185 
    186             double aux = (stt[k] - szz[k])*(stt[k] - szz[k]) + 4*stz[k]*stz[k];
    187             aux = 1. / (stt[k] + szz[k] + sqrt(aux));
    188 
    189             if(k == 0 || aux < beta_c_min)
    190             {
    191               beta_c_min = aux;
    192               k_min = k;
    193             }
    194 
    195             beta_c[k] = aux;
    196           }
    197 
    198           std::pair<double, unsigned int> out(beta_c_min, k_min);
    199           return out;
    200         }
    201     };
    202 
    203     VertexFinderDA4D();
    204     ~VertexFinderDA4D();
    205 
    206     void Init();
    207     void Process();
    208     void Finish();
    209 
    210     void clusterize(TObjArray &clusters);
    211 
    212     // Define the distance metric between tracks and vertices
    213     double Energy(double t_z, double v_z, double dz2_o, double t_t, double v_t, double dt2_o);
    214 
    215     // Fill the tracks structure from the input array
    216     void fill(tracks_t &tks);
    217 
    218     // Compute higher phase transition temperature
    219     double beta0(tracks_t & tks, vertex_t &vtx);
    220 
    221     // Compute the new vertexes position and mass
    222     double update(double beta, tracks_t &tks, vertex_t &vtx, double rho0);
    223 
    224     // If a vertex has beta_c lower than beta, split it
    225     bool split(double &beta,  vertex_t & vtx, tracks_t & tks);
    226 
    227     // Merge vertexes closer than declared dimensions
    228     bool merge(vertex_t & vtx, double d2_merge);
    229 
    230     // Eliminate clusters with only one significant/unique track
    231     bool purge(vertex_t & vtx, tracks_t & tks, double & rho0, const double beta, double min_prob, double min_trk);
    232 
    233     // Compute all the energies and set the partition function normalization for each track
    234     std::vector<double> Compute_pk_exp_mBetaE(double beta, vertex_t &vtx, tracks_t &tks, double Z_init);
    235 
    236     // Plot status of tracks and Vertices
    237     void plot_status(double beta, vertex_t &vtx, tracks_t &tks, int n_it = 0, const char* flag ="");
    238 
    239     // Plot status at the end of the fitting
    240     void plot_status_end(vertex_t &vtx, tracks_t &tks);
    241 
    242     // Plot Crush
    243     void plot_split_crush(double zn, double tn, vertex_t &vtx, tracks_t &tks, int i_vtx);
    244 
    245 
    246   private:
    247 
    248     unsigned int fVerbose;
    249 
    250     UInt_t fMaxIterations;
    251     UInt_t fMaxVertexNumber;
    252 
    253     Float_t fBetaMax;
    254     Float_t fBetaStop;
    255     Float_t fBetaPurge;
    256 
    257 
    258     Float_t fVertexZSize;
    259     Float_t fVertexTSize;
    260 
    261     Double_t fCoolingFactor;
    262 
    263     Double_t fDzCutOff;
    264     Double_t fD0CutOff;
    265     Double_t fDtCutOff;
    266     Double_t fPtMin;
    267     Double_t fPtMax;
    268 
    269     Double_t fD2UpdateLim;
    270     Double_t fD2Merge;
    271     Double_t fMuOutlayer;
    272     Double_t fMinTrackProb;
    273     Int_t fMinNTrack;
    274 
    275     TObjArray *fInputArray;
    276     TIterator *fItInputArray;
    277 
    278     TObjArray *fTrackOutputArray;
    279     TObjArray *fVertexOutputArray;
    280 
    281     ClassDef(VertexFinderDA4D, 1)
    282 
    283     //Used to keep track of number of verices in verbose mode
    284     std::vector<double> fEnergy_rec;
    285     std::vector<double> fBeta_rec;
    286     std::vector<double> fNvtx_rec;
    287 
    288     // Debug purpose only
    289     TObjArray *fInputGenVtx;
    290     TIterator *fItInputGenVtx;
    291 
    292     TString fFigFolderPath = "";
     54  ClassDef(VertexFinderDA4D, 1)
    29355};
    29456
  • readers/DelphesPythia8.cpp

    r83ee320 r2d7ff18  
    122122
    123123    pdgParticle = pdg->GetParticle(pid);
    124 
    125     if(pdgParticle)
    126     {
    127       candidate->Charge = int(pdgParticle->Charge()/3.0);
    128     }
    129     else if(abs(pid) == 1000612) candidate->Charge = TMath::Sign(1, pid);
    130     else if(abs(pid) == 1000622) candidate->Charge = 0;
    131     else if(abs(pid) == 1000632) candidate->Charge = TMath::Sign(1, pid);
    132     else if(abs(pid) == 1000642) candidate->Charge = 0;
    133     else if(abs(pid) == 1000652) candidate->Charge = TMath::Sign(1, pid);
    134     else if(abs(pid) == 1006113) candidate->Charge = 0;
    135     else if(abs(pid) == 1006211) candidate->Charge = TMath::Sign(1, pid);
    136     else if(abs(pid) == 1006213) candidate->Charge = TMath::Sign(1, pid);
    137     else if(abs(pid) == 1006223) candidate->Charge = TMath::Sign(2, pid);
    138     else if(abs(pid) == 1006311) candidate->Charge = 0;
    139     else if(abs(pid) == 1006313) candidate->Charge = 0;
    140     else if(abs(pid) == 1006321) candidate->Charge = TMath::Sign(1, pid);
    141     else if(abs(pid) == 1006323) candidate->Charge = TMath::Sign(1, pid);
    142     else if(abs(pid) == 1006333) candidate->Charge = 0;
    143     else {
    144       candidate->Charge = -999;
    145       cout << "[WARNING] Unrecognised particle. PID: " << pid << endl;
    146     }
    147 
     124    candidate->Charge = pdgParticle ? Int_t(pdgParticle->Charge() / 3.0) : -999;
    148125    candidate->Mass = mass;
    149126
     
    151128
    152129    candidate->Position.SetXYZT(x, y, z, t);
     130
    153131    allParticleOutputArray->Add(candidate);
    154132
    155     if(!pdgParticle && (abs(pid) > 1006333 || abs(pid) < 1000612) )
    156       continue;
     133    if(!pdgParticle) continue;
    157134
    158135    if(status == 1)
Note: See TracChangeset for help on using the changeset viewer.