#! /bin/csh -f

set number_max=1

set i=-1
while ($i < $number_max)
@ i++

cd /afs/cern.ch/user/g/giamman/scratch0/fastsim/ecal

set workdir=dirTunePar2_$i
echo creating directory $workdir
rm -r $workdir
mkdir $workdir
cd $workdir
set SCRAM_ARCH=slc5_amd64_gcc462 
scram project CMSSW CMSSW_6_0_0_pre1
cd CMSSW_6_0_0_pre1/src
pwd

cvs co FastSimulation/CaloRecHitsProducer
cvs co Validation/RecoEgamma

cd FastSimulation/CaloRecHitsProducer/python

rm CaloRecHits_cff.py
cat > CaloRecHits_cff.py <<EOF
import FWCore.ParameterSet.Config as cms

#To include the ECAL RecHit containment corrections (the famous 0.97 factor)
from SimCalorimetry.EcalSimProducers.ecalNotContainmentSim_cff import *

# This includes is needed for the ECAL digis
from SimCalorimetry.EcalTrigPrimProducers.ecalTriggerPrimitiveDigis_cff import *

from SimCalorimetry.HcalTrigPrimProducers.hcaltpdigi_cff import *
from SimCalorimetry.HcalSimProducers.hcalSimParameters_cfi import *

# This includes is needed for the ECAL digis
from SimCalorimetry.EcalTrigPrimProducers.ecalTriggerPrimitiveDigis_cff import *

ecalRecHit = cms.EDProducer("CaloRecHitsProducer",
                            InputRecHitCollectionTypes = cms.vuint32(2, 3),
                            OutputRecHitCollections = cms.vstring('EcalRecHitsEB', 
                                                                  'EcalRecHitsEE'),
                            doDigis = cms.bool(False),
                            doMiscalib = cms.bool(False),

                            RecHitsFactory = cms.PSet(
                                                       ECALBarrel = cms.PSet(
                                                       Noise = cms.double(-1.),
                                                       NoiseADC = cms.double(1.054),
                                                       HighNoiseParameters = cms.vdouble(2.56,0.${i}1,0.0086),
                                                       Threshold = cms.double(0.1),
						       SRThreshold = cms.double(1.),
                                                       Refactor = cms.double(1.),
                                                       Refactor_mean = cms.double(1.),
                                                       MixedSimHits = cms.InputTag("mix","famosSimHitsEcalHitsEB"),
                                                       ContFact = cms.PSet(ecal_notCont_sim)),
                                                       
                                                       ECALEndcap = cms.PSet(
                                                       Noise = cms.double(-1.),
                                                       NoiseADC = cms.double(2.32),
                                                       HighNoiseParameters = cms.vdouble(4.77,1.${i}5,2.7,5.1),
                                                       Threshold = cms.double(.32), 
                                                       SRThreshold = cms.double(1.),
                                                       Refactor = cms.double(1.),
                                                       Refactor_mean = cms.double(1.),
                                                       MixedSimHits = cms.InputTag("mix","famosSimHitsEcalHitsEE"),
                                                       ContFact = cms.PSet(ecal_notCont_sim)),
                                                       ))


ecalPreshowerRecHit =  cms.EDProducer("CaloRecHitsProducer",
                                      InputRecHitCollectionTypes = cms.vuint32(1),
                                      OutputRecHitCollections = cms.vstring('EcalRecHitsES'),
                                      doDigis = cms.bool(False),
                                      doMiscalib = cms.bool(False),

                                      RecHitsFactory = cms.PSet(
                                                       ECALPreshower = cms.PSet(
                                                       Noise = cms.double(1.5e-05),
                                                       Threshold = cms.double(4.5e-05),
                                                       MixedSimHits = cms.InputTag("mix","famosSimHitsEcalHitsES"))))


hbhereco = cms.EDProducer("CaloRecHitsProducer",
                          InputRecHitCollectionTypes = cms.vuint32(4),
                          OutputRecHitCollections = cms.vstring(""),
                          doDigis = cms.bool(False),
                          doMiscalib = cms.bool(False),
                          
                          RecHitsFactory = cms.PSet(
                                           HCAL = cms.PSet(
                                           Noise = cms.vdouble(-1.,-1.),
                                           NoiseCorrectionFactor = cms.vdouble(1.39,1.32),
                                           Threshold = cms.vdouble(-1.,-1.),
                                           MixedSimHits = cms.InputTag("mix","famosSimHitsHcalHits"),
                                           EnableSaturation = cms.bool(True),
                                           Refactor = cms.double(1.),
                                           Refactor_mean = cms.double(1.),
                                           fileNameHcal = cms.string('hcalmiscalib_0.0.xml'))))


horeco = cms.EDProducer("CaloRecHitsProducer",
                          InputRecHitCollectionTypes = cms.vuint32(5),
                          OutputRecHitCollections = cms.vstring(""),
                          doDigis = cms.bool(False),
                          doMiscalib = cms.bool(False),
                          
                          RecHitsFactory = cms.PSet(
                                           HCAL = cms.PSet(
                                           Noise = cms.vdouble(-1.),
                                           NoiseCorrectionFactor = cms.vdouble(3.),#1.17 to be tuned
                                           Threshold = cms.vdouble(-1.5),
                                           MixedSimHits = cms.InputTag("mix","famosSimHitsHcalHits"),
                                           EnableSaturation = cms.bool(True),
                                           Refactor = cms.double(1.),
                                           Refactor_mean = cms.double(1.),
                                           fileNameHcal = cms.string('hcalmiscalib_0.0.xml'))))

hfreco = cms.EDProducer("CaloRecHitsProducer",
                        InputRecHitCollectionTypes = cms.vuint32(6),
                        OutputRecHitCollections = cms.vstring(""),
                        doDigis = cms.bool(False),
                        doMiscalib = cms.bool(False),
                        
                        RecHitsFactory = cms.PSet(
                                           HCAL = cms.PSet(
                                           Noise = cms.vdouble(-1.),
                                           NoiseCorrectionFactor = cms.vdouble(2.51),
                                           Threshold = cms.vdouble(-0.5),
                                           MixedSimHits = cms.InputTag("mix","famosSimHitsHcalHits"),
                                           EnableSaturation = cms.bool(True),
                                           Refactor = cms.double(1.),
                                           Refactor_mean = cms.double(1.),
                                           fileNameHcal = cms.string('hcalmiscalib_0.0.xml'))))


simHcalTriggerPrimitiveDigis.peakFilter = False
simHcalTriggerPrimitiveDigis.inputLabel =  cms.VInputTag(cms.InputTag('hbhereco'), cms.InputTag('hfreco'))
'hbhereco'
simEcalTriggerPrimitiveDigis.Famos = True
simEcalTriggerPrimitiveDigis.Label = 'ecalRecHit'

caloRecHits = cms.Sequence(ecalRecHit*ecalPreshowerRecHit*hbhereco*horeco*hfreco)
EOF

cd -
scram b -j 8

cat > RelValZEE_START52_V4_FastSim.py <<EOF
# using:
# Source: /cvs/CMSSW/CMSSW/Configuration/PyReleaseValidation/python/ConfigBuilder.py,v
# with command line options: ZEE_8TeV_cfi --conditions auto:startup -s GEN,FASTSIM,HLT:GRun,VALIDATION --datatier GEN-SIM-DIGI-RECO -n 10 --relval 100000,500 --eventcontent FEVTDEBUGHLT --no_exec --python_filename RelValZEE_START52_V4_FastSim.py
import FWCore.ParameterSet.Config as cms

process = cms.Process('HLT')

# import of standard configurations
process.load('Configuration.StandardSequences.Services_cff')
process.load('SimGeneral.HepPDTESSource.pythiapdt_cfi')
process.load('FWCore.MessageService.MessageLogger_cfi')
process.load('FastSimulation.Configuration.EventContent_cff')
process.load('FastSimulation.PileUpProducer.PileUpSimulator_NoPileUp_cff')
process.load('FastSimulation.Configuration.Geometries_START_cff')
process.load('Configuration.StandardSequences.MagneticField_38T_cff')
process.load('Configuration.StandardSequences.Generator_cff')
process.load('GeneratorInterface.Core.genFilterSummary_cff')
process.load('FastSimulation.Configuration.FamosSequences_cff')
process.load('IOMC.EventVertexGenerators.VtxSmearedParameters_cfi')
process.load('FastSimulation.Configuration.HLT_GRun_cff')
process.load('FastSimulation.Configuration.Validation_cff')
process.load('Configuration.StandardSequences.EndOfProcess_cff')
process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')

process.maxEvents = cms.untracked.PSet(
#        input = cms.untracked.int32(3000)
        input = cms.untracked.int32(30)
        )

# Input source
process.source = cms.Source("EmptySource")

process.options = cms.untracked.PSet(

    )


# Output definition

process.FEVTDEBUGHLToutput = cms.OutputModule("PoolOutputModule",
                                                  splitLevel = cms.untracked.int32(0),
                                                  eventAutoFlushCompressedSize = cms.untracked.int32(5242880),
                                                  outputCommands = process.FEVTDEBUGHLTEventContent.outputCommands,
                                                  fileName = cms.untracked.string('/tmp/giamman/ZEE_${workdir}.root'),
                                                  dataset = cms.untracked.PSet(
            filterName = cms.untracked.string(''),
                    dataTier = cms.untracked.string('GEN-SIM-DIGI-RECO')
                ),
                                                  SelectEvents = cms.untracked.PSet(
            SelectEvents = cms.vstring('generation_step')
                )
                                              )

# Additional output definition

# Other statements
process.famosSimHits.SimulateCalorimetry = True
process.famosSimHits.SimulateTracking = True
process.simulation = cms.Sequence(process.simulationWithFamos)
process.HLTEndSequence = cms.Sequence(process.reconstructionWithFamos)
process.Realistic7TeV2011CollisionVtxSmearingParameters.type = cms.string("BetaFunc")
process.famosSimHits.VertexGenerator = process.Realistic7TeV2011CollisionVtxSmearingParameters
process.famosPileUp.VertexGenerator = process.Realistic7TeV2011CollisionVtxSmearingParameters
process.GlobalTag.globaltag = 'START52_V4::All'

process.generator = cms.EDFilter("Pythia6GeneratorFilter",
                                 pythiaPylistVerbosity = cms.untracked.int32(0),
                                 filterEfficiency = cms.untracked.double(1.0),
                                 pythiaHepMCVerbosity = cms.untracked.bool(False),
                                 comEnergy = cms.double(8000.0),
                                 maxEventsToPrint = cms.untracked.int32(0),
                                 PythiaParameters = cms.PSet(
    pythiaUESettings = cms.vstring('MSTU(21)=1     ! Check on possible errors during program execution',
                                   'MSTJ(22)=2     ! Decay those unstable particles',
                                   'PARJ(71)=10 .  ! for which ctau  10 mm',
                                   'MSTP(33)=0     ! no K factors in hard cross sections',
                                   'MSTP(2)=1      ! which order running alphaS',
                                   'MSTP(51)=10042 ! structure function chosen (external PDF CTEQ6L1)',
                                   'MSTP(52)=2     ! work with LHAPDF',
                                   'PARP(82)=1.921 ! pt cutoff for multiparton interactions',
                                   'PARP(89)=1800. ! sqrts for which PARP82 is set',
                                   'PARP(90)=0.227 ! Multiple interactions: rescaling power',
                                   'MSTP(95)=6     ! CR (color reconnection parameters)',
                                   'PARP(77)=1.016 ! CR',
                                   'PARP(78)=0.538 ! CR',
                                   'PARP(80)=0.1   ! Prob. colored parton from BBR',
                                   'PARP(83)=0.356 ! Multiple interactions: matter distribution parameter',
                                   'PARP(84)=0.651 ! Multiple interactions: matter distribution parameter',
                                   'PARP(62)=1.025 ! ISR cutoff',
                                   'MSTP(91)=1     ! Gaussian primordial kT',
                                   'PARP(93)=10.0  ! primordial kT-max',
                                   'MSTP(81)=21    ! multiple parton interactions 1 is Pythia default',
                                   'MSTP(82)=4     ! Defines the multi-parton model'),
    processParameters = cms.vstring('MSEL         = 11 ',
                                    'MDME( 174,1) = 0    !Z decay into d dbar',
                                    'MDME( 175,1) = 0    !Z decay into u ubar',
                                    'MDME( 176,1) = 0    !Z decay into s sbar',
                                    'MDME( 177,1) = 0    !Z decay into c cbar',
                                    'MDME( 178,1) = 0    !Z decay into b bbar',
                                    'MDME( 179,1) = 0    !Z decay into t tbar',
                                    'MDME( 182,1) = 1    !Z decay into e- e+',
                                    'MDME( 183,1) = 0    !Z decay into nu_e nu_ebar',
                                    'MDME( 184,1) = 0    !Z decay into mu- mu+',
                                    'MDME( 185,1) = 0    !Z decay into nu_mu nu_mubar',
                                    'MDME( 186,1) = 0    !Z decay into tau- tau+',
                                    'MDME( 187,1) = 0    !Z decay into nu_tau nu_taubar',
                                    'CKIN( 1)     = 40.  !(D=2. GeV)',
                                    'CKIN( 2)     = -1.  !(D=-1. GeV)'),
    parameterSets = cms.vstring('pythiaUESettings',
                                'processParameters')
    )
                                 )


# Path and EndPath definitions
process.generation_step = cms.Path(process.pgen_genonly)
process.reconstruction = cms.Path(process.reconstructionWithFamos)
process.prevalidation_step = cms.Path(process.prevalidation)
process.genfiltersummary_step = cms.EndPath(process.genFilterSummary)
process.validation_step = cms.EndPath(process.validation)
process.endjob_step = cms.EndPath(process.endOfProcess)
process.FEVTDEBUGHLToutput_step = cms.EndPath(process.FEVTDEBUGHLToutput)

# Schedule definition
process.schedule = cms.Schedule(process.generation_step,process.genfiltersummary_step)
process.schedule.extend(process.HLTSchedule)
process.schedule.extend([process.reconstruction,process.prevalidation_step,process.validation_step,process.endjob_step,process.FEVTDEBUGHLToutput_step])
# filter all path with the production filter sequence
for path in process.paths:
    getattr(process,path)._seq = process.generator * getattr(process,path)._seq 
EOF


cat > step2_cfg.py <<EOF
import sys
import os
import FWCore.ParameterSet.Config as cms

process = cms.Process("electronValidation")

process.DQMStore = cms.Service("DQMStore")
process.load("DQMServices.Components.DQMStoreStats_cfi")
from DQMServices.Components.DQMStoreStats_cfi import *
dqmStoreStats.runOnEndJob = cms.untracked.bool(True)

process.maxEvents = cms.untracked.PSet(input = cms.untracked.int32(-1))
process.source = cms.Source ("PoolSource",fileNames = cms.untracked.vstring('rfio:/castor/cern.ch/user/g/giamman/fastsim_ecal/ZEE_${workdir}.root'))

process.load('Configuration.StandardSequences.Services_cff')
process.load('SimGeneral.HepPDTESSource.pythiapdt_cfi')
process.load('FWCore.MessageService.MessageLogger_cfi')
process.load('Configuration.EventContent.EventContent_cff')
process.load('SimGeneral.MixingModule.mixNoPU_cfi')
process.load('Configuration.StandardSequences.GeometryDB_cff')
process.load('Configuration.StandardSequences.MagneticField_38T_cff')
process.load('Configuration.StandardSequences.RawToDigi_cff')
process.load('Configuration.StandardSequences.Reconstruction_cff')
process.load('Configuration.StandardSequences.EndOfProcess_cff')
process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')

from Configuration.AlCa.autoCond import autoCond
process.GlobalTag.globaltag = autoCond['startup']

process.load("Validation.RecoEgamma.electronIsoFromDeps_cff")
process.load("Validation.RecoEgamma.ElectronMcSignalValidator_cfi")

process.electronMcSignalValidator.OutputFile = cms.string('DQM_${workdir}.root')

process.p = cms.Path(process.electronIsoFromDeps*process.electronMcSignalValidator*process.dqmStoreStats)
EOF

set SUBMIT=submit_${workdir}.csh
cat > ${SUBMIT} <<EOF
#! /bin/csh -f
cd /afs/cern.ch/user/g/giamman/scratch0/fastsim/ecal/${workdir}/CMSSW_6_0_0_pre1/src
eval `scramv1 runtime -csh`
limit vmemoryuse unlimited
cmsRun RelValZEE_START52_V4_FastSim.py
rfcp /tmp/giamman/ZEE_${workdir}.root /castor/cern.ch/user/g/giamman/fastsim_ecal
cmsRun step2_cfg.py
wget http://agiamman.web.cern.ch/agiamman/fastsim/electrons.C
ls -l /afs/cern.ch/user/g/giamman/scratch0/fastsim/ecal/DQM_*.root 
root -l -b -q electrons.C\(\"DQM_${workdir}.root\",\"/afs/cern.ch/user/g/giamman/scratch0/fastsim/ecal/DQM_fullsim.root\"\)
mv ecalIso04.pdf ecalIso04_vs_fullsim.pdf
root -l -b -q electrons.C\(\"DQM_${workdir}.root\",\"/afs/cern.ch/user/g/giamman/scratch0/fastsim/ecal/DQM_reference.root\"\)
mv ecalIso04.pdf ecalIso04_vs_reference.pdf
EOF

chmod +x ${SUBMIT}
bsub -q cmscaf1nd ${SUBMIT}

end



