diff --git a/.gitignore b/.gitignore index b36994d9a6..1a1360a8fa 100644 --- a/.gitignore +++ b/.gitignore @@ -33,4 +33,7 @@ hs_err_pid* # no log files: *.log +*.evio +bin/evio2hipotest +export.sh \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index c86c4a70da..ac345fa687 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,13 +5,12 @@ sudo: required language: java jdk: - - oraclejdk9 + - openjdk11 -# this affects which java version is used: addons: apt: packages: - - oracle-java9-installer + - openjfx before_install: - ls -lthra @@ -32,6 +31,7 @@ script: - ./run-eb-tests.sh -100 electrongamma || travis_terminate 1; - ./run-eb-tests.sh -100 electronprotonC || travis_terminate 1; - ./run-eb-tests.sh -100 electronneutronC || travis_terminate 1; + - ./run-eb-tests.sh -100 electronFTpion || travis_terminate 1; - cd - - echo "finished advanced tests" # - mvn cobertura:cobertura &> /dev/null # for codecov diff --git a/bin.old/calibration b/bin.old/calibration new file mode 100755 index 0000000000..f30041ab7f --- /dev/null +++ b/bin.old/calibration @@ -0,0 +1,5 @@ +#!/bin/sh -f + +source `dirname $0`/env.sh + +java -XX:+UseSerialGC -Xmx2048m -Xms2048m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/plugins/*" org.jlab.calib.services.TOFCalibration $* diff --git a/bin/clara-rec b/bin.old/clara-rec similarity index 100% rename from bin/clara-rec rename to bin.old/clara-rec diff --git a/bin.old/convertor b/bin.old/convertor new file mode 100755 index 0000000000..650ae2470e --- /dev/null +++ b/bin.old/convertor @@ -0,0 +1,5 @@ +#!/bin/sh -f + +source `dirname $0`/env.sh + +java -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/plugins/*" org.jlab.clas.reco.io.HipoConvertor $* diff --git a/bin.old/ddr b/bin.old/ddr new file mode 100755 index 0000000000..759fe005d9 --- /dev/null +++ b/bin.old/ddr @@ -0,0 +1,5 @@ +#!/bin/sh -f + +source `dirname $0`/env.sh + +java -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/plugins/*" org.jlab.clas.service.DataDistributionService -type et -host localhost -file /tmp/et_sys_$SESSION diff --git a/bin.old/decoder-debugger b/bin.old/decoder-debugger new file mode 100755 index 0000000000..0d613a4ec7 --- /dev/null +++ b/bin.old/decoder-debugger @@ -0,0 +1,8 @@ +#!/bin/bash + +# This doesn't work in dash (Travis's /bin/sh): +source `dirname $0`/env.sh + +MALLOC_ARENA_MAX=1; export MALLOC_ARENA_MAX + +java -Xmx1536m -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/plugins/*" org.jlab.detector.decode.DetectorDecoderDebug $* diff --git a/bin.old/decoder3 b/bin.old/decoder3 new file mode 100755 index 0000000000..2f968b71c6 --- /dev/null +++ b/bin.old/decoder3 @@ -0,0 +1,7 @@ +#!/bin/bash + +source `dirname $0`/env.sh + +MALLOC_ARENA_MAX=1; export MALLOC_ARENA_MAX + +java -Xmx1536m -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/plugins/*" org.jlab.detector.decode.CLASDecoder $* diff --git a/bin.old/grid b/bin.old/grid new file mode 100755 index 0000000000..1b5ffbb7c3 --- /dev/null +++ b/bin.old/grid @@ -0,0 +1,5 @@ +#!/bin/sh -f + +source `dirname $0`/env.sh + +java -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/plugins/*" org.jlab.groot.matrix.SparseGridIO $* diff --git a/bin.old/hipo-writer b/bin.old/hipo-writer new file mode 100755 index 0000000000..6ac8133e92 --- /dev/null +++ b/bin.old/hipo-writer @@ -0,0 +1,5 @@ +#!/bin/sh -f + +source `dirname $0`/env.sh + +java -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/plugins/*" org.jlab.io.utils.Evio2HipoConverter $* diff --git a/bin.old/hipo3utils b/bin.old/hipo3utils new file mode 100755 index 0000000000..5fe21358d5 --- /dev/null +++ b/bin.old/hipo3utils @@ -0,0 +1,7 @@ +#!/bin/sh -f + +source `dirname $0`/env.sh + +MALLOC_ARENA_MAX=1; export MALLOC_ARENA_MAX + +java -Xmx2048m -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/plugins/*" org.jlab.jnp.hipo.utils.HipoUtilities $* diff --git a/bin.old/rec-monitor b/bin.old/rec-monitor new file mode 100755 index 0000000000..2641c037aa --- /dev/null +++ b/bin.old/rec-monitor @@ -0,0 +1,5 @@ +#!/bin/sh -f + +source `dirname $0`/env.sh + +java -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/plugins/*" org.jlab.monitor.eb.ReconstructionMonitor $* diff --git a/bin.old/studio b/bin.old/studio new file mode 100755 index 0000000000..39a00e472a --- /dev/null +++ b/bin.old/studio @@ -0,0 +1,5 @@ +#!/bin/sh -f + +source `dirname $0`/env.sh + +java -Xms1024m -Xmx2048m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/plugins/*" org.jlab.clas.physics.EventTree $* diff --git a/bin.old/update b/bin.old/update new file mode 100755 index 0000000000..ac4a0d5f98 --- /dev/null +++ b/bin.old/update @@ -0,0 +1,9 @@ +#!/bin/sh -f + +source `dirname $0`/env.sh + +java -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/utils/*:$CLAS12DIR/lib/plugins/*" org.jlab.clas.update.UpdateManager link http://clasweb.jlab.org/clas12maven/org/jlab/coat/coat-libs/3.0-SNAPSHOT/ coat-libs-3.0-SNAPSHOT.jar $CLAS12DIR/lib/clas + +java -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/utils/*:$CLAS12DIR/lib/plugins/*" org.jlab.clas.update.UpdateManager link https://userweb.jlab.org/~devita/kpp/ KPP-Plots-1.0.jar $CLAS12DIR/lib/utils + +java -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/utils/*:$CLAS12DIR/lib/plugins/*" org.jlab.clas.update.UpdateManager link https://userweb.jlab.org/~devita/kpp/ KPP-Monitoring-1.0.jar $CLAS12DIR/lib/utils diff --git a/bin.old/x-client b/bin.old/x-client new file mode 100755 index 0000000000..e51c06ea1f --- /dev/null +++ b/bin.old/x-client @@ -0,0 +1,5 @@ +#!/bin/sh -f + +source `dirname $0`/env.sh + +java -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/plugins/*" org.jlab.io.hipo.HipoRingSource $* diff --git a/bin.old/x-client-evio b/bin.old/x-client-evio new file mode 100755 index 0000000000..f873691079 --- /dev/null +++ b/bin.old/x-client-evio @@ -0,0 +1,5 @@ +#!/bin/sh -f + +source `dirname $0`/env.sh + +java -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/plugins/*" org.jlab.io.evio.EvioRingSource $* diff --git a/bin.old/x-server b/bin.old/x-server new file mode 100755 index 0000000000..5dc9385ea6 --- /dev/null +++ b/bin.old/x-server @@ -0,0 +1,5 @@ +#!/bin/sh -f + +source `dirname $0`/env.sh + +java -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/plugins/*" org.jlab.clas.service.DataDistributionService $* diff --git a/bin/analyzer b/bin/analyzer deleted file mode 100755 index 446f4ba71b..0000000000 --- a/bin/analyzer +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/sh -f - -source `dirname $0`/env.sh - -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.hipo.HipoDataSync $* -java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.clas.physics.DataAnalysis $* diff --git a/bin/bos2hipo b/bin/bos2hipo index 5b2b9141f6..4730acd9d1 100755 --- a/bin/bos2hipo +++ b/bin/bos2hipo @@ -2,18 +2,4 @@ source `dirname $0`/env.sh -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.hipo.HipoDataSync $* -java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.utils.Bos2HipoEventBank $* +java -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/plugins/*" org.jlab.io.utils.Bos2HipoEventBank $* diff --git a/bin/browser b/bin/browser deleted file mode 100755 index 1b2bce5c31..0000000000 --- a/bin/browser +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/sh -f - -source `dirname $0`/env.sh - -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.groot.ui.TBrowser $* diff --git a/bin/calibration b/bin/calibration deleted file mode 100755 index 091339cd42..0000000000 --- a/bin/calibration +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/sh -f - -source `dirname $0`/env.sh - -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -XX:+UseSerialGC -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.clasrec.rec.CLASReconstruction $* -#java -XX:+UseSerialGC -Xmx2048m -Xms2048m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.detector.calib.tasks.CalibrationEngineTask $* -java -XX:+UseSerialGC -Xmx2048m -Xms2048m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.calib.services.TOFCalibration $* diff --git a/bin/convertor b/bin/convertor deleted file mode 100755 index 76a9afed03..0000000000 --- a/bin/convertor +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/sh -f - -source `dirname $0`/env.sh - -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.hipo.HipoDataSync $* -java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.clas.reco.io.HipoConvertor $* diff --git a/bin/daq-monitor b/bin/daq-monitor deleted file mode 100755 index 55be7c9ae0..0000000000 --- a/bin/daq-monitor +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/sh -f - -source `dirname $0`/env.sh - -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/services/*:$DATAMINING/lib/utils/*" org.jlab.detector.examples.DaqPulsePlotter $* diff --git a/bin/daqEventViewer b/bin/daqEventViewer index 6ad1aaa55d..b91ebbfbc4 100755 --- a/bin/daqEventViewer +++ b/bin/daqEventViewer @@ -2,17 +2,4 @@ source `dirname $0`/env.sh -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/services/*:$DATAMINING/lib/utils/*" org.jlab.detector.examples.RawEventViewer $* +java -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/services/*:$CLAS12DIR/lib/utils/*" org.jlab.detector.examples.RawEventViewer $* diff --git a/bin/dclayereffs-ana b/bin/dclayereffs-ana new file mode 100755 index 0000000000..7db7d2ed02 --- /dev/null +++ b/bin/dclayereffs-ana @@ -0,0 +1,5 @@ +#!/bin/sh -f + +source `dirname $0`/env.sh + +java -Dsun.java2d.pmoffscreen=false -Xmx2048m -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/utils/*:$CLAS12DIR/lib/services/*" org.jlab.service.dc.LayerEfficiencyAnalyzer $* diff --git a/bin/dclayereffs-anal b/bin/dclayereffs-anal deleted file mode 100755 index 024abb172e..0000000000 --- a/bin/dclayereffs-anal +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/sh -f - -source `dirname $0`/env.sh - -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.hipo.HipoDataSync $* -java -Dsun.java2d.pmoffscreen=false -Xmx2048m -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/utils/*:$DATAMINING/lib/services/*" org.jlab.service.dc.LayerEfficiencyAnalyzer $* diff --git a/bin/ddr b/bin/ddr deleted file mode 100755 index 26f9faa8dd..0000000000 --- a/bin/ddr +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/sh -f - -source `dirname $0`/env.sh - -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.hipo.HipoDataSync $* -#java -XX:+UseNUMA -XX:+UseBiasedLocking -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.coda.xmsg.sys.xMsgProxy & -#java -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.coda.xmsg.sys.xMsgProxy -java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.clas.service.DataDistributionService -type et -host localhost -file /tmp/et_sys_$SESSION diff --git a/bin/debug_ec.sh b/bin/debug_ec.sh deleted file mode 100755 index 85c00bd8eb..0000000000 --- a/bin/debug_ec.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/sh -f - -source `dirname $0`/env.sh - -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.display.ec.ECPion $* diff --git a/bin/decoder b/bin/decoder index 7c7850098b..760071bdbe 100755 --- a/bin/decoder +++ b/bin/decoder @@ -5,18 +5,8 @@ source `dirname $0`/env.sh MALLOC_ARENA_MAX=1; export MALLOC_ARENA_MAX -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - echo +------------------------------------------------------------------------- echo "| DECODER GENERATION 4 (using HIPO-4 Library)" echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.hipo.HipoDataSync $* -java -Xmx1536m -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.detector.decode.CLASDecoder4 $* +java -Xmx1536m -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/plugins/*" org.jlab.detector.decode.CLASDecoder4 $* diff --git a/bin/decoder-debugger b/bin/decoder-debugger deleted file mode 100755 index 2716be2193..0000000000 --- a/bin/decoder-debugger +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/bash - -# This doesn't work in dash (Travis's /bin/sh): -source `dirname $0`/env.sh - -MALLOC_ARENA_MAX=1; export MALLOC_ARENA_MAX - -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.hipo.HipoDataSync $* -java -Xmx1536m -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.detector.decode.DetectorDecoderDebug $* diff --git a/bin/decoder3 b/bin/decoder3 deleted file mode 100755 index 0402b19e52..0000000000 --- a/bin/decoder3 +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/bash - -# This doesn't work in dash (Travis's /bin/sh): -source `dirname $0`/env.sh - -MALLOC_ARENA_MAX=1; export MALLOC_ARENA_MAX - -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.hipo.HipoDataSync $* -java -Xmx1536m -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.detector.decode.CLASDecoder $* diff --git a/bin/dict-maker b/bin/dict-maker index 174feb9ebb..28af7f0001 100755 --- a/bin/dict-maker +++ b/bin/dict-maker @@ -3,18 +3,5 @@ source `dirname $0`/env.sh MALLOC_ARENA_MAX=1; export MALLOC_ARENA_MAX -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.hipo.HipoDataSync $* -java -Xmx1536m -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/services/*:$DATAMINING/lib/utils/*" org.jlab.service.dc.TrackDictionaryMakerRNG $* +java -Xmx1536m -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/services/*:$CLAS12DIR/lib/utils/*" org.jlab.service.dc.TrackDictionaryMakerRNG $* diff --git a/bin/dict-merge b/bin/dict-merge index 2252ecf882..e58c4f22b4 100755 --- a/bin/dict-merge +++ b/bin/dict-merge @@ -3,18 +3,5 @@ source `dirname $0`/env.sh MALLOC_ARENA_MAX=1; export MALLOC_ARENA_MAX -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.hipo.HipoDataSync $* -java -Xmx1536m -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/services/*:$DATAMINING/lib/utils/*" org.jlab.service.dc.TrackDictionaryMerger $* +java -Xmx1536m -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/services/*:$CLAS12DIR/lib/utils/*" org.jlab.service.dc.TrackDictionaryMerger $* diff --git a/bin/dict-validate b/bin/dict-validate index e227208bdb..5d70ba8581 100755 --- a/bin/dict-validate +++ b/bin/dict-validate @@ -3,18 +3,5 @@ source `dirname $0`/env.sh MALLOC_ARENA_MAX=1; export MALLOC_ARENA_MAX -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.hipo.HipoDataSync $* -java -Xmx1536m -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/services/*:$DATAMINING/lib/utils/*" org.jlab.service.dc.TrackDictionaryValidation $* +java -Xmx1536m -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/services/*:$CLAS12DIR/lib/utils/*" org.jlab.service.dc.TrackDictionaryValidation $* diff --git a/bin/dst-maker b/bin/dst-maker new file mode 100755 index 0000000000..81aca6fac8 --- /dev/null +++ b/bin/dst-maker @@ -0,0 +1,32 @@ +#!/bin/sh + +usage="\nUsage: dst-maker -o outputfile inputfile [inputfile [...]]\n" + +if [ "$#" -lt 3 ]; then + echo -e $usage + exit +elif [ "$1" != "-o" ]; then + echo -e $usage + exit +elif [ -e $2 ]; then + echo -e $usage + echo File already exists: $2 + exit +else + for x in ${@:3} + do + if ! [ -e $x ]; then + echo -e $usage + echo File does not exist: $x + exit + fi + done +fi + +hipo-utils \ + -filter \ + -b 'RUN::*,RAW::epics,RAW::scaler,HEL::flip,HEL::online,REC::*,RECFT::*,MC::*' \ + -merge \ + -o $2 \ + ${@:3} + diff --git a/bin/eb-monitor b/bin/eb-monitor deleted file mode 100755 index 9d8b6d29d0..0000000000 --- a/bin/eb-monitor +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/sh -f - -source `dirname $0`/env.sh - -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/services/*:$DATAMINING/lib/utils/*" org.jlab.service.eb.EBDebug $* diff --git a/bin/ec-monitor b/bin/ec-monitor deleted file mode 100755 index 2ac2584b1d..0000000000 --- a/bin/ec-monitor +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/sh -f - -source `dirname $0`/env.sh - -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/services/*:$DATAMINING/lib/utils/*" org.jlab.display.ec.ECMonitor $* diff --git a/bin/env.sh b/bin/env.sh index b0b6c9a2bb..200f78ccdb 100644 --- a/bin/env.sh +++ b/bin/env.sh @@ -1,10 +1,7 @@ #!/bin/bash SCRIPT_DIR=`dirname $0` -DISTRO_DIR=$SCRIPT_DIR/../ ; export DISTRO_DIR CLAS12DIR=$SCRIPT_DIR/../ ; export CLAS12DIR -CLARA_SERVICES=$DISTRO_DIR/lib/services; export CLARA_SERVICES -DATAMINING=$DISTRO_DIR ; export DATAMINING # Set default field maps (but do not override user's env): if [ -z "$COAT_MAGFIELD_TORUSMAP" ]; then @@ -17,3 +14,7 @@ if [ -z "$COAT_MAGFIELD_SOLENOIDMAP" ]; then export COAT_MAGFIELD_SOLENOIDMAP=Symm_solenoid_r601_phi1_z1201_13June2018.dat fi +echo +------------------------------------------------------------------------- +echo "| COATJAVA LIBRARY DIRECTORY = " $CLAS12DIR/lib/clas/ +echo +------------------------------------------------------------------------- + diff --git a/bin/evio-viewer b/bin/evio-viewer index 8d41a5d774..8d659aaf39 100755 --- a/bin/evio-viewer +++ b/bin/evio-viewer @@ -2,18 +2,4 @@ source `dirname $0`/env.sh -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -java -cp "$DATAMINING/lib/clas/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -cp "$DATAMINING/lib/clas/*" org.jlab.coda.jevio.graphics.EventTreeFrame $* -#java -cp "$DATAMINING/lib/clas/*" org.jlab.coda.jevio.graphics.EventTreeFrame $* +java -cp "$CLAS12DIR/lib/clas/*" org.jlab.coda.eventViewer.EventTreeFrame $* diff --git a/bin/evio2hipo b/bin/evio2hipo index b64a8c82ac..ceda619f9b 100755 --- a/bin/evio2hipo +++ b/bin/evio2hipo @@ -4,18 +4,4 @@ source `dirname $0`/env.sh MALLOC_ARENA_MAX=1; export MALLOC_ARENA_MAX -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.hipo.HipoDataSync $* -java -Xmx1536m -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.clas.reco.io.EvioHipoEvent4 $* +java -Xmx1536m -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/plugins/*" org.jlab.clas.reco.io.EvioHipoEvent4 $* diff --git a/bin/eviocure b/bin/eviocure index 258a4bf05e..d2e0768d3f 100755 --- a/bin/eviocure +++ b/bin/eviocure @@ -4,18 +4,4 @@ source `dirname $0`/env.sh MALLOC_ARENA_MAX=1; export MALLOC_ARENA_MAX -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.hipo.HipoDataSync $* -java -Xmx1536m -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.utils.EvioCure $* +java -Xmx1536m -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/plugins/*" org.jlab.io.utils.EvioCure $* diff --git a/bin/eviodump b/bin/eviodump index be98a29fef..db4f7b0c4f 100755 --- a/bin/eviodump +++ b/bin/eviodump @@ -2,17 +2,4 @@ source `dirname $0`/env.sh -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.utils.DataSourceDump $* +java -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/plugins/*" org.jlab.io.utils.DataSourceDump $* diff --git a/bin/gemc-evio b/bin/gemc-evio deleted file mode 100755 index 82f5e8f76f..0000000000 --- a/bin/gemc-evio +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/sh -f - -source `dirname $0`/env.sh - -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.clas.reco.io.ReconstructionIO $* diff --git a/bin/grid b/bin/grid deleted file mode 100755 index 68a7685fb2..0000000000 --- a/bin/grid +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/sh -f - -source `dirname $0`/env.sh - -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.groot.matrix.SparseGridIO $* diff --git a/bin/hadd b/bin/hadd index 2c045d5696..87673aade6 100755 --- a/bin/hadd +++ b/bin/hadd @@ -2,17 +2,4 @@ source `dirname $0`/env.sh -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.groot.data.TDirectory $* +java -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/plugins/*" org.jlab.groot.data.TDirectory $* diff --git a/bin/hipo-browser b/bin/hipo-browser new file mode 100755 index 0000000000..820bf4995d --- /dev/null +++ b/bin/hipo-browser @@ -0,0 +1,5 @@ +#!/bin/sh -f + +source `dirname $0`/env.sh + +java -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/plugins/*" org.jlab.groot.ui.TBrowser $* diff --git a/bin/hipo-utils b/bin/hipo-utils index 2871f0ad81..4b48c1deac 100755 --- a/bin/hipo-utils +++ b/bin/hipo-utils @@ -4,19 +4,4 @@ source `dirname $0`/env.sh MALLOC_ARENA_MAX=1; export MALLOC_ARENA_MAX -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.hipo.HipoDataSync $* -#java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.clas.reco.io.HipoFileUtils $* -java -Xmx2048m -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.jnp.hipo4.utils.HipoUtilities $* +java -Xmx2048m -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/plugins/*" org.jlab.jnp.hipo4.utils.HipoUtilities $* diff --git a/bin/hipo-writer b/bin/hipo-writer deleted file mode 100755 index eae747fceb..0000000000 --- a/bin/hipo-writer +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/sh -f - -source `dirname $0`/env.sh - -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.hipo.HipoDataSync $* -java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.utils.Evio2HipoConverter $* diff --git a/bin/hipo3utils b/bin/hipo3utils deleted file mode 100755 index 569279e187..0000000000 --- a/bin/hipo3utils +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/sh -f - -source `dirname $0`/env.sh - -MALLOC_ARENA_MAX=1; export MALLOC_ARENA_MAX - -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.hipo.HipoDataSync $* -#java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.clas.reco.io.HipoFileUtils $* -java -Xmx2048m -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.jnp.hipo.utils.HipoUtilities $* diff --git a/bin/jaw b/bin/jaw deleted file mode 100755 index 84955d6b99..0000000000 --- a/bin/jaw +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/sh -f - -source `dirname $0`/env.sh - -java -Dsun.java2d.pmoffscreen=false -Xms1024m -Xmx2048m -cp "$DATAMINING/lib/utils/*" org.jlab.jnp.math.cli.MathCli $* - -#********************************************************* -#--------------------------------------------------------- -# JHEP math CLI interface. -#--------------------------------------------------------- -#java -cp "target/jnp-math-1.0-SNAPSHOT-jar-with-dependencies.jar" org.jlab.jnp.math.cli.MathCli $* diff --git a/bin/kpp-plots b/bin/kpp-plots index 6f4135adce..f33f426b58 100755 --- a/bin/kpp-plots +++ b/bin/kpp-plots @@ -2,18 +2,4 @@ source `dirname $0`/env.sh -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.hipo.HipoDataSync $* -java -Dsun.java2d.pmoffscreen=false -Xmx2048m -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/utils/*:$DATAMINING/lib/services/*" org.clas.viewer.KPPViewer $* +java -Dsun.java2d.pmoffscreen=false -Xmx2048m -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/utils/*:$CLAS12DIR/lib/services/*" org.clas.viewer.KPPViewer $* diff --git a/bin/mon12 b/bin/mon12 index 02e50f2583..fc693331c2 100755 --- a/bin/mon12 +++ b/bin/mon12 @@ -2,18 +2,4 @@ source `dirname $0`/env.sh -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.hipo.HipoDataSync $* -java -Dsun.java2d.pmoffscreen=false -Xmx2048m -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/utils/*:$DATAMINING/lib/services/*" org.clas.viewer.EventViewer $* +java -Dsun.java2d.pmoffscreen=false -Xmx2048m -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/utils/*:$CLAS12DIR/lib/services/*" org.clas.viewer.EventViewer $* diff --git a/bin/pion b/bin/pion deleted file mode 100755 index 7ee68900fa..0000000000 --- a/bin/pion +++ /dev/null @@ -1,19 +0,0 @@ -#!/bin/sh -f - -source `dirname $0`/env.sh - -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.hipo.HipoDataSync $* -java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/services/*" org.jlab.display.ec.ECPionFinder $* diff --git a/bin/postprocess b/bin/postprocess new file mode 100755 index 0000000000..b3d44933ad --- /dev/null +++ b/bin/postprocess @@ -0,0 +1,7 @@ +#!/bin/bash + +source `dirname $0`/env.sh + +MALLOC_ARENA_MAX=1; export MALLOC_ARENA_MAX + +java -Xmx768m -Xms768m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/services/*:$CLAS12DIR/lib/utils/*" org.jlab.analysis.postprocess.Tag1ToEvent $* diff --git a/bin/rec-monitor b/bin/rec-monitor deleted file mode 100755 index 1257139a79..0000000000 --- a/bin/rec-monitor +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/sh -f - -source `dirname $0`/env.sh - -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.monitor.eb.ReconstructionMonitor $* diff --git a/bin/recon-util b/bin/recon-util index 0fe6c5e885..763324174c 100755 --- a/bin/recon-util +++ b/bin/recon-util @@ -3,18 +3,5 @@ source `dirname $0`/env.sh MALLOC_ARENA_MAX=1; export MALLOC_ARENA_MAX -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.hipo.HipoDataSync $* -java -Xmx1536m -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/services/*:$DATAMINING/lib/utils/*" org.jlab.clas.reco.EngineProcessor $* +java -Xmx1536m -Xms1024m -cp "$CLAS12DIR/lib/clas/*:$CLAS12DIR/lib/services/*:$CLAS12DIR/lib/utils/*" org.jlab.clas.reco.EngineProcessor $* diff --git a/bin/run-groovy b/bin/run-groovy index b36fe48fe1..6a93a9ea5e 100755 --- a/bin/run-groovy +++ b/bin/run-groovy @@ -3,17 +3,17 @@ source `dirname $0`/env.sh CLARA_HOME=`dirname $0`/.. -DATAMINING=`dirname $0`/.. +CLAS12DIR=`dirname $0`/.. CLAS12DIR=`dirname $0`/.. ; export CLAS12DIR CLARA_SERVICES=$CLAS12DIR/lib/services ; export CLARA_SERVICES -#JYTHONPATH=${DATAMINING}/lib/jython +#JYTHONPATH=${CLAS12DIR}/lib/jython #echo ${JYTHONPATH} #-------------------------------------------------------------- # Adding supporting COAT jar files -for i in `ls -a $DATAMINING/lib/clas/*.jar` +for i in `ls -a $CLAS12DIR/lib/clas/*.jar` do #echo "$i" if [ -z "${JYPATH}" ] ; then @@ -24,7 +24,7 @@ fi done #-------------------------------------------------------------- # Adding supporting plugins directory -for i in `ls -a $DATAMINING/lib/services/*.jar` +for i in `ls -a $CLAS12DIR/lib/services/*.jar` do if [ -z "${JYPATH}" ] ; then JYPATH="$i" @@ -38,7 +38,7 @@ done # Done loading plugins #-------------------------------------------------------------- # Adding supporting plugins directory -for i in `ls -a $DATAMINING/lib/utils/*.jar` +for i in `ls -a $CLAS12DIR/lib/utils/*.jar` do if [ -z "${JYPATH}" ] ; then JYPATH="$i" @@ -47,7 +47,7 @@ JYPATH=${JYPATH}:"$i" fi done #------------------------------------------------------------- -JYPATH=${JYPATH}:${DATAMINING}/lib/packages +JYPATH=${JYPATH}:${CLAS12DIR}/lib/packages echo " " echo " " echo "*****************************************" diff --git a/bin/studio b/bin/studio deleted file mode 100755 index 8afb445e32..0000000000 --- a/bin/studio +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/sh -f - -source `dirname $0`/env.sh - -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -java -Xms1024m -Xmx2048m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.clas.physics.EventTree $* diff --git a/bin/update b/bin/update deleted file mode 100755 index 7f9704a2c6..0000000000 --- a/bin/update +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/sh -f - -source `dirname $0`/env.sh - -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` -#echo +------------------------------------------------------------------------- -#echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -#echo +------------------------------------------------------------------------- -#echo "\n" -#echo "INSTALLATION DIRECTORY = " $CLARA_HOME -#echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.clas.tools.utils.StringTable -#java -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/utils/*:$DATAMINING/lib/plugins/*" org.jlab.clas.update.UpdateManager $* - -java -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/utils/*:$DATAMINING/lib/plugins/*" org.jlab.clas.update.UpdateManager link http://clasweb.jlab.org/clas12maven/org/jlab/coat/coat-libs/3.0-SNAPSHOT/ coat-libs-3.0-SNAPSHOT.jar $CLAS12DIR/lib/clas - -java -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/utils/*:$DATAMINING/lib/plugins/*" org.jlab.clas.update.UpdateManager link https://userweb.jlab.org/~devita/kpp/ KPP-Plots-1.0.jar $CLAS12DIR/lib/utils - -java -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/utils/*:$DATAMINING/lib/plugins/*" org.jlab.clas.update.UpdateManager link https://userweb.jlab.org/~devita/kpp/ KPP-Monitoring-1.0.jar $CLAS12DIR/lib/utils diff --git a/bin/x-client b/bin/x-client deleted file mode 100755 index cab1bef627..0000000000 --- a/bin/x-client +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/sh -f - -source `dirname $0`/env.sh - -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.hipo.HipoRingSource $* diff --git a/bin/x-client-evio b/bin/x-client-evio deleted file mode 100755 index 9c2150a3fd..0000000000 --- a/bin/x-client-evio +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/sh -f - -source `dirname $0`/env.sh - -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.evio.EvioRingSource $* diff --git a/bin/x-server b/bin/x-server deleted file mode 100755 index f3e2c73090..0000000000 --- a/bin/x-server +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/sh -f - -source `dirname $0`/env.sh - -#CLARA_HOME=`dirname $0` -#CLARA_SERVICES=`dirname $0` -#DATAMINING=`dirname $0` - -echo +------------------------------------------------------------------------- -echo "| Starting CLARA-PLATFORM with CLARA_SERVICES = " $CLARA_SERVICES -echo +------------------------------------------------------------------------- -echo "\n" - -echo "INSTALLATION DIRECTORY = " $CLARA_HOME -echo "LIBRARY DIRECTORY = " $DATAMINING/lib/clas/ - -#java -cp "$DATAMINING/lib/clas/core/*" org.jlab.coda.eventViewer.EventTreeFrame $* -#java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.io.hipo.HipoDataSync $* -#java -XX:+UseNUMA -XX:+UseBiasedLocking -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.coda.xmsg.sys.xMsgProxy & -#java -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.coda.xmsg.sys.xMsgProxy -java -Xms1024m -cp "$DATAMINING/lib/clas/*:$DATAMINING/lib/plugins/*" org.jlab.clas.service.DataDistributionService $* diff --git a/build-coatjava.sh b/build-coatjava.sh index e5abbc3485..bf11ae5644 100755 --- a/build-coatjava.sh +++ b/build-coatjava.sh @@ -66,7 +66,7 @@ cp external-dependencies/vecmath-1.3.1-2.jar coatjava/lib/clas/ mkdir -p coatjava/lib/utils cp external-dependencies/jclara-4.3-SNAPSHOT.jar coatjava/lib/utils cp external-dependencies/clas12mon-3.1.jar coatjava/lib/utils -cp external-dependencies/KPP-Plots-3.1.jar coatjava/lib/utils +cp external-dependencies/KPP-Plots-3.2.jar coatjava/lib/utils #cp external-dependencies/jaw-1.0.jar coatjava/lib/utils mkdir -p coatjava/lib/services @@ -109,5 +109,6 @@ cp reconstruction/rich/target/clas12detector-rich-*-SNAPSHOT.jar coatjava/lib/se cp reconstruction/fvt/target/clas12detector-fmt-*-SNAPSHOT.jar coatjava/lib/services/ cp reconstruction/eb/target/clas12detector-eb-*-SNAPSHOT.jar coatjava/lib/services/ cp reconstruction/band/target/clas12detector-band-*-SNAPSHOT.jar coatjava/lib/services/ +cp reconstruction/rtpc/target/clas12detector-rtpc-*-SNAPSHOT.jar coatjava/lib/services/ echo "COATJAVA SUCCESSFULLY BUILT !" diff --git a/common-tools/clas-analysis/pom.xml b/common-tools/clas-analysis/pom.xml index 6724843558..96b5060d95 100644 --- a/common-tools/clas-analysis/pom.xml +++ b/common-tools/clas-analysis/pom.xml @@ -3,14 +3,14 @@ 4.0.0 org.jlab.clas clas-analysis - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT jar org.jlab.clas clas12rec ../../parent/pom.xml - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT @@ -30,31 +30,31 @@ org.jlab.clas clas-utils - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-physics - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-io - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-geometry - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-detector - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT diff --git a/common-tools/clas-analysis/src/main/java/org/jlab/analysis/physics/TestEvent.java b/common-tools/clas-analysis/src/main/java/org/jlab/analysis/physics/TestEvent.java index c8d9ea864b..a18f04bec0 100644 --- a/common-tools/clas-analysis/src/main/java/org/jlab/analysis/physics/TestEvent.java +++ b/common-tools/clas-analysis/src/main/java/org/jlab/analysis/physics/TestEvent.java @@ -15,49 +15,53 @@ public class TestEvent { public static HipoDataEvent getDCSector1ElectronEvent(SchemaFactory schemaFactory) { Event testEvent = new Event(); + + // this event is based on a gemc event with - // one generated electron with p=2.5, th=25, ph=0 - // (i.e. px=1.057, py=0, pz=2.266) - // torus = -1.0 , solenoid = 0.0 - // updated to use non-linear t2d - // updated to include mini-stagger + // one generated electron with p=2.5, th=25, ph=0 + // (i.e. px=1.057, py=0, pz=2.266) + // torus = -1.0 , solenoid = 0.0 - Bank config = new Bank(schemaFactory.getSchema("RUN::config"), 1); - config.putInt("run", 0, (int) 11); - config.putInt("event", 0, (int) 1); - config.putInt("unixtime", 0, (int) 0); - config.putLong("trigger", 0, (long) 0); - config.putLong("timestamp", 0, (long) 0); - config.putByte("type", 0, (byte) 0); - config.putByte("mode", 0, (byte) 0); - config.putFloat("torus", 0, (float) -1.0); - config.putFloat("solenoid", 0, (float) 0.0); - - Bank event = new Bank(schemaFactory.getSchema("RECHB::Event"), 1); - event.putFloat("startTime", 0, (float) 124.25); + Bank config = new Bank(schemaFactory.getSchema("RUN::config"), 1); + config.putInt("run", 0, (int) 11); + config.putInt("event", 0, (int) 1); + config.putInt("unixtime", 0, (int) 0); + config.putLong("trigger", 0, (long) 0); + config.putLong("timestamp", 0, (long) 0); + config.putByte("type", 0, (byte) 0); + config.putByte("mode", 0, (byte) 0); + config.putFloat("torus", 0, (float) -1.0); + config.putFloat("solenoid", 0, (float) 0.0); + + Bank event = new Bank(schemaFactory.getSchema("RECHB::Event"), 1); + event.putFloat("startTime", 0, (float) 124.25); + int[] layer = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 + , 11, 12, 13, 14, 15, 16, 16, 17, 18, 19 + , 20, 21, 22, 23, 24, 25, 25, 26, 27, 28 + , 29, 30, 30, 31, 32, 33, 33, 34, 35, 26}; + - int[] layer = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 - , 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 - , 21, 22, 23, 24, 25, 26, 26, 27, 28, 29 - , 30, 31, 31, 32, 33, 34, 35, 36}; - int[] component = { 63, 64, 63, 64, 63, 64, 64, 64, 64, 64 - , 64, 64, 59, 60, 59, 60, 59, 60, 59, 59 - , 59, 59, 59, 59, 52, 53, 52, 52, 52, 52 - , 52, 52, 51, 52, 51, 52, 51, 51}; - int[] TDC = { 73, 74, 79, 72, 77, 75, 21, 145, 27, 136 - , 29, 136, 149, 124, 99, 192, 43, 260, 89, 142 - , 159, 69, 243, 3, 88, 456, 547, 67, 256, 280 - , 56, 537, 484, 96, 220, 312, 18, 423}; + int[] component = { 66, 67, 66, 67, 66, 67, 67, 67, 67, 67 + , 67, 67, 62, 63, 62, 63, 62, 62, 62, 61 + , 62, 61, 62, 61, 62, 55, 54, 55, 54, 55 + , 54, 55, 54, 54, 54, 54, 53, 54, 53, 54}; + + + int[] TDC = { 86, 60, 95, 52, 103, 39, 80, 75, 74, 84 + , 67, 93, 60, 228, 21, 285, 341, 16, 229, 253 + , 68, 175, 125, 104, 196, 470, 558, 48, 269, 237 + , 85, 462, 518, 326, 51, 644, 450, 104, 210, 338}; + - Bank DCtdc = new Bank(schemaFactory.getSchema("DC::tdc"), layer.length); - for(int i = 0; i < layer.length; i++) { - DCtdc.putByte("sector", i, (byte) 1); - DCtdc.putByte("order", i, (byte) 2); - DCtdc.putByte("layer", i, (byte) layer[i]); - DCtdc.putShort("component", i, (short) component[i]); - DCtdc.putInt("TDC", i, TDC[i]); - } + Bank DCtdc = new Bank(schemaFactory.getSchema("DC::tdc"), layer.length); + for(int i = 0; i < layer.length; i++) { + DCtdc.putByte("sector", i, (byte) 1); + DCtdc.putByte("order", i, (byte) 2); + DCtdc.putByte("layer", i, (byte) layer[i]); + DCtdc.putShort("component", i, (short) component[i]); + DCtdc.putInt("TDC", i, TDC[i]); + } diff --git a/common-tools/clas-analysis/src/main/java/org/jlab/analysis/postprocess/Tag1ToEvent.java b/common-tools/clas-analysis/src/main/java/org/jlab/analysis/postprocess/Tag1ToEvent.java new file mode 100644 index 0000000000..5f5bf6026b --- /dev/null +++ b/common-tools/clas-analysis/src/main/java/org/jlab/analysis/postprocess/Tag1ToEvent.java @@ -0,0 +1,134 @@ +package org.jlab.analysis.postprocess; + +import java.util.ArrayList; +import java.util.List; + +import org.jlab.jnp.hipo4.data.Bank; +import org.jlab.jnp.hipo4.data.Event; + +import org.jlab.jnp.hipo4.io.HipoReader; +import org.jlab.jnp.hipo4.io.HipoWriterSorted; + +import org.jlab.utils.system.ClasUtilsFile; + +import org.jlab.detector.decode.DaqScalers; +import org.jlab.detector.decode.DaqScalersSequence; + +import org.jlab.detector.helicity.HelicityBit; +import org.jlab.detector.helicity.HelicitySequenceManager; + +import org.jlab.utils.options.OptionParser; + +/** + * Calls routines to do analysis and per-event lookup of delayed helicity + * and beam charge from tag-1 events, and outputs a file with modified + * REC::Event.helicity/beamCharge/liveTime. + * + * Usage: Tag1ToEvent outputFile inputFile1 [inputFile2 [inputFile3 [...]]] + * + * FIXME: DaqScalersSequence doesn't manage run numbers. Until then, we + * cannot mix run numbers here. + * + * @author wphelps + * @author baltzell + */ + +public class Tag1ToEvent { + + public static void main(String[] args) { + + OptionParser parser = new OptionParser("postprocess"); + parser.addOption("-q","0","do beam charge and livetime (0/1=false/true)"); + parser.addOption("-d","0","do delayed helicity (0/1=false/true)"); + parser.addRequired("-o","output.hipo"); + parser.parse(args); + + // input files: + List inputList = parser.getInputList(); + if(inputList.isEmpty()==true){ + parser.printUsage(); + System.err.println("\n >>>> error : no input file is specified....\n"); + System.exit(1); + } + + // output file: + String fileout = parser.getOption("-o").stringValue(); + + // helicity / beamcharge options: + final boolean doHelicity = parser.getOption("-d").intValue() != 0; + final boolean doBeamCharge = parser.getOption("-q").intValue() != 0; + if (!doHelicity && !doBeamCharge) { + parser.printUsage(); + System.err.println("\n >>>>> error : at least one of -q/-d must be specified\n"); + System.exit(1); + } + + HelicitySequenceManager helSeq = new HelicitySequenceManager(8,inputList); + DaqScalersSequence chargeSeq = DaqScalersSequence.readSequence(inputList); + + HipoWriterSorted writer = new HipoWriterSorted(); + writer.getSchemaFactory().initFromDirectory(ClasUtilsFile.getResourceDir("COATJAVA", "etc/bankdefs/hipo4")); + writer.setCompressionType(1); + writer.open(fileout); + + Event event = new Event(); + + // we're going to modify this bank: + Bank recEventBank = new Bank(writer.getSchemaFactory().getSchema("REC::Event")); + + // FIXME: we shouldn't need this bank, but just the event: + Bank runConfigBank = new Bank(writer.getSchemaFactory().getSchema("RUN::config")); + + long badCharge = 0; + long goodCharge = 0; + long badHelicity = 0; + long goodHelicity = 0; + + for (String filename : inputList) { + + HipoReader reader = new HipoReader(); + reader.open(filename); + + while (reader.hasNext()) { + + reader.nextEvent(event); + event.read(recEventBank); + event.remove(recEventBank.getSchema()); + + // FIXME: we shouldn't need this bank, but just the event: + event.read(runConfigBank); + final long timestamp = runConfigBank.getLong("timestamp", 0); + + // do the lookups: + HelicityBit hb = helSeq.search(event); + DaqScalers ds = chargeSeq.get(timestamp); + + // write heliicty to REC::Event: + if (Math.abs(hb.value())==1) goodHelicity++; + else badHelicity++; + if (doHelicity) { + recEventBank.putByte("helicity",0,hb.value()); + } + + // write beam charge to REC::Event: + if (ds==null) badCharge++; + else { + goodCharge++; + if (doBeamCharge) { + recEventBank.putFloat("beamCharge",0,ds.getBeamCharge()); + recEventBank.putDouble("liveTime",0,ds.getLivetime()); + } + } + + // update the output file: + event.write(recEventBank); + writer.addEvent(event, event.getEventTag()); + } + reader.close(); + } + writer.close(); + + System.out.println(String.format("Tag1ToEvent: Good Helicity Fraction: %.2f%%",100*(float)goodHelicity/(goodHelicity+badHelicity))); + System.out.println(String.format("Tag1ToEvent: Good Charge Fraction: %.2f%%",100*(float)goodCharge/(goodCharge+badCharge))); + } +} diff --git a/common-tools/clas-detector/pom.xml b/common-tools/clas-detector/pom.xml index 6cbfa77191..bbf38fb4ea 100644 --- a/common-tools/clas-detector/pom.xml +++ b/common-tools/clas-detector/pom.xml @@ -3,14 +3,14 @@ 4.0.0 org.jlab.clas clas-detector - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT jar org.jlab.clas clas12rec ../../parent/pom.xml - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT @@ -30,7 +30,7 @@ org.jlab.clas clas-utils - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT @@ -42,13 +42,13 @@ org.jlab.clas clas-io - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-geometry - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT diff --git a/common-tools/clas-detector/src/main/java/org/jlab/detector/base/DetectorDescriptor.java b/common-tools/clas-detector/src/main/java/org/jlab/detector/base/DetectorDescriptor.java index c20ad2d7b9..81d12615df 100644 --- a/common-tools/clas-detector/src/main/java/org/jlab/detector/base/DetectorDescriptor.java +++ b/common-tools/clas-detector/src/main/java/org/jlab/detector/base/DetectorDescriptor.java @@ -69,20 +69,23 @@ public void setOrder(int order){ public final void setType(DetectorType type){ this.detectorType = type; } - + + public final void setLayer(int layer) { + this.dt_LAYER = layer; + } + public final void setCrateSlotChannel(int crate, int slot, int channel){ this.hw_CRATE = crate; this.hw_SLOT = slot; this.hw_CHANNEL = channel; } - + public final void setSectorLayerComponent(int sector, int layer, int comp){ this.dt_SECTOR = sector; this.dt_LAYER = layer; this.dt_COMPONENT = comp; } - - + public static int generateHashCode(int s, int l, int c){ return ((s<<24)&0xFF000000)| ((l<<16)&0x00FF0000)|(c&0x0000FFFF); @@ -94,8 +97,7 @@ public int getHashCode(){ (this.dt_COMPONENT&0x00000FFF); return hash; } - - + public void copy(DetectorDescriptor desc){ this.hw_SLOT = desc.hw_SLOT; diff --git a/common-tools/clas-detector/src/main/java/org/jlab/detector/base/DetectorLayer.java b/common-tools/clas-detector/src/main/java/org/jlab/detector/base/DetectorLayer.java index b3b2564ef5..1f2241a221 100644 --- a/common-tools/clas-detector/src/main/java/org/jlab/detector/base/DetectorLayer.java +++ b/common-tools/clas-detector/src/main/java/org/jlab/detector/base/DetectorLayer.java @@ -9,14 +9,17 @@ public class DetectorLayer { public static final byte PCAL_U=1; public static final byte PCAL_V=2; public static final byte PCAL_W=3; + public static final byte PCAL_Z=9; // layer number used to define the longitudinal coordinate of the cluster public static final byte EC_INNER_U=4; public static final byte EC_INNER_V=5; public static final byte EC_INNER_W=6; + public static final byte EC_INNER_Z=0; // layer number used to define the longitudinal coordinate of the cluster public static final byte EC_OUTER_U=7; public static final byte EC_OUTER_V=8; public static final byte EC_OUTER_W=9; + public static final byte EC_OUTER_Z=0; // layer number used to define the longitudinal coordinate of the cluster public static final byte PCAL=PCAL_U; public static final byte EC_INNER=EC_INNER_U; diff --git a/common-tools/clas-detector/src/main/java/org/jlab/detector/base/GeometryFactory.java b/common-tools/clas-detector/src/main/java/org/jlab/detector/base/GeometryFactory.java index c8cf35c2de..32fd485b3e 100644 --- a/common-tools/clas-detector/src/main/java/org/jlab/detector/base/GeometryFactory.java +++ b/common-tools/clas-detector/src/main/java/org/jlab/detector/base/GeometryFactory.java @@ -46,6 +46,7 @@ public static ConstantProvider getConstants(DetectorType type, int run, String v provider.loadTable("/geometry/dc/layer"); provider.loadTable("/geometry/dc/alignment"); provider.loadTable("/geometry/dc/ministagger"); + provider.loadTable("/geometry/dc/endplatesbow"); } if(type==DetectorType.ECAL){ @@ -101,6 +102,7 @@ public static ConstantProvider getConstants(DetectorType type, int run, String v provider.loadTable("/geometry/cvt/svt/material/box"); provider.loadTable("/geometry/cvt/svt/material/tube"); provider.loadTable("/geometry/cvt/svt/alignment"); + provider.loadTable("/geometry/target"); } if(type==DetectorType.TARGET){ diff --git a/common-tools/clas-detector/src/main/java/org/jlab/detector/calib/utils/ConstantsManager.java b/common-tools/clas-detector/src/main/java/org/jlab/detector/calib/utils/ConstantsManager.java index 7d40695e0f..8e76419037 100644 --- a/common-tools/clas-detector/src/main/java/org/jlab/detector/calib/utils/ConstantsManager.java +++ b/common-tools/clas-detector/src/main/java/org/jlab/detector/calib/utils/ConstantsManager.java @@ -22,8 +22,12 @@ public class ConstantsManager { private DatabaseConstantsDescriptor defaultDescriptor = new DatabaseConstantsDescriptor(); private volatile Map runConstants = new LinkedHashMap(); + private volatile Map runConstantRequestHistory = new LinkedHashMap(); + private String databaseVariation = "default"; private String timeStamp = ""; + private int requestStatus = 0; + private int maxRequests = 2; private volatile Map rcdbConstants = new LinkedHashMap(); @@ -51,6 +55,10 @@ public synchronized void init(List tables){ this.defaultDescriptor.addTables(tables); } + public int getRequestStatus(){ + return requestStatus; + } + public synchronized void init(List keys, List tables){ Set keysSet = new LinkedHashSet(keys); Set tablesSet = new LinkedHashSet(tables); @@ -85,6 +93,18 @@ private synchronized void loadConstantsForRun(int run){ if(this.runConstants.containsKey(run)==true) return; + if(this.runConstantRequestHistory.containsKey(run)==false){ + runConstantRequestHistory.put(run, 1); + } else { + int requests = runConstantRequestHistory.get(run); + runConstantRequestHistory.put(run, requests+1); + if(requests>maxRequests) { + requestStatus = -1; + System.out.println("[ConstantsManager] exceeded maximum requests " + requests + " for run " + run); + } + } + //String historyString = + //if() System.out.println("[ConstantsManager] ---> loading table for run = " + run); DatabaseConstantsDescriptor desc = defaultDescriptor.getCopy(run); DatabaseConstantProvider provider = new DatabaseConstantProvider(run, @@ -118,6 +138,10 @@ private synchronized void loadConstantsForRun(int run){ rcdbpro.disconnect(); } + public void reset(){ + this.runConstants.clear(); + } + @Override public String toString(){ StringBuilder str = new StringBuilder(); @@ -229,9 +253,12 @@ public static void main(String[] args){ manager.init(Arrays.asList(new String[]{ "/daq/fadc/ec", "/daq/fadc/ftof","/daq/fadc/htcc"})); - - IndexedTable table1 = manager.getConstants(10, "/daq/fadc/htcc"); - IndexedTable table2 = manager.getConstants(10, "/daq/fadc/ec"); - IndexedTable table3 = manager.getConstants(12, "/daq/fadc/htcc"); + for(int i = 0; i < 5 ; i++){ + IndexedTable table1 = manager.getConstants(10, "/daq/fadc/htcc"); + IndexedTable table2 = manager.getConstants(10, "/daq/fadc/ec"); + IndexedTable table3 = manager.getConstants(12, "/daq/fadc/htcc"); + manager.reset(); + System.out.println("\n\n STATUS = " + manager.getRequestStatus()); + } } } diff --git a/common-tools/clas-detector/src/main/java/org/jlab/detector/calib/utils/RCDBConstants.java b/common-tools/clas-detector/src/main/java/org/jlab/detector/calib/utils/RCDBConstants.java index 2372350831..429be436b2 100644 --- a/common-tools/clas-detector/src/main/java/org/jlab/detector/calib/utils/RCDBConstants.java +++ b/common-tools/clas-detector/src/main/java/org/jlab/detector/calib/utils/RCDBConstants.java @@ -70,7 +70,7 @@ public Long getLong(String key) { } public Time getTime(String key) { if (data.containsKey(key)) { - if (data.get(key).getValue() instanceof Double) { + if (data.get(key).getValue() instanceof Time) { return (Time) data.get(key).getValue(); } } diff --git a/common-tools/clas-detector/src/main/java/org/jlab/detector/decode/BonusDecoder.java b/common-tools/clas-detector/src/main/java/org/jlab/detector/decode/BonusDecoder.java new file mode 100644 index 0000000000..d71b693fcf --- /dev/null +++ b/common-tools/clas-detector/src/main/java/org/jlab/detector/decode/BonusDecoder.java @@ -0,0 +1,101 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.jlab.detector.decode; + +import java.util.ArrayList; +import java.util.List; +import org.jlab.coda.jevio.EvioNode; +import org.jlab.io.evio.EvioDataEvent; +import org.jlab.io.evio.EvioTreeBranch; +import org.jlab.io.evio.EvioSource; +/** + * + * @author gavalian + */ +public class BonusDecoder { + private CodaEventDecoder codaDecoder = null; + private EvioSource reader = new EvioSource(); + + public BonusDecoder(){ + codaDecoder = new CodaEventDecoder(); + } + + public void open(String filename){ + reader.open(filename); + } + + public boolean hasEvent(){ + return reader.hasEvent(); + } + + public List nextEvent(int crate){ + + EvioDataEvent event = (EvioDataEvent) reader.getNextEvent(); + List branches = codaDecoder.getEventBranches(event); + //System.out.println("Next Event-----"); + for(int i = 0; i < branches.size(); i++){ + EvioTreeBranch branch = branches.get(i); + //System.out.println("node found : tag = " + branch.getTag() + " num = " + branch.getNum()); + if(branch.getTag()==crate){ + for(EvioNode node : branch.getNodes()){ + /*System.out.println("\t ["+branch.getTag()+"] : node : tag = " + + node.getTag() + " , num = " + node.getNum() + ", type = " + + node.getDataTypeObj());*/ + if(node.getTag()==57641){ + //System.out.println("analyzing data----"); + List data = codaDecoder.getDataEntries_57641(crate, node, event); + return data; + //System.out.println("data size = " + data.size()); + /*for(int d = 0; d < data.size(); d++){ + System.out.println(data.get(d).toString()); + //data.get(i). + }*/ + } + } + } + } + return new ArrayList(); + //EvioTreeBranch cbranch = codaDecoder.getEventBranch(branches, crate); + //if(cbranch == null ) return ; +/* + for (EvioNode node : cbranch.getNodes()) { + if(node.getTag()==57641){ + // This is bit-packed PULSE mode for BONUS + System.err.println("found tag = " + node.getTag() + " " + node.getNum()); + //getDataEntries_57640(crate, node, event); + } + }*/ + } + + public static void main(String[] args){ + String filename = "/Users/gavalian/Work/DataSpace/clas12/bonus/bonustest_000002.evio.00000"; + BonusDecoder decoder = new BonusDecoder(); + decoder.open(filename); + int counter = 0; + while(decoder.hasEvent()==true&&counter<100){ + counter++; + decoder.nextEvent(63); + + List data = decoder.nextEvent(63); + System.out.println("printout event # " + counter); + for(int i = 0; i < data.size(); i++){ + DetectorDataDgtz bonusData = data.get(i); + long timestamp = bonusData.getADCData(0).getTimeStamp(); + short[] pulse = bonusData.getADCData(0).getPulseArray(); + System.out.println("TIME STAMP = " + timestamp); + int crate = bonusData.getDescriptor().getCrate(); + int slot = bonusData.getDescriptor().getSlot(); + int channel = bonusData.getDescriptor().getChannel(); + System.out.printf("CRATE : %5d , SLOT : %5d , CHANNEL = %5d \n",crate,slot,channel); + System.out.printf("%6d : ",pulse.length); + for(int p = 0; p < pulse.length; p++){ + System.out.printf("%6d ", pulse[p]); + } + System.out.println(); + } + } + } +} diff --git a/common-tools/clas-detector/src/main/java/org/jlab/detector/decode/CLASDecoder4.java b/common-tools/clas-detector/src/main/java/org/jlab/detector/decode/CLASDecoder4.java index 3b98499074..d6443a8731 100644 --- a/common-tools/clas-detector/src/main/java/org/jlab/detector/decode/CLASDecoder4.java +++ b/common-tools/clas-detector/src/main/java/org/jlab/detector/decode/CLASDecoder4.java @@ -273,6 +273,7 @@ public Bank getDataBankADC(String name, DetectorType type){ adcBANK.putInt("integral", i, adcDGTZ.get(i).getADCData(0).getIntegral()); adcBANK.putLong("timestamp", i, adcDGTZ.get(i).getADCData(0).getTimeStamp()); } + if(name == "BAND::adc") adcBANK.putInt("amplitude", i, adcDGTZ.get(i).getADCData(0).getHeight()); } return adcBANK; } @@ -451,7 +452,20 @@ public Event getDataEvent(){ } catch(Exception e) { e.printStackTrace(); } - + //----------------------------------------------------- + // CREATING BONUS BANK -------------------------------- + //----------------------------------------------------- + try { + //System.out.println("creating bonus bank...."); + Bank bonusBank = this.createBonusBank(); + if(bonusBank!=null){ + if(bonusBank.getRows()>0){ + event.write(bonusBank); + } + } + } catch(Exception e) { + e.printStackTrace(); + } return event; } @@ -602,7 +616,51 @@ public Bank createReconScalerBank(Event event){ return scalerBank; } - + + public Bank createBonusBank(){ + //System.out.println("create bonus bank function..."); + if(schemaFactory.hasSchema("RTPC::adc")==false) return null; + //System.out.println("bank descriptor does exist"); + List bonusData = this.getEntriesADC(DetectorType.RTPC); + //System.out.println("number of entries in the list = " + bonusData.size() + //+ " data list size = " + dataList.size()); + int totalSize = 0; + for(int i = 0; i < bonusData.size(); i++){ + short[] pulse = bonusData.get(i).getADCData(0).getPulseArray(); + totalSize += pulse.length; + } + + Bank bonusBank = new Bank(schemaFactory.getSchema("RTPC::adc"), totalSize); + int currentRow = 0; + for(int i = 0; i < bonusData.size(); i++){ + + DetectorDataDgtz bonus = bonusData.get(i); + + short[] pulses = bonus.getADCData(0).getPulseArray(); + long timestamp = bonus.getADCData(0).getTimeStamp(); + double time = bonus.getADCData(0).getTime(); + double coeff = time*120.0; + + double offset1 = 0.0; + double offset2 = (double) (8*(timestamp%8)); + + for(int k = 0; k < pulses.length; k++){ + + double pulseTime = coeff + offset1 + offset2 + k*120.0; + + bonusBank.putByte("sector", currentRow, (byte) bonus.getDescriptor().getSector()); + bonusBank.putByte("layer" , currentRow, (byte) bonus.getDescriptor().getLayer()); + bonusBank.putShort("component", currentRow, (short) bonus.getDescriptor().getComponent()); + bonusBank.putByte("order", currentRow, (byte) bonus.getDescriptor().getOrder()); + bonusBank.putInt("ADC", currentRow, pulses[k]); + bonusBank.putFloat("time", currentRow, (float) pulseTime); + bonusBank.putShort("ped", currentRow, (short) 0); + currentRow++; + } + } + + return bonusBank; + } public Bank createHelicityFlipBank(Event event,HelicityState state) { IndexedTable hwpTable=this.detectorDecoder.scalerManager.getConstants( this.detectorDecoder.getRunNumber(),"/runcontrol/hwp"); @@ -769,6 +827,9 @@ public static void main(String[] args){ counter++; progress.updateStatus(); + if(counter%25000==0){ + System.gc(); + } if(nevents>0){ if(counter>=nevents) break; } diff --git a/common-tools/clas-detector/src/main/java/org/jlab/detector/decode/CodaEventDecoder.java b/common-tools/clas-detector/src/main/java/org/jlab/detector/decode/CodaEventDecoder.java index 2622173406..f42791afda 100644 --- a/common-tools/clas-detector/src/main/java/org/jlab/detector/decode/CodaEventDecoder.java +++ b/common-tools/clas-detector/src/main/java/org/jlab/detector/decode/CodaEventDecoder.java @@ -44,9 +44,11 @@ public class CodaEventDecoder { private int timeStampErrors = 0; private long triggerBits = 0; private byte helicityLevel3 = HelicityBit.UDF.value(); - private List triggerWords = new ArrayList<>(); + private List triggerWords = new ArrayList<>(); JsonObject epicsData = new JsonObject(); + private final long timeStampTolerance = 0L; + public CodaEventDecoder(){ } @@ -86,7 +88,7 @@ public JsonObject getEpicsData(){ public List getTriggerWords(){ return this.triggerWords; } - + private void printByteBuffer(ByteBuffer buffer, int max, int columns){ int n = max; if(buffer.capacity()0) { long ts = tiEntries.get(0).getTimeStamp(); for(int i=1; ithis.timeStampTolerance) { tiSync=false; if(this.timeStampErrors<100) { System.out.println("WARNING: mismatch in TI time stamps: crate " + tiEntries.get(i).getDescriptor().getCrate() + " reports " - + tiEntries.get(i).getTimeStamp() + " instead of " + ts); + + tiEntries.get(i).getTimeStamp() + " instead of the " + ts + + " from crate " + tiEntries.get(0).getDescriptor().getCrate()); this.timeStampErrors++; } } @@ -151,7 +154,7 @@ public void setTriggerBits(long triggerBits) { this.triggerBits = triggerBits; } - + public List getADCEntries(EvioDataEvent event){ List entries = new ArrayList(); List branches = this.getEventBranches(event); @@ -163,38 +166,38 @@ public List getADCEntries(EvioDataEvent event){ } return entries; } - + public List getADCEntries(EvioDataEvent event, int crate){ List entries = new ArrayList(); - + List branches = this.getEventBranches(event); EvioTreeBranch cbranch = this.getEventBranch(branches, crate); - + if(cbranch == null ) return null; - + for(EvioNode node : cbranch.getNodes()){ if(node.getTag()==57638){ //System.out.println(" NODE = " + node.getTag() + " , " + node.getNum() + - // " , " + node.getTypeObj().name()); + // " , " + node.getTypeObj().name()); return this.getDataEntries_57638(crate, node, event); } } - + return entries; } - + public List getADCEntries(EvioDataEvent event, int crate, int tagid){ - + List adc = new ArrayList(); List branches = this.getEventBranches(event); - + EvioTreeBranch cbranch = this.getEventBranch(branches, crate); if(cbranch == null ) return null; - + for(EvioNode node : cbranch.getNodes()){ -// +// //if(node.getTag()==57638){ if(node.getTag()==tagid){ // This is regular integrated pulse mode, used for FTOF @@ -202,11 +205,11 @@ public List getADCEntries(EvioDataEvent event, int crate, int tagid){ return this.getADCEntries_Tag(crate, node, event,tagid); //return this.getDataEntriesMode_7(crate,node, event); } - + } return adc; } - + /** * returns list of decoded data in the event for given crate. * @param event @@ -226,7 +229,7 @@ public List getDataEntries(EvioDataEvent event, int crate){ // This is regular integrated pulse mode, used for FTOF // FTCAL and EC/PCAL //return this.getDataEntries_57602(crate, node, event); - + this.readHeaderBank(crate, node, event); //return this.getDataEntriesMode_7(crate,node, event); } @@ -245,7 +248,7 @@ public List getDataEntries(EvioDataEvent event, int crate){ // This is regular integrated pulse mode, used for FTOF // FTCAL and EC/PCAL //return this.getDataEntries_57602(crate, node, event); - + return this.getDataEntries_57617(crate, node, event); //return this.getDataEntriesMode_7(crate,node, event); } @@ -253,33 +256,33 @@ else if(node.getTag()==57602){ // This is regular integrated pulse mode, used for FTOF // FTCAL and EC/PCAL //return this.getDataEntries_57602(crate, node, event); - + return this.getDataEntries_57602(crate, node, event); //return this.getDataEntriesMode_7(crate,node, event); } else if(node.getTag()==57601){ // This is regular integrated pulse mode, used for FTOF // FTCAL and EC/PCAL - + return this.getDataEntries_57601(crate, node, event); //return this.getDataEntriesMode_7(crate,node, event); } else if(node.getTag()==57627){ // This is regular integrated pulse mode, used for MM - + return this.getDataEntries_57627(crate, node, event); //return this.getDataEntriesMode_7(crate,node, event); } else if(node.getTag()==57640){ // This is bit-packed pulse mode, used for MM - + return this.getDataEntries_57640(crate, node, event); //return this.getDataEntriesMode_7(crate,node, event); } else if(node.getTag()==57622){ // This is regular integrated pulse mode, used for FTOF // FTCAL and EC/PCAL - + return this.getDataEntries_57622(crate, node, event); //return this.getDataEntriesMode_7(crate,node, event); } @@ -287,6 +290,10 @@ else if(node.getTag()==57636){ // RICH TDC data return this.getDataEntries_57636(crate, node, event); //return this.getDataEntriesMode_7(crate,node, event); + } else if(node.getTag()==57641){ + // RTPC data decoding + return this.getDataEntries_57641(crate, node, event); + //return this.getDataEntriesMode_7(crate,node, event); } } return bankEntries; @@ -431,7 +438,7 @@ public ArrayList getDataEntries_57617(Integer crate, EvioNode int halfID = DataUtils.getInteger(halfWord, 3, 3); int adc = adcbyte; Integer channelKey = ((half<<8) | (channel & 0xff)); - + // System.err.println( "Half/chip = " + half + " CHIP = " + chipID + " HALF = " + halfID + " CHANNEL = " + channel + " KEY = " + channelKey ); // TDC data entry @@ -441,7 +448,7 @@ public ArrayList getDataEntries_57617(Integer crate, EvioNode chipID = DataUtils.getInteger(halfWord, 0, 1) + 1; channel = 0; channelKey = 0; - tdc = (short) ((adcbyte<<8) | (tdcbyte & 0xff)); + tdc = (short) ((adcbyte<<8) | (tdcbyte & 0xff)); // System.err.println( "Half/chip = " + half + " CHIP = " + chipID + " HALF = " + halfID + " TDC = " + tdcbyte + " ADC = " + adc + " Time = " + tdc ); adc = -1; } @@ -476,7 +483,7 @@ public ArrayList getDataEntries_57617(Integer crate, EvioNode } return rawdata; } - + public List getADCEntries_Tag(Integer crate, EvioNode node, EvioDataEvent event, int tagid){ List entries = new ArrayList(); if(node.getTag()==tagid){ @@ -570,7 +577,7 @@ public void decodeComposite(ByteBuffer buffer, int offset, List ctypes citems.add(counter); ctypes.add(DataType.NVALUE); position++; - + for(int i = 0; i < counter; i++){ Short channel = (short) (0x00FF&(buffer.get(position))); position++; @@ -592,7 +599,7 @@ public void decodeComposite(ByteBuffer buffer, int offset, List ctypes System.out.println("Exception : Length = " + length + " position = " + position); } } - + public List getDataEntries_57638(Integer crate, EvioNode node, EvioDataEvent event){ List entries = new ArrayList(); if(node.getTag()==57638){ @@ -600,7 +607,7 @@ public List getDataEntries_57638(Integer crate, EvioNode node, EvioDa ByteBuffer compBuffer = node.getByteData(true); //System.out.println(" COMPOSITE TYPE = " + node.getTypeObj().name() + " " + node.getDataTypeObj().name()); //System.out.println(" COMPOSITE BUFFER = " + compBuffer.array().length); - + /*for(int i = 0; i < compBuffer.array().length; i++){ short value = (short) (0x00FF&(compBuffer.array()[i])); System.out.println(String.format("%4d %4d ",i,value)); @@ -609,7 +616,7 @@ public List getDataEntries_57638(Integer crate, EvioNode node, EvioDa List cdatatypes = new ArrayList(); List cdataitems = new ArrayList(); this.decodeComposite(compBuffer, 24, cdatatypes, cdataitems); - + /*try { CompositeData compData = new CompositeData(compBuffer.array(),event.getByteOrder()); List ccdatatypes = compData.getTypes(); @@ -622,15 +629,15 @@ public List getDataEntries_57638(Integer crate, EvioNode node, EvioDa } catch (EvioException ex) { Logger.getLogger(CodaEventDecoder.class.getName()).log(Level.SEVERE, null, ex); }*/ - - - + + + /* CompositeData compData = new CompositeData(compBuffer.array(),event.getByteOrder()); List cdatatypes = compData.getTypes(); List cdataitems = compData.getItems(); - + */ /*if(cdatatypes.get(3) != DataType.NVALUE){ System.err.println("[EvioRawDataSource] ** error ** corrupted " @@ -643,7 +650,7 @@ public List getDataEntries_57638(Integer crate, EvioNode node, EvioDa while(position branches = this.getEventBranches(event); @@ -1152,7 +1252,7 @@ public List getDataEntries_Scalers(EvioDataEvent event){ SCALERData scaler = new SCALERData(); scaler.setHelicity((byte) helicity); scaler.setQuartet((byte) quartet); - scaler.setValue(value); + scaler.setValue(value); entry.addSCALER(scaler); scalerEntries.add(entry); } @@ -1164,12 +1264,12 @@ else if(node.getTag()==57621 && loop>=5) { if(id<3 && slot<4) { DetectorDataDgtz entry = new DetectorDataDgtz(crate,num,loop-5); SCALERData scaler = new SCALERData(); - scaler.setValue(DataUtils.getLongFromInt(dataEntry)); + scaler.setValue(DataUtils.getLongFromInt(dataEntry)); entry.addSCALER(scaler); scalerEntries.add(entry); // long long_data = 0; // long value = (long) ((long_data|dataEntry)&0x00000000FFFFFFFFL); -// System.out.println(loop + " " + crate + " " + slot + " " + id + " " + dataEntry + " " + value + " " + DataUtils.getLongFromInt(dataEntry) + " " + String.format("0x%08X", dataEntry) + " " + String.format("0x%16X", value)); +// System.out.println(loop + " " + crate + " " + slot + " " + id + " " + dataEntry + " " + value + " " + DataUtils.getLongFromInt(dataEntry) + " " + String.format("0x%08X", dataEntry) + " " + String.format("0x%16X", value)); } } } @@ -1180,8 +1280,8 @@ else if(node.getTag()==57621 && loop>=5) { } public List getDataEntries_VTP(EvioDataEvent event){ - - List vtpEntries = new ArrayList(); + + List vtpEntries = new ArrayList(); // this.triggerBank = null; //System.out.println(" READING TRIGGER BANK"); List branches = this.getEventBranches(event); @@ -1255,13 +1355,13 @@ public List getDataEntries_TI(EvioDataEvent event){ for(EvioNode node : cbranch.getNodes()){ if(node.getTag()==57610){ long[] longData = ByteDataTransformer.toLongArray(node.getStructureBuffer(true)); - int[] intData = ByteDataTransformer.toIntArray(node.getStructureBuffer(true)); + int[] intData = ByteDataTransformer.toIntArray(node.getStructureBuffer(true)); long tStamp = longData[2]&0x0000ffffffffffffL; // Below is endian swap if needed //long ntStamp = (((long)(intData[5]&0x0000ffffL))<<32) | (intData[4]&0xffffffffL); //System.out.println(longData[2]+" "+tStamp+" "+crate+" "+node.getDataLength()); - + DetectorDataDgtz entry = new DetectorDataDgtz(crate,0,0); entry.setTimeStamp(tStamp); if(node.getDataLength()==4) tiEntries.add(entry); @@ -1304,7 +1404,7 @@ public static void main(String[] args){ detectorDecoder.translate(dataSet); detectorDecoder.fitPulses(dataSet); if(decoder.getDataEntries_VTP(event).size()!=0) { -// for(DetectorDataDgtz entry : decoder.getDataEntries_VTP(event)) +// for(DetectorDataDgtz entry : decoder.getDataEntries_VTP(event)) // System.out.println(entry.toString()); } // System.out.println("---> printout EVENT # " + icounter); diff --git a/common-tools/clas-detector/src/main/java/org/jlab/detector/decode/DaqScalers.java b/common-tools/clas-detector/src/main/java/org/jlab/detector/decode/DaqScalers.java index f85c45e95e..8102364c9d 100644 --- a/common-tools/clas-detector/src/main/java/org/jlab/detector/decode/DaqScalers.java +++ b/common-tools/clas-detector/src/main/java/org/jlab/detector/decode/DaqScalers.java @@ -41,16 +41,33 @@ public class DaqScalers { private float beamCharge=0; private float beamChargeGated=0; private float livetime=0; + private long timestamp = 0; public Dsc2RawReading dsc2=null; public StruckRawReading struck=null; + public void setTimestamp(long timestamp) { this.timestamp=timestamp; } private void setBeamCharge(float q) { this.beamCharge=q; } private void setBeamChargeGated(float q) { this.beamChargeGated=q; } private void setLivetime(float l) { this.livetime=l; } public float getBeamCharge() { return beamCharge; } public float getBeamChargeGated() { return beamChargeGated; } public float getLivetime() { return livetime; } + public long getTimestamp() { return timestamp; } public void show() { System.out.println("BCG=%.3f LT=%.3f"); } + /** + * @param runScalerBank HIPO RUN::scaler bank + */ + public static DaqScalers create(Bank runScalerBank) { + DaqScalers ds=new DaqScalers(); + for (int ii=0; ii { + + private final List scalers=new ArrayList<>(); + + @Override + public int compare(DaqScalers o1, DaqScalers o2) { + if (o1.getTimestamp() < o2.getTimestamp()) return -1; + if (o1.getTimestamp() > o2.getTimestamp()) return +1; + return 0; + } + + private int findIndex(long timestamp) { + if (this.scalers.isEmpty()) return -1; + if (timestamp < this.scalers.get(0).getTimestamp()) return -1; + // assume late timestamps are ok and go with last readout, so comment this out: + //if (timestamp > this.scalers.get(this.scalers.size()-1).getTimestamp()) return -1; + // make a fake state for timestamp search: + DaqScalers ds=new DaqScalers(); + ds.setTimestamp(timestamp); + final int index=Collections.binarySearch(this.scalers,ds,new DaqScalersSequence()); + final int n = index<0 ? -index-2 : index; + return n; + } + + protected boolean add(DaqScalers ds) { + if (this.scalers.isEmpty()) { + this.scalers.add(ds); + return true; + } + else { + final int index=Collections.binarySearch(this.scalers,ds,new DaqScalersSequence()); + if (index==this.scalers.size()) { + // its timestamp is later than the existing sequence: + this.scalers.add(ds); + return true; + } + else if (index<0) { + // it's a unique timestamp, insert it: + this.scalers.add(-index-1,ds); + return true; + } + else { + // it's a duplicate timestamp, ignore it: + return false; + } + } + } + + /** + * @param timestamp TI timestamp (i.e. RUN::config.timestamp) + * @return the most recent DaqScalers for the given timestamp + */ + public DaqScalers get(long timestamp) { + final int n=this.findIndex(timestamp); + if (n>=0) return this.scalers.get(n); + return null; + } + + /** + * This reads tag=1 events for RUN::scaler banks, and initializes and returns + * a {@link DaqScalersSequence} that can be used to access the most recent scaler + * readout for any given event. + * + * @param filenames list of names of HIPO files to read + * @return sequence + */ + public static DaqScalersSequence readSequence(List filenames) { + + DaqScalersSequence seq=new DaqScalersSequence(); + + for (String filename : filenames) { + + HipoReader reader = new HipoReader(); + reader.setTags(1); + reader.open(filename); + + SchemaFactory schema = reader.getSchemaFactory(); + + while (reader.hasNext()) { + + Event event=new Event(); + Bank scalerBank=new Bank(schema.getSchema("RUN::scaler")); + Bank configBank=new Bank(schema.getSchema("RUN::config")); + + reader.nextEvent(event); + event.read(scalerBank); + event.read(configBank); + + long timestamp=0; + + if (scalerBank.getRows()<1) continue; + if (configBank.getRows()>0) { + timestamp=configBank.getLong("timestamp",0); + } + + DaqScalers ds=DaqScalers.create(scalerBank); + ds.setTimestamp(timestamp); + seq.add(ds); + } + + reader.close(); + } + + return seq; + } + + public static void main(String[] args) { + + final String dir="/Users/baltzell/data/CLAS12/rg-a/decoded/6b.2.0/"; + final String file="clas_005038.evio.00000-00004.hipo"; + //final String dir="/Users/baltzell/data/CLAS12/rg-b/decoded/"; + //final String file="clas_006432.evio.00041-00042.hipo"; + + List filenames=new ArrayList<>(); + if (args.length>0) filenames.addAll(Arrays.asList(args)); + else filenames.add(dir+file); + + // 1!!!1 initialize a sequence from tag=1 events: + DaqScalersSequence seq = DaqScalersSequence.readSequence(filenames); + + long good=0; + long bad=0; + + for (String filename : filenames) { + + HipoReader reader = new HipoReader(); + reader.setTags(0); + reader.open(filename); + + SchemaFactory schema = reader.getSchemaFactory(); + + while (reader.hasNext()) { + + Bank rcfgBank=new Bank(schema.getSchema("RUN::config")); + + Event event=new Event(); + reader.nextEvent(event); + + event.read(rcfgBank); + + long timestamp = -1; + if (rcfgBank.getRows()>0) + timestamp = rcfgBank.getLong("timestamp",0); + + // 2!!!2 use the timestamp to get the most recent scaler data: + DaqScalers ds=seq.get(timestamp); + + if (ds==null) { + bad++; + } + else { + good++; + // do something useful with beam charge here: + System.out.println(timestamp+" "+ds.getBeamCharge()+" "+ds.getBeamChargeGated()); + } + } + + System.out.println("DaqScalersSequence: bad/good/badPercent: " + +bad+" "+good+" "+100*((float)bad)/(bad+good)+"%"); + + reader.close(); + + } + } +} diff --git a/common-tools/clas-detector/src/main/java/org/jlab/detector/decode/DetectorDataDgtz.java b/common-tools/clas-detector/src/main/java/org/jlab/detector/decode/DetectorDataDgtz.java index 32260b1ff2..9b4b7caaf5 100644 --- a/common-tools/clas-detector/src/main/java/org/jlab/detector/decode/DetectorDataDgtz.java +++ b/common-tools/clas-detector/src/main/java/org/jlab/detector/decode/DetectorDataDgtz.java @@ -312,10 +312,19 @@ public ADCData setTime(int time){ @Override public String toString(){ + int nsamples = 0; + if(this.adcPulse.isEmpty()==false) nsamples = adcPulse.get(0).length; StringBuilder str = new StringBuilder(); - str.append(String.format("ADC (%d) : %5d %5d %5d time = %5d %9.4f max = %5d", - getOrder(), + if(nsamples>0){ + str.append("PULSE : "); + for(int i = 0; i < nsamples; i++){ + str.append(String.format("%5d ", adcPulse.get(0)[i])); + } + } else { + str.append(String.format("ADC (%d) (L=%6d) : %5d %5d %5d time = %5d %9.4f max = %5d", + getOrder(), nsamples, getIntegral(),getADC(), getPedestal(), getTimeCourse(), getTime(), getHeight())); + } return str.toString(); } diff --git a/common-tools/clas-detector/src/main/java/org/jlab/detector/decode/DetectorEventDecoder.java b/common-tools/clas-detector/src/main/java/org/jlab/detector/decode/DetectorEventDecoder.java index 776505686e..ce936f5f94 100644 --- a/common-tools/clas-detector/src/main/java/org/jlab/detector/decode/DetectorEventDecoder.java +++ b/common-tools/clas-detector/src/main/java/org/jlab/detector/decode/DetectorEventDecoder.java @@ -87,24 +87,27 @@ public DetectorEventDecoder(){ } public final void initDecoderDev(){ - keysTrans = Arrays.asList(new String[]{ "HTCC","BST"} ); - tablesTrans = Arrays.asList(new String[]{ "/daq/tt/clasdev/htcc","/daq/tt/clasdev/svt" }); + keysTrans = Arrays.asList(new String[]{ "HTCC","BST","RTPC"} ); + tablesTrans = Arrays.asList(new String[]{ "/daq/tt/clasdev/htcc","/daq/tt/clasdev/svt" + ,"/daq/tt/clasdev/rtpc" }); keysFitter = Arrays.asList(new String[]{"HTCC"}); tablesFitter = Arrays.asList(new String[]{"/daq/fadc/clasdev/htcc"}); translationManager.init(keysTrans,tablesTrans); fitterManager.init(keysFitter, tablesFitter); + + scalerManager.init(Arrays.asList(new String[]{"/runcontrol/fcup","/runcontrol/hwp"})); } public final void initDecoder(){ keysTrans = Arrays.asList(new String[]{ - "FTCAL","FTHODO","FTTRK","LTCC","ECAL","FTOF","HTCC","DC","CTOF","CND","BST","RF","BMT","FMT","RICH","HEL","BAND" + "FTCAL","FTHODO","FTTRK","LTCC","ECAL","FTOF","HTCC","DC","CTOF","CND","BST","RF","BMT","FMT","RICH","HEL","BAND","RTPC" }); tablesTrans = Arrays.asList(new String[]{ "/daq/tt/ftcal","/daq/tt/fthodo","/daq/tt/fttrk","/daq/tt/ltcc", "/daq/tt/ec","/daq/tt/ftof","/daq/tt/htcc","/daq/tt/dc","/daq/tt/ctof","/daq/tt/cnd","/daq/tt/svt", - "/daq/tt/rf","/daq/tt/bmt","/daq/tt/fmt","/daq/tt/rich","/daq/tt/hel","/daq/tt/band" + "/daq/tt/rf","/daq/tt/bmt","/daq/tt/fmt","/daq/tt/rich","/daq/tt/hel","/daq/tt/band","/daq/tt/rtpc" }); translationManager.init(keysTrans,tablesTrans); diff --git a/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicityAnalysis.java b/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicityAnalysis.java deleted file mode 100644 index d43bfef54b..0000000000 --- a/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicityAnalysis.java +++ /dev/null @@ -1,158 +0,0 @@ -package org.jlab.detector.helicity; - -import java.util.List; -import java.util.ArrayList; -import java.util.Arrays; - -import org.jlab.jnp.hipo4.io.HipoReader; -import org.jlab.jnp.hipo4.data.Event; -import org.jlab.jnp.hipo4.data.Bank; -import org.jlab.jnp.hipo4.data.SchemaFactory; - -/** - * An example of reading the helicity flips, analyzing the sequence, and getting - * the state for any event. - * - * @author baltzell - */ -public class HelicityAnalysis { - - /** - * This reads tag=1 events for HEL::flip banks, and initializes and returns - * a {@link HelicitySequenceDelayed} with delay set to zero. The delay can - * be changed later before a user tries to access the sequence. - * - * @param filenames list of names of HIPO file to read - * @return unanalyzed sequence - */ - public static HelicitySequenceDelayed readSequence(List filenames) { - - HelicitySequenceDelayed seq=new HelicitySequenceDelayed(8); - - for (String filename : filenames) { - - HipoReader reader = new HipoReader(); - reader.setTags(1); - reader.open(filename); - - SchemaFactory schema = reader.getSchemaFactory(); - - while (reader.hasNext()) { - - Event event=new Event(); - Bank flipBank=new Bank(schema.getSchema("HEL::flip")); - - reader.nextEvent(event); - event.read(flipBank); - - if (flipBank.getRows()<1) continue; - - seq.addState(HelicityState.createFromFlipBank(flipBank)); - } - - reader.close(); - } - - return seq; - } - - public static void main(String[] args) { - - final String dir="/Users/baltzell/data/CLAS12/rg-a/decoded/6b.2.0/"; - final String file="clas_005038.evio.00000-00004.hipo"; - //final String dir="/Users/baltzell/data/CLAS12/rg-b/decoded/"; - //final String file="clas_006432.evio.00041-00042.hipo"; - - List filenames=new ArrayList<>(); - if (args.length>0) filenames.addAll(Arrays.asList(args)); - else filenames.add(dir+file); - - // initialize a sequence from tag=1 events: - HelicitySequenceDelayed seq = HelicityAnalysis.readSequence(filenames); - seq.setVerbosity(1); - final boolean integrity = seq.analyze(); - if (!integrity) { - System.err.println("\n\n######### OOPS\n\n"); - // We may want to investigate further, or discard events. - } - - // print the sequence: - seq.show(); - - // set the appropriate delay for this data: - seq.setDelay(8); - - // now read the full events, e.g. during a normal physics analysis: - int nevents=0; - int nflips=0; - - for (String filename : filenames) { - - HipoReader reader = new HipoReader(); - reader.setTags(0); - reader.open(filename); - - SchemaFactory schema = reader.getSchemaFactory(); - - while (reader.hasNext()) { - - nevents++; - - Bank flipBank=new Bank(schema.getSchema("HEL::flip")); - Bank rcfgBank=new Bank(schema.getSchema("RUN::config")); - Bank onliBank=new Bank(schema.getSchema("HEL::online")); - - Event event=new Event(); - reader.nextEvent(event); - event.read(flipBank); - event.read(rcfgBank); - event.read(onliBank); - - // just to curtail printouts: - if (flipBank.getRows()>0) nflips++; - if (nflips<240) continue; - if (nevents%100!=0) continue; - - long timestamp = -1; - HelicityBit level3 = HelicityBit.UDF; - HelicityBit predicted = HelicityBit.UDF; - HelicityBit measured = HelicityBit.UDF; - HelicityBit lookedup = HelicityBit.UDF; - - // Get RUN::config.timestamp for this event: - if (rcfgBank.getRows()>0) - timestamp = rcfgBank.getLong("timestamp",0); - - // Get HEL::online.rawHelicity, the online, delay-corrected - // helicity for this event (if available): - if (onliBank.getRows()>0) - level3 = HelicityBit.create(onliBank.getByte("helicity",0)); - - // Get the offline, delay-corrected helicity for this event based - // on the measured sequence. If this timestamp is outside the - // measured range, the bit will be null. - if (seq.find(timestamp)!=null) - measured = seq.find(timestamp); - - // Same as previous, except use the pseudo-random generator's - // prediction which provides for bits later than the measured range. - // For example, the last N windows in a given file are measured in - // the next file (or not at all if it's the last file in a run), - // so will only be accessible with the generator. If you try to - // use a timestamp before the measured sequence, the generator will - // return null. - if (seq.findPrediction(timestamp)!=null) - predicted = seq.findPrediction(timestamp); - - if (seq.lookupPrediction(timestamp)!=null) - lookedup = seq.lookupPrediction(timestamp); - - System.out.println(String.format("%d %5d L3/Predict/Measured/Looked = %6s%6s%6s%6s", - timestamp,nflips,level3,predicted,measured,lookedup)); - } - - reader.close(); - - } - } -} diff --git a/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicityAnalysisSimple.java b/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicityAnalysisSimple.java index 1faeffa4cf..def72512a6 100644 --- a/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicityAnalysisSimple.java +++ b/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicityAnalysisSimple.java @@ -1,106 +1,124 @@ package org.jlab.detector.helicity; +import java.util.List; import java.util.ArrayList; import java.util.Arrays; -import java.util.List; -import org.jlab.jnp.hipo4.data.Bank; + +import org.jlab.jnp.hipo4.io.HipoReader; import org.jlab.jnp.hipo4.data.Event; +import org.jlab.jnp.hipo4.data.Bank; import org.jlab.jnp.hipo4.data.SchemaFactory; -import org.jlab.jnp.hipo4.io.HipoReader; /** + * An example of reading the helicity flips, analyzing the sequence, and getting + * the state for any event. * + * The 2 lines marked with "!!!" are the essential delayed-helicity correction + * and requires input from RUN::config.run and RUN::config.timestamp. + * * @author baltzell */ public class HelicityAnalysisSimple { - /** - * Example of accessing delay-corrected helicity. - * - * The 2 lines marked with "!!!" are specific to delay-corrected helicity. - * - * @param args a list of input HIPO4 filenames - */ public static void main(String[] args) { + + //final String dir="/Users/baltzell/data/CLAS12/rg-a/decoded/6b.2.0/"; + //final String file="clas_005038.evio.00000-00004.hipo"; + final String dir="/Users/baltzell/data/CLAS12/rg-b/decoded/"; + final String file="clas_006432.evio.00041-00042.hipo"; - final String dir="/Users/baltzell/data/CLAS12/rg-a/decoded/6b.2.0/"; - final String file="clas_005038.evio.00000-00004.hipo"; - //final String dir="/Users/baltzell/data/CLAS12/rg-b/decoded/"; - //final String file="clas_006432.evio.00041-00042.hipo"; List filenames=new ArrayList<>(); - - // override with user-inputs if available: if (args.length>0) filenames.addAll(Arrays.asList(args)); else filenames.add(dir+file); - // 1!!!1 initialize the helicity sequence: - HelicitySequenceDelayed seq = HelicityAnalysis.readSequence(filenames); - - seq.setVerbosity(2); + // !!! 111 + // initialize a sequence, with delay=8, from tag=1 events: + HelicitySequenceManager seq = new HelicitySequenceManager(8,filenames); - seq.analyze(); - - seq.show(); + // or initialize with a reader object: + //HelicitySequenceManager seq = new HelicitySequenceManager(8,HipoReader); + + // increase info printouts: + //seq.setVerbosity(2); + // print the sequence if any problems: + //if (!seq.analyze()) seq.show(); + // now read the full events, e.g. during a normal physics analysis: - - int nGoodEvents=0; - int nBadEvents=0; - int nMismatches=0; - int nMismatches2=0; + int nevents=0; + int nflips=0; + int nbad=0; - // loop over files: for (String filename : filenames) { - // open the file, initialize reader/tags/schema: HipoReader reader = new HipoReader(); reader.setTags(0); reader.open(filename); + SchemaFactory schema = reader.getSchemaFactory(); - - // loop over events: + while (reader.hasNext()) { - - // read the event: - Event event=new Event(); - reader.nextEvent(event); + + nevents++; - // get the event's timestamp: + Bank flipBank=new Bank(schema.getSchema("HEL::flip")); Bank rcfgBank=new Bank(schema.getSchema("RUN::config")); + Bank onliBank=new Bank(schema.getSchema("HEL::online")); + + Event event=new Event(); + reader.nextEvent(event); + event.read(flipBank); event.read(rcfgBank); - if (rcfgBank.getRows()<=0) continue; - final int evno = rcfgBank.getInt("event",0); + event.read(onliBank); + + // Get RUN::config.runno/timestamp for this event: + if (rcfgBank.getRows()<=0) continue; final long timestamp = rcfgBank.getLong("timestamp",0); - - // 2!!!2 use the timestamp to get the delay-corrected helicity: - HelicityBit predicted = seq.findPrediction(timestamp); + final int runno = rcfgBank.getInt("run",0); - HelicityBit lookup = seq.lookupPrediction(timestamp); - if (lookup!=HelicityBit.UDF && predicted!=lookup) { - nMismatches++; - } - HelicityBit measured = seq.find(timestamp); - if (measured!=HelicityBit.UDF && predicted!=measured) { - nMismatches2++; - } + // Get HEL::online.rawHelicity, the online, delay-corrected + // helicity for this event (if available): + //HelicityBit level3 = HelicityBit.UDF; + //if (onliBank.getRows()>0) + // level3 = HelicityBit.create(onliBank.getByte("helicity",0)); + + // !!! 222 + // Get the offline, delay-corrected helicity for this event + // based on the measured sequence. If the timestamp is outside + // the measured range, or the measured sequence is corrupted between + // the timestamp and the delayed timestamp, this will return null. + final HelicityBit measured = seq.search(runno,timestamp); + + // Same as previous, except assumes the pseudo-random generator's + // prediction, which allows to access states later than the measured + // range and cross intermediate sequence corruption. However, it + // requires a 4x longer consecutive valid sequence for initialization + // than the non-generator methods. + //final HelicityBit lookedup = seq.searchGenerated(runno,timestamp); - if ( (predicted==null || predicted==HelicityBit.UDF) && - timestamp>=seq.generator.getTimestamp()) { - nBadEvents++; - System.out.println(String.format("Bad Helicity: event=%d time=%d helicity=%s",evno,timestamp,predicted)); + // Same as previous, except relies on TI clock synced with helicity clock + // instead of counting states: + //final HelicityBit predicted = seq.predictGenerated(runno,timestamp); + + if (measured==HelicityBit.UDF) { + nbad++; } else { - // proceed with physics analysis: - nGoodEvents++; + // proceed with physics analysis } + + //if (flipBank.getRows()>0) nflips++; + //if (nflips>240 && nevents%100!=0) { + // System.out.println(String.format("%d %5d L3/Measured/LookedG/PredictG = %6s%6s%6s%6s", + // timestamp,nflips,level3,measured,lookedup,predicted)); + //} } + + System.out.println(String.format("HelicityAnalysisSimple: EVENTS BAD/TOTAL/FRACTION = %d/%d/%.2f%%", + nbad,nevents,100*((float)nbad)/nevents)); + reader.close(); + } - System.out.println(String.format("HelicityAnalysisSimple: BAD/GOOD/FRACTION=%d/%d/%.5f%%", - nBadEvents,nGoodEvents,100*((float)nBadEvents)/(nBadEvents+nGoodEvents))); - //System.out.println(String.format("HelicityAnalysisSimple: MISMATCHES/FRACTION=%d/%.5f%%", - // nMismatches,100*((float)nMismatches)/(nBadEvents+nGoodEvents))); - System.out.println(String.format("HelicityAnalysisSimple: MISMATCHES2/FRACTION=%d/%.5f%%", - nMismatches2,100*((float)nMismatches2)/(nBadEvents+nGoodEvents))); } } diff --git a/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicityBit.java b/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicityBit.java index c1604e5b23..2d9998b335 100644 --- a/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicityBit.java +++ b/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicityBit.java @@ -32,6 +32,7 @@ public static HelicityBit create(byte value) { public static HelicityBit getFlipped(HelicityBit bit) { if (bit==PLUS) return MINUS; if (bit==MINUS) return PLUS; + if (bit==DNE) return DNE; return UDF; } diff --git a/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicityGenerator.java b/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicityGenerator.java index 23b213bb22..9d0f33e9ee 100644 --- a/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicityGenerator.java +++ b/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicityGenerator.java @@ -3,6 +3,7 @@ import java.util.List; import java.util.ArrayList; import java.util.Collections; +import java.util.Comparator; /** * Helicity Pseudo-Random Sequence. @@ -24,7 +25,7 @@ * * @author baltzell */ -public final class HelicityGenerator { +public final class HelicityGenerator implements Comparable, Comparator { public static final int REGISTER_SIZE=30; private final List states=new ArrayList<>(); @@ -32,9 +33,12 @@ public final class HelicityGenerator { private int register=0; private long timestamp=0; private int verbosity=0; + private double clock=29.56; // Hz public HelicityGenerator(){} + public void setClock(double clock){this.clock=clock;} + /** * Get the next bit in the sequence. * Requires initialized()==true. @@ -48,6 +52,18 @@ private int getNextBit() { return nextBit; } + @Override + public int compareTo(HelicityGenerator other) { + if (this.getTimestamp() < other.getTimestamp()) return -1; + if (this.getTimestamp() > other.getTimestamp()) return +1; + return 0; + } + + @Override + public int compare(HelicityGenerator o1, HelicityGenerator o2) { + return o1.compareTo(o2); + } + /** * Get the timestamp of the first state in the generator sequence. * @return timestamp (4ns) @@ -85,7 +101,7 @@ public void reset() { /** * Test whether the generator is sufficiently initialized such that - * {@link getState(int)} method can be called, based on whether the + * {@link #get(int)} method can be called, based on whether the * number of added states is at least {@link REGISTER_SIZE}. * * @return whether the sequence is initialized @@ -146,7 +162,7 @@ public void addState(HelicityState state) { * @param n number of states after the first one. * @return the nth HelicityBit in the sequence. */ - public HelicityBit getState(final int n) { + public HelicityBit get(final int n) { if (!this.initialized()) throw new RuntimeException("Not initialized."); if (n < 0) @@ -232,8 +248,8 @@ else if (iStates.size() > 2 && prevState.getTimestamp()) / HelicitySequence.TIMESTAMP_CLOCK; // bad timestamp delta, reset the sequence: - if (seconds < (1.0-0.5)/HelicitySequence.HELICITY_CLOCK || - seconds > (1.0+0.5)/HelicitySequence.HELICITY_CLOCK) { + if (seconds < (1.0-0.5)/this.clock || + seconds > (1.0+0.5)/this.clock) { if (this.verbosity>1){ System.out.println("HelicityGenerator: got bad timestamp, resetting... "); } @@ -296,7 +312,7 @@ else if (iStates.size() > 2 && // subtract off the nominal flip period: if (this.size() > 0) { long timeStamp=state.getTimestamp(); - double corr=(jj-this.offset)/HelicitySequence.HELICITY_CLOCK*HelicitySequence.TIMESTAMP_CLOCK; + double corr=(jj-this.offset)/this.clock*HelicitySequence.TIMESTAMP_CLOCK; timestamps.add(timeStamp-corr); timestampsRaw.add((double)timeStamp); if (this.verbosity>2) { @@ -309,9 +325,12 @@ else if (iStates.size() > 2 && } if (!this.initialized()) { - System.out.println("HelicityGenerator: Initialization Error."); + System.err.println("HelicityGenerator: Initialization Error."); this.reset(); } + else if (this.verbosity>0) { + System.out.println("HelicityGenerator: Initialized."); + } return this.initialized(); } diff --git a/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicityPattern.java b/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicityPattern.java new file mode 100644 index 0000000000..e2468edd45 --- /dev/null +++ b/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicityPattern.java @@ -0,0 +1,36 @@ +package org.jlab.detector.helicity; + +/** + * This is the same numbering/naming convention used by CEBAF's EPICS + * variable HELPATTERNd, the helicity board manual, and in our CCDB + * table /runcontrol/helicity. + * + * @author baltzell + */ +public enum HelicityPattern { + + UDF ( -1 ), + PAIR ( 0 ), + QUARTET ( 1 ), + OCTET ( 2 ), + TOGGLE ( 3 ); + + private final int value; + + HelicityPattern(int value) { + this.value=value; + } + + public byte value() { + return (byte)this.value; + } + + public static HelicityPattern create(byte value) { + for(HelicityPattern hp: HelicityPattern.values()) { + if (hp.value() == value) return hp; + } + return UDF; + } + +} + diff --git a/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicitySequence.java b/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicitySequence.java index 056b78249a..1376dd9783 100644 --- a/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicitySequence.java +++ b/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicitySequence.java @@ -3,22 +3,34 @@ import java.util.List; import java.util.ArrayList; import java.util.Collections; -import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; + +import org.jlab.jnp.hipo4.data.Bank; +import org.jlab.jnp.hipo4.data.Event; +import org.jlab.jnp.hipo4.data.SchemaFactory; +import org.jlab.jnp.hipo4.io.HipoReader; /** * Stores a sequence of helicity states and provides timestamp- or state-count- - * based lookup of helicity state based on the measured sequence or pseudo-random + * based search of helicity state based on the measured sequence or pseudo-random * generator sequence, and provides some integrity checking of the sequence, * including comparing the measured and generator sequences. * + * ____________________________________________________________________ * Getter methods naming convention: - * "find" - lookup state based on timestamp - * "get" - lookup state based on state count - * "predict" - use pseudorandom generator (if necessary) + * + * Prefixes: + * "get" - based on state count + * "search" - based on finding timestamp in the measured sequence + * "predict" - based on generator seed time and expected periodicity * + * Suffixes: + * "Generated" - use the psuedo-random generator's sequence + * ____________________________________________________________________ + * * The generator methods are able to look past the measured range, while the - * non-generator methods cannot. Return values are null if the helicity cannot - * be determined. + * non-generator methods cannot. * * The inputs to initialize the sequence are {@link HelicityState} objects, one * per window at the helicity board clock frequency, which contain important @@ -28,18 +40,18 @@ * The return values from getters are just {@link HelicityBit} objects and * represent the HWP-corrected helicity. * - * See {@link HelicityAnalysis} for an example on using this class. + * See {@link HelicityAnalysisSimple} for an example on using this class. * * @author baltzell */ -public class HelicitySequence implements Comparator { +class HelicitySequence { - // FIXME: these should go to CCDB: public static final double TIMESTAMP_CLOCK=250.0e6; // Hz - public static final double HELICITY_CLOCK=29.56; // Hz - + protected double helicityClock=29.56; // Hz + protected HelicityPattern pattern=HelicityPattern.QUARTET; protected boolean halfWavePlate=false; protected boolean analyzed=false; + protected final Map generators=new HashMap<>(); protected final HelicityGenerator generator=new HelicityGenerator(); protected final List states=new ArrayList<>(); protected int verbosity=0; @@ -55,19 +67,6 @@ public boolean getHalfWavePlate() { return this.halfWavePlate; } - /** - * Compare based on timestamp for sorting and List insertion. - * @param o1 - * @param o2 - * @return negative/positive of o1 is before/after o2, else zero. - */ - @Override - public int compare(HelicityState o1, HelicityState o2) { - if (o1.getTimestamp() < o2.getTimestamp()) return -1; - if (o1.getTimestamp() > o2.getTimestamp()) return +1; - return 0; - } - /** * Get the the number of states in the sequence. * @return the number of states @@ -89,6 +88,13 @@ public final boolean addState(HelicityState state) { if (this.verbosity>3) { System.out.println("HelicitySequence: adding state: "+state); } + + // terminate if trying to add more than one run number: + for (HelicityState hs : this.states) { + if (hs.getRun()!=state.getRun()) { + throw new RuntimeException("Run number mismatch: "+state.getRun()+"/"+state.getRun()); + } + } // mark that we'll need to redo the analysis: this.analyzed=false; @@ -102,7 +108,7 @@ public final boolean addState(HelicityState state) { return true; } else { - final int index=Collections.binarySearch(this.states,state,new HelicitySequence()); + final int index=Collections.binarySearch(this.states,state,new HelicityState()); if (index==this.states.size()) { // its timestamp is later than the existing sequence: this.states.add(state); @@ -140,14 +146,14 @@ public final static HelicityBit getBitInQuartet(HelicityBit firstBit, int bitInd * @param timestamp TI timestamp (i.e. RUN::config.timestamp) * @return index */ - protected final int findIndex(long timestamp) { + protected final int searchIndex(long timestamp) { if (!this.analyzed) this.analyze(); if (timestamp < this.getTimestamp(0)) return -1; if (timestamp > this.getTimestamp(this.size()-1)) return -1; // make a fake state for timestamp search: HelicityState state=new HelicityState(); state.setTimestamp(timestamp); - final int index=Collections.binarySearch(this.states,state,new HelicitySequence()); + final int index=Collections.binarySearch(this.states,state,new HelicityState()); final int n = index<0 ? -index-2 : index; return n; } @@ -164,7 +170,7 @@ public int predictIndex(long timestamp) { if (!this.generator.initialized()) return -1; if (timestamp < this.generator.getTimestamp()) return -1; final int n = (int) ( (timestamp-this.generator.getTimestamp()) / - TIMESTAMP_CLOCK * HELICITY_CLOCK ); + TIMESTAMP_CLOCK * this.helicityClock ); return n+this.generator.getOffset(); } @@ -184,8 +190,8 @@ protected HelicityState getState(int n) { * @param timestamp TI timestamp (i.e. RUN::config.timestamp) * @return the helicity state, null if timestamp is outside of measured range */ - protected HelicityState findState(long timestamp) { - final int index = this.findIndex(timestamp); + protected HelicityState searchState(long timestamp) { + final int index = this.searchIndex(timestamp); if (index < 0) return null; return this.getState(index); } @@ -193,11 +199,11 @@ protected HelicityState findState(long timestamp) { /** * Get the nth state in the measured sequence. * @param n the index of the state, where 0 corresponds to the first state - * @return the helicity state, null if outside the mesaured range + * @return the helicity state, HelicityBit.UDF if outside the mesaured range */ protected HelicityBit get(int n) { HelicityState state = this.getState(n); - if (state==null) return null; + if (state==null) return HelicityBit.UDF; else return state.getHelicity(); } @@ -206,9 +212,9 @@ protected HelicityBit get(int n) { * @param timestamp TI timestamp (i.e. RUN::config.timestamp) * @return the helicity state, null if timestamp is outside of measured range */ - public HelicityBit find(long timestamp) { - HelicityState state = this.findState(timestamp); - if (state==null) return null; + public HelicityBit search(long timestamp) { + HelicityState state = this.searchState(timestamp); + if (state==null) return HelicityBit.UDF; else return state.getHelicity(); } @@ -223,17 +229,17 @@ public HelicityBit find(long timestamp) { * @param n the index of the state * @return the helicity bit */ - protected HelicityBit getPrediction(int n) { + protected HelicityBit getGenerated(int n) { if (!this.analyzed) this.analyze(); - if (!this.generator.initialized()) return null; - if (n-this.generator.getOffset()<0) return null; + if (!this.generator.initialized()) return HelicityBit.UDF; + if (n-this.generator.getOffset()<0) return HelicityBit.UDF; // Generator only knows about first states in a pattern (e.g. quartets), // so get it and then calculate here within that pattern. // FIXME: here we assume the helicity board is in QUARTET configuration. final int nQuartet = (n-this.generator.getOffset())/4; final int nBitInQuartet = (n-this.generator.getOffset())%4; - HelicityBit firstBitInQuartet = this.generator.getState(nQuartet); + HelicityBit firstBitInQuartet = this.generator.get(nQuartet); HelicityBit bit = getBitInQuartet(firstBitInQuartet,nBitInQuartet); // the generator operates on the raw states, so flip it if the HWP is in: @@ -253,15 +259,15 @@ protected HelicityBit getPrediction(int n) { * @param timestamp TI timestamp (i.e. RUN::config.timestamp) * @return the helicity bit */ - public HelicityBit findPrediction(long timestamp) { + public HelicityBit predictGenerated(long timestamp) { final int n=this.predictIndex(timestamp); if (n<0) return HelicityBit.UDF; - return this.getPrediction(n); + return this.getGenerated(n); /* if (timestamp < this.getTimestamp(0)) return null; if (timestamp <= this.getTimestamp(this.size()-1)) { - // it's in the measured range, so lookup index based on timestamp: - return this.getPrediction(this.findIndex(timestamp)); + // it's in the measured range, so search index based on timestamp: + return this.getGenerated(this.findIndex(timestamp)); } else { // here we predict past the measured sequence, @@ -270,8 +276,8 @@ public HelicityBit findPrediction(long timestamp) { // FIXME: use the latest available measured timestamp, // or an average final int n = (int) ( (timestamp-this.getTimestamp(0)) / - TIMESTAMP_CLOCK * HELICITY_CLOCK ); - return this.getPrediction(n); + TIMESTAMP_CLOCK * this.helicityClock ); + return this.getGenerated(n); } */ } @@ -290,15 +296,15 @@ public boolean initialized() { } public void show() { - HelicityState prev=this.states.get(0); - for (int ii=0; ii0) { this.states.remove(0); } - int nRejects=0; while (true) { boolean rejection=false; for (int ii=0; ii0) { - System.out.println("HelicitySequence: analyze() ...."); + System.out.println("HelicitySequence: Analyzing ...."); } final int nRejects=this.rejectFalseFlips(); - if (verbosity>1){ - System.out.println("HelicitySequence: rejected false flips: "+nRejects); + if (verbosity>0) { + System.out.println("HelicitySequence: Rejected false flips: "+nRejects); } if (this.states.size()>0) { @@ -367,9 +372,14 @@ protected final boolean analyze() { this.analyzed=true; - boolean integrity=this.integrityCheck(); + final boolean integrity=this.integrityCheck(); + + final boolean geninit=this.generator.initialize(this.states); + + if (geninit) { + this.generators.put(this.generator.getTimestamp(), this.generator); + } - boolean geninit=this.generator.initialize(this.states); return integrity && geninit; } @@ -397,6 +407,7 @@ public final boolean integrityCheck() { // check if neighboring syncs are the same (they shouldn't be): if (this.states.get(ii).getPairSync().value() == this.states.get(ii-1).getPairSync().value()) { syncErrors++; + this.states.get(ii).addSwStatusMask(HelicityState.Mask.SYNC); if (verbosity>1) System.err.println("ERROR: HelicitySequence SYNC: "+ii); } @@ -407,21 +418,22 @@ public final boolean integrityCheck() { this.states.get(ii-2).getPatternSync().value()+ this.states.get(ii-3).getPatternSync().value() != 2) { quartetErrors++; + this.states.get(ii).addSwStatusMask(HelicityState.Mask.PATTERN); if (verbosity>1) System.err.println("ERROR: HelicitySequence QUARTET: "+ii); } } // check timestamp deltas: final double seconds = (this.getTimestamp(ii)-this.getTimestamp(ii-1))/TIMESTAMP_CLOCK; - if (seconds < (1.0-0.5)/HELICITY_CLOCK) { + if (seconds < (1.0-0.5)/this.helicityClock) { smallGapErrors++; - this.states.get(ii).addStatusMask(HelicityState.Mask.SMALLGAP); + this.states.get(ii).addSwStatusMask(HelicityState.Mask.SMALLGAP); if (verbosity>1) System.err.println("ERROR: HelicitySequence TIMESTAMP: "+ii+" "+ this.getTimestamp(ii)+" "+this.getTimestamp(ii-1)+" "+seconds+"s"); } - else if (seconds > (1.0+0.5)/HELICITY_CLOCK) { + else if (seconds > (1.0+0.5)/this.helicityClock) { bigGapErrors++; - this.states.get(ii).addStatusMask(HelicityState.Mask.BIGGAP); + this.states.get(ii).addSwStatusMask(HelicityState.Mask.BIGGAP); if (verbosity>1) System.err.println("ERROR: HelicitySequence TIMESTAMP: "+ii+" "+ this.getTimestamp(ii)+" "+this.getTimestamp(ii-1)+" "+seconds+"s"); } @@ -431,7 +443,7 @@ else if (seconds > (1.0+0.5)/HELICITY_CLOCK) { int generatorErrors=0; if (this.generator.initialized()) { for (int ii=0; ii (1.0+0.5)/HELICITY_CLOCK) { return (hwpErrors+syncErrors+quartetErrors+bigGapErrors+smallGapErrors+generatorErrors) == 0; } + public void initialize(HipoReader reader) { + SchemaFactory schema = reader.getSchemaFactory(); + while (reader.hasNext()) { + Event event=new Event(); + Bank flipBank=new Bank(schema.getSchema("HEL::flip")); + reader.nextEvent(event); + event.read(flipBank); + if (flipBank.getRows()<1) continue; + this.addState(HelicityState.createFromFlipBank(flipBank)); + } + } + + public void initialize(List filenames) { + for (String filename : filenames) { + HipoReader reader = new HipoReader(); + reader.setTags(1); + reader.open(filename); + initialize(reader); + } + } } diff --git a/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicitySequenceDelayed.java b/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicitySequenceDelayed.java index c5868022d9..8512d5942e 100644 --- a/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicitySequenceDelayed.java +++ b/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicitySequenceDelayed.java @@ -1,10 +1,42 @@ package org.jlab.detector.helicity; +import org.jlab.utils.groups.IndexedTable; +import org.jlab.detector.calib.utils.DatabaseConstantProvider; + /** - * - * Just adding a delay to HelicitySequence, where delay is the number + * Just adds a delay to HelicitySequence, where delay is the number * of "windows". For example, a quartet pattern contains 4 windows, and * if the helicity clock is the usual 29.56 Hz, a window lasts 33.829 ms. + * + * Stores a sequence of helicity states and provides timestamp- or state-count- + * based search of helicity state based on the measured sequence or pseudo-random + * generator sequence, and provides some integrity checking of the sequence, + * including comparing the measured and generator sequences. + * + * ____________________________________________________________________ + * Getter methods naming convention: + * + * Prefixes: + * "get" - based on state count + * "search" - based on finding timestamp in the measured sequence + * "predict" - based on generator seed time and expected periodicity + * + * Suffixes: + * "Generated" - use the psuedo-random generator's sequence + * ____________________________________________________________________ + * + * The generator methods are able to look past the measured range, while the + * non-generator methods cannot. + * + * The inputs to initialize the sequence are {@link HelicityState} objects, one + * per window at the helicity board clock frequency, which contain important + * information for constructing and validating the sequence (e.g. helicity and + * sync bits and timestamps). + * + * The return values from getters are just {@link HelicityBit} objects and + * represent the HWP-corrected helicity. + * + * See {@link HelicityAnalysisSimple} for an example on using this class. * * @author baltzell */ @@ -16,102 +48,128 @@ public HelicitySequenceDelayed(int delay) { this.delay=delay; } - /** - * Set the number of windows delayed. - * - * @param delay - */ - public void setDelay(int delay) { - this.delay=delay; + public boolean setRunNumber(int runNumber) { + try { + DatabaseConstantProvider dcp=new DatabaseConstantProvider(runNumber,"default"); + IndexedTable it=dcp.readTable("/runcontrol/helicity"); + this.helicityClock=it.getDoubleValue("frequency",0,0,0); + this.delay=it.getIntValue("delay",0,0,0); + this.pattern=HelicityPattern.create((byte)it.getIntValue("pattern",0,0,0)); + this.generator.setClock(this.helicityClock); + System.out.println(String.format("HelicitySequenceDelayed: got parameters from CCDB for run %d:",runNumber)); + System.out.println(String.format("HelicitySequenceDelayed: CCDB clock: %.4f seconds",this.helicityClock)); + System.out.println(String.format("HelicitySequenceDelayed: CCDB delay: %d windows",this.delay)); + System.out.println(String.format("HelicitySequenceDelayed: CCDB pattern: %s",this.pattern)); + if (this.pattern != HelicityPattern.QUARTET) { + System.err.println("HelicitySequenceDelayed: not ready for non-QUARTET pattern"); + return false; + } + return true; + } + catch (Exception e) { + System.err.println(String.format("HelicitySequence: error retrieving clock from ccdb for run %d",runNumber)); + return false; + } } - + /** - * Get the delay-corrected nth state in the measured sequence. + * Get the delay-corrected nth state in the measured sequence, by walking + * forward delay states and returning HelicityBit.UDF if any errors + * along the way. * * @param n the index of the state, where 0 corresponds to the first state - * @return the helicity state, null if outside the mesaured range + * @return the helicity state */ @Override protected HelicityBit get(int n) { + if (n<0) return HelicityBit.UDF; + for (int i=n+1; i<=n+delay && i seqMap=new HashMap<>(); + Bank rcfgBank=null; + + public HelicitySequenceManager(int delay,List filenames) { + this.delay=delay; + initialize(filenames); + } + + private HelicitySequenceManager(int delay,HipoReader reader) { + this.delay=delay; + initialize(reader); + } + + public void setVerbosity(int verbosity) { + this.verbosity=verbosity; + for (HelicitySequence hs : seqMap.values()) { + hs.setVerbosity(verbosity); + } + } + + private boolean addState(int runno,HelicityState state) { + if (runno <= 0) return false; + if (!seqMap.containsKey(runno)) { + seqMap.put(runno, new HelicitySequenceDelayed(delay)); + seqMap.get(runno).setVerbosity(verbosity); + if (!seqMap.get(runno).setRunNumber(runno)) { + System.err.println("HelicitySequenceManager: error retrieving from CCDB, ABORT."); + System.exit(1); + } + } + return seqMap.get(runno).addState(state); + } + + public HelicitySequence getSequence(int runno) { + if (seqMap.containsKey(runno)) return seqMap.get(runno); + return null; + } + + public HelicityBit search(int runno, long timestamp) { + if (seqMap.containsKey(runno)) return seqMap.get(runno).search(timestamp); + return HelicityBit.UDF; + } + public HelicityBit predictGenerated(int runno, long timestamp) { + if (seqMap.containsKey(runno)) return seqMap.get(runno).predictGenerated(timestamp); + return HelicityBit.UDF; + } + public HelicityBit searchGenerated(int runno, long timestamp) { + if (seqMap.containsKey(runno)) return seqMap.get(runno).searchGenerated(timestamp); + return HelicityBit.UDF; + } + + public HelicityBit search(Event event) { + event.read(this.rcfgBank); + if (rcfgBank.getRows()<1) return HelicityBit.UDF; + return this.search(rcfgBank.getInt("run",0),rcfgBank.getLong("timestamp",0)); + } + public HelicityBit predictGenerated(Event event) { + event.read(this.rcfgBank); + if (rcfgBank.getRows()<1) return HelicityBit.UDF; + return this.predictGenerated(rcfgBank.getInt("run",0),rcfgBank.getLong("timestamp",0)); + } + public HelicityBit searchGenerated(Event event) { + event.read(this.rcfgBank); + if (rcfgBank.getRows()<1) return HelicityBit.UDF; + return this.searchGenerated(rcfgBank.getInt("run",0),rcfgBank.getLong("timestamp",0)); + } + + public boolean getHalfWavePlate(Event event) { + event.read(this.rcfgBank); + if (rcfgBank.getRows()>0) { + int runno=rcfgBank.getInt("run",0); + if (seqMap.containsKey(runno)) { + return seqMap.get(runno).getHalfWavePlate(); + } + } + return false; + } + + /** + * Initialize from a HipoReader object. + * This requires an unread HipoReader, since HipoReader doesn't provide a + * rewind option, nor a way to read the set tags. + * @param reader + */ + private void initialize(HipoReader reader) { + if (this.schema==null) { + this.schema=reader.getSchemaFactory(); + this.rcfgBank=new Bank(this.schema.getSchema("RUN::config")); + } + reader.setTags(1); + while (reader.hasNext()) { + Event event=new Event(); + Bank flipBank=new Bank(this.schema.getSchema("HEL::flip")); + reader.nextEvent(event); + event.read(flipBank); + if (flipBank.getRows()<1) continue; + final int runno=flipBank.getInt("run",0); + this.addState(runno,HelicityState.createFromFlipBank(flipBank)); + } + } + + /** + * Initialize from a list of file names: + * @param filenames + */ + private void initialize(List filenames) { + for (String filename : filenames) { + HipoReader reader = new HipoReader(); + reader.open(filename); + initialize(reader); + reader.close(); + } + } + + public boolean analyze() { + boolean ret=true; + for (HelicitySequenceDelayed hsd : seqMap.values()) { + if (!hsd.analyze()) ret=false; + } + return ret; + } + + public void show() { + for (Entry x : seqMap.entrySet()) { + System.out.println("Run Number:::::::::::::::::: "+x.getKey()); + x.getValue().show(); + } + } + +} diff --git a/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicityState.java b/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicityState.java index f471e0e4f3..bb43be0711 100644 --- a/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicityState.java +++ b/common-tools/clas-detector/src/main/java/org/jlab/detector/helicity/HelicityState.java @@ -1,5 +1,6 @@ package org.jlab.detector.helicity; +import java.util.Comparator; import org.jlab.jnp.hipo4.data.SchemaFactory; import org.jlab.jnp.hipo4.data.Bank; @@ -12,7 +13,7 @@ * * @author baltzell */ -public class HelicityState implements Comparable { +public class HelicityState implements Comparable, Comparator { public static class Mask { public static final int HELICITY =0x1; @@ -21,7 +22,7 @@ public static class Mask { public static final int BIGGAP =0x8; public static final int SMALLGAP =0x10; } - + // FIXME: these should go in CCDB private static final short HALFADC=2000; private static final byte SECTOR=1; @@ -37,16 +38,45 @@ public static class Mask { private long timestamp = 0; private int event = 0; private int run = 0; - private byte status = -1; + private byte hwStatus = 0; + private byte swStatus = 0; public HelicityState(){} - public void addStatusMask(int mask) { - this.status |= mask; + /** + * Compare based on timestamp for sorting and List insertion. + * @param o1 + * @param o2 + * @return negative/positive if o1 is before/after o2, else zero. + */ + @Override + public int compare(HelicityState o1, HelicityState o2) { + return o1.compareTo(o2); + } + + /** + * Compare based on timestamp for sorting and List insertion. + * @param other + * @return negative/positive if this is before/after other, else zero. + */ + @Override + public int compareTo(HelicityState other) { + if (this.getTimestamp() < other.getTimestamp()) return -1; + if (this.getTimestamp() > other.getTimestamp()) return +1; + return 0; + } + + + public void addSwStatusMask(int mask) { + this.swStatus |= mask; } - public int getStatus() { - return this.status; + public int getSwStatus() { + return this.swStatus; + } + + public int getHwStatus() { + return this.hwStatus; } private HelicityBit getFadcState(short ped) { @@ -55,13 +85,6 @@ private HelicityBit getFadcState(short ped) { else return HelicityBit.MINUS; } - @Override - public int compareTo(HelicityState other) { - if (this.getTimestamp() < other.getTimestamp()) return -1; - if (this.getTimestamp() > other.getTimestamp()) return +1; - return 0; - } - /** * Create a state from a HEL::adc org.jlab.jnp.hipo4.data.Bank * @@ -87,10 +110,10 @@ public static HelicityState createFromFadcBank(Bank adcBank) { break; } } - state.status=0; - if (state.helicityRaw==HelicityBit.UDF) state.status |= Mask.HELICITY; - if (state.pairSync==HelicityBit.UDF) state.status |= Mask.SYNC; - if (state.patternSync==HelicityBit.UDF) state.status |= Mask.PATTERN; + state.hwStatus=0; + if (state.helicityRaw==HelicityBit.UDF) state.hwStatus |= Mask.HELICITY; + if (state.pairSync==HelicityBit.UDF) state.hwStatus |= Mask.SYNC; + if (state.patternSync==HelicityBit.UDF) state.hwStatus |= Mask.PATTERN; state.fixMissingReadouts(); return state; } @@ -106,7 +129,7 @@ public static HelicityState createFromFlipBank(Bank flipBank) { state.run = flipBank.getInt("run",0); state.event = flipBank.getInt("event",0); state.timestamp = flipBank.getLong("timestamp",0); - state.status = flipBank.getByte("status",0); + state.hwStatus = flipBank.getByte("status",0); state.helicity = HelicityBit.create(flipBank.getByte("helicity",0)); state.helicityRaw = HelicityBit.create(flipBank.getByte("helicityRaw",0)); state.pairSync = HelicityBit.create(flipBank.getByte("pair",0)); @@ -127,7 +150,7 @@ public static HelicityState createFromFlipBank(DataBank flipBank) { state.run = flipBank.getInt("run",0); state.event = flipBank.getInt("event",0); state.timestamp = flipBank.getLong("timestamp",0); - state.status = flipBank.getByte("status",0); + state.hwStatus = flipBank.getByte("status",0); state.helicity = HelicityBit.create(flipBank.getByte("helicity",0)); state.helicityRaw = HelicityBit.create(flipBank.getByte("helicityRaw",0)); state.pairSync = HelicityBit.create(flipBank.getByte("pair",0)); @@ -171,7 +194,7 @@ public String toString() { } public String getInfo(HelicityState other,int counter) { - return String.format("%s %6.2f %5d %7d", + return String.format("%s %8.2f %5d %7d", this.toString(), 1000*this.getSecondsDelta(other), this.getEventDelta(other), @@ -183,7 +206,7 @@ public Bank getFlipBank(SchemaFactory schemaFactory) { bank.putInt("run", 0, this.run); bank.putInt("event", 0, this.event); bank.putLong("timestamp", 0, this.timestamp); - bank.putByte("status", 0, this.status); + bank.putByte("status", 0, this.hwStatus); bank.putByte("helicity", 0, this.helicity.value()); bank.putByte("helicityRaw", 0, this.helicityRaw.value()); bank.putByte("pair", 0, this.pairSync.value()); diff --git a/common-tools/clas-eventmerger/pom.xml b/common-tools/clas-eventmerger/pom.xml index 63f4695d53..f48732911b 100644 --- a/common-tools/clas-eventmerger/pom.xml +++ b/common-tools/clas-eventmerger/pom.xml @@ -2,14 +2,14 @@ 4.0.0 clas-eventmerger - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT jar org.jlab.clas clas12rec ../../parent/pom.xml - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT @@ -29,19 +29,19 @@ org.jlab.clas clas-utils - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-io - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-geometry - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT diff --git a/common-tools/clas-geometry/pom.xml b/common-tools/clas-geometry/pom.xml index 89c3559289..908157764b 100644 --- a/common-tools/clas-geometry/pom.xml +++ b/common-tools/clas-geometry/pom.xml @@ -3,14 +3,14 @@ 4.0.0 org.jlab.clas clas-geometry - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT jar org.jlab.clas clas12rec ../../parent/pom.xml - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT @@ -27,6 +27,11 @@ + + org.openjfx + javafx-controls + 11 + org.jlab.ccdb ccdb diff --git a/common-tools/clas-geometry/src/main/java/org/jlab/geom/detector/ec/ECFactory.java b/common-tools/clas-geometry/src/main/java/org/jlab/geom/detector/ec/ECFactory.java index c75ae3d155..658f7af914 100644 --- a/common-tools/clas-geometry/src/main/java/org/jlab/geom/detector/ec/ECFactory.java +++ b/common-tools/clas-geometry/src/main/java/org/jlab/geom/detector/ec/ECFactory.java @@ -147,16 +147,17 @@ public ECSuperlayer createSuperlayer(ConstantProvider cp, int sectorId, int supe if (!(0<=superlayerId && superlayerId<3)) throw new IllegalArgumentException("Error: invalid superlayer="+superlayerId); ECSuperlayer superlayer = new ECSuperlayer(sectorId, superlayerId); - /* + int numLayers = (superlayerId == 0)? 15 : // PCAL (superlayerId == 1)? 15 : // Inner EC (superlayerId == 2)? 24 : // Outer EC -1; // ?? - */ + /* int numLayers = (superlayerId == 0)? 3 : // PCAL (superlayerId == 1)? 3 : // Inner EC (superlayerId == 2)? 3 : // Outer EC -1; // ?? + */ for (int layerId=0; layerId4.0.0 org.jlab.clas clas-io - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT jar org.jlab.clas clas12rec ../../parent/pom.xml - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT @@ -28,6 +28,12 @@ + + javax.xml.bind + jaxb-api + 2.3.0 + + org.jlab.coda jevio @@ -69,7 +75,7 @@ org.jlab.clas clas-utils - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT diff --git a/common-tools/clas-io/src/main/java/org/jlab/io/evio/EvioDataDictionary.java b/common-tools/clas-io/src/main/java/org/jlab/io/evio/EvioDataDictionary.java index 6903aed1a3..a279d45d40 100644 --- a/common-tools/clas-io/src/main/java/org/jlab/io/evio/EvioDataDictionary.java +++ b/common-tools/clas-io/src/main/java/org/jlab/io/evio/EvioDataDictionary.java @@ -87,7 +87,7 @@ public final void initWithDir(String dirname) { ArrayList ignorePrefixes = new ArrayList(); ignorePrefixes.add("."); ignorePrefixes.add("_"); - System.err.println("[EvioDataDictionary]---> loading bankdefs from directory : " + dirname); + System.out.println("[EvioDataDictionary]---> loading bankdefs from directory : " + dirname); File dict_dir = new File(dirname); if (dict_dir.exists() == false) { @@ -96,7 +96,7 @@ public final void initWithDir(String dirname) { } ArrayList xmlFileList = FileUtils.filesInFolder(dict_dir, "xml", ignorePrefixes); - System.err.println("[EvioDataDictionary]------> number of XML files located : " + xmlFileList.size()); + System.out.println("[EvioDataDictionary]------> number of XML files located : " + xmlFileList.size()); Integer counter = 0; for (String file : xmlFileList) { ArrayList descList = DictionaryLoader.getDescriptorsFromFile(file); @@ -111,7 +111,7 @@ public final void initWithDir(String dirname) { counter++; } } - System.err.println("[EvioDataDictionary]--> total number of descriptors found : " + counter.toString()); + System.out.println("[EvioDataDictionary]--> total number of descriptors found : " + counter.toString()); } public void show() { @@ -167,7 +167,7 @@ public String getNameByTagNum(int tag, int num) { public DataBank createBank(String name, int rows) { if (descriptors.containsKey(name) == false) { - System.out.println("[EvioDataDictionary]:: ERROR ---> no descriptor with name = " + name + " is found"); + System.err.println("[EvioDataDictionary]:: ERROR ---> no descriptor with name = " + name + " is found"); } EvioDataDescriptor desc = descriptors.get(name); EvioDataBank bank = new EvioDataBank(desc); diff --git a/common-tools/clas-io/src/main/java/org/jlab/io/evio/EvioSource.java b/common-tools/clas-io/src/main/java/org/jlab/io/evio/EvioSource.java index 274454f61f..cf24b7b319 100644 --- a/common-tools/clas-io/src/main/java/org/jlab/io/evio/EvioSource.java +++ b/common-tools/clas-io/src/main/java/org/jlab/io/evio/EvioSource.java @@ -53,7 +53,7 @@ public EvioSource() { EvioFactory.loadDictionary(dictionaryPath); dictionary = EvioFactory.getDictionary(); - System.err.println("[EvioSource] ---> Factory loaded descriptor count : " + dictionary.getDescriptorList().length); + System.out.println("[EvioSource] ---> Factory loaded descriptor count : " + dictionary.getDescriptorList().length); // dictionary.show(); } @@ -85,7 +85,7 @@ public EvioSource(String filename) { EvioFactory.loadDictionary(dictionaryPath); dictionary = EvioFactory.getDictionary(); - System.err.println("[EvioSource] ---> Factory loaded descriptor count : " + dictionary.getDescriptorList().length); + System.out.println("[EvioSource] ---> Factory loaded descriptor count : " + dictionary.getDescriptorList().length); dictionary.show(); this.open(filename); } diff --git a/common-tools/clas-jcsg/pom.xml b/common-tools/clas-jcsg/pom.xml index e5e473f0a9..cdcf3927af 100644 --- a/common-tools/clas-jcsg/pom.xml +++ b/common-tools/clas-jcsg/pom.xml @@ -3,14 +3,14 @@ 4.0.0 org.jlab.clas clas-jcsg - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT jar org.jlab.clas clas12rec ../../parent/pom.xml - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT @@ -27,15 +27,25 @@ + + org.openjfx + javafx-controls + 11 + + + org.openjfx + javafx-fxml + 11 + org.jlab.clas clas-geometry - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-detector - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT java3d diff --git a/common-tools/clas-jcsg/src/main/java/org/jlab/detector/geant4/v2/DCGeant4Factory.java b/common-tools/clas-jcsg/src/main/java/org/jlab/detector/geant4/v2/DCGeant4Factory.java index 09db12ee8e..cfa81049f3 100644 --- a/common-tools/clas-jcsg/src/main/java/org/jlab/detector/geant4/v2/DCGeant4Factory.java +++ b/common-tools/clas-jcsg/src/main/java/org/jlab/detector/geant4/v2/DCGeant4Factory.java @@ -47,6 +47,8 @@ final class DCdatabase { private final double align_dthetax[][] = new double[nSectors][nRegions]; private final double align_dthetay[][] = new double[nSectors][nRegions]; private final double align_dthetaz[][] = new double[nSectors][nRegions]; + + private final double endplatesbow[][][] = new double[nSectors][nRegions][2]; private int nsensewires; private int nguardwires; @@ -54,6 +56,8 @@ final class DCdatabase { private boolean ministaggerStatus = false; private double ministagger ; + private boolean endplatesStatus = false; + private final String dcdbpath = "/geometry/dc/"; private static DCdatabase instance = null; @@ -94,19 +98,28 @@ public void connect(ConstantProvider cp) { superwidth[isuper] = wpdist[isuper] * (nsenselayers[isuper] + nguardlayers[isuper] - 1) * cellthickness[isuper]; } - int alignrows = cp.length(dcdbpath+"alignment/dx"); - for(int irow = 0; irow< alignrows; irow++) { - int isec = cp.getInteger(dcdbpath + "alignment/sector",irow)-1; - int ireg = cp.getInteger(dcdbpath + "alignment/region",irow)-1; + int alignrows = cp.length(dcdbpath+"alignment/dx"); + for(int irow = 0; irow< alignrows; irow++) { + int isec = cp.getInteger(dcdbpath + "alignment/sector",irow)-1; + int ireg = cp.getInteger(dcdbpath + "alignment/region",irow)-1; - align_dx[isec][ireg]=cp.getDouble(dcdbpath + "alignment/dx",irow); - align_dy[isec][ireg]=cp.getDouble(dcdbpath + "alignment/dy",irow); - align_dz[isec][ireg]=cp.getDouble(dcdbpath + "alignment/dz",irow); + align_dx[isec][ireg]=cp.getDouble(dcdbpath + "alignment/dx",irow); + align_dy[isec][ireg]=cp.getDouble(dcdbpath + "alignment/dy",irow); + align_dz[isec][ireg]=cp.getDouble(dcdbpath + "alignment/dz",irow); - align_dthetax[isec][ireg]=cp.getDouble(dcdbpath + "alignment/dtheta_x",irow); - align_dthetay[isec][ireg]=cp.getDouble(dcdbpath + "alignment/dtheta_y",irow); - align_dthetaz[isec][ireg]=cp.getDouble(dcdbpath + "alignment/dtheta_z",irow); - } + align_dthetax[isec][ireg]=cp.getDouble(dcdbpath + "alignment/dtheta_x",irow); + align_dthetay[isec][ireg]=cp.getDouble(dcdbpath + "alignment/dtheta_y",irow); + align_dthetaz[isec][ireg]=cp.getDouble(dcdbpath + "alignment/dtheta_z",irow); + } + + int endplatesrows = cp.length(dcdbpath+"endplatesbow/coefficient"); + for(int irow = 0; irow< endplatesrows; irow++) { + int isec = cp.getInteger(dcdbpath + "endplatesbow/sector",irow)-1; + int ireg = cp.getInteger(dcdbpath + "endplatesbow/region",irow)-1; + int order = cp.getInteger(dcdbpath + "endplatesbow/order",irow); + endplatesbow[isec][ireg][order] = cp.getDouble(dcdbpath+"endplatesbow/coefficient", irow)*Length.cm; + //System.out.println("READ ENDPLATES COEFF [isec"+isec+"]["+ireg+"]="+endplatesbow[isec][ireg][order] ); + } } public double dist2tgt(int ireg) { @@ -200,7 +213,19 @@ public void setMinistaggerStatus(boolean ministaggerStatus) { public boolean getMinistaggerStatus(){ return ministaggerStatus; } + + public double endplatesbow(int isec, int ireg, int order) { + return endplatesbow[isec][ireg][order]; + } + + public void setEndPlatesStatus(boolean endplatesStatus) { + this.endplatesStatus = endplatesStatus; + } + public boolean getEndPlatesStatus(){ + return endplatesStatus; + } + public double getAlignmentThetaX(int isec, int ireg) { return align_dthetax[isec][ireg]; } @@ -220,10 +245,11 @@ public Vector3d getAlignmentShift(int isec, int ireg) { final class Wire { + private final int sector; private final int ireg; private final int isuper; - private final int ilayer; - private final int iwire; + private final int layer; + private final int wire; private final DCdatabase dbref = DCdatabase.getInstance(); private final Vector3d midpoint; @@ -290,11 +316,58 @@ private void findEnds() { rightend = direction.times(wlenr).add(midpoint); } - public Wire(int isuper, int ilayer, int iwire) { - this.isuper = isuper; - this.ilayer = ilayer; - this.iwire = iwire; - this.ireg = isuper / 2; + /** + * Correct for endplates bowing in tilted coordinate system. (ziegler) + */ + public void correctEnds() { + double iwirn = (double) wire/112.0; + //deflection function has to be 1 at extremum (3.8465409 scales it so it is 1 at first derivative) + double defFunc = 3.8465409*(iwirn - 3 * iwirn*iwirn*iwirn +2 * iwirn*iwirn*iwirn*iwirn); + //max deflection for L and R sides of wire + double deflMaxL = dbref.endplatesbow(sector-1, ireg, 0); + double deflMaxR = dbref.endplatesbow(sector-1, ireg, 1); + //deflection of the L and R sides + double deflL = 0.5 * deflMaxL * defFunc; + double deflR = 0.5 * deflMaxR * defFunc; + + double xL = leftend.x + deflL; + double xR = rightend.x + deflR; + double yL = leftend.y; + double yR = rightend.y; + + // the uncorrected wirelength. We assume the wire length is not changing + double wlenl = leftend.sub(midpoint).magnitude(); + double wlenr = rightend.sub(midpoint).magnitude(); + //get the modified wire direction + double n = Math.sqrt((xR - xL)*(xR - xL)+(yR - yL)*(yR - yL)); + direction.set((xR - xL)/n, (yR - yL)/n, 0); + // midpoint corresponds to y = 0 + midpoint.set(xR -yR*((xR-xL)/(yR-yL)), 0, midpoint.z); + //get left and right ends assuming the wire length is not changing + leftend = direction.times(-wlenl).add(midpoint); + rightend = direction.times(wlenr).add(midpoint); + +// if(sector == 4) +// System.out.println((this.isuper+1)+" "+layer+" "+wire+" "+(float)(xL-deflL)+" "+(float)yL+" "+(float)leftend.z+" "+ +// (float)(xL)+" "+(float)yL+" "+(float)leftend.z+" "+ +// (float)leftend.x+" "+(float)leftend.y+" "+(float)leftend.z +// +" "+(float)(xR-deflR)+" "+(float)yR+" "+(float)rightend.z+" "+ +// (float)(xR)+" "+(float)yR+" "+(float)rightend.z+" "+ +// (float)rightend.x+" "+(float)rightend.y+" "+(float)rightend.z); + } + /** + * + * @param sector sector 1...6 + * @param super superlayer index 0...5 + * @param layer layer 1...6 + * @param wire wire 1...112 + */ + public Wire(int sector, int isuperl, int layer, int wire) { + this.sector = sector; + this.isuper = isuperl; + this.layer = layer; + this.wire = wire; + this.ireg = isuper / 2; // calculate first-wire distance from target double w2tgt = dbref.dist2tgt(ireg); @@ -315,13 +388,13 @@ public Wire(int isuper, int ilayer, int iwire) { double dw2 = dw / cster; // hh: wire distance in the wire plane - double hh = (iwire-1 + ((double)(ilayer % 2)) / 2.0) * dw2; - if(ireg==2 && isSensitiveWire(isuper, ilayer, iwire) && dbref.getMinistaggerStatus()) - hh += ((ilayer%2)*2-1)*dbref.ministagger(); + double hh = (wire-1 + ((double)(layer % 2)) / 2.0) * dw2; + if(ireg==2 && isSensitiveWire(isuper, layer, wire) && dbref.getMinistaggerStatus()) + hh += ((layer%2)*2-1)*dbref.ministagger(); // ll: layer distance double tt = dbref.cellthickness(isuper) * dbref.wpdist(isuper); - double ll = ilayer * tt; + double ll = layer * tt; // wire x=0 coordinates in the lab double ym = y0mid + ll * stilt + hh * ctilt; @@ -398,16 +471,21 @@ public final class DCGeant4Factory extends Geant4Factory { public static boolean MINISTAGGERON=true; public static boolean MINISTAGGEROFF=false; + + public static boolean ENDPLATESBOWON=true; + public static boolean ENDPLATESBOWOFF=false; /////////////////////////////////////////////////// public DCGeant4Factory(ConstantProvider provider) { - this(provider, MINISTAGGEROFF); + this(provider, MINISTAGGEROFF, ENDPLATESBOWOFF); } /////////////////////////////////////////////////// - public DCGeant4Factory(ConstantProvider provider, boolean ministaggerStatus) { + public DCGeant4Factory(ConstantProvider provider, boolean ministaggerStatus, + boolean endplatesStatus) { dbref.setMinistaggerStatus(ministaggerStatus); - + dbref.setEndPlatesStatus(endplatesStatus); + motherVolume = new G4World("fc"); dbref.connect(provider); @@ -448,11 +526,11 @@ public DCGeant4Factory(ConstantProvider provider, boolean ministaggerStatus) { for(int ilayer=0; ilayer z (beamline) - + System.out.println("SVT READ Z SHIFT VALUE "+cp.getDouble("/geometry/target/position", 0)); // LAYERRADIUS and ZSTARTACTIVE are used primarily by the Reconstruction and getStrip() for( int region = 0; region < NREGIONS; region++ ) { NSECTORS[region] = cp.getInteger(ccdbPath+"region/nSectors", region ); + STATUS[region] = cp.getInteger(ccdbPath+"region/status", region ); Z0ACTIVE[region] = cp.getDouble(ccdbPath+"region/zStart", region ); // Cu edge of hybrid sensor's active volume REFRADIUS[region] = cp.getDouble(ccdbPath+"region/UlayerOuterRadius", region); // radius to outer side of U (inner) module @@ -344,7 +348,37 @@ else if( value == "tube" ) // offset by boxNum to reset row for CCDB table //System.out.println("LAYERRADIUS "+ LAYERRADIUS[region][m]); } } + + NTOTALSECTORS = convertRegionSector2Index( NREGIONS-1, NSECTORS[NREGIONS-1]-1 )+1; + NTOTALFIDUCIALS = convertRegionSectorFiducial2Index(NREGIONS-1, NSECTORS[NREGIONS-1]-1, NFIDUCIALS-1 )+1; + RSI = new int[NREGIONS][NTOTALSECTORS]; + for( int aRegion = 0; aRegion < NREGIONS; aRegion++ ) + { + for( int aSector = 0; aSector < NSECTORS[aRegion]; aSector++ ) + { + RSI[aRegion][aSector] = convertRegionSector2Index( aRegion, aSector ); + System.out.println(" a Region "+aRegion +" aSector "+aSector+" RSI "+RSI[aRegion][aSector] ); + } + } + System.out.println("Reading alignment shifts from database"); + + SECTORSHIFTDATA = new double[NTOTALSECTORS][]; + + for( int i = 0; i < NTOTALSECTORS; i++ ) + { + double tx = cp.getDouble(ccdbPath+"alignment/tx", i ); + double ty = cp.getDouble(ccdbPath+"alignment/ty", i ); + double tz = cp.getDouble(ccdbPath+"alignment/tz", i ); + double rx = cp.getDouble(ccdbPath+"alignment/rx", i ); + double ry = cp.getDouble(ccdbPath+"alignment/ry", i ); + double rz = cp.getDouble(ccdbPath+"alignment/rz", i ); + double ra = cp.getDouble(ccdbPath+"alignment/ra", i ); + + SECTORSHIFTDATA[i] = new double[]{ tx, ty, tz, rx, ry, rz, Math.toRadians(ra) }; + + } + if( VERBOSE ) { System.out.println("NSECTORS STATUS Z0ACTIVE REFRADIUS SUPPORTRADIUS LAYERRADIUS (U,V)"); @@ -360,9 +394,8 @@ else if( value == "tube" ) // offset by boxNum to reset row for CCDB table } } - NTOTALSECTORS = convertRegionSector2Index( NREGIONS-1, NSECTORS[NREGIONS-1]-1 )+1; - NTOTALFIDUCIALS = convertRegionSectorFiducial2Index(NREGIONS-1, NSECTORS[NREGIONS-1]-1, NFIDUCIALS-1 )+1; + // check one constant from each table //if( NREGIONS == 0 || NSECTORS[0] == 0 || FIDCUX == 0 || MATERIALS[0][0] == 0 || SUPPORTRADIUS[0] == 0 ) //throw new NullPointerException("please load the following tables from CCDB in "+ccdbPath+"\n svt\n region\n support\n fiducial\n material\n"); @@ -427,6 +460,7 @@ else if( value == "tube" ) // offset by boxNum to reset row for CCDB table System.out.println(); } } + } } @@ -436,7 +470,7 @@ else if( value == "tube" ) // offset by boxNum to reset row for CCDB table * * @param cp a DatabaseConstantProvider that has loaded the "alignment" table */ - public static void loadAlignmentShifts( ConstantProvider cp ) + public static synchronized void loadAlignmentShifts( ConstantProvider cp ) { System.out.println("reading alignment shifts from database"); @@ -478,7 +512,8 @@ public static void loadAlignmentShifts( ConstantProvider cp ) SECTORSHIFTDATA[i] = new double[]{ ltx, lty, ltz, lrx, lry, lrz, Math.toRadians(lra) }; }*/ } - if( VERBOSE ) showSectorShiftData(); + //if( VERBOSE ) + showSectorShiftData(); } @@ -648,6 +683,7 @@ public static int convertRegionSector2Index( int aRegion, int aSector ) throws I if( aRegion < 0 || aRegion > NREGIONS-1 ){ throw new IllegalArgumentException("region out of bounds"); } if( aSector < 0 || aSector > NSECTORS[aRegion]-1 ){ throw new IllegalArgumentException("sector out of bounds"); } return Util.subArraySum( NSECTORS, aRegion ) + aSector; + } diff --git a/common-tools/clas-jcsg/src/main/java/org/jlab/detector/geom/dc/DCGeantFactory.java b/common-tools/clas-jcsg/src/main/java/org/jlab/detector/geom/dc/DCGeantFactory.java index 2e15d50d6e..95aaaa32b4 100644 --- a/common-tools/clas-jcsg/src/main/java/org/jlab/detector/geom/dc/DCGeantFactory.java +++ b/common-tools/clas-jcsg/src/main/java/org/jlab/detector/geom/dc/DCGeantFactory.java @@ -38,7 +38,7 @@ public class DCGeantFactory implements Factory4.0.0 org.jlab.clas clas-math - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT jar org.jlab.clas clas12rec ../../parent/pom.xml - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT diff --git a/common-tools/clas-physics/pom.xml b/common-tools/clas-physics/pom.xml index dcfd100835..cae0f269b8 100644 --- a/common-tools/clas-physics/pom.xml +++ b/common-tools/clas-physics/pom.xml @@ -4,7 +4,7 @@ org.jlab.clas clas-physics - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT jar @@ -23,7 +23,7 @@ org.jlab.clas clas12rec ../../parent/pom.xml - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT diff --git a/common-tools/clas-reco/pom.xml b/common-tools/clas-reco/pom.xml index fc70e1e375..54a85fc890 100644 --- a/common-tools/clas-reco/pom.xml +++ b/common-tools/clas-reco/pom.xml @@ -3,14 +3,14 @@ 4.0.0 org.jlab.clas clas-reco - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT jar org.jlab.clas clas12rec ../../parent/pom.xml - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT @@ -67,7 +67,7 @@ org.jlab.clas clas-math - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT before rotat : % 8.4f % 8.4f % 8.4f\n", aPoint.x, aPoint.y, aPoint.z ); - Vector3d vecAxis = new Vector3d(Constants.RX[region-1][sector-1], Constants.RY[region-1][sector-1], Constants.RZ[region-1][sector-1] ).normalized(); - vecAxis.rotate( aPoint, Math.toRadians(Constants.RA[region-1][sector-1]) ); - //aPoint.rotateZ(Math.toRadians(Constants.RA[region-1][sector-1])); - System.out.printf(Constants.RA[region-1][sector-1]+" --> rotat ax : % 8.4f % 8.4f % 8.4f\n", vecAxis.x, vecAxis.y, vecAxis.z ); - System.out.printf(" --> after rotat : % 8.4f % 8.4f % 8.4f\n", aPoint.x, aPoint.y, aPoint.z ); - aCenter.times( -1 ); // reverse translation - aPoint.add( aCenter ) ; - System.out.printf(" --> center : % 8.4f % 8.4f % 8.4f\n", aCenter.x, aCenter.y, aCenter.z ); - System.out.printf(" --> rotat : % 8.4f % 8.4f % 8.4f\n", aPoint.x, aPoint.y, aPoint.z ); - } - - // do the translation here. - Vector3d translationVec = new Vector3d( Constants.TX[region-1][sector-1], Constants.TY[region-1][sector-1], Constants.TZ[region-1][sector-1] ); - aPoint.set( aPoint.add( translationVec ) ); - //if(Math.abs(cross.x()-aPoint.x)<1 && Math.abs(cross.y()-aPoint.y)<1) { - System.out.println(" unshifted \n"+cross.toString()+" in sector "+sector+" region "+region); - cross.set(aPoint.x, aPoint.y, aPoint.z); - System.out.printf(" --> shifted : % 8.4f % 8.4f % 8.4f\n", aPoint.x, aPoint.y, aPoint.z ); - // } } - - -/** - * Applies the inverse of the given alignment shift to the given point. gilfoyle 12/21/17 - * - * @param aPoint a point in the lab frame - * @param aShift a translation and axis-angle rotation of the form { tx, ty, tz, rx, ry, rz, ra } - * @param aCenter a point about which to rotate the first point (for example the midpoint of the ideal fiducials) - * @param aScaleT a scale factor for the translation shift - * @param aScaleR a scale factor for the rotation shift - * @throws IllegalArgumentException incorrect number of elements in shift array - */ -public static void applyInverseShift( Vector3d aPoint, double[] aShift, Vector3d aCenter, double aScaleT, double aScaleR ) throws IllegalArgumentException -{ - - double tx = aShift[0]; // The Java language has references but you cannot dereference the memory addresses like you can in C++. - double ty = aShift[1]; // The Java runtime does have pointers, but they're not accessible to the programmer. (no pointer arithmetic) - double tz = aShift[2]; - double rx = aShift[3]; - double ry = aShift[4]; - double rz = aShift[5]; - double ra = aShift[6]; - - tx *= aScaleT; - ty *= aScaleT; - tz *= aScaleT; - ra *= aScaleR; - - - { - System.out.printf("PN: % 8.3f % 8.3f % 8.3f\n", aPoint.x, aPoint.y, aPoint.z ); - System.out.printf("ST: % 8.3f % 8.3f % 8.3f\n", tx, ty, tz ); - System.out.printf("SR: % 8.3f % 8.3f % 8.3f % 8.3f\n", rx, ry, rz, Math.toDegrees(ra) ); - System.out.printf("SC: % 8.3f % 8.3f % 8.3f\n", aCenter.x, aCenter.y, aCenter.z ); - } - - // undo the translation. - Vector3d translationVec = new Vector3d( -tx, -ty, -tz ); - aPoint.set( aPoint.add( translationVec ) ); - - // test size of rotation - too small creates errors. - if( !(ra < 1E-3) ) - { - aCenter.times( -1 ); // reverse translation - aPoint.set( aPoint.add( aCenter ) ); // move origin to center of rotation axis - - //System.out.printf("PC: % 8.3f % 8.3f % 8.3f\n", aPoint.x, aPoint.y, aPoint.z ); - - Vector3d vecAxis = new Vector3d( rx, ry, rz ).normalized(); - vecAxis.rotate( aPoint, -ra ); - - //System.out.printf("PR: % 8.3f % 8.3f % 8.3f\n", aPoint.x, aPoint.y, aPoint.z ); - - aCenter.times( -1 ); // reverse translation - aPoint.set( aPoint.add( aCenter ) ); - - //System.out.printf("PC: % 8.3f % 8.3f % 8.3f\n", aPoint.x, aPoint.y, aPoint.z ); - } - - - System.out.printf("PS: % 8.3f % 8.3f % 8.3f\n", aPoint.x, aPoint.y, aPoint.z ); - } - public static void main(String arg[]) throws FileNotFoundException { - - Constants.Load(); - - int s1 = 1; - int s2 = 1; - - Geometry geo = new Geometry(); - - System.out.println(" old geom strip inter " + geo.getLocCoord(s1, s2)[0] + "," + geo.getLocCoord(s1, s2)[1]); - - /* - * X[0][0] = x1; - X[0][1] = z1; - X[1][0] = x2; - X[1][1] = z2; - */ - //System.out.println(" end points 1"+geo.getStripEndPoints(s1, 0)[0][0]+", "+geo.getStripEndPoints(s1, 0)[0][1]); - //System.out.println(" end points "+(geo.getStripEndPoints(10, 1)[0][0]-Constants.ACTIVESENWIDTH/2)+", "+geo.getStripEndPoints(10, 1)[0][1]+"; " - // +(geo.getStripEndPoints(10, 1)[1][0]-Constants.ACTIVESENWIDTH/2)+", "+geo.getStripEndPoints(10, 1)[1][1]); - double[][] X = geo.getStripEndPoints(s1, 0); - double[][] Y = geo.getStripEndPoints(s2, 1); - System.out.println(" ep1 loc x " + X[0][0] + ", y" + X[0][1] + ", x " + X[1][0] + ", y " + X[1][1] + " ep2 loc x " + Y[0][0] + ", y" + Y[0][1] + ", x " + Y[1][0] + ", y " + Y[1][1]); - Point3D EP1u = geo.transformToFrame(1, 1, X[0][0], 0, X[0][1], "lab", ""); - Point3D EP2u = geo.transformToFrame(1, 1, X[1][0], 0, X[1][1], "lab", ""); - - Point3D EP1v = geo.transformToFrame(1, 2, Y[0][0], 0, Y[0][1], "lab", ""); - Point3D EP2v = geo.transformToFrame(1, 2, Y[1][0], 0, Y[1][1], "lab", ""); - System.out.println(EP1u.toString()); - System.out.println(EP2u.toString()); - System.out.println(EP1v.toString()); - System.out.println(EP2v.toString()); - - //System.out.println(geo.calcNearestStrip(25.66, -66.55, 1.37,2, 10) ); - //System.out.println(geo.transformToFrame(8, 1, 66.3, 7.8, 38.6, "local", "").z()-Constants.ACTIVESENLEN*2-2*0.835-Constants.ACTIVESENLEN/2); - /* - Line3D stripLine1 = svt.createStrip(s1-1); - Line3D stripLine2 = svt.createStrip(s2-1); - stripLine2.rotateZ(Math.toRadians(180)); - Transformation3D transform = new Transformation3D(); - transform.translateXYZ( -svt.DEADZNWID + svt.MODULEWID/2 , 0, -svt.DEADZNLEN + svt.MODULELEN/2 ); // align - - transform.apply( stripLine1 ); - transform.apply( stripLine2 ); - */ - /* - double[] LC = geo.getLocCoord(136,39); - double LC_x = LC[0]; - double LC_z = LC[1]; - - Point3D crPoint = geo.transformToFrame( 10, 2-1, LC_x, 0, LC_z, "lab", "middle"); - - - double m1 = (stripLine1.origin().x() - stripLine1.end().x() )/(stripLine1.origin().z() - stripLine1.end().z() ); - double m2 = (stripLine2.origin().x() - stripLine2.end().x() )/(stripLine2.origin().z() - stripLine2.end().z() ); - double b1 = stripLine1.origin().x() - stripLine1.origin().z()*m1; - double b2 = stripLine2.origin().x() - stripLine2.origin().z()*m2; - double z = (b2-b1)/(m1-m2); - double x = m1*z +b1; - System.out.println(" x "+x +" z "+z+" my geo "+crPoint.toString()); - - System.out.println(geo.getPlaneModuleOrigin(1, 1).toString() ); - */ - /* - int l = 1; - int s = 6; - double s10 = geo.calcNearestStrip(0., Constants.MODULERADIUS[l-1][s-1], 0, l, s); - double s20 = geo.calcNearestStrip(0., Constants.MODULERADIUS[l][s-1], 0, l+1, s); - - double s1 = geo.calcNearestStrip(0.5, Constants.MODULERADIUS[l-1][s-1], 0, l, s); - double s2 = geo.calcNearestStrip(0.5, Constants.MODULERADIUS[l][s-1], 0, l+1, s); - - - System.out.println("D "+geo.getLocCoord(s10, s20)[0]+","+geo.getLocCoord(s10, s20)[1]+" ; "+geo.getLocCoord(s1, s2)[0]+","+geo.getLocCoord(s1, s2)[1]); - */ } - } diff --git a/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/track/TrackCandListFinder.java b/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/track/TrackCandListFinder.java index a243aeaf93..1463030892 100644 --- a/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/track/TrackCandListFinder.java +++ b/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/track/TrackCandListFinder.java @@ -308,20 +308,20 @@ public ArrayList getHelicalTracks(CrossList crossList, ArrayList passedcands = this.rmHelicalTrkClones(org.jlab.rec.cvt.svt.Constants.removeClones, cands); // loop over candidates and set the trajectories - for (int ic = 0; ic < passedcands.size(); ic++) { - Helix trkHelix = passedcands.get(ic).get_helix(); - if(trkHelix!=null) { - TrajectoryFinder trjFind = new TrajectoryFinder(); - - //Trajectory traj = trjFind.findTrajectory(passedcands.get(ic).get_Id(), trkHelix, passedcands.get(ic), svt_geo, bmt_geo, "final"); - Trajectory traj = trjFind.findTrajectory(ic+1, passedcands.get(ic), svt_geo, bmt_geo, ctof_geo, cnd_geo, swimmer, "final"); - - passedcands.get(ic).set_Trajectory(traj.get_Trajectory()); - - passedcands.get(ic).set_Id(ic+1); - } - - } +// for (int ic = 0; ic < passedcands.size(); ic++) { +// Helix trkHelix = passedcands.get(ic).get_helix(); +// if(trkHelix!=null) { +// TrajectoryFinder trjFind = new TrajectoryFinder(); +// +// //Trajectory traj = trjFind.findTrajectory(passedcands.get(ic).get_Id(), trkHelix, passedcands.get(ic), svt_geo, bmt_geo, "final"); +// Trajectory traj = trjFind.findTrajectory(ic+1, passedcands.get(ic), svt_geo, bmt_geo, ctof_geo, cnd_geo, swimmer, "final"); +// +// passedcands.get(ic).set_Trajectory(traj.get_Trajectory()); +// +// passedcands.get(ic).set_Id(ic+1); +// } +// +// } return passedcands; diff --git a/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/track/TrackListFinder.java b/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/track/TrackListFinder.java index 4f15e43da0..d9d171bc42 100644 --- a/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/track/TrackListFinder.java +++ b/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/track/TrackListFinder.java @@ -49,7 +49,7 @@ public List getTracks(List cands, int charge = trk.get_Q(); double maxPathLength = 5.0;//very loose cut - bstSwim.SetSwimParameters(trk.get_helix().xdca() / 10, trk.get_helix().ydca() / 10, trk.get_helix().get_Z0() / 10, + bstSwim.SetSwimParameters((trk.get_helix().xdca()+org.jlab.rec.cvt.Constants.getXb()) / 10, (trk.get_helix().ydca()+org.jlab.rec.cvt.Constants.getYb()) / 10, trk.get_helix().get_Z0() / 10 , Math.toDegrees(trk.get_helix().get_phi_at_dca()), Math.toDegrees(Math.acos(trk.get_helix().costheta())), trk.get_P(), charge, maxPathLength) ; diff --git a/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/track/TrackSeederCA.java b/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/track/TrackSeederCA.java index f82ea6feca..97142306d0 100644 --- a/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/track/TrackSeederCA.java +++ b/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/track/TrackSeederCA.java @@ -536,7 +536,7 @@ public Track fitSeed(List VTCrosses, if (bmtCSz >= 2) { useSVTdipAngEst = 0; } - + ((ArrayList) X).ensureCapacity(svtSz + bmtZSz); ((ArrayList) Y).ensureCapacity(svtSz + bmtZSz); ((ArrayList) Z).ensureCapacity(svtSz * useSVTdipAngEst + bmtCSz); @@ -544,7 +544,7 @@ public Track fitSeed(List VTCrosses, ((ArrayList) ErrZ).ensureCapacity(svtSz * useSVTdipAngEst + bmtCSz); ((ArrayList) ErrRho).ensureCapacity(svtSz * useSVTdipAngEst + bmtCSz); // Try: don't use svt in dipdangle fit determination ((ArrayList) ErrRt).ensureCapacity(svtSz + bmtZSz); - + cand = new Track(null, swimmer); cand.addAll(SVTCrosses); for (int j = 0; j < SVTCrosses.size(); j++) { @@ -580,8 +580,8 @@ public Track fitSeed(List VTCrosses, ErrZ.add(j, BMTCrossesC.get(j - svtSz * useSVTdipAngEst).get_PointErr().z()); } } - X.add((double) 0); - Y.add((double) 0); + X.add((double) org.jlab.rec.cvt.Constants.getXb()); + Y.add((double) org.jlab.rec.cvt.Constants.getYb()); ErrRt.add((double) 0.1); @@ -598,15 +598,19 @@ public Track fitSeed(List VTCrosses, cand.addAll(BMTCrossesZ); cand.set_HelicalTrack(fitTrk.get_helix(), swimmer, b); - if( X.size()>3 ) + if( X.size()>3 ) { cand.set_circleFitChi2PerNDF(fitTrk.get_chisq()[0]/(X.size()-3)); - else + } + else { cand.set_circleFitChi2PerNDF(fitTrk.get_chisq()[0]*2); // penalize tracks with only 3 crosses + } - if( Z.size() > 2 ) + if( Z.size() > 2 ) { cand.set_lineFitChi2PerNDF(fitTrk.get_chisq()[1]/Z.size()); - else + } + else { cand.set_lineFitChi2PerNDF(fitTrk.get_chisq()[1]*2);// penalize tracks with only 2 crosses + } //if(shift==0) // if (fitTrk.get_chisq()[0] < chisqMax) { diff --git a/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/track/fit/KFitter.java b/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/track/fit/KFitter.java index b9d12514a3..fc4c8143ea 100644 --- a/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/track/fit/KFitter.java +++ b/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/track/fit/KFitter.java @@ -64,15 +64,15 @@ public void init(Seed trk, org.jlab.rec.cvt.svt.Geometry geo, DataEvent event, S //take first plane along beam line with n = y-dir; sv.Layer.add(0); sv.Sector.add(0); - sv.X0.add((double) Constants.getXb()); - sv.Y0.add((double) Constants.getYb()); + sv.X0.add((double) org.jlab.rec.cvt.Constants.getXb()); + sv.Y0.add((double) org.jlab.rec.cvt.Constants.getYb()); sv.Z0.add((double) 0.0); for (int i = 1; i < mv.measurements.size(); i++) { sv.Layer.add(mv.measurements.get(i).layer); sv.Sector.add(mv.measurements.get(i).sector); //Point3D ref = geo.intersectionOfHelixWithPlane(mv.measurements.get(i).layer, mv.measurements.get(i).sector, helix) ; //ref = new Point3D(0,Constants.MODULERADIUS[mv.measurements.get(i).layer-1][0], 0); - Point3D ref = new Point3D(Constants.getXb(), Constants.getYb(), 0); + Point3D ref = new Point3D(org.jlab.rec.cvt.Constants.getXb(), org.jlab.rec.cvt.Constants.getYb(), 0); sv.X0.add(ref.x()); sv.Y0.add(ref.y()); sv.Z0.add(ref.z()); @@ -105,9 +105,9 @@ public void runFitter(org.jlab.rec.cvt.svt.Geometry sgeo, org.jlab.rec.cvt.bmt.G this.filter(k - 1, sgeo, bgeo, swimmer); } - if (it < totNumIter - 1) { - this.Rinit(swimmer); - } + //if (it < totNumIter - 1) { + // this.Rinit(swimmer); + //} this.chi2=this.calc_chi2(sgeo); if(this.chi20.1) { + h_dca = -x/Math.sin(h_phi0); + } else { + h_dca = y/Math.cos(h_phi0); + } + double kappa = Math.signum(this.trackTraj.get(kf).kappa) / Math.sqrt(px * px + py * py); double h_omega = kappa / this.trackTraj.get(kf).alpha; h_omega = kappa/this.trackTraj.get(0).alpha; double h_dz = z; double h_tandip = pz / Math.sqrt(px * px + py * py); Helix trkHelix = new Helix(h_dca, h_phi0, h_omega, h_dz, h_tandip, this.trackCov.get(kf).covMat); - // System.out.println("x "+x+" y "+y+" z "+z+" p "+p_unc+" pt "+Math.sqrt(px*px+py*py) +" theta "+Math.toDegrees(Math.acos(pz/Math.sqrt(px*px+py*py+pz*pz)))+" phi "+Math.toDegrees(Math.atan2(py, px))+" q "+q); + //System.out.println("x "+x+" y "+y+" x' "+(-h_dca*Math.sin(h_phi0))+" y' "+y*Math.cos(h_phi0) +" theta "+Math.toDegrees(Math.acos(pz/Math.sqrt(px*px+py*py+pz*pz)))+" phi "+Math.toDegrees(Math.atan2(py, px))+" q "+q); return trkHelix; } public void init(Seed trk, KFitter kf, Swim swimmer) { //init stateVec - StateVec initSV = new StateVec(0); initSV.x = -trk.get_Helix().get_dca() * Math.sin(trk.get_Helix().get_phi_at_dca()); initSV.y = trk.get_Helix().get_dca() * Math.cos(trk.get_Helix().get_phi_at_dca()); initSV.z = trk.get_Helix().get_Z0(); double xcen = (1. / trk.get_Helix().get_curvature() - trk.get_Helix().get_dca()) * Math.sin(trk.get_Helix().get_phi_at_dca()); double ycen = (-1. / trk.get_Helix().get_curvature() + trk.get_Helix().get_dca()) * Math.cos(trk.get_Helix().get_phi_at_dca()); - B Bf = new B(0, 0, 0, 0, swimmer); + B Bf = new B(0, (float)org.jlab.rec.cvt.Constants.getXb(), (float)org.jlab.rec.cvt.Constants.getYb(), initSV.z, swimmer); initSV.alpha = Bf.alpha; initSV.kappa = Bf.alpha * trk.get_Helix().get_curvature(); initSV.phi0 = Math.atan2(ycen, xcen); @@ -568,7 +579,7 @@ public void init(Seed trk, KFitter kf, Swim swimmer) { initSV.d_rho = trk.get_Helix().get_dca(); initSV.phi = 0; // - + this.trackTraj.put(0, initSV); //init covMat Matrix fitCovMat = trk.get_Helix().get_covmatrix(); diff --git a/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/trajectory/Helix.java b/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/trajectory/Helix.java index 16621ef06a..d1c6b2a51f 100755 --- a/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/trajectory/Helix.java +++ b/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/trajectory/Helix.java @@ -133,11 +133,11 @@ public double ycen() { // (x,y) coordinates of the dca public double xdca() { - return this.get_dca() * Math.cos(this.get_phi_at_dca()); + return -this.get_dca() * Math.sin(this.get_phi_at_dca()); } public double ydca() { - return this.get_dca() * Math.sin(this.get_phi_at_dca()); + return this.get_dca() * Math.cos(this.get_phi_at_dca()); } public double getArcLength_dca(Point3D refpoint) { @@ -199,8 +199,10 @@ public Point3D getPointAtRadius(double r) { double alpha = -newPathLength * omega; - double x = d0 * charge * Math.sin(phi0) + (charge / Math.abs(omega)) * (Math.sin(phi0) - Math.cos(alpha) * Math.sin(phi0) - Math.sin(alpha) * Math.cos(phi0)); - double y = -d0 * charge * Math.cos(phi0) - (charge / Math.abs(omega)) * (Math.cos(phi0) + Math.sin(alpha) * Math.sin(phi0) - Math.cos(alpha) * Math.cos(phi0)); + double x = d0 * charge * Math.sin(phi0) + (charge / Math.abs(omega)) + * (Math.sin(phi0) - Math.cos(alpha) * Math.sin(phi0) - Math.sin(alpha) * Math.cos(phi0)); + double y = -d0 * charge * Math.cos(phi0) - (charge / Math.abs(omega)) + * (Math.cos(phi0) + Math.sin(alpha) * Math.sin(phi0) - Math.cos(alpha) * Math.cos(phi0)); double z = z0 + newPathLength * tandip; return new Point3D(x, y, z); diff --git a/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/trajectory/StateVec.java b/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/trajectory/StateVec.java index 46d97ad3b1..e0097736e6 100644 --- a/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/trajectory/StateVec.java +++ b/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/trajectory/StateVec.java @@ -12,6 +12,7 @@ */ public class StateVec extends Matrix implements Comparable { + /** * serialVersionUID */ @@ -21,6 +22,7 @@ public class StateVec extends Matrix implements Comparable { private int _SurfaceDetector; private int _SurfaceLayer; private int _SurfaceSector; + private int _SurfaceComponent; private double _TrkPhiAtSurface; private double _TrkThetaAtSurface; private double _TrkToModuleAngle; @@ -70,7 +72,20 @@ public void set_SurfaceSector(int _SurfaceSector) { public double get_TrkPhiAtSurface() { return _TrkPhiAtSurface; } + /** + * @return the _SurfaceComponent + */ + public int get_SurfaceComponent() { + return _SurfaceComponent; + } + /** + * @param _SurfaceComponent the _SurfaceComponent to set + */ + public void set_SurfaceComponent(int _SurfaceComponent) { + this._SurfaceComponent = _SurfaceComponent; + } + public void set_TrkPhiAtSurface(double _TrkPhiAtSurface) { this._TrkPhiAtSurface = _TrkPhiAtSurface; } diff --git a/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/trajectory/TrajectoryFinder.java b/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/trajectory/TrajectoryFinder.java index 6efcaf0f98..419dce6a1c 100644 --- a/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/trajectory/TrajectoryFinder.java +++ b/reconstruction/cvt/src/main/java/org/jlab/rec/cvt/trajectory/TrajectoryFinder.java @@ -1,15 +1,23 @@ package org.jlab.rec.cvt.trajectory; + +import eu.mihosoft.vrl.v3d.Vector3d; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.List; import org.jlab.clas.swimtools.Swim; import org.jlab.detector.base.DetectorType; import org.jlab.detector.geant4.v2.CTOFGeant4Factory; +import org.jlab.detector.hits.CTOFDetHit; +import org.jlab.detector.hits.DetHit; import org.jlab.geom.base.Detector; +import org.jlab.geom.prim.Line3D; +import org.jlab.geom.prim.Path3D; import org.jlab.geom.prim.Point3D; import org.jlab.geom.prim.Vector3D; +import org.jlab.geometry.prim.Line3d; import org.jlab.rec.cvt.cluster.Cluster; import org.jlab.rec.cvt.cross.Cross; import org.jlab.rec.cvt.hit.FittedHit; @@ -29,7 +37,7 @@ public class TrajectoryFinder { public TrajectoryFinder() { } - + /** * * @param candCrossList the input list of crosses used in determining a @@ -90,25 +98,53 @@ public Trajectory findTrajectory(int id, Track trk, traj.set_SVTSector(Sectors); ArrayList stateVecs = new ArrayList(); + + // initialize swimmer starting from the track vertex + double maxPathLength = 1; + swimmer.SetSwimParameters((trk.get_helix().xdca()+org.jlab.rec.cvt.Constants.getXb()) / 10, (trk.get_helix().ydca()+org.jlab.rec.cvt.Constants.getYb()) / 10, trk.get_helix().get_Z0() / 10, + Math.toDegrees(trk.get_helix().get_phi_at_dca()), Math.toDegrees(Math.acos(trk.get_helix().costheta())), + trk.get_P(), trk.get_Q(), maxPathLength) ; + double[] inters = null; + double path = 0; // SVT for (int l = 0; l < org.jlab.rec.cvt.svt.Constants.NLAYR; l++) { + // reinitilize swimmer from last surface +// if(inters!=null) { +// double intersPhi = Math.atan2(inters[4], inters[3]); +// double intersTheta = Math.acos(inters[5]/Math.sqrt(inters[3]*inters[3]+inters[4]*inters[4]+inters[5]*inters[5])); +// swimmer.SetSwimParameters(inters[0], inters[1], inters[2], Math.toDegrees(intersPhi), Math.toDegrees(intersTheta), trk.get_P(), trk.get_Q(), maxPathLength) ; +// } int layer = l + 1; int sector = Sectors[l]; - - Point3D helixInterWithBstPlane = svt_geo.intersectionOfHelixWithPlane(layer, sector, helix); - double R = Math.sqrt(helixInterWithBstPlane.x() * helixInterWithBstPlane.x() + helixInterWithBstPlane.y() * helixInterWithBstPlane.y()); - - Vector3D trkDir = helix.getTrackDirectionAtRadius(R); - - StateVec stVec = new StateVec(helixInterWithBstPlane.x(), helixInterWithBstPlane.y(), helixInterWithBstPlane.z(), - trkDir.x(), trkDir.y(), trkDir.z()); + +// Point3D helixInterWithBstPlane = svt_geo.intersectionOfHelixWithPlane(layer, sector, helix); +// double R = Math.sqrt(helixInterWithBstPlane.x() * helixInterWithBstPlane.x() + helixInterWithBstPlane.y() * helixInterWithBstPlane.y()); +// +// Vector3D trkDir = helix.getTrackDirectionAtRadius(R); +// +// StateVec stVec = new StateVec(helixInterWithBstPlane.x(), helixInterWithBstPlane.y(), helixInterWithBstPlane.z(), +// trkDir.x(), trkDir.y(), trkDir.z()); +// stVec.set_planeIdx(l); +// stVec.set_SurfaceDetector(DetectorType.CVT.getDetectorId()); +// stVec.set_SurfaceLayer(layer); +// stVec.set_SurfaceSector(sector); +// stVec.set_CalcCentroidStrip(svt_geo.calcNearestStrip(helixInterWithBstPlane.x(), helixInterWithBstPlane.y(), helixInterWithBstPlane.z(), layer, sector)); +// +// this.fill_HelicalTrkAngleWRTSVTPlane(sector, layer, trkDir, svt_geo, stVec); +// + // + Vector3D n = svt_geo.findBSTPlaneNormal(sector, layer); + Point3D p = svt_geo.getPlaneModuleOrigin(sector, layer); + double d = n.dot(p.toVector3D()); + inters = swimmer.SwimToPlaneBoundary(d/10.0, n, 1); + path = inters[6]; + StateVec stVec = new StateVec(inters[0]*10, inters[1]*10, inters[2]*10, inters[3], inters[4], inters[5]); stVec.set_planeIdx(l); stVec.set_SurfaceDetector(DetectorType.CVT.getDetectorId()); stVec.set_SurfaceLayer(layer); stVec.set_SurfaceSector(sector); - stVec.set_CalcCentroidStrip(svt_geo.calcNearestStrip(helixInterWithBstPlane.x(), helixInterWithBstPlane.y(), helixInterWithBstPlane.z(), layer, sector)); - - this.fill_HelicalTrkAngleWRTSVTPlane(sector, layer, trkDir, svt_geo, stVec); + stVec.set_CalcCentroidStrip(svt_geo.calcNearestStrip(inters[0]*10, inters[1]*10, inters[2]*10, layer, sector)); + stVec.set_Path(path*10); stVec.set_ID(id); stateVecs.add(stVec); @@ -117,9 +153,10 @@ public Trajectory findTrajectory(int id, Track trk, if (matchCrossToStateVec(c, stVec, layer, sector) == false) { continue; } - + Vector3D dir = new Vector3D(inters[3], inters[4], inters[5]).asUnit(); + this.fill_HelicalTrkAngleWRTSVTPlane(sector, layer, dir, svt_geo, stVec); // set the cross dir - c.set_Dir(trkDir); + c.set_Dir(dir); Cluster clsOnTrk = null; if (l % 2 == 0) { @@ -137,127 +174,176 @@ public Trajectory findTrajectory(int id, Track trk, } } + // reinitialize from vertex + maxPathLength = 1.5; + swimmer.SetSwimParameters((trk.get_helix().xdca()+org.jlab.rec.cvt.Constants.getXb()) / 10, (trk.get_helix().ydca()+org.jlab.rec.cvt.Constants.getYb()) / 10, trk.get_helix().get_Z0() / 10, + Math.toDegrees(trk.get_helix().get_phi_at_dca()), Math.toDegrees(Math.acos(trk.get_helix().costheta())), + trk.get_P(), trk.get_Q(), maxPathLength) ; + inters = null; + path = 0; //BMT for (int l = org.jlab.rec.cvt.svt.Constants.NLAYR; l < org.jlab.rec.cvt.svt.Constants.NLAYR + 2 * org.jlab.rec.cvt.bmt.Constants.NREGIONS; l++) { - int BMTRegIdx = (l - org.jlab.rec.cvt.svt.Constants.NLAYR) / 2; - - if (org.jlab.rec.cvt.bmt.Constants.getCRCRADIUS()[BMTRegIdx] == 0) { - continue; // Use the correctly defined geometry + // re-initilize swimmer from last surface + if(inters!=null) { + double intersPhi = Math.atan2(inters[4], inters[3]); + double intersTheta = Math.acos(inters[5]/Math.sqrt(inters[3]*inters[3]+inters[4]*inters[4]+inters[5]*inters[5])); + swimmer.SetSwimParameters(inters[0], inters[1], inters[2], Math.toDegrees(intersPhi), Math.toDegrees(intersTheta), trk.get_P(), trk.get_Q(), maxPathLength) ; } - double R = 0; + if(inters!=null || l==org.jlab.rec.cvt.svt.Constants.NLAYR) { // don't swim if previous layers was not reached + int BMTRegIdx = (l - org.jlab.rec.cvt.svt.Constants.NLAYR) / 2; - if (org.jlab.rec.cvt.bmt.Geometry.getZorC(l + 1-6) == 1) { - R = org.jlab.rec.cvt.bmt.Constants.getCRZRADIUS()[BMTRegIdx] + org.jlab.rec.cvt.bmt.Constants.LYRTHICKN; - } - if (org.jlab.rec.cvt.bmt.Geometry.getZorC(l + 1-6) == 0) { - R = org.jlab.rec.cvt.bmt.Constants.getCRCRADIUS()[BMTRegIdx] + org.jlab.rec.cvt.bmt.Constants.LYRTHICKN; - } - Point3D InterPoint = helix.getPointAtRadius(R); - Vector3D trkDir = helix.getTrackDirectionAtRadius(R); - - StateVec stVec = new StateVec(InterPoint.x(), InterPoint.y(), InterPoint.z(), - trkDir.x(), trkDir.y(), trkDir.z()); - - stVec.set_planeIdx(l); - double phiPos = Math.atan2(stVec.y(),stVec.x()); - int sector = bmt_geo.isInSector(BMTRegIdx+1,phiPos, 0); - stVec.set_SurfaceDetector(DetectorType.CVT.getDetectorId()); - stVec.set_SurfaceSector(sector); - stVec.set_SurfaceLayer(l+1); - stVec.set_ID(id); - //stateVecs.add(stVec); - // calculate crosses on BMT layers using track information. These are used in the event display - for (Cross c : BMTCrossList) { - if (matchCrossToStateVec(c, stVec, l + 1, 0) == false) { - continue; + if (org.jlab.rec.cvt.bmt.Constants.getCRCRADIUS()[BMTRegIdx] == 0) { + continue; // Use the correctly defined geometry } - if (c.get_DetectorType().equalsIgnoreCase("C")) { //C-detector measuring Z - double x = InterPoint.x(); - double y = InterPoint.y(); - if (traj.isFinal) { - c.set_Point(new Point3D(x, y, c.get_Point().z())); - c.set_Dir(trkDir); - } + double R = 0; - // calculate the hit residuals - this.setHitResolParams("BMT", c.get_Cluster1().get_Sector(), c.get_Cluster1().get_Layer(), c.get_Cluster1(), - stVec, svt_geo, bmt_geo, traj.isFinal); - -// StateVec stVecC = new StateVec(InterPoint.x(), InterPoint.y(), InterPoint.z(), -// trkDir.x(), trkDir.y(), trkDir.z()); - -// stVecC.set_planeIdx(l); - //C-detector measuring z - stVec.set_CalcCentroidStrip(bmt_geo.getCStrip(BMTRegIdx+1, stVec.z())); -// this.fill_HelicalTrkAngleWRTBMTTangentPlane(trkDir, stVec); + if (org.jlab.rec.cvt.bmt.Geometry.getZorC(l + 1-6) == 1) { + R = org.jlab.rec.cvt.bmt.Constants.getCRZRADIUS()[BMTRegIdx] + org.jlab.rec.cvt.bmt.Constants.LYRTHICKN; } -// if (c.get_DetectorType().equalsIgnoreCase("Z")) { //Z-detector measuring phi - else { //Z-detector measuring phi - double z = InterPoint.z(); - if (traj.isFinal) { - c.set_Point(new Point3D(c.get_Point().x(), c.get_Point().y(), z)); - c.set_Dir(trkDir); + if (org.jlab.rec.cvt.bmt.Geometry.getZorC(l + 1-6) == 0) { + R = org.jlab.rec.cvt.bmt.Constants.getCRCRADIUS()[BMTRegIdx] + org.jlab.rec.cvt.bmt.Constants.LYRTHICKN; + } + + // swimmer.SetSwimParameters((trk.get_helix().xdca()+org.jlab.rec.cvt.Constants.getXb()) / 10, (trk.get_helix().ydca()+org.jlab.rec.cvt.Constants.getYb()) / 10, trk.get_helix().get_Z0() / 10, + // Math.toDegrees(trk.get_helix().get_phi_at_dca()), Math.toDegrees(Math.acos(trk.get_helix().costheta())), + // trk.get_P(), trk.get_Q(), + // 5.0) ; + inters = swimmer.SwimToCylinder(R/10); + double r = Math.sqrt(inters[0]*inters[0]+inters[1]*inters[1]); + path = path + inters[6]; + if(r>R/10) { + StateVec stVec = new StateVec(inters[0]*10, inters[1]*10, inters[2]*10, inters[3], inters[4], inters[5]); + stVec.set_planeIdx(l); + double phiPos = Math.atan2(stVec.y(),stVec.x()); + int sector = bmt_geo.isInSector(BMTRegIdx+1,phiPos, 0); + stVec.set_SurfaceDetector(DetectorType.CVT.getDetectorId()); + stVec.set_SurfaceSector(sector); + stVec.set_SurfaceLayer(l+1); + stVec.set_ID(id); + stVec.set_Path(path*10); + Vector3D dir = new Vector3D(inters[3], inters[4], inters[5]).asUnit(); + //stateVecs.add(stVec); + // calculate crosses on BMT layers using track information. These are used in the event display + for (Cross c : BMTCrossList) { + if (matchCrossToStateVec(c, stVec, l + 1, 0) == false) { + continue; + } + + if (c.get_DetectorType().equalsIgnoreCase("C")) { //C-detector measuring Z + double x = stVec.x(); + double y = stVec.y(); + if (traj.isFinal) { + + c.set_Point(new Point3D(x, y, c.get_Point().z())); + c.set_Dir(dir); + } + + // calculate the hit residuals + this.setHitResolParams("BMT", c.get_Cluster1().get_Sector(), c.get_Cluster1().get_Layer(), c.get_Cluster1(), + stVec, svt_geo, bmt_geo, traj.isFinal); + + // StateVec stVecC = new StateVec(InterPoint.x(), InterPoint.y(), InterPoint.z(), + // trkDir.x(), trkDir.y(), trkDir.z()); + + // stVecC.set_planeIdx(l); + //C-detector measuring z + stVec.set_CalcCentroidStrip(bmt_geo.getCStrip(BMTRegIdx+1, stVec.z())); + // this.fill_HelicalTrkAngleWRTBMTTangentPlane(trkDir, stVec); + } + // if (c.get_DetectorType().equalsIgnoreCase("Z")) { //Z-detector measuring phi + else { //Z-detector measuring phi + double z = stVec.z(); + if (traj.isFinal) { + c.set_Point(new Point3D(c.get_Point().x(), c.get_Point().y(), z)); + c.set_Dir(dir); + } + + // calculate the hit residuals + this.setHitResolParams("BMT", c.get_Cluster1().get_Sector(), c.get_Cluster1().get_Layer(), c.get_Cluster1(), + stVec, svt_geo, bmt_geo, traj.isFinal); + // StateVec stVecZ = new StateVec(InterPoint.x(), InterPoint.y(), InterPoint.z(), + // trkDir.x(), trkDir.y(), trkDir.z()); + // stVecZ.set_planeIdx(l); + //Z-detector measuring phi + // double phiPos = Math.atan2(stVec.y(),stVec.x()); + stVec.set_CalcCentroidStrip(bmt_geo.getZStrip(BMTRegIdx+1, phiPos)); + // int sector = bmt_geo.isInSector(BMTRegIdx+1,phiPos, 0); + // stVecZ.set_SurfaceSector(sector); + //Layer starting at 7 + // stVecZ.set_SurfaceLayer(l+1); + // stVecZ.set_ID(id); + // stateVecs.add(stVecZ); + } } - // calculate the hit residuals - this.setHitResolParams("BMT", c.get_Cluster1().get_Sector(), c.get_Cluster1().get_Layer(), c.get_Cluster1(), - stVec, svt_geo, bmt_geo, traj.isFinal); -// StateVec stVecZ = new StateVec(InterPoint.x(), InterPoint.y(), InterPoint.z(), -// trkDir.x(), trkDir.y(), trkDir.z()); -// stVecZ.set_planeIdx(l); - //Z-detector measuring phi -// double phiPos = Math.atan2(stVec.y(),stVec.x()); - stVec.set_CalcCentroidStrip(bmt_geo.getZStrip(BMTRegIdx+1, phiPos)); -// int sector = bmt_geo.isInSector(BMTRegIdx+1,phiPos, 0); -// stVecZ.set_SurfaceSector(sector); - //Layer starting at 7 -// stVecZ.set_SurfaceLayer(l+1); -// stVecZ.set_ID(id); -// stateVecs.add(stVecZ); + this.fill_HelicalTrkAngleWRTBMTTangentPlane(dir, stVec); + stateVecs.add(stVec); + } + else { + inters=null; } } - - this.fill_HelicalTrkAngleWRTBMTTangentPlane(trkDir, stVec); - stateVecs.add(stVec); - } -// // CTOF -// if(ctof_geo!=null) { -// double radius = ctof_geo.getRadius(1); -// int charge = trk.get_Q(); -// double maxPathLength = 5.0;//very loose cut -// swimmer.SetSwimParameters(trk.get_helix().xdca() / 10, trk.get_helix().ydca() / 10, trk.get_helix().get_Z0() / 10, -// Math.toDegrees(trk.get_helix().get_phi_at_dca()), Math.toDegrees(Math.acos(trk.get_helix().costheta())), -// trk.get_P(), charge, -// maxPathLength) ; -// double[] inters = swimmer.SwimToCylinder(radius); -// StateVec stVec = new StateVec(inters[0]*10, inters[1]*10, inters[2]*10, inters[3], inters[4], inters[5]); -// stVec.set_SurfaceDetector(DetectorType.CTOF.getDetectorId()); -// stVec.set_SurfaceSector(1); -// stVec.set_SurfaceLayer(1); -// stVec.set_ID(id); -// stVec.set_TrkPhiAtSurface(Math.atan2(inters[4], inters[3])); -// stVec.set_TrkThetaAtSurface(Math.acos(inters[5]/Math.sqrt(inters[3]*inters[3]+inters[4]*inters[4]+inters[5]*inters[5]))); -// stVec.set_TrkToModuleAngle(0); -// stVec.set_Path(inters[6]*10); -// stateVecs.add(stVec); -// } -// // CND -// for(int ilayer=0; ilayer=radius) { + StateVec stVec = new StateVec(inters[0]*10, inters[1]*10, inters[2]*10, inters[3], inters[4], inters[5]); + stVec.set_SurfaceDetector(DetectorType.CTOF.getDetectorId()); + stVec.set_SurfaceSector(1); + stVec.set_SurfaceLayer(1); + stVec.set_ID(id); + stVec.set_TrkPhiAtSurface(intersPhi); + stVec.set_TrkThetaAtSurface(intersTheta); + stVec.set_TrkToModuleAngle(0); + stVec.set_Path(path*10); + stateVecs.add(stVec); + } + else inters=null; + } + // CND + if(cnd_geo!=null && inters!=null) { // don't swim to CND if swimming to CTOF failed + for(int ilayer=0; ilayer Constants.interTol) { + if (Math.abs(stVec.z() - c.get_Point0().z()) > Constants.TOLTOMODULELEN) { value = false; } } @@ -501,7 +587,7 @@ private boolean matchCrossToStateVec(Cross c, StateVec stVec, int layer, int sec value = false; } double deltaXt = Math.sqrt((stVec.x() - c.get_Point().x()) * (stVec.x() - c.get_Point().x()) + (stVec.y() - c.get_Point().y()) * (stVec.y() - c.get_Point().y())); - if (deltaXt > 2*Constants.interTol) { + if (deltaXt > 2*Constants.TOLTOMODULELEN) { value = false; } } @@ -530,7 +616,7 @@ public void setHitResolParams(String detector, int sector, int layer, Cluster cl double doca1 = svt_geo.getDOCAToStrip(sector, layer, (double) hit.get_Strip().get_Strip(), new Point3D(stVec.x(), stVec.y(), stVec.z())); double sigma1 = svt_geo.getSingleStripResolution(layer, hit.get_Strip().get_Strip(), stVec.z()); hit.set_stripResolutionAtDoca(sigma1); - hit.set_docaToTrk(doca1); + hit.set_docaToTrk(doca2Cls); if (trajFinal) { hit.set_TrkgStatus(2); } @@ -810,4 +896,55 @@ public void hitsToArray(List hits2) { } } + + private List getTrkInMiddleOfBar(int id, double[] inters, CTOFGeant4Factory ctof_geo) { + List stateVecs = new ArrayList(); + + double p = Math.sqrt(inters[3]*inters[3]+inters[4]*inters[4]+inters[5]*inters[5]); + double x = inters[0]; + double y = inters[1]; + double z = inters[2]; + double ux = inters[3]/p; + double uy = inters[4]/p; + double uz = inters[5]/p; + double path = inters[6]; + + Line3d line = new Line3d(new Vector3d(x,y,z), new Vector3d(x+5*ux,y+5*uy, z+5*uz)); + + List trkHits = ctof_geo.getIntersections(line); + if (trkHits != null && trkHits.size() > 0) { + for (DetHit hit : trkHits) { + CTOFDetHit trkHit = new CTOFDetHit(hit); + //track extrp to a line, make sure you pick up the right hit + if(Math.sqrt((trkHit.origin().x-x)*(trkHit.origin().x-x)+ + (trkHit.origin().y-y)*(trkHit.origin().y-y))>3.5*2) //thickness*2 + continue; + int component = trkHit.getPaddle(); + // get the coordinates for the track hit, which is defined + // as the mid-point between its entrance and its exit from + // the bar + path+=trkHit.origin().distance(trkHit.end()); + new Point3D(trkHit.mid().x,trkHit.mid().y, trkHit.mid().z); + Vector3d dir = trkHit.end().minus(trkHit.origin()).normalized(); + + StateVec stVec = new StateVec(trkHit.mid().x*10, trkHit.mid().y*10, trkHit.mid().z*10, + dir.x*p, dir.y*p, dir.z*p); + stVec.set_SurfaceDetector(DetectorType.CTOF.getDetectorId()); + stVec.set_SurfaceSector(1); + stVec.set_SurfaceLayer(1); + stVec.set_ID(id); + stVec.set_SurfaceComponent(component); + stVec.set_CalcCentroidStrip(component); + stVec.set_TrkPhiAtSurface(Math.atan2(dir.y, dir.x)); + stVec.set_TrkThetaAtSurface(Math.acos(dir.z)); + stVec.set_TrkToModuleAngle(0); + stVec.set_Path(path*10); + stateVecs.add(stVec); + + } + } + return stateVecs; + } + + } diff --git a/reconstruction/dc/pom.xml b/reconstruction/dc/pom.xml index 35483e6e78..e69f847cb8 100644 --- a/reconstruction/dc/pom.xml +++ b/reconstruction/dc/pom.xml @@ -25,7 +25,7 @@ org.jlab.clas clas12rec ../../parent/pom.xml - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT @@ -39,7 +39,7 @@ org.jlab.clas clas-jcsg - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT @@ -52,13 +52,13 @@ org.jlab.clas clas-reco - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-analysis - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT @@ -87,13 +87,13 @@ org.jlab.clas swim-tools - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-math - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/Constants.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/Constants.java index 95ff57d7cd..f87d4d80f4 100644 --- a/reconstruction/dc/src/main/java/org/jlab/rec/dc/Constants.java +++ b/reconstruction/dc/src/main/java/org/jlab/rec/dc/Constants.java @@ -85,6 +85,8 @@ public class Constants { public static final double SEGMENTPLANESANGLE = 1.5; // the angle between the normals to the segment fit planes is 12 degrees (6+6 for +/- stereo relative angles) + 1.5 degrees tolerance. This number (1.5) should be optimized public static final double ARGONRADLEN = 14; // radiation length in Argon is 14 cm + + public static final double AIRRADLEN = 30400; // radiation length in cm public static final double SWIMSTEPSIZE = 5.00*1.e-4; //n00 microns @@ -108,6 +110,8 @@ public class Constants { public static final int[] SNR_RIGHTSHIFTS = {0,1,2,2,4,4}; public static final int[] SNR_LEFTSHIFTS = {0,1,2,2,4,4}; + // Z Range for MS + public static double[] Z = new double[13]; // Arrays for combinatorial cluster compositions private static final int[][] CombArray1Layer = new int[][]{ @@ -161,12 +165,20 @@ public class Constants { public static int[][] STBLOC; private static boolean USETSTART = true; + private static boolean USETIMETBETA = false; + public static double SEEDCUT = 5000; public static double MINPATH = 200; public static double BETAHIGH = 1.5; public static double BETALOW = 0.15; //max number of hits allowed in the event to do tracking public static double MAXHITS = 2000; + ; + public static double TRANSVTXCUT = 20; + + public static double AVEDRIFTVEL = 0.0027; //velocity in cm / ns. [CLAS-Note 96-008] + public static boolean CHECKBETA = false; + public static double DOCASUMMAXFAC = 1.6; public static boolean isUSETSTART() { return USETSTART; @@ -176,6 +188,15 @@ public static void setUSETSTART(boolean USETSTART) { Constants.USETSTART = USETSTART; } + public static boolean useUSETIMETBETA() { + return USETIMETBETA; + } + + public static void setUSETIMETBETA(boolean USETIMETBETA) { + Constants.USETIMETBETA = USETIMETBETA; + } + + private static double WIREDIST = 0.0; /** @@ -295,5 +316,8 @@ public static double getT2D() { return Constants.T2D; } - + // geometry constants not yet read from CCDB of from geometry services + public static double htccRadius=175; + public static double ltccPlane=653.09; + } diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/banks/HitReader.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/banks/HitReader.java index 4f6ab2a55e..36e041bfc7 100644 --- a/reconstruction/dc/src/main/java/org/jlab/rec/dc/banks/HitReader.java +++ b/reconstruction/dc/src/main/java/org/jlab/rec/dc/banks/HitReader.java @@ -79,7 +79,7 @@ public List get_TBHits() { private void set_TBHits(List _TBHits) { this._TBHits = _TBHits; } - + private final double timeBuf = 25.0; /** * reads the hits using clas-io methods to get the EvioBank for the DC and * fill the values to instantiate the DChit and MChit classes. This methods @@ -193,7 +193,7 @@ public void fetch_DCHits(DataEvent event, Clas12NoiseAnalysis noiseAnalysis, break; case 3: timeCutMin = tab2.getIntValue("MinEdge", 0, region, 0); - timeCutMax = tab2.getIntValue("MaxEdge", 0, region, 0); + timeCutMax = tab2.getIntValue("MaxEdge", 0, region, 0)+timeBuf; break; } boolean passTimingCut = false; @@ -302,16 +302,25 @@ public void read_HBHits(DataEvent event, IndexedTable constants0, IndexedTable c if (trkID[i] == -1) { continue; } - + double T_0 = 0; double T_Start = 0; + + if (!event.hasBank("RECHB::Event")) { + continue; + } + if (event.hasBank("RECHB::Event") && + event.getBank("RECHB::Event").getFloat("startTime", 0)==-1000) { + continue; + } + if (!event.hasBank("MC::Particle") && event.getBank("RUN::config").getInt("run", 0) > 100) { - T_0 = this.get_T0(sector[i], slayer[i], layer[i], wire[i], T0, T0ERR)[0]; + //T_0 = this.get_T0(sector[i], slayer[i], layer[i], wire[i], T0, T0ERR)[0]; if (event.hasBank("RECHB::Event")) T_Start = event.getBank("RECHB::Event").getFloat("startTime", 0); } - + T_0 = this.get_T0(sector[i], slayer[i], layer[i], wire[i], T0, T0ERR)[0]; FittedHit hit = new FittedHit(sector[i], slayer[i], layer[i], wire[i], tdc[i], id[i]); hit.set_Id(id[i]); hit.setB(B[i]); @@ -320,6 +329,7 @@ public void read_HBHits(DataEvent event, IndexedTable constants0, IndexedTable c hit.setTProp(tProp[i]); //hit.setTFlight(tFlight[i]); hit.set_Beta(this.readBeta(event, trkID[i])); + this.set_BetaFlag(event, trkID[i], hit, hit.get_Beta());//reset beta for out of range assuming the pion hypothesis and setting a flag hit.setTFlight(tFlight[i]/hit.get_Beta0to1()); //resetting TFlight after beta has been obtained //hit.setSignalTimeOfFlight(); @@ -332,8 +342,9 @@ public void read_HBHits(DataEvent event, IndexedTable constants0, IndexedTable c hit.set_LeftRightAmb(LR[i]); hit.set_TrkgStatus(0); hit.calc_CellSize(DcDetector); + hit.calc_GeomCorr(DcDetector, 0); hit.set_ClusFitDoca(trkDoca[i]); - hit.set_TimeToDistance(event, 1.0, B[i], constants1, tde); + hit.set_TimeToDistance(event, 0.0, B[i], constants1, tde); hit.set_QualityFac(0); if (hit.get_Doca() > hit.get_CellSize()) { @@ -346,115 +357,134 @@ public void read_HBHits(DataEvent event, IndexedTable constants0, IndexedTable c hit.set_DocaErr(hit.get_PosErr(event, B[i], constants0, constants1, tde)); hit.set_AssociatedClusterID(clusterID[i]); hit.set_AssociatedHBTrackID(trkID[i]); - if(hit.get_Beta()>0.15) { - hits.add(hit); - } + + //if(hit.betaFlag == 0) + if(passHit(hit.betaFlag)) + hits.add(hit); } this.set_HBHits(hits); } + + private boolean passHit(int betaFlag) { + boolean pass = true; + if(Constants.CHECKBETA) { + //if(betaFlag != 0) { //all beta cuts + // pass = false; + //} + if(Math.abs(betaFlag) == 1) { // beta cut: beta >0.15 + pass = false; + } + } + return pass; + } + + public void read_NNHits(DataEvent event, DCGeant4Factory DcDetector, + double triggerPhase) { + + if (!(event.hasBank("DC::tdc") && event.hasBank("nn::dchits") )) { + _DCHits = new ArrayList<>(); - public void read_TBHits(DataEvent event, IndexedTable constants0, IndexedTable constants1, - TimeToDistanceEstimator tde, double[][][][] T0, double[][][][] T0ERR) { - /* - 0: this.getConstantsManager().getConstants(newRun, "/calibration/dc/signal_generation/doca_resolution"), - 1: this.getConstantsManager().getConstants(newRun, "/calibration/dc/time_to_distance/t2d") - */ - if (!event.hasBank("TimeBasedTrkg::TBHits") || !event.hasBank("RECHB::Event")) { - //System.err.println("there is no HB dc bank "); - _TBHits = new ArrayList<>(); return; } + DataBank bank = event.getBank("nn::dchits"); + DataBank bankDGTZ = event.getBank("DC::tdc"); - DataBank bank = event.getBank("TimeBasedTrkg::TBHits"); - int rows = bank.rows(); - - int[] id = new int[rows]; - int[] sector = new int[rows]; - int[] slayer = new int[rows]; - int[] layer = new int[rows]; - int[] wire = new int[rows]; - int[] tdc = new int[rows]; - int[] LR = new int[rows]; - double[] B = new double[rows]; - int[] clusterID = new int[rows]; - int[] trkID = new int[rows]; - double[] tProp = new double[rows]; - double[] tFlight = new double[rows]; - double startTime = (double) event.getBank("REC::Event").getFloat("startTime", 0); - - if (startTime < 0) - return; + int rows = bankDGTZ.rows(); + int[] sector = new int[rows]; + int[] layer = new int[rows]; + int[] wire = new int[rows]; + int[] tdc = new int[rows]; for (int i = 0; i < rows; i++) { - sector[i] = bank.getByte("sector", i); - slayer[i] = bank.getByte("superlayer", i); - layer[i] = bank.getByte("layer", i); - wire[i] = bank.getShort("wire", i); - tdc[i] = bank.getInt("TDC", i); - id[i] = bank.getShort("id", i); - LR[i] = bank.getByte("LR", i); - B[i] = bank.getFloat("B", i); - clusterID[i] = bank.getShort("clusterID", i); - trkID[i] = bank.getByte("trkID", i); - tProp[i] = bank.getFloat("TProp", i); - tFlight[i] = bank.getFloat("TFlight", i); + sector[i] = bankDGTZ.getByte("sector", i); + layer[i] = bankDGTZ.getByte("layer", i); + wire[i] = bankDGTZ.getShort("component", i); + tdc[i] = bankDGTZ.getInt("TDC", i); - if (event.hasBank("MC::Particle") || - event.getBank("RUN::config").getInt("run", 0) < 100) { - tProp[i] = 0; - tFlight[i] = 0; - } } - int size = layer.length; - List hits = new ArrayList<>(); - for (int i = 0; i < size; i++) { - //use only hits that have been fit to a track - if (trkID[i] == -1) { - continue; + int[] layerNum = new int[rows]; + int[] superlayerNum = new int[rows]; + double[] smearedTime = new double[rows]; + + List hits = new ArrayList<>(); + + for (int i = 0; i < rows; i++) { + + smearedTime[i] = (double) tdc[i] - triggerPhase; + if (smearedTime[i] < 0) { + smearedTime[i] = 1; } - // - FittedHit hit = new FittedHit(sector[i], slayer[i], layer[i], wire[i], tdc[i], id[i]); - hit.setB(B[i]); - //hit.setT0SubTime(time[i]- T_0+tProp[i]+tFlight[i]); - double T_0 = this.get_T0(sector[i], slayer[i], layer[i], wire[i], T0, T0ERR)[0]; - hit.setT0(T_0); - hit.set_Beta(this.readBeta(event, trkID[i])); - hit.setTStart(startTime); - hit.setTProp(tProp[i]); - //reset the time based on new beta - //double newtFlight = tFlight[i] / hit.get_Beta(); - //hit.setTFlight(newtFlight); - hit.setSignalTimeOfFlight(); - double newtFlight = hit.getTFlight(); - hit.set_Time((double) tdc[i] - tProp[i] - newtFlight - T_0 - startTime); - hit.set_LeftRightAmb(LR[i]); - hit.set_TrkgStatus(0); + - hit.set_DocaErr(hit.get_PosErr(event, B[i], constants0, constants1, tde)); - hit.set_AssociatedClusterID(clusterID[i]); - hit.set_AssociatedTBTrackID(trkID[i]); + superlayerNum[i] = (layer[i] - 1) / 6 + 1; + layerNum[i] = layer[i] - (superlayerNum[i] - 1) * 6; + + } + + for (int j = 0; j < bank.rows(); j++) { + int i = bank.getInt("index", j)-1; + int tid = (int)bank.getByte("id", j); + Hit hit = new Hit(sector[i], superlayerNum[i], layerNum[i], wire[i], tdc[i], (i + 1)); + hit.set_Id(i+1); + hit.calc_CellSize(DcDetector); + double posError = hit.get_CellSize() / Math.sqrt(12.); + hit.set_DocaErr(posError); + hit.NNTrkId = tid; + hits.add(hit); + } - hit.set_TimeToDistance(event, 1.0, B[i], constants1, tde); + this.set_DCHits(hits); + } - hit.set_QualityFac(0); - if (hit.get_Doca() > hit.get_CellSize()) { - hit.set_OutOfTimeFlag(true); - hit.set_QualityFac(2); - } - if (hit.get_Time() < 0) - hit.set_QualityFac(1); - if(hit.get_Beta()>0.2 && hit.get_Beta()<=1.30) { - //if(hit.get_Beta()>1.0) - // hit.set_Beta(1.0); - hits.add(hit); + //betaFlag:0 = OK; -1 = negative; 1 = less than lower cut (0.15); 2 = greater than 1.15 (from HBEB beta vs p plots for data) + private void set_BetaFlag(DataEvent event, int trkId, FittedHit hit, double beta) { + if(beta<0.15) { + if(beta<0) { + hit.betaFlag = -1; + this.set_ToPionHypothesis(event, trkId, hit); + } else { + hit.betaFlag = 1; } + } + if(beta>1.15) { + hit.betaFlag = 2; } - - this.set_TBHits(hits); } + private void set_ToPionHypothesis(DataEvent event, int trkId, FittedHit hit) { + double piMass = 0.13957018; + + double px=0; + double py=0; + double pz=0; + if (!event.hasBank("RECHB::Particle") || !event.hasBank("RECHB::Track")) + return ; + DataBank bank = event.getBank("RECHB::Track"); + int rows = bank.rows(); + for (int i = 0; i < rows; i++) { + if (bank.getByte("detector", i) == 6 && + bank.getShort("index", i) == trkId - 1) { + px = event.getBank("RECHB::Particle").getFloat("px", + bank.getShort("pindex", i)); + py = event.getBank("RECHB::Particle").getFloat("py", + bank.getShort("pindex", i)); + pz = event.getBank("RECHB::Particle").getFloat("pz", + bank.getShort("pindex", i)); + } + } + + double p = Math.sqrt(px*px+py*py+pz*pz); + if(p == 0) { + System.err.println("DC Track not matched in EB"); + return; + } + + double beta = p/Math.sqrt(p*p + piMass*piMass); + hit.set_Beta(beta); + } + private double readBeta(DataEvent event, int trkId) { double _beta = 1.0; diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/banks/RecoBankWriter.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/banks/RecoBankWriter.java index 4d2779024b..9c52062249 100755 --- a/reconstruction/dc/src/main/java/org/jlab/rec/dc/banks/RecoBankWriter.java +++ b/reconstruction/dc/src/main/java/org/jlab/rec/dc/banks/RecoBankWriter.java @@ -2,7 +2,6 @@ import java.util.ArrayList; import java.util.List; -import org.jlab.jnp.hipo.data.HipoEvent; import org.jlab.io.base.DataBank; import org.jlab.io.base.DataEvent; @@ -708,17 +707,16 @@ private DataBank fillTBCrossesBank(DataEvent event, List crosslist) { * @return segments bank */ private DataBank fillTBTracksBank(DataEvent event, List candlist) { - if(event.hasBank("TimeBasedTrkg::TBTracks")) { // for second pass tracking - HipoDataEvent de = (HipoDataEvent) event; + // if(event.hasBank("TimeBasedTrkg::TBTracks")) { // for second pass tracking + // HipoDataEvent de = (HipoDataEvent) event; //HipoEvent dde = de.getHipoEvent(); // HipoGroup group = dde.getGroup("TimeBasedTrkg::TBTracks"); ////event.show(); //group.show(); //dde.removeGroup("TimeBasedTrkg::TBTracks"); - } + // } DataBank bank = event.createBank("TimeBasedTrkg::TBTracks", candlist.size()); - - for (int i = 0; i < candlist.size(); i++) { + for (int i = 0; i < candlist.size(); i++) { bank.setShort("id", i, (short) candlist.get(i).get_Id()); bank.setShort("status", i, (short) (100+candlist.get(i).get_Status()*10+candlist.get(i).get_MissingSuperlayer())); bank.setByte("sector", i, (byte) candlist.get(i).get_Sector()); @@ -799,7 +797,7 @@ private DataBank fillTrajectoryBank(DataEvent event, List tracks) { continue; // save the last layer in a superlayer bank.setShort("id", i1, (short) track.get_Id()); - bank.setShort("detector", i1, (short) track.trajectory.get(j).getDetId()); + bank.setByte("detector", i1, (byte) track.trajectory.get(j).getDetId()); bank.setByte("layer", i1, (byte) track.trajectory.get(j).getLayerId()); bank.setFloat("x", i1, (float) track.trajectory.get(j).getX()); bank.setFloat("y", i1, (float) track.trajectory.get(j).getY()); diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/cluster/ClusterCleanerUtilities.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/cluster/ClusterCleanerUtilities.java index 2abe822e4d..9a36f76218 100644 --- a/reconstruction/dc/src/main/java/org/jlab/rec/dc/cluster/ClusterCleanerUtilities.java +++ b/reconstruction/dc/src/main/java/org/jlab/rec/dc/cluster/ClusterCleanerUtilities.java @@ -376,11 +376,17 @@ public FittedCluster LRAmbiguityResolver(DataEvent event, FittedCluster fClus, newhitPos.set_DeltaTimeBeta(hit.get_DeltaTimeBeta()); newhitPos.setTStart(hit.getTStart()); newhitPos.setTProp(hit.getTProp()); + newhitPos.betaFlag= hit.betaFlag; newhitPos.setTFlight(hit.getTFlight()); newhitPos.set_Time(hit.get_Time()); newhitPos.set_Id(hit.get_Id()); newhitPos.set_TrkgStatus(0); newhitPos.calc_CellSize(DcDetector); + newhitPos.set_XWire(hit.get_XWire()); + newhitPos.set_Z(hit.get_Z()); + newhitPos.set_WireLength(hit.get_WireLength()); + newhitPos.set_WireMaxSag(hit.get_WireMaxSag()); + newhitPos.set_WireLine(hit.get_WireLine()); newhitPos.set_LeftRightAmb(1); newhitPos.updateHitPositionWithTime(event, 1, hit.getB(), tab, DcDetector, tde); // assume the track angle is // to the layer, so that cosTrkAng =1 @@ -397,11 +403,17 @@ public FittedCluster LRAmbiguityResolver(DataEvent event, FittedCluster fClus, newhitNeg.set_DeltaTimeBeta(hit.get_DeltaTimeBeta()); newhitNeg.setTStart(hit.getTStart()); newhitNeg.setTProp(hit.getTProp()); + newhitNeg.betaFlag= hit.betaFlag; newhitNeg.setTFlight(hit.getTFlight()); newhitNeg.set_Time(hit.get_Time()); newhitNeg.set_Id(hit.get_Id()); newhitNeg.set_TrkgStatus(0); newhitNeg.calc_CellSize(DcDetector); + newhitNeg.set_XWire(hit.get_XWire()); + newhitNeg.set_Z(hit.get_Z()); + newhitNeg.set_WireLength(hit.get_WireLength()); + newhitNeg.set_WireMaxSag(hit.get_WireMaxSag()); + newhitNeg.set_WireLine(hit.get_WireLine()); newhitNeg.set_LeftRightAmb(-1); newhitNeg.updateHitPositionWithTime(event, 1, hit.getB(), tab, DcDetector, tde); // assume the track angle is // to the layer @@ -603,28 +615,36 @@ public FittedCluster SecondariesRemover(DataEvent event, FittedCluster clus, Clu for (int j = 0; j < hitsInLayer.size(); j++) { docaSum += hitsInLayer.get(j).get_Doca(); } - //double passingCut = 1.75 * hitsInLayer.get(0).get_CellSize() * Math.cos(Math.toRadians(6.)); - double passingCut = 1.5 * hitsInLayer.get(0).get_CellSize() ; - //if (docaSum < passingCut) { // reset LR to 0 - //use doca ratio instead of sum - double hit1doca = 0; - double hit2doca = 0; - if(hitsInLayer.get(0).get_Doca()>hitsInLayer.get(1).get_Doca()) { - hit1doca = hitsInLayer.get(0).get_Doca(); - hit2doca = hitsInLayer.get(1).get_Doca(); + if(hitsInLayer.get(0).get_Doca()>0.5*hitsInLayer.get(0).get_CellSize() && + hitsInLayer.get(1).get_Doca()>0.5*hitsInLayer.get(1).get_CellSize() + && docaSum>Constants.DOCASUMMAXFAC * hitsInLayer.get(0).get_CellSize()) {// both greater than 50% cell size + baseClusterHits.addAll(hitsInLayer); // safe all good hits to base cluster + hitsInLayer.get(0).updateHitPositionWithTime(event, 1, hitsInLayer.get(0).getB(), tab, DcDetector, tde); + hitsInLayer.get(1).updateHitPositionWithTime(event, 1, hitsInLayer.get(1).getB(), tab, DcDetector, tde); } else { - hit1doca = hitsInLayer.get(1).get_Doca(); - hit2doca = hitsInLayer.get(0).get_Doca(); - } - double passingCut2 = 0.75; - if (hit2doca/hit1doca < passingCut2 || (hit2doca/hit1doca > passingCut2 && docaSum < passingCut)) { // reset LR to 0 - for (int j = 0; j < hitsInLayer.size(); j++) { - hitsInLayer.get(j).set_LeftRightAmb(0); - hitsInLayer.get(j).updateHitPositionWithTime(event, 1, hitsInLayer.get(j).getB(), tab, DcDetector, tde); + //double passingCut = 1.75 * hitsInLayer.get(0).get_CellSize() * Math.cos(Math.toRadians(6.)); + double passingCut = 1.5 * hitsInLayer.get(0).get_CellSize() ; + //if (docaSum < passingCut) { // reset LR to 0 + //use doca ratio instead of sum + double hit1doca = 0; + double hit2doca = 0; + if(hitsInLayer.get(0).get_Doca()>hitsInLayer.get(1).get_Doca()) { + hit1doca = hitsInLayer.get(0).get_Doca(); + hit2doca = hitsInLayer.get(1).get_Doca(); + } else { + hit1doca = hitsInLayer.get(1).get_Doca(); + hit2doca = hitsInLayer.get(0).get_Doca(); + } + double passingCut2 = 0.75; + if (hit2doca/hit1doca < passingCut2 || (hit2doca/hit1doca > passingCut2 && docaSum < passingCut)) { // reset LR to 0 + for (int j = 0; j < hitsInLayer.size(); j++) { + hitsInLayer.get(j).set_LeftRightAmb(0); + hitsInLayer.get(j).updateHitPositionWithTime(event, 1, hitsInLayer.get(j).getB(), tab, DcDetector, tde); + } + hitsInSameLayerLists.add(hitsInLayer); + } else { + baseClusterHits.addAll(hitsInLayer); // safe all good hits to base cluster } - hitsInSameLayerLists.add(hitsInLayer); - } else { - baseClusterHits.addAll(hitsInLayer); // safe all good hits to base cluster } } } @@ -732,7 +752,7 @@ public FittedCluster OverlappingClusterResolver(FittedCluster thisclus, List HitListPruner(List hits) { - //Collections.sort(hits); + Collections.sort(hits); for(int l = 0; l < 6; l++) { sortedHits.get(l).clear(); @@ -760,8 +780,8 @@ public List HitListPruner(List hits) { kHits.add(sortedHits.get(l).get(sortedHits.get(l).size()-2)); rmHits.removeAll(kHits); sortedHits.get(l).removeAll(rmHits); - } - if(sortedHits.get(l).size()==10) + } + if(sortedHits.get(l).size()>=10) sortedHits.get(l).removeAll(sortedHits.get(l)); } @@ -853,4 +873,105 @@ public void outOfTimersRemover(FittedCluster fClus, boolean removeHit) { } } + public FittedCluster ClusterCleaner(FittedCluster clus, ClusterFitter cf, DCGeant4Factory DcDetector) { + //System.out.println(" cleaner :"+clus.printInfo()); + Collections.sort(clus); + + ArrayList> sortedHits = new ArrayList>(6); + //initialize + for (int i = 0; i < 6; i++) { + sortedHits.add(new ArrayList()); + } + + for (int i = 0; i < clus.size(); i++) { + FittedHit hit = clus.get(i); + sortedHits.get(hit.get_Layer() - 1).add(hit); + } + + ArrayList clusters = new ArrayList(); + + ArrayList> hitsInSameLayerLists = new ArrayList>(); + ArrayList> hitsInClusCandLists = new ArrayList>(); + ArrayList baseClusterHits = new ArrayList(); + + for (int i = 0; i < 6; i++) { + ArrayList hitsInLayer = sortedHits.get(i); + //for(int j =0; jhitsInLayer.get(1).get_Residual()) { + hit1doca = hitsInLayer.get(0).get_Residual(); + hit2doca = hitsInLayer.get(1).get_Residual(); + } else { + hit1doca = hitsInLayer.get(1).get_Residual(); + hit2doca = hitsInLayer.get(0).get_Residual(); + } + + if (hit1doca+hit2doca>passingCut) { + + hitsInSameLayerLists.add(hitsInLayer); + } else { + baseClusterHits.addAll(hitsInLayer); // save all good hits to base cluster + } + } + } + + int nbLyr = hitsInSameLayerLists.size(); + if (nbLyr == 0) { + return clus; + } + + if (nbLyr > 0) { + + for (int clusIdx = 0; clusIdx < Constants.CombArray.get(nbLyr - 1).length; clusIdx++) { + ArrayList hitsInClusterCand = new ArrayList(); + hitsInClusterCand.addAll(baseClusterHits); + + for (int k = 0; k < Constants.CombArray.get(nbLyr - 1)[clusIdx].length; k++) { + hitsInClusterCand.add(hitsInSameLayerLists.get(k).get(Constants.CombArray.get(nbLyr - 1)[clusIdx][k])); + } + hitsInClusCandLists.add(hitsInClusterCand); + } + } + for (int i = 0; i < hitsInClusCandLists.size(); i++) { + FittedCluster newClus = new FittedCluster(clus.getBaseCluster()); + for (int i1 = 0; i1 < newClus.size(); i1++) { + newClus.remove(i1); + } + newClus.addAll(hitsInClusCandLists.get(i)); + clusters.add(newClus); + } + + // get the best cluster + //System.out.println(" clusters for selection "); + //for(FittedCluster c : clusters) { + // System.out.println(c.printInfo()); + // for(FittedHit h : c) + // System.out.println(h.printInfo()); + //} + FittedCluster BestCluster = cf.BestClusterSelector(clusters, "LC"); + //System.out.println(" ---> selected cluster : "); + //for(FittedHit h : BestCluster) + // System.out.println(h.printInfo()); + return BestCluster; + } + } diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/cluster/ClusterFinder.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/cluster/ClusterFinder.java index 44ab676ceb..b5d0c4d001 100644 --- a/reconstruction/dc/src/main/java/org/jlab/rec/dc/cluster/ClusterFinder.java +++ b/reconstruction/dc/src/main/java/org/jlab/rec/dc/cluster/ClusterFinder.java @@ -2,7 +2,10 @@ import java.util.ArrayList; import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; import java.util.List; +import java.util.Map; import org.jlab.detector.geant4.v2.DCGeant4Factory; import org.jlab.io.base.DataEvent; @@ -72,7 +75,7 @@ public void setHitArray(Hit[][][] hitArray) { * * @param hits the unfitted hit */ - private void fillHitArray(List hits, int rejectLayer) { + public void fillHitArray(List hits, int rejectLayer) { // a Hit Array is used to identify clusters Hit[][][] hitArray = new Hit[nsect * nslay][nwire][nlayr]; @@ -203,7 +206,7 @@ public List FindHitBasedClusters(List allhits, ClusterCleane continue; selectedClusList.add(fClus); } - + //System.out.println(" Clusters Step 2"); // for(FittedCluster c : selectedClusList) // for(FittedHit h : c) @@ -216,33 +219,48 @@ public List FindHitBasedClusters(List allhits, ClusterCleane cf.SetFitArray(clus, "LC"); cf.Fit(clus, true); - - if (clus.get_fitProb() > Constants.HITBASEDTRKGMINFITHI2PROB || clus.size() < Constants.HITBASEDTRKGNONSPLITTABLECLSSIZE) { + if(clus.get_fitProb() Constants.HITBASEDTRKGMINFITHI2PROB ){ + // || + // (clus.size() < Constants.HITBASEDTRKGNONSPLITTABLECLSSIZE && clus.get_fitProb()!=0) ){ fittedClusList.add(clus); //if the chi2 prob is good enough, then just add the cluster, or if the cluster is not split-able because it has too few hits - } else { + } else { + List splitClus = ct.ClusterSplitter(clus, selectedClusList.size(), cf); fittedClusList.addAll(splitClus); } } - + + ArrayList rmHits = new ArrayList(); for (FittedCluster clus : fittedClusList) { - if (clus != null && clus.size() > 3 ) { - + if (clus != null && clus.size() > 3 && clus.get_fitProb()>Constants.HITBASEDTRKGMINFITHI2PROB) { + // update the hits for (FittedHit fhit : clus) { fhit.set_TrkgStatus(0); fhit.updateHitPosition(DcDetector); - fhit.set_AssociatedClusterID(clus.get_Id()); + //fhit.set_AssociatedClusterID(clus.get_Id()); } + cf.SetFitArray(clus, "TSC"); cf.Fit(clus, true); cf.SetResidualDerivedParams(clus, false, false, DcDetector); //calcTimeResidual=false, resetLRAmbig=false, local= false - + + clus = ct.ClusterCleaner(clus, cf, DcDetector); + // update the hits + for (FittedHit fhit : clus) { + fhit.set_AssociatedClusterID(clus.get_Id()); + } cf.SetFitArray(clus, "TSC"); cf.Fit(clus, false); cf.SetSegmentLineParameters(clus.get(0).get_Z(), clus); - - if (clus != null) { + + if (clus != null ) { refittedClusList.add(clus); } @@ -258,48 +276,46 @@ public List FindHitBasedClusters(List allhits, ClusterCleane } + private List RecomposeClusters(DataEvent event, List fhits, IndexedTable tab, DCGeant4Factory DcDetector, TimeToDistanceEstimator tde) { - + Map> grpHits = new HashMap>(); List clusters = new ArrayList(); - int NbClus = -1; + for (FittedHit hit : fhits) { - if (hit.get_AssociatedClusterID() == -1) { - continue; - } - if (hit.get_AssociatedClusterID() > NbClus) { - NbClus = hit.get_AssociatedClusterID(); - } - } - - FittedHit[][] HitArray = new FittedHit[fhits.size()][NbClus + 1]; - - int index = 0; - for (FittedHit hit : fhits) { - if (hit.get_AssociatedClusterID() == -1) { + if (hit.get_AssociatedClusterID() == -1 || hit.get_AssociatedHBTrackID() == -1) { continue; } - HitArray[index][hit.get_AssociatedClusterID()] = hit; - hit.updateHitPosition(DcDetector); - - index++; - } - - for (int c = 0; c < NbClus + 1; c++) { - List hitlist = new ArrayList(); - for (int i = 0; i < index; i++) { - if (HitArray[i][c] != null) { - hitlist.add(HitArray[i][c]); + if (hit.get_AssociatedClusterID() != -1 && + hit.get_AssociatedHBTrackID() != -1) { + int index = hit.get_AssociatedHBTrackID()*10000+hit.get_AssociatedClusterID(); + if(grpHits.get(index)==null) { // if the list not yet created make it + grpHits.put(index, new ArrayList()); + grpHits.get(index).add(hit); // append hit + } else { + grpHits.get(index).add(hit); // append hit } } - if (hitlist.size() > 0) { - - Cluster cluster = new Cluster(hitlist.get(0).get_Sector(), hitlist.get(0).get_Superlayer(), c); + } + + // using iterators + Iterator>> itr = grpHits.entrySet().iterator(); + + while(itr.hasNext()) { + Map.Entry> entry = itr.next(); + + if(entry.getValue().size()>3) { + Cluster cluster = new Cluster(entry.getValue().get(0).get_Sector(), + entry.getValue().get(0).get_Superlayer(), entry.getValue().get(0).get_AssociatedClusterID()); FittedCluster fcluster = new FittedCluster(cluster); - fcluster.addAll(hitlist); + for (FittedHit hit : entry.getValue()) { + hit.updateHitPosition(DcDetector); + } + fcluster.addAll(entry.getValue()); clusters.add(fcluster); } } + for (FittedCluster clus : clusters) { if (clus != null) { @@ -379,12 +395,18 @@ public List FindTimeBasedClusters(DataEvent event, newhit.set_DeltaTimeBeta(hit.get_DeltaTimeBeta()); newhit.setTStart(hit.getTStart()); newhit.setTProp(hit.getTProp()); + newhit.betaFlag= hit.betaFlag; newhit.setTFlight(hit.getTFlight()); newhit.set_Time(hit.get_Time()); newhit.set_Id(hit.get_Id()); newhit.set_TrkgStatus(hit.get_TrkgStatus()); newhit.set_LeftRightAmb(-hit.get_LeftRightAmb()); newhit.calc_CellSize(DcDetector); + newhit.set_XWire(hit.get_XWire()); + newhit.set_Z(hit.get_Z()); + newhit.set_WireLength(hit.get_WireLength()); + newhit.set_WireMaxSag(hit.get_WireMaxSag()); + newhit.set_WireLine(hit.get_WireLine()); newhit.updateHitPositionWithTime(event, 1, hit.getB(), tab, DcDetector, tde); // assume the track angle is // to the layer newhit.set_AssociatedClusterID(hit.get_AssociatedClusterID()); newhit.set_AssociatedHBTrackID(hit.get_AssociatedHBTrackID()); @@ -407,27 +429,24 @@ public List FindTimeBasedClusters(DataEvent event, cf.SetFitArray(clus, "TSC"); cf.Fit(clus, true); - double cosTrkAngle = 1. / Math.sqrt(1. + clus.get_clusterLineFitSlope() * clus.get_clusterLineFitSlope()); - // update the hits for (FittedHit fhit : clus) { - fhit.updateHitPositionWithTime(event, cosTrkAngle, fhit.getB(), tab, DcDetector, tde); + fhit.updateHitPositionWithTime(event, clus.get_clusterLineFitSlope(), fhit.getB(), tab, DcDetector, tde); } // iterate till convergence of trkAngle double Chi2Diff = 1; double prevChi2 = 999999999; - double cosTrkAngleFinal = 0; + double trkAngleFinal = 0; while (Chi2Diff > 0) { cf.SetFitArray(clus, "TSC"); cf.Fit(clus, true); Chi2Diff = prevChi2 - clus.get_Chisq(); if (Chi2Diff > 0) { - cosTrkAngle = 1. / Math.sqrt(1. + clus.get_clusterLineFitSlope() * clus.get_clusterLineFitSlope()); // update the hits for (FittedHit fhit : clus) { - fhit.updateHitPositionWithTime(event, cosTrkAngle, fhit.getB(), tab, DcDetector, tde); + fhit.updateHitPositionWithTime(event, clus.get_clusterLineFitSlope(), fhit.getB(), tab, DcDetector, tde); } - cosTrkAngleFinal = cosTrkAngle; + trkAngleFinal = clus.get_clusterLineFitSlope(); } prevChi2 = clus.get_Chisq(); } @@ -436,7 +455,7 @@ public List FindTimeBasedClusters(DataEvent event, cf.SetResidualDerivedParams(clus, false, false, DcDetector); //calcTimeResidual=false, resetLRAmbig=false for (FittedHit fhit : clus) { - fhit.updateHitPositionWithTime(event, cosTrkAngleFinal, fhit.getB(), tab, DcDetector, tde); + fhit.updateHitPositionWithTime(event, trkAngleFinal, fhit.getB(), tab, DcDetector, tde); } cf.SetFitArray(clus, "TSC"); cf.Fit(clus, true); diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/cluster/FittedCluster.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/cluster/FittedCluster.java index 6d43c5f2e2..e5c9d9fead 100644 --- a/reconstruction/dc/src/main/java/org/jlab/rec/dc/cluster/FittedCluster.java +++ b/reconstruction/dc/src/main/java/org/jlab/rec/dc/cluster/FittedCluster.java @@ -35,6 +35,7 @@ public FittedCluster(Cluster rawCluster) { fhit.set_DocaErr(rawCluster.get(i).get_DocaErr()); fhit.set_CellSize(rawCluster.get(i).get_CellSize()); fhit.set_Id(rawCluster.get(i).get_Id()); + this.add(fhit); } } diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/cross/CrossListFinder.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/cross/CrossListFinder.java index 049c24a800..8aeb6d2f18 100644 --- a/reconstruction/dc/src/main/java/org/jlab/rec/dc/cross/CrossListFinder.java +++ b/reconstruction/dc/src/main/java/org/jlab/rec/dc/cross/CrossListFinder.java @@ -108,6 +108,14 @@ public CrossList candCrossLists(DataEvent event, double cosTh2 = traj2.dot(c2.get_Dir().toVector3D()); double cosTh3 = traj3.dot(c3.get_Dir().toVector3D()); + // require a line containing crosses in R1 and R2 to intersect the lab z coordinate line in the lab + // downstream of the position of the first cross + //Point3D labR1 = c1.getCoordsInLab(X[0], Y[0], Z[0]); + //Point3D labR2 = c1.getCoordsInLab(X[1], Y[1], Z[1]); + //double s = (labR2.x()-labR1.x())/(labR2.z()-labR1.z()); + //if(labR2.x()/s<0) { + // continue; + //} // require that the cross direction estimate be in the direction of the trajectory if(cosTh1 { private int _AssociatedHBTrackID = -1; private int _AssociatedTBTrackID = -1; + public int betaFlag = 0; //0 = OK; -1 = negative; 1 = less than lower cut (0.15); 2 = greater than 1.15 // intersection of cross direction line with the hit wire (TCS) private Point3D CrossDirIntersWire; @@ -177,7 +179,7 @@ public double get_PosErr(DataEvent event, double B, IndexedTable constants0, Ind if (this._TrkgStatus != -1) { if (this.get_TimeToDistance() == 0) // if the time-to-dist is not set ... set it { - set_TimeToDistance(event, 1.0, B, constants1, tde); + set_TimeToDistance(event, 0.0, B, constants1, tde); } double x = this.get_Doca() / this.get_CellSize(); @@ -344,34 +346,46 @@ public void setAssociatedStateVec(StateVec _AssociatedStateVec) { /** * sets the calculated distance (in cm) from the time (in ns) */ - public void set_TimeToDistance(DataEvent event, double cosTrkAngle, double B, IndexedTable tab,TimeToDistanceEstimator tde) { + public void set_TimeToDistance(DataEvent event, double trkAngle, double B, IndexedTable tab,TimeToDistanceEstimator tde) { double distance = 0; int slIdx = this.get_Superlayer() - 1; int secIdx = this.get_Sector() - 1; if (_TrkgStatus != -1 && this.get_Time() > 0) { - + //local angle correction double theta0 = Math.acos(1-0.02*B); - double alpha = Math.acos(cosTrkAngle); + double alpha = Math.atan(trkAngle); + // correct alpha with theta0, the angle corresponding to the isochrone lines twist due to the electric field if(event.hasBank("MC::Particle")==false) alpha-=Swimmer.getTorScale()*theta0; - //reduce the corrected angle + this.setAlpha(Math.toDegrees(alpha)); + //reduce the corrected angle double ralpha = this.reducedAngle(alpha); double beta = this.get_Beta0to1(); double x = this.get_ClusFitDoca(); double deltatime_beta = 0; + double deltatime_beta2 = 0; if (x != -1) { - deltatime_beta = calcDeltaTimeBeta(x, tab, beta); + if(Constants.useUSETIMETBETA()==true) { + deltatime_beta = calcDeltaTimeBetaTFCN(this.get_Time(), tab, beta); + deltatime_beta2 = calcDeltaTimeBeta(this.get_Time(), tab, beta); + } else { + deltatime_beta = calcDeltaTimeBeta(x, tab, beta); + } } if(event.hasBank("MC::Particle")==false) { - distance = tde.interpolateOnGrid(B, Math.toDegrees(ralpha), this.getCorrectedTime(this.get_Time(), deltatime_beta), secIdx, slIdx) ; + distance = tde.interpolateOnGrid(B, Math.toDegrees(ralpha), + this.getCorrectedTime(this.get_Time(), deltatime_beta+deltatime_beta2), + secIdx, slIdx) ; } else { - distance = tde.interpolateOnGrid(B, Math.toDegrees(ralpha), this.getCorrectedTime(this.get_Time(), 0), secIdx, slIdx) ; + distance = tde.interpolateOnGrid(B, Math.toDegrees(ralpha), + this.getCorrectedTime(this.get_Time(), 0), + secIdx, slIdx) ; } //deltatime_beta = calcDeltaTimeBeta(distance, tab, beta); //deltatime_beta = calcDeltaTimeBeta(distance, this.get_Superlayer(), beta); @@ -389,6 +403,7 @@ public double getCorrectedTime(double t, double dbt) { correctedTime=0.01; // fixes edge effects ... to be improved return correctedTime; } + public double calcDeltaTimeBeta(double x, IndexedTable tab, double beta){ return (Math.sqrt(x * x + (tab.getDoubleValue("distbeta", this.get_Sector(), this.get_Superlayer(),0) * beta * beta) * @@ -396,10 +411,15 @@ public double calcDeltaTimeBeta(double x, IndexedTable tab, double beta){ this.get_Superlayer(),0) * beta * beta)) - x) / Constants.V0AVERAGED; } - //public double calcDeltaTimeBeta(double x, int superlayer, double beta) { - // double distbeta = TableLoader.distbetaValues[superlayer-1]; - // return (Math.sqrt(x * x + (distbeta * beta * beta) * (distbeta* beta * beta)) - x) / Constants.V0AVERAGED; - //} + public double calcDeltaTimeBetaTFCN(double t,IndexedTable tab, double beta){ + double delt = tab.getDoubleValue("c3", this.get_Sector(), + this.get_Superlayer(),0); + + //see [CLAS-Note 96-008] + double tBeta = (0.5 *delt*delt*delt*t)/(delt*delt*delt+t*t*t); + return tBeta*beta*beta; + } + /** * @@ -457,11 +477,11 @@ public void set_X(double _X) { this._X = _X; } - public double get_XMP() { + public double get_XWire() { return _XMP; } - public void set_XMP(double _XMP) { + public void set_XWire(double _XMP) { this._XMP = _XMP; } @@ -489,42 +509,46 @@ public void set_Z(double _Z) { * local coord.sys. wire positions */ public void updateHitPosition(DCGeant4Factory DcDetector) { - - //double z = GeometryLoader.dcDetector.getSector(0).getSuperlayer(this.get_Superlayer()-1).getLayer(this.get_Layer()-1).getComponent(this.get_Wire()-1).getMidpoint().z(); - double z = DcDetector.getWireMidpoint(this.get_Sector() - 1, this.get_Superlayer() - 1, this.get_Layer() - 1, this.get_Wire() - 1).z; - double x= this.calc_GeomCorr(DcDetector, 0); - // - this.set_X(x); - this.set_Z(z); + if(this.get_Z()==0) + this.calc_GeomCorr(DcDetector, 0); + this.set_X(this.get_XWire()); } /** * A method to update the hit position information after the fit to the wire * positions employing hit-based tracking algorithms has been performed. */ - public void updateHitPositionWithTime(DataEvent event, double cosTrkAngle, double B, IndexedTable tab, DCGeant4Factory DcDetector, TimeToDistanceEstimator tde) { + public void updateHitPositionWithTime(DataEvent event, double trkAngle, double B, + IndexedTable tab, DCGeant4Factory DcDetector, TimeToDistanceEstimator tde) { if (this.get_Time() > 0) { - this.set_TimeToDistance(event, cosTrkAngle, B, tab, tde); + this.set_TimeToDistance(event, trkAngle, B, tab, tde); } - - double z = DcDetector.getWireMidpoint(this.get_Sector() - 1, this.get_Superlayer() - 1, this.get_Layer() - 1, this.get_Wire() - 1).z; - //double x = DcDetector.getWireMidpoint(this.get_Superlayer() - 1, this.get_Layer() - 1, this.get_Wire() - 1).x; - double x = this.calc_GeomCorr(DcDetector, 0); + if(this.get_Z()==0) + this.calc_GeomCorr(DcDetector, 0); + double x = this.get_XWire(); //this.set_X(x+this.get_LeftRightAmb()*this.get_TimeToDistance()); double MPCorr = 1; - if (cosTrkAngle > 0.8 & cosTrkAngle <= 1) { - MPCorr = cosTrkAngle; + double cosTkAng = 1./Math.sqrt(trkAngle*trkAngle + 1.); + if (cosTkAng > 0.8 & cosTkAng <= 1) { + MPCorr = cosTkAng; } - this.set_X(x + this.get_LeftRightAmb() * (this.get_TimeToDistance() / MPCorr) / FastMath.cos(Math.toRadians(6.))); - this.set_Z(z); - + this.set_X(x + this.get_LeftRightAmb() * (this.get_TimeToDistance() / MPCorr) );/// FastMath.cos(Math.toRadians(6.))); + } - - public double XatY(DCGeant4Factory DcDetector, double y) { - double x = this.calc_GeomCorr(DcDetector, y); - return x + this.get_LeftRightAmb() * (this.get_TimeToDistance()) ; + public double corrForMidPlaneProjection(double trkAngle, Line3D wireLine, FittedHit hit) { + double tilt = 90-Math.toDegrees(wireLine.direction().asUnit().angle(new Vector3D(1,0,0))); + double MPCorr = 1; + double cosTkAng = 1./Math.sqrt(trkAngle*trkAngle + 1.); + if (cosTkAng > 0.8 & cosTkAng <= 1) { + MPCorr = cosTkAng; + } + return MPCorr ; } + //public double XatY(DCGeant4Factory DcDetector, double y) { + // double x = this.calc_GeomCorr(DcDetector, y); + // return x + this.get_LeftRightAmb() * (this.get_TimeToDistance()) ; + //} private double _WireLength; @@ -546,6 +570,16 @@ public void set_WireMaxSag(double _WireMaxSag) { this._WireMaxSag = _WireMaxSag; } + private Line3D _WireLine; + + public Line3D get_WireLine() { + return _WireLine; + } + + public void set_WireLine(Line3D _WireLine) { + this._WireLine = _WireLine; + } + private double _TrkResid=999; public double get_TrkResid() { @@ -556,24 +590,15 @@ public void set_TrkResid(double _TrkResid) { this._TrkResid = _TrkResid; } - private double calc_GeomCorr(DCGeant4Factory DcDetector, double y) { - + public void calc_GeomCorr(DCGeant4Factory DcDetector, double y) { + //corrects for wire sag only double xL = DcDetector.getWireLeftend(this.get_Sector()-1, this.get_Superlayer()-1, this.get_Layer()-1, this.get_Wire()-1).x; double xR = DcDetector.getWireRightend(this.get_Sector()-1, this.get_Superlayer()-1, this.get_Layer()-1, this.get_Wire()-1).x; double yL = DcDetector.getWireLeftend(this.get_Sector()-1, this.get_Superlayer()-1, this.get_Layer()-1, this.get_Wire()-1).y; double yR = DcDetector.getWireRightend(this.get_Sector()-1, this.get_Superlayer()-1, this.get_Layer()-1, this.get_Wire()-1).y; - - double DL = Constants.MAXENDPLTDEFLEC[this.get_Region()-1][this.get_Sector()-1][0]; - double DR = Constants.MAXENDPLTDEFLEC[this.get_Region()-1][this.get_Sector()-1][1]; - + double x = DcDetector.getWireMidpoint(this.get_Sector()-1, this.get_Superlayer()-1, this.get_Layer()-1, this.get_Wire()-1).x; + double z = DcDetector.getWireMidpoint(this.get_Sector()-1, this.get_Superlayer()-1, this.get_Layer()-1, this.get_Wire()-1).z; double wire = this.get_Wire(); - double normW = (double) wire/112.; - - xL-=Constants.getWIREDIST()*DL*(normW-3*normW*normW*normW+2*normW*normW*normW*normW); - xR-=Constants.getWIREDIST()*DR*(normW-3*normW*normW*normW+2*normW*normW*normW*normW); - - double x = xR -(yR-y)*((xR-xL)/(yR-yL)); - double wireLen = Math.sqrt((xL-xR)*(xL-xR)+(yL-yR)*(yL-yR)); int sector = this.get_Sector(); int A = 0; @@ -625,14 +650,17 @@ private double calc_GeomCorr(DCGeant4Factory DcDetector, double y) { double delta_x = MaxSag*(1.-Math.abs(y)/(0.5*wireLen))*(1.-Math.abs(y)/(0.5*wireLen)); - x+=delta_x; + //x+=delta_x; + //Line3D wireLine = new Line3D(new Point3D(xL, yL, z), new Point3D(xR, yR, z)); + //wireLine.setOrigin(x, y, z); + Line3D wireLine = new Line3D(new Point3D(x, 0, z), new Point3D(xR, yR, z)); this.set_WireLength(wireLen); this.set_WireMaxSag(MaxSag); + this.set_WireLine(wireLine); - return x; - //System.out.println(this.printInfo()+ "x0 "+ DcDetector.getWireMidpoint(this.get_Superlayer()-1, this.get_Layer()-1, this.get_Wire()-1).x - //+" x "+x); + this.set_XWire(x); + this.set_Z(z); } /** @@ -676,7 +704,7 @@ public String printInfo() { //double xr = this._X*FastMath.cos(Math.toRadians(25.))+this._Z*FastMath.sin(Math.toRadians(25.)); //double zr = this._Z*FastMath.cos(Math.toRadians(25.))-this._X*FastMath.sin(Math.toRadians(25.)); String s = "DC Fitted Hit: ID " + this.get_Id() + " Sector " + this.get_Sector() + " Superlayer " + this.get_Superlayer() + " Layer " + this.get_Layer() + " Wire " + this.get_Wire() + " TDC " + this.get_TDC()+ " Time " + this.get_Time() - + " LR " + this.get_LeftRightAmb() + " doca " + this.get_TimeToDistance()+ " +/- " +this.get_DocaErr() + " updated pos " + this._X + " clus " + + " LR " + this.get_LeftRightAmb() + " doca " + (float)this.get_TimeToDistance()+ " +/- " +(float)this.get_DocaErr() + " updated pos " + (float)this._X + " clus " + this._AssociatedClusterID; return s; } @@ -962,5 +990,34 @@ public double get_Beta0to1() { beta=1.0; return beta; } + + //make a copy + public FittedHit clone() throws CloneNotSupportedException { + FittedHit hitClone = new FittedHit(this.get_Sector(), this.get_Superlayer(), this.get_Layer(), this.get_Wire(), + this.get_TDC(), this.get_Id()); + hitClone.set_Doca(this.get_Doca()); + hitClone.set_DocaErr(this.get_DocaErr()); + hitClone.setT0(this.getT0()); + hitClone.set_Beta(this.get_Beta()); + hitClone.setB(this.getB()); + hitClone.set_DeltaTimeBeta(this.get_DeltaTimeBeta()); + hitClone.setTStart(this.getTStart()); + hitClone.setTProp(this.getTProp()); + hitClone.setTFlight(this.getTFlight()); + hitClone.set_Time(this.get_Time()); + hitClone.set_Id(this.get_Id()); + hitClone.set_ClusFitDoca(this.get_ClusFitDoca()); + hitClone.set_LeftRightAmb(this.get_LeftRightAmb()); + hitClone.set_X(this.get_X()); + hitClone.set_Z(this.get_Z()); + hitClone.setAlpha(this.getAlpha()); + hitClone.set_CellSize(this.get_CellSize()); + hitClone.set_AssociatedClusterID(this.get_AssociatedClusterID()); + hitClone.set_AssociatedHBTrackID(this.get_AssociatedHBTrackID()); + hitClone.betaFlag = this.betaFlag; + + return hitClone; + } + } diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/hit/Hit.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/hit/Hit.java index 5c6c6023ef..046ba3cac9 100644 --- a/reconstruction/dc/src/main/java/org/jlab/rec/dc/hit/Hit.java +++ b/reconstruction/dc/src/main/java/org/jlab/rec/dc/hit/Hit.java @@ -21,6 +21,7 @@ public class Hit implements Comparable { private double _cellSize; private double _DocaErr; // class implements Comparable interface to allow for sorting a collection of hits by wire number values + public int NNTrkId; // constructors /** diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/nn/PatternRec.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/nn/PatternRec.java new file mode 100644 index 0000000000..de9f28cf8a --- /dev/null +++ b/reconstruction/dc/src/main/java/org/jlab/rec/dc/nn/PatternRec.java @@ -0,0 +1,185 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.jlab.rec.dc.nn; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import org.jlab.detector.geant4.v2.DCGeant4Factory; +import org.jlab.rec.dc.cluster.Cluster; +import org.jlab.rec.dc.cluster.ClusterCleanerUtilities; +import org.jlab.rec.dc.cluster.ClusterFinder; +import org.jlab.rec.dc.cluster.ClusterFitter; +import org.jlab.rec.dc.cluster.FittedCluster; +import org.jlab.rec.dc.cross.Cross; +import org.jlab.rec.dc.cross.CrossList; +import org.jlab.rec.dc.cross.CrossMaker; +import org.jlab.rec.dc.hit.FittedHit; +import org.jlab.rec.dc.hit.Hit; +import org.jlab.rec.dc.segment.Segment; +import org.jlab.rec.dc.trajectory.Road; +import org.jlab.rec.dc.trajectory.RoadFinder; +/** + * + * @author ziegler + */ +public class PatternRec { + + private ClusterFinder clf = new ClusterFinder(); + private ClusterCleanerUtilities ct = new ClusterCleanerUtilities(); + private ClusterFitter cf = new ClusterFitter(); + private CrossMaker crf = new CrossMaker(); + private RoadFinder rf = new RoadFinder(); + + public CrossList RecomposeCrossList(List clusters, + DCGeant4Factory DcDetector) { + CrossList crossList = new CrossList(); + Map> grpCrs = new HashMap>(); + Map> grpCls = new HashMap>(); + + for(Segment cls : clusters) { + int index = cls.get(0).get_AssociatedHBTrackID(); + if(grpCls.get(index)==null) { // if the list not yet created make it + grpCls.put(index, new ArrayList()); + grpCls.get(index).add(cls); // append cluster + } else { + grpCls.get(index).add(cls); // append + } + } + // using iterators + Iterator>> itr = grpCls.entrySet().iterator(); + while(itr.hasNext()) { + Map.Entry> entry = itr.next(); + List crosses = crf.find_Crosses(entry.getValue(), DcDetector); + Collections.sort(crosses); + + if(crosses.size()<3) { // find pseudocross + List allRoads = rf.findRoads(entry.getValue(), DcDetector); + List Segs2Road = new ArrayList<>(); + for (Road r : allRoads) { + Segs2Road.clear(); + int missingSL = -1; + for (int ri = 0; ri < 3; ri++) { + if (r.get(ri).associatedCrossId == -1) { + if (r.get(ri).get_Superlayer() % 2 == 1) { + missingSL = r.get(ri).get_Superlayer() + 1; + } else { + missingSL = r.get(ri).get_Superlayer() - 1; + } + } + } + for (int ri = 0; ri < 3; ri++) { + for (Segment s : entry.getValue()) { + if (s.get_Sector() == r.get(ri).get_Sector() && + s.get_Region() == r.get(ri).get_Region() && + s.associatedCrossId == r.get(ri).associatedCrossId && + r.get(ri).associatedCrossId != -1) { + if (s.get_Superlayer() % 2 == missingSL % 2) + Segs2Road.add(s); + } + } + } + if (Segs2Road.size() == 2) { + Segment pSegment = rf.findRoadMissingSegment(Segs2Road, + DcDetector, + r.a); + if (pSegment != null) + entry.getValue().add(pSegment); + } + } + crosses = crf.find_Crosses(entry.getValue(), DcDetector); + Collections.sort(crosses); + grpCrs.put(entry.getKey(), (ArrayList) crosses); + } else { + grpCrs.put(entry.getKey(), (ArrayList) crosses); + } + } + // using iterators + Iterator>> citr = grpCrs.entrySet().iterator(); + while(citr.hasNext()) { + Map.Entry> entry = citr.next(); + crossList.add(entry.getValue()); + } + return crossList; + } + + public List RecomposeSegments(List fhits, + DCGeant4Factory DcDetector) { + + List fclusters = new ArrayList(); + Map> grpHits = new HashMap>(); + + for (Hit hit : fhits) { + if (hit.NNTrkId > 0) { + int index = hit.NNTrkId; + if(grpHits.get(index)==null) { // if the list not yet created make it + grpHits.put(index, new ArrayList()); + grpHits.get(index).add(hit); // append hit + } else { + grpHits.get(index).add(hit); // append hit + } + } + } + + // using iterators + Iterator>> itr = grpHits.entrySet().iterator(); + + while(itr.hasNext()) { + Map.Entry> entry = itr.next(); + + if(entry.getValue().size()>=20) {// 4 layers per superlayer, 5 out of six superlayer tracking + // find clusters + //fill array of hit + clf.fillHitArray(entry.getValue(), 0); //find clumps of hits init + List clusters = clf.findClumps(entry.getValue(), ct); + for (Cluster clus : clusters) { + FittedCluster fclus = new FittedCluster(clus); + if (clus != null && clus.size() >= 4 ) { //4 layers per superlayer + // update the hits + for (FittedHit fhit : fclus) { + fhit.set_TrkgStatus(0); + fhit.updateHitPosition(DcDetector); + } + + cf.SetFitArray(fclus, "TSC"); + cf.Fit(fclus, true); + cf.SetResidualDerivedParams(fclus, false, false, DcDetector); //calcTimeResidual=false, resetLRAmbig=false, local= false + + fclus = ct.ClusterCleaner(fclus, cf, DcDetector); + // update the hits + for (FittedHit fhit : fclus) { + fhit.set_AssociatedClusterID(clus.get_Id()); + fhit.set_AssociatedHBTrackID(entry.getKey()); + } + cf.SetFitArray(fclus, "TSC"); + cf.Fit(fclus, false); + cf.SetSegmentLineParameters(fclus.get(0).get_Z(), fclus); + + Segment seg = new Segment(fclus); + seg.set_fitPlane(DcDetector); + + double sumRes=0; + double sumTime=0; + + for(FittedHit h : seg) { + sumRes+=h.get_TimeResidual(); + sumTime+=h.get_Time(); + } + seg.set_ResiSum(sumRes); + seg.set_TimeSum(sumTime); + + fclusters.add(seg); + } + } + } + } + return fclusters; + } + +} diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/segment/SegmentFinder.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/segment/SegmentFinder.java index 8c9f836bde..a93d59d2c3 100644 --- a/reconstruction/dc/src/main/java/org/jlab/rec/dc/segment/SegmentFinder.java +++ b/reconstruction/dc/src/main/java/org/jlab/rec/dc/segment/SegmentFinder.java @@ -84,8 +84,8 @@ public void get_LayerEfficiencies(Segment seg, DataEvent event, DCGeant4Factory int trjWire = trj.getWireOnTrajectory(seg.get_Sector(), seg.get_Superlayer(), l + 1, trkXMP, DcDetector); //double x = GeometryLoader.dcDetector.getSector(0).getSuperlayer(seg.get_Superlayer()-1).getLayer(l).getComponent(trjWire-1).getMidpoint().x(); double x = DcDetector.getWireMidpoint(seg.get_Sector() - 1, seg.get_Superlayer() - 1, l, trjWire - 1).x; - double cosTrkAngle = FastMath.cos(Math.toRadians(6.)) * Math.sqrt(1. + seg.get_fittedCluster().get_clusterLineFitSlope() * seg.get_fittedCluster().get_clusterLineFitSlope()); - double calc_doca = (x - trkX) * cosTrkAngle; + double cosTkAng = FastMath.cos(Math.toRadians(6.)) * Math.sqrt(1. + seg.get_fittedCluster().get_clusterLineFitSlope() * seg.get_fittedCluster().get_clusterLineFitSlope()); + double calc_doca = (x - trkX) * cosTkAng; trkDocas[l] = calc_doca; for (int j = 0; j < sector.length; j++) { diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/timetodistance/T2DFunctions.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/timetodistance/T2DFunctions.java index 07593e6b25..012ebaeccf 100644 --- a/reconstruction/dc/src/main/java/org/jlab/rec/dc/timetodistance/T2DFunctions.java +++ b/reconstruction/dc/src/main/java/org/jlab/rec/dc/timetodistance/T2DFunctions.java @@ -5,8 +5,6 @@ */ package org.jlab.rec.dc.timetodistance; -import org.jlab.rec.dc.Constants; - /** * * @author ziegler @@ -334,7 +332,8 @@ public static synchronized double polyFcnMac(double x, double alpha, double bfie c = c /(4.-(1.-6.*R*R)/(1.-2.*R)); double b = delv/(rcapital*rcapital) - 4.*c/(3.*rcapital); double d = 1/v_0; - double a = (tmax - b*dmaxalpha*dmaxalpha*dmaxalpha - c*dmaxalpha*dmaxalpha - d*dmaxalpha)/(dmaxalpha*dmaxalpha*dmaxalpha*dmaxalpha) ; + double a = (tmax - b*dmaxalpha*dmaxalpha*dmaxalpha - + c*dmaxalpha*dmaxalpha - d*dmaxalpha)/(dmaxalpha*dmaxalpha*dmaxalpha*dmaxalpha) ; time = a*x*x*x*x + b*x*x*x + c*x*x + d*x ; //B correction diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/timetodistance/TableLoader.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/timetodistance/TableLoader.java index 364e9f7570..790b60a06e 100644 --- a/reconstruction/dc/src/main/java/org/jlab/rec/dc/timetodistance/TableLoader.java +++ b/reconstruction/dc/src/main/java/org/jlab/rec/dc/timetodistance/TableLoader.java @@ -36,27 +36,24 @@ public TableLoader() { */ public static void test(){ TimeToDistanceEstimator tde = new TimeToDistanceEstimator(); - for(int s = 0; s<6; s++ ){ // loop over sectors - for(int r = 0; r<6; r++ ){ //loop over slys - for(int ibfield =0; ibfield1) - DISTFROMTIME[s][r][ibfield][icosalpha][tb]=DISTFROMTIME[s][r][ibfield][icosalpha][tb-1]; - if(DISTFROMTIME[s][r][ibfield][icosalpha][tb]==0) - System.out.println("Bbin "+ibfield+" cos "+icosalpha+" tb "+tb); - //double Xalpha = -(Math.toDegrees(Math.acos(Math.cos(Math.toRadians(30.)) + (icosalpha)*(1. - Math.cos(Math.toRadians(30.)))/5.)) - 30.); - //double Xtime=(2*tb+1); - - //for (int k=0; k<10; k++){ - //double Bf = (ibfield+0.1*k)*0.5; - //int bbin = tde.getBIdx(Bf); - //double Xdoca=tde.interpolateOnGrid((double) Bf, Xalpha, Xtime, s, r); - // System.out.println("Bbin "+ibfield+" B "+ (float)Bf+" sl "+(r+1)+" time "+Xtime+" tb "+tb+" timeBin "+tde.getTimeIdx(Xtime, s, r, ibfield, icosalpha) - // +" icosalpha "+icosalpha+" Xalpha "+(float) Xalpha + " dis "+ (float)DISTFROMTIME[s][r][bbin][icosalpha][tde.getTimeIdx(Xtime, s, r, ibfield, icosalpha)] +" dis' "+ - // (float) Xdoca ); - //} + double Xalpha = -(Math.toDegrees(Math.acos(Math.cos(Math.toRadians(30.)) + (icosalpha)*(1. - Math.cos(Math.toRadians(30.)))/5.)) - 30.); + double Xtime=(2*tb+1); + + //for (int k=0; k<10; k++){ + double Bf = (ibfield)*0.5; + int bbin = tde.getBIdx(Bf); + double Xdoca=tde.interpolateOnGrid((double) Bf, Xalpha, Xtime, s, r); + System.out.println("Bbin "+ibfield+" B "+ (float)Bf+" sl "+(r+1)+" time "+Xtime+" tb "+tb+" timeBin "+tde.getTimeIdx(Xtime, s, r, ibfield, icosalpha) + +" icosalpha "+icosalpha+" Xalpha "+(float) Xalpha + " dis "+ (float)DISTFROMTIME[s][r][bbin][icosalpha][tde.getTimeIdx(Xtime, s, r, ibfield, icosalpha)] +" time' "+ + (float) calc_Time( Xdoca, Xalpha, Bf, s+1, r+1) +" tdix "+tde.getTimeIdx(calc_Time( Xdoca, Xalpha, Bf, s+1, r+1), s, r, ibfield, icosalpha)); + //} } } @@ -131,7 +128,7 @@ public static synchronized void Fill(IndexedTable tab) { //CCDBTables 1 = "/calibration/dc/time_to_distance/t2d"; //CCDBTables 2 = "/calibration/dc/time_corrections/T0_correction"; if (T2DLOADED) return; - System.out.println(" T2D TABLE FILLED....."); + double stepSize = 0.0010; DecimalFormat df = new DecimalFormat("#"); df.setRoundingMode(RoundingMode.CEILING); @@ -164,7 +161,7 @@ public static synchronized void Fill(IndexedTable tab) { double cos30minusalpha = Math.cos(Math.toRadians(30.)) + (double) (icosalpha)*(1. - Math.cos(Math.toRadians(30.)))/5.; double alpha = -(Math.toDegrees(Math.acos(cos30minusalpha)) - 30); int nxmax = (int) (dmax*cos30minusalpha/stepSize); - + for(int idist =0; idistDISTFROMTIME[s][r][ibfield][icosalpha][tbin] + // && Math.abs((double)(2.*tbin+1)-timebfield)<=Math.abs((double)(2.*tbin+1)-prevTime)) { + // DISTFROMTIME[s][r][ibfield][icosalpha][tbin]=x; + //} // bincount++; DISTFROMTIME[s][r][ibfield][icosalpha][tbin]+=stepSize; } - + /* if(timebfield>timebfield_max) { DISTFROMTIME[s][r][ibfield][icosalpha][tbin]=x-stepSize*0.5; if(DISTFROMTIME[s][r][ibfield][icosalpha][tbin]>dmax) @@ -201,7 +204,8 @@ public static synchronized void Fill(IndexedTable tab) { } } TableLoader.fillMissingTableBins(); - + //TableLoader.test(); + System.out.println(" T2D TABLE FILLED....."); T2DLOADED = true; } diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/timetodistance/TimeToDistanceEstimator.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/timetodistance/TimeToDistanceEstimator.java index b8dd441dba..dcdea3f806 100644 --- a/reconstruction/dc/src/main/java/org/jlab/rec/dc/timetodistance/TimeToDistanceEstimator.java +++ b/reconstruction/dc/src/main/java/org/jlab/rec/dc/timetodistance/TimeToDistanceEstimator.java @@ -72,7 +72,7 @@ public double interpolateOnGrid(double Bf, double alpha, double t, int SecIdx, double alpha1 = this.getAlphaFromAlphaIdx(binlowAlpha); double alpha2 = this.getAlphaFromAlphaIdx(binhighAlpha); - + // interpolate in B: double f_B_alpha1_t1 = interpolateLinear(B*B, B1*B1, B2*B2, TableLoader.DISTFROMTIME[SecIdx][SlyrIdx][binlowB][binlowAlpha][this.getTimeIdx(t, SecIdx, SlyrIdx, binlowB, binlowAlpha)], @@ -89,21 +89,23 @@ public double interpolateOnGrid(double Bf, double alpha, double t, int SecIdx, // interpolate in d for 2 values of alpha: double f_B_alpha1_t = interpolateLinear(t, this.getTimeIdx(t, SecIdx, SlyrIdx, binlowB, binlowAlpha)*2., this.getTimeNextIdx(t, SecIdx, SlyrIdx, binhighB, binlowAlpha)*2., f_B_alpha1_t1, f_B_alpha1_t2); double f_B_alpha2_t = interpolateLinear(t, this.getTimeIdx(t, SecIdx, SlyrIdx, binlowB, binhighAlpha)*2., this.getTimeNextIdx(t, SecIdx, SlyrIdx, binhighB, binhighAlpha)*2., f_B_alpha2_t1, f_B_alpha2_t2); -//if( TableLoader.DISTFROMTIME[SecIdx][SlyrIdx][binlowB][binlowAlpha][this.getTimeIdx(t, SecIdx, SlyrIdx, binlowB, binlowAlpha)]==0) -// System.out.println(SlyrIdx+" binlowB "+binlowB+" binlowAlpha "+binlowAlpha+" t "+this.getTimeIdx(t, SecIdx, SlyrIdx, binlowB, binlowAlpha)+" time "+t); -//if(TableLoader.DISTFROMTIME[SecIdx][SlyrIdx][binlowB][binhighAlpha][this.getTimeIdx(t, SecIdx, SlyrIdx, binlowB, binhighAlpha)]==0) -// System.out.println(SlyrIdx+" binlowB "+binlowB+" binhighAlpha "+binhighAlpha+" t "+this.getTimeIdx(t, SecIdx, SlyrIdx, binlowB, binhighAlpha)+" time "+t); -//if(TableLoader.DISTFROMTIME[SecIdx][SlyrIdx][binhighB][binlowAlpha][this.getTimeIdx(t, SecIdx, SlyrIdx, binhighB, binlowAlpha)]==0) -// System.out.println(SlyrIdx+" binhighB "+binhighB+" binlowAlpha "+binlowAlpha+" t "+this.getTimeIdx(t, SecIdx, SlyrIdx, binhighB, binlowAlpha)+" time "+t); -//if(TableLoader.DISTFROMTIME[SecIdx][SlyrIdx][binhighB][binhighAlpha][this.getTimeIdx(t, SecIdx, SlyrIdx, binhighB, binhighAlpha)]==0) -// System.out.println(SlyrIdx+" binhighB "+binhighB+" binhighAlpha "+binhighAlpha+" t "+this.getTimeIdx(t, SecIdx, SlyrIdx, binhighB, binhighAlpha)+" time "+t); - + //System.out.println( TableLoader.DISTFROMTIME[SecIdx][SlyrIdx][binlowB][binlowAlpha][this.getTimeIdx(t, SecIdx, SlyrIdx, binlowB, binlowAlpha)]); + //System.out.println(SlyrIdx+" binlowB "+binlowB+" binlowAlpha "+binlowAlpha+" t "+this.getTimeIdx(t, SecIdx, SlyrIdx, binlowB, binlowAlpha)+" time "+t); + //System.out.println(TableLoader.DISTFROMTIME[SecIdx][SlyrIdx][binlowB][binhighAlpha][this.getTimeIdx(t, SecIdx, SlyrIdx, binlowB, binhighAlpha)]); + //System.out.println(SlyrIdx+" binlowB "+binlowB+" binhighAlpha "+binhighAlpha+" t "+this.getTimeIdx(t, SecIdx, SlyrIdx, binlowB, binhighAlpha)+" time "+t); + //System.out.println(TableLoader.DISTFROMTIME[SecIdx][SlyrIdx][binhighB][binlowAlpha][this.getTimeIdx(t, SecIdx, SlyrIdx, binhighB, binlowAlpha)]); + //System.out.println(SlyrIdx+" binhighB "+binhighB+" binlowAlpha "+binlowAlpha+" t "+this.getTimeIdx(t, SecIdx, SlyrIdx, binhighB, binlowAlpha)+" time "+t); + //System.out.println(TableLoader.DISTFROMTIME[SecIdx][SlyrIdx][binhighB][binhighAlpha][this.getTimeIdx(t, SecIdx, SlyrIdx, binhighB, binhighAlpha)]); + //System.out.println(SlyrIdx+" binhighB "+binhighB+" binhighAlpha "+binhighAlpha+" t "+this.getTimeIdx(t, SecIdx, SlyrIdx, binhighB, binhighAlpha)+" time "+t); + //System.out.println(" f_B_alpha1_t1 "+f_B_alpha1_t1+" f_B_alpha2_t1 "+f_B_alpha2_t1 + // +" f_B_alpha1_t2 "+f_B_alpha1_t2+" f_B_alpha2_t2 "+f_B_alpha2_t2 + // +" f_B_alpha1_t "+f_B_alpha1_t+" f_B_alpha2_t "+f_B_alpha2_t); + // interpolate in alpha: (cos30-cosA) double f_B_alpha_t = interpolateLinear(Math.cos(Math.toRadians(30.))-Math.cos(Math.toRadians(alpha)), Math.cos(Math.toRadians(30.))-Math.cos(Math.toRadians(alpha1)), Math.cos(Math.toRadians(30.))-Math.cos(Math.toRadians(alpha2)), f_B_alpha1_t, f_B_alpha2_t); - return f_B_alpha_t; /* @@ -228,5 +230,24 @@ private int getTimeNextIdx(double t, int SecIdx, int SlyrIdx, int binlowB, int b } return binhighT; } - + + /** + * @param slyIdx superlayer index + * @param time + * @return test doca corr + */ + public double addDOCACorr(double time, int slyIdx) { + double dDoca = 0; + if(slyIdx+1 == 5 || slyIdx+1 ==6) { + if(time>600) { + dDoca = 0.15; + } else { + dDoca = (7.6e-3 - 2.4e-4*time +9.8e-3*time*time - 3.8e-6*time*time*time)*5.5410595e-05; + } + //System.out.println("time "+time +" added doca "+(float)dDoca); + } + return dDoca; + } } + + diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/Track.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/Track.java index 9365de0c0c..7bae226c0e 100755 --- a/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/Track.java +++ b/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/Track.java @@ -1,10 +1,12 @@ package org.jlab.rec.dc.track; -import Jama.Matrix; +//import Jama.Matrix; +import org.jlab.jnp.matrix.*; import java.util.ArrayList; import java.util.List; import org.jlab.geom.prim.Point3D; import org.jlab.geom.prim.Vector3D; +import org.jlab.rec.dc.Constants; import org.jlab.rec.dc.hit.FittedHit; import org.jlab.rec.dc.segment.Segment; import org.jlab.rec.dc.trajectory.StateVec; @@ -380,6 +382,12 @@ public List getHitsOnTrack() { return _hitsOnTrack; } + + public boolean isGood() { + boolean isGood=true; + if(this._trakOrig.distance(0, 0, 0)>Constants.htccRadius) isGood=false; + return isGood; + } /** * Basic track info */ diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/TrackCandListFinder.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/TrackCandListFinder.java index 42fcbb9971..73df657bbd 100755 --- a/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/TrackCandListFinder.java +++ b/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/TrackCandListFinder.java @@ -1,7 +1,9 @@ package org.jlab.rec.dc.track; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import org.jlab.clas.clas.math.FastMath; import org.jlab.clas.swimtools.Swim; import org.jlab.detector.geant4.v2.DCGeant4Factory; @@ -12,7 +14,8 @@ import org.jlab.rec.dc.cross.CrossList; import org.jlab.rec.dc.hit.FittedHit; import org.jlab.rec.dc.segment.Segment; -import org.jlab.rec.dc.track.fit.KFitter; +//import org.jlab.rec.dc.track.fit.KFitter; +import org.jlab.rec.dc.track.fit.KFitterDoca; import org.jlab.rec.dc.trajectory.StateVec; import org.jlab.rec.dc.trajectory.Trajectory; import org.jlab.rec.dc.trajectory.TrajectoryFinder; @@ -317,7 +320,7 @@ public void setTrackPars(Track cand, Swim dcSwim) { double pz = cand.get_P() / Math.sqrt(stateVec.tanThetaX() * stateVec.tanThetaX() + stateVec.tanThetaY() * stateVec.tanThetaY() + 1); - + //System.out.println("Setting track params for ");stateVec.printInfo(); dcSwim.SetSwimParameters(stateVec.x(), stateVec.y(), z, pz * stateVec.tanThetaX(), pz * stateVec.tanThetaY(), pz, @@ -569,24 +572,48 @@ public void setTrackPars(Track cand, cand.set_PreRegion1CrossDir(new Point3D(uxInner, uyInner, uzInner)); } - public void removeOverlappingTracks(List trkcands) { - List selectedTracks = new ArrayList(); + private Integer getKey(Track trk) { + return trk.get(0).get_Id()*1000000+ + trk.get(1).get_Id()*1000+ + trk.get(2).get_Id(); + } + public void removeOverlappingTracks(List trkcands) { + Map selectedTracksMap = new HashMap(); List list = new ArrayList(); int size = trkcands.size(); for (int i = 0; i < size; i++) { list.clear(); this.getOverlapLists(trkcands.get(i), trkcands, list); - trkcands.removeAll(list); - size -= list.size(); Track selectedTrk = this.FindBestTrack(list); + if (selectedTrk == null) continue; - //if(this.ListContainsTrack(selectedTracks, selectedTrk)==false) - selectedTracks.add(selectedTrk); + selectedTracksMap.put(this.getKey(selectedTrk), selectedTrk); } - //trkcands.removeAll(trkcands); - trkcands.addAll(selectedTracks); + + trkcands.removeAll(trkcands); + for(Map.Entry entry : selectedTracksMap.entrySet()) + trkcands.add(entry.getValue()); } + +// public void removeOverlappingTracks(List trkcands) { +// List selectedTracks = new ArrayList(); +// List list = new ArrayList(); +// int size = trkcands.size(); +// for (int i = 0; i < size; i++) { +// list.clear(); +// this.getOverlapLists(trkcands.get(i), trkcands, list); +// trkcands.removeAll(list); +// size -= list.size(); +// Track selectedTrk = this.FindBestTrack(list); +// if (selectedTrk == null) +// continue; +// //if(this.ListContainsTrack(selectedTracks, selectedTrk)==false) +// selectedTracks.add(selectedTrk); +// } +// //trkcands.removeAll(trkcands); +// trkcands.addAll(selectedTracks); +// } /** * @param selectedTracks the list of selected tracks @@ -603,7 +630,7 @@ private boolean ListContainsTrack(List selectedTracks, Track selectedTrk) } return isInList; } - + /** * @param track the track * @param trkcands the list of candidates @@ -661,17 +688,15 @@ public void matchHits(List stateVecAtPlanesList, Track trk, for (Cross c : trk) { for (FittedHit h1 : c.get_Segment1()) { - if (Math.abs(st.getZ() - h1.get_Z()) < 0.1 && c.get_Segment1().get_Id()>-1) { + if (Math.abs(st.getZ() - h1.get_Z()) < 0.1 && c.get_Segment1().get_Id()>-1 && + (h1.get_XWire() - st.getProjector())<0.1) { - if((h1.get_X() - st.getProjector())>h1.get_CellSize()*2) - continue; - h1.set_Id(h1.get_Id()); h1.set_TDC(h1.get_TDC()); h1.set_AssociatedHBTrackID(trk.get_Id()); h1.set_AssociatedClusterID(h1.get_AssociatedClusterID()); h1.setAssociatedStateVec(st); - h1.set_TrkResid(h1.get_X() - st.getProjector()); + h1.set_TrkResid(h1.get_Doca()*Math.signum(st.getProjectorDoca()) - st.getProjectorDoca()); h1.setB(st.getB()); h1.calc_SignalPropagAlongWire(st.x(), st.y(), DcDetector); h1.setSignalPropagTimeAlongWire(DcDetector); @@ -695,17 +720,15 @@ public void matchHits(List stateVecAtPlanesList, Track trk, } } for (FittedHit h1 : c.get_Segment2()) { - if (Math.abs(st.getZ() - h1.get_Z()) < 0.1 && c.get_Segment2().get_Id()>-1) { + if (Math.abs(st.getZ() - h1.get_Z()) < 0.1 && c.get_Segment2().get_Id()>-1 && + (h1.get_XWire() - st.getProjector())<0.1) { - if((h1.get_X() - st.getProjector())>h1.get_CellSize()*2) - continue; - h1.set_Id(h1.get_Id()); h1.set_TDC(h1.get_TDC()); h1.set_AssociatedHBTrackID(trk.get_Id()); h1.set_AssociatedClusterID(h1.get_AssociatedClusterID()); h1.setAssociatedStateVec(st); - h1.set_TrkResid(h1.get_X() - st.getProjector()); + h1.set_TrkResid(h1.get_Doca()*Math.signum(st.getProjectorDoca()) - st.getProjectorDoca()); h1.setB(st.getB()); h1.calc_SignalPropagAlongWire(st.x(), st.y(), DcDetector); h1.setSignalPropagTimeAlongWire(DcDetector); @@ -797,7 +820,7 @@ private List findStraightTracks(CrossList crossList, DCGeant4Factory DcDe cand.get(0).get_Dir().y() / cand.get(0).get_Dir().z()); cand.set_StateVecAtReg1MiddlePlane(VecAtReg1MiddlePlane); // initialize the fitter with the candidate track - KFitter kFit = new KFitter(cand, DcDetector, false, dcSwim); + KFitterDoca kFit = new KFitterDoca(cand, DcDetector, false, dcSwim,0); kFit.totNumIter = 1; if (debug) startTime = System.currentTimeMillis(); @@ -847,6 +870,9 @@ private List findCurvedTracks(CrossList crossList, DCGeant4Factory DcDete return cands; } for (List aCrossList : crossList) { + if(aCrossList.size()<3) { + return cands; + } //initialize Track cand = new Track(); TrajectoryFinder trjFind = new TrajectoryFinder(); @@ -1003,71 +1029,53 @@ private List findCurvedTracks(CrossList crossList, DCGeant4Factory DcDete cand.get(0).get_Dir().y() / cand.get(0).get_Dir().z()); cand.set_StateVecAtReg1MiddlePlane(VecAtReg1MiddlePlane); // initialize the fitter with the candidate track + KFitterDoca kFit = null; + StateVec fitStateVec = null; - KFitter kFit = new KFitter(cand, DcDetector, false, dcSwim); - // if(this.trking.equalsIgnoreCase("TimeBased")) - // kFit.totNumIter=30; - - // initialize the state vector corresponding to the last measurement site - StateVec fn = new StateVec(); - - if (debug) startTime = System.currentTimeMillis(); - kFit.runFitter(cand.get(0).get_Sector()); + if (debug) System.out.println("Kalman fitter - 2 = " + (System.currentTimeMillis() - startTime)); - + // prefer to initialize the seed with region 2 cross due to higher background in region 1 + int crossIdxinList = 1; + if(cand.get(1).isPseudoCross) { + crossIdxinList = 0; + } + kFit = new KFitterDoca(cand, DcDetector, false, dcSwim, crossIdxinList); + kFit.totNumIter = 10; + kFit.runFitter(cand.get(0).get_Sector()); if (kFit.finalStateVec == null) { - //System.out.println(" FIT FAILED no SV"); continue; - } - - if (this.trking.equalsIgnoreCase("HitBased")) { - - if (debug) startTime = System.currentTimeMillis(); - double HBc2 = getHitBasedFitChi2ToCrosses(cand.get(0).get_Sector(), - x1, y1, z1, x2, y2, z2, x3, y3, z3, - 1. / Math.abs(kFit.finalStateVec.Q), - (int) Math.signum(kFit.finalStateVec.Q), - kFit.finalStateVec.x, - kFit.finalStateVec.y, - kFit.finalStateVec.z, - kFit.finalStateVec.tx, - kFit.finalStateVec.ty, - dcSwim); - if (debug) - System.out.println("getHitBasedFitChi2ToCrosses = " + - (System.currentTimeMillis() - startTime)); - - if (HBc2 > Constants.MAXCHI2) { - kFit.setFitFailed = true; - } - } - - if (!kFit.setFitFailed && kFit.finalStateVec != null) { - // set the state vector at the last measurement site - fn.set(kFit.finalStateVec.x, - kFit.finalStateVec.y, - kFit.finalStateVec.tx, - kFit.finalStateVec.ty); - fn.setZ(kFit.finalStateVec.z); - cand.setFinalStateVec(fn); - - //set the track parameters if the filter does not fail - cand.set_P(1. / Math.abs(kFit.finalStateVec.Q)); - cand.set_Q((int) Math.signum(kFit.finalStateVec.Q)); - this.setTrackPars(cand, traj, - trjFind, fn, - kFit.finalStateVec.z, + } else { + if(kFit.chi2 kfStateVecsAlongTrajectory; - public int totNumIter = 30; - private double newChisq = Double.POSITIVE_INFINITY; - - public double chi2 = 0; - private double chi2kf = 0; - public int NDF = 0; - public int ConvStatus = 1; - - public KFitter(Track trk, DCGeant4Factory DcDetector, - boolean TimeBasedUsingHBtrack, - Swim swimmer) { - sv = new StateVecs(swimmer); - if (TimeBasedUsingHBtrack) { - this.initFromHB(trk, DcDetector); - } else { - this.init(trk, DcDetector); - } - } - - private void initFromHB(Track trk, DCGeant4Factory DcDetector) { - mv.setMeasVecsFromHB(trk, DcDetector); - int mSize = mv.measurements.size(); - sv.Z = new double[mSize]; - - for (int i = 0; i < mSize; i++) { - sv.Z[i] = mv.measurements.get(i).z; - } - sv.initFromHB(trk, sv.Z[0], this); - } - - public void init(Track trk, DCGeant4Factory DcDetector) { - mv.setMeasVecs(trk, DcDetector); - int mSize = mv.measurements.size(); - - sv.Z = new double[mSize]; - - for (int i = 0; i < mSize; i++) { - sv.Z[i] = mv.measurements.get(i).z; - } - sv.init(trk, sv.Z[0], this); - } - - public void runFitter(int sector) { - this.chi2 = 0; - this.NDF = mv.ndf; - int svzLength = sv.Z.length; - -// IntStream.range(1,totNumIter ).parallel().forEach(i -> { - for (int i = 1; i <= totNumIter; i++) { - - this.chi2kf = 0; - if (i > 1) { - //get new state vec at 1st measurement after propagating back from the last filtered state - /*sv.transport(sector, - svzLength - 1, - 0, - sv.trackTraj.get(svzLength - 1), - sv.trackCov.get(svzLength- 1)); */ - for (int k = svzLength - 1; k >0; k--) { - //if(i==2 && this.totNumIter==30) - //System.out.println("sector " +sector+"stateVec "+sv.trackTraj.get(k).printInfo()); - sv.transport(sector, k, k - 1, - sv.trackTraj.get(k), - sv.trackCov.get(k)); - this.filter(k - 1); - } - } - for (int k = 0; k < svzLength - 1; k++) { - //if(i==2 && this.totNumIter==30) - //System.out.println("stateVec "+sv.trackTraj.get(k).printInfo()); - sv.transport(sector, k, k + 1, - sv.trackTraj.get(k), - sv.trackCov.get(k)); - this.filter(k + 1); - } - if (i > 1) { - if(this.setFitFailed==true) - i = totNumIter; - if (this.chi2kf < newChisq) { - if(this.finalStateVec!=null) { - if(Math.abs(sv.trackTraj.get(svzLength - 1).Q-this.finalStateVec.Q)<5.e-4 && - Math.abs(sv.trackTraj.get(svzLength - 1).x-this.finalStateVec.x)<1.e-4 && - Math.abs(sv.trackTraj.get(svzLength - 1).y-this.finalStateVec.y)<1.e-4 && - Math.abs(sv.trackTraj.get(svzLength - 1).tx-this.finalStateVec.tx)<1.e-6 && - Math.abs(sv.trackTraj.get(svzLength - 1).ty-this.finalStateVec.ty)<1.e-6) { - i = totNumIter; - } - } - this.finalStateVec = sv.trackTraj.get(svzLength - 1); - this.finalCovMat = sv.trackCov.get(svzLength - 1); - -// if (deltaChi2 < 0.001) { -// this.ConvStatus = 0; -// i = totNumIter; -// } - - newChisq = this.chi2kf; - } else { - this.ConvStatus = 1; - } - } - } -// }); - if(totNumIter==1) { - this.finalStateVec = sv.trackTraj.get(svzLength - 1); - this.finalCovMat = sv.trackCov.get(svzLength - 1); - } - this.calcFinalChisq(sector); - - } - - private void filter(int k) { - if (sv.trackTraj.get(k) != null && - sv.trackCov.get(k).covMat != null && - k < sv.Z.length - && mv.measurements.get(k).reject==false) { - double[] K = new double[5]; - double V = Math.abs(mv.measurements.get(k).unc); - double[] H = mv.H(sv.trackTraj.get(k).y, - mv.measurements.get(k).tilt, - mv.measurements.get(k).wireMaxSag, - mv.measurements.get(k).wireLen); - - double[][] HTGH = new double[][]{ - {H[0] * H[0] / V, H[0] * H[1] / V, 0, 0, 0}, - {H[0] * H[1] / V, H[1] * H[1] / V, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0}, - {0, 0, 0, 0, 0} - }; - - Matrix Ci; - - if (!this.isNonsingular(sv.trackCov.get(k).covMat)) { - return; - } - try { - Ci = sv.trackCov.get(k).covMat.inverse(); - } catch (Exception e) { - return; - } - - Matrix Ca; - try { - Ca = Ci.plus(new Matrix(HTGH)); - } catch (Exception e) { - return; - } - if (Ca != null && !this.isNonsingular(Ca)) { - return; - } - if (Ca != null) { - Matrix CaInv = Ca.inverse(); - if (CaInv != null) { - sv.trackCov.get(k).covMat = CaInv; - } else { - return; - } - } else { - return; - } - - for (int j = 0; j < 5; j++) { - // the gain matrix - K[j] = (H[0] * sv.trackCov.get(k).covMat.get(j, 0) + - H[1] * sv.trackCov.get(k).covMat.get(j, 1)) / V; - } - - double h = mv.h(new double[]{sv.trackTraj.get(k).x, sv.trackTraj.get(k).y}, - mv.measurements.get(k).tilt, - mv.measurements.get(k).wireMaxSag, - mv.measurements.get(k).wireLen); - double c2 = ((mv.measurements.get(k).x - h) * (mv.measurements.get(k).x - h) / V); - - double x_filt = sv.trackTraj.get(k).x + K[0] * (mv.measurements.get(k).x - h); - double y_filt = sv.trackTraj.get(k).y + K[1] * (mv.measurements.get(k).x - h); - double tx_filt = sv.trackTraj.get(k).tx + K[2] * (mv.measurements.get(k).x - h); - double ty_filt = sv.trackTraj.get(k).ty + K[3] * (mv.measurements.get(k).x - h); - double Q_filt = sv.trackTraj.get(k).Q + K[4] * (mv.measurements.get(k).x - h); - - - chi2kf += c2; - sv.trackTraj.get(k).x = x_filt; - sv.trackTraj.get(k).y = y_filt; - sv.trackTraj.get(k).tx = tx_filt; - sv.trackTraj.get(k).ty = ty_filt; - sv.trackTraj.get(k).Q = Q_filt; - - } - } - - @SuppressWarnings("unused") - private void smooth(int sector, int k) { - this.chi2 = 0; - if (sv.trackTraj.get(k) != null && sv.trackCov.get(k).covMat != null) { - sv.transport(sector, k, 0, sv.trackTraj.get(k), sv.trackCov.get(k)); - for (int k1 = 0; k1 < k; k1++) { - sv.transport(sector, k1, k1 + 1, sv.trackTraj.get(k1), sv.trackCov.get(k1)); - this.filter(k1 + 1); - } - } - } - - private void calcFinalChisq(int sector) { - int k = sv.Z.length - 1; - this.chi2 = 0; - double path = 0; - double[] nRj = new double[3]; - - kfStateVecsAlongTrajectory = new ArrayList<>(); - if (sv.trackTraj.get(k) != null && sv.trackCov.get(k).covMat != null) { - sv.transport(sector, sv.Z.length - 1, 0, - sv.trackTraj.get(sv.Z.length - 1), - sv.trackCov.get(sv.Z.length - 1)); - org.jlab.rec.dc.trajectory.StateVec svc = - new org.jlab.rec.dc.trajectory.StateVec(sv.trackTraj.get(0).x, - sv.trackTraj.get(0).y, - sv.trackTraj.get(0).tx, - sv.trackTraj.get(0).ty); - svc.setZ(sv.trackTraj.get(0).z); - svc.setB(sv.trackTraj.get(0).B); - path += sv.trackTraj.get(0).deltaPath; - svc.setPathLength(path); - double h0 = mv.h(new double[]{sv.trackTraj.get(0).x, sv.trackTraj.get(0).y}, - mv.measurements.get(0).tilt, - mv.measurements.get(0).wireMaxSag, - mv.measurements.get(0).wireLen); - svc.setProjector(h0); - kfStateVecsAlongTrajectory.add(svc); - double res = (mv.measurements.get(0).x - h0); - chi2 += (mv.measurements.get(0).x - h0) * (mv.measurements.get(0).x - h0) / mv.measurements.get(0).error; - nRj[mv.measurements.get(0).region-1]+=res*res/mv.measurements.get(0).error; - - for (int k1 = 0; k1 < k; k1++) { - sv.transport(sector, k1, k1 + 1, sv.trackTraj.get(k1), sv.trackCov.get(k1)); - - double V = mv.measurements.get(k1 + 1).error; - double h = mv.h(new double[]{sv.trackTraj.get(k1 + 1).x, sv.trackTraj.get(k1 + 1).y}, - mv.measurements.get(k1 + 1).tilt, - mv.measurements.get(k1 + 1).wireMaxSag, - mv.measurements.get(k1 + 1).wireLen); - svc = new org.jlab.rec.dc.trajectory.StateVec(sv.trackTraj.get(k1 + 1).x, - sv.trackTraj.get(k1 + 1).y, - sv.trackTraj.get(k1 + 1).tx, - sv.trackTraj.get(k1 + 1).ty); - svc.setZ(sv.trackTraj.get(k1 + 1).z); - svc.setB(sv.trackTraj.get(k1 + 1).B); - path += sv.trackTraj.get(k1 + 1).deltaPath; - svc.setPathLength(path); - svc.setProjector(h); - kfStateVecsAlongTrajectory.add(svc); - res = (mv.measurements.get(k1 + 1).x - h); - chi2 += (mv.measurements.get(k1 + 1).x - h) * (mv.measurements.get(k1 + 1).x - h) / V; - - nRj[mv.measurements.get(k1 + 1).region-1]+=res*res/V; - - } - } - - } - - private boolean isNonsingular(Matrix mat) { - double matDet = mat.det(); - return Math.abs(matDet) >= 1.e-30; - } - -} diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/fit/KFitterDoca.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/fit/KFitterDoca.java new file mode 100644 index 0000000000..3f04b2790c --- /dev/null +++ b/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/fit/KFitterDoca.java @@ -0,0 +1,426 @@ +package org.jlab.rec.dc.track.fit; + +//import Jama.Matrix; + +import java.util.ArrayList; +import java.util.List; + +import org.jlab.clas.swimtools.Swim; +import org.jlab.detector.geant4.v2.DCGeant4Factory; +import org.jlab.rec.dc.track.Track; +import org.jlab.rec.dc.track.fit.StateVecsDoca.CovMat; +import org.jlab.rec.dc.track.fit.StateVecsDoca.StateVec; +import org.jlab.jnp.matrix.*; + +/** + * @author ziegler + */ +public class KFitterDoca { + + public boolean setFitFailed = false; + + private StateVecsDoca sv; + private MeasVecsDoca mv = new MeasVecsDoca(); + + public StateVec finalStateVec; + public CovMat finalCovMat; + private StateVec initialStateVec; + private CovMat initialCovMat; + public List kfStateVecsAlongTrajectory; + public int totNumIter = 30; + private double newChisq = Double.POSITIVE_INFINITY; + public boolean filterOn = true; + public double chi2 = 0; + private double chi2kf = 0; + public int NDF = 0; + public int ConvStatus = 1; + + Matrix first_inverse = new Matrix(); + Matrix addition = new Matrix(); + Matrix result = new Matrix(); + Matrix result_inv = new Matrix(); + Matrix adj = new Matrix(); + + public KFitterDoca(Track trk, DCGeant4Factory DcDetector, + boolean TimeBasedUsingHBtrack, + Swim swimmer, int c) { + sv = new StateVecsDoca(swimmer); + if (TimeBasedUsingHBtrack) { + this.initFromHB(trk, DcDetector); + } else { + this.init(trk, DcDetector, c); + } + } + boolean TBT =false; + private void initFromHB(Track trk, DCGeant4Factory DcDetector) { + mv.setMeasVecsFromHB(trk, DcDetector); + int mSize = mv.measurements.size(); + sv.Z = new double[mSize]; + + for (int i = 0; i < mSize; i++) { + sv.Z[i] = mv.measurements.get(i).z; + } + sv.initFromHB(trk, sv.Z[0], this); + TBT = true; + } + + public void init(Track trk, DCGeant4Factory DcDetector, int c) { + mv.setMeasVecs(trk, DcDetector); + int mSize = mv.measurements.size(); + + sv.Z = new double[mSize]; + + for (int i = 0; i < mSize; i++) { + sv.Z[i] = mv.measurements.get(i).z; + } + sv.init(trk, sv.Z[0], this, c); + } + public int interNum = 0; + double initChi2 = Double.POSITIVE_INFINITY; + public void runFitter(int sector) { + this.chi2 = Double.POSITIVE_INFINITY; + double initChi2 = Double.POSITIVE_INFINITY; + this.NDF = mv.ndf; + int svzLength = sv.Z.length; + + if(TBT==true) { + this.chi2kf = 0; + // Get the input parameters + for (int k = 0; k < svzLength - 1; k++) { + sv.transport(sector, k, k + 1, + sv.trackTraj.get(k), + sv.trackCov.get(k)); + } + this.calcFinalChisq(sector); + this.initialStateVec = sv.trackTraj.get(svzLength - 1); + this.initialCovMat = sv.trackCov.get(svzLength - 1); + this.finalStateVec = sv.trackTraj.get(svzLength - 1); + this.finalCovMat = sv.trackCov.get(svzLength - 1); + initChi2 = this.chi2; + if(Double.isNaN(chi2)) { + this.setFitFailed = true; + return; + } + } + // IntStream.range(1,totNumIter ).parallel().forEach(i -> { + for (int i = 1; i <= totNumIter; i++) { + interNum = i; + this.chi2kf = 0; + + if (i > 1) { + //get new state vec at 1st measurement after propagating back from the last filtered state + /*sv.transport(sector, + svzLength - 1, + 0, + sv.trackTraj.get(svzLength - 1), + sv.trackCov.get(svzLength- 1)); */ + for (int k = svzLength - 1; k >0; k--) { + //if(i==2 && this.totNumIter==30) + //System.out.println("sector " +sector+"stateVec "+sv.trackTraj.get(k).printInfo()); + if(k>=2) { + sv.transport(sector, k, k - 2, + sv.trackTraj.get(k), + sv.trackCov.get(k)); + this.filter(k - 2); + sv.transport(sector, k - 2, k - 1, + sv.trackTraj.get(k - 2), + sv.trackCov.get(k - 2)); + this.filter(k - 1); + } else { + sv.transport(sector, 1, 0, + sv.trackTraj.get(1), + sv.trackCov.get(1)); + this.filter(0); + } + } + } + for (int k = 0; k < svzLength - 1; k++) { + //if(i==2 && this.totNumIter==30) + //System.out.println("stateVec "+sv.trackTraj.get(k).printInfo()); + sv.transport(sector, k, k + 1, + sv.trackTraj.get(k), + sv.trackCov.get(k)); + //if(i==1 && k==0) + // Matrix5x5.show(sv.trackCov.get(k).covMat); + this.filter(k + 1); + } + if (i > 1) { + if(this.setFitFailed==true) + i = totNumIter; + if (this.setFitFailed==false) { + if(this.finalStateVec!=null) { + if(Math.abs(sv.trackTraj.get(svzLength - 1).Q-this.finalStateVec.Q)<5.e-4 && + Math.abs(sv.trackTraj.get(svzLength - 1).x-this.finalStateVec.x)<1.e-4 && + Math.abs(sv.trackTraj.get(svzLength - 1).y-this.finalStateVec.y)<1.e-4 && + Math.abs(sv.trackTraj.get(svzLength - 1).tx-this.finalStateVec.tx)<1.e-6 && + Math.abs(sv.trackTraj.get(svzLength - 1).ty-this.finalStateVec.ty)<1.e-6) { + i = totNumIter; + } + } + + this.finalStateVec = sv.trackTraj.get(svzLength - 1); + this.finalCovMat = sv.trackCov.get(svzLength - 1); + + } else { + this.ConvStatus = 1; + } + } + } + // }); + if(totNumIter==1) { + this.finalStateVec = sv.trackTraj.get(svzLength - 1); + this.finalCovMat = sv.trackCov.get(svzLength - 1); + } + this.calcFinalChisq(sector); + if(Double.isNaN(chi2)) + this.setFitFailed = true; + if(TBT==true) { + if(chi2>initChi2) { // fit failed + this.finalStateVec = this.initialStateVec; + this.finalCovMat = this.initialCovMat; + sv.trackTraj.put(svzLength - 1,this.initialStateVec); + sv.trackCov.put(svzLength - 1, this.initialCovMat); + this.calcFinalChisq(sector); + } + } + } + + public Matrix filterCovMat(double[] H, Matrix Ci, double V) { + + double det = Matrix5x5.inverse(Ci, first_inverse, adj); + if(Math.abs(det)<1.e-30) + return null; + + addition.set( + H[0] * H[0] / V, H[0] * H[1] / V, 0, 0, 0, + H[0] * H[1] / V, H[1] * H[1] / V, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0); + //System.out.println("Ci "); + //Matrix5x5.show(Ci); + //System.out.println("Cinv "); + //Matrix5x5.show(first_inverse); + //System.out.println("addition "); + //Matrix5x5.show(addition); + + Matrix5x5.add(first_inverse, addition, result); + double det2 = Matrix5x5.inverse(result, result_inv, adj); + //System.out.println("addition result"); + //Matrix5x5.show(result); + //System.out.println("inv result"); + //Matrix5x5.show(result_inv); + if(Math.abs(det2)<1.e-30) + return null; + + return result_inv; + } + private double KFScale = 4; + private void filter(int k) { + if(Double.isNaN(sv.trackTraj.get(k).x) || Double.isNaN(sv.trackTraj.get(k).y) + || Double.isNaN(sv.trackTraj.get(k).tx) ||Double.isNaN(sv.trackTraj.get(k).ty ) + || Double.isNaN(sv.trackTraj.get(k).Q)) { + this.setFitFailed = true; + return; + } + if (sv.trackTraj.get(k) != null && + sv.trackCov.get(k).covMat != null && + k < sv.Z.length + && mv.measurements.get(k).reject==false) { + + + double[] K = new double[5]; + double V = mv.measurements.get(k).unc[0]*KFScale; + double[] H = mv.H(new double[]{sv.trackTraj.get(k).x, sv.trackTraj.get(k).y}, + mv.measurements.get(k).z, + mv.measurements.get(k).wireLine[0]); + Matrix CaInv = this.filterCovMat(H, sv.trackCov.get(k).covMat, V); + if (CaInv != null) { + sv.trackCov.get(k).covMat = CaInv; + } else { + return; + } + + for (int j = 0; j < 5; j++) { + // the gain matrix + K[j] = (H[0] * sv.trackCov.get(k).covMat.get(j, 0) + + H[1] * sv.trackCov.get(k).covMat.get(j, 1)) / V; + } + + double h = mv.h(new double[]{sv.trackTraj.get(k).x, sv.trackTraj.get(k).y}, + mv.measurements.get(k).z, + mv.measurements.get(k).wireLine[0]); + + double signMeas = 1; + double sign = 1; + if(mv.measurements.get(k).doca[1]!=-99 || + !(Math.abs(mv.measurements.get(k).doca[0])<0.5 && mv.measurements.get(k).doca[1]==-99 ) ) { //use LR only for double hits && large enough docas + signMeas = Math.signum(mv.measurements.get(k).doca[0]); + sign = Math.signum(h); + } else { + signMeas = Math.signum(h); + sign = Math.signum(h); + } + //if(this.interNum>1) + // signMeas = Math.signum(h); + double c2 = ((signMeas*Math.abs(mv.measurements.get(k).doca[0]) - sign*Math.abs(h)) + * (signMeas*Math.abs(mv.measurements.get(k).doca[0]) - sign*Math.abs(h)) / V); + //if(signMeas!=Math.signum(h) && this.interNum>1) System.out.println(sv.trackTraj.get(k).printInfo()+" h "+(float)h); + double x_filt = sv.trackTraj.get(k).x + K[0] * (signMeas*Math.abs(mv.measurements.get(k).doca[0]) - sign*Math.abs(h)); + double y_filt = sv.trackTraj.get(k).y + K[1] * (signMeas*Math.abs(mv.measurements.get(k).doca[0]) - sign*Math.abs(h)); + double tx_filt = sv.trackTraj.get(k).tx + K[2] * (signMeas*Math.abs(mv.measurements.get(k).doca[0]) - sign*Math.abs(h)); + double ty_filt = sv.trackTraj.get(k).ty + K[3] * (signMeas*Math.abs(mv.measurements.get(k).doca[0]) - sign*Math.abs(h)); + double Q_filt = sv.trackTraj.get(k).Q + K[4] * (signMeas*Math.abs(mv.measurements.get(k).doca[0]) - sign*Math.abs(h)); + + //USE THE DOUBLE HIT + if(mv.measurements.get(k).doca[1]!=-99) { + //now filter using the other Hit + V = mv.measurements.get(k).unc[1]*KFScale; + H = mv.H(new double[]{x_filt, y_filt}, + mv.measurements.get(k).z, + mv.measurements.get(k).wireLine[1]); + CaInv = this.filterCovMat(H, sv.trackCov.get(k).covMat, V); + if (CaInv != null) { + sv.trackCov.get(k).covMat = CaInv; + } else { + return; + } + for (int j = 0; j < 5; j++) { + // the gain matrix + K[j] = (H[0] * sv.trackCov.get(k).covMat.get(j, 0) + + H[1] * sv.trackCov.get(k).covMat.get(j, 1)) / V; + } + h=mv.h(new double[]{x_filt, y_filt}, + mv.measurements.get(k).z, + mv.measurements.get(k).wireLine[1]); + + signMeas = Math.signum(mv.measurements.get(k).doca[1]); + sign = Math.signum(h); + //if(this.interNum>1) + // signMeas = Math.signum(h); + + x_filt += K[0] * (signMeas*Math.abs(mv.measurements.get(k).doca[1]) - sign*Math.abs(h)); + y_filt += K[1] * (signMeas*Math.abs(mv.measurements.get(k).doca[1]) - sign*Math.abs(h)); + tx_filt += K[2] * (signMeas*Math.abs(mv.measurements.get(k).doca[1]) - sign*Math.abs(h)); + ty_filt += K[3] * (signMeas*Math.abs(mv.measurements.get(k).doca[1]) - sign*Math.abs(h)); + Q_filt += K[4] * (signMeas*Math.abs(mv.measurements.get(k).doca[1]) - sign*Math.abs(h)); + + c2 += ((signMeas*Math.abs(mv.measurements.get(k).doca[1]) - sign*Math.abs(h)) + * (signMeas*Math.abs(mv.measurements.get(k).doca[1]) - sign*Math.abs(h)) / V); + } + + chi2kf += c2; + if(filterOn) { + sv.trackTraj.get(k).x = x_filt; + sv.trackTraj.get(k).y = y_filt; + sv.trackTraj.get(k).tx = tx_filt; + sv.trackTraj.get(k).ty = ty_filt; + sv.trackTraj.get(k).Q = Q_filt; + } + } + } + + @SuppressWarnings("unused") + private void smooth(int sector, int k) { + this.chi2 = 0; + if (sv.trackTraj.get(k) != null && sv.trackCov.get(k).covMat != null) { + sv.transport(sector, k, 0, sv.trackTraj.get(k), sv.trackCov.get(k)); + for (int k1 = 0; k1 < k; k1++) { + sv.transport(sector, k1, k1 + 1, sv.trackTraj.get(k1), sv.trackCov.get(k1)); + this.filter(k1 + 1); + } + } + } + + public Matrix propagateToVtx(int sector, double Zf) { + return sv.transport(sector, 0, Zf, sv.trackTraj.get(0), sv.trackCov.get(0)); + + } + private void calcFinalChisq(int sector) { + int k = sv.Z.length - 1; + this.chi2 = 0; + double path = 0; + double[] nRj = new double[3]; + + kfStateVecsAlongTrajectory = new ArrayList<>(); + if (sv.trackTraj.get(k) != null && sv.trackCov.get(k).covMat != null) { + sv.transport(sector, sv.Z.length - 1, 0, + sv.trackTraj.get(sv.Z.length - 1), + sv.trackCov.get(sv.Z.length - 1)); + org.jlab.rec.dc.trajectory.StateVec svc = + new org.jlab.rec.dc.trajectory.StateVec(sv.trackTraj.get(0).x, + sv.trackTraj.get(0).y, + sv.trackTraj.get(0).tx, + sv.trackTraj.get(0).ty); + svc.setZ(sv.trackTraj.get(0).z); + svc.setB(sv.trackTraj.get(0).B); + path += sv.trackTraj.get(0).deltaPath; + svc.setPathLength(path); + double V0 = mv.measurements.get(0).unc[0]; + double h0 = mv.h(new double[]{sv.trackTraj.get(0).x, sv.trackTraj.get(0).y}, + mv.measurements.get(0).z, + mv.measurements.get(0).wireLine[0]); + svc.setProjector(mv.measurements.get(0).wireLine[0].origin().x()); + svc.setProjectorDoca(h0); + kfStateVecsAlongTrajectory.add(svc); + double res = (mv.measurements.get(0).doca[0] - h0); + chi2 += (mv.measurements.get(0).doca[0] - h0) * (mv.measurements.get(0).doca[0] - h0) / V0; + nRj[mv.measurements.get(0).region-1]+=res*res/mv.measurements.get(0).error; + //USE THE DOUBLE HIT + if(mv.measurements.get(0).doca[1]!=-99) { + V0 = mv.measurements.get(0).unc[1]; + h0 = mv.h(new double[]{sv.trackTraj.get(0).x, sv.trackTraj.get(0).y}, + mv.measurements.get(0).z, + mv.measurements.get(0).wireLine[1]); + res = (mv.measurements.get(0).doca[1] - h0); + chi2 += (mv.measurements.get(0).doca[1] - h0) * (mv.measurements.get(0).doca[1] - h0) / V0; + nRj[mv.measurements.get(0).region-1]+=res*res/mv.measurements.get(0).error; + svc.setProjector(mv.measurements.get(0).wireLine[1].origin().x()); + svc.setProjectorDoca(h0); + kfStateVecsAlongTrajectory.add(svc); + } + for (int k1 = 0; k1 < k; k1++) { + sv.transport(sector, k1, k1 + 1, sv.trackTraj.get(k1), sv.trackCov.get(k1)); + + double V = mv.measurements.get(k1 + 1).unc[0]; + double h = mv.h(new double[]{sv.trackTraj.get(k1 + 1).x, sv.trackTraj.get(k1 + 1).y}, + mv.measurements.get(k1 + 1).z, + mv.measurements.get(k1 + 1).wireLine[0]); + svc = new org.jlab.rec.dc.trajectory.StateVec(sv.trackTraj.get(k1 + 1).x, + sv.trackTraj.get(k1 + 1).y, + sv.trackTraj.get(k1 + 1).tx, + sv.trackTraj.get(k1 + 1).ty); + svc.setZ(sv.trackTraj.get(k1 + 1).z); + svc.setB(sv.trackTraj.get(k1 + 1).B); + path += sv.trackTraj.get(k1 + 1).deltaPath; + svc.setPathLength(path); + svc.setProjector(mv.measurements.get(k1 + 1).wireLine[0].origin().x()); + svc.setProjectorDoca(h); + kfStateVecsAlongTrajectory.add(svc); + res = (mv.measurements.get(k1 + 1).doca[0] - h); + chi2 += (mv.measurements.get(k1 + 1).doca[0] - h) * (mv.measurements.get(k1 + 1).doca[0] - h) / V; + nRj[mv.measurements.get(k1 + 1).region-1]+=res*res/V; + //USE THE DOUBLE HIT + if(mv.measurements.get(k1 + 1).doca[1]!=-99) { + V = mv.measurements.get(k1 + 1).unc[1]; + h = mv.h(new double[]{sv.trackTraj.get(k1 + 1).x, sv.trackTraj.get(k1 + 1).y}, + mv.measurements.get(k1 + 1).z, + mv.measurements.get(k1 + 1).wireLine[1]); + res = (mv.measurements.get(k1 + 1).doca[1] - h); + chi2 += (mv.measurements.get(k1 + 1).doca[1] - h) * (mv.measurements.get(k1 + 1).doca[1] - h) / V; + nRj[mv.measurements.get(k1 + 1).region-1]+=res*res/V; + svc.setProjector(mv.measurements.get(k1 + 1).wireLine[1].origin().x()); + svc.setProjectorDoca(h); + kfStateVecsAlongTrajectory.add(svc); + } + } + } + + } + + /*private boolean isNonsingular(Matrix mat) { + double matDet = mat.det(); + return Math.abs(matDet) >= 1.e-30; + }*/ + +} diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/fit/MeasVecs.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/fit/MeasVecsDoca.java similarity index 60% rename from reconstruction/dc/src/main/java/org/jlab/rec/dc/track/fit/MeasVecs.java rename to reconstruction/dc/src/main/java/org/jlab/rec/dc/track/fit/MeasVecsDoca.java index 702cf014e1..b5495fa5fb 100644 --- a/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/fit/MeasVecs.java +++ b/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/fit/MeasVecsDoca.java @@ -4,45 +4,48 @@ import java.util.Collections; import java.util.List; import org.jlab.detector.geant4.v2.DCGeant4Factory; +import org.jlab.geom.prim.Line3D; +import org.jlab.geom.prim.Point3D; +import org.jlab.geom.prim.Vector3D; import org.jlab.rec.dc.hit.FittedHit; import org.jlab.rec.dc.track.Track; -public class MeasVecs { +public class MeasVecsDoca { public List measurements = new ArrayList(); public int ndf=0; - /** - * The state projector - it projects the state onto the measurement - * - * @param stateV the state vector - * @param s the superlayer of the measurement (0..1) - * @return a double array corresponding to the 2 entries of the projector - * matrix - */ - public double[] H(double y, int s, double w, double l) { + + public double[] H(double[] stateV, double Z, Line3D wireLine) { double[] hMatrix = new double[2]; - hMatrix[0] = 1; - hMatrix[1] = -Math.tan((Math.toRadians(s * 6.))); - // add geometric corrections - //hMatrix[1]-= w*(4./l)*(1 - y/(l/2.)); + double[] stateVec = new double[2]; + double Err = 0.025; + double[][] Result = new double[2][2]; + for(int i = 0; i < 2; i++) { + stateVec[0] = stateV[0] + (double)Math.pow(-1, i) * Err; + stateVec[1] = stateV[1]; + Result[i][0] = h(stateVec, Z, wireLine); + } + for(int i = 0; i < 2; i++) { + stateVec[0] = stateV[0]; + stateVec[1] = stateV[1] + (double)Math.pow(-1, i) * Err; + Result[i][1] = h(stateVec, Z, wireLine); + } + hMatrix[0] = (Result[0][0]-Result[1][0])/(2.*Err); + hMatrix[1] = (Result[0][1]-Result[1][1])/(2.*Err); + return hMatrix; } - /** - * The projected measurement derived from the stateVector at the measurement - * site - * - * @param stateV the state vector - * @param s the superlayer (0..1) - * @return projected measurement - */ - public double h(double[] stateV, int s, double w, double l) { - - double val = stateV[0] - Math.tan((Math.toRadians(s * 6.))) * stateV[1]; - // add geometric corrections - val+= w; - return val; + public double h(double[] stateV, double Z, Line3D wireLine) { + + Line3D WL = new Line3D(); + WL.copy(wireLine); + WL.copy(WL.distance(new Point3D(stateV[0], stateV[1], Z))); + + //System.out.println(Math.signum(-WL.direction().x())+ + // wireLine.origin().toString()+WL.toString()+" "+stateV[0]+" ,"+stateV[1]); + return WL.length()*Math.signum(-WL.direction().x()); } public void setMeasVecs(Track trkcand, DCGeant4Factory DcDetector) { @@ -72,19 +75,30 @@ public void setMeasVecs(Track trkcand, DCGeant4Factory DcDetector) { // continue; //} - HitOnTrack hot = new HitOnTrack(slayr, X, Z, trkcand.get(c).get(s).get(h).get_WireLength(), trkcand.get(c).get(s).get(h).get_WireMaxSag()); + HitOnTrack hot = new HitOnTrack(slayr, X, Z, + trkcand.get(c).get(s).get(h).get_WireMaxSag(), + trkcand.get(c).get(s).get(h).get_WireLine() + ); double err_sl1 = trkcand.get(c).get(s).get_fittedCluster().get_clusterLineFitSlopeErr(); double err_it1 = trkcand.get(c).get(s).get_fittedCluster().get_clusterLineFitInterceptErr(); double err_cov1 = trkcand.get(c).get(s).get_fittedCluster().get_clusterLineFitSlIntCov(); - hot._Unc = Math.sqrt(err_sl1 * err_sl1 * Z * Z + err_it1 * err_it1); + hot._Unc[0] = Math.sqrt(err_sl1 * err_sl1 * Z * Z + err_it1 * err_it1); hot._hitError = err_sl1 * err_sl1 * Z * Z + err_it1 * err_it1 + 2 * Z * err_cov1 + trkcand.get(c).get(s).get(h).get_DocaErr()*trkcand.get(c).get(s).get(h).get_DocaErr(); //if(trkcand.get(c).get(s).get(h).get_Time()/CCDBConstants.getTMAXSUPERLAYER()[trkcand.get(c).get(s).get(h).get_Sector()-1][trkcand.get(c).get(s).get(h).get_Superlayer()-1]<1.1) // hot._hitError = 100000; //exclude outoftimers from fit hot.region = trkcand.get(c).get(s).get(h).get_Region(); - //if(Math.abs(trkcand.get(c).get(s).get(h).get_Residual())<1) - hOTS.add(hot); + + hot._doca[0] = trkcand.get(c).get(s).get(h).get_ClusFitDoca(); + + double LR = Math.signum(trkcand.get(c).get(s).get(h).get_XWire()-trkcand.get(c).get(s).get(h).get_X()); + hot._doca[0]*=LR; + //hot._hitError = err_sl1 * err_sl1 * Z * Z + err_it1 * err_it1 + 2 * Z * err_cov1 + trk.get_ListOfHBSegments().get(s).get(h).get_DocaErr()*trk.get_ListOfHBSegments().get(s).get(h).get_DocaErr(); + hot._hitError = trkcand.get(c).get(s).get(h).get_DocaErr()*trkcand.get(c).get(s).get(h).get_DocaErr(); + //System.out.println(" Z "+Z+" ferr "+(float)(hot._Unc /(hot._hitError/4.))); + hot._Unc[0] = hot._hitError; + hOTS.add(hot); } } @@ -95,12 +109,14 @@ public void setMeasVecs(Track trkcand, DCGeant4Factory DcDetector) { for (int i = 0; i < hOTS.size(); i++) { if (i > 0) { if (Math.abs(hOTS.get(i - 1)._Z - hOTS.get(i)._Z)<0.01) { - hOTS.get(i - 1)._X = (hOTS.get(i - 1)._X / (hOTS.get(i - 1)._Unc * hOTS.get(i - 1)._Unc) + hOTS.get(i)._X / (hOTS.get(i)._Unc * hOTS.get(i)._Unc)) / (1. / (hOTS.get(i - 1)._Unc * hOTS.get(i - 1)._Unc) + 1. / (hOTS.get(i)._Unc * hOTS.get(i)._Unc)); - //hOTS.get(i-1)._hitError = 1./Math.sqrt(1./(hOTS.get(i-1)._hitError*hOTS.get(i-1)._hitError) + 1./(hOTS.get(i)._hitError*hOTS.get(i)._hitError) ); + hOTS.get(i - 1)._doca[1] = hOTS.get(i)._doca[0]; + hOTS.get(i - 1)._Unc[1] = hOTS.get(i)._Unc[0]; + hOTS.get(i - 1)._wireLine[1] = hOTS.get(i)._wireLine[0]; hOTS.remove(i); } } } + measurements = new ArrayList(hOTS.size()); @@ -112,8 +128,9 @@ public void setMeasVecs(Track trkcand, DCGeant4Factory DcDetector) { meas.error = hOTS.get(i)._hitError; meas.unc = hOTS.get(i)._Unc; //uncertainty used in KF fit meas.tilt = hOTS.get(i)._tilt; - meas.wireLen = hOTS.get(i)._wireLen; + meas.doca = hOTS.get(i)._doca; meas.wireMaxSag = hOTS.get(i)._wireMaxSag; + meas.wireLine = hOTS.get(i)._wireLine; this.measurements.add(i, meas); } } @@ -132,25 +149,19 @@ void setMeasVecsFromHB(Track trk, DCGeant4Factory DcDetector) { double Z = hitOnTrk.get_Z(); double X = sl1 * Z + it1; - - //exclude hits that have poor segment - //if ((trkcand.get(c).get(s).get(h).get_X() - X) / (trkcand.get(c).get(s).get(h).get_CellSize() / FastMath.cos(Math.toRadians(6.))) > 1.5) { - //if(Math.abs(trk.get_ListOfHBSegments().get(s).get(h).get_Residual())>1) { - // continue; - //} - - HitOnTrack hot = new HitOnTrack(slayr, X, Z, hitOnTrk.get_WireLength(), hitOnTrk.get_WireMaxSag()); - double err_sl1 = trk.get_ListOfHBSegments().get(s).get_fittedCluster().get_clusterLineFitSlopeErr(); - - double err_it1 = trk.get_ListOfHBSegments().get(s).get_fittedCluster().get_clusterLineFitInterceptErr(); - double err_cov1 = trk.get_ListOfHBSegments().get(s).get_fittedCluster().get_clusterLineFitSlIntCov(); - - hot._Unc = Math.sqrt(err_sl1 * err_sl1 * Z * Z + err_it1 * err_it1); - //hot._hitError = err_sl1 * err_sl1 * Z * Z + err_it1 * err_it1 + 2 * Z * err_cov1 + trk.get_ListOfHBSegments().get(s).get(h).get_DocaErr()*trk.get_ListOfHBSegments().get(s).get(h).get_DocaErr(); - hot._hitError = trk.get_ListOfHBSegments().get(s).get(h).get_DocaErr()*trk.get_ListOfHBSegments().get(s).get(h).get_DocaErr()*4; + HitOnTrack hot = new HitOnTrack(slayr, X, Z, + hitOnTrk.get_WireMaxSag(), + hitOnTrk.get_WireLine()); + + hot._doca[0] = trk.get_ListOfHBSegments().get(s).get(h).get_Doca(); + + double LR = Math.signum(trk.get_ListOfHBSegments().get(s).get(h).get_XWire()-trk.get_ListOfHBSegments().get(s).get(h).get_X()); + hot._doca[0]*=LR; + hot._hitError = trk.get_ListOfHBSegments().get(s).get(h).get_DocaErr()*trk.get_ListOfHBSegments().get(s).get(h).get_DocaErr(); + //System.out.println(" Z "+Z+" ferr "+(float)(hot._Unc /(hot._hitError/4.))); + hot._Unc[0] = hot._hitError; hot.region = trk.get_ListOfHBSegments().get(s).get(h).get_Region(); - //if(Math.abs(trk.get_ListOfHBSegments().get(s).get(h).get_Residual())<1) - hOTS.add(hot); + hOTS.add(hot); } } @@ -160,8 +171,9 @@ void setMeasVecsFromHB(Track trk, DCGeant4Factory DcDetector) { for (int i = 0; i < hOTS.size(); i++) { if (i > 0) { if (Math.abs(hOTS.get(i - 1)._Z - hOTS.get(i)._Z)<0.01) { - hOTS.get(i - 1)._X = (hOTS.get(i - 1)._X / (hOTS.get(i - 1)._Unc * hOTS.get(i - 1)._Unc) + hOTS.get(i)._X / (hOTS.get(i)._Unc * hOTS.get(i)._Unc)) / (1. / (hOTS.get(i - 1)._Unc * hOTS.get(i - 1)._Unc) + 1. / (hOTS.get(i)._Unc * hOTS.get(i)._Unc)); - //hOTS.get(i-1)._hitError = 1./Math.sqrt(1./(hOTS.get(i-1)._hitError*hOTS.get(i-1)._hitError) + 1./(hOTS.get(i)._hitError*hOTS.get(i)._hitError) ); + hOTS.get(i - 1)._doca[1] = hOTS.get(i)._doca[0]; + hOTS.get(i - 1)._Unc[1] = hOTS.get(i)._Unc[0]; + hOTS.get(i - 1)._wireLine[1] = hOTS.get(i)._wireLine[0]; hOTS.remove(i); } } @@ -175,10 +187,13 @@ void setMeasVecsFromHB(Track trk, DCGeant4Factory DcDetector) { meas.z = hOTS.get(i)._Z; meas.region = hOTS.get(i).region; meas.error = hOTS.get(i)._hitError; - meas.unc = hOTS.get(i)._Unc; //uncertainty used in KF fit + meas.unc[0] = hOTS.get(i)._Unc[0]; //uncertainty used in KF fit + meas.unc[1] = hOTS.get(i)._Unc[1]; //uncertainty used in KF fit meas.tilt = hOTS.get(i)._tilt; - meas.wireLen = hOTS.get(i)._wireLen; + meas.doca = hOTS.get(i)._doca; meas.wireMaxSag = hOTS.get(i)._wireMaxSag; + meas.wireLine[0] = hOTS.get(i)._wireLine[0]; + meas.wireLine[1] = hOTS.get(i)._wireLine[1]; this.measurements.add(i, meas); //System.out.println(" measurement "+i+" = "+meas.x+" at "+meas.z); } @@ -189,14 +204,16 @@ public class MeasVec { final int k; public double z; public double x; - public double unc; - public int tilt; + public double[] unc = new double[2]; + public double tilt; public double error; - public double wireLen; + public double[] doca = new double[2]; public double wireMaxSag; - boolean reject = false; + public Line3D[] wireLine = new Line3D[2]; + public boolean reject = false; int region; + MeasVec(int k) { this.k = k; } @@ -208,24 +225,25 @@ private class HitOnTrack implements Comparable { public double _hitError; private double _X; private double _Z; - private double _Unc; - private int _tilt; - private double _wireLen; + private double[] _Unc = new double[2]; + private double _tilt; + private double[] _doca = new double[2]; private double _wireMaxSag; + private Line3D[] _wireLine = new Line3D[2]; private int region; - HitOnTrack(int superlayer, double X, double Z, double wirelen, double wiremaxsag) { + HitOnTrack(int superlayer, double X, double Z, double wiremaxsag, Line3D wireLine) { _X = X; _Z = Z; - _wireLen = wirelen; _wireMaxSag = wiremaxsag; + _wireLine[0] = wireLine; + _doca[0] = -99; + _doca[1] = -99; + _Unc[0] = 1; + _Unc[1] = 1; - int s = (int) (superlayer) % 2; - int tilt = 1; - if (s == 0) { - tilt = -1; - } - _tilt = tilt; + //use stereo angle in fit based on wire direction + _tilt = 90-Math.toDegrees(wireLine.direction().asUnit().angle(new Vector3D(1,0,0))); } @Override diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/fit/RungeKutta.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/fit/RungeKuttaDoca.java similarity index 93% rename from reconstruction/dc/src/main/java/org/jlab/rec/dc/track/fit/RungeKutta.java rename to reconstruction/dc/src/main/java/org/jlab/rec/dc/track/fit/RungeKuttaDoca.java index 088b97bc07..96ab61e7bf 100644 --- a/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/fit/RungeKutta.java +++ b/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/fit/RungeKuttaDoca.java @@ -5,16 +5,15 @@ */ package org.jlab.rec.dc.track.fit; -import Jama.Matrix; +//import Jama.Matrix; +import org.jlab.jnp.matrix.*; import java.util.ArrayList; import org.jlab.clas.swimtools.Swim; -import org.jlab.rec.dc.Constants; - /** * * @author ziegler */ -public class RungeKutta { +public class RungeKuttaDoca { private final float[] _b = new float[3]; final double v = 0.0029979245; @@ -27,7 +26,7 @@ public class RungeKutta { private final ArrayList jk3; private final ArrayList jk4; - public RungeKutta() { + public RungeKuttaDoca() { this.k1 = new ArrayList(4); this.k2 = new ArrayList(4); this.k3 = new ArrayList(4); @@ -39,7 +38,7 @@ public RungeKutta() { } - public void SwimToZ(int sector, StateVecs.StateVec fVec, Swim dcSwim, double z0, float[] bf){ + public void SwimToZ(int sector, StateVecsDoca.StateVec fVec, Swim dcSwim, double z0, float[] bf){ double stepSize = 1.0; dcSwim.Bfield(sector, fVec.x, fVec.y, fVec.z, bf); @@ -76,7 +75,7 @@ public void SwimToZ(int sector, StateVecs.StateVec fVec, Swim dcSwim, double z0, } void RK4transport(int sector, double q, double x0, double y0, double z0, double tx0, double ty0, double h, Swim swimmer, - double dPath, StateVecs.StateVec fVec) { // lab system = 1, TSC =0 + double dPath, StateVecsDoca.StateVec fVec) { // lab system = 1, TSC =0 swimmer.Bfield(sector, x0, y0, z0, _b); double x1 = tx0; @@ -124,7 +123,7 @@ void RK4transport(int sector, double q, double x0, double y0, double z0, double } // void RK4transport(int sector, double q, double x0, double y0, double z0, double tx0, double ty0, double h, Swim swimmer, - StateVecs.CovMat covMat, StateVecs.StateVec fVec, StateVecs.CovMat fCov, double mass, double dPath) { + StateVecsDoca.CovMat covMat, StateVecsDoca.StateVec fVec, StateVecsDoca.CovMat fCov, double dPath) { // Jacobian: double[][] u = new double[5][5]; double[][] C = new double[5][5]; @@ -221,9 +220,9 @@ void RK4transport(int sector, double q, double x0, double y0, double z0, double double delx_delq0_3 = deltx_delq0_0+0.5*h*deltx_delq0_2; double dely_delq0_3 = delty_delq0_0+0.5*h*delty_delq0_2; - double deltx_delq0_3 = this.deltx_delq0_next(q,v,tx0+0.5*h*tx2,ty0+0.5*ty2,_b[0],_b[1],_b[2], + double deltx_delq0_3 = this.deltx_delq0_next(q,v,tx0+0.5*h*tx2,ty0+0.5*h*ty2,_b[0],_b[1],_b[2], deltx_delq0_0+0.5*h*deltx_delq0_2,delty_delq0_0+0.5*h*delty_delq0_2); - double delty_delq0_3 = this.delty_delq0_next(q,v,tx0+0.5*h*tx2,ty0+0.5*ty2,_b[0],_b[1],_b[2], + double delty_delq0_3 = this.delty_delq0_next(q,v,tx0+0.5*h*tx2,ty0+0.5*h*ty2,_b[0],_b[1],_b[2], deltx_delq0_0+0.5*h*deltx_delq0_2,delty_delq0_0+0.5*h*delty_delq0_2); swimmer.Bfield(sector, x0+h*x3, y0+h*y3, z0+h, _b); @@ -294,31 +293,28 @@ void RK4transport(int sector, double q, double x0, double y0, double z0, double C[i1][4] = u[i1][4]; } - // Q process noise matrix estimate - double p = Math.abs(1. / q); - double pz = p / Math.sqrt(1 + tx * tx + ty * ty); - double px = tx * pz; - double py = ty * pz; - - double t_ov_X0 = Math.signum(h) * h / Constants.ARGONRADLEN; //path length in radiation length units = t/X0 [true path length/ X0] ; Ar radiation length = 14 cm - - - double beta = p / Math.sqrt(p * p + mass * mass); // use particle momentum - double cosEntranceAngle = Math.abs((x * px + y * py + z * pz) / (Math.sqrt(x * x + y * y + z * z) * p)); - double pathLength = t_ov_X0 / cosEntranceAngle; - - double sctRMS = (0.0136 / (beta * p)) * Math.sqrt(pathLength) * (1 + 0.038 * Math.log(pathLength)); // Highland-Lynch-Dahl formula - - double cov_txtx = (1 + tx * tx) * (1 + tx * tx + ty * ty) * sctRMS * sctRMS; - double cov_tyty = (1 + ty * ty) * (1 + tx * tx + ty * ty) * sctRMS * sctRMS; - double cov_txty = tx * ty * (1 + tx * tx + ty * ty) * sctRMS * sctRMS; - - if (h > 0) { - C[2][2] += cov_txtx; - C[2][3] += cov_txty; - C[3][2] += cov_txty; - C[3][3] += cov_tyty; - } +// // Q process noise matrix estimate +// double p = Math.abs(1. / q); +// +// double X0 = fVec.getX0(z0+h/2); +// double t_ov_X0 = Math.sqrt((x0-x)*(x0-x)+(y0-y)*(y0-y)+h*h) / X0;//path length in radiation length units = t/X0 [true path length/ X0] ; Ar radiation length = 14 cm +// +// double beta = p / Math.sqrt(p * p + mass * mass); //use particle momentum +// beta = 1; +// +// double sctRMS = ((0.0136)/(beta*p))*Math.sqrt(t_ov_X0*Math.sqrt(1 + tx0 * tx0 + ty0 * ty0))* +// (1 + 0.038 * Math.log(t_ov_X0*Math.sqrt(1 + tx0 * tx0 + ty0 * ty0))); +// +// double cov_txtx = (1 + tx0 * tx0) * (1 + tx0 * tx0 + ty0 * ty0) * sctRMS * sctRMS; +// double cov_tyty = (1 + ty0 * ty0) * (1 + tx0 * tx0 + ty0 * ty0) * sctRMS * sctRMS; +// double cov_txty = tx0 * ty0 * (1 + tx0 * tx0 + ty0 * ty0) * sctRMS * sctRMS; +// +// if (h > 0) { +// C[2][2] += cov_txtx; +// C[2][3] += cov_txty; +// C[3][2] += cov_txty; +// C[3][3] += cov_tyty; +// } fVec.x = x; fVec.y = y ; @@ -328,9 +324,9 @@ void RK4transport(int sector, double q, double x0, double y0, double z0, double fVec.Q = q; fVec.B = Math.sqrt(_b[0]*_b[0]+_b[1]*_b[1]+_b[2]*_b[2]); fVec.deltaPath = Math.sqrt((x0-x)*(x0-x)+(y0-y)*(y0-y)+h*h)+dPath; - fCov.covMat=new Matrix(C); - - + fCov.covMat.set(C); + //System.out.println("Transported matrix"); + //Matrix5x5.show(fCov.covMat); } @@ -508,7 +504,7 @@ private void getjRKn(int sector, ArrayList k1, ArrayList jk1, Ar jk2.add(10, deltx_delq0_2 ); jk2.add(11, delty_delq0_2 ); } - + } diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/fit/StateVecs.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/fit/StateVecs.java deleted file mode 100755 index 24522839ae..0000000000 --- a/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/fit/StateVecs.java +++ /dev/null @@ -1,314 +0,0 @@ -package org.jlab.rec.dc.track.fit; - -import Jama.Matrix; -import java.util.HashMap; -import java.util.Map; -import org.jlab.clas.clas.math.FastMath; -import org.jlab.clas.swimtools.Swim; -import org.jlab.rec.dc.track.Track; - -public class StateVecs { - private double Bmax = 2.366498; // averaged - - final double speedLight = 0.002997924580; - public double[] Z; - // public List bfieldPoints = new ArrayList(); - public Map trackTraj = new HashMap(); - public Map trackCov = new HashMap(); - - - public StateVec StateVec; - public CovMat CovMat; - public Matrix F; - private final double[] A = new double[2]; - private final double[] dA = new double[4]; - private final float[] bf = new float[3]; - private final float[] lbf = new float[3]; - private Swim dcSwim; - private RungeKutta rk; - - /** - * State vector representing the track in the sector coordinate system at the measurement layer - */ - public StateVecs(Swim swimmer) { - //Max Field Location: (phi, rho, z) = (29.50000, 44.00000, 436.00000) - // get the maximum value of the B field - dcSwim = swimmer; - rk = new RungeKutta(); - } - - /** - * - * @param i initial state vector index - * @param f final state vector index - * @param iVec state vector at the initial index - * @param covMat state covariance matrix at the initial index - */ - public void transport(int sector, int i, int f, StateVec iVec, CovMat covMat) { // s = signed step-size - if(iVec==null) - return; - double stepSize = 1.0; - StateVecs.StateVec fVec = new StateVec(f); - CovMat fCov = new CovMat(f); - fVec.x = iVec.x; - fVec.y = iVec.y; - fVec.z = iVec.z; - fVec.tx = iVec.tx; - fVec.ty = iVec.ty; - fVec.Q = iVec.Q; - fVec.B = iVec.B; - fCov.covMat = covMat.covMat; - - double s = 0; - double z = Z[i]; - double BatMeas = iVec.B; - - while(Math.signum(Z[f] - Z[i]) *zMath.signum(Z[f] - Z[i]) *Z[f]) - s=Math.signum(Z[f] - Z[i]) *Math.abs(Z[f]-z); - - rk.RK4transport( sector, Q, x, y, z, tx, ty, s, dcSwim, - covMat, fVec, fCov, mass, dPath); - - if( Math.abs(fVec.B - BatMeas)<0.0001) - stepSize*=2; - - BatMeas = fVec.B; - } - - this.trackTraj.put(f, fVec); - this.trackCov.put(f, fCov); - } - - /** - * - * @param i initial state vector index - * @param f final state vector index - * @param iVec state vector at the initial index - * @param covMat state covariance matrix at the initial index - */ - public void transportFixed(int sector, int i, int f, StateVec iVec, CovMat covMat) { // s = signed step-size - if(iVec==null) - return; - double stepSize = 0.5; - - StateVecs.StateVec fVec = new StateVec(f); - CovMat fCov = new CovMat(f); - fVec.x = iVec.x; - fVec.y = iVec.y; - fVec.z = iVec.z; - fVec.tx = iVec.tx; - fVec.ty = iVec.ty; - fVec.Q = iVec.Q; - fCov.covMat = covMat.covMat; - int nSteps = (int) (Math.abs((Z[i] - Z[f]) / stepSize) + 1); - - double s = (Z[f] - Z[i]) / (double) nSteps; - double z = Z[i]; - - for (int j = 0; j < nSteps; j++) { - // get the sign of the step - if (j == nSteps - 1) { - s = Math.signum(Z[f] - Z[i]) * Math.abs(z - Z[f]); - } - //System.out.println(" RK step num "+(j+1)+" = "+(float)s+" nSteps = "+nSteps); - double x = fVec.x; - double y = fVec.y; - z = fVec.z; - double tx = fVec.tx; - double ty = fVec.ty; - double Q = fVec.Q; - double dPath = fVec.deltaPath; - covMat.covMat = fCov.covMat; - - rk.RK4transport( sector, Q, x, y, z, tx, ty, s, dcSwim, - covMat, fVec, fCov, mass, dPath); - - } - - this.trackTraj.put(f, fVec); - this.trackCov.put(f, fCov); - } - - - private void A(double tx, double ty, double Bx, double By, double Bz, double[] a) { - - double C = Math.sqrt(1 + tx * tx + ty * ty); - a[0] = C * (ty * (tx * Bx + Bz) - (1 + tx * tx) * By); - a[1] = C * (-tx * (ty * By + Bz) + (1 + ty * ty) * Bx); - } - - private void delA_delt(double tx, double ty, double Bx, double By, double Bz, double[] dela_delt) { - - double C2 = 1 + tx * tx + ty * ty; - double C = Math.sqrt(1 + tx * tx + ty * ty); - double Ax = C * (ty * (tx * Bx + Bz) - (1 + tx * tx) * By); - double Ay = C * (-tx * (ty * By + Bz) + (1 + ty * ty) * Bx); - - dela_delt[0] = tx * Ax / C2 + C * (ty * Bx - 2 * tx * By); //delAx_deltx - dela_delt[1] = ty * Ax / C2 + C * (tx * Bx + Bz); //delAx_delty - dela_delt[2] = tx * Ay / C2 + C * (-ty * By - Bz); //delAy_deltx - dela_delt[3] = ty * Ay / C2 + C * (-tx * By + 2 * ty * Bx); //delAy_delty - } - - - private double mass = 0.13957018; - public void setMass(int hypo, double mass) { - - switch (hypo) { - case 0: - mass = 0.000510998; - break; - case 1: - mass = 0.13957018; - break; - case 2: - mass = 0.493677; - break; - case 3: - mass = 0.105658369; - break; - case 4: - mass = 0.938272029; - break; - } - } - - - /** - * - * @param trkcand the track candidate - * @param z0 the value in z to which the track is swam back to - * @param kf the final state measurement index - */ - public void init(Track trkcand, double z0, KFitter kf) { - - if (trkcand.get_StateVecAtReg1MiddlePlane() != null) { - - StateVec initSV = new StateVec(0); - initSV.x = trkcand.get_StateVecAtReg1MiddlePlane().x(); - initSV.y = trkcand.get_StateVecAtReg1MiddlePlane().y(); - initSV.z = trkcand.get(0).get_Point().z(); - initSV.tx = trkcand.get_StateVecAtReg1MiddlePlane().tanThetaX(); - initSV.ty = trkcand.get_StateVecAtReg1MiddlePlane().tanThetaY(); - initSV.Q = trkcand.get_Q() / trkcand.get_P(); - - rk.SwimToZ(trkcand.get(0).get_Sector(), initSV, dcSwim, z0, bf); - - this.trackTraj.put(0, initSV); - } else { - kf.setFitFailed = true; - return; - } - //System.out.println((0)+"] init "+this.trackTraj.get(0).x+","+this.trackTraj.get(0).y+","+ - // this.trackTraj.get(0).z+","+this.trackTraj.get(0).tx+","+this.trackTraj.get(0).ty+" "+1/this.trackTraj.get(0).Q); - double err_sl1 = trkcand.get(0).get_Segment1().get_fittedCluster().get_clusterLineFitSlopeErr(); - double err_sl2 = trkcand.get(0).get_Segment2().get_fittedCluster().get_clusterLineFitSlopeErr(); - double err_it1 = trkcand.get(0).get_Segment1().get_fittedCluster().get_clusterLineFitInterceptErr(); - double err_it2 = trkcand.get(0).get_Segment2().get_fittedCluster().get_clusterLineFitInterceptErr(); - double wy_over_wx = (FastMath.cos(Math.toRadians(6.)) / FastMath.sin(Math.toRadians(6.))); - - double eux = 0.5 * Math.sqrt(err_sl1 * err_sl1 + err_sl2 * err_sl2); - double euy = 0.5 * wy_over_wx * Math.sqrt(err_sl1 * err_sl1 + err_sl2 * err_sl2); - double z = trkcand.get(0).get_Point().z(); - double ex = 0.5 * Math.sqrt(err_it1 * err_it1 + err_it2 * err_it2 + z * z * (err_sl1 * err_sl1 + err_sl2 * err_sl2)); - double ey = 0.5 * wy_over_wx * Math.sqrt(err_it1 * err_it1 + err_it2 * err_it2 + z * z * (err_sl1 * err_sl1 + err_sl2 * err_sl2)); - double epSq = 0.001 * trkcand.get_P() * trkcand.get_P(); - - Matrix initCMatrix = new Matrix(new double[][]{ - {ex * ex, 0, 0, 0, 0}, - {0, ey * ey, 0, 0, 0}, - {0, 0, eux * eux, 0, 0}, - {0, 0, 0, euy * euy, 0}, - {0, 0, 0, 0, epSq} - }); - - CovMat initCM = new CovMat(0); - initCM.covMat = initCMatrix; - this.trackCov.put(0, initCM); - } - - - void initFromHB(Track trkcand, double z0, KFitter kf) { - if (trkcand != null && trkcand.getFinalStateVec()!=null - && trkcand.get_CovMat()!=null) { - - StateVec initSV = new StateVec(0); - initSV.x = trkcand.getFinalStateVec().x(); - initSV.y = trkcand.getFinalStateVec().y(); - initSV.z = trkcand.getFinalStateVec().getZ(); - initSV.tx = trkcand.getFinalStateVec().tanThetaX(); - initSV.ty = trkcand.getFinalStateVec().tanThetaY(); - initSV.Q = ((double) trkcand.get_Q())/trkcand.get_P(); - - rk.SwimToZ(trkcand.get(0).get_Sector(), initSV, dcSwim, z0, bf); - this.trackTraj.put(0, initSV); - - CovMat initCM = new CovMat(0); - initCM.covMat = trkcand.get_CovMat(); - this.trackCov.put(0, initCM); - } else { - kf.setFitFailed = true; - return; - } - - } - - public void printMatrix(Matrix C) { - for (int k = 0; k < 5; k++) { - for (int j = 0; j < 5; j++) { - System.out.println("C["+j+"]["+k+"] = "+C.get(j, k)); - } - } - } - - /** - * The state vector representing the track at a given measurement site - */ - public class StateVec { - - final int k; //index - public double z; //z (fixed measurement planes) - public double x; //track x in the tilted sector coordinate system at z - public double y; //track y in the tilted sector coordinate system at z - public double tx; //track px/pz in the tilted sector coordinate system at z - public double ty; //track py/pz in the tilted sector coordinate system at z - public double Q; //track q/p - double B; - double deltaPath; - - StateVec(int k) { - this.k = k; - } - - String printInfo() { - return this.k+"] = "+(float)this.x+", "+(float)this.y+", "+(float)this.z+", " - +(float)this.tx+", "+(float)this.ty+", "+(float)this.Q+" B = "+(float)this.B; - } - } - /** - * The track covariance matrix - */ - public class CovMat { - - final int k; - public Matrix covMat; - - CovMat(int k) { - this.k = k; - } - - } -} diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/fit/StateVecsDoca.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/fit/StateVecsDoca.java new file mode 100644 index 0000000000..34b2f6206f --- /dev/null +++ b/reconstruction/dc/src/main/java/org/jlab/rec/dc/track/fit/StateVecsDoca.java @@ -0,0 +1,560 @@ +package org.jlab.rec.dc.track.fit; + +//import Jama.Matrix; +import org.jlab.jnp.matrix.*; +import java.util.HashMap; +import java.util.Map; +import org.jlab.clas.clas.math.FastMath; +import org.jlab.clas.pdg.PhysicsConstants; +import org.jlab.clas.swimtools.Swim; +import org.jlab.rec.dc.Constants; +import org.jlab.rec.dc.track.Track; +import org.jlab.geom.prim.Point3D; +/** + * + * @author ziegler + */ +public class StateVecsDoca { + private double Bmax = 2.366498; // averaged + + final double speedLight = 0.002997924580; + public double[] Z; + // public List bfieldPoints = new ArrayList(); + public Map trackTraj = new HashMap(); + public Map trackCov = new HashMap(); + + + public StateVec StateVec; + public CovMat CovMat; + public Matrix F = new Matrix(); + private Matrix fMS = new Matrix(); + private Matrix copyMatrix = new Matrix(); + private final double[] A = new double[2]; + private final double[] dA = new double[4]; + private final float[] bf = new float[3]; + private final float[] lbf = new float[3]; + private Swim dcSwim; + private RungeKuttaDoca rk; + + /** + * State vector representing the track in the sector coordinate system at the measurement layer + */ + public StateVecsDoca(Swim swimmer) { + //Max Field Location: (phi, rho, z) = (29.50000, 44.00000, 436.00000) + // get the maximum value of the B field + dcSwim = swimmer; + rk = new RungeKuttaDoca(); + } + + /** + * + * @param i initial state vector index + * @param f final state vector index + * @param iVec state vector at the initial index + * @param covMat state covariance matrix at the initial index + */ + public Matrix transport(int sector, int i, double Zf, StateVec iVec, CovMat covMat) { // s = signed step-size + + double stepSize = 1.0; + StateVecsDoca.StateVec fVec = new StateVec(0); + CovMat fCov = new CovMat(0); + fVec.x = iVec.x; + fVec.y = iVec.y; + fVec.z = iVec.z; + fVec.tx = iVec.tx; + fVec.ty = iVec.ty; + fVec.Q = iVec.Q; + fVec.B = iVec.B; + //fCov.covMat = covMat.covMat; + Matrix5x5.copy(covMat.covMat, fCov.covMat); + double s = 0; + double z = Z[i]; + double BatMeas = iVec.B; + + while(Math.signum(Zf - Z[i]) *zMath.signum(Zf - Z[i]) *Zf) + s=Math.signum(Zf - Z[i]) *Math.abs(Zf-z); + + rk.RK4transport(sector, Q, x, y, z, tx, ty, s, dcSwim, + covMat, fVec, fCov, dPath); + + // Q process noise matrix estimate + + double p = Math.abs(1. / iVec.Q); + + double X0 = this.getX0(z); + double t_ov_X0 = Math.abs(s) / X0;//path length in radiation length units = t/X0 [true path length/ X0] ; Ar radiation length = 14 cm + + double beta = this.beta; + if(beta>1.0 || beta<=0) + beta =1.0; + + double sctRMS = 0; + + if(Math.abs(s)>0) + sctRMS = ((0.0136)/(beta*PhysicsConstants.speedOfLight()*p))*Math.sqrt(t_ov_X0)* + (1 + 0.038 * Math.log(t_ov_X0)); + + + double cov_txtx = (1 + tx * tx) * (1 + tx * tx + ty * ty) * sctRMS * sctRMS; + double cov_tyty = (1 + ty * ty) * (1 + tx * tx + ty * ty) * sctRMS * sctRMS; + double cov_txty = tx * ty * (1 + tx * tx + ty * ty) * sctRMS * sctRMS; + + + //if (Math.signum(Z[f] - Z[i]) > 0) { + fMS.set( + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, cov_txtx, cov_txty, 0, + 0, 0, cov_txty, cov_tyty, 0, + 0, 0, 0, 0, 0 + ); + + Matrix5x5.copy(fCov.covMat, copyMatrix); + Matrix5x5.add(copyMatrix, fMS, fCov.covMat); + + //} + // end add process noise + + if( Math.abs(fVec.B - BatMeas)<0.0001) + stepSize*=2; + + BatMeas = fVec.B; + } + + return fCov.covMat; + } + + /** + * + * @param i initial state vector index + * @param f final state vector index + * @param iVec state vector at the initial index + * @param covMat state covariance matrix at the initial index + */ + public void transport(int sector, int i, int f, StateVec iVec, CovMat covMat) { // s = signed step-size + if(iVec==null) + return; + double stepSize = 1.0; + StateVecsDoca.StateVec fVec = new StateVec(f); + CovMat fCov = new CovMat(f); + fVec.x = iVec.x; + fVec.y = iVec.y; + fVec.z = iVec.z; + fVec.tx = iVec.tx; + fVec.ty = iVec.ty; + fVec.Q = iVec.Q; + fVec.B = iVec.B; + //fCov.covMat = covMat.covMat; + Matrix5x5.copy(covMat.covMat, fCov.covMat); + double s = 0; + double z = Z[i]; + double BatMeas = iVec.B; + + while(Math.signum(Z[f] - Z[i]) *zMath.signum(Z[f] - Z[i]) *Z[f]) + s=Math.signum(Z[f] - Z[i]) *Math.abs(Z[f]-z); + + rk.RK4transport(sector, Q, x, y, z, tx, ty, s, dcSwim, + covMat, fVec, fCov, dPath); + + // Q process noise matrix estimate + + double p = Math.abs(1. / iVec.Q); + + double X0 = this.getX0(z); + double t_ov_X0 = Math.abs(s) / X0;//path length in radiation length units = t/X0 [true path length/ X0] ; Ar radiation length = 14 cm + + double beta = this.beta; + if(beta>1.0 || beta<=0) + beta =1.0; + + double sctRMS = 0; + + if(Math.abs(s)>0) + sctRMS = ((0.0136)/(beta*PhysicsConstants.speedOfLight()*p))*Math.sqrt(t_ov_X0)* + (1 + 0.038 * Math.log(t_ov_X0)); + + + double cov_txtx = (1 + tx * tx) * (1 + tx * tx + ty * ty) * sctRMS * sctRMS; + double cov_tyty = (1 + ty * ty) * (1 + tx * tx + ty * ty) * sctRMS * sctRMS; + double cov_txty = tx * ty * (1 + tx * tx + ty * ty) * sctRMS * sctRMS; + + + //if (Math.signum(Z[f] - Z[i]) > 0) { + fMS.set( + 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, + 0, 0, cov_txtx, cov_txty, 0, + 0, 0, cov_txty, cov_tyty, 0, + 0, 0, 0, 0, 0 + ); + + Matrix5x5.copy(fCov.covMat, copyMatrix); + Matrix5x5.add(copyMatrix, fMS, fCov.covMat); + + //} + // end add process noise + + if( Math.abs(fVec.B - BatMeas)<0.0001) + stepSize*=2; + + BatMeas = fVec.B; + } + this.trackTraj.put(f, fVec); + this.trackCov.put(f, fCov); + } + public double getX0(double z) { + double X0 = Constants.AIRRADLEN; + double tolerance = 0.01; + for(int i = 1; i =Constants.Z[i]-tolerance && z<=Constants.Z[i+1]+tolerance) { + return Constants.ARGONRADLEN; + } + } + + return X0; + } + /** + * + * @param i initial state vector index + * @param f final state vector index + * @param iVec state vector at the initial index + * @param covMat state covariance matrix at the initial index + */ + public void transportFixed(int sector, int i, int f, StateVec iVec, CovMat covMat) { // s = signed step-size + if(iVec==null) + return; + double stepSize = 0.5; + + StateVecsDoca.StateVec fVec = new StateVec(f); + StateVecsDoca.CovMat fCov = new CovMat(f); + fVec.x = iVec.x; + fVec.y = iVec.y; + fVec.z = iVec.z; + fVec.tx = iVec.tx; + fVec.ty = iVec.ty; + fVec.Q = iVec.Q; + fCov.covMat = covMat.covMat; + int nSteps = (int) (Math.abs((Z[i] - Z[f]) / stepSize) + 1); + + double s = (Z[f] - Z[i]) / (double) nSteps; + double z = Z[i]; + + for (int j = 0; j < nSteps; j++) { + // get the sign of the step + if (j == nSteps - 1) { + s = Math.signum(Z[f] - Z[i]) * Math.abs(z - Z[f]); + } + //System.out.println(" RK step num "+(j+1)+" = "+(float)s+" nSteps = "+nSteps); + double x = fVec.x; + double y = fVec.y; + z = fVec.z; + double tx = fVec.tx; + double ty = fVec.ty; + double Q = fVec.Q; + double dPath = fVec.deltaPath; + covMat.covMat = fCov.covMat; + + rk.RK4transport(sector, Q, x, y, z, tx, ty, s, dcSwim, + covMat, fVec, fCov, dPath); + + } + + this.trackTraj.put(f, fVec); + this.trackCov.put(f, fCov); + } + + + private void A(double tx, double ty, double Bx, double By, double Bz, double[] a) { + + double C = Math.sqrt(1 + tx * tx + ty * ty); + a[0] = C * (ty * (tx * Bx + Bz) - (1 + tx * tx) * By); + a[1] = C * (-tx * (ty * By + Bz) + (1 + ty * ty) * Bx); + } + + private void delA_delt(double tx, double ty, double Bx, double By, double Bz, double[] dela_delt) { + + double C2 = 1 + tx * tx + ty * ty; + double C = Math.sqrt(1 + tx * tx + ty * ty); + double Ax = C * (ty * (tx * Bx + Bz) - (1 + tx * tx) * By); + double Ay = C * (-tx * (ty * By + Bz) + (1 + ty * ty) * Bx); + + dela_delt[0] = tx * Ax / C2 + C * (ty * Bx - 2 * tx * By); //delAx_deltx + dela_delt[1] = ty * Ax / C2 + C * (tx * Bx + Bz); //delAx_delty + dela_delt[2] = tx * Ay / C2 + C * (-ty * By - Bz); //delAy_deltx + dela_delt[3] = ty * Ay / C2 + C * (-tx * By + 2 * ty * Bx); //delAy_delty + } + + + private double beta = 1.0; + public void setMass(int hypo, double mass) { + + switch (hypo) { + case 0: + mass = 0.000510998; + break; + case 1: + mass = 0.13957018; + break; + case 2: + mass = 0.493677; + break; + case 3: + mass = 0.105658369; + break; + case 4: + mass = 0.938272029; + break; + } + } + + + /** + * + * @param trkcand the track candidate + * @param z0 the value in z to which the track is swam back to + * @param kf the final state measurement index + */ + public void init(Track trkcand, double z0, KFitterDoca kf, int c) { + + Point3D trkCrs = trkcand.get(c).get_Point(); + Point3D trkCrsD = trkcand.get(c).get_Dir(); + StateVec initSV = new StateVec(0); + initSV.x = trkCrs.x(); + initSV.y = trkCrs.y(); + initSV.z = trkCrs.z(); + initSV.tx = trkCrsD.x()/trkCrsD.z(); + initSV.ty = trkCrsD.y()/trkCrsD.z(); + initSV.Q = trkcand.get_Q() / trkcand.get_P(); + + rk.SwimToZ(trkcand.get(0).get_Sector(), initSV, dcSwim, z0, bf); + + if (initSV != null) { + + this.trackTraj.put(0, initSV); + } else { + kf.setFitFailed = true; + return; + } + //System.out.println((0)+"] init "+this.trackTraj.get(0).x+","+this.trackTraj.get(0).y+","+ + // this.trackTraj.get(0).z+","+this.trackTraj.get(0).tx+","+this.trackTraj.get(0).ty+" "+1/this.trackTraj.get(0).Q); + double err_sl1 = trkcand.get(0).get_Segment1().get_fittedCluster().get_clusterLineFitSlopeErr(); + double err_sl2 = trkcand.get(0).get_Segment2().get_fittedCluster().get_clusterLineFitSlopeErr(); + double err_it1 = trkcand.get(0).get_Segment1().get_fittedCluster().get_clusterLineFitInterceptErr(); + double err_it2 = trkcand.get(0).get_Segment2().get_fittedCluster().get_clusterLineFitInterceptErr(); + double wy_over_wx = (FastMath.cos(Math.toRadians(6.)) / FastMath.sin(Math.toRadians(6.))); + + double eux = 0.5 * Math.sqrt(err_sl1 * err_sl1 + err_sl2 * err_sl2); + double euy = 0.5 * wy_over_wx * Math.sqrt(err_sl1 * err_sl1 + err_sl2 * err_sl2); + double z = trkcand.get(0).get_Point().z(); + double ex = 0.5 * Math.sqrt(err_it1 * err_it1 + err_it2 * err_it2 + z * z * (err_sl1 * err_sl1 + err_sl2 * err_sl2)); + double ey = 0.5 * wy_over_wx * Math.sqrt(err_it1 * err_it1 + err_it2 * err_it2 + z * z * (err_sl1 * err_sl1 + err_sl2 * err_sl2)); + double epSq = 0.001 * trkcand.get_P() * trkcand.get_P(); + + Matrix initCMatrix = new Matrix(); + initCMatrix.set(ex * ex, 0, 0, 0, 0, + 0, ey * ey, 0, 0, 0, + 0, 0, eux * eux, 0, 0, + 0, 0, 0, euy * euy, 0, + 0, 0, 0, 0, epSq + ); + + CovMat initCM = new CovMat(0); + initCM.covMat = initCMatrix; + this.trackCov.put(0, initCM); + } + private StateVec reset(StateVec SVplus, StateVec stateVec) { + SVplus = new StateVec(stateVec.k); + SVplus.x = stateVec.x; + SVplus.y = stateVec.y; + SVplus.tx = stateVec.tx; + SVplus.ty = stateVec.ty; + SVplus.z = stateVec.z; + SVplus.Q = stateVec.Q; + + return SVplus; + } + private void swimToSite(int sector, double z0, + StateVec SVplus, StateVec SVminus) { + + rk.SwimToZ(sector, SVplus, dcSwim, z0, bf); + rk.SwimToZ(sector, SVminus, dcSwim, z0, bf); + } + + double[] F(int sector, double z0, StateVec stateVec) { + double[] _F = new double[5]; + StateVec SVplus = null; + StateVec SVminus = null; + + SVplus = this.reset(SVplus, stateVec); + SVminus = this.reset(SVminus, stateVec); + + double delt_x = 0.05; + SVplus.x += delt_x/2.; + SVminus.x-= delt_x/2.; + + this.swimToSite(sector, z0, SVplus, SVminus); + + _F[0] = (SVplus.x - SVminus.x)/delt_x; + + SVplus = this.reset(SVplus, stateVec); + SVminus = this.reset(SVminus, stateVec); + + double delt_y = 0.05; + SVplus.y += delt_y/2.; + SVminus.y-= delt_y/2.; + + this.swimToSite(sector, z0, SVplus, SVminus); + + _F[1] = (SVplus.y - SVminus.y)/delt_y; + + SVplus = this.reset(SVplus, stateVec); + SVminus = this.reset(SVminus, stateVec); + + double delt_tx = 0.001; + SVplus.tx += delt_tx/2.; + SVminus.tx-= delt_tx/2.; + + this.swimToSite(sector, z0, SVplus, SVminus); + + _F[2] = (SVplus.tx - SVminus.tx)/delt_tx; + + SVplus = this.reset(SVplus, stateVec); + SVminus = this.reset(SVminus, stateVec); + + double delt_ty = 0.001; + SVplus.ty += delt_ty/2.; + SVminus.ty-= delt_ty/2.; + + this.swimToSite(sector, z0, SVplus, SVminus); + + _F[3] = (SVplus.ty - SVminus.ty)/delt_ty; + + SVplus = this.reset(SVplus, stateVec); + SVminus = this.reset(SVminus, stateVec); + + + _F[4] = 0.01/Math.abs(SVplus.Q); + + return _F; + + } + + void initFromHB(Track trkcand, double z0, KFitterDoca kf) { + if (trkcand != null && trkcand.getFinalStateVec()!=null + && trkcand.get_CovMat()!=null) { + beta = trkcand.get(0).get(0).get(0).get_Beta(); + StateVec initSV = new StateVec(0); + initSV.x = trkcand.getFinalStateVec().x(); + initSV.y = trkcand.getFinalStateVec().y(); + initSV.z = trkcand.getFinalStateVec().getZ(); + initSV.tx = trkcand.getFinalStateVec().tanThetaX(); + initSV.ty = trkcand.getFinalStateVec().tanThetaY(); + initSV.Q = ((double) trkcand.get_Q())/trkcand.get_P(); + + rk.SwimToZ(trkcand.get(0).get_Sector(), initSV, dcSwim, z0, bf); + this.trackTraj.put(0, initSV); + + CovMat initCM = new CovMat(0); + //initCM.covMat = trkcand.get_CovMat(); + //test + StateVec rinitSV = new StateVec(0); + rinitSV.x = trkcand.getFinalStateVec().x(); + rinitSV.y = trkcand.getFinalStateVec().y(); + rinitSV.z = trkcand.getFinalStateVec().getZ(); + rinitSV.tx = trkcand.getFinalStateVec().tanThetaX(); + rinitSV.ty = trkcand.getFinalStateVec().tanThetaY(); + rinitSV.Q = ((double) trkcand.get_Q())/trkcand.get_P(); + double[] FTF = new double[25]; + double[] F = this.F(trkcand.get(0).get_Sector(), z0, rinitSV); + for(int i = 0; i<5; i++) { + FTF[i*5+i]=F[i]*F[i]; + + } + + //Matrix initCMatrix = new Matrix(FTF); + Matrix initCMatrix = new Matrix(); + initCMatrix.set(FTF); + initCM.covMat = initCMatrix; + //end test + this.trackCov.put(0, initCM); //this.printMatrix(initCM.covMat); + } else { + kf.setFitFailed = true; + return; + } + + } + + public void printMatrix(Matrix C) { + for (int k = 0; k < 5; k++) { + for (int j = 0; j < 5; j++) { + System.out.println("C["+j+"]["+k+"] = "+C.get(j, k)); + } + } + } + + /** + * The state vector representing the track at a given measurement site + */ + public class StateVec { + + final int k; //index + public double z; //z (fixed measurement planes) + public double x; //track x in the tilted sector coordinate system at z + public double y; //track y in the tilted sector coordinate system at z + public double tx; //track px/pz in the tilted sector coordinate system at z + public double ty; //track py/pz in the tilted sector coordinate system at z + public double Q; //track q/p + double B; + double deltaPath; + + StateVec(int k) { + this.k = k; + } + + String printInfo() { + return this.k+"] = "+(float)this.x+", "+(float)this.y+", "+(float)this.z+", " + +(float)this.tx+", "+(float)this.ty+", "+(float)1./this.Q+" B = "+(float)this.B; + } + } + /** + * The track covariance matrix + */ + public class CovMat { + + final int k; + public Matrix covMat = new Matrix(); + + CovMat(int k) { + this.k = k; + } + + } +} diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/trajectory/RoadFinder.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/trajectory/RoadFinder.java index de7d7bd440..722e14d4e3 100644 --- a/reconstruction/dc/src/main/java/org/jlab/rec/dc/trajectory/RoadFinder.java +++ b/reconstruction/dc/src/main/java/org/jlab/rec/dc/trajectory/RoadFinder.java @@ -124,7 +124,7 @@ public Segment findRoadMissingSegment(List segList, DCGeant4Factory DcD return null; // make the missing segment Cluster pseudoCluster = new Cluster(segList.get(0).get_Sector(),slyr,-1); - FittedCluster fpseudoCluster = new FittedCluster(pseudoCluster); + FittedCluster fpseudoCluster = new FittedCluster(pseudoCluster); for(int l = 0; l<6; l++) { int layer = l+1; double z = DcDetector.getWireMidpoint(segList.get(0).get_Sector() - 1, slyr-1,layer-1,0).z; @@ -134,6 +134,7 @@ public Segment findRoadMissingSegment(List segList, DCGeant4Factory DcD 0, -1); //estimate the error on the hit as the cellSize/sqrt(12) pseudoHit.calc_CellSize(DcDetector); + pseudoHit.calc_GeomCorr(DcDetector, 0); pseudoHit.set_DocaErr(pseudoHit.get_CellSize()/Math.sqrt(12.)); //update the hit position estimate and add to the pseudo-cluster pseudoHit.updateHitPosition(DcDetector); @@ -174,6 +175,7 @@ private Segment reFit(Segment pseudoSeg, ArrayList segList, DCGeant4Fac 0, -1); pseudoHit.set_DocaErr(pseudoHit.get_CellSize()/Math.sqrt(12.)/FastMath.cos(Math.toRadians(6.))); pseudoHit.updateHitPosition(DcDetector); + pseudoHit.calc_GeomCorr(DcDetector, 0); fpseudoCluster.add(pseudoHit); } cf.SetFitArray(fpseudoCluster, "TSC"); diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/trajectory/StateVec.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/trajectory/StateVec.java index fa833cb24a..1bc2f7fa1c 100644 --- a/reconstruction/dc/src/main/java/org/jlab/rec/dc/trajectory/StateVec.java +++ b/reconstruction/dc/src/main/java/org/jlab/rec/dc/trajectory/StateVec.java @@ -83,17 +83,26 @@ public double getB() { public void setB(double b) { this.b = b; } - // KF projector - private double h; + // KF projector --> get Wire midPoint match + private double hw; public double getProjector() { - return h; + return hw; } public void setProjector(double h) { + this.hw = h; + } + // KF projector --> get fit doca + private double h; + + public double getProjectorDoca() { + return h; + } + + public void setProjectorDoca(double h) { this.h = h; } - /** * Sets the stateVec * diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/trajectory/Trajectory.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/trajectory/Trajectory.java index ce85c25253..cf8f0bb6b1 100644 --- a/reconstruction/dc/src/main/java/org/jlab/rec/dc/trajectory/Trajectory.java +++ b/reconstruction/dc/src/main/java/org/jlab/rec/dc/trajectory/Trajectory.java @@ -6,6 +6,7 @@ import org.jlab.detector.base.DetectorLayer; import org.jlab.detector.base.DetectorType; import org.jlab.geom.prim.Vector3D; +import org.jlab.rec.dc.Constants; import org.jlab.rec.dc.cross.Cross; @@ -264,12 +265,14 @@ public void calcTrajectory(int id, Swim dcSwim, double x, double y, double z, d int dir = 1; //HTCC: swim to sphere and save end point - double[] trkParsCheren = dcSwim.SwimToSphere(175.); +// System.out.println("New track " + x + " " + y + " " + z); + double[] trkParsCheren = dcSwim.SwimToSphere(Constants.htccRadius); if(trkParsCheren==null) return; this.FillTrajectory(id, trajectory, trkParsCheren, trkParsCheren[6], trkParsCheren[7], DetectorType.HTCC, 1); pathLen = trkParsCheren[6]; iBdl = trkParsCheren[7]; // System.out.println( "HTCC" + " " + trkParsCheren[0] + " " + trkParsCheren[1] + " " + trkParsCheren[2] + " " + trkParsCheren[6] + " " + trkParsCheren[7]); + int is = _Sector-1; // loop over surfaces: Target, FMT, DC, LTCC, FTOF, ECAL @@ -298,6 +301,8 @@ public void calcTrajectory(int id, Swim dcSwim, double x, double y, double z, d trkPars[3]=tv.px(); trkPars[4]=tv.py(); trkPars[5]=tv.pz(); + trkPars[6]=DCtrkPars[6]; + trkPars[7]=DCtrkPars[7]; } // set swimming starting point depending on surface else { @@ -319,7 +324,7 @@ else if(surface.getDetectorType()==DetectorType.FMT) { dcSwim.SetSwimParameters(trkParsCheren[0], trkParsCheren[1], trkParsCheren[2], trkParsCheren[3], trkParsCheren[4], trkParsCheren[5], q); dir=1; } - + // Swim in the lab for all detectors that are not DC trkPars = dcSwim.SwimToPlaneBoundary(surface.get_d(), new Vector3D(surface.get_nx(),surface.get_ny(),surface.get_nz()),dir); @@ -333,7 +338,7 @@ else if(surface.getDetectorType()==DetectorType.FMT) { //System.out.println(" Failed swim"); return; } - + // System.out.println(surface.getDetectorType().getName() + " " + surface.getDetectorLayer() + " " + trkPars[0] + " " + trkPars[1] + " " + trkPars[2] + " " + trkPars[6] + " " + trkPars[7]); // if surface correspond to target, invert unit vector before is saved and calculate manually the pathlength @@ -347,6 +352,7 @@ else if(surface.getDetectorType()==DetectorType.FMT){ this.FillTrajectory(id, trajectory, trkPars, trkPars[6], trkPars[7], surface.getDetectorType(), surface.getDetectorLayer()); } else { +// System.out.println(surface.getDetectorType() + " " + surface.getDetectorLayer() + " " + trkPars[2] + " " + pathLen + " " + trkPars[6]); this.FillTrajectory(id, trajectory, trkPars, pathLen+trkPars[6], iBdl+trkPars[7], surface.getDetectorType(), surface.getDetectorLayer()); } diff --git a/reconstruction/dc/src/main/java/org/jlab/rec/dc/trajectory/TrajectorySurfaces.java b/reconstruction/dc/src/main/java/org/jlab/rec/dc/trajectory/TrajectorySurfaces.java index b7f6733977..6505fa47a1 100644 --- a/reconstruction/dc/src/main/java/org/jlab/rec/dc/trajectory/TrajectorySurfaces.java +++ b/reconstruction/dc/src/main/java/org/jlab/rec/dc/trajectory/TrajectorySurfaces.java @@ -5,6 +5,8 @@ */ package org.jlab.rec.dc.trajectory; +import java.io.File; +import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; import org.jlab.detector.base.DetectorLayer; @@ -14,6 +16,9 @@ import org.jlab.detector.geant4.v2.FTOFGeant4Factory; import org.jlab.geom.base.Detector; import org.jlab.geom.prim.Vector3D; +import org.jlab.rec.dc.Constants; + +import java.io.PrintWriter; /** * A class to load the geometry constants used in the DC reconstruction. The * coordinate system used in the Tilted Sector coordinate system. @@ -39,11 +44,25 @@ public void LoadSurfaces(double targetPosition, double targetLength, DCGeant4Factory dcDetector, FTOFGeant4Factory ftofDetector, Detector ecalDetector) { - + // creating Boundaries for MS + Constants.Z[0]= targetPosition; + Constants.Z[1]= dcDetector.getWireMidpoint(0, 0, 0, 0).z; + Constants.Z[2]= dcDetector.getWireMidpoint(0, 0, 5, 0).z; + Constants.Z[3]= dcDetector.getWireMidpoint(0, 1, 0, 0).z; + Constants.Z[4]= dcDetector.getWireMidpoint(0, 1, 5, 0).z; + Constants.Z[5]= dcDetector.getWireMidpoint(0, 2, 0, 0).z; + Constants.Z[6]= dcDetector.getWireMidpoint(0, 2, 5, 0).z; + Constants.Z[7]= dcDetector.getWireMidpoint(0, 3, 0, 0).z; + Constants.Z[8]= dcDetector.getWireMidpoint(0, 3, 5, 0).z; + Constants.Z[9]= dcDetector.getWireMidpoint(0, 4, 0, 0).z; + Constants.Z[10]= dcDetector.getWireMidpoint(0, 4, 5, 0).z; + Constants.Z[11]= dcDetector.getWireMidpoint(0, 5, 0, 0).z; + Constants.Z[12]= dcDetector.getWireMidpoint(0, 5, 5, 0).z; + //DcDetector.getWireMidpoint(this.get_Sector()-1, this.get_Superlayer()-1, this.get_Layer()-1, this.get_Wire()-1).z; + double d = 0; Vector3D n; for(int is =0; is<6; is++) { - int index =0; System.out.println(" CREATING SURFACES FOR SECTOR "+(is+1)); this._DetectorPlanes.add(new ArrayList()); @@ -52,12 +71,12 @@ public void LoadSurfaces(double targetPosition, double targetLength, this._DetectorPlanes.get(is).add(new Surface(DetectorType.TARGET, DetectorLayer.TARGET_DOWNSTREAM, targetPosition+targetLength/2, 0., 0., 1.)); this._DetectorPlanes.get(is).add(new Surface(DetectorType.TARGET, DetectorLayer.TARGET_CENTER, targetPosition, 0., 0., 1.)); - //add FMT - for(int i=0;i<6;i++) { - d = FVT_Z1stlayer+i*FVT_Interlayer; - this._DetectorPlanes.get(is).add(new Surface(DetectorType.FMT, i+1, d, 0., 0., 1.)); - } - index=7; // end of MM + HTCC(7) +// //add FMT +// for(int i=0;i<6;i++) { +// d = FVT_Z1stlayer+i*FVT_Interlayer; +// this._DetectorPlanes.get(is).add(new Surface(DetectorType.FMT, i+1, d, 0., 0., 1.)); +// } + // Add DC //n = this.RotateFromTSCtoLabC(0,0,1, is+1).toVector3D(); // don't rotate to the lab @@ -86,28 +105,34 @@ public void LoadSurfaces(double targetPosition, double targetLength, d = P.dot(n); this._DetectorPlanes.get(is).add(new Surface(DetectorType.FTOF, DetectorLayer.FTOF1A, -d, -n.x(), -n.y(), -n.z())); //LTCC - this._DetectorPlanes.get(is).add(new Surface(DetectorType.LTCC,1, 653.09, -n.x(), -n.y(), -n.z())); + this._DetectorPlanes.get(is).add(new Surface(DetectorType.LTCC,1, Constants.ltccPlane, -n.x(), -n.y(), -n.z())); //PCAL int superLayer = (int) ((DetectorLayer.PCAL_V-1)/3); - int localLayer = (DetectorLayer.PCAL_V-1)%3; + int localLayer = DetectorLayer.PCAL_Z+1; P = ecalDetector.getSector(is).getSuperlayer(superLayer).getLayer(localLayer).getPlane().point().toVector3D(); + Vector3D P1 = ecalDetector.getSector(is).getSuperlayer(superLayer).getLayer(localLayer).getComponent(1).getMidpoint().toVector3D(); n = ecalDetector.getSector(is).getSuperlayer(superLayer).getLayer(localLayer).getPlane().normal(); - d = P.dot(n); - this._DetectorPlanes.get(is).add(new Surface(DetectorType.ECAL, DetectorLayer.PCAL_V, d, n.x(), n.y(), n.z())); + d = P.dot(n); +// System.out.println("PCAL " + d + " " + P1.dot(n)); + this._DetectorPlanes.get(is).add(new Surface(DetectorType.ECAL, DetectorLayer.PCAL_U, d, n.x(), n.y(), n.z())); //ECin superLayer = (int) ((DetectorLayer.EC_INNER_V-1)/3); - localLayer = (DetectorLayer.EC_INNER_V-1)%3; + localLayer = DetectorLayer.EC_INNER_Z+1; P = ecalDetector.getSector(is).getSuperlayer(superLayer).getLayer(localLayer).getPlane().point().toVector3D(); + P1 = ecalDetector.getSector(is).getSuperlayer(superLayer).getLayer(localLayer).getComponent(1).getMidpoint().toVector3D(); n = ecalDetector.getSector(is).getSuperlayer(superLayer).getLayer(localLayer).getPlane().normal(); d = P.dot(n); - this._DetectorPlanes.get(is).add(new Surface(DetectorType.ECAL, DetectorLayer.EC_INNER_V, d, n.x(), n.y(), n.z())); +// System.out.println("ECin " + d + " " + P1.dot(n)); + this._DetectorPlanes.get(is).add(new Surface(DetectorType.ECAL, DetectorLayer.EC_INNER_U, d, n.x(), n.y(), n.z())); //ECout superLayer = (int) ((DetectorLayer.EC_OUTER_V-1)/3); - localLayer = (DetectorLayer.EC_OUTER_V-1)%3; + localLayer = DetectorLayer.EC_OUTER_Z+1; P = ecalDetector.getSector(is).getSuperlayer(superLayer).getLayer(localLayer).getPlane().point().toVector3D(); + P1 = ecalDetector.getSector(is).getSuperlayer(superLayer).getLayer(localLayer).getComponent(1).getMidpoint().toVector3D(); n = ecalDetector.getSector(is).getSuperlayer(superLayer).getLayer(localLayer).getPlane().normal(); d = P.dot(n); - this._DetectorPlanes.get(is).add(new Surface(DetectorType.ECAL, DetectorLayer.EC_OUTER_V, d, n.x(), n.y(), n.z())); +// System.out.println("ECout " + d + " " + P1.dot(n)); + this._DetectorPlanes.get(is).add(new Surface(DetectorType.ECAL, DetectorLayer.EC_OUTER_U, d, n.x(), n.y(), n.z())); } } // private Point3D RotateFromTSCtoLabC(double X, double Y, double Z, int sector) { @@ -119,4 +144,28 @@ public void LoadSurfaces(double targetPosition, double targetLength, // // return new Point3D(rx,ry,rzs); // } + + public void checkDCGeometry(DCGeant4Factory dcDetector) throws FileNotFoundException { + int is = 0; + PrintWriter pw = new PrintWriter(new File("/Users/ziegler/WireEndPoints.txt")); + + pw.printf("superlayer"+" "+"layer"+" "+"wire"+" "+"xL"+" "+"yL"+" "+ + "xR"+" "+"yR"+" "+"z" + ); + for(int isup =0; isup<6; isup++) { + for(int il =5; il<6; il++) { + for(int ic =0; ic<112; ic++) { // include only layer 6 + double z = dcDetector.getWireMidpoint(is, isup, il, ic).z; + double xL = dcDetector.getWireLeftend(is, isup, il, ic).x; + double xR = dcDetector.getWireRightend(is, isup, il, ic).x; + double yL = dcDetector.getWireLeftend(is, isup, il, ic).y; + double yR = dcDetector.getWireRightend(is, isup, il, ic).y; + pw.printf("%d\t %d\t %d\t %.1f\t %.1f\t %.1f\t %.1f\t %.1f\t\n", (isup+1),(il+1),(ic+1),xL,yL,xR,yR,z + ); + } + } + } + } + + } diff --git a/reconstruction/dc/src/main/java/org/jlab/service/dc/DCEngine.java b/reconstruction/dc/src/main/java/org/jlab/service/dc/DCEngine.java index b9d73a51ea..fa32934987 100755 --- a/reconstruction/dc/src/main/java/org/jlab/service/dc/DCEngine.java +++ b/reconstruction/dc/src/main/java/org/jlab/service/dc/DCEngine.java @@ -1,7 +1,10 @@ package org.jlab.service.dc; +import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Optional; +import java.util.logging.Level; +import java.util.logging.Logger; import org.jlab.clas.reco.ReconstructionEngine; import org.jlab.detector.base.DetectorType; import org.jlab.detector.base.GeometryFactory; @@ -24,6 +27,7 @@ public class DCEngine extends ReconstructionEngine { TrajectorySurfaces tSurf; String clasDictionaryPath ; String variationName; + boolean endplatesBowing; public DCEngine(String name) { super(name,"ziegler","5.0"); } @@ -53,25 +57,64 @@ public void setOptions() { if (wireDistortionsFlag!=null) { System.out.println("["+this.getName()+"] run with wire distortions in tracking config chosen based on yaml = "+wireDistortionsFlag); if(Boolean.valueOf(wireDistortionsFlag)==true) { - Constants.setWIREDIST(1.0); + //Constants.setWIREDIST(1.0); + endplatesBowing = DCGeant4Factory.ENDPLATESBOWON; } else { - Constants.setWIREDIST(0); + //Constants.setWIREDIST(0); + endplatesBowing = DCGeant4Factory.ENDPLATESBOWOFF; } } else { - wireDistortionsFlag = System.getenv("COAT_DC_WIREDISTORTION"); + wireDistortionsFlag = System.getenv("COAT_DC_WIREDISTORTION"); if (wireDistortionsFlag!=null) { System.out.println("["+this.getName()+"] run with wire distortions in tracking config chosen based on env = "+wireDistortionsFlag); if(Boolean.valueOf(wireDistortionsFlag)==true) { - Constants.setWIREDIST(1.0); + //Constants.setWIREDIST(1.0); + endplatesBowing = DCGeant4Factory.ENDPLATESBOWON; } else { - Constants.setWIREDIST(0); + //Constants.setWIREDIST(0); + endplatesBowing = DCGeant4Factory.ENDPLATESBOWOFF; } } } if (wireDistortionsFlag==null) { System.out.println("["+this.getName()+"] run with default setting for wire distortions in tracking (MC-off/Data-on)"); } + //Use time in tBeta function (true: use time; false: use track doca) + String useTIMETBETA = this.getEngineConfigString("dcTimeTBeta"); + + if (useTIMETBETA!=null) { + System.out.println("["+this.getName()+"] run with new tBeta chosen based on yaml = "+useTIMETBETA); + Constants.setUSETIMETBETA(Boolean.valueOf(useTIMETBETA)); + } + else { + useTIMETBETA = System.getenv("COAT_DC_USETIMETBETA"); + if (useTIMETBETA!=null) { + System.out.println("["+this.getName()+"] run with with new tBeta config chosen based on env = "+useTIMETBETA); + Constants.setUSETIMETBETA(Boolean.valueOf(useTIMETBETA)); + } + } + if (useTIMETBETA==null) { + System.out.println("["+this.getName()+"] run with with new tBeta config chosen based on default = "+Constants.useUSETIMETBETA()); + } + //CHECKBETA + //Use beta cut(true: use time; false: use track doca) + String useBETACUT = this.getEngineConfigString("dcBetaCut"); + + if (useBETACUT!=null) { + System.out.println("["+this.getName()+"] run with Beta cut chosen based on yaml = "+useBETACUT); + Constants.CHECKBETA=Boolean.valueOf(useBETACUT); + } + else { + useBETACUT = System.getenv("COAT_DC_USEBETACUT"); + if (useBETACUT!=null) { + System.out.println("["+this.getName()+"] run with with with Beta cut config chosen based on env = "+useBETACUT); + Constants.CHECKBETA=Boolean.valueOf(useBETACUT); + } + } + if (useBETACUT==null) { + System.out.println("["+this.getName()+"] run with with Beta cut config chosen based on default = "+Constants.CHECKBETA); + } //T2D Function String T2Dfcn = this.getEngineConfigString("dcT2DFunc"); @@ -133,7 +176,7 @@ public void LoadTables() { // Load the geometry String geoVariation = Optional.ofNullable(geomDBVar).orElse("default"); ConstantProvider provider = GeometryFactory.getConstants(DetectorType.DC, 11, geoVariation); - dcDetector = new DCGeant4Factory(provider, DCGeant4Factory.MINISTAGGERON); + dcDetector = new DCGeant4Factory(provider, DCGeant4Factory.MINISTAGGERON, endplatesBowing); for(int l=0; l<6; l++) { Constants.wpdist[l] = provider.getDouble("/geometry/dc/superlayer/wpdist", l); System.out.println("****************** WPDIST READ *********FROM "+geoVariation+"**** VARIATION ****** "+provider.getDouble("/geometry/dc/superlayer/wpdist", l)); @@ -151,6 +194,13 @@ public void LoadTables() { // create the surfaces tSurf = new TrajectorySurfaces(); + // for debugging the end plates bowing: + //==================================== + //try { + // tSurf.checkDCGeometry(dcDetector); + //} catch (FileNotFoundException ex) { + // Logger.getLogger(DCEngine.class.getName()).log(Level.SEVERE, null, ex); + //} tSurf.LoadSurfaces(targetPosition, targetLength,dcDetector, ftofDetector, ecalDetector); // Get the constants for the correct variation diff --git a/reconstruction/dc/src/main/java/org/jlab/service/dc/DCNNEngine.java b/reconstruction/dc/src/main/java/org/jlab/service/dc/DCNNEngine.java new file mode 100644 index 0000000000..2031f12072 --- /dev/null +++ b/reconstruction/dc/src/main/java/org/jlab/service/dc/DCNNEngine.java @@ -0,0 +1,170 @@ +package org.jlab.service.dc; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import org.jlab.clas.swimtools.Swim; +import org.jlab.clas.swimtools.Swimmer; +import org.jlab.io.base.DataBank; +import org.jlab.io.base.DataEvent; +import org.jlab.rec.dc.Constants; +import org.jlab.rec.dc.banks.HitReader; +import org.jlab.rec.dc.banks.RecoBankWriter; +import org.jlab.rec.dc.cluster.FittedCluster; +import org.jlab.rec.dc.cross.Cross; +import org.jlab.rec.dc.cross.CrossList; +import org.jlab.rec.dc.hit.FittedHit; +import org.jlab.rec.dc.hit.Hit; +import org.jlab.rec.dc.nn.PatternRec; +import org.jlab.rec.dc.segment.Segment; +import org.jlab.rec.dc.timetodistance.TableLoader; +import org.jlab.rec.dc.track.Track; +import org.jlab.rec.dc.track.TrackCandListFinder; +import org.jlab.utils.groups.IndexedTable; + +/** + * @author zigler + */ +public class DCNNEngine extends DCEngine { + + private AtomicInteger Run = new AtomicInteger(0); + private double triggerPhase; + private int newRun = 0; + + public DCNNEngine() { + super("DCNN"); + } + + @Override + public boolean init() { + // Load cuts + Constants.Load(); + super.setOptions(); + super.LoadTables(); + return true; + } + + @Override + public boolean processDataEvent(DataEvent event) { +// long startTime = 0; + //setRunConditionsParameters( event) ; + if (!event.hasBank("RUN::config")) { + return true; + } + + DataBank bank = event.getBank("RUN::config"); + long timeStamp = bank.getLong("timestamp", 0); + double triggerPhase = 0; + + // Load the constants + //------------------- + int newRun = bank.getInt("run", 0); + if (newRun == 0) + return true; + + if (Run.get() == 0 || (Run.get() != 0 && Run.get() != newRun)) { + if (timeStamp == -1) + return true; + // if (debug.get()) startTime = System.currentTimeMillis(); + IndexedTable tabJ = super.getConstantsManager().getConstants(newRun, Constants.TIMEJITTER); + double period = tabJ.getDoubleValue("period", 0, 0, 0); + int phase = tabJ.getIntValue("phase", 0, 0, 0); + int cycles = tabJ.getIntValue("cycles", 0, 0, 0); + + if (cycles > 0) triggerPhase = period * ((timeStamp + phase) % cycles); + + TableLoader.FillT0Tables(newRun, super.variationName); + TableLoader.Fill(super.getConstantsManager().getConstants(newRun, Constants.TIME2DIST)); + + Run.set(newRun); + if (event.hasBank("MC::Particle") && this.getEngineConfigString("wireDistort")==null) { + Constants.setWIREDIST(0); + } + + // if (debug.get()) System.out.println("NEW RUN INIT = " + (System.currentTimeMillis() - startTime)); + } + + // get Field + Swim dcSwim = new Swim(); + + RecoBankWriter rbc = new RecoBankWriter(); + + HitReader hitRead = new HitReader(); + + hitRead.read_NNHits(event, dcDetector, triggerPhase); + + //I) get the lists + List hits = hitRead.get_DCHits(); + List fhits = new ArrayList(); + List clusters = new ArrayList(); + //II) process the hits + //1) exit if hit list is empty + if (hits.isEmpty()) { + return true; + } + PatternRec pr = new PatternRec(); + List segments = pr.RecomposeSegments(hits, dcDetector); + + if (segments.isEmpty()) { + return true; + } + + //crossList + CrossList crosslist = pr.RecomposeCrossList(segments, dcDetector); + List crosses = new ArrayList(); + + for (List clist : crosslist) { + crosses.addAll(clist); + } + //find the list of track candidates + TrackCandListFinder trkcandFinder = new TrackCandListFinder(Constants.HITBASE); + List trkcands = trkcandFinder.getTrackCands(crosslist, + dcDetector, + Swimmer.getTorScale(), + dcSwim); + + // track found + int trkId = 1; + if (trkcands.size() > 0) { + // remove overlaps + trkcandFinder.removeOverlappingTracks(trkcands); + for (Track trk : trkcands) { + // reset the id + trk.set_Id(trkId); + trkcandFinder.matchHits(trk.get_Trajectory(), + trk, + dcDetector, + dcSwim); + for (Cross c : trk) { + c.get_Segment1().isOnTrack = true; + c.get_Segment2().isOnTrack = true; + clusters.add(c.get_Segment1().get_fittedCluster()); + clusters.add(c.get_Segment2().get_fittedCluster()); + for (FittedHit h1 : c.get_Segment1()) { + h1.set_AssociatedHBTrackID(trk.get_Id()); + fhits.add(h1); + } + for (FittedHit h2 : c.get_Segment2()) { + h2.set_AssociatedHBTrackID(trk.get_Id()); + fhits.add(h2); + } + } + trkId++; + } + } + + // no candidate found, stop here + if (trkcands.isEmpty()) { + return true; + } + rbc.fillAllHBBanks(event, + rbc, + fhits, + clusters, + segments, + crosses, + trkcands); + return true; + } + +} diff --git a/reconstruction/dc/src/main/java/org/jlab/service/dc/DCTBEngine.java b/reconstruction/dc/src/main/java/org/jlab/service/dc/DCTBEngine.java index 86471b5f55..18259bd614 100755 --- a/reconstruction/dc/src/main/java/org/jlab/service/dc/DCTBEngine.java +++ b/reconstruction/dc/src/main/java/org/jlab/service/dc/DCTBEngine.java @@ -1,6 +1,7 @@ package org.jlab.service.dc; -import Jama.Matrix; +//import Jama.Matrix; +import org.jlab.jnp.matrix.*; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; @@ -24,7 +25,7 @@ import org.jlab.rec.dc.timetodistance.TimeToDistanceEstimator; import org.jlab.rec.dc.track.Track; import org.jlab.rec.dc.track.TrackCandListFinder; -import org.jlab.rec.dc.track.fit.KFitter; +import org.jlab.rec.dc.track.fit.KFitterDoca; import org.jlab.rec.dc.trajectory.StateVec; import org.jlab.rec.dc.trajectory.Trajectory; import org.jlab.rec.dc.trajectory.TrajectoryFinder; @@ -101,17 +102,9 @@ public boolean processDataEvent(DataEvent event) { super.getConstantsManager().getConstants(newRun, "/calibration/dc/signal_generation/doca_resolution"), super.getConstantsManager().getConstants(newRun, "/calibration/dc/time_to_distance/time2dist"), Constants.getT0(), Constants.getT0Err(), dcDetector, tde); - hitRead.read_TBHits(event, - super.getConstantsManager().getConstants(newRun, "/calibration/dc/signal_generation/doca_resolution"), - super.getConstantsManager().getConstants(newRun, "/calibration/dc/time_to_distance/time2dist"), tde, Constants.getT0(), Constants.getT0Err()); List hits = new ArrayList(); //I) get the hits - if(hitRead.get_TBHits().isEmpty()) { - hits = hitRead.get_HBHits(); - - } else { - hits = hitRead.get_TBHits(); - } + hits = hitRead.get_HBHits(); //II) process the hits //1) exit if hit list is empty @@ -189,7 +182,8 @@ public boolean processDataEvent(DataEvent event) { trkbank.getFloat("tx", i), trkbank.getFloat("ty", i)); HBFinalSV.setZ(trkbank.getFloat("z", i)); HBtrk.setFinalStateVec(HBFinalSV); - Matrix initCMatrix = new Matrix(new double[][]{ + Matrix initCMatrix = new Matrix(); + initCMatrix.set(new double[][]{ {trkcovbank.getFloat("C11", i), trkcovbank.getFloat("C12", i), trkcovbank.getFloat("C13", i), trkcovbank.getFloat("C14", i), trkcovbank.getFloat("C15", i)}, {trkcovbank.getFloat("C21", i), trkcovbank.getFloat("C22", i), trkcovbank.getFloat("C23", i), trkcovbank.getFloat("C24", i), trkcovbank.getFloat("C25", i)}, {trkcovbank.getFloat("C31", i), trkcovbank.getFloat("C32", i), trkcovbank.getFloat("C33", i), trkcovbank.getFloat("C34", i), trkcovbank.getFloat("C35", i)}, @@ -227,8 +221,8 @@ public boolean processDataEvent(DataEvent event) { //if(TrackArray[i].get_FitChi2()>200) { // resetTrackParams(TrackArray[i], new DCSwimmer()); //} - KFitter kFit = new KFitter(TrackArray[i], dcDetector, true, dcSwim); - + KFitterDoca kFit = new KFitterDoca(TrackArray[i], dcDetector, true, dcSwim, 0); + StateVec fn = new StateVec(); kFit.runFitter(TrackArray[i].get(0).get_Sector()); @@ -246,10 +240,14 @@ public boolean processDataEvent(DataEvent event) { TrackArray[i].set_Trajectory(kFit.kfStateVecsAlongTrajectory); TrackArray[i].set_FitConvergenceStatus(kFit.ConvStatus); TrackArray[i].set_Id(TrackArray[i].size()+1); - TrackArray[i].set_CovMat(kFit.finalCovMat.covMat); + //TrackArray[i].set_CovMat(kFit.finalCovMat.covMat); if(TrackArray[i].get_Vtx0().toVector3D().mag()>500) continue; - trkcands.add(TrackArray[i]); + // get CovMat at vertex + Point3D VTCS = crosses.get(0).getCoordsInSector( + TrackArray[i].get_Vtx0().x(), TrackArray[i].get_Vtx0().y(), TrackArray[i].get_Vtx0().z()); + TrackArray[i].set_CovMat(kFit.propagateToVtx(crosses.get(0).get_Sector(), VTCS.z())); + if(TrackArray[i].isGood()) trkcands.add(TrackArray[i]); } } diff --git a/reconstruction/dc/src/main/java/org/jlab/service/dc/LayerEfficiencyAnalyzer.java b/reconstruction/dc/src/main/java/org/jlab/service/dc/LayerEfficiencyAnalyzer.java index eaa966c52a..5700ce07c8 100644 --- a/reconstruction/dc/src/main/java/org/jlab/service/dc/LayerEfficiencyAnalyzer.java +++ b/reconstruction/dc/src/main/java/org/jlab/service/dc/LayerEfficiencyAnalyzer.java @@ -8,12 +8,12 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTabbedPane; import org.jlab.clas.swimtools.MagFieldsEngine; -import org.jlab.clas.swimtools.Swim; import org.jlab.io.hipo.HipoDataSource; import org.jlab.rec.dc.Constants; @@ -36,8 +36,10 @@ import org.jlab.rec.dc.hit.FittedHit; import org.jlab.rec.dc.segment.Segment; import org.jlab.rec.dc.segment.SegmentFinder; +import org.jlab.rec.dc.timetodistance.TableLoader; import org.jlab.rec.dc.timetodistance.TimeToDistanceEstimator; import org.jlab.rec.dc.trajectory.SegmentTrajectory; +import org.jlab.utils.groups.IndexedTable; public class LayerEfficiencyAnalyzer extends DCEngine implements IDataEventListener{ @@ -80,9 +82,17 @@ public LayerEfficiencyAnalyzer(){ private EmbeddedCanvas can12 = null; public double[] maxDoca = new double[6]; + + private AtomicInteger Run = new AtomicInteger(0); + + private int newRun = 0; @Override public boolean init() { + + Constants.Load(); + super.setOptions(); super.LoadTables(); + Constants.setT2D(1); maxDoca[0]=0.8;maxDoca[1]=0.9;maxDoca[2]=1.3;maxDoca[3]=1.4;maxDoca[4]=1.9;maxDoca[5]=2.0; //plots @@ -111,83 +121,25 @@ public boolean init() { can12 = new EmbeddedCanvas(); can12.divide(2, 3); // create histograms - for(int i =0; i<6; i++) { - - LayerEffs1.put(new Coordinate(i), - new H1F("Sector-1 layer efficiencies" + (i + 1), "superlayer" + (i + 1), 6, 0.5, 6.5)); - LayerEffs1.get(new Coordinate(i)).setTitleX("Layer" ); - LayerEffs1.get(new Coordinate(i)).setTitleY("Efficiency for superlayer "+(i+1) ); - - LayerEffs2.put(new Coordinate(i), - new H1F("Sector-2 layer efficiencies" + (i + 1), "superlayer" + (i + 1), 6, 0.5, 6.5)); - LayerEffs2.get(new Coordinate(i)).setTitleX("Layer" ); - LayerEffs2.get(new Coordinate(i)).setTitleY("Efficiency for superlayer "+(i+1) ); - - LayerEffs3.put(new Coordinate(i), - new H1F("Sector-3 layer efficiencies" + (i + 1), "superlayer" + (i + 1), 6, 0.5, 6.5)); - LayerEffs3.get(new Coordinate(i)).setTitleX("Layer" ); - LayerEffs3.get(new Coordinate(i)).setTitleY("Efficiency for superlayer "+(i+1) ); - - LayerEffs4.put(new Coordinate(i), - new H1F("Sector-4 layer efficiencies" + (i + 1), "superlayer" + (i + 1), 6, 0.5, 6.5)); - LayerEffs4.get(new Coordinate(i)).setTitleX("Layer" ); - LayerEffs4.get(new Coordinate(i)).setTitleY("Efficiency for superlayer "+(i+1) ); - - LayerEffs5.put(new Coordinate(i), - new H1F("Sector-5 layer efficiencies" + (i + 1), "superlayer" + (i + 1), 6, 0.5, 6.5)); - LayerEffs5.get(new Coordinate(i)).setTitleX("Layer" ); - LayerEffs5.get(new Coordinate(i)).setTitleY("Efficiency for superlayer "+(i+1) ); - - LayerEffs6.put(new Coordinate(i), - new H1F("Sector-6 layer efficiencies" + (i + 1), "superlayer" + (i + 1), 6, 0.5, 6.5)); - LayerEffs6.get(new Coordinate(i)).setTitleX("Layer" ); - LayerEffs6.get(new Coordinate(i)).setTitleY("Efficiency for superlayer "+(i+1) ); - - LayerEffsTrkD1.put(new Coordinate(i), - new H1F("Sector-1 layer inefficiencies vs trkDoca" + (i + 1), "superlayer" + (i + 1), 40, 0.0, 4.0)); - LayerEffsTrkD1.get(new Coordinate(i)).setTitleX("Track Doca (cm)" ); - LayerEffsTrkD1.get(new Coordinate(i)).setTitleY("Inefficiency for superlayer "+(i+1) ); - - LayerEffsTrkD2.put(new Coordinate(i), - new H1F("Sector-2 layer inefficiencies vs trkDoca" + (i + 1), "superlayer" + (i + 1), 40, 0.0, 4.0)); - LayerEffsTrkD2.get(new Coordinate(i)).setTitleX("Track Doca (cm)" ); - LayerEffsTrkD2.get(new Coordinate(i)).setTitleY("Inefficiency for superlayer "+(i+1) ); - - LayerEffsTrkD3.put(new Coordinate(i), - new H1F("Sector-3 layer inefficiencies vs trkDoca" + (i + 1), "superlayer" + (i + 1), 40, 0.0, 4.0)); - LayerEffsTrkD3.get(new Coordinate(i)).setTitleX("Track Doca (cm)" ); - LayerEffsTrkD3.get(new Coordinate(i)).setTitleY("Inefficiency for superlayer "+(i+1) ); - - LayerEffsTrkD4.put(new Coordinate(i), - new H1F("Sector-4 layer inefficiencies vs trkDoca" + (i + 1), "superlayer" + (i + 1), 40, 0.0, 4.0)); - LayerEffsTrkD4.get(new Coordinate(i)).setTitleX("Track Doca (cm)" ); - LayerEffsTrkD4.get(new Coordinate(i)).setTitleY("Inefficiency for superlayer "+(i+1) ); - - LayerEffsTrkD5.put(new Coordinate(i), - new H1F("Sector-5 layer inefficiencies vs trkDoca" + (i + 1), "superlayer" + (i + 1), 40, 0.0, 4.0)); - LayerEffsTrkD5.get(new Coordinate(i)).setTitleX("Track Doca (cm)" ); - LayerEffsTrkD5.get(new Coordinate(i)).setTitleY("Inefficiency for superlayer "+(i+1) ); - - LayerEffsTrkD6.put(new Coordinate(i), - new H1F("Sector-6 layer inefficiencies vs trkDoca" + (i + 1), "superlayer" + (i + 1), 40, 0.0, 4.0)); - LayerEffsTrkD6.get(new Coordinate(i)).setTitleX("Track Doca (cm)" ); - LayerEffsTrkD6.get(new Coordinate(i)).setTitleY("Inefficiency for superlayer "+(i+1) ); - - - this.setHistosAtt(LayerEffs1.get(new Coordinate(i)), 4); - this.setHistosAtt(LayerEffs2.get(new Coordinate(i)), 4); - this.setHistosAtt(LayerEffs3.get(new Coordinate(i)), 4); - this.setHistosAtt(LayerEffs4.get(new Coordinate(i)), 4); - this.setHistosAtt(LayerEffs5.get(new Coordinate(i)), 4); - this.setHistosAtt(LayerEffs6.get(new Coordinate(i)), 4); - this.setHistosAtt(LayerEffsTrkD1.get(new Coordinate(i)), 2); - this.setHistosAtt(LayerEffsTrkD2.get(new Coordinate(i)), 2); - this.setHistosAtt(LayerEffsTrkD3.get(new Coordinate(i)), 2); - this.setHistosAtt(LayerEffsTrkD4.get(new Coordinate(i)), 2); - this.setHistosAtt(LayerEffsTrkD5.get(new Coordinate(i)), 2); - this.setHistosAtt(LayerEffsTrkD6.get(new Coordinate(i)), 2); + for(int si =0; si<6; si++) { + LayerEffs.add(new HashMap()); + LayerEffsTrkD.add(new HashMap()); + for(int i =0; i<6; i++) { + LayerEffs.get(si).put(new Coordinate(i), + new H1F("Sector-"+si+" layer efficiencies" + (i + 1), "superlayer" + (i + 1), 6, 0.5, 6.5)); + LayerEffs.get(si).get(new Coordinate(i)).setTitleX("Layer" ); + LayerEffs.get(si).get(new Coordinate(i)).setTitleY("Efficiency for superlayer "+(i+1) ); + + + LayerEffsTrkD.get(si).put(new Coordinate(i), + new H1F("Sector-"+si+" layer inefficiencies vs trkDoca" + (i + 1), "superlayer" + (i + 1), 40, 0.0, 4.0)); + LayerEffsTrkD.get(si).get(new Coordinate(i)).setTitleX("Track Doca (cm)" ); + LayerEffsTrkD.get(si).get(new Coordinate(i)).setTitleY("Inefficiency for superlayer "+(i+1) ); + + this.setHistosAtt(LayerEffs.get(si).get(new Coordinate(i)), 4); + this.setHistosAtt(LayerEffsTrkD.get(si).get(new Coordinate(i)), 2); + } } - tabbedPane.add("Sector-1 Layer Efficiencies", can1); tabbedPane.add("Sector-2 Layer Efficiencies", can2); tabbedPane.add("Sector-3 Layer Efficiencies", can3); @@ -195,7 +147,7 @@ public boolean init() { tabbedPane.add("Sector-5 Layer Efficiencies", can5); tabbedPane.add("Sector-6 Layer Efficiencies", can6); - tabbedPane.add("Sector-1 Infficiencies vs Track Doca", can7); + tabbedPane.add("Sector-1 Inefficiencies vs Track Doca", can7); tabbedPane.add("Sector-2 Inefficiencies vs Track Doca", can8); tabbedPane.add("Sector-3 Inefficiencies vs Track Doca", can9); tabbedPane.add("Sector-4 Inefficiencies vs Track Doca", can10); @@ -259,75 +211,70 @@ public boolean equals(Object obj) { } } - private Map LayerEffs1 = new HashMap(); - private Map LayerEffs2 = new HashMap(); - private Map LayerEffs3 = new HashMap(); - private Map LayerEffs4 = new HashMap(); - private Map LayerEffs5 = new HashMap(); - private Map LayerEffs6 = new HashMap(); - private Map LayerEffsTrkD1 = new HashMap(); - private Map LayerEffsTrkD2 = new HashMap(); - private Map LayerEffsTrkD3 = new HashMap(); - private Map LayerEffsTrkD4 = new HashMap(); - private Map LayerEffsTrkD5 = new HashMap(); - private Map LayerEffsTrkD6 = new HashMap(); - + private ArrayList> LayerEffs = new ArrayList>(); + private ArrayList> LayerEffsTrkD = new ArrayList>(); - @Override + //instantiate bank writer + RecoBankWriter rbc = new RecoBankWriter(); + HitReader hitRead = new HitReader(); + + @Override public boolean processDataEvent(DataEvent event) { - //setRunConditionsParameters( event) ; - if(event.hasBank("RUN::config")==false) { - System.err.println("RUN CONDITIONS NOT READ AT TIMEBASED LEVEL!"); + if (!event.hasBank("RUN::config")) { return true; } - //if(event.getBank("RECHB::Event").getFloat("startTime", 0)<0) - // return true; // require the start time to reconstruct the tracks in the event - - DataBank bank = event.getBank("RUN::config"); + + DataBank bank = event.getBank("RUN::config"); + long timeStamp = bank.getLong("timestamp", 0); + double triggerPhase = 0; + // Load the constants //------------------- int newRun = bank.getInt("run", 0); - if(newRun==0) - return true; - - double T_Start = 0; - if(Constants.isUSETSTART() == true) { - if(event.hasBank("RECHB::Event")==true) { - T_Start = event.getBank("RECHB::Event").getFloat("startTime", 0); - if(T_Start<0) { - return true; // quit if start time not found in data - } - } else { - return true; // no REC HB bank - } - } - // get Field - Swim dcSwim = new Swim(); + if (newRun == 0) + return true; + + if (Run.get() == 0 || (Run.get() != 0 && Run.get() != newRun)) { + if (timeStamp == -1) + return true; + // if (debug.get()) startTime = System.currentTimeMillis(); + IndexedTable tabJ = super.getConstantsManager().getConstants(newRun, Constants.TIMEJITTER); + double period = tabJ.getDoubleValue("period", 0, 0, 0); + int phase = tabJ.getIntValue("phase", 0, 0, 0); + int cycles = tabJ.getIntValue("cycles", 0, 0, 0); + + if (cycles > 0) triggerPhase = period * ((timeStamp + phase) % cycles); + + TableLoader.FillT0Tables(newRun, super.variationName); + TableLoader.Fill(super.getConstantsManager().getConstants(newRun, Constants.TIME2DIST)); + + Run.set(newRun); + if (event.hasBank("MC::Particle") && this.getEngineConfigString("wireDistort")==null) { + Constants.setWIREDIST(0); + } + } //System.out.println(" RUNNING TIME BASED...................................."); ClusterFitter cf = new ClusterFitter(); ClusterCleanerUtilities ct = new ClusterCleanerUtilities(); - List fhits = new ArrayList(); List clusters = new ArrayList(); List segments = new ArrayList(); - //instantiate bank writer - RecoBankWriter rbc = new RecoBankWriter(); - - HitReader hitRead = new HitReader(); + hitRead.read_HBHits(event, super.getConstantsManager().getConstants(newRun, "/calibration/dc/signal_generation/doca_resolution"), super.getConstantsManager().getConstants(newRun, "/calibration/dc/time_to_distance/time2dist"), Constants.getT0(), Constants.getT0Err(), dcDetector, tde); - hitRead.read_TBHits(event, - super.getConstantsManager().getConstants(newRun, "/calibration/dc/signal_generation/doca_resolution"), - super.getConstantsManager().getConstants(newRun, "/calibration/dc/time_to_distance/time2dist"), tde, Constants.getT0(), Constants.getT0Err()); + //hitRead.read_TBHits(event, + // super.getConstantsManager().getConstants(newRun, "/calibration/dc/signal_generation/doca_resolution"), + // super.getConstantsManager().getConstants(newRun, "/calibration/dc/time_to_distance/time2dist"), tde, Constants.getT0(), Constants.getT0Err()); List hits = new ArrayList(); //I) get the hits - if(hitRead.get_TBHits().isEmpty()) { + if(hitRead.get_HBHits()==null) + return true; + if(!hitRead.get_HBHits().isEmpty()) { hits = hitRead.get_HBHits(); - } else { - hits = hitRead.get_TBHits(); + return true; } //II) process the hits @@ -371,6 +318,7 @@ public boolean processDataEvent(DataEvent event) { index++; } } + event.appendBank(bankE); } return true; @@ -406,178 +354,58 @@ private void ProcessLayerEffs(DataEvent event) { } if(totLay[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][Bank.getByte("layer", i)-1]>0) { - if(Bank.getByte("sector", i)==1) { - float d = effLay[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][Bank.getByte("layer", i)-1]; - float n = totLay[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][Bank.getByte("layer", i)-1]; - float err = (float) (Math.sqrt(d*(d/n+1))/n); - LayerEffs1 - .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) - .setBinContent(Bank.getByte("layer", i)-1,(float)100*d/ (float)n); - LayerEffs1 - .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) - .setBinError(Bank.getByte("layer", i)-1,(float)100*err); - - if(Math.abs(Bank.getFloat("trkDoca", i))<4.0) { - float ddc = effLayA[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][(int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning)))]; - float ndc = totLayA[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][(int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning)))]; - float errdc = (float) (Math.sqrt(ddc*(ddc/ndc+1))/ndc); - LayerEffsTrkD1 - .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) - .setBinContent((int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning))),(float)100*ddc/ (float)ndc); - LayerEffsTrkD1 - .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) - .setBinError((int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning))),(float)100*errdc); - } - } - if(Bank.getByte("sector", i)==2) { - float d = effLay[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][Bank.getByte("layer", i)-1]; - float n = totLay[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][Bank.getByte("layer", i)-1]; - float err = (float) (Math.sqrt(d*(d/n+1))/n); - LayerEffs2 - .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) - .setBinContent(Bank.getByte("layer", i)-1,(float)100*d/ (float)n); - LayerEffs2 - .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) - .setBinError(Bank.getByte("layer", i)-1,(float)100*err); - - if(Math.abs(Bank.getFloat("trkDoca", i))<4.0) { - float ddc = effLayA[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][(int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning)))]; - float ndc = totLayA[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][(int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning)))]; - float errdc = (float) (Math.sqrt(ddc*(ddc/ndc+1))/ndc); - LayerEffsTrkD2 - .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) - .setBinContent((int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning))),(float)100*ddc/ (float)ndc); - LayerEffsTrkD2 - .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) - .setBinError((int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning))),(float)100*errdc); - } - } - if(Bank.getByte("sector", i)==3) { - float d = effLay[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][Bank.getByte("layer", i)-1]; - float n = totLay[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][Bank.getByte("layer", i)-1]; - float err = (float) (Math.sqrt(d*(d/n+1))/n); - LayerEffs3 - .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) - .setBinContent(Bank.getByte("layer", i)-1,(float)100*d/ (float)n); - LayerEffs3 - .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) - .setBinError(Bank.getByte("layer", i)-1,(float)100*err); - - if(Math.abs(Bank.getFloat("trkDoca", i))<4.0) { - float ddc = effLayA[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][(int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning)))]; - float ndc = totLayA[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][(int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning)))]; - float errdc = (float) (Math.sqrt(ddc*(ddc/ndc+1))/ndc); - LayerEffsTrkD3 - .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) - .setBinContent((int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning))),(float)100*ddc/ (float)ndc); - LayerEffsTrkD3 - .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) - .setBinError((int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning))),(float)100*errdc); - } - } - if(Bank.getByte("sector", i)==4) { - float d = effLay[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][Bank.getByte("layer", i)-1]; - float n = totLay[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][Bank.getByte("layer", i)-1]; - float err = (float) (Math.sqrt(d*(d/n+1))/n); - LayerEffs4 - .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) - .setBinContent(Bank.getByte("layer", i)-1,(float)100*d/ (float)n); - LayerEffs4 - .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) - .setBinError(Bank.getByte("layer", i)-1,(float)100*err); - - if(Math.abs(Bank.getFloat("trkDoca", i))<4.0) { - float ddc = effLayA[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][(int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning)))]; - float ndc = totLayA[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][(int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning)))]; - float errdc = (float) (Math.sqrt(ddc*(ddc/ndc+1))/ndc); - LayerEffsTrkD4 - .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) - .setBinContent((int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning))),(float)100*ddc/ (float)ndc); - LayerEffsTrkD4 - .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) - .setBinError((int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning))),(float)100*errdc); - } - } - if(Bank.getByte("sector", i)==5) { - float d = effLay[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][Bank.getByte("layer", i)-1]; - float n = totLay[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][Bank.getByte("layer", i)-1]; - float err = (float) (Math.sqrt(d*(d/n+1))/n); - LayerEffs5 - .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) + float d = effLay[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][Bank.getByte("layer", i)-1]; + float n = totLay[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][Bank.getByte("layer", i)-1]; + float err = (float) (Math.sqrt(d*(d/n+1))/n); + + LayerEffs.get(Bank.getByte("sector", i)-1).get(new Coordinate(Bank.getByte("superlayer", i) - 1)) .setBinContent(Bank.getByte("layer", i)-1,(float)100*d/ (float)n); - LayerEffs5 - .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) + LayerEffs.get(Bank.getByte("sector", i)-1).get(new Coordinate(Bank.getByte("superlayer", i) - 1)) .setBinError(Bank.getByte("layer", i)-1,(float)100*err); - - if(Math.abs(Bank.getFloat("trkDoca", i))<4.0) { + if(Math.abs(Bank.getFloat("trkDoca", i))<4.0) { float ddc = effLayA[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][(int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning)))]; float ndc = totLayA[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][(int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning)))]; float errdc = (float) (Math.sqrt(ddc*(ddc/ndc+1))/ndc); - LayerEffsTrkD5 + LayerEffsTrkD.get(Bank.getByte("sector", i)-1) .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) .setBinContent((int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning))),(float)100*ddc/ (float)ndc); - LayerEffsTrkD5 + LayerEffsTrkD.get(Bank.getByte("sector", i)-1) .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) .setBinError((int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning))),(float)100*errdc); - } - } - if(Bank.getByte("sector", i)==6) { - float d = effLay[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][Bank.getByte("layer", i)-1]; - float n = totLay[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][Bank.getByte("layer", i)-1]; - float err = (float) (Math.sqrt(d*(d/n+1))/n); - LayerEffs6 - .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) - .setBinContent(Bank.getByte("layer", i)-1,(float)100*d/ (float)n); - LayerEffs6 - .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) - .setBinError(Bank.getByte("layer", i)-1,(float)100*err); - - if(Math.abs(Bank.getFloat("trkDoca", i))<4.0) { - float ddc = effLayA[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][(int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning)))]; - float ndc = totLayA[Bank.getByte("sector", i)-1][Bank.getByte("superlayer", i)-1][(int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning)))]; - float errdc = (float) (Math.sqrt(ddc*(ddc/ndc+1))/ndc); - LayerEffsTrkD6 - .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) - .setBinContent((int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning))),(float)100*ddc/ (float)ndc); - LayerEffsTrkD6 - .get(new Coordinate(Bank.getByte("superlayer", i) - 1)) - .setBinError((int)((Math.floor(Math.abs(Bank.getFloat("trkDoca", i))/trkDBinning))),(float)100*errdc); - } - } - } - } - - } + } + } + } + } private void drawPlots() { for (int i = 0; i < 6; i++) { can1.cd(i); - can1.draw(LayerEffs1.get(new Coordinate(i)), "E"); + can1.draw(LayerEffs.get(0).get(new Coordinate(i)), "E"); can2.cd(i); - can2.draw(LayerEffs2.get(new Coordinate(i)), "E"); + can2.draw(LayerEffs.get(1).get(new Coordinate(i)), "E"); can3.cd(i); - can3.draw(LayerEffs3.get(new Coordinate(i)), "E"); + can3.draw(LayerEffs.get(2).get(new Coordinate(i)), "E"); can4.cd(i); - can4.draw(LayerEffs4.get(new Coordinate(i)), "E"); + can4.draw(LayerEffs.get(3).get(new Coordinate(i)), "E"); can5.cd(i); - can5.draw(LayerEffs5.get(new Coordinate(i)), "E"); + can5.draw(LayerEffs.get(4).get(new Coordinate(i)), "E"); can6.cd(i); - can6.draw(LayerEffs6.get(new Coordinate(i)), "E"); + can6.draw(LayerEffs.get(5).get(new Coordinate(i)), "E"); can7.cd(i); - can7.draw(LayerEffsTrkD1.get(new Coordinate(i)), "E"); + can7.draw(LayerEffsTrkD.get(0).get(new Coordinate(i)), "E"); can8.cd(i); - can8.draw(LayerEffsTrkD2.get(new Coordinate(i)), "E"); + can8.draw(LayerEffsTrkD.get(1).get(new Coordinate(i)), "E"); can9.cd(i); - can9.draw(LayerEffsTrkD3.get(new Coordinate(i)), "E"); + can9.draw(LayerEffsTrkD.get(2).get(new Coordinate(i)), "E"); can10.cd(i); - can10.draw(LayerEffsTrkD4.get(new Coordinate(i)), "E"); + can10.draw(LayerEffsTrkD.get(3).get(new Coordinate(i)), "E"); can11.cd(i); - can11.draw(LayerEffsTrkD5.get(new Coordinate(i)), "E"); + can11.draw(LayerEffsTrkD.get(4).get(new Coordinate(i)), "E"); can12.cd(i); - can12.draw(LayerEffsTrkD6.get(new Coordinate(i)), "E"); + can12.draw(LayerEffsTrkD.get(5).get(new Coordinate(i)), "E"); can7.getPad(i).getAxisX().setRange(0, this.maxDoca[i]); can8.getPad(i).getAxisX().setRange(0, this.maxDoca[i]); @@ -614,18 +442,10 @@ public void saveHistosToFile(String fileName) { dir.cd(folder); for (int i = 0; i < 6; i++) { - dir.addDataSet(LayerEffs1.get(new Coordinate(i))); - dir.addDataSet(LayerEffs2.get(new Coordinate(i))); - dir.addDataSet(LayerEffs3.get(new Coordinate(i))); - dir.addDataSet(LayerEffs4.get(new Coordinate(i))); - dir.addDataSet(LayerEffs5.get(new Coordinate(i))); - dir.addDataSet(LayerEffs6.get(new Coordinate(i))); - dir.addDataSet(LayerEffsTrkD1.get(new Coordinate(i))); - dir.addDataSet(LayerEffsTrkD2.get(new Coordinate(i))); - dir.addDataSet(LayerEffsTrkD3.get(new Coordinate(i))); - dir.addDataSet(LayerEffsTrkD4.get(new Coordinate(i))); - dir.addDataSet(LayerEffsTrkD5.get(new Coordinate(i))); - dir.addDataSet(LayerEffsTrkD6.get(new Coordinate(i))); + for (int si = 0; si < 6; si++) { + dir.addDataSet(LayerEffs.get(si).get(new Coordinate(i))); + dir.addDataSet(LayerEffsTrkD.get(si).get(new Coordinate(i))); + } } System.out.println("Saving histograms to file " + fileName); dir.writeFile(fileName); @@ -639,11 +459,10 @@ public static void main(String[] args) { screensize = Toolkit.getDefaultToolkit().getScreenSize(); frame.setSize((int) (screensize.getHeight() * .75 * 1.618), (int) (screensize.getHeight() * .75)); - LayerEfficiencyAnalyzer tm = new LayerEfficiencyAnalyzer(); + MagFieldsEngine enf = new MagFieldsEngine(); enf.init(); - DCHBEngine en = new DCHBEngine(); - en.init(); + LayerEfficiencyAnalyzer tm = new LayerEfficiencyAnalyzer(); tm.init(); frame.add(tm.mainPanel); @@ -661,13 +480,13 @@ public static void main(String[] args) { while (reader.hasEvent()) { counter++; DataEvent event = reader.getNextEvent(); - enf.processDataEvent(event); - en.processDataEvent(event); tm.processDataEvent(event); tm.ProcessLayerEffs(event); //event.show(); - if(counter%1000==0) + if(counter%1000==0) { + System.out.println(counter); tm.drawPlots(); + } } tm.drawPlots(); tm.saveHistosToFile("dclayereffs.hipo"); diff --git a/reconstruction/dc/src/main/java/org/jlab/service/dc/TrackDictionaryMaker.java b/reconstruction/dc/src/main/java/org/jlab/service/dc/TrackDictionaryMaker.java index 1ee0bea748..5b33cb3ed7 100644 --- a/reconstruction/dc/src/main/java/org/jlab/service/dc/TrackDictionaryMaker.java +++ b/reconstruction/dc/src/main/java/org/jlab/service/dc/TrackDictionaryMaker.java @@ -618,7 +618,7 @@ public void setWl6(List Wl6) { private void resetGeom(String geomDBVar) { ConstantProvider provider = GeometryFactory.getConstants(DetectorType.DC, 11, Optional.ofNullable(geomDBVar).orElse("default")); - dcDetector = new DCGeant4Factory(provider, DCGeant4Factory.MINISTAGGERON); + dcDetector = new DCGeant4Factory(provider, DCGeant4Factory.MINISTAGGERON, DCGeant4Factory.ENDPLATESBOWON); for(int l=0; l<6; l++) { Constants.wpdist[l] = provider.getDouble("/geometry/dc/superlayer/wpdist", l); diff --git a/reconstruction/dc/src/main/java/org/jlab/service/dc/TrackDictionaryMakerRNG.java b/reconstruction/dc/src/main/java/org/jlab/service/dc/TrackDictionaryMakerRNG.java index 0aaeae68d3..6ccb4dac21 100644 --- a/reconstruction/dc/src/main/java/org/jlab/service/dc/TrackDictionaryMakerRNG.java +++ b/reconstruction/dc/src/main/java/org/jlab/service/dc/TrackDictionaryMakerRNG.java @@ -380,6 +380,7 @@ public void ProcessTracks(PrintWriter pw,DCGeant4Factory dcDetector, wires.add(pcalV); wires.add(pcalW); wires.add(htcc); + wires.add(sector); if(newDictionary.containsKey(wires) && duplicates!=0) { int nRoad = newDictionary.get(wires) + 1; newDictionary.replace(wires, nRoad); @@ -410,7 +411,8 @@ public void ProcessTracks(PrintWriter pw,DCGeant4Factory dcDetector, + "%d\t%d\t%d\t%d\t%d\t%d\t" + "%d\t%d\t%d\t%d\t%d\t%d\t" + "%d\t%d\t%d\t%d\t%d\t%d\t" - + "%d\t%.2f\t%d\t%d\t%d\t%d\t%d\n", + + "%d\t%.2f\t%d\t%d\t%d\t%d\t" + + "%d\t%d\t0.0\t0.0\t0.0\n", q, p, thetaDeg, phiDeg, Wl1.get(0), Wl2.get(0), Wl3.get(0), Wl4.get(0), Wl5.get(0), Wl6.get(0), Wl1.get(1), Wl2.get(1), Wl3.get(1), Wl4.get(1), Wl5.get(1), Wl6.get(1), @@ -418,7 +420,7 @@ public void ProcessTracks(PrintWriter pw,DCGeant4Factory dcDetector, Wl1.get(3), Wl2.get(3), Wl3.get(3), Wl4.get(3), Wl5.get(3), Wl6.get(3), Wl1.get(4), Wl2.get(4), Wl3.get(4), Wl4.get(4), Wl5.get(4), Wl6.get(4), Wl1.get(5), Wl2.get(5), Wl3.get(5), Wl4.get(5), Wl5.get(5), Wl6.get(5), - paddle1b, vzCm, paddle2, pcalU, pcalV, pcalW, htcc); + paddle1b, vzCm, paddle2, pcalU, pcalV, pcalW, htcc, sector); } } } @@ -669,7 +671,7 @@ public void setWl6(List Wl6) { private void resetGeom(String geomDBVar) { ConstantProvider provider = GeometryFactory.getConstants(DetectorType.DC, 11, Optional.ofNullable(geomDBVar).orElse("default")); - dcDetector = new DCGeant4Factory(provider, DCGeant4Factory.MINISTAGGERON); + dcDetector = new DCGeant4Factory(provider, DCGeant4Factory.MINISTAGGERON, DCGeant4Factory.ENDPLATESBOWON); for(int l=0; l<6; l++) { Constants.wpdist[l] = provider.getDouble("/geometry/dc/superlayer/wpdist", l); diff --git a/reconstruction/dc/src/main/java/org/jlab/service/dc/TrackDictionaryMerger.java b/reconstruction/dc/src/main/java/org/jlab/service/dc/TrackDictionaryMerger.java index 3ba6137759..4e63e7fd62 100644 --- a/reconstruction/dc/src/main/java/org/jlab/service/dc/TrackDictionaryMerger.java +++ b/reconstruction/dc/src/main/java/org/jlab/service/dc/TrackDictionaryMerger.java @@ -86,12 +86,14 @@ public void readDictionary(String fileName) { int pcalv = Integer.parseInt(lineValues[44]); int pcalw = Integer.parseInt(lineValues[45]); int htcc = Integer.parseInt(lineValues[46]); + int sector = Integer.parseInt(lineValues[47]); wires.add((byte) paddle1b); wires.add((byte) paddle2); wires.add((byte) pcalu); wires.add((byte) pcalv); wires.add((byte) pcalw); wires.add((byte) htcc); + wires.add((byte) sector); nFull++; this.nfull++; if(this.dictionary.containsKey(wires)) { @@ -145,6 +147,7 @@ private void writeDictionary(String dictName) { int pcalV = road.get(9); int pcalW = road.get(10); int htcc = road.get(11); + int sector = road.get(12); pw.printf("%d\t%.2f\t%.2f\t%.2f\t" + "%d\t%d\t%d\t%d\t%d\t%d\t" + "%d\t%d\t%d\t%d\t%d\t%d\t" @@ -153,7 +156,7 @@ private void writeDictionary(String dictName) { + "%d\t%d\t%d\t%d\t%d\t%d\t" + "%d\t%d\t%d\t%d\t%d\t%d\t" + "%d\t%.2f\t%d\t%d\t%d\t%d\t" - + "%d\n", + + "%d\t%d\n", //+ "%.1f\t %.1f\t %.1f\t %.1f\t %.1f\t %.1f\t\n", part.charge(), part.p(), Math.toDegrees(part.theta()), Math.toDegrees(part.phi()), road.get(0), 0, 0, 0, 0, 0, @@ -162,7 +165,7 @@ private void writeDictionary(String dictName) { road.get(3), 0, 0, 0, 0, 0, road.get(4), 0, 0, 0, 0, 0, road.get(5), 0, 0, 0, 0, 0, - paddle1b, part.vz(), paddle2, pcalU, pcalV, pcalW, htcc); + paddle1b, part.vz(), paddle2, pcalU, pcalV, pcalW, htcc, sector); } } pw.close(); diff --git a/reconstruction/dc/src/main/java/org/jlab/service/dc/TrackDictionaryValidation.java b/reconstruction/dc/src/main/java/org/jlab/service/dc/TrackDictionaryValidation.java index 1be9c635ac..57e21f3972 100644 --- a/reconstruction/dc/src/main/java/org/jlab/service/dc/TrackDictionaryValidation.java +++ b/reconstruction/dc/src/main/java/org/jlab/service/dc/TrackDictionaryValidation.java @@ -131,18 +131,19 @@ public void createDictionary(String inputFileName, String dictName , int pidSele // save particle information Particle part = new Particle( -11*charge, - recParticle.getFloat("px", i), - recParticle.getFloat("py", i), - recParticle.getFloat("pz", i), - recParticle.getFloat("vx", i), - recParticle.getFloat("vy", i), - recParticle.getFloat("vz", i)); + recParticle.getFloat("px", pindex), + recParticle.getFloat("py", pindex), + recParticle.getFloat("pz", pindex), + recParticle.getFloat("vx", pindex), + recParticle.getFloat("vy", pindex), + recParticle.getFloat("vz", pindex)); if(part.p() wires, int dcSmear, int pcalUSmear, in wiresCopy.set(4, (byte) (wires.get(4) + k5)); wiresCopy.set(5, (byte) (wires.get(5) + k6)); wiresCopy.set(6, (byte) (wires.get(6) + k7)); + wiresCopy.set(7, (byte) 0); //panel 2 wiresCopy.set(8, (byte) (wires.get(8) + k8)); wiresCopy.set(9, (byte) (wires.get(9) + k9)); wiresCopy.set(10,(byte) (wires.get(10)+ k10)); + wiresCopy.set(11, (byte) 0); //htcc + wiresCopy.set(12,(byte) (wires.get(12))); if(this.dictionary.containsKey(wiresCopy)) { foundRoad=this.dictionary.get(wiresCopy); break; @@ -814,12 +835,12 @@ public void processFile(String fileName, int wireSmear, int pcalSmear, int mode, // save particle information Particle part = new Particle( -11*charge, - recParticle.getFloat("px", i), - recParticle.getFloat("py", i), - recParticle.getFloat("pz", i), - recParticle.getFloat("vx", i), - recParticle.getFloat("vy", i), - recParticle.getFloat("vz", i)); + recParticle.getFloat("px", pindex), + recParticle.getFloat("py", pindex), + recParticle.getFloat("pz", pindex), + recParticle.getFloat("vx", pindex), + recParticle.getFloat("vy", pindex), + recParticle.getFloat("vz", pindex)); boolean goodTrack=true; // meglect tracks below 1 GeV if(part.p() 2) { + if (recCherenkov != null && htccRec != null && htccADC != null && mode > 2 && false) { int htcc_event; // recCherenkov.show(); htccADC.show(); for (int j = 0; j < recCherenkov.rows(); j++) { @@ -919,8 +941,11 @@ public void processFile(String fileName, int wireSmear, int pcalSmear, int mode, int detectorCheren = recCherenkov.getByte("detector", j); if (detectorCheren == DetectorType.HTCC.getDetectorId()) { int nhits = htccRec.getShort("nhits",recCherenkov.getShort("index", j)); - double thetaCheren = recCherenkov.getFloat("theta", j); - double phiCheren = recCherenkov.getFloat("phi", j); + double x = recCherenkov.getFloat("x", j); + double y = recCherenkov.getFloat("y", j); + double z = recCherenkov.getFloat("z", j); + double thetaCheren = Math.acos(z/Math.sqrt(x*x+y*y+z*z)); + double phiCheren = Math.atan2(y, x); thetaCheren = Math.toDegrees(thetaCheren); phiCheren = Math.toDegrees(phiCheren ); double phiCC = Math.round(phiCheren); @@ -969,10 +994,11 @@ public void processFile(String fileName, int wireSmear, int pcalSmear, int mode, wires.add((byte) pcalV); wires.add((byte) pcalW); wires.add((byte) htcc); + wires.add((byte) trackSector); if(mode>0 && (paddle1b==0 || pcalU==0)) continue; if(mode>1 && (paddle1b==0 || pcalU==0 || pcalV==0 || pcalW==0)) continue; - if(mode>2 && (paddle1b==0 || pcalU==0 || pcalV==0 || pcalW==0 || htcc==0)) continue; - double phi = (Math.toDegrees(part.phi())+180+30)%60-30; + if(mode>2 && (paddle1b==0 || pcalU==0 || pcalV==0 || pcalW==0 || htcc==-1)) continue; + double phi = (Math.toDegrees(part.phi())+180+30)%60-30; Particle road = this.findRoad(wires,wireSmear,pcalUSmear,pcalVWSmear); if(road != null) { double phiRoad = (Math.toDegrees(road.phi())+180+30)%60-30; @@ -1035,7 +1061,7 @@ public void readDictionary(String fileName, int mode, double thrs) { String[] lineValues; lineValues = line.split("\t"); ArrayList wires = new ArrayList(); - if(lineValues.length < 47) { + if(lineValues.length < 51) { System.out.println("WARNING: dictionary line " + nLines + " incomplete: skipping"); } else { @@ -1049,12 +1075,19 @@ public void readDictionary(String fileName, int mode, double thrs) { double py = p*Math.sin(Math.toRadians(theta))*Math.sin(Math.toRadians(phi)); double pz = p*Math.cos(Math.toRadians(theta)); double phiSec = (phi+360+30)%60-30; + double pcalE = Double.parseDouble(lineValues[48]); + double ecinE = Double.parseDouble(lineValues[49]); + double ecoutE = Double.parseDouble(lineValues[50]); Particle road = new Particle(211*charge, px, py, pz, 0, 0, vz); + road.setProperty("pcalE", pcalE); + road.setProperty("ecinE", ecinE); + road.setProperty("ecoutE", ecoutE); // take wire id of first layer in each superlayer, id>0 for(int i=0; i<6; i++) { int wire = Integer.parseInt(lineValues[4+i*6]); if(wire>0) wires.add((byte) wire); } + int sector = 0; int paddle1b = 0; int paddle2 = 0; int pcalu = 0; @@ -1070,9 +1103,12 @@ public void readDictionary(String fileName, int mode, double thrs) { pcalv = Integer.parseInt(lineValues[44]); pcalw = Integer.parseInt(lineValues[45]); } - if(lineValues.length >=47 & mode>2) { + if(lineValues.length >=47 & mode>2) { htcc = Integer.parseInt(lineValues[46]); - } + } + if(lineValues.length >=48) { + sector = Integer.parseInt(lineValues[47]); + } // keep only roads with 6 superlayers if(wires.size()!=6 || road.p()< thrs) continue; // add other detectors @@ -1082,6 +1118,7 @@ public void readDictionary(String fileName, int mode, double thrs) { wires.add((byte) pcalv); wires.add((byte) pcalw); wires.add((byte) htcc); + wires.add((byte) sector); nFull++; if(this.dictionary.containsKey(wires)) { nDupli++; @@ -1128,7 +1165,7 @@ private void writeDictionary(Map, Particle> dictionary, Strin for(Map.Entry, Particle> entry : dictionary.entrySet()) { ArrayList road = entry.getKey(); Particle part = entry.getValue(); - if(road.size()<12) { + if(road.size()<13) { continue; } else { @@ -1144,6 +1181,7 @@ private void writeDictionary(Map, Particle> dictionary, Strin int pcalV = road.get(9); int pcalW = road.get(10); int htcc = road.get(11); + int sector = road.get(12); pw.printf("%d\t%.2f\t%.2f\t%.2f\t" + "%d\t%d\t%d\t%d\t%d\t%d\t" + "%d\t%d\t%d\t%d\t%d\t%d\t" @@ -1152,7 +1190,7 @@ private void writeDictionary(Map, Particle> dictionary, Strin + "%d\t%d\t%d\t%d\t%d\t%d\t" + "%d\t%d\t%d\t%d\t%d\t%d\t" + "%d\t%.2f\t%d\t%d\t%d\t%d\t" - + "%d\n", + + "%d\t%d\t%.1f\t%.1f\t%.1f\n", //+ "%.1f\t %.1f\t %.1f\t %.1f\t %.1f\t %.1f\t\n", part.charge(), part.p(), Math.toDegrees(part.theta()), Math.toDegrees(part.phi()), road.get(0), 0, 0, 0, 0, 0, @@ -1161,7 +1199,8 @@ private void writeDictionary(Map, Particle> dictionary, Strin road.get(3), 0, 0, 0, 0, 0, road.get(4), 0, 0, 0, 0, 0, road.get(5), 0, 0, 0, 0, 0, - paddle1b, part.vz(), paddle2, pcalU, pcalV, pcalW, htcc); + paddle1b, part.vz(), paddle2, pcalU, pcalV, pcalW, htcc, sector, + part.getProperty("pcalE"), part.getProperty("ecinE"), part.getProperty("ecoutE")); } } pw.close(); diff --git a/reconstruction/dc/src/test/java/org/jlab/service/dc/DCReconstructionTest.java b/reconstruction/dc/src/test/java/org/jlab/service/dc/DCReconstructionTest.java index 97cd6966aa..cb34b82487 100644 --- a/reconstruction/dc/src/test/java/org/jlab/service/dc/DCReconstructionTest.java +++ b/reconstruction/dc/src/test/java/org/jlab/service/dc/DCReconstructionTest.java @@ -17,30 +17,29 @@ import org.jlab.utils.CLASResources; import org.jlab.utils.system.ClasUtilsFile; - /** * - * @author naharrison + * @author nharrison, marmstr */ public class DCReconstructionTest { @Test public void testDCReconstruction() { System.setProperty("CLAS12DIR", "../../"); - + String mapDir = CLASResources.getResourcePath("etc")+"/data/magfield"; - try { - MagneticFields.getInstance().initializeMagneticFields(mapDir, - "Symm_torus_r2501_phi16_z251_24Apr2018.dat","Symm_solenoid_r601_phi1_z1201_13June2018.dat"); - } - catch (Exception e) { - e.printStackTrace(); - } - + try { + MagneticFields.getInstance().initializeMagneticFields(mapDir, + "Symm_torus_r2501_phi16_z251_24Apr2018.dat","Symm_solenoid_r601_phi1_z1201_13June2018.dat"); + } + catch (Exception e) { + e.printStackTrace(); + } + String dir = ClasUtilsFile.getResourceDir("CLAS12DIR", "etc/bankdefs/hipo4"); SchemaFactory schemaFactory = new SchemaFactory(); schemaFactory.initFromDirectory(dir); - + DataEvent testEvent = TestEvent.getDCSector1ElectronEvent(schemaFactory); MagFieldsEngine enf = new MagFieldsEngine(); @@ -48,11 +47,12 @@ public void testDCReconstruction() { enf.processDataEvent(testEvent); DCHBEngine engineHB = new DCHBEngine(); engineHB.init(); - engineHB.processDataEvent(testEvent); + engineHB.processDataEvent(testEvent); if(testEvent.hasBank("HitBasedTrkg::HBTracks")) { testEvent.getBank("HitBasedTrkg::HBTracks").show(); } + //Compare HB momentum to expectation assertEquals(testEvent.hasBank("HitBasedTrkg::HBTracks"), true); assertEquals(testEvent.getBank("HitBasedTrkg::HBTracks").rows(), 1); assertEquals(testEvent.getBank("HitBasedTrkg::HBTracks").getByte("q", 0), -1); @@ -61,21 +61,49 @@ public void testDCReconstruction() { assertEquals(testEvent.getBank("HitBasedTrkg::HBTracks").getFloat("p0_y", 0) < 0.1, true); assertEquals(ClasMath.isWithinXPercent(16.0, testEvent.getBank("HitBasedTrkg::HBTracks").getFloat("p0_z", 0), 2.266), true); + //TB reconstruction DCTBEngine engineTB = new DCTBEngine(); engineTB.init(); - engineTB.processDataEvent(testEvent); + engineTB.processDataEvent(testEvent); if(testEvent.hasBank("TimeBasedTrkg::TBTracks")) { testEvent.getBank("TimeBasedTrkg::TBTracks").show(); } + assertEquals(testEvent.hasBank("TimeBasedTrkg::TBTracks"), true); assertEquals(testEvent.getBank("TimeBasedTrkg::TBTracks").rows(), 1); assertEquals(testEvent.getBank("TimeBasedTrkg::TBTracks").getByte("q", 0), -1); - assertEquals(ClasMath.isWithinXPercent(5.0, testEvent.getBank("TimeBasedTrkg::TBTracks").getFloat("p0_x", 0), 1.057), true); - assertEquals(testEvent.getBank("TimeBasedTrkg::TBTracks").getFloat("p0_y", 0) > -0.05, true); - assertEquals(testEvent.getBank("TimeBasedTrkg::TBTracks").getFloat("p0_y", 0) < 0.05, true); - assertEquals(ClasMath.isWithinXPercent(5.0, testEvent.getBank("TimeBasedTrkg::TBTracks").getFloat("p0_z", 0), 2.266), true); - - } + assertEquals(ClasMath.isWithinXPercent(27.9, testEvent.getBank("TimeBasedTrkg::TBTracks").getFloat("p0_x", 0), 0.997), true); + assertEquals(testEvent.getBank("TimeBasedTrkg::TBTracks").getFloat("p0_y", 0) > -0.0702, true); + assertEquals(testEvent.getBank("TimeBasedTrkg::TBTracks").getFloat("p0_y", 0) < 0.0438, true); + assertEquals(ClasMath.isWithinXPercent(17.5, testEvent.getBank("TimeBasedTrkg::TBTracks").getFloat("p0_z", 0), 2.04), true); + + assertEquals(testEvent.getBank("TimeBasedTrkg::TBTracks").getFloat("Vtx0_x", 0) < 0.2, true); + assertEquals(testEvent.getBank("TimeBasedTrkg::TBTracks").getFloat("Vtx0_x", 0) > -0.2, true); + assertEquals(testEvent.getBank("TimeBasedTrkg::TBTracks").getFloat("Vtx0_y", 0) < 0.18, true); + assertEquals(testEvent.getBank("TimeBasedTrkg::TBTracks").getFloat("Vtx0_y", 0) > -0.228, true); + assertEquals(testEvent.getBank("TimeBasedTrkg::TBTracks").getFloat("Vtx0_z", 0) < 0.885, true); + assertEquals(testEvent.getBank("TimeBasedTrkg::TBTracks").getFloat("Vtx0_z", 0) > -0.0753, true); + + + //Region 1 + assertEquals(ClasMath.isWithinXPercent(155, testEvent.getBank("TimeBasedTrkg::TBCrosses").getFloat("x", 0), 4.02), true); + assertEquals(testEvent.getBank("TimeBasedTrkg::TBCrosses").getFloat("y", 0 ) < 9.25, true); + assertEquals(testEvent.getBank("TimeBasedTrkg::TBCrosses").getFloat("y", 0 ) > -11.78, true); + + //Region 2 + assertEquals(testEvent.getBank("TimeBasedTrkg::TBCrosses").getFloat("x", 1 ) < 14.2, true); + assertEquals(testEvent.getBank("TimeBasedTrkg::TBCrosses").getFloat("x", 1 ) > -5.8, true); + assertEquals(testEvent.getBank("TimeBasedTrkg::TBCrosses").getFloat("y", 1 ) < 13.9, true); + assertEquals(testEvent.getBank("TimeBasedTrkg::TBCrosses").getFloat("y", 1 ) > -17.8, true); + + //Region 3 + assertEquals(ClasMath.isWithinXPercent(127, testEvent.getBank("TimeBasedTrkg::TBCrosses").getFloat("x", 2), -11.0), true); + assertEquals(testEvent.getBank("TimeBasedTrkg::TBCrosses").getFloat("y", 2 ) < 17.96, true); + assertEquals(testEvent.getBank("TimeBasedTrkg::TBCrosses").getFloat("y", 2 ) > -23.66, true); + + + } + } diff --git a/reconstruction/eb/pom.xml b/reconstruction/eb/pom.xml index d957aa7510..124433e690 100644 --- a/reconstruction/eb/pom.xml +++ b/reconstruction/eb/pom.xml @@ -26,7 +26,7 @@ org.jlab.clas clas12rec ../../parent/pom.xml - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT @@ -47,25 +47,25 @@ org.jlab.clas clas-utils - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-io - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-reco - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-analysis - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT diff --git a/reconstruction/eb/src/main/java/org/jlab/rec/eb/EBUtil.java b/reconstruction/eb/src/main/java/org/jlab/rec/eb/EBUtil.java index 7cb8db0b01..13fe86df54 100644 --- a/reconstruction/eb/src/main/java/org/jlab/rec/eb/EBUtil.java +++ b/reconstruction/eb/src/main/java/org/jlab/rec/eb/EBUtil.java @@ -2,6 +2,7 @@ import static java.lang.Math.abs; import static java.lang.Math.pow; +import java.util.List; import org.jlab.clas.detector.DetectorResponse; import org.jlab.clas.detector.DetectorParticle; import org.jlab.detector.base.DetectorType; @@ -72,12 +73,29 @@ else if (resp.getDescriptor().getType()==DetectorType.CTOF) { return 0.065; } else { - throw new RuntimeException("not ready for non-TOF"); + return 0;//throw new RuntimeException("not ready for non-TOF"); } return ccdb.getTable(tableName). getDoubleValue("tres",sector,layer,component); } + /** + * Calculate beta for given detector type/layer, prioritized by layer: + */ + public static double getNeutralBeta(DetectorParticle p, DetectorType type, List layers,double startTime) { + double beta=-9999; + for (int layer : layers) { + DetectorResponse resp = p.getHit(type,layer); + if (resp!=null) { + beta = resp.getPosition().mag() / + (resp.getTime()-startTime) / + PhysicsConstants.speedOfLight(); + break; + } + } + return beta; + } + /** * Calculate beta for given detector type/layer, prioritized by layer: */ diff --git a/reconstruction/eb/src/main/java/org/jlab/service/eb/EBAnalyzer.java b/reconstruction/eb/src/main/java/org/jlab/service/eb/EBAnalyzer.java index 9df997867a..49b0b0847f 100644 --- a/reconstruction/eb/src/main/java/org/jlab/service/eb/EBAnalyzer.java +++ b/reconstruction/eb/src/main/java/org/jlab/service/eb/EBAnalyzer.java @@ -2,7 +2,11 @@ import static java.lang.Math.abs; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; +import java.util.Map; +import java.util.LinkedHashMap; +import java.util.Map.Entry; import org.jlab.clas.detector.DetectorEvent; import org.jlab.clas.detector.DetectorParticle; @@ -34,9 +38,27 @@ public class EBAnalyzer { static final int[] PID_NEGATIVE = new int[]{ 11, -211,-321,-2212}; static final int[] PID_NEUTRAL = new int[]{22,2112}; + Map > chargedBetaDetectors; + Map > neutralBetaDetectors; + public EBAnalyzer(EBCCDBConstants ccdb,EBRadioFrequency ebrf) { this.ccdb=ccdb; this.ebrf=ebrf; + + // setup prioritization on timing detectors: + chargedBetaDetectors=new LinkedHashMap<>(); + chargedBetaDetectors.put(DetectorType.FTOF,Arrays.asList(2,1,3)); + chargedBetaDetectors.put(DetectorType.CTOF,Arrays.asList(1)); + chargedBetaDetectors.put(DetectorType.ECAL,Arrays.asList(1,4,7)); + //chargedBetaDetectors.put(DetectorType.HTCC,Arrays.asList(0)); + //chargedBetaDetectors.put(DetectorType.CND,Arrays.asList(0)); + //chargedBetaDetectors.put(DetectorType.FTCAL,Arrays.asList(0)); + neutralBetaDetectors=new LinkedHashMap<>(); + neutralBetaDetectors.put(DetectorType.ECAL,Arrays.asList(1,4,7)); + neutralBetaDetectors.put(DetectorType.CND,Arrays.asList(0)); + neutralBetaDetectors.put(DetectorType.FTCAL,Arrays.asList(0)); + //neutralBetaDetectors.put(DetectorType.FTOF,Arrays.asList(2,1,3)); + //neutralBetaDetectors.put(DetectorType.CTOF,Arrays.asList(0)); } @@ -282,6 +304,8 @@ public void assignBetas(DetectorEvent event,final boolean useStartTimeFromFT){ for (DetectorParticle p : event.getParticles()) { double beta = -99; + final double thisStartTime = p.getCharge()==0 ? startTime : p.getStartTime(); + if (p.isTriggerParticle()) { final double mass = PDGDatabase.getParticleById(p.getPid()).mass(); final double mom = p.vector().mag(); @@ -289,36 +313,30 @@ public void assignBetas(DetectorEvent event,final boolean useStartTimeFromFT){ } else { if (p.getCharge()==0) { - if (p.hasHit(DetectorType.ECAL)) { - // NOTE: prioritized by layer: PCAL, else Inner, else Outer - beta = EBUtil.getNeutralBeta(p,DetectorType.ECAL,new int[]{1,4,7},startTime); - } - else if (p.hasHit(DetectorType.CND)) { - beta = EBUtil.getNeutralBeta(p,DetectorType.CND,0,startTime); - } - else if (p.hasHit(DetectorType.FTCAL)) { - beta = EBUtil.getNeutralBeta(p,DetectorType.FTCAL,0,startTime); + for (Entry> bd : neutralBetaDetectors.entrySet()) { + if (p.hasHit(bd.getKey())) { + beta = EBUtil.getNeutralBeta(p,bd.getKey(),bd.getValue(),startTime); + break; + } } } else { - if (p.hasHit(DetectorType.FTOF, 2)==true){ - beta = p.getBeta(DetectorType.FTOF,2, p.getStartTime()); - } - else if(p.hasHit(DetectorType.FTOF, 1)==true){ - beta = p.getBeta(DetectorType.FTOF, 1,p.getStartTime()); - } - else if(p.hasHit(DetectorType.CTOF)==true){ - beta = p.getBeta(DetectorType.CTOF ,p.getStartTime()); - } - else if(p.hasHit(DetectorType.FTOF, 3)==true){ - beta = p.getBeta(DetectorType.FTOF, 3,p.getStartTime()); + boolean found=false; + for (Entry> bd : chargedBetaDetectors.entrySet()) { + for (Integer layer : bd.getValue()) { + if (p.hasHit(bd.getKey(),layer)) { + beta = p.getBeta(bd.getKey(),layer, p.getStartTime()); + found=true; + break; + } + } + if (found) break; } } } p.setBeta(beta); } } - public void assignPids(DetectorEvent event,final boolean useStartTimeFromFT) { PIDHypothesis pidHyp = new PIDHypothesis(); @@ -470,14 +488,17 @@ else if (p.hasHit(DetectorType.CND)) { for (int ii=0; ii> bd : chargedBetaDetectors.entrySet()) { + for (Integer layer : bd.getValue()) { + if (p.hasHit(bd.getKey(),layer)==true) { + dt = p.getVertexTime(bd.getKey(),layer,hypotheses[ii])-p.getStartTime(); + found=true; + break; + } + } + if (found) break; + } if ( abs(dt) < minTimeDiff ) { minTimeDiff=abs(dt); bestPid=hypotheses[ii]; @@ -487,7 +508,6 @@ else if (p.hasHit(DetectorType.FTOF,3)==true) return bestPid; } - /** * Get a basic pid quality factor. * @param p the particle for which to calculate a pid quality factor @@ -511,23 +531,21 @@ else if (abs(pid)==11) { else if (p.getCharge()!=0) { double sigma = -1; double delta_t = 99999; - if (p.hasHit(DetectorType.FTOF,2)==true) { - sigma = EBUtil.getDetTimingResolution(p.getHit(DetectorType.FTOF,2),ccdb); - delta_t = p.getVertexTime(DetectorType.FTOF, 2, pid)-p.getStartTime(); - } - else if (p.hasHit(DetectorType.FTOF,1)==true) { - sigma = EBUtil.getDetTimingResolution(p.getHit(DetectorType.FTOF,1),ccdb); - delta_t = p.getVertexTime(DetectorType.FTOF, 1, pid)-p.getStartTime(); - } - else if (p.hasHit(DetectorType.CTOF)==true) { - sigma = EBUtil.getDetTimingResolution(p.getHit(DetectorType.CTOF,0),ccdb); - delta_t = p.getVertexTime(DetectorType.CTOF, 0, pid)-p.getStartTime(); - } - else if (p.hasHit(DetectorType.FTOF,3)==true) { - sigma = EBUtil.getDetTimingResolution(p.getHit(DetectorType.FTOF,3),ccdb); - delta_t = p.getVertexTime(DetectorType.FTOF, 3, pid)-p.getStartTime(); + + boolean found=false; + for (Entry> bd : chargedBetaDetectors.entrySet()) { + for (Integer layer : bd.getValue()) { + if (p.hasHit(bd.getKey(),layer)==true) { + sigma = EBUtil.getDetTimingResolution(p.getHit(bd.getKey(),layer),ccdb); + if (sigma>0) delta_t = p.getVertexTime(bd.getKey(),layer, pid)-p.getStartTime(); + found=true; + break; + } + if (found) break; + } + if (found) break; } - q = delta_t / sigma; + if (sigma>0) q = delta_t / sigma; } // neutrals: diff --git a/reconstruction/eb/src/main/java/org/jlab/service/eb/EBEngine.java b/reconstruction/eb/src/main/java/org/jlab/service/eb/EBEngine.java index 2de53b6ecd..e94f422319 100644 --- a/reconstruction/eb/src/main/java/org/jlab/service/eb/EBEngine.java +++ b/reconstruction/eb/src/main/java/org/jlab/service/eb/EBEngine.java @@ -23,6 +23,7 @@ public class EBEngine extends ReconstructionEngine { boolean dropBanks = false; boolean alreadyDroppedBanks = false; + boolean usePOCA = false; // output banks: String eventBank = null; @@ -53,6 +54,10 @@ public void initBankNames() { //Initialize bank names } + public void setUsePOCA(boolean val) { + this.usePOCA=val; + } + @Override public boolean processDataEvent(DataEvent de) { throw new RuntimeException("EBEngine cannot be used directly. Use EBTBEngine/EBHBEngine instead."); @@ -77,6 +82,7 @@ public boolean processDataEvent(DataEvent de,EBScalers ebs) { DetectorHeader head = EBio.readHeader(de,ebs,ccdb); EventBuilder eb = new EventBuilder(ccdb); + eb.setUsePOCA(this.usePOCA); eb.initEvent(head); // clear particles EBMatching ebm = new EBMatching(eb); @@ -265,6 +271,8 @@ public void dropBanks(DataEvent de) { } de.removeBank(eventBank); de.removeBank(particleBank); + de.removeBank(eventBankFT); + de.removeBank(particleBankFT); de.removeBank(calorimeterBank); de.removeBank(scintillatorBank); de.removeBank(cherenkovBank); diff --git a/reconstruction/eb/src/main/java/org/jlab/service/eb/EBHBEngine.java b/reconstruction/eb/src/main/java/org/jlab/service/eb/EBHBEngine.java index eb4f60bbc7..ba460f9e90 100644 --- a/reconstruction/eb/src/main/java/org/jlab/service/eb/EBHBEngine.java +++ b/reconstruction/eb/src/main/java/org/jlab/service/eb/EBHBEngine.java @@ -14,6 +14,7 @@ public class EBHBEngine extends EBEngine { public EBHBEngine(){ super("EBHB"); + setUsePOCA(true); } @Override diff --git a/reconstruction/eb/src/main/java/org/jlab/service/eb/EBTBEngine.java b/reconstruction/eb/src/main/java/org/jlab/service/eb/EBTBEngine.java index 50b3126567..2e95035b5d 100644 --- a/reconstruction/eb/src/main/java/org/jlab/service/eb/EBTBEngine.java +++ b/reconstruction/eb/src/main/java/org/jlab/service/eb/EBTBEngine.java @@ -14,6 +14,7 @@ public class EBTBEngine extends EBEngine { public EBTBEngine(){ super("EBTB"); + setUsePOCA(false); } @Override diff --git a/reconstruction/eb/src/main/java/org/jlab/service/eb/EBio.java b/reconstruction/eb/src/main/java/org/jlab/service/eb/EBio.java index e70a5450b5..916d966e78 100644 --- a/reconstruction/eb/src/main/java/org/jlab/service/eb/EBio.java +++ b/reconstruction/eb/src/main/java/org/jlab/service/eb/EBio.java @@ -111,14 +111,16 @@ public static List readCentralTracks(DataEvent event){ double tandip = bank.getDouble("tandip", i); double z0 = bank.getDouble("z0", i); double d0 = bank.getDouble("d0", i); + double xb = bank.getDouble("xb", i); + double yb = bank.getDouble("yb", i); DetectorParticle part = new DetectorParticle(); double pz = pt*tandip; double py = pt*Math.sin(phi0); double px = pt*Math.cos(phi0); - double vx = d0*Math.cos(phi0); - double vy = d0*Math.sin(phi0); + double vx = -d0*Math.sin(phi0)+xb; + double vy = d0*Math.cos(phi0)+yb; part.vector().setXYZ(px, py, pz); part.vertex().setXYZ(vx, vy, z0); diff --git a/reconstruction/eb/src/main/java/org/jlab/service/eb/EventBuilder.java b/reconstruction/eb/src/main/java/org/jlab/service/eb/EventBuilder.java index 6179b6912c..5147c83e87 100644 --- a/reconstruction/eb/src/main/java/org/jlab/service/eb/EventBuilder.java +++ b/reconstruction/eb/src/main/java/org/jlab/service/eb/EventBuilder.java @@ -14,6 +14,7 @@ import org.jlab.clas.detector.DetectorHeader; import org.jlab.clas.detector.DetectorEvent; import org.jlab.clas.detector.DetectorParticle; +import org.jlab.clas.detector.DetectorParticleTraj; import org.jlab.clas.detector.DetectorResponse; import org.jlab.clas.detector.DetectorTrack; import org.jlab.clas.detector.TaggerResponse; @@ -38,10 +39,15 @@ public class EventBuilder { private static final int[] TRIGGERLIST = new int[]{11,-11,211,-211,0}; + private boolean usePOCA=false; + public EventBuilder(EBCCDBConstants ccdb){ this.ccdb=ccdb; } + public void setUsePOCA(boolean val) { + usePOCA=val; + } public void initEvent() { detectorEvent.clear(); } @@ -65,8 +71,10 @@ public void addFTIndices(List> ftindex) { */ public void addTracks(List tracks) { for(int i = 0 ; i < tracks.size(); i++){ - DetectorParticle particle = new DetectorParticle(tracks.get(i)); - detectorEvent.addParticle(particle); + if (this.usePOCA) + detectorEvent.addParticle(new DetectorParticle(tracks.get(i))); + else + detectorEvent.addParticle(new DetectorParticleTraj(tracks.get(i))); } } @@ -136,8 +144,8 @@ public void processHitMatching(){ // only match with CTOF/CND if it's a central track: else if (p.getTrackDetectorID()==DetectorType.CVT.getDetectorId()) { // NOTE: Should we do 2-d matching in cylindrical coordinates for CD? - findMatchingHit(n,p,detectorResponses,DetectorType.CTOF,0, ccdb.getDouble(EBCCDBEnum.CTOF_DZ)); - findMatchingHit(n,p,detectorResponses,DetectorType.CND, 0, ccdb.getDouble(EBCCDBEnum.CND_DZ)); + findMatchingHit(n,p,detectorResponses,DetectorType.CTOF,1, ccdb.getDouble(EBCCDBEnum.CTOF_DZ)); + findMatchingHit(n,p,detectorResponses,DetectorType.CND,-1, ccdb.getDouble(EBCCDBEnum.CND_DZ)); } } diff --git a/reconstruction/ec/pom.xml b/reconstruction/ec/pom.xml index 2d9b80c3af..d9a6ed1730 100644 --- a/reconstruction/ec/pom.xml +++ b/reconstruction/ec/pom.xml @@ -26,7 +26,7 @@ org.jlab.clas clas12rec ../../parent/pom.xml - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT @@ -46,37 +46,37 @@ org.jlab.clas clas-io - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-detector - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-geometry - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-reco - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-physics - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-analysis - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT diff --git a/reconstruction/ec/src/main/java/org/jlab/service/ec/ECCommon.java b/reconstruction/ec/src/main/java/org/jlab/service/ec/ECCommon.java index 69ac88b470..fce46b2648 100644 --- a/reconstruction/ec/src/main/java/org/jlab/service/ec/ECCommon.java +++ b/reconstruction/ec/src/main/java/org/jlab/service/ec/ECCommon.java @@ -5,6 +5,7 @@ import java.util.List; import org.jlab.detector.base.DetectorCollection; +import org.jlab.detector.base.DetectorLayer; import org.jlab.detector.calib.utils.ConstantsManager; import org.jlab.geom.base.Detector; import org.jlab.geom.base.Layer; @@ -127,7 +128,9 @@ public static List initEC(DataEvent event, Detector detector, Constant + " LOCAL LAYER = " + localLayer + " LAYER = " + layer); */ - Layer detLayer = detector.getSector(sector-1).getSuperlayer(superlayer).getLayer(localLayer); + int off = (superlayer==0)?DetectorLayer.PCAL_Z:0; + + Layer detLayer = detector.getSector(sector-1).getSuperlayer(superlayer).getLayer(localLayer+off); ScintillatorPaddle paddle = (ScintillatorPaddle) detLayer.getComponent(component-1); ScintillatorPaddle firstPaddle = (ScintillatorPaddle) detLayer.getComponent(0); ScintillatorPaddle lastPaddle = (ScintillatorPaddle) detLayer.getComponent(detLayer.getNumComponents()-1); diff --git a/reconstruction/ft/pom.xml b/reconstruction/ft/pom.xml index 453c8ec809..9e20a3a752 100644 --- a/reconstruction/ft/pom.xml +++ b/reconstruction/ft/pom.xml @@ -26,7 +26,7 @@ org.jlab.clas clas12rec ../../parent/pom.xml - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT @@ -47,19 +47,19 @@ org.jlab.clas clas-utils - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-io - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-reco - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT diff --git a/reconstruction/ft/src/main/java/org/jlab/rec/ft/FTConstants.java b/reconstruction/ft/src/main/java/org/jlab/rec/ft/FTConstants.java index 498abf252a..fc51b84123 100644 --- a/reconstruction/ft/src/main/java/org/jlab/rec/ft/FTConstants.java +++ b/reconstruction/ft/src/main/java/org/jlab/rec/ft/FTConstants.java @@ -10,6 +10,8 @@ * @author devita */ public class FTConstants { + + public static final int HODO_MIN_CLUSTER_SIZE = 2; // minimum size of hodo clusters for match to calorimeter public static final double CAL_HODO_DISTANCE_MATCHING = 3.0; // matching distance in cm public static final double CAL_HODO_TIME_MATCHING = 8; // matching time in ns diff --git a/reconstruction/ft/src/main/java/org/jlab/rec/ft/FTEBEngine.java b/reconstruction/ft/src/main/java/org/jlab/rec/ft/FTEBEngine.java index 553de47a10..7b6c51974f 100644 --- a/reconstruction/ft/src/main/java/org/jlab/rec/ft/FTEBEngine.java +++ b/reconstruction/ft/src/main/java/org/jlab/rec/ft/FTEBEngine.java @@ -130,8 +130,7 @@ public static void main(String arg[]){ en.init(); // String input = "/Users/devita/Work/clas12/simulations/tests/detectors/clas12/ft/elec_nofield_header.evio"; // EvioSource reader = new EvioSource(); - String input = "/Users/devita/Work/clas12/simulations/clas12Tags/4.3.1/out.hipo"; -// String input = "/Users/devita/out_gemc_10.hipo"; + String input = "/Users/devita/Work/clas12/simulations/clas12Tags/4.4.0/out.hipo"; HipoDataSource reader = new HipoDataSource(); reader.open(input); @@ -142,12 +141,12 @@ public static void main(String arg[]){ H1F h2 = new H1F("Energy Resolution", 100, -1, 1); h2.setOptStat(Integer.parseInt("1111")); h2.setTitleX("Energy Resolution(GeV)"); - H1F h3 = new H1F("Theta Resolution", 100, -2, 2); - h3.setOptStat(Integer.parseInt("1111")); - h3.setTitleX("Theta Resolution(deg)"); - H1F h4 = new H1F("Phi Resolution", 100, -10, 10); - h4.setOptStat(Integer.parseInt("1111")); - h4.setTitleX("Phi Resolution(deg)"); + H2F h3 = new H2F("Theta Resolution", 100, 0, 5, 100, -2, 2); + h3.setTitleX("Energy (GeV)"); + h3.setTitleY("Theta Resolution(deg)"); + H2F h4 = new H2F("Phi Resolution", 100, 0, 5, 100, -10, 10); + h4.setTitleX("Energy (GeV)"); + h4.setTitleY("Phi Resolution(deg)"); H1F h5 = new H1F("Time Resolution", 100, -2, 2); h5.setOptStat(Integer.parseInt("1111")); h5.setTitleX("Time Resolution(ns)"); @@ -183,8 +182,8 @@ public static void main(String arg[]){ h1.fill(bank.getDouble("Energy", i)); h2.fill(bank.getDouble("Energy", i) - gen.getParticle("[11]").vector().p()); Vector3D part = new Vector3D(bank.getDouble("Cx", i), bank.getDouble("Cy", i), bank.getDouble("Cz", i)); - h3.fill(Math.toDegrees(part.theta() - gen.getParticle("[11]").theta())); - h4.fill(Math.toDegrees(part.phi() - gen.getParticle("[11]").phi())); + h3.fill(gen.getParticle("[11]").vector().p(),Math.toDegrees(part.theta() - gen.getParticle("[11]").theta())); + h4.fill(gen.getParticle("[11]").vector().p(),Math.toDegrees(part.phi() - gen.getParticle("[11]").phi())); h5.fill(bank.getDouble("Time", i)); h6.fill(bank.getDouble("Energy", i), bank.getDouble("Energy", i) - gen.getParticle("[11]").vector().p()); } @@ -200,8 +199,8 @@ public static void main(String arg[]){ h1.fill(bank.getFloat("energy", i)); h2.fill(bank.getFloat("energy", i) - gen.getGeneratedParticle(0).vector().p()); Vector3D part = new Vector3D(bank.getFloat("cx", i), bank.getFloat("cy", i), bank.getFloat("cz", i)); - h3.fill(Math.toDegrees(part.theta() - gen.getGeneratedParticle(0).theta())); - h4.fill(Math.toDegrees(part.phi() - gen.getGeneratedParticle(0).phi())); + h3.fill(gen.getGeneratedParticle(0).vector().p(),Math.toDegrees(part.theta() - gen.getGeneratedParticle(0).theta())); + h4.fill(gen.getGeneratedParticle(0).vector().p(),Math.toDegrees(part.phi() - gen.getGeneratedParticle(0).phi())); h5.fill(bank.getFloat("time", i) - 124.25); h6.fill(bank.getFloat("cx", i) * FTCALConstantsLoader.CRYS_ZPOS, bank.getFloat("cy", i) * FTCALConstantsLoader.CRYS_ZPOS, bank.getFloat("energy", i) - gen.getGeneratedParticle(0).vector().p()); h7.fill(bank.getFloat("cx", i) * FTCALConstantsLoader.CRYS_ZPOS, bank.getFloat("cy", i) * FTCALConstantsLoader.CRYS_ZPOS); diff --git a/reconstruction/ft/src/main/java/org/jlab/rec/ft/FTEventBuilder.java b/reconstruction/ft/src/main/java/org/jlab/rec/ft/FTEventBuilder.java index e6ef7fecd6..cd048b7393 100644 --- a/reconstruction/ft/src/main/java/org/jlab/rec/ft/FTEventBuilder.java +++ b/reconstruction/ft/src/main/java/org/jlab/rec/ft/FTEventBuilder.java @@ -2,6 +2,7 @@ import java.util.ArrayList; import java.util.List; +import org.jlab.clas.pdg.PhysicsConstants; import org.jlab.detector.calib.utils.ConstantsManager; import org.jlab.io.base.DataBank; import org.jlab.io.base.DataEvent; @@ -140,7 +141,7 @@ public List initFTparticles(List responses) { track.setEnergy(responses.get(i).getEnergy()); track.setPosition(responses.get(i).getPosition()); track.setDirection(); - track.setTime(responses.get(i).getTime() - responses.get(i).getPosition().mag() / 29.97); + track.setTime(responses.get(i).getTime() - responses.get(i).getPosition().mag() / PhysicsConstants.speedOfLight()); track.setCalorimeterIndex(responses.get(i).getId()); track.setHodoscopeIndex(-1); track.setTrackerIndex(-1); diff --git a/reconstruction/ft/src/main/java/org/jlab/rec/ft/FTParticle.java b/reconstruction/ft/src/main/java/org/jlab/rec/ft/FTParticle.java index e27c8b7006..cda4624fa1 100644 --- a/reconstruction/ft/src/main/java/org/jlab/rec/ft/FTParticle.java +++ b/reconstruction/ft/src/main/java/org/jlab/rec/ft/FTParticle.java @@ -1,6 +1,7 @@ package org.jlab.rec.ft; import java.util.List; +import org.jlab.clas.pdg.PhysicsConstants; import org.jlab.geom.prim.Line3D; import org.jlab.geom.prim.Vector3D; import org.jlab.utils.groups.IndexedTable; @@ -11,7 +12,7 @@ public class FTParticle { private int _ID; // track ID private int _Charge; // 0/1 for photon/electron - private double _Time; // time of impact on the FT + private double _Time; // time of the particle at the vertex private double _Energy; // total energy of the cluster including correction private Vector3D _Position = new Vector3D(); // position private Vector3D _Direction = new Vector3D(); // direction @@ -95,8 +96,8 @@ public void setDirection(IndexedTable thetaTable, IndexedTable phiTable) { if(this._Charge==-1) { double energy = this._Energy; double thetaCorr = Math.exp(thetaTable.getDoubleValue("thetacorr0", 1,1,0)+thetaTable.getDoubleValue("thetacorr1", 1,1,0)*energy)+ - Math.exp(thetaTable.getDoubleValue("thetacorr1", 1,1,0)+thetaTable.getDoubleValue("thetacorr3", 1,1,0)*energy); - thetaCorr = Math.toRadians(thetaCorr * this._field); + Math.exp(thetaTable.getDoubleValue("thetacorr2", 1,1,0)+thetaTable.getDoubleValue("thetacorr3", 1,1,0)*energy); + thetaCorr = Math.toRadians(thetaCorr * Math.abs(this._field)); double phiCorr = Math.exp(phiTable.getDoubleValue("phicorr0", 1,1,0)+phiTable.getDoubleValue("phicorr1", 1,1,0)*energy)+ Math.exp(phiTable.getDoubleValue("phicorr2", 1,1,0)+phiTable.getDoubleValue("phicorr3", 1,1,0)*energy)+ Math.exp(phiTable.getDoubleValue("phicorr4", 1,1,0)+phiTable.getDoubleValue("phicorr5", 1,1,0)*energy); @@ -153,8 +154,8 @@ public int getDetectorHit(List hitList, String detectorType, double FTResponse response = hitList.get(loop); if(response.getAssociation()<0 && response.getType() == detectorType){ Line3D dist = cross.distance(response.getPosition().toPoint3D()); - double hitdistance = dist.length(); - double timedistance = Math.abs(this.getTime()-response.getTime()); + double hitdistance = dist.length(); + double timedistance = Math.abs(this.getTime()-(response.getTime()-response.getPosition().mag()/PhysicsConstants.speedOfLight())); // System.out.println(" LOOP = " + loop + " distance = " + hitdistance); if(timedistance hitList, String detectorType, double } } } + if(bestIndex>-1) { + if(hitList.get(bestIndex).getSize()0) addFlag = true; + if(hit.get_Edep()>thresholds.getDoubleValue("thresholdCluster",1,1,hit.get_COMPONENT())) { + for(int j = 0; j< this.size(); j++) { + double tDiff = Math.abs(hit.get_Time() - this.get(j).get_Time()); + double xDiff = Math.abs(hit.get_IDX() - this.get(j).get_IDX()); + double yDiff = Math.abs(hit.get_IDY() - this.get(j).get_IDY()); + if(tDiff <= clusterTable.getDoubleValue("time_window", 1,1,0) && xDiff <= 1 && yDiff <= 1 && (xDiff + yDiff) >0) addFlag = true; + } } return addFlag; } diff --git a/reconstruction/ft/src/main/java/org/jlab/rec/ft/cal/FTCALConstantsLoader.java b/reconstruction/ft/src/main/java/org/jlab/rec/ft/cal/FTCALConstantsLoader.java index 1ba689d7d3..fa27ad10c5 100644 --- a/reconstruction/ft/src/main/java/org/jlab/rec/ft/cal/FTCALConstantsLoader.java +++ b/reconstruction/ft/src/main/java/org/jlab/rec/ft/cal/FTCALConstantsLoader.java @@ -62,8 +62,8 @@ public FTCALConstantsLoader() { // public static double[][][] c3 = new double[1][1][484]; // public static double[][][] c4 = new double[1][1][484]; - public static int MAX_CLUS_RAD =3 ; // maximum radius of the cluster in # of crystals - public static double EN_THRES = 0.01; // energy threshold in GeV +// public static int MAX_CLUS_RAD =3 ; // maximum radius of the cluster in # of crystals +// public static double EN_THRES = 0.01; // energy threshold in GeV // GEOMETRY PARAMETERS public static double CRYS_DELTA = 11.5; public static double CRYS_WIDTH = 15.3; // crystal width in mm diff --git a/reconstruction/ft/src/main/java/org/jlab/rec/ft/cal/FTCALEngine.java b/reconstruction/ft/src/main/java/org/jlab/rec/ft/cal/FTCALEngine.java index fdf29adc88..bab57366cd 100644 --- a/reconstruction/ft/src/main/java/org/jlab/rec/ft/cal/FTCALEngine.java +++ b/reconstruction/ft/src/main/java/org/jlab/rec/ft/cal/FTCALEngine.java @@ -38,6 +38,7 @@ public boolean init() { "/calibration/ft/ftcal/time_offsets", "/calibration/ft/ftcal/time_walk", "/calibration/ft/ftcal/status", + "/calibration/ft/ftcal/thresholds", "/calibration/ft/ftcal/cluster", "/calibration/ft/ftcal/energycorr" }; @@ -61,7 +62,7 @@ public boolean processDataEvent(DataEvent event) { // get hits fron banks allHits = reco.initFTCAL(event,this.getConstantsManager(), run); // select good hits and order them by energy - selectedHits = reco.selectHits(allHits); + selectedHits = reco.selectHits(allHits,this.getConstantsManager(), run); // create clusters allClusters = reco.findClusters(selectedHits, this.getConstantsManager(), run); // select good clusters @@ -94,7 +95,7 @@ public int setRunConditionsParameters(DataEvent event) { public static void main (String arg[]) { FTCALEngine cal = new FTCALEngine(); cal.init(); - String input = "/Users/devita/Work/clas12/simulations/clas12Tags/4.3.1/out.hipo"; + String input = "/Users/devita/Work/clas12/simulations/clas12Tags/4.4.0/out.hipo"; HipoDataSource reader = new HipoDataSource(); // String input = "/Users/devita/Work/clas12/simulations/tests/detectors/clas12/ft/out_header.ev"; // EvioSource reader = new EvioSource(); diff --git a/reconstruction/ft/src/main/java/org/jlab/rec/ft/cal/FTCALHit.java b/reconstruction/ft/src/main/java/org/jlab/rec/ft/cal/FTCALHit.java index c64c94e4d3..dadb3d4cec 100644 --- a/reconstruction/ft/src/main/java/org/jlab/rec/ft/cal/FTCALHit.java +++ b/reconstruction/ft/src/main/java/org/jlab/rec/ft/cal/FTCALHit.java @@ -206,9 +206,9 @@ public void set_ClusIndex(int _ClusIndex) { this._ClusIndex = _ClusIndex; } - public static boolean passHitSelection(FTCALHit hit) { + public static boolean passHitSelection(FTCALHit hit, IndexedTable thresholds) { // a selection cut to pass the hit. - if(hit.get_Edep() > FTCALConstantsLoader.EN_THRES) { + if(hit.get_Edep() > thresholds.getDoubleValue("thresholdHit", 1,1,hit.get_COMPONENT())) { return true; } else { return false; diff --git a/reconstruction/ft/src/main/java/org/jlab/rec/ft/cal/FTCALReconstruction.java b/reconstruction/ft/src/main/java/org/jlab/rec/ft/cal/FTCALReconstruction.java index 6213bc275b..341a8e1bf7 100644 --- a/reconstruction/ft/src/main/java/org/jlab/rec/ft/cal/FTCALReconstruction.java +++ b/reconstruction/ft/src/main/java/org/jlab/rec/ft/cal/FTCALReconstruction.java @@ -47,14 +47,16 @@ public List initFTCAL(DataEvent event, ConstantsManager manager, int r return allhits; } - public List selectHits(List allhits) { + public List selectHits(List allhits, ConstantsManager manager, int run) { if(debugMode>=1) System.out.println("\nSelecting hits"); ArrayList hits = new ArrayList(); + IndexedTable thresholds = manager.getConstants(run, "/calibration/ft/ftcal/thresholds"); + for(int i = 0; i < allhits.size(); i++) { - if(FTCALHit.passHitSelection(allhits.get(i))) { + if(FTCALHit.passHitSelection(allhits.get(i), thresholds)) { hits.add(allhits.get(i)); } } @@ -74,6 +76,7 @@ public List findClusters(List hits, ConstantsManager man List clusters = new ArrayList(); + IndexedTable thresholds = manager.getConstants(run, "/calibration/ft/ftcal/thresholds"); IndexedTable clusterTable = manager.getConstants(run, "/calibration/ft/ftcal/cluster"); if(debugMode>=1) System.out.println("\nBuilding clusters"); @@ -82,10 +85,11 @@ public List findClusters(List hits, ConstantsManager man if(hit.get_ClusIndex()==0) { // this hit is not yet associated with a cluster for(int jclus=0; jclus=1) System.out.println("Attaching hit " + ihit + " to cluster " + cluster.getID()); + break; } } } diff --git a/reconstruction/fvt/pom.xml b/reconstruction/fvt/pom.xml index d582a72551..be90a3685c 100644 --- a/reconstruction/fvt/pom.xml +++ b/reconstruction/fvt/pom.xml @@ -26,7 +26,7 @@ org.jlab.clas clas12rec ../../parent/pom.xml - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT @@ -40,7 +40,7 @@ org.jlab.clas clas-jcsg - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT jar @@ -53,7 +53,7 @@ org.jlab.clas clas-reco - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT diff --git a/reconstruction/htcc/pom.xml b/reconstruction/htcc/pom.xml index e6bf0cb3a3..94699e127b 100644 --- a/reconstruction/htcc/pom.xml +++ b/reconstruction/htcc/pom.xml @@ -26,7 +26,7 @@ org.jlab.clas clas12rec ../../parent/pom.xml - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT @@ -47,19 +47,19 @@ org.jlab.clas clas-utils - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-io - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-reco - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT diff --git a/reconstruction/ltcc/pom.xml b/reconstruction/ltcc/pom.xml index 618dd67d6b..166b5b281b 100644 --- a/reconstruction/ltcc/pom.xml +++ b/reconstruction/ltcc/pom.xml @@ -26,7 +26,7 @@ org.jlab.clas clas12rec ../../parent/pom.xml - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT @@ -46,13 +46,13 @@ org.jlab.clas clas-reco - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-io - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT diff --git a/reconstruction/pom.xml b/reconstruction/pom.xml index f806bc01f6..ed73f58f03 100644 --- a/reconstruction/pom.xml +++ b/reconstruction/pom.xml @@ -3,14 +3,14 @@ org.jlab.clas reconstruction - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT pom org.jlab.clas clas12rec ../parent/pom.xml - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT @@ -26,5 +26,6 @@ fvt eb band + rtpc diff --git a/reconstruction/rich/pom.xml b/reconstruction/rich/pom.xml index 252c286cae..d3dee734e0 100644 --- a/reconstruction/rich/pom.xml +++ b/reconstruction/rich/pom.xml @@ -13,7 +13,7 @@ org.jlab.clas clas12rec ../../parent/pom.xml - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT @@ -33,19 +33,19 @@ org.jlab.clas clas-io - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-reco - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT org.jlab.clas clas-jcsg - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT diff --git a/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHConstants.java b/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHConstants.java index 197810df05..462ea6a9ad 100644 --- a/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHConstants.java +++ b/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHConstants.java @@ -37,7 +37,7 @@ public class RICHConstants { public static final double RICH_MIN_CHANGLE = 10.e-3; // rad public static final double RICH_MATCH_POLYDIST = 1.e-3; // Matching dist between poly and point - public static final double RICH_BKG_PROBABILITY = 1.e-3; // Background probability for likelihood + public static final double RICH_BKG_PROBABILITY = 1.e-5; // Background probability for likelihood public static final double READ_FROM_FILES = 0.; // read values from txt files @@ -64,10 +64,15 @@ public class RICHConstants { public int DO_MIRROR_HADS = 1; // if 1 reconstruct hadrons pointing to mirror public int DO_CURVED_AERO = 1; // if 1 use spherical surface of aerogel + public int USE_ELECTRON_ANGLES = 0; // Get Cherenkov angle and rms from electrons control sample + public int USE_PIXEL_PROPERTIES = 0; // Use pixel status and efficiency in the likelihood + public int SAVE_THROWS = 0; // Store throwed photons in the photons bank + public int QUADRANT_NUMBER = 15; // Number of quadrants (square root of) + public double GOODHIT_FRAC = 80.; // Maximum duration (in % of local max) to flag xtalk public double RICH_DCMATCH_CUT = 15.; // RICH cluster matching cut with tracks public double RICH_HITMATCH_RMS = 0.6; // RICH - particle matching chi2 reference (cm) - public double RICH_DIRECT_RMS = 4.2e-3; // Expected single photon angular resolution (rad) + public double RICH_DIRECT_RMS = 6.0e-3; // Expected single photon angular resolution (rad) public double SHOW_PROGRESS_INTERVAL = 10.; // Time interval between progress dumping (sec) public double THROW_ASSOCIATION_CUT = 10.; // Max distance to set initial values for tracing photons (cm) diff --git a/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHEBEngine.java b/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHEBEngine.java index dcd1532ade..8055cfebf0 100644 --- a/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHEBEngine.java +++ b/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHEBEngine.java @@ -14,6 +14,9 @@ import java.util.Arrays; import java.util.Optional; +import org.jlab.geom.prim.Plane3D; +import org.jlab.geom.prim.Line3D; + public class RICHEBEngine extends ReconstructionEngine { private int Run = -1; @@ -39,18 +42,73 @@ public boolean init() { int debugMode = 0; + if(debugMode>=1)System.out.format("I am in RICHEBEngine \n"); tool = new RICHTool(); - boolean ccdb = init_CCDB(); + boolean ccdb = init_CCDB(1); return true; } + + /* + // ---------------- + public boolean init_forTraj() { + // ---------------- + + + int debugMode = 0; + + tool = new RICHTool(); + + boolean ccdb = init_CCDB(0); + + //testTraj(); + + return true; + + }*/ + + // ---------------- + public void testTraj() { + // ---------------- + + tool.testTraj(); + } + + // ---------------- - public boolean init_CCDB() { + public Plane3D get_MaPMTforTraj() { + // ---------------- + + return tool.get_MaPMTforTraj(); + + } + + + // ---------------- + public Plane3D get_AeroforTraj(int iflag) { + // ---------------- + + return tool.get_AeroforTraj(iflag); + + } + + + //------------------------------ + public int select_AeroforTraj(Line3D first, Line3D second, Line3D third) { + //------------------------------ + + return tool.select_AeroforTraj(first, second, third); + + } + + + // ---------------- + public boolean init_CCDB(int iflag) { // ---------------- int debugMode = 0; @@ -60,13 +118,15 @@ public boolean init_CCDB() { "/calibration/rich/time_walk", "/calibration/rich/time_offset", "/calibration/rich/misalignments", - "/calibration/rich/parameter" + "/calibration/rich/parameterss", + "/calibration/rich/pixels", + "/calibration/rich/electro" }; requireConstants(Arrays.asList(richTables)); // initialize constants manager default variation, will be then modified based on yaml settings - // Get the constants for the correct variation + // Get the constants for the correct variation String engineVariation = Optional.ofNullable(this.getEngineConfigString("variation")).orElse("default"); getConstantsManager().setVariation(engineVariation); @@ -75,11 +135,10 @@ public boolean init_CCDB() { // Get the constant tables for reconstruction parameters, geometry and optical characterization int run = 11; - IndexedTable test = getConstantsManager().getConstants(run, "/calibration/rich/parameter"); - + //IndexedTable test = getConstantsManager().getConstants(run, "/calibration/rich/parameter"); - tool.init_GeoConstants( - getConstantsManager().getConstants(run, "/calibration/rich/parameter"), + tool.init_GeoConstants(iflag, + getConstantsManager().getConstants(run, "/calibration/rich/parameterss"), getConstantsManager().getConstants(run, "/calibration/rich/aerogel"), getConstantsManager().getConstants(run, "/calibration/rich/misalignments") ); @@ -151,7 +210,9 @@ public void init_Event(DataEvent event, RICHEvent richevent, RICHTool tool) { // Get the run-dependent tables for time calibration tool.init_TimeConstants( getConstantsManager().getConstants(run, "/calibration/rich/time_walk"), - getConstantsManager().getConstants(run, "/calibration/rich/time_offset") ); + getConstantsManager().getConstants(run, "/calibration/rich/time_offset"), + getConstantsManager().getConstants(run, "/calibration/rich/electro"), + getConstantsManager().getConstants(run, "/calibration/rich/pixels") ); } diff --git a/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHEvent.java b/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHEvent.java index b02d6214bd..d1b046f31d 100644 --- a/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHEvent.java +++ b/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHEvent.java @@ -38,9 +38,6 @@ public class RICHEvent { private ArrayList hadrons = new ArrayList(); private ArrayList photons = new ArrayList(); - private double match_chi2 = 0.0; - private int match_nchi2 = 0; - // constructor // ---------------- @@ -246,12 +243,162 @@ public void clear(){ public int get_nMatch() { return matches.size(); } // ---------------- + // ---------------- + public void get_ChMean(RICHParticle hadron, int recotype) { + // ---------------- + + int debugMode = 0; + int SELE = 2; + + if(debugMode>=1)System.out.format("Ch Mean calc for reco %d \n",recotype); + + int update = 1; + while (update==1) { + + update = 0; + int nea = 0; + double mea = 0.0; + double sea = 0.0; + for( RICHParticle pho: photons) { + if(pho.get_type()==0 && pho.get_ParentIndex() == hadron.get_id()){ + + + if(debugMode>=1)System.out.format("calc mean for photon %d ",pho.get_id()); + RICHSolution reco = new RICHSolution(); + if(recotype==0) reco = pho.analytic; + if(recotype==1) reco = pho.traced; + double etac = reco.get_EtaC(); + + if(reco.get_OK()==SELE){ + if(debugMode>=1)System.out.format(" etac %7.2f \n",etac*MRAD); + nea++; + mea += etac; + sea += etac*etac; + }else{ + if(debugMode>=1)System.out.format(" -> no\n"); + } + } + + } + + if(nea>0){ + mea = mea /nea; + sea = Math.sqrt( sea/nea - mea*mea ); + } + if(debugMode>=1)System.out.format(" mean etac %7.2f %7.2f \n",mea*MRAD,sea*MRAD); + + for( RICHParticle pho: photons) { + if(pho.get_type()==0 && pho.get_ParentIndex() == hadron.get_id()){ + + RICHSolution reco = new RICHSolution(); + if(recotype==0) reco = pho.analytic; + if(recotype==1) reco = pho.traced; + double etac = reco.get_EtaC(); + double chi = mea - 3 *sea; + double cha = mea + 3 *sea; + + if(reco.get_OK()==SELE && ( etac < chi || etac > cha )) { + reco.set_OK(1); + update = 1; + if(debugMode>=1)System.out.format(" reject photon %d with etac %7.2f vs [%7.2f : %7.2f] \n",pho.get_id(),etac*MRAD,chi*MRAD,cha*MRAD); + } + } + } + + } + if(debugMode>=1)System.out.format(" Done with average \n"); + + int ndir = 0; + int nlat = 0; + int nspe = 0; + double chdir = 0.0; + double chlat = 0.0; + double chspe = 0.0; + double sdir = 0.0; + double slat = 0.0; + double sspe = 0.0; + for( RICHParticle pho: photons) { + if(pho.get_type()==0 && pho.get_ParentIndex() == hadron.get_id()){ + + RICHSolution reco = new RICHSolution(); + if(recotype==0) reco = pho.analytic; + if(recotype==1) reco = pho.traced; + if(reco.get_OK()!=SELE) continue; + + double etac = reco.get_EtaC(); + + int irefle = reco.get_RefleType(); + if(irefle<0 || irefle>2) continue; + + if(irefle==0){ + chdir+=etac; + sdir+=etac*etac; + ndir++; + }else{ + if(irefle==2){ + chspe+=etac; + sspe+=etac*etac; + nspe++; + }else{ + chlat+=etac; + slat+=etac*etac; + nlat++; + } + } + } + } + + if(ndir>0){ + chdir = chdir /ndir; + sdir = Math.sqrt( sdir/ndir - chdir*chdir ); + } + if(nlat>0){ + chlat = chlat /nlat; + slat = Math.sqrt( slat/nlat - chlat*chlat ); + } + if(nspe>0){ + chspe = chspe /nspe; + sspe = Math.sqrt( sspe/nspe - chspe*chspe ); + } + + RICHSolution hreco = null; + String sreco = null; + if(recotype==0) {hreco = hadron.analytic; sreco = "ALI";} + if(recotype==1) {hreco = hadron.traced; sreco = "TRA";} + + int ntot = ndir+nlat+nspe; + double chtot = 0.0; + double stot = 0.0; + if(ntot>0){ + chtot = (chdir*ndir + chlat*nlat + chspe*nspe)/ntot; + stot = Math.sqrt(sdir*sdir*ndir + slat*slat*nlat + sspe*sspe*nspe)/ntot; + } + + if(debugMode>=1)System.out.format("Ave %s %7.2f %7.2f %d dir %d %7.2f %7.2f lat %d %7.2f %7.2f spe %d %7.2f %7.2f tot %d %7.2f %7.2f \n",sreco,hadron.get_momentum(), + hadron.lab_theta*RAD,hadron.get_CLASpid(),ndir,chdir*MRAD, sdir*MRAD,nlat,chlat*MRAD,slat*MRAD,nspe,chspe*MRAD,sspe*MRAD,ntot,chtot*MRAD,stot*MRAD); + + hreco.set_Ndir(ndir); + hreco.set_Chdir(chdir); + hreco.set_RMSdir(sdir); + + hreco.set_Nlat(nlat); + hreco.set_Chlat(chlat); + hreco.set_RMSlat(slat); + + hreco.set_Nspe(nspe); + hreco.set_Chspe(chspe); + hreco.set_RMSspe(sspe); + + } + + // ---------------- public void get_pid(RICHParticle hadron, int recotype) { // ---------------- int debugMode = 0; - int npho = 0; + int SELE=2; + double lh_el = 0.0; double lh_pi = 0.0; double lh_k = 0.0; @@ -277,76 +424,78 @@ public void get_pid(RICHParticle hadron, int recotype) { for( RICHParticle pho: photons) { if(pho.get_type()==0 && pho.get_ParentIndex() == hadron.get_id()){ - if(debugMode>=1)System.out.format("calc prob for photon %d \n",npho); - RICHSolution reco = new RICHSolution(); if(recotype==0) reco = pho.analytic; if(recotype==1) reco = pho.traced; double etac = reco.get_EtaC(); + if(reco.get_OK()!=SELE) continue; + + RICHHit hit = hits.get( pho.get_hit_index() ); + if(debugMode>=1)System.out.format("calc prob for photon %d \n",pho.get_id()); + // prob for backgound - prob = pho.pid_probability(hadron, 0, recotype); + prob = pho.pid_probability(hadron, hit, 0, recotype); if(prob-1>=RICHConstants.RICH_BKG_PROBABILITY){ lh_bg += Math.log(prob); ch_bg += Math.log(prob)*etac; n_bg++; - reco.set_bgprob(Math.log(prob)); - if(debugMode>=2)System.out.format("prob %d etac %8.4f for background %g %g \n",npho, etac*MRAD, prob, Math.log(prob)); + reco.set_BgProb(Math.log(prob)); + if(debugMode>=2)System.out.format(" --> etac %8.4f for background %g %g \n", etac*MRAD, prob, Math.log(prob)); }else{ //System.out.format("ATT: wrong prob for background %g \n",prob-1); } // prob for electron - prob = pho.pid_probability(hadron, 11, recotype); + prob = pho.pid_probability(hadron, hit, 11, recotype); if(prob-1>=RICHConstants.RICH_BKG_PROBABILITY){ lh_el += Math.log(prob); ch_el += Math.log(prob)*etac; n_el++; - reco.set_elprob(Math.log(prob)); - if(debugMode>=2)System.out.format("prob %d etac %8.4f for electron %g %g \n",npho, etac*MRAD, prob, Math.log(prob)); + reco.set_ElProb(Math.log(prob)); + if(debugMode>=2)System.out.format("- --> etac %8.4f for electron %g %g \n", etac*MRAD, prob, Math.log(prob)); }else{ //System.out.format("ATT: wrong prob for electron %g \n",prob-1); } // prob for pion - prob=pho.pid_probability(hadron, 211, recotype); + prob=pho.pid_probability(hadron, hit, 211, recotype); if(prob-1>=RICHConstants.RICH_BKG_PROBABILITY){ lh_pi += Math.log(prob); ch_pi += Math.log(prob)*etac; n_pi++; - reco.set_piprob(Math.log(prob)); - if(debugMode>=1)System.out.format("prob %d etac %8.4f for pion %g %g \n",npho, etac*MRAD, prob, Math.log(prob)); + reco.set_PiProb(Math.log(prob)); + if(debugMode>=1)System.out.format(" --> etac %8.4f for pion %g %g \n", etac*MRAD, prob, Math.log(prob)); }else{ //System.out.format("ATT: wrong prob for pion %g \n",prob-1); } // prob for kaon - prob=pho.pid_probability(hadron, 321, recotype); + prob=pho.pid_probability(hadron, hit, 321, recotype); if(prob-1>=RICHConstants.RICH_BKG_PROBABILITY){ lh_k += Math.log(prob); ch_k += Math.log(prob)*etac; n_k++; - reco.set_kprob(Math.log(prob)); - if(debugMode>=1)System.out.format("prob %d etac %8.4f for kaon %g %g \n",npho, etac*MRAD, prob, Math.log(prob)); + reco.set_KProb(Math.log(prob)); + if(debugMode>=1)System.out.format(" --> etac %8.4f for kaon %g %g \n", etac*MRAD, prob, Math.log(prob)); }else{ //System.out.format("ATT: wrong prob for kaon %g \n",prob-1); } // prob for proton - prob=pho.pid_probability(hadron, 2212, recotype); + prob=pho.pid_probability(hadron, hit, 2212, recotype); if(prob-1>=RICHConstants.RICH_BKG_PROBABILITY){ lh_pr += Math.log(prob); ch_pr += Math.log(prob)*etac; - reco.set_prprob(Math.log(prob)); + reco.set_PrProb(Math.log(prob)); n_pr++; - if(debugMode>=1)System.out.format("prob %d etac %8.4f for proton %g %g \n",npho, etac*MRAD, prob, Math.log(prob)); + if(debugMode>=1)System.out.format(" --> etac %8.4f for proton %g %g \n", etac*MRAD, prob, Math.log(prob)); }else{ //System.out.format("ATT: wrong prob for proton %g \n",prob-1); } if(debugMode>=2) pho.shortshow(); } - npho++; } if(lh_el>0)ch_el=ch_el/lh_el; @@ -364,22 +513,18 @@ public void get_pid(RICHParticle hadron, int recotype) { ch_el, ch_pi, ch_k, ch_pr, ch_had); double newRQ = 0.0; - if(recotype==0) { - newRQ = hadron.analytic.assign_PID(lh_el, lh_pi, lh_k, lh_pr, lh_bg); - hadron.set_RICHpid(hadron.analytic.get_bestH()); - if(debugMode>=1)System.out.format("NEW ALY eve %8d mom %6.2f xy %7.2f %7.2f %7.2f %7.2f %8.2f %8.4f Npho %5d %8.4f %3d %g %3d %g --> %8.5f %7.2f %7.2f %3d %3d | %5d %8.4f \n",eventID, hadron.get_momentum(), - hadron.lab_origin.x(), hadron.lab_origin.y(), hadron.meas_hit.x, hadron.meas_hit.y, hadron.get_changle(0)*MRAD, hadron.refi_emission, - n_el, lh_el, hadron.analytic.get_bestH(), hadron.analytic.get_bestprob(), hadron.analytic.get_secH(), hadron.analytic.get_secprob(), - newRQ, ch_had*MRAD, ch_el*MRAD, hadron.get_CLASpid(), hadron.get_RICHpid(), match_nchi2, match_chi2); - } - if(recotype==1) { - newRQ = hadron.traced.assign_PID(lh_el, lh_pi, lh_k, lh_pr, lh_bg); - hadron.set_RICHpid(hadron.traced.get_bestH()); - if(debugMode>=1)System.out.format("NEW TRA eve %8d mom %6.2f xy %7.2f %7.2f %7.2f %7.2f %8.2f %8.4f Npho %5d %8.4f %3d %g %3d %g --> %8.5f %7.2f %7.2f %3d %3d | %5d %8.4f \n",eventID, hadron.get_momentum(), - hadron.lab_origin.x(), hadron.lab_origin.y(), hadron.meas_hit.x, hadron.meas_hit.y, hadron.get_changle(0)*MRAD, hadron.refi_emission, - n_el, lh_el, hadron.traced.get_bestH(), hadron.traced.get_bestprob(), hadron.traced.get_secH(), hadron.traced.get_secprob(), - newRQ, ch_had*MRAD, ch_el*MRAD, hadron.get_CLASpid(), hadron.get_RICHpid(), match_nchi2, match_chi2); - } + RICHSolution hreco = new RICHSolution(); + String hstri = null; + if(recotype==0) {hreco = hadron.analytic; hstri="ALI";} + if(recotype==1) {hreco = hadron.traced; hstri="TRA";} + + newRQ = hreco.assign_PID(lh_el, lh_pi, lh_k, lh_pr, lh_bg); + hadron.set_RICHpid(hreco.get_BestH()); + if(debugMode>=1)System.out.format("%s eve %8d mom %6.2f xy %7.2f %7.2f %7.2f %7.2f %8.2f %8.4f Npho %5d %8.4f %3d %g %3d %g --> %8.5f %7.2f %7.2f %3d %3d\n", + hstri,eventID, hadron.get_momentum(), + hadron.lab_origin.x(), hadron.lab_origin.y(), hadron.meas_hit.x, hadron.meas_hit.y, hadron.get_changle(0,0)*MRAD, hadron.refi_emission, + n_el, lh_el, hadron.analytic.get_BestH(), hadron.analytic.get_Bestprob(), hadron.analytic.get_secH(), hadron.analytic.get_secprob(), + newRQ, ch_el*MRAD, ch_had*MRAD, hadron.get_CLASpid(), hadron.get_RICHpid()); } @@ -411,6 +556,53 @@ public void showEvent(){ } } + // ---------------- + public void select_Photons(RICHConstants recopar, int recotype){ + // ---------------- + int debugMode = 0; + int jj=0; + for( RICHParticle pho: photons){ + if(pho.get_type()==0){ + + RICHHit hit = get_Hit( pho.get_hit_index() ); + RICHParticle had = get_Hadron( pho.get_ParentIndex() ); + + RICHSolution reco = new RICHSolution(); + String stype = null; + if(recotype==0) { + if (had.get_Status()!=1)continue; + reco = pho.analytic; stype="analytic"; + } + if(recotype==1) {reco = pho.traced; stype="traced";} + + double htime = hit.get_time(); + double dtime = pho.get_start_time() + reco.get_time() - htime; + + int irefle = reco.get_RefleType(); + if(irefle<0 || irefle>2) continue; + + double CHMI = had.minChAngle(irefle); + double CHMA = had.maxChAngle(irefle); + double DTMA = recopar.RICH_TIME_RMS*3; + + double etaC = reco.get_EtaC(); + + // select acceptable Cherenkov solution + if((etaC>CHMI && etaC=1){ + System.out.format("Test pho %4d %4d %s %7.2f (%7.2f-%7.2f) %7.2f (%7.2f) --> %4d %d\n", + jj,pho.get_id(), stype, etaC*MRAD, CHMI*MRAD, CHMA*MRAD, dtime, DTMA, reco.get_OK(),reco.get_FirstRefle()); + } + jj++; + + } + + } + + } // ---------------- public void analyze_Photons(){ @@ -466,8 +658,8 @@ public void associate_Throws(RICHTool tool){ // ---------------- int debugMode = 0; - match_nchi2 = 0 ; - match_chi2 = 0.0 ; + int match_nchi2 = 0 ; + double match_chi2 = 0.0 ; RICHConstants recopar = tool.get_Constants(); @@ -576,6 +768,7 @@ public void throw_Photons(RICHParticle hadron, int Npho, double theta, int type, // store in the event if(rays.get(rays.size()-1).is_detected()){ + if(debugMode>=1)System.out.format(" --> detected \n"); photons.add(photon); fac=1; if (photon.traced.get_rayrefle()>2)fac=2.; diff --git a/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHEventBuilder.java b/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHEventBuilder.java index adc762a952..bde92eca71 100644 --- a/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHEventBuilder.java +++ b/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHEventBuilder.java @@ -265,6 +265,7 @@ public boolean read_ForwardTracks(DataEvent event) { * disregard central detector tracks */ if(idet!=6)continue; + if(tr.getSector()!=4)continue; for (int j=0; j=1) System.out.format(" --> %7.2f %7.2f %7.2f | %7.2f %7.2f %7.2f -> %7.2f %7.2f %7.2f \n", - jx,jy,jz,jcx,jcy,jcz,vdir.x,vdir.y,vdir.z); + if(debugMode>=1) System.out.format(" --> %7.2f %7.2f %7.2f | %7.2f %7.2f %7.2f -> %7.2f %7.2f %7.2f | path %7.2f \n", + jx,jy,jz,jcx,jcy,jcz,vdir.x,vdir.y,vdir.z,rbank.getFloat("path", j)); }else{ if(debugMode>=1) System.out.format("\n"); } @@ -380,8 +381,13 @@ public void process_Hit_Matching(){ int index = p.getDetectorHit(richevent.get_ResClus(), DetectorType.RICH, 1, rich_match_cut); if(index>=0){ // while storing the match, calculates the matched position as middle point between track and hit and path (track last cross plus distance to hit) - p.addResponse(richevent.get_ResClu(index), true); - richevent.get_ResClu(index).setAssociation(n); + + DetectorResponse res = richevent.get_ResClu(index); + double dist = tool.toVector3d(res.getPosition()).distance( tool.toVector3d(p.getLastCross().origin()) ); + //res.setPath(p.getPathLength()+dist); + + p.addResponse(res, true); + res.setAssociation(p.getTrackStatus()); if(debugMode>=1) System.out.println(" --> match found "+index+" for particle "+n); } @@ -462,41 +468,53 @@ public boolean find_Hadrons() { double CLASbeta = p.getTheoryBeta(CLASpid); if(debugMode>=1) { - System.out.format(" --> track %4d %4d ori %s P %8.2f the %8.2f time @IP %8.2f \n",p.getTrackIndex(),CLASpid, - tool.toString(p.getLastCross().origin()),p.vector().mag(),theta*RAD,richevent.get_EventTime()); + System.out.format(" --> track %4d %4d ori %s P %8.2f the %8.2f time @IP %8.2f path %7.2f\n",p.getTrackIndex(),CLASpid, + tool.toString(p.getLastCross().origin()),p.vector().mag(),theta*RAD,richevent.get_EventTime(),p.getPathLength()); } DetectorResponse r = null; - int nresp = 0; + DetectorResponse exr = null; + int nr = 0; + int nexr = 0; + double RICHtime = 0.0; + double Match_chi2 = 0.0; + int RICHiclu = -1; for(DetectorResponse rtest : p.getDetectorResponses()){ if(rtest.getDescriptor().getType()==DetectorType.RICH){ r = rtest; - nresp++; + RICHtime = richevent.get_EventTime() + r.getPath()/CLASbeta/(PhysicsConstants.speedOfLight()); + RICHiclu = r.getHitIndex(); + double CLAStime = richevent.get_EventTime() + r.getPath()/CLASbeta/(PhysicsConstants.speedOfLight()); + + if(debugMode>=1)System.out.format(" --> cluster %4d hit %s path %7.2f --> clas %8.2f vs rich %8.2f time\n \n",RICHiclu, + tool.toString(r.getPosition()), r.getPath(), CLAStime, RICHtime); + + nr++; } } - if(tool.get_Constants().DO_MIRROR_HADS==1 && nresp==0){ - if(debugMode>=1)System.out.format("EXTRAPOLATED \n"); - r = extrapolate_RICHResponse(p); - if(r!=null) nresp++; + + if( (nr==1) || (nr==0 && tool.get_Constants().DO_MIRROR_HADS==1) ){ + if(debugMode>=1)System.out.format("EXTRAPOLATED with nresp %d \n",nr); + exr = extrapolate_RICHResponse(p, r); + if(exr!=null) nexr++; } // ATT: define the response tratment in special cases - if(nresp==0){if(debugMode>=1)System.out.format("No RICH intersection for particle %8.2f \n",theta*RAD); continue;} - if(nresp>1){if(debugMode>=1)System.out.format("Too many RICH responses for particle \n"); continue;} + if(nexr==0){if(debugMode>=1)System.out.format("No RICH intersection for particle with nresp %d and theta %8.2f \n",nr,theta*RAD); continue;} + if(nr==1)Match_chi2 = 2*exr.getMatchedDistance()/tool.get_Constants().RICH_HITMATCH_RMS; - // ATT: time taken at the RICH matching point - double CLAStime = richevent.get_EventTime() + r.getPath()/CLASbeta/(PhysicsConstants.speedOfLight()); + // ATT: time taken at the RICH extrapolated point + double CLAStime = richevent.get_EventTime() + exr.getPath()/CLASbeta/(PhysicsConstants.speedOfLight()); //double CLAStime = richevent.get_EventTime() + p.getPathLength()/CLASbeta/(PhysicsConstants.speedOfLight()); - if(debugMode>=1) { - System.out.format(" --> response %4d hit %s path %7.2f --> clas %8.2f vs rich %8.2f time\n \n",r.getHitIndex(), - tool.toString(r.getPosition()), r.getPath(), CLAStime, r.getTime()); - } + if(debugMode>=1)System.out.format(" --> intersec %4d hit %s path %7.2f --> time clas %7.2f vs rich %8.2f chi2 %7.2f \n \n",RICHiclu, + tool.toString(exr.getPosition()), exr.getPath(), CLAStime, RICHtime, Match_chi2); - RICHParticle richhadron = new RICHParticle(hindex, p.getTrackStatus(), r.getHitIndex(), p.vector().mag(), CLASpid, tool); + RICHParticle richhadron = new RICHParticle(hindex, p.getTrackStatus(), RICHiclu, p.vector().mag(), CLASpid, tool); richhadron.traced.set_time((float) CLAStime); - richhadron.set_meas_time(r.getTime()); - if(!richhadron.set_points(p.getLastCross().origin(), p.getLastCross().end(), r.getPosition(), r.getStatus(), tool) ){ + richhadron.traced.set_machi2(Match_chi2); + richhadron.set_meas_time(exr.getTime()); + if(!richhadron.set_points(p.getLastCross().origin(), p.getLastCross().end(), exr.getPosition(), exr.getStatus(), tool) ){ if(debugMode>=1)System.out.println(" ERROR: no MAPMT interesection found for hadron \n"); continue; } @@ -518,7 +536,7 @@ public boolean find_Hadrons() { if(debugMode>=1){ System.out.format(" ------------------- \n"); System.out.format(" Hadron %4d id %4d from part %4d and clu %4d CLAS eve %7d pid %5d \n ", hindex, richhadron.get_id(), - p.getTrackStatus(), r.getHitIndex(), richevent.get_EventID(), CLASpid); + p.getTrackStatus(), RICHiclu, richevent.get_EventID(), CLASpid); System.out.format(" ------------------- \n"); richhadron.show(); @@ -569,6 +587,8 @@ public boolean find_Photons(List RichHits){ photon.set_points(richhadron, tool.toVector3d(RichHits.get(k).getPosition())); photon.set_meas_time(RichHits.get(k).getTime()); photon.set_start_time(richhadron.get_start_time()); + RICHHit hit = richevent.get_Hit( RichHits.get(k).getHitIndex() ); + photon.set_PixelProp(hit, tool); richevent.add_Photon(photon); @@ -590,9 +610,15 @@ public boolean analyze_Cherenkovs() { if(tool.get_Constants().DO_ANALYTIC==1){ richevent.analyze_Photons(); + richevent.select_Photons(tool.get_Constants(), 0); for(RICHParticle richhadron : richevent.get_Hadrons()){ - richevent.get_pid(richhadron,0); + if (richhadron.get_Status()==1){ + richevent.get_ChMean(richhadron,0); + richevent.get_pid(richhadron,0); + }else{ + if(debugMode>=1)System.out.format(" Hadron pointing to mirror, skip analytic analysis \n"); + } } } @@ -612,23 +638,23 @@ public boolean reco_Cherenkovs() { int trials = tool.get_Constants().THROW_PHOTON_NUMBER; if(tool.get_Constants().THROW_ELECTRONS==1){ - double chel = richhadron.get_changle(0); + double chel = richhadron.get_changle(0,0); if(chel>0)richevent.throw_Photons(richhadron, trials, chel, 5, tool); } if(tool.get_Constants().THROW_PIONS==1){ - double chpi = richhadron.get_changle(1); + double chpi = richhadron.get_changle(1,0); if(chpi>0)richevent.throw_Photons(richhadron, trials, chpi, 1, tool); } if(tool.get_Constants().THROW_KAONS==1){ - double chk = richhadron.get_changle(2); + double chk = richhadron.get_changle(2,0); if(chk>0)richevent.throw_Photons(richhadron, trials, chk, 2, tool); } if(tool.get_Constants().THROW_PROTONS==1){ - double chpr = richhadron.get_changle(3); + double chpr = richhadron.get_changle(3,0); if(chpr>0)richevent.throw_Photons(richhadron, trials, chpr, 3, tool); } @@ -640,8 +666,10 @@ public boolean reco_Cherenkovs() { richevent.associate_Throws(tool); richevent.trace_Photons(tool); + richevent.select_Photons(tool.get_Constants(), 1); for(RICHParticle richhadron : richevent.get_Hadrons()){ + richevent.get_ChMean(richhadron,1); richevent.get_pid(richhadron,1); } @@ -652,32 +680,53 @@ public boolean reco_Cherenkovs() { // ---------------- - public DetectorResponse extrapolate_RICHResponse(DetectorParticle p){ + public DetectorResponse extrapolate_RICHResponse(DetectorParticle p, DetectorResponse r){ // ---------------- int debugMode = 0; + int imir=0; - DetectorResponse r = new DetectorResponse(4, 18, 1); + DetectorResponse exr = new DetectorResponse(4, 18, 1); - Vector3d extra = tool.find_intersection_UpperHalf_RICH( p.getLastCross()); + Point3D extra = tool.toPoint3D( tool.find_intersection_MAPMT( p.getLastCross()) ); if(extra==null){ - extra = tool.find_intersection_MAPMT( p.getLastCross()); + imir=1; + extra = tool.toPoint3D( tool.find_intersection_UpperHalf_RICH( p.getLastCross()) ); } if(extra==null) return null; - double dist = extra.distance( tool.toVector3d(p.getLastCross().origin()) ); + double extrapath = extra.distance( p.getLastCross().origin() ); + + Point3D rpos = new Point3D(0.0, 0.0, 0.0); + Point3D rmatch = new Point3D(0.0, 0.0, 0.0); + if(r!=null){ + + rpos = r.getPosition().toPoint3D(); + Line3D lmatch = new Line3D(rpos, extra); + rmatch = lmatch.midpoint(); + exr.setPosition( rpos.x(), rpos.y(), rpos.z() ); + exr.setMatchPosition( rmatch.x(), rmatch.y(), rmatch.z()); + exr.setStatus(1); + + }else{ + + exr.setPosition( extra.x(), extra.y(), extra.z() ); + exr.setMatchPosition( extra.x(), extra.y(), extra.z()); + exr.setStatus(0); - r.setPosition(extra.x, extra.y, extra.z); - r.setPath(p.getPathLength()+dist); - r.setStatus(0); + } + exr.setPath(p.getPathLength()+extrapath); int CLASpid = p.getPid(); if(CLASpid==0)CLASpid = 211; double CLASbeta = p.getTheoryBeta(CLASpid); - r.setTime( richevent.get_EventTime() + r.getPath()/CLASbeta/(PhysicsConstants.speedOfLight()) ); + exr.setTime( richevent.get_EventTime() + exr.getPath()/CLASbeta/(PhysicsConstants.speedOfLight()) ); + + if(debugMode>0)System.out.format("extrapolate_RICHResponse: %d %d ex %s r %s mach %s L %7.2f (%7.2f + %7.2f) T %7.2f \n",exr.getStatus(),imir,extra.toStringBrief(2), + rpos.toStringBrief(2),rmatch.toStringBrief(2),exr.getPath(),p.getPathLength(),extrapath,exr.getTime()); - return r; + return exr; } // ---------------- diff --git a/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHHit.java b/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHHit.java index 8b3f622d2a..be4d71cdd3 100644 --- a/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHHit.java +++ b/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHHit.java @@ -20,11 +20,13 @@ public class RICHHit implements Comparable{ private int idy; // anode local idy (within PMT) private int glx; // anode global idx (onto RICH plane) private int gly; // anode global idy (onto RICH plane) + private float x; // anode global x (within CLAS) private float y; // anode global y (within CLAS) private float z; // anode global z (within CLAS) private float time; // Hit time private float rawtime; // Hit rawtime + private int duration; // Hit duration private int cluster; // parent cluster ID private int xtalk; // xtalk type @@ -44,7 +46,7 @@ public RICHHit(int hid, RICHTool tool, int phase, RICHEdge lead, RICHEdge trail) this.id = hid; this.sector = lead.get_sector(); this.tile = lead.get_tile(); - this.pmt = tool.Tile2PMT(tile, lead.get_channel()); // run from1 to 64 + this.pmt = tool.Tile2PMT(tile, lead.get_channel()); // run from1 to 391 this.channel = (lead.get_channel()-1)%64; this.anode = tool.Maroc2Anode(channel); // run from 1 to 64 this.idx = tool.Anode2idx(anode); diff --git a/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHLayer.java b/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHLayer.java index 9bd228a3f5..7112a058ab 100644 --- a/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHLayer.java +++ b/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHLayer.java @@ -9,6 +9,7 @@ import org.jlab.geom.prim.Point3D; import org.jlab.geom.prim.Line3D; import org.jlab.geom.prim.Vector3D; +import org.jlab.geom.prim.Plane3D; import eu.mihosoft.vrl.v3d.Vertex; import eu.mihosoft.vrl.v3d.Vector3d; @@ -20,6 +21,9 @@ public class RICHLayer extends ArrayList { * A layer in the RICH consists of an array of components */ + private static double MRAD = 1000.; + private static double RAD = 180./Math.PI; + private int id; // layer id private String name; // layer name @@ -228,6 +232,43 @@ public Sphere3D get_TrackingSphere(int ico) { public Vector3D get_LayerCSGBary(){ return get_CompoCSGBary(-1); } //------------------------------ + //------------------------------ + public Plane3D get_TrajPlane(){ + //------------------------------ + + int debugMode = 0; + + double toIP = -1.; + if(get_Name().equals("mapmts")) toIP=1.; + + Point3D pos = toPoint3D( get_SurfBary(-1, vinside.multiply(toIP)) ); + Vector3D ver = get_LayerNormal(vinside.multiply(toIP) ); + Plane3D plane = new Plane3D(pos, ver); + + if(debugMode>=1) { + System.out.format("get_TrajPlane %d %s to IP %7.2f %s\n",id,name,toIP,vinside.multiply(toIP).toStringBrief(2)); + System.out.format("get_TrajPlane %s %s \n",pos.toStringBrief(2), ver.toStringBrief(2)); + plane.show(); + } + return plane; + + } + + //------------------------------ + public Vector3D get_CompoBary(int icompo){ + //------------------------------ + + int debugMode = 0; + + Vector3D bary = get_SurfBary(icompo, vinside); + Vector3D sbary = get_SurfBary(icompo, vinside.multiply(-1.)); + + if(debugMode>0)System.out.format("%s %s \n",bary.toStringBrief(2), sbary.toStringBrief(2)); + return (bary.add(sbary)).multiply(0.5); + + } + + //------------------------------ public Vector3D get_CompoCSGBary(int icompo){ //------------------------------ @@ -301,6 +342,11 @@ public ArrayList select_Vertexes(Shape3D surf, Vector3D vers) { for(int ifa=0; ifa=1)System.out.format("Vertex %s \n", p.toStringBrief(2)); + } + if(toTriangle3D(f).normal().dot(vers)<0)continue; for (int ipo=0; ipo<3; ipo++){ @@ -388,6 +434,167 @@ public Vector3D get_SurfBary(int icompo, Vector3D vers){ return null; } + + //------------------------------ + public int get_TileQuadrant(int Nqua, int icompo, Point3D point, ArrayList verts) { + //------------------------------ + + int debugMode = 0; + + Shape3D surf = get_TrackingSurf(icompo); + Vector3D vers = new Vector3D(vinside.multiply(-1.)); + Point3D surfb = toPoint3D(get_SurfBary(icompo, vers)); + + if(debugMode==1)System.out.format(" --- N quadrant --- %d \n",Nqua); + for(int i=0; i %s \n",i,j,v0.toStringBrief(2)); + System.out.format(" stpx %3d %3d --> %s \n",i,j,stpx.toStringBrief(2)); + System.out.format(" vb %3d %3d --> %s \n",i,j,vb.toStringBrief(2)); + System.out.format(" vcross %3d %3d --> %s \n",i,j,vcross.toStringBrief(2)); + System.out.format(" vspy %3d %3d --> %s \n",i,j,stpy.toStringBrief(2)); + System.out.format(" vbary %3d %3d --> %s \n",i,j,vbary.toStringBrief(2)); + } + + found=1; + + } + } + } + + Vector3D step = new Vector3D(0.,0.,0.); + Vector3D vtx = new Vector3D(0.,0.,0.); + step.add(stpx); + step.add(stpy); + step.scale(-1.); + double phi = step.phi()*RAD; + if(debugMode==1)System.out.format(" step --> %s %7.2f\n",step.toStringBrief(2),phi); + + if(phi>0 && phi<=90) { + vtx = v0.toVector3D(); + } + if(phi>-180 && phi<=-90) { + vtx = (vbary.sub(step)).clone(); + stpx.scale(-1); + stpy.scale(-1); + } + if(phi>90 && phi<=180) { + vcross.rotate(step,90/RAD); + vtx = (vbary.add(step)).clone(); + stpx.scale(-1); + } + if(phi>-90 && phi<=0) { + vcross.rotate(step,-90/RAD); + vtx = (vbary.add(step)).clone(); + stpy.scale(-1); + } + + Vector3D diff = vtx.toPoint3D().vectorTo(point); + Vector3D prox = diff.projection(stpx); + Vector3D proy = diff.projection(stpy); + + if(debugMode==1){ + System.out.format(" \n"); + System.out.format(" diff %s \n",diff.toStringBrief(2)); + System.out.format(" stpx %s \n",stpx.toStringBrief(2)); + System.out.format(" prox %s \n",prox.toStringBrief(2)); + System.out.format(" stpy %s \n",stpy.toStringBrief(2)); + System.out.format(" proy %s \n",proy.toStringBrief(2)); + System.out.format(" \n"); + } + + double dx = prox.mag(); + double dy = proy.mag(); + double ddx = dx/20*Nqua; + double ddy = dy/20*Nqua; + + double th = diff.theta(); + double ph = prox.theta(); + + int idx = (int) ddx; + int idy = (int) ddy; + + if(debugMode==1){ + System.out.format(" angles %7.2f %7.2f \n",th,ph); + System.out.format(" diff --> %s\n",diff.toStringBrief(2)); + System.out.format(" prox --> %s\n",prox.toStringBrief(2)); + System.out.format(" proy --> %s\n",proy.toStringBrief(2)); + System.out.format(" vtx --> %s\n",vtx.toStringBrief(2)); + System.out.format(" point --> %s --> %7.2f %7.2f %7.2f %7.2f %4d %4d\n",point.toStringBrief(2), dx,dy,ddx,ddy,idx,idy); + if(idx>=Nqua || idy>=Nqua)System.out.format(" ECCOLO x %7.2f %4d y %7.2f %4d \n",ddx,idx,ddy,idy); + } + + // to stay within limits + if(idx<0)idx=0; + if(idx>Nqua-1)idx=Nqua-1; + if(idy<0)idy=0; + if(idy>Nqua-1)idy=Nqua-1; + + return idy*Nqua+idx; + } + + //------------------------------ + public int get_Quadrant(int Nqua, int icompo, Point3D point){ + //------------------------------ + + /* + * Look for the quadrant of aerogel tile + */ + int debugMode = 0; + + if(Nqua<0 || Nqua>15)Nqua=1; + int Nqua2 = (int) Math.pow(Nqua,2); + + if(debugMode>=1)System.out.format(" Get %d %d quadrant for compo %d ilay %d point %s\n", Nqua, Nqua2,icompo,id, point.toStringBrief(2)); + + Shape3D surf = get_TrackingSurf(icompo); + Vector3D vers = new Vector3D(vinside); + int iqua = get_TileQuadrant(Nqua, icompo, point, select_Vertexes(surf, vers)); + + return iqua; + + } + + + //------------------------------ public boolean into_Layer(Line3D ray, int icompo, int ifa) { //------------------------------ @@ -452,7 +659,7 @@ public RICHIntersection find_Intersection(Line3D ray, int ico, int exit, int pos //ATT:aggiungere min path int debugMode = 0; - if(ico<-1 || ico>=this.size()) return null; + if(ico<-2 || ico>=this.size()) return null; boolean global = true; int ilay = this.get_id(); @@ -825,6 +1032,10 @@ public ArrayList merge_CompoList() { public Point3D toPoint3D(Vertex ver) {return new Point3D(ver.pos.x, ver.pos.y, ver.pos.z); } //------------------------------ + //------------------------------ + public Point3D toPoint3D(Vector3D ver) {return new Point3D(ver.x(), ver.y(), ver.z()); } + //------------------------------ + //------------------------------ public Vector3d toVector3d(Vertex ver) {return new Vector3d(ver.pos.x, ver.pos.y, ver.pos.z); } //------------------------------ diff --git a/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHParticle.java b/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHParticle.java index 813080bb16..465c54ed3a 100644 --- a/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHParticle.java +++ b/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHParticle.java @@ -33,23 +33,35 @@ public class RICHParticle { private int parent_index = -999; private int hit_index = -999; private int type = 0; + private int recofound = -1; private int status = -1; private int CLASpid = -999; private int RICHpid = -999; private double momentum = 0; - private double[] ChAngle = new double[4]; + private double[][] ChAngle = new double[4][3]; + private double[] sChAngle = new double[3]; public Vector3d meas_hit = null; private double meas_time = 0.0; public Point3D lab_origin = null; public Vector3d lab_emission = null; - public int ilay_emission = 0; - public int ico_emission = 0; + public int ilay_emission = -1; + public int ico_emission = -1; + public int ico_entrance = -1; + public int iqua_emission = -1; public float refi_emission = 0; + public double chele_emission[] = {0.0, 0.0, 0.0}; + public double schele_emission[] = {0.0, 0.0, 0.0}; public double lab_phi = 0.0; public double lab_theta = 0.0; + private double pixel_gain = 0.0; + private double pixel_eff = 0.0; + private int pixel_flag = 0; + private double pixel_mtime = 0; + private double pixel_stime = 0; + // rotated frame into RICH local coordinates (used for the analytic solution) public double RotAngle = 0.0; public Vector3d RotAxis = null; @@ -96,8 +108,6 @@ public RICHParticle(int id, int parent_index, int hit_index, double mom, int CLA recopar = tool.get_Constants(); - //if(CLASpid!=22)set_changle(); - } @@ -134,15 +144,35 @@ private void set_changle() { // define only one Cherenkov angle depending on the pid hypothesis int debugMode = 0; - for(int k=0 ; k<4; k++) ChAngle[k] = 0.0; - ChAngle[0] = expectedChAngle(11); // expected angle for electron - ChAngle[1] = expectedChAngle(211); // pion - ChAngle[2] = expectedChAngle(321); // kaon - ChAngle[3] = expectedChAngle(2212); // proton + for(int j=0; j<3; j++) { + for(int k=0 ; k<4; k++) ChAngle[k][j] = 0.0; + sChAngle[j] = 0.0; + } + + for (int iref=0; iref<3; iref++){ + if(recopar.USE_ELECTRON_ANGLES==1){ + ChAngle[0][iref] = calibrated_ChAngle(11, iref); // expected angle for electron + ChAngle[1][iref] = calibrated_ChAngle(211, iref); // pion + ChAngle[2][iref] = calibrated_ChAngle(321, iref); // kaon + ChAngle[3][iref] = calibrated_ChAngle(2212, iref); // proton + + sChAngle[iref] = calibrated_sChAngle(iref); // expected angle for electron + + }else{ + + ChAngle[0][iref] = nominal_ChAngle(11); // expected angle for electron + ChAngle[1][iref] = nominal_ChAngle(211); // pion + ChAngle[2][iref] = nominal_ChAngle(321); // kaon + ChAngle[3][iref] = nominal_ChAngle(2212); // proton + + sChAngle[iref] = nominal_sChAngle(); // expected angle for electron + } + } if(debugMode>=1) { - System.out.format(" Create RICH particle mom %8.2f Ch %8.2f %8.2f %8.2f %8.2f \n",momentum,ChAngle[0]*MRAD,ChAngle[1]*MRAD,ChAngle[2]*MRAD,ChAngle[3]*MRAD); - System.out.format(" --> Ch angle limits %8.2f %8.2f \n",minChAngle()*MRAD,maxChAngle()*MRAD); + System.out.format(" Create RICH particle mom %8.2f \n",momentum); + for(int ir=0; ir<3; ir++) System.out.format(" --> Refle %3d pr %7.2f k %7.2f pi %7.2f e %7.2f --> limi %7.2f %7.2f res %7.2f\n",ir, + ChAngle[3][ir]*MRAD,ChAngle[2][ir]*MRAD,ChAngle[1][ir]*MRAD,ChAngle[0][ir]*MRAD,minChAngle(ir)*MRAD,maxChAngle(ir)*MRAD,sChAngle[ir]*MRAD); } } @@ -163,6 +193,10 @@ private void set_changle() { public int get_type() {return type;} // ------------- + // ------------- + public int get_recofound() {return recofound;} + // ------------- + // ------------- public int get_Status() {return status;} // ------------- @@ -184,9 +218,12 @@ private void set_changle() { // ------------- // ------------- - public double get_changle(int i) { return ChAngle[i]; } + public double get_changle(int ipar, int irefle) { return ChAngle[ipar][irefle]; } // ------------- + // ------------- + public double get_schangle(int irefle) { return sChAngle[irefle]; } + // ------------ // ------------- public double get_beta(int pid) { @@ -207,26 +244,33 @@ public double get_beta(int pid) { } // ---------------- - public double maxChAngle() { + public double maxChAngle(int irefle) { // ---------------- - for(int k=0 ; k<4; k++) if(ChAngle[k]>0)return ChAngle[k] + 3*recopar.RICH_DIRECT_RMS; + for(int k=0 ; k<4; k++) if(ChAngle[k][irefle]>0)return ChAngle[k][irefle] + 3*sChAngle[irefle]; return 0.0; } // ---------------- - public double minChAngle() { + public double minChAngle(int irefle) { // ---------------- // calculate the minimum Cherenlov angle compatible with the momentum - for(int k=3 ; k>=0; k--) if(ChAngle[k]>0)return Math.max(recopar.RICH_MIN_CHANGLE, ChAngle[k] - 3*recopar.RICH_DIRECT_RMS); + for(int k=3 ; k>=0; k--) if(ChAngle[k][irefle]>0) return Math.max(recopar.RICH_MIN_CHANGLE, ChAngle[k][irefle] - 3*sChAngle[irefle]); return 0.0; } // ---------------- - public double expectedChAngle(int pid){ + public double nominal_sChAngle(){ + // ---------------- + + return recopar.RICH_DIRECT_RMS; + } + + // ---------------- + public double nominal_ChAngle(int pid){ // ---------------- int debugMode = 0; @@ -238,6 +282,31 @@ public double expectedChAngle(int pid){ return 0.0; } + // ---------------- + public double calibrated_sChAngle(int irefle){ + // ---------------- + + return schele_emission[irefle]; + } + + // ---------------- + public double calibrated_ChAngle(int pid, int irefle){ + // ---------------- + + int debugMode = 0; + double arg = 0.0; + double beta = get_beta(pid); + double cose = Math.cos(chele_emission[irefle]); + + // ATT: beta=1 assumed for electron + if(beta>0) arg = 1.0/beta*cose; + if(debugMode>=1) System.out.format(" Expected Ch Angle %7.2f %8.4f beta %8.4f n %7.3f arg %8.4f\n",chele_emission[irefle]*1000, + get_mass(pid),beta,refi_emission, Math.acos(arg)*MRAD); + if(arg>0.0 && arg<1.0) return Math.acos(arg); + return 0.0; + } + + // ---------------- public void set_id(int id) { this.id=id;} // ---------------- @@ -254,6 +323,10 @@ public double expectedChAngle(int pid){ public void set_type(int type) { this.type=type; } // ---------------- + // ---------------- + public void set_recofound(int recof) { this.recofound=recof; } + // ---------------- + // ---------------- public void set_Status(int sta) { this.status = sta; } // ---------------- @@ -299,6 +372,34 @@ public void set_RICHpid(int hpid){ if(this.CLASpid<0)RICHpid*=-1; } + // ---------------- + public void set_PixelProp(RICHHit hit, RICHTool tool){ + // ---------------- + + int debugMode = 0; + + int ipmt = hit.get_pmt()-1; + int ich = hit.get_anode()-1; + + if (tool.get_Constants().USE_PIXEL_PROPERTIES==1){ + pixel_gain = tool.get_PixelGain(ipmt, ich); + pixel_eff = tool.get_PixelEff(ipmt, ich); + pixel_flag = tool.get_PixelFlag(ipmt, ich); + pixel_mtime = tool.get_PixelMtime(ipmt, ich); + pixel_stime = tool.get_PixelStime(ipmt, ich); + }else{ + pixel_gain = 1.0; + pixel_eff = 1.0; + pixel_flag = 1; + pixel_mtime = 0.0; + pixel_stime = recopar.RICH_TIME_RMS; + } + + if(debugMode>=1) System.out.format("Photon pixel %4d %4d %4d --> %2d %7.2f %7.2f %7.2f %7.2f \n",hit.get_id(), ipmt, ich, pixel_flag, pixel_gain, + pixel_eff, pixel_mtime, pixel_stime); + + } + // ---------------- public void set_points(RICHParticle hadron, Vector3d impa){ // ---------------- @@ -419,26 +520,37 @@ public boolean find_aerogel_points(RICHTool tool){ aero_entrance = tool.toVector3d(entrance.get_pos()); aero_exit = tool.toVector3d(exit.get_pos()); aero_normal = tool.toVector3d(exit.get_normal()); + /* * Take point at 3/4 of path inside aerrogel */ Vector3d amiddle = aero_exit.midpoint(aero_entrance); aero_middle = aero_exit.midpoint(amiddle); lab_emission = aero_middle; - // take the downstream aerogel tile as the one with largest number of phtoons and average emisison point + // take the downstream aerogel tile as the one with largest number of phtoons and average emission point ilay_emission = exit.get_layer(); ico_emission = exit.get_component(); - if(debugMode>=1)System.out.format(" AERO lay %3d ico %3d \n",ilay_emission,ico_emission); + ico_entrance = entrance.get_component(); refi_emission = tool.get_Component(ilay_emission,ico_emission).get_index(); + int Nqua = tool.get_Constants().QUADRANT_NUMBER; + iqua_emission = tool.get_Layer(ilay_emission).get_Quadrant(Nqua, ico_emission, exit.get_pos()); + + if(debugMode>=1){ + System.out.format(" AERO lay %3d ico %3d qua %3d \n",ilay_emission,ico_emission,iqua_emission); + if(entrance.get_layer()!=ilay_emission || entrance.get_component()!=ico_emission) + System.out.format(" AERO CROSS ilay %4d %4d ico %4d %4d \n",entrance.get_layer(),ilay_emission,entrance.get_component(),ico_emission); + } + + + for(int iref=0; iref<3; iref++)chele_emission[iref] = tool.get_ChElectron(ilay_emission, ico_emission, iqua_emission, iref); + for(int iref=0; iref<3; iref++)schele_emission[iref] = tool.get_sChElectron(ilay_emission, ico_emission, iqua_emission, iref); + set_changle(); RotAxis = aero_normal.cross(Vector3d.Z_ONE).normalized(); RotAngle = aero_normal.angle(Vector3d.Z_ONE); - if(debugMode>=1){ - System.out.format(" Qua %d %f \n",CLASpid,meas_hit.x); - } if(start_time==0.0)start_time = traced.get_time() - meas_hit.distance(aero_middle)/get_beta(CLASpid)/(PhysicsConstants.speedOfLight()); if(debugMode>=3){ @@ -623,7 +735,7 @@ public void find_EtaC_raytrace_steps(RICHParticle hadron, RICHTool tool) { double EtaCmin = 0.0; if(Math.abs(Cos_EtaC)<1.)EtaCmin = Math.acos(Cos_EtaC); int ntrials = 0; - while (dist > recopar.RICH_DIRECT_RMS*100/2. && ntrials<10){ + while (dist > nominal_sChAngle()*100/10. && ntrials<20){ if(debugMode>=1){ System.out.format(" Attempt %d with the %7.1f (%7.2f) phi %7.2f EtaC %7.2f\n",ntrials, the_min*MRAD, the_min*RAD, phi_min*RAD, EtaCmin*MRAD); @@ -634,16 +746,19 @@ public void find_EtaC_raytrace_steps(RICHParticle hadron, RICHTool tool) { int nthe = 0; for (nthe=1; nthe<=4; nthe++){ - double theta_dthe = the_min + recopar.RICH_DIRECT_RMS/nthe; + double theta_dthe = the_min + nominal_sChAngle()/nthe; Vector3d vpho_dthe = new Vector3d( Math.sin(theta_dthe)*Math.cos(phi_min), Math.sin(theta_dthe)*Math.sin(phi_min), Math.cos(theta_dthe)); - ArrayList rays_dthe = tool.RayTrace(lab_emission, ilay_emission, ico_emission, vpho_dthe); + double naero = 1/(hadron.get_beta(get_CLASpid())*(Math.sin(Theta_P)* Math.sin(theta_dthe)*Math.cos(phi_min-Phi_P)+Math.cos(Theta_P)*Math.cos(theta_dthe))); + + ArrayList rays_dthe = tool.RayTrace(lab_emission, ilay_emission, ico_emission, vpho_dthe, naero); + //ArrayList rays_dthe = tool.RayTrace(lab_emission, ilay_emission, ico_emission, vpho_dthe); if(rays_dthe!=null){ int nrefle_dthe = get_rayrefle(rays_dthe); if(debugMode>=1) System.out.format(" test %2d the %7.1f nrfl %2d vs %2d ",nthe, theta_dthe*MRAD, nrefle_dthe, nrefle_min); if(nrefle_dthe==nrefle_min){ Vector3d pmt_dthe = tool.toVector3d(rays_dthe.get(rays_dthe.size()-1).end()); Vector3d vers_dthe = pmt_dthe.minus(pmt_min); - dthe = (vec_dist.x*vers_dthe.x + vec_dist.y*vers_dthe.y) / (vers_dthe.x*vers_dthe.x + vers_dthe.y*vers_dthe.y) * recopar.RICH_DIRECT_RMS; + dthe = (vec_dist.x*vers_dthe.x + vec_dist.y*vers_dthe.y) / (vers_dthe.x*vers_dthe.x + vers_dthe.y*vers_dthe.y) * nominal_sChAngle(); if(debugMode>=1) System.out.format(" --> dthe pos %7.2f %7.2f %7.2f delta %7.1f (%8.2f %8.2f) \n", pmt_dthe.x, pmt_dthe.y, pmt_dthe.z, dthe*MRAD, vers_dthe.x, vers_dthe.y); break; @@ -654,16 +769,19 @@ public void find_EtaC_raytrace_steps(RICHParticle hadron, RICHTool tool) { } for (int nphi=1; nphi<=4; nphi++){ - double phi_dphi = phi_min + recopar.RICH_DIRECT_RMS/nphi; + double phi_dphi = phi_min + nominal_sChAngle()/nphi; Vector3d vpho_dphi = new Vector3d( Math.sin(the_min)*Math.cos(phi_dphi), Math.sin(the_min)*Math.sin(phi_dphi), Math.cos(the_min)); - ArrayList rays_dphi = tool.RayTrace(lab_emission, ilay_emission, ico_emission, vpho_dphi); + double naero = 1/(hadron.get_beta(get_CLASpid())*(Math.sin(Theta_P)* Math.sin(the_min)*Math.cos(phi_dphi-Phi_P)+Math.cos(Theta_P)*Math.cos(the_min))); + + ArrayList rays_dphi = tool.RayTrace(lab_emission, ilay_emission, ico_emission, vpho_dphi, naero); + //ArrayList rays_dphi = tool.RayTrace(lab_emission, ilay_emission, ico_emission, vpho_dphi); if(rays_dphi!=null){ int nrefle_dphi = get_rayrefle(rays_dphi); if(debugMode>=1) System.out.format(" test %2d phi %7.2f nrfl %2d vs %2d ",nphi, phi_dphi*RAD, nrefle_dphi, nrefle_min); if(nrefle_dphi==nrefle_min){ Vector3d pmt_dphi = tool.toVector3d(rays_dphi.get(rays_dphi.size()-1).end()); Vector3d vers_dphi = (pmt_dphi.minus(pmt_min)); - dphi = (vec_dist.x*vers_dphi.x + vec_dist.y*vers_dphi.y) / (vers_dphi.x*vers_dphi.x + vers_dphi.y*vers_dphi.y) * recopar.RICH_DIRECT_RMS; + dphi = (vec_dist.x*vers_dphi.x + vec_dist.y*vers_dphi.y) / (vers_dphi.x*vers_dphi.x + vers_dphi.y*vers_dphi.y) * nominal_sChAngle(); if(debugMode>=1) System.out.format(" --> dphi pos %7.2f %7.2f %7.2f delta %7.2f (%8.2f %8.2f) \n", pmt_dphi.x, pmt_dphi.y, pmt_dphi.z, dphi*RAD, vers_dphi.x, vers_dphi.y); break; @@ -681,7 +799,10 @@ public void find_EtaC_raytrace_steps(RICHParticle hadron, RICHTool tool) { if(debugMode>=1) System.out.format(" do step nn %3d the %7.1f phi %7.2f (from %7.1f %7.2f) \n",nn,the_new*MRAD,phi_new*RAD,the_min*MRAD,phi_min*RAD); Vector3d vpho_min = new Vector3d( Math.sin(the_new)*Math.cos(phi_new), Math.sin(the_new)*Math.sin(phi_new), Math.cos(the_new)); - rays_min = tool.RayTrace(lab_emission, ilay_emission, ico_emission, vpho_min); + double naero = 1/(hadron.get_beta(get_CLASpid())*(Math.sin(Theta_P)* Math.sin(the_new)*Math.cos(phi_new-Phi_P)+Math.cos(Theta_P)*Math.cos(the_new))); + + rays_min = tool.RayTrace(lab_emission, ilay_emission, ico_emission, vpho_min, naero); + //rays_min = tool.RayTrace(lab_emission, ilay_emission, ico_emission, vpho_min); if(rays_min!=null){ int nrefle_new = get_rayrefle(rays_min); if(debugMode>=1) System.out.format(" test %2d the %7.1f phi %7.2f nrfl %2d vs %2d ",nn, the_new*MRAD, phi_new*RAD, nrefle_new, nrefle_min); @@ -716,7 +837,7 @@ public void find_EtaC_raytrace_steps(RICHParticle hadron, RICHTool tool) { ntrials++; } - if(dist < recopar.RICH_DIRECT_RMS*100.){ + if(dist < nominal_sChAngle()*100.){ if(debugMode>=1){ System.out.format(" --> Matched value found using %d calls: result is %8.2f %8.2f matched hit %7.2f %7.2f %7.2f dist %7.3f \n", @@ -855,7 +976,7 @@ public double time_probability(double testtime, int recotype) { // ---------------- - public double pid_probability(RICHParticle hadron, int pid, int recotype) { + public double pid_probability(RICHParticle hadron, RICHHit hit, int pid, int recotype) { // ---------------- /* * calculate probability for a given pid hypothesis @@ -870,37 +991,55 @@ public double pid_probability(RICHParticle hadron, int pid, int recotype) { if(recotype==0) reco = analytic; if(recotype==1) reco = traced; - // angle probability - double mean = 0.0; - if(Math.abs(pid)==11)mean=hadron.get_changle(0); - if(Math.abs(pid)==211)mean=hadron.get_changle(1); - if(Math.abs(pid)==321)mean=hadron.get_changle(2); - if(Math.abs(pid)==2212)mean=hadron.get_changle(3); - double func = 0.0; double dfunc = 1e-3; - double sigma = recopar.RICH_DIRECT_RMS; - - if(mean>0){ - func = Math.exp((-0.5)*Math.pow((reco.get_EtaC() - mean)/sigma, 2) )/ (sigma*Math.sqrt(2* Math.PI)); - } - - // timing probability - double meant = start_time + reco.get_time(); - double sigmat = recopar.RICH_TIME_RMS; double funt = 0.0; double dfunt = 1; - if(meant>0){ - funt = Math.exp((-0.5)*Math.pow((meas_time - meant)/sigmat, 2) )/ (sigmat*Math.sqrt(2* Math.PI)); + + double mean = 0.0; + double sigma = 0.0; + double recot = 0.0; + double meant = 0.0; + double sigmat = 0.0; + + if(pixel_flag==1){ + + // angle probability + + int irefle = reco.get_RefleType(); + if(irefle>=0 && irefle<=2){ + if(Math.abs(pid)==11)mean=hadron.get_changle(0, irefle); + if(Math.abs(pid)==211)mean=hadron.get_changle(1, irefle); + if(Math.abs(pid)==321)mean=hadron.get_changle(2, irefle); + if(Math.abs(pid)==2212)mean=hadron.get_changle(3, irefle); + + sigma = hadron.get_schangle(irefle); + } + + if(mean>0 && sigma>0){ + func = Math.exp((-0.5)*Math.pow((reco.get_EtaC() - mean)/sigma, 2) )/ (sigma*Math.sqrt(2* Math.PI)); + } + + // timing probability + recot = start_time + reco.get_time(); + meant = pixel_mtime; + sigmat = pixel_stime; + + + if(recot>0 && sigmat>0){ + funt = Math.exp((-0.5)*Math.pow((meas_time - recot - meant)/sigmat, 2) )/ (sigmat*Math.sqrt(2* Math.PI)); + } + } - - double prob = 1 + func*dfunc*funt*dfunt + recopar.RICH_BKG_PROBABILITY; - if(debugMode>=1)if(prob-1>recopar.RICH_BKG_PROBABILITY)System.out.format( - "PID prob %4d mean %8.3f etaC %8.3f meant %8.3f time %8.3f --> %g %g %g \n",pid, - mean*MRAD,reco.get_EtaC()*MRAD,meant,meas_time,func*dfunc,funt*dfunt,Math.log(prob)); + double prob = 1 + pixel_eff*func*dfunc*funt*dfunt + recopar.RICH_BKG_PROBABILITY; + + //if(debugMode>=1)if(prob-1>recopar.RICH_BKG_PROBABILITY)System.out.format( + if(debugMode>=1)System.out.format( + "PID prob %4d mean %7.2f etaC %7.2f sigma %7.2f meant %7.2f (%7.2f + %7.2f) time %7.2f sigmat %7.2f eff %7.2f --> %g %g %8.4f e-3\n",pid, + mean*MRAD,reco.get_EtaC()*MRAD,sigma*MRAD,recot+meant,recot,meant,meas_time,sigmat,pixel_eff,func*dfunc,funt*dfunt,Math.log(prob)*1e3); return prob; } @@ -933,8 +1072,13 @@ public void show() { Vector3d ori_impact = meas_hit.minus(reference); System.out.format(" PART info pid %d mass %8.5f mom %g \n", CLASpid, get_mass(CLASpid), momentum); - System.out.format(" ChAngle (mrad) %8.2f %8.2f %8.2f %8.2f limits %8.2f %8.2f \n", ChAngle[3]*MRAD, ChAngle[2]*MRAD, ChAngle[1]*MRAD, ChAngle[0]*MRAD, - minChAngle()*MRAD, maxChAngle()*MRAD); + + System.out.format(" ChAngle dir (mrad) %8.2f %8.2f %8.2f %8.2f limits %8.2f %8.2f \n", ChAngle[3][0]*MRAD, ChAngle[2][0]*MRAD, ChAngle[1][0]*MRAD, ChAngle[0][0]*MRAD, + minChAngle(0)*MRAD, maxChAngle(0)*MRAD); + System.out.format(" ChAngle lat (mrad) %8.2f %8.2f %8.2f %8.2f limits %8.2f %8.2f \n", ChAngle[3][1]*MRAD, ChAngle[2][1]*MRAD, ChAngle[1][1]*MRAD, ChAngle[0][1]*MRAD, + minChAngle(1)*MRAD, maxChAngle(1)*MRAD); + System.out.format(" ChAngle spe (mrad) %8.2f %8.2f %8.2f %8.2f limits %8.2f %8.2f \n", ChAngle[3][2]*MRAD, ChAngle[2][2]*MRAD, ChAngle[1][2]*MRAD, ChAngle[0][2]*MRAD, + minChAngle(2)*MRAD, maxChAngle(2)*MRAD); System.out.println(" "); System.out.format(" TRACK origin %8.1f %8.1f %8.1f \n", lab_origin.x(), lab_origin.y(), lab_origin.z()); System.out.format(" direction %8.3f %8.3f %8.3f theta %8.2f phi %8.2f \n", lab_direction.x, lab_direction.y, lab_direction.z, lab_theta*RAD, lab_phi*RAD); diff --git a/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHSolution.java b/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHSolution.java index ae91ccff37..0c8c0c2e07 100644 --- a/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHSolution.java +++ b/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHSolution.java @@ -28,6 +28,7 @@ public RICHSolution(int type) { } private int type; // Solution type + private int OK = -1; // Solution type private float EtaC=0; // Cherenkov angle private float aeron=0; // Aerogel refrative index @@ -37,6 +38,7 @@ public RICHSolution(int type) { private int nrefle=0; // Number of photon reflections private int nrefra=0; // Number of photon refractions private float time=0; // Transit time within the RICH (solution dependent) + private double machi2 = 0.0; // chi2 of the hit-trajectory matching private Vector3d hit = new Vector3d(0,0,0);; // Impact point of photon on the PMT private ArrayList raytracks = new ArrayList(); // Detailed path of the photon @@ -47,6 +49,16 @@ public RICHSolution(int type) { private double prprob = 0.0; // Cherenkov probability for proton private double bgprob = 0.0; // Cherenkov probability for background + private int ndir = 0; // Number of direct photons + private double chdir = 0.0; // Mean Cherenkov angle for direct photons + private double sdir = 0.0; // RMS Cherenkov angle for direct photons + private int nlat = 0; // Number of photons reflected by lateral mirrors + private double chlat = 0.0; // Mean Cherenkov angle for photons reflected by lateral mirrors + private double slat = 0.0; // RMS Cherenkov angle for photons reflected by lateral mirrors + private int nspe = 0; // Number of photons reflected by ssperical mirrors + private double chspe = 0.0; // Mean Cherenkov angle for photons reflected by ssperical mirrors + private double sspe = 0.0; // RMS Cherenkov angle for photons reflected by ssperical mirrors + private double bestprob = 0.0; // best Cherenkov probability for hadron ID private double secprob = 0.0; // second best Cherenkov probability for hadron ID private int bestH = 0; // best Cherenkov probability for hadron ID @@ -57,6 +69,10 @@ public RICHSolution(int type) { public int get_type() { return type; } // ---------------- + // ---------------- + public int get_OK() { return OK; } + // ---------------- + // ---------------- public float get_EtaC() { return EtaC; } // ---------------- @@ -81,6 +97,10 @@ public RICHSolution(int type) { public float get_time() { return time; } // ---------------- + // ---------------- + public double get_machi2() { return machi2; } + // ---------------- + // ---------------- public float get_raypath() { // ---------------- @@ -108,11 +128,29 @@ public float get_raytime() { } // ---------------- - public int get_firstrefle() { + public int get_FirstRefle() { // ---------------- if(raytracks.size()>2) return raytracks.get(2).get_type(); - return -1; + return 0; + + } + + // ---------------- + public int get_RefleType() { + // ---------------- + + int ifirst = get_FirstRefle(); + int ilay = (int) (ifirst-10000)/100; + if(ifirst<10000){ + return 0; + }else{ + if(ilay==11){ + return 2; + }else{ + return 1; + } + } } @@ -171,27 +209,63 @@ public int get_rayrefra() { // ---------------- // ---------------- - public double get_elprob() { return elprob; } + public double get_ElProb() { return elprob; } + // ---------------- + + // ---------------- + public double get_PiProb() { return piprob; } + // ---------------- + + // ---------------- + public double get_KProb() { return kprob; } + // ---------------- + + // ---------------- + public double get_PrProb() { return prprob; } + // ---------------- + + // ---------------- + public double get_BgProb() { return bgprob; } + // ---------------- + + // ---------------- + public int get_Ndir() { return ndir; } + // ---------------- + + // ---------------- + public double get_Chdir() { return chdir; } + // ---------------- + + // ---------------- + public double get_RMSdir() { return sdir; } + // ---------------- + + // ---------------- + public int get_Nlat() { return nlat; } + // ---------------- + + // ---------------- + public double get_Chlat() { return chlat; } // ---------------- // ---------------- - public double get_piprob() { return piprob; } + public double get_RMSlat() { return slat; } // ---------------- // ---------------- - public double get_kprob() { return kprob; } + public int get_Nspe() { return nspe; } // ---------------- // ---------------- - public double get_prprob() { return prprob; } + public double get_Chspe() { return chspe; } // ---------------- // ---------------- - public double get_bgprob() { return bgprob; } + public double get_RMSspe() { return sspe; } // ---------------- // ---------------- - public int get_bestH() { return bestH; } + public int get_BestH() { return bestH; } // ---------------- // ---------------- @@ -199,7 +273,7 @@ public int get_rayrefra() { // ---------------- // ---------------- - public double get_bestprob() { return bestprob; } + public double get_Bestprob() { return bestprob; } // ---------------- // ---------------- @@ -214,11 +288,11 @@ public int get_rayrefra() { public double assign_PID(double lh_el, double lh_pi, double lh_k, double lh_pr, double lh_bg) { // ---------------- - this.set_elprob(lh_el); - this.set_piprob(lh_pi); - this.set_kprob(lh_k); - this.set_prprob(lh_pr); - this.set_bgprob(lh_bg); + this.set_ElProb(lh_el); + this.set_PiProb(lh_pi); + this.set_KProb(lh_k); + this.set_PrProb(lh_pr); + this.set_BgProb(lh_bg); double likeh[] = {this.piprob, this.kprob, this.prprob}; Arrays.sort(likeh); @@ -241,6 +315,10 @@ public double assign_PID(double lh_el, double lh_pi, double lh_k, double lh_pr, public void set_type(int type) { this.type = type; } // ---------------- + // ---------------- + public void set_OK(int ok) { this.OK = ok; } + // ---------------- + // ---------------- public void set_EtaC(float EtaC) { this.EtaC = EtaC; } // ---------------- @@ -265,6 +343,10 @@ public double assign_PID(double lh_el, double lh_pi, double lh_k, double lh_pr, public void set_time(float time) { this.time = time; } // ---------------- + // ---------------- + public void set_machi2(double machi2) { this.machi2 = machi2; } + // ---------------- + // ---------------- public void set_nrefle(int nrefle) { this.nrefle = nrefle; } // ---------------- @@ -302,23 +384,59 @@ public void set_raytracks(ArrayList rays){ // ---------------- // ---------------- - public void set_elprob(double elprob) { this.elprob = elprob; } + public void set_ElProb(double elprob) { this.elprob = elprob; } + // ---------------- + + // ---------------- + public void set_PiProb(double piprob) { this.piprob = piprob; } + // ---------------- + + // ---------------- + public void set_KProb(double kprob) { this.kprob = kprob; } + // ---------------- + + // ---------------- + public void set_PrProb(double prprob) { this.prprob = prprob; } + // ---------------- + + // ---------------- + public void set_BgProb(double bgprob) { this.bgprob = bgprob; } + // ---------------- + + // ---------------- + public void set_Ndir(int ndir) { this.ndir= ndir; } + // ---------------- + + // ---------------- + public void set_Chdir(double chdir) { this.chdir= chdir; } + // ---------------- + + // ---------------- + public void set_RMSdir(double sdir) { this.sdir= sdir; } + // ---------------- + + // ---------------- + public void set_Nlat(int nlat) { this.nlat= nlat; } + // ---------------- + + // ---------------- + public void set_Chlat(double chlat) { this.chlat= chlat; } // ---------------- // ---------------- - public void set_piprob(double piprob) { this.piprob = piprob; } + public void set_RMSlat(double slat) { this.slat= slat; } // ---------------- // ---------------- - public void set_kprob(double kprob) { this.kprob = kprob; } + public void set_Nspe(int nspe) { this.nspe= nspe; } // ---------------- // ---------------- - public void set_prprob(double prprob) { this.prprob = prprob; } + public void set_Chspe(double chspe) { this.chspe= chspe; } // ---------------- // ---------------- - public void set_bgprob(double bgprob) { this.bgprob = bgprob; } + public void set_RMSspe(double sspe) { this.sspe= sspe; } // ---------------- // ---------------- @@ -360,7 +478,7 @@ public void showSolution() { // ---------------- System.out.format("SOL type %3d EtaC %8.3f n %6.4f the %7.3f phi %7.3f hit %6.1f %6.1 %6.1f path %6.1f time %6.2f nrfl %2d nfr %2d pel %7.5f pi %7.5g k %7.5g pr %7.5g bg %7.5g \n", get_type(), get_EtaC(), get_aeron(), get_theta(), get_phi(), get_hit().x, get_hit().y, get_hit().z, get_path(), get_time(), get_nrefle(), get_nrefra(), - get_elprob(), get_piprob(), get_kprob(), get_prprob(), get_bgprob()); + get_ElProb(), get_PiProb(), get_KProb(), get_PrProb(), get_BgProb()); } } diff --git a/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHTool.java b/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHTool.java index 8ba793ae48..f440c0c5df 100644 --- a/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHTool.java +++ b/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHTool.java @@ -202,8 +202,21 @@ public void RICHTool(){ private double pmt_timeoff[][] = new double[NPMT][NPIX]; private double pmt_timewalk[][] = new double[NPMT][4]; + private double pixel_gain[][] = new double[NPMT][NPIX]; + private double pixel_eff[][] = new double[NPMT][NPIX]; + private int pixel_flag[][] = new int [NPMT][NPIX]; // 0 = dead, 1 = ok, 2= hot + private int pixel_ntime[][] = new int [NPMT][NPIX]; // 0 = dead, 1 = ok, 2= hot + private double pixel_mtime[][] = new double [NPMT][NPIX]; // 0 = dead, 1 = ok, 2= hot + private double pixel_stime[][] = new double [NPMT][NPIX]; // 0 = dead, 1 = ok, 2= hot + private double aero_refi[][] = new double[4][31]; private double aero_plan[][] = new double[4][31]; + private double aero_chele_dir[][][] = new double[4][31][225]; + private double aero_chele_lat[][][] = new double[4][31][225]; + private double aero_chele_spe[][][] = new double[4][31][225]; + private double aero_schele_dir[][][] = new double[4][31][225]; + private double aero_schele_lat[][][] = new double[4][31][225]; + private double aero_schele_spe[][][] = new double[4][31][225]; private Vector3D rich_survey_angle = new Vector3D(); private Vector3D rich_survey_shift = new Vector3D(); @@ -233,11 +246,20 @@ public void RICHTool(){ private RICHConstants reco_constants = new RICHConstants(); //------------------------------ - public void init_GeoConstants(IndexedTable aeroConstants, IndexedTable misaConstants, IndexedTable paraConstants){ + public void init_GeoConstants(int iflag, IndexedTable aeroConstants, IndexedTable misaConstants, IndexedTable paraConstants){ //------------------------------ + // generate the tracking layers (0 = only Aerogel and MaPMT for trajectory, 1 = all) // start processing time init_ProcessTime(); + + // reset alignment constants + for (int ila=0; ila0){ + // global pixel coordinat indexes + init_GlobalPixelGeo(); - // RICH survey - init_Survey(); + // RICH survey + init_Survey(); + } // RICH geometry organized on layers of Shape3D area and RICH components - init_RICHLayers(); + init_RICHLayers(iflag); } //------------------------------ - public void init_TimeConstants(IndexedTable timewalkConstants, IndexedTable timeoffConstants){ + public void init_TimeConstants(IndexedTable timewalkConstants, IndexedTable timeoffConstants, IndexedTable cheleConstants, IndexedTable pixelConstants){ //------------------------------ // load constants if(RICHConstants.READ_FROM_FILES==1){ init_ConstantsTxT(2); }else{ - init_TimeConstantsCCDB(timewalkConstants, timeoffConstants); + init_TimeConstantsCCDB(timewalkConstants, timeoffConstants, cheleConstants, pixelConstants); } } @@ -336,7 +359,7 @@ public int get_Globalidy(int pmt, int anode) { //------------------------------ - public void init_TimeConstantsCCDB(IndexedTable timewalkConstants, IndexedTable timeoffConstants){ + public void init_TimeConstantsCCDB(IndexedTable timewalkConstants, IndexedTable timeoffConstants, IndexedTable cheleConstants, IndexedTable pixelConstants){ //------------------------------ int debugMode = 1; @@ -350,7 +373,7 @@ public void init_TimeConstantsCCDB(IndexedTable timewalkConstants, IndexedTable pmt_timeoff[ipmt][ich] = (float) timeoffConstants.getDoubleValue("offset", 4, ipmt+1, ich+1); } if(debugMode>=1 && reco_constants.RICH_DEBUG>0){ - if(ipmt<10 || ipmt>380)System.out.format("CCDB RICH TOFF ipmt %4d %8.2f (ch1) %8.2f (ch2) %8.2f (ch63) %8.2f (ch64) \n", ipmt+1, + if(ipmt<10 || ipmt>380)System.out.format("CCDB RICH TOFF ipmt %4d %8.3f (ch1) %8.3f (ch2) %8.3f (ch63) %8.3f (ch64) \n", ipmt+1, pmt_timeoff[ipmt][0], pmt_timeoff[ipmt][1], pmt_timeoff[ipmt][62], pmt_timeoff[ipmt][63]); if(ipmt==10)System.out.format("CCDB RICH TOFF ....... \n"); if(ipmt==390)System.out.format(" \n"); @@ -361,20 +384,94 @@ public void init_TimeConstantsCCDB(IndexedTable timewalkConstants, IndexedTable * TIME_WALKs */ - // ATT: time_walk bank definition is wrong + // TODO: time_walk bank definition is wrong for(int ipmt=0; ipmt=1 && reco_constants.RICH_DEBUG>0){ - if(ipmt<10 || ipmt>380)System.out.format("CCDB RICH TWALK ipmt %4d D0 = %8.2f T0 = %8.2f m1 = %8.3f m2 = %8.3f\n", ipmt+1, + if(ipmt<10 || ipmt>380)System.out.format("CCDB RICH TWALK ipmt %4d D0 = %8.3f T0 = %8.3f m1 = %8.4f m2 = %8.4f\n", ipmt+1, pmt_timewalk[ipmt][0], pmt_timewalk[ipmt][1] , pmt_timewalk[ipmt][2], pmt_timewalk[ipmt][3]); if(ipmt==10)System.out.format("CCDB RICH TWALK ....... \n"); if(ipmt==390)System.out.format(" \n"); } } + /* + * AEROGEL CALIBRATED OPTCIS (USING ELECTRON CONTROL SAMPLE) + */ + + int ndo[] = {16,22,31,31}; + double mrad = reco_constants.MRAD; + for (int ila=0; ila<4; ila++){ + for (int ico=0; ico=1 && reco_constants.RICH_DEBUG>0){ + if( (itil<2 || itil>ndo[ila]-3) && (iqua==0 || iqua==224)) { + System.out.format("CCDB RICH CHELE ila %4d itile %3d iq %4d dir = %7.2f %7.2f lat = %7.2f %7.2f spe = %7.2f %7.2f \n", 201+ila, itil+1, iqua+1, + aero_chele_dir[ila][itil][iqua]*mrad, aero_schele_dir[ila][itil][iqua]*mrad, + aero_chele_lat[ila][itil][iqua]*mrad, aero_schele_lat[ila][itil][iqua]*mrad, + aero_chele_spe[ila][itil][iqua]*mrad, aero_schele_spe[ila][itil][iqua]*mrad); + } + if(ila==3 && ico==ndo[ila]*225-1)System.out.format(" \n"); + } + } + } + + /* + * PIXELS + */ + + for(int ipmt=0; ipmt=1 && reco_constants.RICH_DEBUG>0){ + if(ipmt<2 || ipmt>388)System.out.format("CCDB PIXEL GAIN ipmt %4d %8.2f (ch1) %8.2f (ch2) %8.2f (ch63) %8.2f (ch64) \n", ipmt+1, + pixel_gain[ipmt][0], pixel_gain[ipmt][1], pixel_gain[ipmt][62], pixel_gain[ipmt][63]); + if(ipmt==10)System.out.format("CCDB PIXEL GAIN ....... \n"); + + if(ipmt<2 || ipmt>388)System.out.format("CCDB PIXEL EFF ipmt %4d %8.2f (ch1) %8.2f (ch2) %8.2f (ch63) %8.2f (ch64) \n", ipmt+1, + pixel_eff[ipmt][0], pixel_eff[ipmt][1], pixel_eff[ipmt][62], pixel_eff[ipmt][63]); + if(ipmt==10)System.out.format("CCDB PIXEL EFF ....... \n"); + + if(ipmt<2 || ipmt>388)System.out.format("CCDB PIXEL STATUS ipmt %4d %8d (ch1) %8d (ch2) %8d (ch63) %8d (ch64) \n", ipmt+1, + pixel_flag[ipmt][0], pixel_flag[ipmt][1], pixel_flag[ipmt][62], pixel_flag[ipmt][63]); + if(ipmt==10)System.out.format("CCDB PIXEL STATUS ....... \n"); + + if(ipmt<2 || ipmt>388)System.out.format("CCDB PIXEL NTIME ipmt %4d %8d (ch1) %8d (ch2) %8d (ch63) %8d (ch64) \n", ipmt+1, + pixel_ntime[ipmt][0], pixel_ntime[ipmt][1], pixel_ntime[ipmt][62], pixel_ntime[ipmt][63]); + if(ipmt==10)System.out.format("CCDB PIXEL NTIME ....... \n"); + + if(ipmt<2 || ipmt>388)System.out.format("CCDB PIXEL MTIME ipmt %4d %8.2f (ch1) %8.2f (ch2) %8.2f (ch63) %8.2f (ch64) \n", ipmt+1, + pixel_mtime[ipmt][0], pixel_mtime[ipmt][1], pixel_mtime[ipmt][62], pixel_mtime[ipmt][63]); + if(ipmt==10)System.out.format("CCDB PIXEL MTIME ....... \n"); + + if(ipmt<2 || ipmt>388)System.out.format("CCDB PIXEL STIME ipmt %4d %8.2f (ch1) %8.2f (ch2) %8.2f (ch63) %8.2f (ch64) \n", ipmt+1, + pixel_stime[ipmt][0], pixel_stime[ipmt][1], pixel_stime[ipmt][62], pixel_stime[ipmt][63]); + if(ipmt==10)System.out.format("CCDB PIXEL STIME ....... \n"); + + if(ipmt==390)System.out.format(" \n"); + } + } + } @@ -402,10 +499,15 @@ public void init_GeoConstantsCCDB(IndexedTable paraConstants, IndexedTable aeroC reco_constants.THROW_PHOTON_NUMBER = paraConstants.getIntValue("flag11", 4, 0, 0); reco_constants.TRACE_PHOTONS = paraConstants.getIntValue("flag12", 4, 0, 0); - reco_constants.REDO_RICH_RECO = paraConstants.getIntValue("falg13", 4, 0, 0); + reco_constants.REDO_RICH_RECO = paraConstants.getIntValue("flag13", 4, 0, 0); reco_constants.DO_MIRROR_HADS = paraConstants.getIntValue("flag14", 4, 0, 0); reco_constants.DO_CURVED_AERO = paraConstants.getIntValue("flag15", 4, 0, 0); + reco_constants.USE_ELECTRON_ANGLES = paraConstants.getIntValue("flag16", 4, 0, 0); + reco_constants.USE_PIXEL_PROPERTIES = paraConstants.getIntValue("flag17", 4, 0, 0); + reco_constants.SAVE_THROWS = paraConstants.getIntValue("flag18", 4, 0, 0); + reco_constants.QUADRANT_NUMBER = paraConstants.getIntValue("flag19", 4, 0, 0); + reco_constants.GOODHIT_FRAC = paraConstants.getDoubleValue("par1", 4, 0, 0); reco_constants.RICH_DCMATCH_CUT = paraConstants.getDoubleValue("par2", 4, 0, 0); reco_constants.RICH_HITMATCH_RMS = paraConstants.getDoubleValue("par3", 4, 0, 0); @@ -418,40 +520,49 @@ public void init_GeoConstantsCCDB(IndexedTable paraConstants, IndexedTable aeroC reco_constants.MISA_SHIFT_SCALE = paraConstants.getDoubleValue("par9", 4, 0, 0); reco_constants.MISA_ANGLE_SCALE = paraConstants.getDoubleValue("par10", 4, 0, 0); - //ATT: check + //TODO: check //reco_constants.RICH_DEBUG = 1.0; - if(debugMode>=1 && reco_constants.RICH_DEBUG>0){ + //reco_constants.QUADRANT_NUMBER = 5; + //reco_constants.USE_ELECTRON_ANGLES = 1; + //reco_constants.USE_PIXEL_PROPERTIES = 1; + if(debugMode>=1 && reco_constants.RICH_DEBUG>0){ //MC + //if(debugMode>=1){ System.out.format(" \n"); - System.out.format("CCDB RICH PARA DO_MISALIGNMENT %8d \n", reco_constants.DO_MISALIGNMENT); - System.out.format("CCDB RICH PARA FORCE_DC_MATCH %8d \n", reco_constants.FORCE_DC_MATCH); - System.out.format("CCDB RICH PARA MISA_RICH_REF %8d \n", reco_constants.MISA_RICH_REF); - System.out.format("CCDB RICH PARA MISA_PMT_PIVOT %8d \n", reco_constants.MISA_PMT_PIVOT); - System.out.format("CCDB RICH PARA APPLY_SURVEY %8d \n", reco_constants.APPLY_SURVEY); - - System.out.format("CCDB RICH PARA DO_ANALYTIC %8d \n", reco_constants.DO_ANALYTIC); - System.out.format("CCDB RICH PARA THROW_ELECTRONS %8d \n", reco_constants.THROW_ELECTRONS); - System.out.format("CCDB RICH PARA THROW_PIONS %8d \n", reco_constants.THROW_PIONS); - System.out.format("CCDB RICH PARA THROW_KAONS %8d \n", reco_constants.THROW_KAONS); - System.out.format("CCDB RICH PARA THROW_PROTONS %8d \n", reco_constants.THROW_PROTONS); - System.out.format("CCDB RICH PARA THROW_PHOTON_NUMBER %8d \n", reco_constants.THROW_PHOTON_NUMBER); - System.out.format("CCDB RICH PARA TRACE_PHOTONS %8d \n", reco_constants.TRACE_PHOTONS); - - System.out.format("CCDB RICH PARA REDO_RICH_RECO %8d \n", reco_constants.REDO_RICH_RECO); - System.out.format("CCDB RICH PARA DO_MIRROR_HADS %8d \n", reco_constants.DO_MIRROR_HADS); - System.out.format("CCDB RICH PARA DO_CURVED_AERO %8d \n", reco_constants.DO_CURVED_AERO); - - System.out.format("CCDB RICH PARA GOODHIT_FRAC %8.4f \n", reco_constants.GOODHIT_FRAC); - System.out.format("CCDB RICH PARA RICH_DCMATCH_CUT %8.4f \n", reco_constants.RICH_DCMATCH_CUT); - System.out.format("CCDB RICH PARA RICH_HITMATCH_RMS %8.4f \n", reco_constants.RICH_HITMATCH_RMS); - System.out.format("CCDB RICH PARA RICH_DIRECT_RMS %8.4f \n", reco_constants.RICH_DIRECT_RMS); - System.out.format("CCDB RICH PARA SHOW_PROGRESS_INTERVAL %8.4f \n", reco_constants.SHOW_PROGRESS_INTERVAL); - System.out.format("CCDB RICH PARA THROW_ASSOCIATION_CUT %8.4f \n", reco_constants.THROW_ASSOCIATION_CUT); - - System.out.format("CCDB RICH PARA RICH_DEBUG %8.4f \n", reco_constants.RICH_DEBUG); - System.out.format("CCDB RICH PARA RICH_TIME_RMS %8.4f \n", reco_constants.RICH_TIME_RMS); - System.out.format("CCDB RICH PARA MISA_SHIFT_SCALE %8.4f \n", reco_constants.MISA_SHIFT_SCALE); - System.out.format("CCDB RICH PARA MISA_ANGLE_SCALE %8.4f \n", reco_constants.MISA_ANGLE_SCALE); + System.out.format("CCDB RICH PARA DO_MISALIGNMENT %9d \n", reco_constants.DO_MISALIGNMENT); + System.out.format("CCDB RICH PARA FORCE_DC_MATCH %9d \n", reco_constants.FORCE_DC_MATCH); + System.out.format("CCDB RICH PARA MISA_RICH_REF %9d \n", reco_constants.MISA_RICH_REF); + System.out.format("CCDB RICH PARA MISA_PMT_PIVOT %9d \n", reco_constants.MISA_PMT_PIVOT); + System.out.format("CCDB RICH PARA APPLY_SURVEY %9d \n", reco_constants.APPLY_SURVEY); + + System.out.format("CCDB RICH PARA DO_ANALYTIC %9d \n", reco_constants.DO_ANALYTIC); + System.out.format("CCDB RICH PARA THROW_ELECTRONS %9d \n", reco_constants.THROW_ELECTRONS); + System.out.format("CCDB RICH PARA THROW_PIONS %9d \n", reco_constants.THROW_PIONS); + System.out.format("CCDB RICH PARA THROW_KAONS %9d \n", reco_constants.THROW_KAONS); + System.out.format("CCDB RICH PARA THROW_PROTONS %9d \n", reco_constants.THROW_PROTONS); + System.out.format("CCDB RICH PARA THROW_PHOTON_NUMBER %9d \n", reco_constants.THROW_PHOTON_NUMBER); + System.out.format("CCDB RICH PARA TRACE_PHOTONS %9d \n", reco_constants.TRACE_PHOTONS); + + System.out.format("CCDB RICH PARA REDO_RICH_RECO %9d \n", reco_constants.REDO_RICH_RECO); + System.out.format("CCDB RICH PARA DO_MIRROR_HADS %9d \n", reco_constants.DO_MIRROR_HADS); + System.out.format("CCDB RICH PARA DO_CURVED_AERO %9d \n", reco_constants.DO_CURVED_AERO); + + System.out.format("CCDB RICH PARA USE_ELECTRON_ANGLES %9d \n", reco_constants.USE_ELECTRON_ANGLES); + System.out.format("CCDB RICH PARA USE_PIXEL_PROPERTIES %9d \n", reco_constants.USE_PIXEL_PROPERTIES); + System.out.format("CCDB RICH PARA SAVE_THROWS %9d \n", reco_constants.SAVE_THROWS); + System.out.format("CCDB RICH PARA QUADRANT_NUMBER %9d \n \n", reco_constants.QUADRANT_NUMBER); + + System.out.format("CCDB RICH PARA GOODHIT_FRAC %9.4f \n", reco_constants.GOODHIT_FRAC); + System.out.format("CCDB RICH PARA RICH_DCMATCH_CUT %9.4f \n", reco_constants.RICH_DCMATCH_CUT); + System.out.format("CCDB RICH PARA RICH_HITMATCH_RMS %9.4f \n", reco_constants.RICH_HITMATCH_RMS); + System.out.format("CCDB RICH PARA RICH_DIRECT_RMS %9.4f \n", reco_constants.RICH_DIRECT_RMS); + System.out.format("CCDB RICH PARA SHOW_PROGRESS_INTERVAL %9.4f \n", reco_constants.SHOW_PROGRESS_INTERVAL); + System.out.format("CCDB RICH PARA THROW_ASSOCIATION_CUT %9.4f \n", reco_constants.THROW_ASSOCIATION_CUT); + + System.out.format("CCDB RICH PARA RICH_DEBUG %9.4f \n", reco_constants.RICH_DEBUG); + System.out.format("CCDB RICH PARA RICH_TIME_RMS %9.4f \n", reco_constants.RICH_TIME_RMS); + System.out.format("CCDB RICH PARA MISA_SHIFT_SCALE %9.4f \n", reco_constants.MISA_SHIFT_SCALE); + System.out.format("CCDB RICH PARA MISA_ANGLE_SCALE %9.4f \n", reco_constants.MISA_ANGLE_SCALE); System.out.format(" \n"); } @@ -462,41 +573,37 @@ public void init_GeoConstantsCCDB(IndexedTable paraConstants, IndexedTable aeroC * This comes on top of the RICH survey and global transformation */ - for (int ila=0; ila=1 && reco_constants.RICH_DEBUG>0){ + //System.out.format("QUA QUA %4d %4d %d %d %7.2f %7.2f %7.2f %7.2f %7.2f \n",ila,ico,lla,cco,dx,dy,dz, + // layer_misa_shift[ila][ico].mag(),layer_misa_angle[ila][ico].mag()*reco_constants.MRAD); if(layer_misa_shift[ila][ico].mag()>0 || layer_misa_angle[ila][ico].mag()>0){ System.out.format("CCDB RICH MISA ila %4d ico %3d (%4d %3d) shift %s angle %s \n", lla,cco, ila,ico, layer_misa_shift[ila][ico].toStringBrief(3), layer_misa_angle[ila][ico].toStringBrief(3)); @@ -508,7 +615,7 @@ public void init_GeoConstantsCCDB(IndexedTable paraConstants, IndexedTable aeroC /* - * AEROGEL OPTCIS + * AEROGEL NOMINAL OPTCIS */ int nco[] = {16,22,31,31}; @@ -516,7 +623,19 @@ public void init_GeoConstantsCCDB(IndexedTable paraConstants, IndexedTable aeroC for (int ico=0; ico=1 && reco_constants.RICH_DEBUG>0)System.out.format("CCDB RICH AERO ila %4d ico %3d n = %8.5f pla = %8.2f\n", 201+ila, ico+1, aero_refi[ila][ico], aero_plan[ila][ico]); + if(debugMode>=2 && reco_constants.RICH_DEBUG>0)System.out.format("CCDB RICH AERO ila %4d ico %3d n = %8.5f pla = %8.2f\n", 201+ila, ico+1, aero_refi[ila][ico], aero_plan[ila][ico]); + } + } + + if(debugMode>=2){ + int ndo[] = {16,22,32,32}; + for (int ila=0; ila<4; ila++){ + for (int ico=0; ico=1){ System.out.format("TEXT PARA DO_MISALIGNMENT %7d \n", reco_constants.DO_MISALIGNMENT); @@ -640,6 +766,10 @@ public void init_ConstantsTxT(int flag){ System.out.format("TEXT PARA MISA_SHIFT_SCALE %7.3f \n", reco_constants.MISA_SHIFT_SCALE); System.out.format("TEXT PARA MISA_ANGLE_SCALE %7.3f \n", reco_constants.MISA_ANGLE_SCALE); + System.out.format("TEXT PARA THROW_PHOTON_NUMBER %7d \n", reco_constants.THROW_PHOTON_NUMBER); + + System.out.format("TEXT PARA RICH_DIRECT_RMS %7.3f (mrad) \n", reco_constants.RICH_DIRECT_RMS*1000); + } } @@ -659,12 +789,12 @@ public void init_ConstantsTxT(int flag){ * SINGLE COMPONENT MISALIGNMENT * This comes on top of the RICH survey and global transformation */ - for (int ila=0; ila=0)System.out.format("MISA conversion %4d %3d --> %4d %3d \n",lla,cco,ila,ico); // the rotation is assumed to be in the component local ref system - layer_misa_shift[ila][ico] = new Vector3D( dx*sscale, dy*sscale, dz*sscale); - layer_misa_angle[ila][ico] = new Vector3D(thx*ascale, thy*ascale, thz*ascale); + layer_misa_shift[ila][ico].add( new Vector3D( dx*sscale, dy*sscale, dz*sscale)); + layer_misa_angle[ila][ico].add( new Vector3D(thx*ascale, thy*ascale, thz*ascale)); if(debugMode>=0){ if(layer_misa_shift[ila][ico].mag()>0 || layer_misa_angle[ila][ico].mag()>0){ System.out.format("TXT MISA layer %4d ico %3d (%4d %3d) shift %s angle %s \n", ila,ico,lla,cco, - layer_misa_shift[ila][ico].toStringBrief(2), layer_misa_angle[ila][ico].toStringBrief(2)); + layer_misa_shift[ila][ico].toStringBrief(3), layer_misa_angle[ila][ico].toStringBrief(3)); } } @@ -756,6 +886,64 @@ public void init_ConstantsTxT(int flag){ if(debugMode>=1)System.out.format("initConstants: DONE \n"); } + + if(flag==4){ + + /* + * AEROGEL CALIBRATED OPTICS + */ + + String chele_filename = new String("CALIB_DATA/aerogel_chele.txt"); + + try { + + BufferedReader bf = new BufferedReader(new FileReader(chele_filename)); + String currentLine = null; + + while ( (currentLine = bf.readLine()) != null) { + + String[] array = currentLine.split(" "); + int idlay = Integer.parseInt(array[1]); + int iaer = Integer.parseInt(array[2]); + int iqua = Integer.parseInt(array[3]); + + if(debugMode>=1)System.out.format("Read chele for AERO lay %3d compo %3d quadrant %3d", idlay, iaer, iqua); + + int ndir = Integer.parseInt(array[4]); + float chdir = Float.parseFloat(array[5]); + float sdir = Float.parseFloat(array[6]); + + int nlat = Integer.parseInt(array[7]); + float chlat = Float.parseFloat(array[8]); + float slat = Float.parseFloat(array[9]); + + int nspe = Integer.parseInt(array[10]); + float chspe = Float.parseFloat(array[11]); + float sspe = Float.parseFloat(array[12]); + + aero_chele_dir[idlay-201][iaer-1][iqua] = chdir; + aero_chele_lat[idlay-201][iaer-1][iqua] = chlat; + aero_chele_spe[idlay-201][iaer-1][iqua] = chspe; + + aero_schele_dir[idlay-201][iaer-1][iqua] = sdir; + aero_schele_lat[idlay-201][iaer-1][iqua] = slat; + aero_schele_spe[idlay-201][iaer-1][iqua] = sspe; + + //aero_refi[idlay-201][iaer-1] = (float) RICHConstants.RICH_AEROGEL_INDEX; + if(debugMode>=1)System.out.format(" n = %8.5f pla = %8.2f \n", aero_refi[idlay-201][iaer-1], aero_plan[idlay-201][iaer-1]); + + } + + } catch (Exception e) { + + System.err.format("Exception occurred trying to read '%s' \n", chele_filename); + e.printStackTrace(); + } + + if(debugMode>=1)System.out.format("initConstants: DONE \n"); + + } + } @@ -938,7 +1126,7 @@ public void init_Survey(){ } //------------------------------ - public void init_RICHLayers(){ + public void init_RICHLayers(int iflag){ //------------------------------ // Take RICHFactory Layers of Geant4 volumes (for GEMC) and convert in coatjava Layers // of RICH components accounting for optical descriptiors plus basic tracking @@ -980,6 +1168,9 @@ public void init_RICHLayers(){ } RICHLayer layer = new RICHLayer(ilay, slayer, vlayer); + //if(iflag==0 && (ilay>3 && ilay<12)) continue; + if(iflag==1 || (ilay<4 || ilay==12)) { + for (int ico=0; ico=1)System.out.format("add layer %d \n",ilay); opticlayers.add(layer); + } /* - * Generate the basic planes for tracking + * Generate and misalign the basic planes for tracking */ - generate_TrackingPlanes(); + rich_frame = survey_frame.clone(); + + for (int ilay=0; ilay3 && ilay<12)) continue; + if(debugMode>=1)System.out.format("generate surfaces for layer %d \n",ilay); + + generate_TrackingPlane(ilay); + + if(reco_constants.DO_MISALIGNMENT==1)misalign_TrackingPlane(ilay); + + store_TrackingPlane(ilay); + + } - /* - * Store the composite planes for tracking - */ - store_TrackingPlanes(); - - /* - * Generate Pixel map on the misaligned MAPMT plane - */ + if(iflag>0){ + /* + * Generate Pixel map on the misaligned MAPMT plane + */ + RICHLayer layer = get_Layer("mapmts"); + List compo_list = layer.get_CompoList(); + Shape3D compo_misa = layer.get_TrackingSurf(); + generate_Pixel_Map(layer.get_id(), 0, compo_misa, compo_list); + + if(debugMode>=1)show_Shape3D(compo_misa, null, "CC"); + if(debugMode>=1)show_RICH("Real RICH Geometry", "RR"); + } + + } + + // ---------------- + public void testTraj() { + // ---------------- + + Plane3D pl_mapmt = get_MaPMTforTraj(); + pl_mapmt.show(); + + Point3D pa[] = new Point3D[3]; + for (int ia=0; ia<3; ia++){ + Plane3D pl_aero = get_AeroforTraj(ia); + pl_aero.show(); + pa[ia]=pl_aero.point(); + System.out.format("Ref point %s \n",pa[ia].toStringBrief(2)); + + } + + Point3D IP = new Point3D(0.,0.,0.); + for (int ia=0; ia<3; ia++){ + Line3D lin = new Line3D(IP, pa[ia]); + int iplane = select_AeroforTraj(lin, lin, lin); + System.out.format("For LIN %d select plane %d \n",ia,iplane); + + } + + } + + + //------------------------------ + public Plane3D get_MaPMTforTraj() { + //------------------------------ + RICHLayer layer = get_Layer("mapmts"); - List compo_list = layer.get_CompoList(); - Shape3D compo_misa = layer.get_TrackingSurf(); - generate_Pixel_Map(layer.get_id(), 0, compo_misa, compo_list); + return layer.get_TrajPlane(); - if(debugMode>=1)show_Shape3D(compo_misa, null, "CC"); - if(debugMode>=1)show_RICH("Real RICH Geometry", "RR"); + } + + + //------------------------------ + public Plane3D get_AeroforTraj(int iflag) { + //------------------------------ + + RICHLayer layer = get_Layer("aerogel_2cm_B1"); + if(iflag==1) layer = get_Layer("aerogel_2cm_B2"); + if(iflag==2) layer = get_Layer("aerogel_3cm_L1"); + + return layer.get_TrajPlane(); + + } + + + //------------------------------ + public int select_AeroforTraj(Line3D first, Line3D second, Line3D third) { + //------------------------------ + + RICHIntersection entra = get_Layer("aerogel_2cm_B2").find_Entrance(second, -2); + if(entra!=null) return 1; + + if(entra==null) entra = get_Layer("aerogel_3cm_L1").find_Entrance(third, -2); + if(entra!=null) return 2; + + // return a solution plane in any case + return 0; } @@ -1326,8 +1590,8 @@ public void build_CompoSurfs(RICHLayer layer, Vector3D orient) { compo.set_TrackingSurf(plane); if(debugMode>=1 && plane.size()>0){ - String head = String.format("COMP %3d %3d ",layer.get_id(),ico); System.out.format("Compo %3d %3d Normal %s \n",layer.get_id(),ico,toString(get_Shape3D_Normal(plane))); + String head = String.format("COMP %3d %3d ",layer.get_id(),ico); show_Shape3D(plane, null, head); } } @@ -1444,7 +1708,7 @@ public void misalign_Layer(RICHLayer layer){ Vector3D lshift = layer_misa_shift[ilay+1][0]; Vector3D langle = layer_misa_angle[ilay+1][0]; if(langle.mag()>0 || lshift.mag()>0){ - if(debugMode>=1){System.out.format(" --> asLayer %s %s \n", toString(lshift), toString(langle)); } + if(debugMode>=1){System.out.format(" --> asLayer %d %s %s \n", ilay, toString(lshift), toString(langle)); } if(debugMode>=1)System.out.format(" --> global \n"); misalign_Element( layer.get_GlobalSurf(), lframe, langle, lshift); @@ -1480,63 +1744,57 @@ public void misalign_Layer(RICHLayer layer){ //------------------------------ - public void generate_TrackingPlanes(){ + public void generate_TrackingPlane(int ilay){ //------------------------------ int debugMode = 0; - rich_frame = survey_frame.clone(); - - for (int ilay=0; ilay=1){ - System.out.format("------------------------\n"); - System.out.format("Generate tracking for Layer %d %s view %s \n", ilay, layer.get_Name(), orient.toStringBrief(3)); - System.out.format("------------------------\n"); - } + RICHLayer layer = get_Layer(ilay); + Vector3D orient = layer.get_Vinside(); - /* - * Nominal plane just for reference - */ - layer.set_NominalPlane( generate_Nominal_Plane(ilay, 0) ); + if(debugMode>=1){ + System.out.format("------------------------\n"); + System.out.format("Generate tracking for Layer %d %s view %s \n", ilay, layer.get_Name(), orient.toStringBrief(3)); + System.out.format("------------------------\n"); + } + /* + * Nominal plane just for reference + */ + layer.set_NominalPlane( generate_Nominal_Plane(ilay, 0) ); - /* - * For each component, group faces with normal and position vs barycenter along orient - */ - build_CompoSurfs(layer, orient); - - /* - * Generate a global plane for fast tracking without gaps - * In case of aerogel add the second global face - */ - build_GlobalPlanes(layer, orient); + /* + * For each component, group faces with normal and position vs barycenter along orient + */ + build_CompoSurfs(layer, orient); + + /* + * Generate a global plane for fast tracking without gaps + * In case of aerogel add the second global face + */ + build_GlobalPlanes(layer, orient); - /* - * Select the pivot for the RICH rotations - */ - if(layer.is_mapmt()) { - if(reco_constants.MISA_PMT_PIVOT==1) rich_frame.set_bref(layer.get_SurfBary()); - if(debugMode>=1)System.out.format("RICH PIVOT %s \n",rich_frame.bref().toStringBrief(2)); - } + /* + * Select the pivot for the RICH rotations + */ + if(layer.is_mapmt()) { + if(reco_constants.MISA_PMT_PIVOT==1) rich_frame.set_bref(layer.get_SurfBary()); + if(debugMode>=1)System.out.format("RICH PIVOT %s \n",rich_frame.bref().toStringBrief(2)); + } - /* - * define the spherical surfaces when needed - */ - build_CompoSpheres(layer); - } + /* + * define the spherical surfaces when needed + */ + build_CompoSpheres(layer); } //------------------------------ - public void misalign_TrackingPlanes(){ + public void misalign_TrackingPlane(int ilay){ //------------------------------ int debugMode = 0; @@ -1544,38 +1802,19 @@ public void misalign_TrackingPlanes(){ /* * Apply misalignment around given PIVOT */ - for (int ilay=0; ilay=1){ - System.out.format("------------------------\n"); - System.out.format("Misalign tracking for Layer %d %s\n", ilay, get_Layer(ilay).get_Name()); - System.out.format("------------------------\n"); - } - - RICHLayer layer = get_Layer(ilay); - /* - * Misalign surfs as required - */ - misalign_Layer(layer); - - /* - * Store misalignmed tracking surfaces for fast tracking - */ - //layer.set_TrackingSurf( layer.merge_CompoSurfs()); - //layer.set_CompoList( layer.merge_CompoList()); + if(debugMode>=1){ + System.out.format("------------------------\n"); + System.out.format("Misalign tracking for Layer %d %s\n", ilay, get_Layer(ilay).get_Name()); + System.out.format("------------------------\n"); + } - /* - * Generate Pixel map on the misaligned MAPMT plane - */ - /*if(layer.is_mapmt()) { - List compo_list = layer.get_CompoList(); - Shape3D compo_misa = layer.get_TrackingSurf(); - if(debugMode>=1)show_Shape3D(compo_misa, null, "CC"); - generate_Pixel_Map(ilay, 0, compo_misa, compo_list); - }*/ + RICHLayer layer = get_Layer(ilay); - } + /* + * Misalign surfs as required + */ + misalign_Layer(layer); /* * Check misalignment effect on survey plane @@ -1594,7 +1833,7 @@ public void misalign_TrackingPlanes(){ //------------------------------ - public void store_TrackingPlanes(){ + public void store_TrackingPlane(int ilay){ //------------------------------ int debugMode = 0; @@ -1602,23 +1841,20 @@ public void store_TrackingPlanes(){ /* * Store the composite tracking planes */ - for (int ilay=0; ilay=1){ - System.out.format("------------------------\n"); - System.out.format("Store tracking for Layer %d %s\n", ilay, get_Layer(ilay).get_Name()); - System.out.format("------------------------\n"); - } - RICHLayer layer = get_Layer(ilay); + if(debugMode>=1){ + System.out.format("------------------------\n"); + System.out.format("Store tracking for Layer %d %s\n", ilay, get_Layer(ilay).get_Name()); + System.out.format("------------------------\n"); + } - /* - * Store misalignmed tracking surfaces for fast tracking - */ - layer.set_TrackingSurf( layer.merge_CompoSurfs()); - layer.set_CompoList( layer.merge_CompoList()); + RICHLayer layer = get_Layer(ilay); - } + /* + * Store misalignmed tracking surfaces for fast tracking + */ + layer.set_TrackingSurf( layer.merge_CompoSurfs()); + layer.set_CompoList( layer.merge_CompoList()); } @@ -1879,6 +2115,113 @@ public double get_aerorefi(int ila, int ico){ } + //------------------------------ + public double get_sChElectron(int ila, int ico, int iqua, int irefle) { + //------------------------------ + + if(get_Constants().USE_ELECTRON_ANGLES==1){ + if(irefle==0){ + if(aero_schele_dir[ila][ico][iqua]>0){ + return aero_schele_dir[ila][ico][iqua]; + }else{ + if(aero_schele_lat[ila][ico][iqua]>0){ + return aero_schele_lat[ila][ico][iqua]; + }else{ + return aero_schele_spe[ila][ico][iqua]; + } + } + } + if(irefle==1){ + if(aero_schele_lat[ila][ico][iqua]>0){ + return aero_schele_lat[ila][ico][iqua]; + }else{ + if(aero_schele_dir[ila][ico][iqua]>0){ + return aero_schele_dir[ila][ico][iqua]; + }else{ + return aero_schele_spe[ila][ico][iqua]; + } + } + } + if(irefle==2){ + if(aero_schele_spe[ila][ico][iqua]>0){ + return aero_schele_spe[ila][ico][iqua]; + }else{ + if(aero_schele_dir[ila][ico][iqua]>0){ + return aero_schele_dir[ila][ico][iqua]; + }else{ + return aero_schele_lat[ila][ico][iqua]; + } + } + } + } + return 0.0; + } + + + //------------------------------ + public double get_PixelGain(int ipmt, int ich) { return pixel_gain[ipmt][ich]; } + //------------------------------ + + //------------------------------ + public double get_PixelEff(int ipmt, int ich) { return pixel_eff[ipmt][ich]; } + //------------------------------ + + //------------------------------ + public int get_PixelFlag(int ipmt, int ich) { return pixel_flag[ipmt][ich]; } + //------------------------------ + + //------------------------------ + public double get_PixelMtime(int ipmt, int ich) { return pixel_mtime[ipmt][ich]; } + //------------------------------ + + //------------------------------ + public double get_PixelStime(int ipmt, int ich) { return pixel_stime[ipmt][ich]; } + //------------------------------ + + //------------------------------ + public double get_ChElectron(int ila, int ico, int iqua, int irefle) { + //------------------------------ + + if(get_Constants().USE_ELECTRON_ANGLES==1){ + if(irefle==0){ + if(aero_chele_dir[ila][ico][iqua]>0){ + return aero_chele_dir[ila][ico][iqua]; + }else{ + if(aero_chele_lat[ila][ico][iqua]>0){ + return aero_chele_lat[ila][ico][iqua]; + }else{ + return aero_chele_spe[ila][ico][iqua]; + } + } + } + if(irefle==1){ + if(aero_chele_lat[ila][ico][iqua]>0){ + return aero_chele_lat[ila][ico][iqua]; + }else{ + if(aero_chele_dir[ila][ico][iqua]>0){ + return aero_chele_dir[ila][ico][iqua]; + }else{ + return aero_chele_spe[ila][ico][iqua]; + } + } + } + if(irefle==2){ + if(aero_chele_spe[ila][ico][iqua]>0){ + return aero_chele_spe[ila][ico][iqua]; + }else{ + if(aero_chele_dir[ila][ico][iqua]>0){ + return aero_chele_dir[ila][ico][iqua]; + }else{ + return aero_chele_lat[ila][ico][iqua]; + } + } + } + } + return 0.0; + + } + + //------------------------------ public double getPMTtimeoff(int ipmt, int ich){ //------------------------------ @@ -2093,6 +2436,7 @@ public Point3D toPoint3D(Vector3D vin) { //------------------------------ public Point3D toPoint3D(Vector3d vin) { //------------------------------ + if(vin==null) return null; Point3D pout = new Point3D(vin.x, vin.y, vin.z); return pout; } @@ -2172,8 +2516,12 @@ public void show_RICH(String name, String head){ RICHLayer layer = get_Layer(ilay); if(layer.is_aerogel() || layer.is_mapmt()){ show_Shape3D(layer.get_GlobalSurf(), null, ini); - if(layer.is_aerogel())show_Shape3D(layer.get_TrackingSurf(), null, "AA"); + if(layer.is_aerogel()){ + show_Shape3D(layer.get_TrackingSurf(), null, "AA"); + for(int ico=0; ico RayTrace(Vector3d emission, int orilay, int orico, Vector3d vlab) { + // ---------------- + + int debugMode = 0; + + RICHLayer layer = get_Layer(orilay); + if(debugMode>=1)System.out.format("Raytrace gets refractive index from CCDB database %8.5f \n",layer.get(orico).get_index()); + return RayTrace(emission, orilay, orico, vlab, layer.get(orico).get_index()); + + } + + // ---------------- + public ArrayList RayTrace(Vector3d emission, int orilay, int orico, Vector3d vlab, double naero) { // ---------------- // return the hit position on the PMT plane of a photon emitted at emission with direction vlab @@ -2793,7 +3152,14 @@ public ArrayList RayTrace(Vector3d emission, int orilay, int orico, Vec Point3D new_pos = first_intersection.get_pos(); RICHRay oriray = new RICHRay(emi, new_pos); - oriray.set_refind(layer.get(orico).get_index()); + + /* rewrite the refractive index to be consistent with photon theta + only valid for initial aerogel + the rest of components take ref index from CCDB database + */ + //oriray.set_refind(layer.get(orico).get_index()); + first_intersection.set_nin((float) naero); + oriray.set_refind(naero); raytracks.add(oriray); RICHRay rayin = new RICHRay(new_pos, oriray.direction().multiply(200)); diff --git a/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHio.java b/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHio.java index a376a3b2a0..07380ec5da 100644 --- a/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHio.java +++ b/reconstruction/rich/src/main/java/org/jlab/rec/rich/RICHio.java @@ -8,11 +8,14 @@ import org.jlab.io.base.DataEvent; import org.jlab.clas.detector.DetectorResponse; + public class RICHio { /* * RICH i/o */ + private static double RAD = 180./Math.PI; + private static double MRAD = 1000; // constructor // ---------------- @@ -40,10 +43,6 @@ public void clear_Banks(DataEvent event) { event.removeBank("RICH::response"); if(debugMode==1)System.out.format("Remove RICH::response from event \n"); } - if(event.hasBank("RICH::ringCher")){ - event.removeBank("RICH::ringCher"); - if(debugMode==1)System.out.format("Remove RICH::ringCher from event \n"); - } if(event.hasBank("RICH::hadrons")){ event.removeBank("RICH::hadrons"); if(debugMode==1)System.out.format("Remove RICH::hadrons from event \n"); @@ -52,6 +51,14 @@ public void clear_Banks(DataEvent event) { event.removeBank("RICH::photons"); if(debugMode==1)System.out.format("Remove RICH::photons from event \n"); } + if(event.hasBank("RICH::ringCher")){ + event.removeBank("RICH::ringCher"); + if(debugMode==1)System.out.format("Remove RICH::ringCher from event \n"); + } + if(event.hasBank("RICH::hadCher")){ + event.removeBank("RICH::hadCher"); + if(debugMode==1)System.out.format("Remove RICH::hadCher from event \n"); + } } @@ -93,10 +100,12 @@ public void write_CherenkovBanks(DataEvent event, RICHEvent richevent, RICHConst if(richevent.get_nHad()>0)write_HadronBank(event, richevent); - if(richevent.get_nPho()>0)write_PhotonBank(event, richevent); + if(richevent.get_nPho()>0)write_PhotonBank(event, richevent, recopar); if(richevent.get_nPho()>0)write_RingCherBank(event, richevent, recopar); + if(richevent.get_nHad()>0)write_HadCherBank(event, richevent, recopar); + } @@ -214,6 +223,7 @@ public void write_HadronBank(DataEvent event, RICHEvent richevent) { bankHads.setFloat("traced_hitz", i, (float) had.meas_hit.z); bankHads.setFloat("traced_time", i, (float) had.traced.get_time()); bankHads.setFloat("traced_path", i, (float) had.traced.get_path()); + //bankHads.setFloat("traced_mchi2", i, (float) had.traced.get_machi2()); bankHads.setShort("traced_ilay", i, (short) had.ilay_emission); bankHads.setShort("traced_ico", i, (short) had.ico_emission); @@ -221,13 +231,76 @@ public void write_HadronBank(DataEvent event, RICHEvent richevent) { bankHads.setFloat("traced_emiy", i, (float) had.lab_emission.y); bankHads.setFloat("traced_emiz", i, (float) had.lab_emission.z); - bankHads.setFloat("EtaC_ele", i, (float) had.get_changle(0)); - bankHads.setFloat("EtaC_pi", i, (float) had.get_changle(1)); - bankHads.setFloat("EtaC_k", i, (float) had.get_changle(2)); - bankHads.setFloat("EtaC_pr", i, (float) had.get_changle(3)); - bankHads.setFloat("EtaC_min", i, (float) had.minChAngle()); - bankHads.setFloat("EtaC_max", i, (float) had.maxChAngle()); + bankHads.setFloat("EtaC_ele", i, (float) had.get_changle(0,0)); + bankHads.setFloat("EtaC_pi", i, (float) had.get_changle(1,0)); + bankHads.setFloat("EtaC_k", i, (float) had.get_changle(2,0)); + bankHads.setFloat("EtaC_pr", i, (float) had.get_changle(3,0)); + bankHads.setFloat("EtaC_min", i, (float) had.minChAngle(0)); + bankHads.setFloat("EtaC_max", i, (float) had.maxChAngle(0)); + + } + event.appendBanks(bankHads); + } + + } + + // ---------------- + public void write_HadCherBank(DataEvent event, RICHEvent richevent, RICHConstants recopar) { + // ---------------- + + int debugMode = 0; + + int NHAD = richevent.get_nHad(); + if(debugMode>=1)System.out.format("Creating Bank for %5d Hadrons \n", NHAD); + + if(NHAD>0) { + if(debugMode>=1)System.out.println(" --> Creating the RICH::hadCher Bank "); + DataBank bankHads = event.createBank("RICH::hadCher", NHAD); + if(bankHads==null){ + System.out.println("ERROR CREATING BANK : RICH::hadCher"); + return; + } + + for(int i = 0; i < NHAD; i++){ + RICHParticle had = richevent.get_Hadron(i); + double dT_max = recopar.RICH_TIME_RMS*3; + + if(debugMode>0)System.out.format(" RICHio %7.2f %7.2f %5d %7.2f %9.4f %9.4f \n",had.minChAngle(0)*MRAD,had.maxChAngle(0)*MRAD, + had.traced.get_BestH(),had.traced.get_RQP(),had.traced.get_ElProb(),had.traced.get_PiProb()); + + if(had.get_id()>255)continue; + if(had.get_hit_index()>255)continue; + if(had.get_ParentIndex()>255)continue; + if(had.ilay_emission>255)continue; + if(had.ico_emission>255)continue; + if(had.ico_entrance>255)continue; + if(had.iqua_emission>255)continue; + if(had.traced.get_BestH()>255)continue; + + bankHads.setByte("id", i ,(byte) had.get_id()); + bankHads.setByte("hindex", i, (byte) had.get_hit_index()); + bankHads.setByte("pindex", i, (byte) had.get_ParentIndex()); + + bankHads.setByte("emilay", i, (byte) had.ilay_emission); + bankHads.setByte("emico", i, (byte) had.ico_emission); + bankHads.setByte("enico", i, (byte) had.ico_entrance); + bankHads.setShort("emqua", i, (short) had.iqua_emission); + bankHads.setFloat("mchi2", i, (float) had.traced.get_machi2()); + + bankHads.setFloat("ch_min", i, (float) had.minChAngle(0)); + bankHads.setFloat("ch_max", i, (float) had.maxChAngle(0)); + bankHads.setFloat("dt_max", i, (float) dT_max); + bankHads.setFloat("ch_dir", i, (float) had.traced.get_Chdir()); + bankHads.setFloat("ch_lat", i, (float) had.traced.get_Chlat()); + bankHads.setFloat("ch_spe", i, (float) had.traced.get_Chspe()); + + bankHads.setByte("best_PID", i, (byte) had.traced.get_BestH()); + bankHads.setFloat("RQ_prob", i, (float) had.traced.get_RQP()); + bankHads.setFloat("el_prob", i, (float) had.traced.get_ElProb()); + bankHads.setFloat("pi_prob", i, (float) had.traced.get_PiProb()); + bankHads.setFloat("k_prob", i, (float) had.traced.get_KProb()); + bankHads.setFloat("pr_prob", i, (float) had.traced.get_PrProb()); } event.appendBanks(bankHads); } @@ -240,21 +313,37 @@ public void write_RingCherBank(DataEvent event, RICHEvent richevent, RICHConstan int debugMode = 0; + int SELE = 2; + int NPHO = richevent.get_nPho(); if(debugMode>=1)System.out.format("Creating Bank for %5d Ring Cherenkovs \n", NPHO); if(NPHO!=0) { - if(debugMode>=1)System.out.println(" --> Creating the RICH::ringCher Bank "); - DataBank bankRing = event.createBank("RICH::ringCher", NPHO); + + int Nring = 0; + + for(int i = 0; i < NPHO; i++){ + RICHParticle pho = richevent.get_Photon(i); + if(pho.get_type()!=0) continue; + if(pho.analytic.get_OK()==SELE || pho.traced.get_OK()==SELE) Nring++; + } + + if(debugMode>=1)System.out.format(" --> Creating the RICH::ringCher Bank for Npho %5d Nring %5d \n",NPHO,Nring); + DataBank bankRing = event.createBank("RICH::ringCher", Nring); if(bankRing==null){ System.out.println("ERROR CREATING BANK : RICH::ringCher"); return; } + + int ientry = 0; for(int i = 0; i < NPHO; i++){ RICHParticle pho = richevent.get_Photon(i); + // consistency + if(ientry>Nring) continue; + // only reconstructed photons if(pho.get_type()!=0) continue; @@ -264,32 +353,44 @@ public void write_RingCherBank(DataEvent event, RICHEvent richevent, RICHConstan double htime = hit.get_time(); double a_time = pho.get_start_time() + pho.analytic.get_time(); double t_time = pho.get_start_time() + pho.traced.get_time(); - double chmi = had.minChAngle(); - double chma = had.maxChAngle(); - double dtma = recopar.RICH_TIME_RMS*3; double a_etaC = pho.analytic.get_EtaC(); double t_etaC = pho.traced.get_EtaC(); + if(debugMode>=1)System.out.format(" pho %3d %3d flag %3d %3d ",i,ientry,pho.analytic.get_OK(),pho.traced.get_OK()); // skip no real Cherenkov solution - if((a_etaCchma) && (t_etaCchma)) continue; - if(Math.abs(a_time-htime)>dtma && Math.abs(t_time-htime)>dtma) continue; + if(pho.analytic.get_OK()==SELE || pho.traced.get_OK()==SELE){ + + if(had.get_ParentIndex()>255)continue; + if(hit.get_anode()>255)continue; + if(pho.traced.get_nrefle()>255)continue; + + if(debugMode>=1)System.out.format(" --> store \n"); + + bankRing.setShort("id", ientry, (short) pho.get_id()); + bankRing.setShort("hindex", ientry, (short) pho.get_hit_index()); + bankRing.setByte("pindex", ientry, (byte) had.get_ParentIndex()); - bankRing.setShort("id", i, (short) pho.get_id()); - bankRing.setShort("hindex", i, (short) pho.get_hit_index()); - bankRing.setShort("pindex", i, (short) had.get_ParentIndex()); + bankRing.setShort("pmt", ientry, (short) hit.get_pmt()); + bankRing.setByte("anode", ientry, (byte) hit.get_anode()); + bankRing.setFloat("time", ientry, (float) htime); - bankRing.setFloat("time", i, (float) htime); - bankRing.setShort("pmt", i, (short) hit.get_pmt()); - bankRing.setShort("anode", i, (short) hit.get_anode()); + bankRing.setFloat("apath", ientry, (float) pho.analytic.get_path()); + bankRing.setFloat("atime", ientry, (float) a_time ); + bankRing.setFloat("aEtaC", ientry, (float) a_etaC ); - bankRing.setFloat("apath", i, (float) pho.analytic.get_path()); - bankRing.setFloat("atime", i, (float) a_time ); - bankRing.setFloat("aEtaC", i, (float) a_etaC ); + bankRing.setFloat("tpath", ientry, (float) pho.traced.get_path()); + bankRing.setFloat("ttime", ientry, (float) t_time ); + bankRing.setFloat("tEtaC", ientry, (float) t_etaC ); - bankRing.setFloat("tpath", i, (float) pho.traced.get_path()); - bankRing.setFloat("ttime", i, (float) t_time ); - bankRing.setFloat("tEtaC", i, (float) t_etaC ); + bankRing.setByte("nrfl", ientry, (byte) pho.traced.get_nrefle()); + bankRing.setShort("1rfl", ientry, (short) pho.traced.get_FirstRefle()); + + ientry++; + + }else{ + if(debugMode>=1)System.out.format(" \n"); + } } event.appendBanks(bankRing); @@ -298,7 +399,7 @@ public void write_RingCherBank(DataEvent event, RICHEvent richevent, RICHConstan // ---------------- - public void write_PhotonBank(DataEvent event, RICHEvent richevent) { + public void write_PhotonBank(DataEvent event, RICHEvent richevent, RICHConstants recopar) { // ---------------- int debugMode = 0; @@ -307,56 +408,80 @@ public void write_PhotonBank(DataEvent event, RICHEvent richevent) { if(debugMode>=1)System.out.format("Creating Bank for %5d Photons \n", NPHO); if(NPHO!=0) { - if(debugMode>=1)System.out.println(" --> Creating the Photons Bank "); - DataBank bankPhos = event.createBank("RICH::photons", NPHO); + + int Nrow = 0; + + for(int i = 0; i < NPHO; i++){ + RICHParticle pho = richevent.get_Photon(i); + if(pho.get_type()==0 || recopar.SAVE_THROWS==1)Nrow++; + } + + if(debugMode>=1)System.out.format(" --> Creating the Photons Bank for Npho %4d Nrow %4d \n",NPHO,Nrow); + DataBank bankPhos = event.createBank("RICH::photons", Nrow); if(bankPhos==null){ System.out.println("ERROR CREATING BANK : RICH::photons"); return; } + int ientry = 0; + for(int i = 0; i < NPHO; i++){ RICHParticle pho = richevent.get_Photon(i); - - bankPhos.setShort("id",i, (short) pho.get_id()); - bankPhos.setShort("type",i, (short) pho.get_type()); - bankPhos.setShort("hit_index",i,(short) pho.get_hit_index()); - bankPhos.setShort("hadron_index",i,(short) pho.get_ParentIndex()); - bankPhos.setFloat("start_time",i,(float) pho.get_start_time()); - - bankPhos.setFloat("analytic_the",i,(float) pho.analytic.get_theta()); - bankPhos.setFloat("analytic_phi",i,(float) pho.analytic.get_phi()); - bankPhos.setFloat("analytic_path",i,(float) pho.analytic.get_path()); - bankPhos.setFloat("analytic_time",i,(float) pho.analytic.get_time()); - //bankPhos.setShort("analytic_nrfl",i,(short) pho.analytic.get_nrefle()); - //bankPhos.setShort("analytic_nrfr",i,(short) pho.analytic.get_nrefra()); - - bankPhos.setFloat("analytic_EtaC",i,(float) pho.analytic.get_EtaC()); - bankPhos.setFloat("analytic_aeron",i,(float) pho.analytic.get_aeron()); - bankPhos.setFloat("analytic_elpr",i,(float) pho.analytic.get_elprob()); - bankPhos.setFloat("analytic_pipr",i,(float) pho.analytic.get_piprob()); - bankPhos.setFloat("analytic_kpr",i,(float) pho.analytic.get_kprob()); - bankPhos.setFloat("analytic_prpr",i,(float) pho.analytic.get_prprob()); - bankPhos.setFloat("analytic_bgpr",i,(float) pho.analytic.get_bgprob()); - - bankPhos.setFloat("traced_the",i,(float) pho.traced.get_theta()); - bankPhos.setFloat("traced_phi",i,(float) pho.traced.get_phi()); - bankPhos.setFloat("traced_hitx",i,(float) pho.traced.get_hit().x); - bankPhos.setFloat("traced_hity",i,(float) pho.traced.get_hit().y); - bankPhos.setFloat("traced_hitz",i,(float) pho.traced.get_hit().z); - bankPhos.setFloat("traced_path",i,(float) pho.traced.get_path()); - bankPhos.setFloat("traced_time",i,(float) pho.traced.get_time()); - bankPhos.setShort("traced_nrfl",i,(short) pho.traced.get_nrefle()); - bankPhos.setShort("traced_nrfr",i,(short) pho.traced.get_nrefra()); - bankPhos.setShort("traced_1rfl",i,(short) pho.traced.get_firstrefle()); - - bankPhos.setFloat("traced_EtaC",i,(float) pho.traced.get_EtaC()); - bankPhos.setFloat("traced_aeron",i,(float) pho.traced.get_aeron()); - bankPhos.setFloat("traced_elpr",i,(float) pho.traced.get_elprob()); - bankPhos.setFloat("traced_pipr",i,(float) pho.traced.get_piprob()); - bankPhos.setFloat("traced_kpr",i,(float) pho.traced.get_kprob()); - bankPhos.setFloat("traced_prpr",i,(float) pho.traced.get_prprob()); - bankPhos.setFloat("traced_bgpr",i,(float) pho.traced.get_bgprob()); + if(debugMode>=1)System.out.format(" pho %3d %3d type %3d %3d ",i,ientry,pho.get_type(),pho.get_ParentIndex()); + + // consistency + if(ientry>Nrow) continue; + + if(pho.get_type()==0 || recopar.SAVE_THROWS==1){ + + if(debugMode>=1)System.out.format(" --> store \n"); + + bankPhos.setShort("id", ientry, (short) pho.get_id()); + bankPhos.setShort("type", ientry, (short) pho.get_type()); + bankPhos.setShort("hit_index", ientry,(short) pho.get_hit_index()); + bankPhos.setShort("hadron_index", ientry,(short) pho.get_ParentIndex()); + bankPhos.setFloat("start_time", ientry,(float) pho.get_start_time()); + + bankPhos.setFloat("analytic_the", ientry,(float) pho.analytic.get_theta()); + bankPhos.setFloat("analytic_phi", ientry,(float) pho.analytic.get_phi()); + bankPhos.setFloat("analytic_path", ientry,(float) pho.analytic.get_path()); + bankPhos.setFloat("analytic_time", ientry,(float) pho.analytic.get_time()); + //bankPhos.setShort("analytic_nrfl",ientry,(short) pho.analytic.get_nrefle()); + //bankPhos.setShort("analytic_nrfr",ientry,(short) pho.analytic.get_nrefra()); + + bankPhos.setFloat("analytic_EtaC", ientry,(float) pho.analytic.get_EtaC()); + bankPhos.setFloat("analytic_aeron", ientry,(float) pho.analytic.get_aeron()); + bankPhos.setFloat("analytic_elpr", ientry,(float) pho.analytic.get_ElProb()); + bankPhos.setFloat("analytic_pipr", ientry,(float) pho.analytic.get_PiProb()); + bankPhos.setFloat("analytic_kpr", ientry,(float) pho.analytic.get_KProb()); + bankPhos.setFloat("analytic_prpr", ientry,(float) pho.analytic.get_PrProb()); + bankPhos.setFloat("analytic_bgpr", ientry,(float) pho.analytic.get_BgProb()); + + bankPhos.setFloat("traced_the", ientry,(float) pho.traced.get_theta()); + bankPhos.setFloat("traced_phi", ientry,(float) pho.traced.get_phi()); + bankPhos.setFloat("traced_hitx", ientry,(float) pho.traced.get_hit().x); + bankPhos.setFloat("traced_hity", ientry,(float) pho.traced.get_hit().y); + bankPhos.setFloat("traced_hitz", ientry,(float) pho.traced.get_hit().z); + bankPhos.setFloat("traced_path", ientry,(float) pho.traced.get_path()); + bankPhos.setFloat("traced_time", ientry,(float) pho.traced.get_time()); + bankPhos.setShort("traced_nrfl", ientry,(short) pho.traced.get_nrefle()); + bankPhos.setShort("traced_nrfr", ientry,(short) pho.traced.get_nrefra()); + bankPhos.setShort("traced_1rfl", ientry,(short) pho.traced.get_FirstRefle()); + + bankPhos.setFloat("traced_EtaC", ientry,(float) pho.traced.get_EtaC()); + bankPhos.setFloat("traced_aeron", ientry,(float) pho.traced.get_aeron()); + bankPhos.setFloat("traced_elpr", ientry,(float) pho.traced.get_ElProb()); + bankPhos.setFloat("traced_pipr", ientry,(float) pho.traced.get_PiProb()); + bankPhos.setFloat("traced_kpr", ientry,(float) pho.traced.get_KProb()); + bankPhos.setFloat("traced_prpr", ientry,(float) pho.traced.get_PrProb()); + bankPhos.setFloat("traced_bgpr", ientry,(float) pho.traced.get_BgProb()); + + ientry++; + + }else{ + if(debugMode>=1)System.out.format(" \n"); + } } event.appendBanks(bankPhos); diff --git a/reconstruction/rtpc/README.md b/reconstruction/rtpc/README.md new file mode 100644 index 0000000000..af61df8ec2 --- /dev/null +++ b/reconstruction/rtpc/README.md @@ -0,0 +1 @@ +# RTPC-Tracking-Software diff --git a/reconstruction/rtpc/pom.xml b/reconstruction/rtpc/pom.xml new file mode 100644 index 0000000000..915f7457bc --- /dev/null +++ b/reconstruction/rtpc/pom.xml @@ -0,0 +1,75 @@ + + + 4.0.0 + + org.jlab.clas12.detector + clas12detector-rtpc + 1.0-SNAPSHOT + jar + + + org.jlab.clas + clas12rec + ../../parent/pom.xml + 6.5.3-SNAPSHOT + + + + + clas12maven + https://clasweb.jlab.org/clas12maven + + + + + + + org.jlab.coda + jclara + 4.3-SNAPSHOT + + + + org.jlab.clas + clas-reco + 6.5.3-SNAPSHOT + + + + org.jlab.clas + clas-analysis + 6.5.3-SNAPSHOT + + + + + + + org.apache.maven.plugins + maven-site-plugin + 3.7.1 + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 3.0.0 + + + + + + + org.codehaus.mojo + findbugs-maven-plugin + + + + + + 1.8 + 1.8 + + + diff --git a/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/Geometry.java b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/Geometry.java new file mode 100644 index 0000000000..9652c3b283 --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/Geometry.java @@ -0,0 +1,20 @@ +package org.jlab.rec.rtpc; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.PrintWriter; + +/*import org.jMath.Vector.threeVec; + +import trackfitter.surface.Line; +import trackfitter.track.Helix;*/ + +public class Geometry { + + public Geometry() { + + } + + + +} diff --git a/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/banks/HitReader.java b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/banks/HitReader.java new file mode 100644 index 0000000000..f0ce9fd8f3 --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/banks/HitReader.java @@ -0,0 +1,112 @@ +package org.jlab.rec.rtpc.banks; + +import java.util.ArrayList; +import java.util.List; + +import org.jlab.io.base.DataBank; +import org.jlab.io.base.DataEvent; + +import org.jlab.rec.rtpc.hit.Hit; +/** + * @author payette + * + */ +public class HitReader { + + private List _Hits; + + /** + * + * @return a list of RTPC hits + */ + public List get_RTPCHits() { + return _Hits; + } + + /** + * sets the list of RTPC hits + * @param RTPCHits list of RTPC hits + */ + public void set_RTPCHits(List RTPCHits) { + this._Hits = RTPCHits; + } + + + + + /** + * reads the hits using clas-io methods to get the EvioBank for the RTPC and fill the values to instanciate the RTPChit and MChit classes. + * This methods fills the RTPChit and MChit list of hits. If the data is not MC, the MChit list remains empty + * @param event DataEvent + */ + public void fetch_RTPCHits(DataEvent event, boolean simulation, boolean cosmic) { + + List hits = new ArrayList<>(); + + DataBank bankDGTZ = null; + if(event.hasBank("RTPC::adc")==true) + bankDGTZ=event.getBank("RTPC::adc"); + DataBank bankTrue = null; + if(simulation){ + if(event.hasBank("MC::True")==true) + bankTrue=event.getBank("MC::True"); + if(bankDGTZ==null || bankTrue==null) + return ; + }else{ + if(bankDGTZ==null) return; + } + int rows = bankDGTZ.rows(); + + + int[] hitnb = new int[rows]; + int[] cellID = new int[rows]; + double[] Time = new double[rows]; + double[] posX = new double[rows]; + double[] posY = new double[rows]; + double[] posZ = new double[rows]; + double[] Edep = new double[rows]; + int layer = 0; + int component = 0; + int[] tid = new int[rows]; + + + for(int i = 0; i 12000 || component < 0 || layer < 0)// || tid[i] != 2) + { + Time[i] = 0; + Edep[i] = 0; + posX[i] = 0; + posY[i] = 0; + posZ[i] = 0; + } + + Hit hit = new Hit(1, cellID[i], 1, Time[i]); + if(cosmic){ + Edep[i] -= 256; + if(Edep[i] < 0) Edep[i] = 0; + } + hit.set_EdepTrue(Edep[i]); + hit.set_Time(Time[i]); + + hits.add(hit); + } + + this.set_RTPCHits(hits); + + } + + private int get_cellid(int row, int col){ + return (row-1)*96 + col; + } + +} diff --git a/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/banks/RecoBankWriter.java b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/banks/RecoBankWriter.java new file mode 100644 index 0000000000..3bbcc1ac7b --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/banks/RecoBankWriter.java @@ -0,0 +1,99 @@ +package org.jlab.rec.rtpc.banks; + +import org.jlab.io.base.DataBank; +import org.jlab.io.base.DataEvent; +import org.jlab.rec.rtpc.hit.HitParameters; +import org.jlab.rec.rtpc.hit.RecoHitVector; +import java.util.List; +import java.util.HashMap; +import org.jlab.rec.rtpc.hit.FinalTrackInfo; + +public class RecoBankWriter { + + /** + * + * @param hitlist the list of hits that are of the type Hit. + * @return hits bank + * + */ + public DataBank fillRTPCHitsBank(DataEvent event, HitParameters params) { + + int listsize = 0; + int row = 0; + HashMap> recotrackmap = params.get_recotrackmap(); + + for(int TID : recotrackmap.keySet()) { + for(int i = 0; i < recotrackmap.get(TID).size(); i++) { + listsize++; + } + } + + DataBank bank = event.createBank("RTPC::hits", listsize); + + + if (bank == null) { + System.err.println("COULD NOT CREATE A BANK!!!!!!"); + return null; + } + + for(int TID : recotrackmap.keySet()) { + for(int i = 0; i < recotrackmap.get(TID).size(); i++) { + int cellID = recotrackmap.get(TID).get(i).pad(); + double x_rec = recotrackmap.get(TID).get(i).x(); + double y_rec = recotrackmap.get(TID).get(i).y(); + double z_rec = recotrackmap.get(TID).get(i).z(); + double time = recotrackmap.get(TID).get(i).time(); + double tdiff = recotrackmap.get(TID).get(i).dt(); + + bank.setInt("trkID", row, TID); + bank.setInt("id", row, cellID); + bank.setFloat("time", row, (float) time); + bank.setFloat("x", row, (float) x_rec); + bank.setFloat("y", row, (float) y_rec); + bank.setFloat("z", row, (float) z_rec); + bank.setFloat("tdiff", row, (float) tdiff); + + row++; + } + } + //bank.show(); + return bank; + } + + public DataBank fillRTPCTrackBank(DataEvent event, HitParameters params) { + + HashMap finaltrackinfomap = params.get_finaltrackinfomap(); + int listsize = finaltrackinfomap.size(); + if(listsize == 0) return null; + if(finaltrackinfomap.size() == 0) return null; + int row = 0; + + + DataBank bank = event.createBank("RTPC::tracks", listsize); + + + if (bank == null) { + System.err.println("COULD NOT CREATE A BANK!!!!!!"); + return null; + } + + for(int TID : finaltrackinfomap.keySet()) { + + bank.setInt("trkID", row, TID); + bank.setFloat("px", row, (float) finaltrackinfomap.get(TID).get_px()/1000); + bank.setFloat("py", row, (float) finaltrackinfomap.get(TID).get_py()/1000); + bank.setFloat("pz", row, (float) finaltrackinfomap.get(TID).get_pz()/1000); + bank.setFloat("vz", row, (float) finaltrackinfomap.get(TID).get_vz()/10); + bank.setFloat("theta", row, (float) finaltrackinfomap.get(TID).get_theta()); + bank.setFloat("phi", row, (float) finaltrackinfomap.get(TID).get_phi()); + bank.setInt("nhits", row, finaltrackinfomap.get(TID).get_numhits()); + bank.setFloat("path", row, (float) finaltrackinfomap.get(TID).get_tl()); + bank.setFloat("dedx", row, (float) finaltrackinfomap.get(TID).get_dEdx()); + + row++; + //bank.show(); + } + + return bank; + } +} \ No newline at end of file diff --git a/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/banks/package.html b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/banks/package.html new file mode 100644 index 0000000000..61a4c9b57d --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/banks/package.html @@ -0,0 +1,14 @@ + + + + + +org.jlab.rec.rtpc.banks + + +
Author:
ziegler
+ + \ No newline at end of file diff --git a/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/ADCMap.java b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/ADCMap.java new file mode 100644 index 0000000000..532413831a --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/ADCMap.java @@ -0,0 +1,99 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.jlab.rec.rtpc.hit; + +import java.util.HashMap; + +/** + * + * @author davidpayette + */ +public class ADCMap { + + private HashMap _ADCMap; + private HashMap _intADCMap; + + final private int TrigWindSize = 10000; + final private int SignalStepSize = 10; + + public ADCMap(){ + _ADCMap = new HashMap<>(); + _intADCMap = new HashMap<>(); + + } + + public void simulateSignal(int Pad, double time, double Edep){ + if(!_ADCMap.containsKey(Pad)){ + _ADCMap.put(Pad, new double[TrigWindSize]); + } + for(int tbin=0;tbin0){ + integral+=0.5*(getSignal(pad,tbin-SignalStepSize)+getSignal(pad,tbin))*SignalStepSize; + } + if(tbin%BinSize==0 && tbin>0){ // integration over BinSize + if(tbin%(BinSize*NBinKept)==0){ // one BinSize over NBinKept is read out + if(!_intADCMap.containsKey(pad)){ + _intADCMap.put(pad, new double[TrigWindSize]); + } + _intADCMap.get(pad)[tbin] = integral; + } + integral=0; + } + } + } + + public double getADC(int Pad, int Time){ + return _intADCMap.get(Pad)[Time]; + } + + public HashMap getADCMap(){ + return _intADCMap; + } + + private double getSignal(int pad, int time){ + return _ADCMap.get(pad)[time]; + } + + public void addSignal(int pad, int time, double edep){ + if(!_intADCMap.containsKey(pad)){ + _intADCMap.put(pad, new double[TrigWindSize]); + } + _intADCMap.get(pad)[time] = edep; + } + + private double getSignalAtBin(double tsignal, double t, double edep){ + + double signal_height; + //t = noise_elec(t); // change t to simulate the electronics noise, also modifies the amplitude + double p0 = 0.0; + double p2 = 178.158; + double p3 = 165.637; + double p4 = 165.165; + + if(t= k) { ind = (i*i-i)/2 + k; r[i-1] += a[ind-1]*v[k-1];} + else { ind = (k*k-k)/2 + i; r[i-1] += a[ind-1]*v[k-1];} + } + } + + } // End of void rwsmav(...) + + void rwsmin(double v[], double b[], int n, int m, int nrank) + { + // Author: V. Blobel + + // Obtain solution of linear equations V*X = B with symmetric matrix V + // and inverse (for m=1) or matrix inversion only (for m=0). + + // V = Symmetric n-by-n matrix in symmetric storage mode + // V(1) = V11, V(2) = V12, V(3) = V22, V(4) = V13, ... + // replaced by inverse matrix + // B = n-vector (for m=0 use a dummy argument) + // replaced by a solution vector + // m = see above + + // Method of solution is by elimination selecting the pivot point on the + // diagonal each stage. The rank of the matrix is returned in nrank. + + // For nrank != n, all remaining rows and columns of the resulting matrix + // V and the corresponding elements of B are set to zero. + + + double EPSS = (double)1.0E-6; + + int i, ii, ni, k=0, kk, j, jj, jl, jk, lk, l, ij; + double vkk, d, e; /* variable 'c' in original fortran file is not used */ + double[][] dr = new double[2][200]; + + // -------- Construct table ----------- + for(i=1; i<=n; i++) dr[0][i-1] = 1; + ni = n; + ii = 0; + for(i=1; i<=n; i++) { ii += i; dr[1][i-1] = Math.abs(v[ii-1]); } + + + // --------- Loop begins ---------- + nrank = n - ni; + + for (i=1; i<=ni; i++) + { + // --- Search for pivot and test for linearity and zero matrix + k = kk = jj = 0; vkk = 0; + for (j=1; j<=n; j++) + { + jj += j; + if (dr[0][j-1] == 0) break; + if (Math.abs(v[jj-1]) <= vkk) break; + if (Math.abs(v[jj-1]) < EPSS*dr[1][j-1]) break; + vkk = Math.abs(v[jj-1]); + k=j; kk=jj; + } + if (k == 0) {break;} + + // --- Preparation for elimination --- + nrank = nrank + 1; + dr[0][k-1] = 0; + d = 1/v[kk-1]; + v[kk-1] = -d; + if (m == 1) b[k-1] *= d; + jk = kk-k; + jl = 0; + + // --- Elimination --- + for (j=1; j<=n; j++) + { + if( j-k < 0 ) jk++; + else { + if ( j-k == 0) {jk = kk; jl += j; break;} + else jk = jk +j -1; + } + + + e = v[jk-1]; + v[jk-1] = d*e; + + if (m==1) b[j-1] -= b[k-1]*e; + lk = kk-k; + for (l=1; l<=j; l++) + { + jl++; + if(l-k < 0) lk++; + else { if (l==k) {lk=kk; break;} + else lk=lk + l - 1; + } + + v[jl-1] -= v[lk-1]*e; + } + } // End of loop over j + } // End of loop over i + + if(k != 0) { + // ----------- Change sign -------------- + ij=0; + for (i=1; i<=n; i++) { + for (j=1; j<=i; j++) + { + ij++; v[ij-1] = -v[ij-1]; + } + } + return; + + } + // --------- Clear rest of the matrix ------------- + + ij=0; + for (i=1; i<=n; i++) + { + if(m == 1 && dr[0][i-1] != 0) b[i-1]=0; + for (j=1; j<=i; j++) + { + ij++; + if (dr[0][i-1] + dr[0][j-1] != 0) v[ij-1]=0; + v[ij-1] = -v[ij-1]; + } + } + + return; + } // End of void rwsmin(double v[], double b[], int n, int m, int* nrank + + + + + //------------------------------------------------------------------------- + void rwfthc(int npt, double rf[], + double pf[], double wfi[], + double zf[], double wzf[], + int iopt, + + double vv0[], double ee0[], double ch2ph, double ch2z, + double del[], double delz[]) + + + // ----- Function for fast helix fit. ----- + + // A generalization of the TFTHEL routine to allow it to be called from a + // routine that contains any list of x and y values xf,yf for a set of npt + // points to be fitted. + + // ----- Input: ----- + + // npt: Number of 3-D points to be fit + // xf[]: Array of X-values of points to be fit + // yf[]: Array of Y-values of points to be fit + // rf[]: Array of R-values of points to be fit + // pf[]: Array of PHI-values of points to be fit + // wfi[]: Array of 1/(sig(rphi))**2 for each point + // zf[]: Array of Z-values of points to be fit + // wzf[]: Array of 1/(sig(z))**2 for each point + // iopt: 0 -> Distance**2 =x**2 +y**2 minimized; + // 1 -> Weighted with 1/SIMA(R*PHI)**2 + // 2 -> Error matrix calculated + // 3 -> 3-Dimensional iteration + + // ----- Output: ----- + + // vv0[5]: [0] = 1/r*charge, positive if clockwise; + // [1] = tan(lambda) { = dz/ds} tan(angle to (X,Y) PLANE); + // [2] = phi0 {0, 2*PI} angle to X-axis at r=d0; + // [3] = d0*sign [cm] minimal distance to Z-axis, + // +ve if axis encircled; + // [4] = z0 [cm] z position at r=d0; + // ee0[15]: Inverse of error matrix in triangular form; + // ch2ph: chi squared = Sum(phi deviations / errors)^2; + // ch2z: chi squared = Sum(z deviations / errors)^2; + // del: Unknown; + // delz: Unknown. + + // Note that the number of degrees of freedom = 2*npt-5 + + // Based on subroutine CIRCLE. + // Reference: "Computer Physics Communications", Volume 33, P. 329 + // Authors: N. Chernov, G. Ososkov and M. Poppe + + // Modified by Fred Weber, 8 Jun 1989. + // Translated into C by Michael Ispiryan, 2006 + + + { + int ITMAX = 15; + int IOWRIT = 6; + double EPS = (double)1.0e-16; + double ONEPI = (double)3.1415927; + double PI = (double)3.1415927; + double TWOPI = (double)6.2831854; + double PIBY2 = (double)1.57074635; + int MAX_HITS_ON_CHAIN = 200; + + double[] sp2 = new double[MAX_HITS_ON_CHAIN], vv1 = new double[5]; + double[] sxy = new double[MAX_HITS_ON_CHAIN], ss0 = new double[MAX_HITS_ON_CHAIN]; + double[] eee = new double[MAX_HITS_ON_CHAIN]; + double[] grad = new double[5], cov= new double[15], dv= new double[5]; + double[] deln = new double[MAX_HITS_ON_CHAIN], delzn = new double[MAX_HITS_ON_CHAIN]; + + double[] xf = new double[MAX_HITS_ON_CHAIN], yf= new double[MAX_HITS_ON_CHAIN], wf= new double[MAX_HITS_ON_CHAIN]; + + double alf, a0, a1, a2, a22, bet, cur, dd, den; + double det, dy, d2, f, fact, fg, f1, g, gam, gam0; + double g1, h, h2, p2, q2, rm, rn, xa, xb = 0, xd, xi; + double xm, xx, xy, x1, x2, den2, ya, yb, yd, yi, ym; + double yy, y1, y2, wn, sa2b2, dd0, phic; + + int i, n, iter, nrank= 0; + + double chi2_here, rr0, asym, sst, ph0, check; + double aa0, ome, gg0, hh0, ff0, sums, sumss, sumz, sumsz, sumw; + double denom, dzds_here, zz0, eta, dfd, dfo, dpd, dpo, ggg, dza; + double dzd, dzo, chi1; + + //nkb added these variables for the recalculation of dz/ds + double kangle, my_phi, xc, yc, xdca; + double ydca, xbar, ybar, xpt, ypt, alpha, beta; + if (npt <= 2) + { + System.out.println("BonusHelixFit::rwfthc(): Cannot fit less than 3 points; exiting..\n"); + return; + } + if (npt > MAX_HITS_ON_CHAIN) + { + System.out.println("BonusHelixFit::rwfthc(): Cannot fit more than " + MAX_HITS_ON_CHAIN + " points; exiting..\n" ); + return; + } + for(i=0; i= ITMAX) break; + dy = a1 + xa*(a22 + xa*(4.0*xa - 12.0)); + xb = xa - ya/dy; + if (Math.abs(ya) > Math.abs(yb)) xb = 0.5*(xb+xa); + if (Math.abs(xa-xb) < EPS) break; + xa = xb; yb = ya; iter++; + } + + gam = gam0*xb; + f1 = f - gam; + g1 = g - gam; + x1 = xd*g1 - yd*h; + y1 = yd*f1 - xd*h; + det = f1*g1 - h2; den2 = 1.0/(x1*x1 + y1*y1 + gam*det*det); + if (den2 <= 0.0) {ch2ph = 1.0E+30; ch2z = 1.0E+30; return;} + den = Math.sqrt(den2); cur = det*den + 0.0000000001; + alf = -(xm*det + x1)*den; + bet = -(ym*det + y1)*den; + rm = xm*xm + ym*ym; + + // ------- Calculation of standard circle parameters. NB: cur is + // ------- always positive. + asym = bet*xm - alf*ym; + sst = 1.0; + if (asym<0.0) sst = -1.0; + rr0 = sst*cur; + if((alf*alf + bet*bet) <= 0.0) {ch2ph = 1.0E+30; ch2z = 1.0E+30; return;} + sa2b2 = 1.0/(Math.sqrt(alf*alf + bet*bet)); + dd0 = (1.0 - 1.0/sa2b2)/cur; + phic = Math.asin(alf*sa2b2) + PIBY2; + if (bet > 0.0) phic = TWOPI - phic; + ph0 = phic + PIBY2; + + if (rr0 <= 0.0) ph0 -= ONEPI; + if (ph0 > TWOPI) ph0 -= TWOPI; + if (ph0 < 0.0) ph0 += TWOPI; + + vv0[0]=rr0; vv0[2]=ph0; vv0[3]=dd0; + //printf("rr0,ph0,dd0 = %f %f %f\n",1/rr0,ph0,dd0); + check = sst*rr0*dd0; + if (check == 1.0) { dd0 -= 0.007; vv0[3] = dd0; } + + // ------- Calculate phi distances to measured points + aa0=sst; ome=rr0; gg0=ome*dd0-aa0; hh0=1.0/gg0; + for(i=0; i 1.0) ff0 = 1.0; + + del[i] = ph0 + (ss0[i]-aa0)*PIBY2 + ss0[i]*Math.asin(ff0) - pf[i]; + if (del[i] > ONEPI) del[i] -= TWOPI; + if (del[i] < -ONEPI) del[i] += TWOPI; + } + + + // -------- Fit straight line in S-Z + for(i=0; i 0.9999) + { + //quiet = FALSE; + //fprintf(stderr, "+Track circles too much for this code(eee=%f); bad dzds\n",eee[i]); + //badarg = TRUE;//break; + //printf("eee[%d] = %f\n",i,eee[i]); + eee[i] = 0.9999; + } + if (eee[i] < -0.9999) + { + //quiet = FALSE; + //fprintf(stderr, "-Track circles too much for this code(eee=%f); bad dzds\n",eee[i]); + //badarg = TRUE;//break; + //printf("eee[%d] = %f\n",i,eee[i]); + eee[i] = -0.9999; + } + + sxy[i] = 2.0*Math.asin(eee[i])/ome; + //printf("original sxy[%d] = %f\n",i,sxy[i]); + } + + //if(badarg) + { + /* + for(i=0; i2.0*PI) my_phi-=2.0*PI; + xc = -Math.sin(my_phi)*((-vv0[3])+Math.abs(1.0/vv0[0])); + yc = Math.cos(my_phi)*((-vv0[3])+Math.abs(1.0/vv0[0])); + xdca = -Math.sin(my_phi)*(-vv0[3]); + ydca = Math.cos(my_phi)*(-vv0[3]); + xbar = xdca - xc; + ybar = ydca - yc; + //printf("xdca= %.1f ydca= %.1f xc= %.1f yc= %.1f xbar= %.1f ybar= %.1f\n", + // xdca, ydca, xc, yc, xbar, ybar); + for(i=0; i 1.0) + { + //quiet = FALSE; + //printf("eee[%d] = %f, rad = %f, mydd = %f\n",i,eee[i],1/rr0,Math.sqrt(mydd)); + //getchar(); + } + sxy[i] = (1/(sst*rr0))*acos(eee[i]); + //printf("law of Math.cos sxy[%d] = %f\n",i,sxy[i]); + */ + //ksxy = sxy[i]; + xpt = xf[i] - xc; + ypt = yf[i] - yc; + alpha = Math.atan2(ypt,xpt); + beta = Math.atan2(ybar,xbar); //if(alpha > 2*PI)alpha -= 2*PI; + //if(alpha < 0) alpha += 2*PI; + //if(beta > 2*PI) beta -= 2*PI; + //if(beta < 0) beta += 2*PI; + //printf("alpha = %.2f beta = %.2f\n",alpha*180./PI,beta*180./PI); + sxy[i] = beta - alpha; + if(sxy[i] > PI) sxy[i] = sxy[i] - 2*PI; + if(sxy[i] < -PI)sxy[i] = sxy[i] + 2*PI; + //if(sxy[i] < 0) sxy[i] += 2*PI; + kangle = sxy[i]; + sxy[i] = (1/rr0)*sxy[i]; + + //printf("[%d] xf= %.1f yf= %.1f xpt= %.1f ypt= %.1f\n", + //i, xf[i], yf[i], xpt, ypt); + //HFILL(9916, ksxy - sxy[i], 0.0, 1.0); + //printf("%f\n",ksxy-sxy[i]); + } + + } + + + sums = 0.0; + sumss = 0.0; + sumz = 0.0; + sumsz = 0.0; + sumw = 0.0; + for(i=0; i= 0.0) denom = 1.0E-6; + else denom = -1.0E-6; + } + + dzds_here = (sumw*sumsz - sums*sumz) / denom; + zz0 = (sumss*sumz - sums*sumsz) / denom; + vv0[1] = dzds_here; vv0[4] = zz0; + + // --------- Calculation of chi**2 + for(i=0; i 0.9999) ff0 = 0.9999; + if (ff0 < -0.9999) ff0 = -0.9999; + eta = ss0[i] / Math.sqrt(Math.abs(1.0+ff0)*(1.0-ff0)); + dfd = (1.0 + hh0*hh0*(1.0-ome*ome*rf[i]*rf[i])) / (2.0*rf[i]); + dfo = -aa0*(rf[i]*rf[i] - dd0*dd0)*hh0*hh0 / (2.0*rf[i]); + dpd = eta*dfd; dpo = eta*dfo; + // --- Derivatives of z component + ggg = eee[i] / Math.sqrt(Math.abs( (1.0+eee[i])*(1.0-eee[i]))); + dza = sxy[i]; + check = rf[i]*rf[i] - vv0[3]*vv0[3]; + if (check == 0.0) check = 2.0*0.007; + dzd = 2.0*(vv0[1]/vv0[0]) * Math.abs(ggg) * (0.5*aa0*vv0[0] / + (1.0 - aa0*vv0[3]*vv0[0]) - vv0[3]/check); + dzo = -vv0[1]*sxy[i]/vv0[0] + vv0[1]*ggg/(vv0[0]*vv0[0]) * + (2.0 + aa0*vv0[0]*vv0[3]/(1.0 - aa0*vv0[0]*vv0[3])); + + // ---- Error matrix + ee0[0] += sp2[i]*dpo*dpo + wzf[i]*dzo*dzo; + ee0[1] += wzf[i]*dza*dzo; + ee0[2] += wzf[i]*dza*dza; + ee0[3] += sp2[i]*dpo; + ee0[5] += sp2[i]; + ee0[6] += sp2[i]*dpo*dpd + wzf[i]*dzo*dzd; + ee0[8] += sp2[i]*dpd; + ee0[9] += sp2[i]*dpd*dpd + wzf[i]*dzd*dzd; + ee0[10] += wzf[i]*dzo; + ee0[11] += wzf[i]*dza; + ee0[13] += wzf[i]*dzd; + ee0[14] += wzf[i]; + + // --- Gradient vector + grad[0] += -del[i]*sp2[i]*dpo - delz[i]*wzf[i]*dzo; + grad[1] += - delz[i]*wzf[i]*dza; + grad[2] += -del[i]*sp2[i]; + grad[3] += -del[i]*sp2[i]*dpd - delz[i]*wzf[i]*dzd; + grad[4] += - delz[i]*wzf[i]; + } // End of for(i...) + + + if (iopt < 3) return; + + + // --------------- Newton's next guess + for(i=0; i<15; i++) cov[i] = ee0[i]; + + rwsmin(cov, vv1, 5, 0, nrank); + rwsmav(dv, cov, grad, 5); + + for(i=0; i<5; i++) vv1[i] = vv0[i] + dv[i]; + + //------- New differences in phi and z + gg0 = vv1[0]*vv1[3] - aa0; + for(i=0; i 1.0) ff0 = 1.0; + if (ff0 < -1.0) ff0 = -1.0; + + deln[i] = vv1[2] + (ss0[i]-aa0)*PIBY2 + ss0[i]*Math.asin(ff0) - pf[i]; + if (deln[i] > ONEPI) deln[i] -= TWOPI; + if (deln[i] < -ONEPI) deln[i] += TWOPI; + eee[i] = 0.5*vv1[0]*Math.sqrt(Math.abs( (rf[i]*rf[i] - vv1[3]*vv1[3]) / + (1.0 - aa0*vv1[0]*vv1[3]) )); + if (eee[i] > 0.9999) eee[i] = 0.9999; + if (eee[i] < -0.9999) eee[i] = -0.9999; + sxy[i] = 2.0*Math.asin(eee[i]) / vv1[0]; + delzn[i] = vv1[4] + vv1[1]*sxy[i] - zf[i]; + } + + // ---------- Calculation of chi**2 + chi1 = ch2ph = ch2z = 0.0; + for(i=0; i24.0) R=24.; + if(R<1.5) R=1.5; + double Para_dPhiVsR[] = {0.753136, -0.391614, 0.0836029, -0.00944999, + 0.000611348, -2.26783e-05, 4.47764e-07, -3.64278e-09}; + double dPhi = Para_dPhiVsR[0]; + for(int i=1;i<=7;i++) dPhi += Para_dPhiVsR[i]*Math.pow(R,i); + Phi = Phi - dPhi; + //apply 2nd correction if R<5.5 cm + if(R<5.5) { + double Para_dPhiVsR_2nd[] = {11.0937, -17.3801, 11.0492, -3.65267, + 0.663338, -0.0628701, 0.00243461}; + double dPhi_2nd = Para_dPhiVsR_2nd[0]; + for(int i=1;i<=6;i++) dPhi_2nd += Para_dPhiVsR_2nd[i]*Math.pow(R,i); + Phi = Phi - dPhi_2nd; + } + + return; + + /****************************************** + r_hel-rho_1st:r_hel, only good for 1.014.5) R=14.5; + if(R<14.50001) { + double Para_dRVsR[] = { 8.2822, -8.35421, 3.32568, -0.685895, 0.0797764, + -0.00527024, 0.000184178, -2.64062e-06}; + double dR = Para_dRVsR[0]; + for(int i=1;i<=7;i++) dR += Para_dRVsR[i]*Math.pow(R,i); + R = R - dR; + Rho = (Rho<0)? -R : R;*/ + //std::cout<<"\t\t dR="<> recotrackmap = params.get_recotrackmap(); + HashMap finaltrackinfomap = new HashMap<>(); + double szpos[][] = new double[10000][3]; + int hit = 0; + for(int TID : recotrackmap.keySet()){ + int numhits = recotrackmap.get(TID).size(); + double ADCsum = 0; + for(hit = 0; hit < numhits; hit++){ + szpos[hit][0] = recotrackmap.get(TID).get(hit).x(); + szpos[hit][1] = recotrackmap.get(TID).get(hit).y(); + szpos[hit][2] = recotrackmap.get(TID).get(hit).z(); + ADCsum += recotrackmap.get(TID).get(hit).adc(); + } + HelixFitJava h = new HelixFitJava(); + HelixFitObject ho = h.HelixFit(hit,szpos,fitToBeamline); + Vector3 v1 = new Vector3(); + double dz = 0; + + dz = recotrackmap.get(TID).get(numhits-1).z() - recotrackmap.get(TID).get(0).z(); + v1 = new Vector3(recotrackmap.get(TID).get(0).x()-ho.get_A(),recotrackmap.get(TID).get(0).y()-ho.get_B(),0); + Vector3 v2 = new Vector3(recotrackmap.get(TID).get(numhits-1).x()-ho.get_A(),recotrackmap.get(TID).get(numhits-1).y()-ho.get_B(),0); + double psi = Math.toRadians(v1.theta(v2)); //angle theta for helix + double momfit = ho.get_Mom(); + double gain = 1; + double px = ho.get_px(); + double py = ho.get_py(); + double pz = ho.get_pz(); + double vz = ho.get_Z0(); + double theta = ho.get_Theta(); + double phi = ho.get_Phi(); + double tl = 0; + if(ho.get_Rho() > 0) Math.sqrt(ho.get_Rho()*ho.get_Rho()*psi*psi + dz*dz); + double dEdx = 0; + if(tl != 0) dEdx = ADCsum/(gain*tl); + finaltrackinfomap.put(TID, new FinalTrackInfo(px,py,pz,vz,theta,phi,numhits,tl,dEdx)); + } + params.set_finaltrackinfomap(finaltrackinfomap); + } +} \ No newline at end of file diff --git a/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/Hit.java b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/Hit.java new file mode 100644 index 0000000000..97c1f984c2 --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/Hit.java @@ -0,0 +1,201 @@ +package org.jlab.rec.rtpc.hit; + +/** + * A hit characterized by Time, cellID, and Edep. The ADC to Time conversion has been done. + * @author payette + */ + + +public class Hit implements Comparable{ + // class implements Comparable interface to allow for sorting a collection of hits by wire number values + + + // constructors + + public Hit(int hitID, int cellID, double ADC, double Time) { + this._Id = hitID; + this._cellID = cellID; + this._Time = Time; + this._ADC = ADC; + } + + /*public Hit(int hitID, int cellID, double Time, double ADC) { + this._Id = hitID; + this._cellID = cellID; + this._Time = Time; + this._ADC = 1; + }*/ + + private int _Id; + private int _cellID; + private double _Time; + private double _ADC; + private int _Step; + private double _Edep; + private double _phiRad; + private double _PosX; + private double _PosY; + private double _PosZ; + private double _EdepTrue; + private double _PosXTrue; + private double _PosYTrue; + private double _PosZTrue; + private double _TShift; + + public int get_Id() { + return _Id; + } + + public void set_Id(int _Id) { + this._Id = _Id; + } + + public int get_cellID() { + return _cellID; + } + + public void set_cellID(int _cellID) { + this._cellID = _cellID; + } + + public double get_Time() { + return _Time; + } + + public void set_Time(double _Time) { + this._Time = _Time; + } + + public double get_ADC() { + return _ADC; + } + + public void set_ADC(double _ADC) { + this._ADC = _ADC; + } + + public int get_Step() { + return _Step; + } + + public void set_Step(int _Step) { + this._Step = _Step; + } + + public double get_Edep() { + return _Edep; + } + + public void set_Edep(double _Edep) { + this._Edep = _Edep; + } + + public double get_phiRad() { + return _phiRad; + } + + public void set_phiRad(double _phiRad) { + this._phiRad = _phiRad; + } + + public double get_PosX() { + return _PosX; + } + + public void set_PosX(double _PosX) { + this._PosX = _PosX; + } + + public double get_PosY() { + return _PosY; + } + + public void set_PosY(double _PosY) { + this._PosY = _PosY; + } + + public double get_PosZ() { + return _PosZ; + } + + public void set_PosZ(double _PosZ) { + this._PosZ = _PosZ; + } + + public double get_EdepTrue() { + return _EdepTrue; + } + + public void set_EdepTrue(double _EdepTrue) { + this._EdepTrue = _EdepTrue; + } + + public double get_PosXTrue() { + return _PosXTrue; + } + + public void set_PosXTrue(double _PosXTrue) { + this._PosXTrue = _PosXTrue; + } + + public double get_PosYTrue() { + return _PosYTrue; + } + + public void set_PosYTrue(double _PosYTrue) { + this._PosYTrue = _PosYTrue; + } + + public double get_PosZTrue() { + return _PosZTrue; + } + + public void set_PosZTrue(double _PosZTrue) { + this._PosZTrue = _PosZTrue; + } + + public double get_TShift() { + return _TShift; + } + + public void set_TShift(double _TShift) { + this._TShift = _TShift; + } + /** + * + * @return print statement with hit information + */ + public String printInfo() { + String s = "RTPC Hit: ID "+this.get_Id()+" cellID "+this.get_cellID()+" ADC "+this.get_ADC()+" Edep "+this.get_Edep()+" Time "+this.get_Time(); + return s; + } + + /** + * + * @param otherHit + * @return a boolean comparing 2 hits based on basic descriptors; + * returns true if the hits are the same + */ + public boolean isSameAs(Hit otherHit) { + Hit thisHit = (Hit) this; + boolean cmp = false; + if(thisHit.get_Edep() == otherHit.get_Edep() + && thisHit.get_cellID() == otherHit.get_cellID() + && thisHit.get_Time() == otherHit.get_Time() + && thisHit.get_ADC() == otherHit.get_ADC() + ) + cmp = true; + return cmp; + } + + @Override + public int compareTo(Hit arg0) { + if(this._cellID>arg0._cellID) { + return 1; + } else { + return 0; + } + } + + +} diff --git a/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/HitDistance.java b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/HitDistance.java new file mode 100644 index 0000000000..f441dab68b --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/HitDistance.java @@ -0,0 +1,129 @@ +package org.jlab.rec.rtpc.hit; +/* +import java.util.HashMap; +import java.util.concurrent.ConcurrentHashMap; +import java.util.List; + +import javax.swing.JFrame; + +import org.jlab.clas.physics.Vector3; +import org.jlab.groot.data.H1F; +import org.jlab.groot.graphics.EmbeddedCanvas; + +public class HitDistance { + + public void FindDistance(HitParameters params) { + HashMap ADCMap = params.get_ADCMap(); + List PadList = params.get_PadList(); + int Pad = 0; //initializing pad + int Pad2 = 0; + int TrigWindSize = params.get_TrigWindSize(); //Trigger Window Size = 10000 + //int StepSize = params.get_StepSize(); + int StepSize = 120; //Time stepsize + double thresh = 1e-5; //Arbitrary ADC threshold + double ADC = 0; + double ADC2 = 0; + Vector3 TempPadCoords = new Vector3(); + Vector3 CheckPadCoords = new Vector3(); + Vector3 CheckPadPrevCoords = new Vector3(); + EmbeddedCanvas c1 = new EmbeddedCanvas(); + EmbeddedCanvas c2 = new EmbeddedCanvas(); + EmbeddedCanvas c3 = new EmbeddedCanvas(); + H1F t1 = new H1F("t1","t1",100,0,50); + H1F t2 = new H1F("t2","t2",100,0,8); + H1F t3 = new H1F("t3","t3",100,0,10); + t1.setTitleX("xy in mm"); + t2.setTitleX("z in mm"); + t3.setTitleX("ellipse formula result"); + JFrame j1 = new JFrame(); + j1.setSize(800,600); + j1.setTitle("xy"); + JFrame j2 = new JFrame(); + j2.setSize(800,600); + j2.setTitle("z"); + JFrame j3 = new JFrame(); + j3.setSize(800,600); + j3.setTitle("ellipse"); + double EllipseDeltax = 0; + double EllipseDeltay = 0; + double EllipseDeltaz = 0; + double EllipseTotal = 0; + double PhiDelta = Math.pow(3, 2); + double ZDelta = Math.pow(6, 2); + for(int t = 0; t < TrigWindSize; t+=StepSize) + { + for(int p = 0; p < PadList.size(); p ++) + { + Pad = PadList.get(p); + ADC = ADCMap.get(Pad)[t]; + if(ADC > thresh) + { + Vector3 PadCoords = PadCoords(Pad); + for(int p2 = 0; p2 < PadList.size(); p2++) + { + if(p2 != p) + { + Pad2 = PadList.get(p2); + ADC2 = ADCMap.get(Pad2)[t]; + if(ADC2 > thresh) + { + CheckPadCoords = PadCoords(Pad2); + EllipseDeltax = Math.pow(Math.abs(PadCoords.x()-CheckPadCoords.x()),2); + EllipseDeltay = Math.pow(Math.abs(PadCoords.y()-CheckPadCoords.y()),2); + EllipseDeltaz = Math.pow(Math.abs(PadCoords.z()-CheckPadCoords.z()),2); + EllipseTotal = ((EllipseDeltax+EllipseDeltay)/PhiDelta) + (EllipseDeltaz/ZDelta); + t1.fill(Math.sqrt(EllipseDeltax+EllipseDeltay)); + t2.fill(Math.sqrt(EllipseDeltaz)); + t3.fill(EllipseTotal); + } + } + } + } + } + } + c1.draw(t1); + c2.draw(t2); + c3.draw(t3); + j1.add(c1); + j2.add(c2); + j3.add(c3); + j1.setVisible(true); + j2.setVisible(true); + j3.setVisible(true); + } + private Vector3 PadCoords(int cellID) { + + double PAD_W = 2.79; // in mm + double PAD_S = 80.0; //in mm + double PAD_L = 4.0; // in mm + double RTPC_L=384.0; // in mm + double phi_pad = 0; + //double Num_of_Rows = (2.0*(Math.PI)*PAD_S)/PAD_W; + double Num_of_Cols = RTPC_L/PAD_L; + double PI=Math.PI; + double z0 = -(RTPC_L/2.0); + double phi_per_pad = PAD_W/PAD_S; // in rad + double chan = (double)cellID; + double col = chan%Num_of_Cols; + double row=(chan-col)/Num_of_Cols; + double z_shift = row%4; + + phi_pad=(row*phi_per_pad)+(phi_per_pad/2.0); + + if(phi_pad>= 2.0*PI) + { + phi_pad -= 2.0*PI; + } + if(phi_pad<0) + { + phi_pad += 2.0*PI; + } + + double z_pad=z0+(col*PAD_L)+(PAD_L/2.0)+z_shift; + + Vector3 PadCoords = new Vector3(PAD_S*Math.cos(phi_pad),PAD_S*Math.sin(phi_pad),z_pad); + return PadCoords; + + } +} +*/ \ No newline at end of file diff --git a/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/HitParameters.java b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/HitParameters.java new file mode 100644 index 0000000000..cf55027016 --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/HitParameters.java @@ -0,0 +1,166 @@ +package org.jlab.rec.rtpc.hit; + +import java.util.List; +import java.util.ArrayList; +import java.util.HashMap; +import org.jlab.detector.calib.utils.ConstantsManager; +import org.jlab.utils.groups.IndexedTable; + +public class HitParameters { + + final private int _SignalStepSize = 10; + final private int _BinSize = 40; + final private int _NBinKept = 3; + final private int _TrigWindSize = 10000; + private int _eventnum = 0; + private ADCMap _ADCMap = new ADCMap(); + private HashMap> _TimeMap = new HashMap<>(); + private HashMap> _FinalTIDMap = new HashMap<>(); + private List _PadN = new ArrayList<>(); // used to read only cell with signal, one entry for each hit + private List _PadList = new ArrayList<>();// used to read only cell with signal, one entry for each cell + private List _Pad = new ArrayList<>(); + private List _ADC = new ArrayList<>(); + private List _Time_o = new ArrayList<>(); + private List _weightave = new ArrayList<>(); + private List _maxinte = new ArrayList<>(); + private List _time = new ArrayList<>(); + private List _XVec = new ArrayList<>(); + private List _YVec = new ArrayList<>(); + private List _ZVec = new ArrayList<>(); + private HashMap>> _TIDMap = new HashMap<>(); + private HashMap>> _strkTIDMap = new HashMap<>(); + private HashMap> _alltracks = new HashMap<>(); + private HashMap _largetmap = new HashMap<>(); + private HashMap> _recotrackmap = new HashMap<>(); + private HashMap _padmap = new HashMap<>(); + private TrackMap _trackmap = new TrackMap(); + private ReducedTrackMap _rtrackmap = new ReducedTrackMap(); + private HashMap _finaltrackinfomap; + private int _timeadjlimit = 4; + private double _zthreshTF = 16; + private double _phithreshTF = 0.16; + private double _zthreshTD = 8; + private double _phithreshTD = 0.1; + private int _tthreshTD = 300; + private double _adcthresh = 320; + private int _minhitspertrack = 5; + private double[] _tmaxparms = new double[5]; + private double[] _toffparms = new double[5]; + private double[] _aphiparms = new double[5]; + private double[] _bphiparms = new double[5]; + private double[] _tgapparms = new double[5]; + private double[] _phigapparms = new double[5]; + private double _tl = 0; + private double _tp = 0; + private double _tr = 0; + private double _tcathode = 0; + + public void init(ConstantsManager manager, int runNo){ + IndexedTable gain_balance = manager.getConstants(runNo, "/calibration/rtpc/gain_balance"); + IndexedTable time_offsets = manager.getConstants(runNo, "/calibration/rtpc/time_offsets"); + IndexedTable time_parms = manager.getConstants(runNo, "/calibration/rtpc/time_parms"); + IndexedTable recon_parms = manager.getConstants(runNo, "/calibration/rtpc/recon_parms"); + + _timeadjlimit = (int) recon_parms.getDoubleValue("Dtm", 1,1,1); + _zthreshTF = recon_parms.getDoubleValue("Dzm", 1,1,1); + _phithreshTF = recon_parms.getDoubleValue("Dphim", 1,1,1); + _adcthresh = recon_parms.getDoubleValue("ADCmin", 1,1,1); + _minhitspertrack = (int) recon_parms.getDoubleValue("Hitmin",1,1,1); + _zthreshTD = recon_parms.getDoubleValue("Dzm", 1,1,2); + _phithreshTD = recon_parms.getDoubleValue("Dphim", 1,1,2); + _tthreshTD = (int) recon_parms.getDoubleValue("Dtm",1,1,2); + for(int i = 0; i < 5; i++){ + _tmaxparms[i] = time_parms.getDoubleValue("z"+i, 1,1,1); + _toffparms[i] = time_parms.getDoubleValue("z"+i, 1,1,2); + _aphiparms[i] = time_parms.getDoubleValue("z"+i, 1,1,3); + _bphiparms[i] = time_parms.getDoubleValue("z"+i, 1,1,4); + _tgapparms[i] = time_parms.getDoubleValue("z"+i, 1,1,5); + _phigapparms[i] = time_parms.getDoubleValue("z"+i, 1,1,6); + } + _tl = time_offsets.getDoubleValue("tl", 1,1,3); + _tp = time_offsets.getDoubleValue("tp", 1,1,3); + _tr = time_offsets.getDoubleValue("tr", 1,1,3); + _tcathode = time_parms.getDoubleValue("z0", 1,1,7); + } + + public int get_SignalStepSize(){return _SignalStepSize;} // step size of the signal before integration (arbitrary value) + public int get_BinSize(){return _BinSize;} // electronics integrates the signal over 40 ns + public int get_NBinKept(){return _NBinKept;} // only 1 bin over 3 is kept by the daq + public int get_TrigWindSize(){return _TrigWindSize;} // Trigger window should be 10 micro + public ADCMap get_ADCMap(){return _ADCMap;} + public HashMap> get_TimeMap(){return _TimeMap;} + public List get_PadN(){return _PadN;} + public List get_PadList(){return _PadList;} + public List get_Pad(){return _Pad;} + public List get_ADC(){return _ADC;} + public List get_Time_o(){return _Time_o;} + public int get_eventnum(){return _eventnum;} + public List get_weightave() {return _weightave;} + public List get_maxinte() {return _maxinte;} + public List get_time() {return _time;} + public List get_XVec() {return _XVec;} + public List get_YVec() {return _YVec;} + public List get_ZVec() {return _ZVec;} + public HashMap>> get_TIDMap() {return _TIDMap;} + public HashMap>> get_strkTIDMap() {return _strkTIDMap;} + public HashMap> get_FinalTIDMap() {return _FinalTIDMap;} + public HashMap> get_alltracks() {return _alltracks;} + public HashMap get_largetmap() {return _largetmap;} + public HashMap> get_recotrackmap() {return _recotrackmap;} + public TrackMap get_trackmap() {return _trackmap;} + public ReducedTrackMap get_rtrackmap() {return _rtrackmap;} + public HashMap get_finaltrackinfomap() {return _finaltrackinfomap;} + public PadVector get_padvector(int pad) { + if(!_padmap.containsKey(pad)) { + _padmap.put(pad, new PadVector(pad)); + } + return _padmap.get(pad); + } + public int get_timeadjlimit(){return _timeadjlimit;} + public double get_zthreshTF(){return _zthreshTF;} + public double get_phithreshTF(){return _phithreshTF;} + public double get_zthreshTD(){return _zthreshTD;} + public double get_phithreshTD(){return _phithreshTD;} + public int get_tthreshTD(){return _tthreshTD;} + public double get_adcthresh(){return _adcthresh;} + public int get_minhitspertrack(){return _minhitspertrack;} + public double[] get_tmaxparms(){return _tmaxparms;} + public double[] get_toffparms(){return _toffparms;} + public double[] get_aphiparms(){return _aphiparms;} + public double[] get_bphiparms(){return _bphiparms;} + public double[] get_tgapparms(){return _tgapparms;} + public double[] get_phigapparms(){return _phigapparms;} + public double get_tl(){return _tl;} + public double get_tp(){return _tp;} + public double get_tr(){return _tr;} + public double get_tcathode(){return _tcathode;} + + public void set_ADCMap(ADCMap _ADCMap){this._ADCMap = _ADCMap;} + public void set_TimeMap(HashMap> _TimeMap){this._TimeMap = _TimeMap;} + public void set_PadN(List _PadN){this._PadN = _PadN;} + public void set_PadList(List _PadList){this._PadList = _PadList;} + public void set_Pad(List _Pad){this._Pad = _Pad;} + public void set_ADC(List _ADC){this._ADC = _ADC;} + public void set_Time_o(List _Time_o){this._Time_o = _Time_o;} + public void set_eventnum(int _eventnum){this._eventnum = _eventnum;} + public void set_weightave(List _weightave) {this._weightave = _weightave;} + public void set_maxinte(List _maxinte) {this._maxinte = _maxinte;} + public void set_time(List _time) {this._time = _time;} + public void set_XVec(List _XVec) {this._XVec = _XVec;} + public void set_YVec(List _YVec) {this._YVec = _YVec;} + public void set_ZVec(List _ZVec) {this._ZVec = _ZVec;} + public void set_TIDMap(HashMap>> _TIDMap) {this._TIDMap = _TIDMap;} + public void set_strkTIDMap(HashMap>> _strkTIDMap) {this._strkTIDMap = _strkTIDMap;} + public void set_FinalTimeMap(HashMap> _finalTIDMap){this._FinalTIDMap = _finalTIDMap;} + public void set_alltracks(HashMap> _alltracks) {this._alltracks = _alltracks;} + public void set_largetmap(HashMap _largetmap) {this._largetmap = _largetmap;} + public void set_recotrackmap(HashMap> _recotrackmap) {this._recotrackmap = _recotrackmap;} + public void set_trackmap(TrackMap _trackmap) {this._trackmap = _trackmap;} + public void set_rtrackmap(ReducedTrackMap _rtrackmap) {this._rtrackmap = _rtrackmap;} + public void set_finaltrackinfomap(HashMap _finaltrackinfomap) {this._finaltrackinfomap = _finaltrackinfomap;} + + + public HitParameters() {} + + +} \ No newline at end of file diff --git a/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/HitReconstruction.java b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/HitReconstruction.java new file mode 100644 index 0000000000..c3cc569537 --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/HitReconstruction.java @@ -0,0 +1,201 @@ +package org.jlab.rec.rtpc.hit; + +import java.util.List; +import java.util.Vector; + +public class HitReconstruction { + + public HitReconstruction() { + // TODO Auto-generated constructor stub + } + + public void Reco(HitParameters params) { + List PadList = params.get_PadList(); + List weightave = params.get_weightave(); + List maxinte = params.get_maxinte(); + + int p = 0; + //for(Hit hit : rawHits) { + for(p = 0; p= 2.0*PI) { + phi_pad -= 2.0*PI; + } + if(phi_pad<0) + { + phi_pad += 2.0*PI; + } + + z_pad=z0+(col*PAD_L)+(PAD_L/2.0)+z_shift; + // ----------------------------------------------------------------------- + + + // find reconstructed position of ionization from Time info + + t_s2pad = Time-t_gap; + + r_rec=((-(Math.sqrt(a_t*a_t+(4.*b_t*t_s2pad)))+a_t+(14.*b_t))/(2.*b_t))*10.0; //in mm + + + dphi=a_phi*(7.-r_rec/10.)+b_phi*(7.-r_rec/10.)*(7.-r_rec/10.); // in rad + + + dz=0; + + phi_rec=phi_pad-dphi-phi_gap; + if( phi_rec<0.0 ) + { + phi_rec+=2.0*PI; + } + if( phi_rec>2.0*PI ) + { + phi_rec-=2.0*PI; + } + + // x,y,z pos of reconstructed track + x_rec=r_rec*(Math.cos(phi_rec)); + y_rec=r_rec*(Math.sin(phi_rec)); + z_rec=z_pad-dz; + + // x,y,z pos of pad hit + //x_pad=(PAD_S)*(Math.cos(phi_pad)); + //y_pad=(PAD_S)*(Math.sin(phi_pad)); + + // actual position on pad of hits + //phi_hit=phi_rad-(row*phi_per_pad); + //z_hit=Z-z0-(col*PAD_L)-z_shift; + + // find differences (delta = generated-reconstructed) + //delta_x=X-x_rec; + //delta_y=Y-y_rec; + //delta_z=Z-z_rec; + //delta_r=r_pos-r_rec; + //delta_phi = phi_pos-phi_rec; + + + + + /*hit.set_cellID(cellID); + hit.set_Time(t_s2pad); + hit.set_Edep(Edep); + hit.set_PosX(x_rec); + hit.set_PosY(y_rec); + hit.set_PosZ(z_rec);*/ + /*TimeVec.add(t_s2pad); + XVec.add(x_rec); + YVec.add(y_rec); + ZVec.add(z_rec); + */ + + + + } + /*params.set_time(TimeVec); + params.set_XVec(XVec); + params.set_YVec(YVec); + params.set_ZVec(ZVec);*/ + //System.out.println(XVec.size() + " " + PadList.size()); + //XVec.clear(); + //YVec.clear(); + //ZVec.clear(); + //TimeVec.clear(); + + } +} diff --git a/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/HitVector.java b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/HitVector.java new file mode 100644 index 0000000000..a3c0b1f925 --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/HitVector.java @@ -0,0 +1,87 @@ +package org.jlab.rec.rtpc.hit; + +public class HitVector { + + private int pad; + private double z; + private double phi; + private double time; + private double adc; + + public HitVector() + { + pad = 0; + z = 0; + phi = 0; + time = 0; + adc = 0; + } + + public HitVector(int padnum, double hittime, double padadc) + { + pad = padnum; + z = 0; + phi = 0; + time = hittime; + adc = padadc; + } + + public HitVector(int padnum, double zpad, double phipad, double hittime, double padadc) + { + pad = padnum; + z = zpad; + phi = phipad; + time = hittime; + adc = padadc; + } + + public void setpad(int padnum) + { + pad = padnum; + } + + public void setz(double zpad) + { + z = zpad; + } + + public void setphi(double phipad) + { + phi = phipad; + } + + public void settime(double hittime) + { + time = hittime; + } + + public void setadc(double padadc) + { + adc = padadc; + } + + public int pad() + { + return pad; + } + + public double z() + { + return z; + } + + public double phi() + { + return phi; + } + + public double time() + { + return time; + } + + public double adc() + { + return adc; + } +} diff --git a/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/PadVector.java b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/PadVector.java new file mode 100644 index 0000000000..a1d6963302 --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/PadVector.java @@ -0,0 +1,66 @@ +package org.jlab.rec.rtpc.hit; + +import org.jlab.clas.physics.Vector3; + +public class PadVector { + + private Vector3 _vec; + /*private double _x; + private double _y; + private double _z; + private double _phi;*/ + private final double PAD_W = 2.79; // in mm + private final double PAD_S = 80.0; //in mm + private final double PAD_L = 4.0; // in mm + private final double RTPC_L= 384.0; // in mm + private double phi_pad; + private final double Num_of_Cols = RTPC_L/PAD_L; + private final double PI=Math.PI; + private final double z0 = -(RTPC_L/2.0); + private final double phi_per_pad = PAD_W/PAD_S; // in rad + private double chan; + private double col; + private double row; + private double z_shift; + private double z_pad; + + public PadVector(int padnum){ + chan = (double)padnum; + col = (chan-1)%Num_of_Cols+1; + row=(chan-col)/Num_of_Cols; + z_shift = row%4; + + phi_pad=(row*phi_per_pad)+(phi_per_pad/2.0); + + if(phi_pad>= 2.0*PI) { + phi_pad -= 2.0*PI; + } + if(phi_pad<0){ + phi_pad += 2.0*PI; + } + + z_pad=z0+((col-1)*PAD_L)+(PAD_L/2.0)+z_shift; + + _vec = new Vector3( + PAD_S*Math.cos(phi_pad), + PAD_S*Math.sin(phi_pad), + z_pad); + + } + + public double x(){ + return _vec.x(); + } + + public double y(){ + return _vec.y(); + } + + public double z(){ + return _vec.z(); + } + + public double phi(){ + return _vec.phi(); + } +} diff --git a/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/RecoHitVector.java b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/RecoHitVector.java new file mode 100644 index 0000000000..8a279cd02c --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/RecoHitVector.java @@ -0,0 +1,100 @@ +package org.jlab.rec.rtpc.hit; + +public class RecoHitVector { + + private int pad; + private double x; + private double y; + private double z; + private double dt; + private double time; + private double _adc; + + public RecoHitVector() + { + pad = 0; + x = 0; + y = 0; + z = 0; + dt = 0; + time = 0; + _adc = 0; + } + + public RecoHitVector(int padnum, double xrec, double yrec, double zrec, double tdiff, double t, double adc) + { + pad = padnum; + x = xrec; + y = yrec; + z = zrec; + dt = tdiff; + time = t; + _adc = adc; + } + + public void setpad(int padnum) + { + pad = padnum; + } + + public void setx(double xrec) + { + x = xrec; + } + + public void sety(double yrec) + { + y = yrec; + } + + public void setz(double zrec) + { + z = zrec; + } + + public void settime(double t) + { + time = t; + } + + public void setdt(double tdiff) + { + dt = tdiff; + } + + public int pad() + { + return pad; + } + + public double x() + { + return x; + } + + public double y() + { + return y; + } + + public double z() + { + return z; + } + + public double time() + { + return time; + } + + public double dt() + { + return dt; + } + + public double adc(){ + return _adc; + } + + +} diff --git a/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/ReducedTrack.java b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/ReducedTrack.java new file mode 100644 index 0000000000..1182359d2c --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/ReducedTrack.java @@ -0,0 +1,65 @@ +package org.jlab.rec.rtpc.hit; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +public class ReducedTrack { + + private List _hits = new ArrayList(); + private boolean _flagTrack = false; + + public ReducedTrack() { + //Default Constructor + } + + public void addHit(HitVector v) { + _hits.add(v); + } + + public void sortHits() { + Collections.sort(_hits, new Comparator() { + @Override + public int compare(HitVector v1, HitVector v2) { + return Double.compare(v2.time(),v1.time()); + } + }); + } + + public double getSmallT() { + return _hits.get(_hits.size()-1).time(); + } + + public double getLargeT() { + return _hits.get(0).time(); + } + + public Set getAllPads() { + Set pads = new HashSet(); + for(HitVector v : _hits) { + pads.add(v.pad()); + } + return pads; + } + + public List getAllHits() { + return _hits; + } + + public void flagTrack() { + _flagTrack = true; + } + + public boolean isTrackFlagged() { + return _flagTrack; + } + + public HitVector getLastHit(){ + return _hits.get(_hits.size()-1); + } + +} diff --git a/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/ReducedTrackMap.java b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/ReducedTrackMap.java new file mode 100644 index 0000000000..4ea6a3f7a1 --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/ReducedTrackMap.java @@ -0,0 +1,59 @@ +package org.jlab.rec.rtpc.hit; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.HashMap; + +public class ReducedTrackMap { + + private HashMap _map; + private int _trackID = 0; + + public ReducedTrackMap() { + _map = new HashMap(); + } + + public void addTrack(ReducedTrack t) { + _trackID++; + _map.put(_trackID, t); + } + + public ReducedTrack getTrack(int trackID) { + if(!_map.containsKey(trackID)) { + addTrack(new ReducedTrack()); + } + return _map.get(trackID); + } + + public void updateTrack(int trackID, ReducedTrack t) { + _map.put(trackID, t); + } + + public void removeTrack(int trackID) { + _map.remove(trackID); + } + + public List getAllTrackIDs() { + List l = new ArrayList(); + for(int i : _map.keySet()) { + if(!l.contains(i)) { l.add(i);} + } + return l; + } + + public int getLastTrackID() { + return _trackID; + } + + public void mergeTracks(int trackIDparent, int trackID) { + ReducedTrack child = getTrack(trackID); + List l = child.getAllHits(); + ReducedTrack parent = getTrack(trackIDparent); + for(HitVector v : l) { + parent.addHit(v); + } + removeTrack(trackID); + } + +} diff --git a/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/SignalSimulation.java b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/SignalSimulation.java new file mode 100644 index 0000000000..1b51b12b18 --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/SignalSimulation.java @@ -0,0 +1,59 @@ +// Author: Gabriel Charles +// Language Conversion: David Payette + +// This code creates a signal shape for each hit on a single pad, and then sums all signals on that pad and stores them +// into a map called ADCMap which uses the pad (cellID) as the key and returns an array which is organized by time bins. +// All variables used in this code are stored and accessed in HitParameters.java which is instantiated in RTPCEngine.java. +// This code is accessed once for each event, and then the signal shaping map is looped through and filled for all hits in that event. +// The map is refreshed for each event. + +package org.jlab.rec.rtpc.hit; +import java.util.*; + + + +public class SignalSimulation { + + private int SignalStepSize; // step size of the signal before integration (arbitrary value) + private int BinSize;// electronics integrates the signal over 40 ns + private int NBinKept;// only 1 bin over 3 is kept by the daq + private int TrigWindSize;// Trigger window should be 10 micro + private int NTrigSampl;// number of time samples + private List PadList = new ArrayList<>(); + private int CellID = 0; + private double Time; + private double Edep; + private ADCMap ADCMap = new ADCMap(); + + + public SignalSimulation(List rawHits, HitParameters params, boolean simulation){ + + SignalStepSize = params.get_SignalStepSize(); // step size of the signal before integration (arbitrary value) + BinSize = params.get_BinSize(); // electronics integrates the signal over 40 ns + NBinKept = params.get_NBinKept(); // only 1 bin over 3 is kept by the daq + TrigWindSize = params.get_TrigWindSize(); // Trigger window should be 10 micro + NTrigSampl = TrigWindSize/BinSize; // number of time samples + + for(Hit hit : rawHits){ + + CellID = hit.get_cellID(); //Pad ID number of the hit + Time = hit.get_Time(); //Time of the hit + Edep = hit.get_EdepTrue(); //Simulated Energy of the hit + + if(simulation){ + ADCMap.simulateSignal(CellID,Time,Edep);//Creates a signal based on the Time and the Energy + ADCMap.integrateSignal(CellID); //Integrates the signal into 120 ns bins based on DREAM elec specifications + }else{ + ADCMap.addSignal(CellID, (int)Time, Edep); + + } + if(!PadList.contains(CellID)){ + PadList.add(CellID); + } //Maintains a list of all unique Pad IDs + + } + + params.set_PadList(PadList); + params.set_ADCMap(ADCMap); + } +} diff --git a/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/TimeAverage.java b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/TimeAverage.java new file mode 100644 index 0000000000..a045ad3f17 --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/TimeAverage.java @@ -0,0 +1,89 @@ +//Author: David Payette + +/* This code takes the tracks from the Track Finder, and reduces the signals in the track to single + * values in time by taking a weighted average of the signal using the ADC value as the weight + * The end result is the same tracks but with hits which now have non-discritized times (not in + * 120 ns slices) This is useful for the disentangler to split merged tracks + */ + +package org.jlab.rec.rtpc.hit; + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + + +public class TimeAverage { + + private ReducedTrackMap RTIDMap = new ReducedTrackMap(); + private ReducedTrack rtrack; + private TrackMap TIDMap; + private ADCMap ADCMap; + private List tids; + private Track track; + private double adc = 0; + private double adcmax = 0; + private double averagetime = 0; + private double adcthresh = 0; + private double sumnum = 0; + private double sumden = 0; + + public TimeAverage(HitParameters params) { + /* + *Initializations + */ + TIDMap = params.get_trackmap(); + ADCMap = params.get_ADCMap(); + tids = TIDMap.getAllTrackIDs(); + + + /* + * Main Algorithm + */ + + for(int tid : tids) { //Loop over all tracks + track = TIDMap.getTrack(tid); + boolean trackflag = track.isTrackFlagged(); + rtrack = new ReducedTrack(); + if(trackflag) rtrack.flagTrack(); + Set l = track.uniquePadList(); + Set timesbypad = new HashSet<>(); + for(int pad : l) { + //g.add(new GraphErrors()); + adcmax = 0; + sumnum = 0; + sumden = 0; + timesbypad = track.PadTimeList(pad); + for(int time : timesbypad) { //Loop to calculate maximum adc value + adc = ADCMap.getADC(pad,time); + if(adc > adcmax) { + adcmax = adc; + } + } + + adcthresh = adcmax/2; + for(int time : timesbypad) { //Loop to calculate weighted average time using ADC values which are above half of the maximum + adc = ADCMap.getADC(pad,time); + if(adc > adcthresh) { + sumnum += adc*time; + sumden += adc; + } + } + averagetime = sumnum/sumden; + PadVector p = params.get_padvector(pad); + HitVector v = new HitVector(pad,p.z(),p.phi(),averagetime,sumden); + rtrack.addHit(v); + } + RTIDMap.addTrack(rtrack); + } + + /* + * Output + */ + + params.set_rtrackmap(RTIDMap); + } +} diff --git a/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/Track.java b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/Track.java new file mode 100644 index 0000000000..37630cfcd6 --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/Track.java @@ -0,0 +1,116 @@ +package org.jlab.rec.rtpc.hit; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.HashMap; + +public class Track { + + private HashMap> _track = new HashMap<>(84,1.0f); + private List _l = new ArrayList<>(); + //private int _padcount; + private boolean _flagTrack = false; + + public Track() { + //default constructor + } + public Track(int time, int padnum) { + if(!_track.containsKey(time)) { + addTimeSlice(time); + } + addPad(time,padnum); + } + + public void addTimeSlice(int time) { + _track.put(time, new ArrayList<>()); + } + + public void addTimeSlice(int time, List l) { + List templ = getTimeSlice(time); + for(int i : l) { + if(!templ.contains(i)) { + templ.add(i); + } + } + } + + public void addPad(int time, int padnum) { + _track.get(time).add(padnum); + } + + public List getTimeSlice(int time) { + if(!_track.containsKey(time)) { + addTimeSlice(time); + } + return _track.get(time); + } + + public List getAllTimeSlices(){ + List l = new ArrayList<>(); + for(int i : _track.keySet()) { + l.add(i); + } + return l; + } + + public boolean padExists(int time, int padnum) { + _l = getTimeSlice(time); + return _l.contains(padnum); + } + + public int padCountbyTime(int time) { + _l = getTimeSlice(time); + return _l.size(); + } + + public int padCountTotal() { + int _padcount = 0; + for(int time : _track.keySet()) { + _padcount += padCountbyTime(time); + } + return _padcount; + } + + public void flagTrack() { + _flagTrack = true; + } + + public boolean isTrackFlagged() { + return _flagTrack; + } + + public Set uniquePadList() { + List slice = new ArrayList<>(); + Set pads = new HashSet<>(); + for(int time : _track.keySet()) { + slice = getTimeSlice(time); + for(int pad : slice) { + + pads.add(pad); + + } + } + return pads; + } + + public Set PadTimeList(int pad) { + Set times = new HashSet<>(); + List allslices = getAllTimeSlices(); + List t = new ArrayList<>(); + for(int slice : allslices) { + t = getTimeSlice(slice); + if(t.contains(pad)) { + times.add(slice); + } + } + return times; + } + + public int uniquePadCountTotal() { + + return uniquePadList().size(); + + } + +} diff --git a/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/TrackDisentangler.java b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/TrackDisentangler.java new file mode 100644 index 0000000000..dea886a1b7 --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/TrackDisentangler.java @@ -0,0 +1,91 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.jlab.rec.rtpc.hit; + +import java.util.ArrayList; +import java.util.List; + +/** + * + * @author davidpayette + */ +public class TrackDisentangler { + private ReducedTrackMap RTIDMap = new ReducedTrackMap(); + private ReducedTrackMap NewTrackMap = new ReducedTrackMap(); + private ReducedTrack rtrack; + private int maxdeltat = 300; + private double maxdeltaz = 8; + private double maxdeltaphi = 0.10; + + public TrackDisentangler(HitParameters params){ + + RTIDMap = params.get_rtrackmap(); + maxdeltat = params.get_tthreshTD(); + maxdeltaz = params.get_zthreshTD(); + maxdeltaphi = params.get_phithreshTD(); + + List origtidlist = RTIDMap.getAllTrackIDs(); + for(int tid : origtidlist){ + rtrack = RTIDMap.getTrack(tid); + if(rtrack.isTrackFlagged()){ + NewTrackMap = new ReducedTrackMap(); + rtrack.sortHits(); + List hits = rtrack.getAllHits(); + for(HitVector hit : hits){ + sortHit(hit); + } + List newtidlist = NewTrackMap.getAllTrackIDs(); + List removedtracks = new ArrayList<>(); + for(int tid1 : newtidlist){ + for(int tid2 : newtidlist){ + if(tid1 != tid2 && !removedtracks.contains(tid1) && !removedtracks.contains(tid2)){ + ReducedTrack t1 = NewTrackMap.getTrack(tid1); + ReducedTrack t2 = NewTrackMap.getTrack(tid2); + HitVector h1 = t1.getLastHit(); + HitVector h2 = t2.getLastHit(); + if(Math.abs(h1.z() - h2.z()) < maxdeltaz && + (Math.abs(h1.phi() - h2.phi()) < maxdeltaphi || Math.abs(h1.phi() - h2.phi() - 2*Math.PI) < maxdeltaphi)){ + NewTrackMap.mergeTracks(tid1, tid2); + NewTrackMap.getTrack(tid1).sortHits(); + removedtracks.add(tid2); + } + } + } + } + RTIDMap.removeTrack(tid); + newtidlist = NewTrackMap.getAllTrackIDs(); + for(int tidfinal : newtidlist){ + RTIDMap.addTrack(NewTrackMap.getTrack(tidfinal)); + } + } + } + params.set_rtrackmap(RTIDMap); + + + } + + private void sortHit(HitVector hit){ + List TIDList = NewTrackMap.getAllTrackIDs(); + boolean hitsorted = false; + for(int tid : TIDList){ + ReducedTrack t = NewTrackMap.getTrack(tid); + HitVector comphit = t.getLastHit(); + if(comphit.time() - hit.time() < maxdeltat && + hit.time() < comphit.time() && + Math.abs(hit.z() - comphit.z()) < maxdeltaz && + (Math.abs(hit.phi() - comphit.phi()) < maxdeltaphi || Math.abs(hit.phi() - comphit.phi() - Math.PI * 2) < maxdeltaphi)){ + t.addHit(hit); + hitsorted = true; + } + } + if(!hitsorted){ + ReducedTrack newt = new ReducedTrack(); + newt.addHit(hit); + NewTrackMap.addTrack(newt); + } + } +} + diff --git a/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/TrackFinder.java b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/TrackFinder.java new file mode 100644 index 0000000000..599b7f9dde --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/TrackFinder.java @@ -0,0 +1,171 @@ +//Author: David Payette + +/* This code sorts pad signals which have been integrated into 120 ns time slices into tracks + * based on their relative positions in space, and how close in time the signals occur + */ + +package org.jlab.rec.rtpc.hit; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Set; +import org.jlab.detector.calib.utils.ConstantsManager; + + +public class TrackFinder { + + private TrackUtils tutil = new TrackUtils(); + private TrackMap TIDMap = new TrackMap(); + private List TIDList; + private Track track; + private ADCMap ADCMap; + private List PadList; + private int TrigWindSize; + private int StepSize = 120;//Bin Size of Dream Electronics Output + private double adcthresh = 1e-6; + private int padloopsize;// = PadList.size(); + private boolean padSorted = false; + private List padTIDlist = new ArrayList<>(); + private List padlist; + private int pad = 0; + private double adc = 0; + private int timeadjlimit = 4; + private int parenttid = -1; + private String method = "phiz"; + private int minhitcount = 5; + private double zthresh = 16; + private double phithresh = 0.16; + + public TrackFinder(HitParameters params, boolean cosmic) { + /* + *Initializations + */ + timeadjlimit = params.get_timeadjlimit(); + adcthresh = params.get_adcthresh(); + minhitcount = params.get_minhitspertrack(); + zthresh = params.get_zthreshTF(); + phithresh = params.get_phithreshTF(); + ADCMap = params.get_ADCMap(); + PadList = params.get_PadList(); + + TrigWindSize = params.get_TrigWindSize(); + padloopsize = PadList.size(); + + /* + * Main Algorithm + */ + TIMELOOP: //Loop over all times + for(int time = 0; time < TrigWindSize; time += StepSize) { //Steps of 120 up to TrigWindSize = 10000 + + PADLOOP: //Loop over all pads + for(int padindex = 0; padindex < padloopsize; padindex++) { + padSorted = false; //Flag to be set when the pad is assigned to a track + padTIDlist.clear(); //List of all TIDs assigned to the pad starts empty + pad = PadList.get(padindex); + adc = ADCMap.getADC(pad,time); + + + + if(adc > adcthresh) { //pad adc threshold check + + PadVector PadVec = params.get_padvector(pad); //initializes the x,y,z,phi for pad + TIDList = TIDMap.getAllTrackIDs(); //Retrieve list of all available TIDs + + TIDLOOP: //Loop over all Track IDs + for(int tid : TIDList) { + track = TIDMap.getTrack(tid); //Get track with current tid + + TIMECHECKLOOP: //Loop over current and former times + for(int timecheck = time; timecheck > 0 && timecheck >= time - timeadjlimit*StepSize; timecheck -= StepSize) { + padlist = track.getTimeSlice(timecheck); //Get pads assigned to current time slice + if(!padlist.contains(pad)) { //Ensures pad isn't already assigned here + PADCHECKLOOP: //Loop over pads + for(int checkpad : padlist) { + PadVector checkpadvec = params.get_padvector(checkpad); + if(tutil.comparePads(PadVec, checkpadvec, method, cosmic, zthresh, phithresh)) { //compares the position of two pads + track.addPad(time, pad); //assign pad to track + padSorted = true; //flag set + padTIDlist.add(tid); //track the TID assigned + break TIMECHECKLOOP; //no need to continue checking previous times + } //END PAD COMPARE + + } //END PADCHECKLOOP + + } else {//pad is somehow in this time slice already so lets go ahead and add it to the current time slice + track.addPad(time, pad); + padSorted = true; + padTIDlist.add(tid); + break TIMECHECKLOOP; + } + + } //END TIMECHECKLOOP + + } //END TIDLOOP + + if(!padSorted) { //we need a new TID if we get here, the pad was never assigned an ID + TIDMap.addTrack(new Track(time,pad)); + } + + if(padTIDlist.size()>1) { //if a pad gets more than 1 ID let's merge the IDs + for(int tidtemp : padTIDlist) { + if(tidtemp == padTIDlist.get(0)) { + parenttid = padTIDlist.get(0); + } else { + TIDMap.mergeTracks(parenttid, tidtemp); + } + } + } + + } //END ADC THRESH CHECK + + } //END PADLOOP + + } //END TIMELOOP + + //END MAIN ALGORITHM + + /* + * Clean up and flag tracks + */ + + for(int tid : TIDMap.getAllTrackIDs()) { //We need to remove tracks with not enough pads to save time later + Track tempt = TIDMap.getTrack(tid); + if(tempt.uniquePadCountTotal() < minhitcount) { + TIDMap.removeTrack(tid); + } + } + + + if(!cosmic){ + //Flag crossing tracks + int tmax = 0; + int tmin = 0; + for(int tid : TIDMap.getAllTrackIDs()) { + Track t = TIDMap.getTrack(tid); + for(int pad : t.uniquePadList()){ + tmax = 0; + tmin = 1000000; + for(int time : t.PadTimeList(pad)){ + if(time > tmax) tmax = time; + if(time < tmin) tmin = time; + } + if(tmax - tmin > 1000){ + t.flagTrack(); + break; + } + } + } + } + + + /* + * Output + */ + + + params.set_trackmap(TIDMap); + + } + +} diff --git a/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/TrackHitReco.java b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/TrackHitReco.java new file mode 100644 index 0000000000..2c4999876a --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/TrackHitReco.java @@ -0,0 +1,173 @@ +//Author: David Payette and Nate Dzbenski + +/* This code takes the time-reduced tracks produced by the Time Average, as well as the original hits + * and uses a fit formula from garfield++ to calculate the hit's position in the drift region + * based on the time of the signal. We use the original hits to see how well the formula performs + * when we include factors such as time shifts and non-uniform magnetic fields + */ + +package org.jlab.rec.rtpc.hit; + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + + +public class TrackHitReco { + + //MAGBOLTZ PARAMETERS DO NOT TOUCH + /*final private double a_t1 = -2.48491E-4; + final private double a_t2 = 2.21413E-4; + final private double a_t3 = -3.11195E-3; + final private double a_t4 = -2.75206E-1; + final private double a_t5 = 1.74281E3; + private double a_t; + + final private double b_t1 = 2.48873E-5; + final private double b_t2 = -1.19976E-4; + final private double b_t3 = -3.75962E-3; + final private double b_t4 = 5.33100E-2; + final private double b_t5 = -1.25647E2; + private double b_t; + + final private double a_phi1 = -3.32718E-8; + final private double a_phi2 = 1.92110E-7; + final private double a_phi3 = 2.16919E-6; + final private double a_phi4 = -8.10207E-5; + final private double a_phi5 = 1.68481E-1; + private double a_phi; + + final private double b_phi1 = -3.23019E-9; + final private double b_phi2 = -6.92075E-8; + final private double b_phi3 = 1.24731E-5; + final private double b_phi4 = 2.57684E-5; + final private double b_phi5 = 2.10680E-2; + private double b_phi; + + final private double t_2GEM2 = 296.082; + final private double t_2GEM3 = 296.131; + final private double t_2PAD = 399.09; + final private double t_gap = t_2GEM2 + t_2GEM3 + t_2PAD; + + final private double phi_2GEM2 = 0.0492538; + final private double phi_2GEM3 = 0.0470817; + final private double phi_2PAD = 0.0612122; + final private double phi_gap = phi_2GEM2 + phi_2GEM3 + phi_2PAD; + */ + + private double larget; + private double smallt; + private double tcathode; + private double tdiff; + private double Time; + private int cellID; + + private double drifttime; + private double r_rec; + private double dphi; + private double phi_rec; + private double x_rec; + private double y_rec; + + private double[] t_offset = new double[5]; + private double toffset = 0; + private double[] t_max = new double[5]; + private double tmax = 0; + private double[] a_phi = new double[5]; + private double aphi = 0; + private double bphi = 0; + private double[] b_phi = new double[5]; + private double[] phi_gap = new double[5]; + private double phigap = 0; + private double tl = 0; + private double tp = 0; + private double tr = 0; + + + private boolean _cosmic = false; + + public TrackHitReco(HitParameters params, List rawHits, boolean cosmic) { + + _cosmic = cosmic; + t_offset = params.get_toffparms(); + t_max = params.get_tmaxparms(); + a_phi = params.get_aphiparms(); + b_phi = params.get_bphiparms(); + phi_gap = params.get_phigapparms(); + tl = params.get_tl(); + tp = params.get_tp(); + tr = params.get_tr(); + tcathode = params.get_tcathode(); + HashMap> recotrackmap = new HashMap<>(); + ReducedTrackMap RTIDMap = params.get_rtrackmap(); + List tids = RTIDMap.getAllTrackIDs(); + + for(int TID : tids) { + double adc = 0; + ReducedTrack track = RTIDMap.getTrack(TID); + track.sortHits(); + smallt = track.getSmallT(); + larget = track.getLargeT(); + + tdiff = tcathode - larget; + recotrackmap.put(TID, new ArrayList<>()); + List allhits = track.getAllHits(); + + for(HitVector hit : allhits) { + adc += hit.adc(); + cellID = hit.pad(); + Time = hit.time(); + + if(!cosmic) Time += tdiff; + + // find reconstructed position of ionization from Time info + drifttime = Time; + r_rec = get_r_rec(hit.z(),drifttime); //in mm + dphi = get_dphi(hit.z(),r_rec); // in rad + phi_rec=hit.phi()-dphi; + if(cosmic) phi_rec = hit.phi(); + + if(phi_rec<0.0) { + phi_rec+=2.0*Math.PI; + } + if(phi_rec>2.0*Math.PI){ + phi_rec-=2.0*Math.PI; + } + + // x,y,z pos of reconstructed track + x_rec=r_rec*(Math.cos(phi_rec)); + y_rec=r_rec*(Math.sin(phi_rec)); + + recotrackmap.get(TID).add(new RecoHitVector(cellID,x_rec,y_rec,hit.z(),tdiff,Time,hit.adc())); + } + } + + params.set_recotrackmap(recotrackmap); + } + + private double get_rec_coef(double[] parms, double z2) { + double z = z2/1000; + return parms[4]*z*z*z*z + parms[3]*z*z*z + parms[2]*z*z + parms[1]*z + parms[0]; + } + + private double get_r_rec(double z,double t){ + toffset = get_rec_coef(t_offset,z) + tl + tp + tr; + tmax = get_rec_coef(t_max,z); + return Math.sqrt((70*70*(1-((t-toffset)/tmax)))+(30*30*((t-toffset)/tmax))); + } + + private double get_dphi(double z, double r){ + aphi = get_rec_coef(a_phi,z); + bphi = get_rec_coef(b_phi,z); + phigap = get_rec_coef(phi_gap,z); + return aphi*(7-r/10)+bphi*(7-r/10)*(7-r/10) + phigap; // in rad + } + + + +} + + + + diff --git a/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/TrackMap.java b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/TrackMap.java new file mode 100644 index 0000000000..1a7b099d60 --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/TrackMap.java @@ -0,0 +1,60 @@ +package org.jlab.rec.rtpc.hit; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.HashMap; + +public class TrackMap { + + private HashMap _map; + private int _trackID = 0; + + public TrackMap() { + _map = new HashMap(); + } + + public void addTrack(Track t) { + _trackID++; + _map.put(_trackID, t); + } + + public Track getTrack(int trackID) { + if(!_map.containsKey(trackID)) { + addTrack(new Track()); + } + return _map.get(trackID); + } + + public void updateTrack(int trackID, Track t) { + _map.put(trackID, t); + } + + public void removeTrack(int trackID) { + _map.remove(trackID); + } + + public List getAllTrackIDs() { + List l = new ArrayList(); + for(int i : _map.keySet()) { + if(!l.contains(i)) { l.add(i);} + } + return l; + } + + public int getLastTrackID() { + return _trackID; + } + + public void mergeTracks(int trackIDparent, int trackID) { + Track child = getTrack(trackID); + List l = child.getAllTimeSlices(); + Track parent = getTrack(trackIDparent); + for(int time : l) { + parent.addTimeSlice(time,child.getTimeSlice(time)); + } + //updateTrack(trackIDparent, parent); + removeTrack(trackID); + } + +} diff --git a/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/TrackUtils.java b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/TrackUtils.java new file mode 100644 index 0000000000..b71efe2801 --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/hit/TrackUtils.java @@ -0,0 +1,53 @@ +package org.jlab.rec.rtpc.hit; + +public class TrackUtils { + private double adjthresh = 16; + private double PhiDelta = 16; + private double ZDelta = 36; + //private double phithresh = 0.16; + //private double zthresh = 16; + private double zthresh = 200; + private double phithresh = 7; + + public TrackUtils() {} + + public boolean comparePads(PadVector p1, PadVector p2, String Method, boolean cosmic, double dz, double dphi) { + if(cosmic){ + zthresh = 200; + phithresh = 7; + }else{ + zthresh = dz; + phithresh = dphi; + } + if(Method == "ellipse") {return ellipseMethod(p1, p2);} + if(Method == "phiz") {return phizMethod(p1,p2);} + else return false; + } + + private boolean ellipseMethod(PadVector p1, PadVector p2) { + double p1x = p1.x(); + double p1y = p1.y(); + double p1z = p1.z(); + double p2x = p2.x(); + double p2y = p2.y(); + double p2z = p2.z(); + double EllipseDeltax = Math.abs(p1x-p2x)*Math.abs(p1x-p2x); + double EllipseDeltay = Math.abs(p1y-p2y)*Math.abs(p1y-p2y); + double EllipseDeltaz = Math.abs(p1z-p2z)*Math.abs(p1z-p2z); + double EllipseTotal = ((EllipseDeltax+EllipseDeltay)/PhiDelta) + (EllipseDeltaz/ZDelta); + if(EllipseTotal < adjthresh) return true; + return false; + } + + private boolean phizMethod(PadVector p1, PadVector p2) { + double p1phi = p1.phi(); + double p2phi = p2.phi(); + double p1z = p1.z(); + double p2z = p2.z(); + double phidiff = p2phi-p1phi; + double zdiff = Math.abs(p1z-p2z); + //System.out.println(p1phi + " " + p2phi + " " + (p1phi - p2phi)); + return ((Math.abs(phidiff) + + + + +org.jlab.rec.rtpc.hit + + +
Author:
ziegler
+ + \ No newline at end of file diff --git a/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/package.html b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/package.html new file mode 100644 index 0000000000..f0cd21cb47 --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/rec/rtpc/package.html @@ -0,0 +1,14 @@ + + + + + +org.jlab.rec.rtpc + + +
Author:
ziegler
+ + \ No newline at end of file diff --git a/reconstruction/rtpc/src/main/java/org/jlab/service/rtpc/RTPCEngine.java b/reconstruction/rtpc/src/main/java/org/jlab/service/rtpc/RTPCEngine.java new file mode 100644 index 0000000000..c021681903 --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/service/rtpc/RTPCEngine.java @@ -0,0 +1,196 @@ +package org.jlab.service.rtpc; + +import java.io.File; +import java.io.FileNotFoundException; + + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.jlab.clas.reco.EngineProcessor; + +import org.jlab.clas.reco.ReconstructionEngine; +import org.jlab.io.base.DataBank; +import org.jlab.io.base.DataEvent; +import org.jlab.io.hipo.HipoDataSource; +import org.jlab.io.hipo.HipoDataSync; +import org.jlab.rec.rtpc.banks.HitReader; +import org.jlab.rec.rtpc.banks.RecoBankWriter; +import org.jlab.rec.rtpc.hit.Hit; +import org.jlab.rec.rtpc.hit.HitParameters; +import org.jlab.rec.rtpc.hit.SignalSimulation; +import org.jlab.rec.rtpc.hit.TimeAverage; +import org.jlab.rec.rtpc.hit.TrackDisentangler; +import org.jlab.rec.rtpc.hit.TrackFinder; +import org.jlab.rec.rtpc.hit.TrackHitReco; +import org.jlab.rec.rtpc.hit.HelixFitTest; + + + + +public class RTPCEngine extends ReconstructionEngine{ + + + public RTPCEngine() { + super("RTPC","davidp","3.0"); + } + + private boolean simulation = true; + private boolean cosmic = false; + private int fitToBeamline = 1; + + @Override + public boolean init() { + String sim = this.getEngineConfigString("rtpcSimulation"); + String cosm = this.getEngineConfigString("rtpcCosmic"); + String beamfit = this.getEngineConfigString("rtpcBeamlineFit"); + //System.out.println(sim + " " + cosm + " " + beamfit); + + if(sim != null){ + simulation = Boolean.valueOf(sim); + } + + if(cosm != null){ + cosmic = Boolean.valueOf(cosm); + } + + if(beamfit != null){ + fitToBeamline = Boolean.valueOf(beamfit)?1:0; + } + + String[] rtpcTables = new String[]{ + "/calibration/rtpc/time_offsets", + "/calibration/rtpc/gain_balance", + "/calibration/rtpc/time_parms", + "/calibration/rtpc/recon_parms" + }; + + requireConstants(Arrays.asList(rtpcTables)); + + return true; + } + + + + @Override + public boolean processDataEvent(DataEvent event) { + + HitParameters params = new HitParameters(); + + HitReader hitRead = new HitReader(); + hitRead.fetch_RTPCHits(event,simulation,cosmic);//boolean is for simulation + + List hits = new ArrayList<>(); + + hits = hitRead.get_RTPCHits(); + + if(hits==null || hits.size()==0) { + return true; + } + + int runNo = 10; + + if(event.hasBank("RUN::config")==true){ + DataBank bank = event.getBank("RUN::config"); + runNo = bank.getInt("run", 0); + if (runNo<=0) { + System.err.println("RTPCEngine: got run <= 0 in RUN::config, skipping event."); + return false; + } + } + + + if(event.hasBank("RTPC::adc")){ + params.init(this.getConstantsManager(), runNo); + + SignalSimulation SS = new SignalSimulation(hits,params,simulation); //boolean is for simulation + + //Sort Hits into Tracks at the Readout Pads + TrackFinder TF = new TrackFinder(params,cosmic); + //Calculate Average Time of Hit Signals + TimeAverage TA = new TimeAverage(params); + //Disentangle Crossed Tracks + TrackDisentangler TD = new TrackDisentangler(params); + //Reconstruct Hits in Drift Region + TrackHitReco TR = new TrackHitReco(params,hits,cosmic); + //Helix Fit Tracks to calculate Track Parameters + HelixFitTest HF = new HelixFitTest(params,fitToBeamline); + + RecoBankWriter writer = new RecoBankWriter(); + DataBank recoBank = writer.fillRTPCHitsBank(event,params); + DataBank trackBank = writer.fillRTPCTrackBank(event,params); + + event.appendBank(recoBank); + event.appendBank(trackBank); + + + } + else{ + return true; + } + return true; + } + + public static void main(String[] args){ + + System.setProperty("CLAS12DIR", "/Users/davidpayette/Desktop/newrtpcbranch/clas12-offline-software"); + double starttime = System.nanoTime(); + + File f = new File("/Users/davidpayette/Desktop/SignalStudies/sig.txt"); + f.delete(); + f = new File("/Users/davidpayette/Desktop/SignalStudies/trackenergy.txt"); + f.delete(); + f = new File("/Users/davidpayette/Desktop/SignalStudies/timespectra.txt"); + f.delete(); + f = new File("/Users/davidpayette/Desktop/SignalStudies/sigafter.txt"); + f.delete(); + f = new File("/Users/davidpayette/Desktop/SignalStudies/sigTF.txt"); + f.delete(); + f = new File("/Users/davidpayette/Desktop/SignalStudies/timeenergy.txt"); + f.delete(); + f = new File("/Users/davidpayette/Desktop/SignalStudies/signalbins.txt"); + f.delete(); + + + //String inputFile = "/Users/davidpayette/Desktop/6b.2.0/myClara/good.hipo"; + //String inputFile = "/Users/davidpayette/Desktop/6b.2.0/myClara/cosmics.hipo"; + //String inputFile = "/Users/davidpayette/Desktop/6b.2.0/myClara/ctest.hipo"; + //String inputFile = "/Users/davidpayette/Desktop/6b.2.0/myClara/new40p.hipo"; + //String inputFile = "/Users/davidpayette/Desktop/rtpcbranch/1ep.hipo"; + //String inputFile = "/Users/davidpayette/Desktop/6b.2.0/myClara/plugins/clas12/340_40p.hipo"; + String inputFile = "/Users/davidpayette/Desktop/newrtpcbranch/10p13120.hipo"; + String outputFile = "/Users/davidpayette/Desktop/6b.2.0/myClara/out_cosmic.hipo"; + + System.err.println(" \n[PROCESSING FILE] : " + inputFile); + + RTPCEngine en = new RTPCEngine(); + //en.init(); + + + EngineProcessor processor = new EngineProcessor(); + processor.addEngine("RTPC", en); + processor.processFile(inputFile, outputFile); + + /* + HipoDataSource reader = new HipoDataSource(); + HipoDataSync writer = reader.createWriter(); + + reader.open(inputFile); + writer.open(outputFile); + //System.out.println("starting " + starttime); + int eventcount = 0; + int eventselect = 144; //144 + while(reader.hasEvent()){ + DataEvent event = reader.getNextEvent(); + //if(eventcount == eventselect){ + en.processDataEvent(event); + writer.writeEvent(event); + //}else if(eventcount > eventselect) break; + eventcount ++; + } + + writer.close(); + */ + System.out.println("finished " + (System.nanoTime() - starttime)*Math.pow(10,-9)); + } +} diff --git a/reconstruction/rtpc/src/main/java/org/jlab/service/rtpc/package-info.java b/reconstruction/rtpc/src/main/java/org/jlab/service/rtpc/package-info.java new file mode 100644 index 0000000000..fb4baf2083 --- /dev/null +++ b/reconstruction/rtpc/src/main/java/org/jlab/service/rtpc/package-info.java @@ -0,0 +1,8 @@ +/** + * + */ +/** + * @author ziegler + * + */ +package org.jlab.service.rtpc; \ No newline at end of file diff --git a/reconstruction/tof/pom.xml b/reconstruction/tof/pom.xml index 211228959e..111d4eeae6 100644 --- a/reconstruction/tof/pom.xml +++ b/reconstruction/tof/pom.xml @@ -26,7 +26,7 @@ org.jlab.clas clas12rec ../../parent/pom.xml - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT @@ -47,7 +47,7 @@ org.jlab.clas clas-jcsg - 6.3.1-SNAPSHOT + 6.5.3-SNAPSHOT diff --git a/reconstruction/tof/src/main/java/org/jlab/rec/tof/banks/ctof/HitReader.java b/reconstruction/tof/src/main/java/org/jlab/rec/tof/banks/ctof/HitReader.java index e3efcf6b99..bfdea2d7fc 100644 --- a/reconstruction/tof/src/main/java/org/jlab/rec/tof/banks/ctof/HitReader.java +++ b/reconstruction/tof/src/main/java/org/jlab/rec/tof/banks/ctof/HitReader.java @@ -239,7 +239,7 @@ private List matchHitsToCVTTrk(List CTOFhits, CTOFGeant4Factory ctofDe // System.out.println(trkHit.getPaddle() + " " + dir); if(dir>0) { // create the new track updating the path to the intersection point - Track ctofTrkHit = new Track(trk.getId(),trk.getLine(),trk.getPath()+trk.getLine().origin().distance(hit.mid())); + Track ctofTrkHit = new Track(trk.getId(),trk.getLine(),trk.getPath()); ctofTrkHit.setHit(trkHit); // if map entry for the given paddle doesn't already exist, add it if(!trkHitsMap.hasItem(trkHit.getPaddle())) { @@ -282,7 +282,9 @@ private List matchHitsToCVTTrk(List CTOFhits, CTOFGeant4Factory ctofDe // get the coordinates for the track hit, which is defined // as the mid-point between its entrance and its exit from // the bar - ctofHit.set_TrkPosition(new Point3D(trkHit.mid().x,trkHit.mid().y, trkHit.mid().z)); + ctofHit.set_TrkPosition(new Point3D((matchedTrk.getLine().origin().x+matchedTrk.getLine().end().x)/2, + (matchedTrk.getLine().origin().y+matchedTrk.getLine().end().y)/2, + (matchedTrk.getLine().origin().z+matchedTrk.getLine().end().z)/2)); // compute the local y at the middle of the bar : // ---------------------------------------------- Point3D origPaddleLine = ctofHit.get_paddleLine().origin(); diff --git a/reconstruction/tof/src/main/java/org/jlab/rec/tof/banks/ctof/RecoBankWriter.java b/reconstruction/tof/src/main/java/org/jlab/rec/tof/banks/ctof/RecoBankWriter.java index ece8cc2628..afb2d9d865 100644 --- a/reconstruction/tof/src/main/java/org/jlab/rec/tof/banks/ctof/RecoBankWriter.java +++ b/reconstruction/tof/src/main/java/org/jlab/rec/tof/banks/ctof/RecoBankWriter.java @@ -70,6 +70,8 @@ public DataBank fillRecHitsBank(DataEvent event, List hitlist) { } for (int i = 0; i < hitlist.size(); i++) { bank.setShort("id", i, (short) hitlist.get(i).get_Id()); + bank.setByte("sector", i, (byte) hitlist.get(i).get_Sector()); + bank.setByte("layer", i, (byte) hitlist.get(i).get_Panel()); bank.setShort("component", i, (short) hitlist.get(i).get_Paddle()); int status = 0; // if (Integer.parseInt(hitlist.get(i).get_StatusWord()) == 1111) { @@ -124,6 +126,8 @@ public DataBank fillClustersBank(DataEvent event, List cluslist) { } for (int i = 0; i < cluslist.size(); i++) { bank.setShort("id", i, (short) cluslist.get(i).get_Id()); + bank.setByte("sector", i, (byte) cluslist.get(i).get_Sector()); + bank.setByte("layer", i, (byte) cluslist.get(i).get_Panel()); bank.setShort("component", i, (short) cluslist.get(i).get(0).get_Paddle()); // paddle id of hit with lowest paddle id in cluster [Check the sorting!!!] int status = 0; if (Integer.parseInt(cluslist.get(i).get_StatusWord()) == 1111) { diff --git a/reconstruction/tof/src/main/java/org/jlab/rec/tof/banks/ctof/TrackReader.java b/reconstruction/tof/src/main/java/org/jlab/rec/tof/banks/ctof/TrackReader.java index 3004e0a6c2..261412521d 100644 --- a/reconstruction/tof/src/main/java/org/jlab/rec/tof/banks/ctof/TrackReader.java +++ b/reconstruction/tof/src/main/java/org/jlab/rec/tof/banks/ctof/TrackReader.java @@ -7,6 +7,7 @@ import org.jlab.io.base.DataEvent; import eu.mihosoft.vrl.v3d.Vector3d; +import org.jlab.detector.base.DetectorType; import org.jlab.rec.tof.track.Track; /** @@ -25,30 +26,34 @@ public ArrayList fetch_Trks(DataEvent event) { ArrayList Tracks = new ArrayList(); - if (event.hasBank("CVTRec::Tracks") == false) { + if (event.hasBank("CVTRec::Trajectory") == false) { // System.err.println("there is no CVT bank "); return Tracks; } else { - DataBank bank = event.getBank("CVTRec::Tracks"); + DataBank bank = event.getBank("CVTRec::Trajectory"); int rows = bank.rows(); for (int i = 0; i < rows; i++) { - int id = bank.getShort("ID", i); - double x = bank.getFloat("c_x", i); - double y = bank.getFloat("c_y", i); - double z = bank.getFloat("c_z", i); - double ux = bank.getFloat("c_ux", i); - double uy = bank.getFloat("c_uy", i); - double uz = bank.getFloat("c_uz", i); - double path = bank.getFloat("pathlength", i); - - Line3d line = new Line3d(new Vector3d(x,y,z), new Vector3d(x+5*ux,y+5*uy, z+5*uz)); - Track track = new Track(id,line,path); - Tracks.add(track); + if(bank.getByte("detector", i)==DetectorType.CTOF.getDetectorId()) { + int id = bank.getShort("id", i); + double x = bank.getFloat("x", i); + double y = bank.getFloat("y", i); + double z = bank.getFloat("z", i); + double theta = bank.getFloat("theta", i); + double phi = bank.getFloat("phi", i); + double ux = Math.sin(theta)*Math.cos(phi); + double uy = Math.sin(theta)*Math.sin(phi); + double uz = Math.cos(theta); + double path = bank.getFloat("path", i); + Line3d line = new Line3d(new Vector3d(x-10*ux,y-10*uy,z-10*uz), new Vector3d(x+10*ux,y+10*uy,z+10*uz)); + Track track = new Track(id,line,path); + Tracks.add(track); + } } } return Tracks; } + } diff --git a/reconstruction/tof/src/main/java/org/jlab/rec/tof/banks/ftof/HitReader.java b/reconstruction/tof/src/main/java/org/jlab/rec/tof/banks/ftof/HitReader.java index 54973b6624..615361ec39 100644 --- a/reconstruction/tof/src/main/java/org/jlab/rec/tof/banks/ftof/HitReader.java +++ b/reconstruction/tof/src/main/java/org/jlab/rec/tof/banks/ftof/HitReader.java @@ -73,7 +73,8 @@ public void fetch_Hits(DataEvent event, long timeStamp, FTOFGeant4Factory geomet IndexedTable constants6, IndexedTable constants7, IndexedTable constants8, - IndexedTable constants9) {/* + IndexedTable constants9, + IndexedTable constants10) {/* 0: "/calibration/ftof/attenuation"), 1: "/calibration/ftof/effective_velocity"), 2: "/calibration/ftof/time_offsets"), @@ -83,7 +84,8 @@ public void fetch_Hits(DataEvent event, long timeStamp, FTOFGeant4Factory geomet 6: "/calibration/ftof/tdc_conv"), 7: "/calibration/ftof/time_jitter"), 8: "/calibration/ftof/time_walk_pos"), - 9: "/calibration/ftof/fadc_offset") ); + 9: "/calibration/ftof/time_walk_exp"), + 10:"/calibration/ftof/fadc_offset") ); */ _numTrks = tracks.size(); @@ -91,7 +93,7 @@ public void fetch_Hits(DataEvent event, long timeStamp, FTOFGeant4Factory geomet BaseHitReader hitReader = new BaseHitReader(); IMatchedHit MH = this; - List hitList = hitReader.get_MatchedHits(event, MH, triggerPhase, constants6, constants9); + List hitList = hitReader.get_MatchedHits(event, MH, triggerPhase, constants6, constants10); if (hitList.size() == 0) { // System.err.println("there is no FTOF bank "); @@ -184,7 +186,8 @@ public void fetch_Hits(DataEvent event, long timeStamp, FTOFGeant4Factory geomet constants3, constants5, constants6, - constants8); + constants8, + constants9); // DetHits.get(hit.get_Panel()-1).add(hit); } // List unique_hits = this.removeDuplicatedHits(updated_hits); diff --git a/reconstruction/tof/src/main/java/org/jlab/rec/tof/cluster/ftof/ClusterMatcher.java b/reconstruction/tof/src/main/java/org/jlab/rec/tof/cluster/ftof/ClusterMatcher.java index 85e6a42fdf..5c0541cca8 100644 --- a/reconstruction/tof/src/main/java/org/jlab/rec/tof/cluster/ftof/ClusterMatcher.java +++ b/reconstruction/tof/src/main/java/org/jlab/rec/tof/cluster/ftof/ClusterMatcher.java @@ -3,6 +3,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Collections; +import org.jlab.clas.pdg.PhysicsConstants; import org.jlab.geom.prim.Vector3D; import org.jlab.io.base.DataBank; @@ -294,14 +295,14 @@ private double[] get_CorrectedHitTime(Cluster clus1A, Cluster clus1B) { // defined double delta_t1a = this.calc_deltaT(clus1A.get_Panel(), CntrInPan1aWithEmax); - double delta_t1b = this.calc_deltaT(clus1A.get_Panel(), + double delta_t1b = this.calc_deltaT(clus1B.get_Panel(), CntrInPan1bWithEmax); double term1 = clus1B.get_t() / delta_t1b; double term3 = 1. / delta_t1a + 1. / delta_t1b; for (int i = 0; i < 3; i++) { if (this._deltaPathLen[i] > 0) { - term2[i] = (clus1A.get_t() - this._deltaPathLen[i] / Beta) / delta_t1a; + term2[i] = (clus1A.get_t() - this._deltaPathLen[i] / Beta/ PhysicsConstants.speedOfLight()) / delta_t1a; tCorr[i] = (term1 + term2[i]) / term3; } } diff --git a/reconstruction/tof/src/main/java/org/jlab/rec/tof/hit/AHit.java b/reconstruction/tof/src/main/java/org/jlab/rec/tof/hit/AHit.java index b3d8cdc3ac..a0c8414e5c 100644 --- a/reconstruction/tof/src/main/java/org/jlab/rec/tof/hit/AHit.java +++ b/reconstruction/tof/src/main/java/org/jlab/rec/tof/hit/AHit.java @@ -447,6 +447,18 @@ public void set_TDCbankHitIdx2(int _TDCbankHitIdx2) { * @param TW02 * @param TW11 * @param TW12 + * @param TW1P + * @param TW2P + * @param TW0E + * @param TW1E + * @param TW2E + * @param TW3E + * @param TW4E + * @param HPOSa + * @param HPOSb + * @param HPOSc + * @param HPOSd + * @param HPOSe * @param lambda1 * @param lambda2 * @param yOffset @@ -475,6 +487,7 @@ public void set_TDCbankHitIdx2(int _TDCbankHitIdx2) { */ public void set_HitParams(int superlayer, double TW01, double TW02, double TW11, double TW12, double TW1P, double TW2P, + double TW0E, double TW1E, double TW2E, double TW3E, double TW4E, double HPOSa, double HPOSb, double HPOSc, double HPOSd, double HPOSe, double lambda1, double lambda2, double yOffset, double v1, double v2, double v1Unc, double v2Unc, @@ -500,9 +513,9 @@ public void set_HitParams(int superlayer, double TW01, double TW02, case "1111": // Good: TDC1, TDC2, ADC1, ADC2 // 1. Compute time-walk corrections: - this.set_timeWalk1(this.calc_timeWalk(TW01, TW11, + this.set_timeWalk1(this.calc_timeWalk(TW0E, TW01, TW11, (int) (this.get_ADC1() - PED1))); - this.set_timeWalk2(this.calc_timeWalk(TW02, TW12, + this.set_timeWalk2(this.calc_timeWalk(TW0E, TW02, TW12, (int) (this.get_ADC2() - PED2))); // 2. Compute corrected hit times & errors: t12 = this.calc_t12(paddle2paddle, timeOffset, triggerPhase, LSBConv, RFPad); @@ -548,6 +561,8 @@ public void set_HitParams(int superlayer, double TW01, double TW02, this.get_Energy2(), this.get_Energy2Unc(), this.get_lambda2(), this.get_lambda2Unc()); this.set_EnergyUnc(eErr); + // 7. add new TW exponential correction + this.set_t(this.get_t()-this.calc_TWexp(this.get_Energy(), TW0E, TW1E, TW2E, TW3E, TW4E)); break; @@ -569,9 +584,9 @@ public void set_HitParams(int superlayer, double TW01, double TW02, this.setMissingADC(y, PED1, PED2); // 3. Compute time-walk corrections (with the estimated ADC1,2 // value): - this.set_timeWalk1(this.calc_timeWalk(TW01, TW11, + this.set_timeWalk1(this.calc_timeWalk(TW0E, TW01, TW11, (int) (this.get_ADC1() - PED1))); - this.set_timeWalk2(this.calc_timeWalk(TW02, TW12, + this.set_timeWalk2(this.calc_timeWalk(TW0E, TW02, TW12, (int) (this.get_ADC2() - PED2))); // 4. Compute corrected hit times & uncertainties: t12 = this.calc_t12(paddle2paddle, timeOffset, triggerPhase, LSBConv, RFPad); @@ -628,15 +643,17 @@ public void set_HitParams(int superlayer, double TW01, double TW02, // 7.1. Compute the uncertainty in y this.set_yUnc(this.calc_yUnc(status, v1, v2, v1Unc, v2Unc, ADC1Err, ADC2Err)); + // 8. add new TW exponential correction + this.set_t(this.get_t()-this.calc_TWexp(this.get_Energy(), TW0E, TW1E, TW2E, TW3E, TW4E)); break; case "1011": case "1110": // Good: ADC1, ADC2 Missing: TDC1 or TDC2 // 1. Compute time-walk corrections: - this.set_timeWalk1(this.calc_timeWalk(TW01, TW11, + this.set_timeWalk1(this.calc_timeWalk(TW0E, TW01, TW11, (int) (this.get_ADC1() - PED1))); - this.set_timeWalk2(this.calc_timeWalk(TW02, TW12, + this.set_timeWalk2(this.calc_timeWalk(TW0E, TW02, TW12, (int) (this.get_ADC2() - PED2))); // 2. Determine hit coordinate from tracking or from ADC log ratio @@ -720,6 +737,8 @@ public void set_HitParams(int superlayer, double TW01, double TW02, this.get_Energy2(), this.get_Energy2Unc(), this.get_lambda2(), this.get_lambda2Unc()); this.set_EnergyUnc(eErr); + // 6. add new TW exponential correction + this.set_t(this.get_t()-this.calc_TWexp(this.get_Energy(), TW0E, TW1E, TW2E, TW3E, TW4E)); break; @@ -743,9 +762,9 @@ public void set_HitParams(int superlayer, double TW01, double TW02, // 2. Compute the missing ADC this.setMissingADC(y, PED1, PED2); // 3. Compute time-walk corrections (with the estimated ADC value): - this.set_timeWalk1(this.calc_timeWalk(TW01, TW11, + this.set_timeWalk1(this.calc_timeWalk(TW0E, TW01, TW11, (int) (this.get_ADC1() - PED1))); - this.set_timeWalk2(this.calc_timeWalk(TW02, TW12, + this.set_timeWalk2(this.calc_timeWalk(TW0E, TW02, TW12, (int) (this.get_ADC2() - PED2))); // 4. Compute corrected hit times & uncertainties: t12 = this.calc_t12(paddle2paddle, timeOffset, triggerPhase, LSBConv, RFPad); @@ -818,6 +837,8 @@ public void set_HitParams(int superlayer, double TW01, double TW02, this.get_lambda2Unc()); this.set_EnergyUnc(eErr); } + // 7. add new TW exponential correction + this.set_t(this.get_t()-this.calc_TWexp(this.get_Energy(), TW0E, TW1E, TW2E, TW3E, TW4E)); break; } @@ -996,8 +1017,9 @@ private double calc_missingADCUnc(double ADC1Err, double ADC2Err) { return err; } - private double calc_timeWalk(double A, double B, int ADC) { - double tw = A / Math.pow((double) ADC, B); + private double calc_timeWalk(double E, double A, double B, int ADC) { + // E: first constants from time_wal_exp table to enable/disable standard TW correction + double tw =(1-E)*(A / Math.pow((double) ADC, B)); return tw; } @@ -1256,6 +1278,24 @@ private double calc_TWpos(double y, double tw1pos, double tw2pos) { return tw1pos*Math.pow(y, 2)+tw2pos*y; } + /** + * Calculate new TW correction for FTOF + * @param energy hit energy deposition + * @param tw0e activate new TW correction (0) or old (1) + * @param tw1e first correction parameter + * @param tw2e second correction parameter, currently not used + * @param tw3e third correction parameter, currently not used + * @param tw4e fourth correction parameter, currently not used + * @return time offset in ns + */ + private double calc_TWexp(double energy, double tw0e, double tw1e, double tw2e, double tw3e, double tw4e) { + double twexp = 0; + if(energy>0) { + twexp = tw0e*tw1e*Math.exp(tw2e*energy)+tw3e/energy; + } + return twexp; + } + /** * Calculate position dependent correction to timing offsets * Currently used for CTOF diff --git a/reconstruction/tof/src/main/java/org/jlab/rec/tof/hit/IGetCalibrationParams.java b/reconstruction/tof/src/main/java/org/jlab/rec/tof/hit/IGetCalibrationParams.java index 120fcfbd95..f5ba7292ce 100644 --- a/reconstruction/tof/src/main/java/org/jlab/rec/tof/hit/IGetCalibrationParams.java +++ b/reconstruction/tof/src/main/java/org/jlab/rec/tof/hit/IGetCalibrationParams.java @@ -18,6 +18,16 @@ public interface IGetCalibrationParams { public double TW2P(IndexedTable tab); + public double TW0E(IndexedTable tab); + + public double TW1E(IndexedTable tab); + + public double TW2E(IndexedTable tab); + + public double TW3E(IndexedTable tab); + + public double TW4E(IndexedTable tab); + public double HPOSa(IndexedTable tab); public double HPOSb(IndexedTable tab); diff --git a/reconstruction/tof/src/main/java/org/jlab/rec/tof/hit/ctof/Hit.java b/reconstruction/tof/src/main/java/org/jlab/rec/tof/hit/ctof/Hit.java index 3c8c35ac94..2703299091 100644 --- a/reconstruction/tof/src/main/java/org/jlab/rec/tof/hit/ctof/Hit.java +++ b/reconstruction/tof/src/main/java/org/jlab/rec/tof/hit/ctof/Hit.java @@ -77,7 +77,12 @@ public void set_HitParameters(int superlayer, double TW1U = this.TW11(null); double TW1D = this.TW12(null); double TW1P = this.TW1P(null); - double TW2P = this.TW2P(null); + double TW2P = this.TW2P(null); + double TW0E = this.TW0E(null); + double TW1E = this.TW1E(null); + double TW2E = this.TW2E(null); + double TW3E = this.TW3E(null); + double TW4E = this.TW4E(null); double HPOSa = this.HPOSa(constants8); double HPOSb = this.HPOSb(constants8); double HPOSc = this.HPOSc(constants8); @@ -113,6 +118,7 @@ public void set_HitParameters(int superlayer, double ScinBarThickn = this.get_barthickness(); this.set_HitParams(superlayer, TW0U, TW0D, TW1U, TW1D, TW1P, TW2P, + TW0E, TW1E, TW2E, TW3E, TW4E, HPOSa, HPOSb, HPOSc, HPOSd, HPOSe, lambdaU,lambdaD, yOffset, vU, vD, vUUnc, vDUnc, PEDU, PEDD, PEDUUnc, PEDDUnc, paddle2paddle, RFPad, timeOffset, triggerPhase, LSBConv, LSBConvErr, @@ -244,6 +250,31 @@ public double TW12(IndexedTable tab) { return 0; } + @Override + public double TW0E(IndexedTable tab) { + return 0; + } + + @Override + public double TW1E(IndexedTable tab) { + return 0; + } + + @Override + public double TW2E(IndexedTable tab) { + return 0; + } + + @Override + public double TW3E(IndexedTable tab) { + return 0; + } + + @Override + public double TW4E(IndexedTable tab) { + return 0; + } + @Override public double HPOSa(IndexedTable tab) { return tab.getDoubleValue("hposa", this.get_Sector(),this.get_Panel(),this.get_Paddle()); diff --git a/reconstruction/tof/src/main/java/org/jlab/rec/tof/hit/ftof/Hit.java b/reconstruction/tof/src/main/java/org/jlab/rec/tof/hit/ftof/Hit.java index ff6178d906..9d6434f04b 100644 --- a/reconstruction/tof/src/main/java/org/jlab/rec/tof/hit/ftof/Hit.java +++ b/reconstruction/tof/src/main/java/org/jlab/rec/tof/hit/ftof/Hit.java @@ -84,15 +84,17 @@ public void set_HitParameters(int superlayer, double triggerPhase, IndexedTable IndexedTable constants3, IndexedTable constants5, IndexedTable constants6, - IndexedTable constants8) {/* + IndexedTable constants8, + IndexedTable constants9) {/* 0: "/calibration/ftof/attenuation"), 1: "/calibration/ftof/effective_velocity"), 2: "/calibration/ftof/time_offsets"), 3: "/calibration/ftof/time_walk"), 4: "/calibration/ftof/status"), 5: "/calibration/ftof/gain_balance"), - 6: "/calibration/ftof/tdc_conv")); - 8: "/calibration/ftof/time_walk_pos")); + 6: "/calibration/ftof/tdc_conv"), + 8: "/calibration/ftof/time_walk_pos"), + 9: "/calibration/ftof/time_walk_exp")); */ double pl = this.get_paddleLine().length(); @@ -103,6 +105,11 @@ public void set_HitParameters(int superlayer, double triggerPhase, IndexedTable double TW1R = this.TW12(constants3); double TW1P = this.TW1P(constants8); double TW2P = this.TW2P(constants8); + double TW0E = this.TW0E(constants9); + double TW1E = this.TW1E(constants9); + double TW2E = this.TW2E(constants9); + double TW3E = this.TW3E(constants9); + double TW4E = this.TW4E(constants9); double HPOSa = this.HPOSa(null); double HPOSb = this.HPOSb(null); double HPOSc = this.HPOSc(null); @@ -138,6 +145,7 @@ public void set_HitParameters(int superlayer, double triggerPhase, IndexedTable double ScinBarThickn = this.get_barthickness(); this.set_HitParams(superlayer, TW0L, TW0R, TW1L, TW1R, TW1P, TW2P, + TW0E, TW1E, TW2E, TW3E, TW4E, HPOSa, HPOSb, HPOSc, HPOSd, HPOSe, lambdaL,lambdaR, yOffset, vL, vR, vLUnc, vRUnc, PEDL, PEDR, PEDLUnc, PEDRUnc, paddle2paddle, RFPad, timeOffset, triggerPhase, LSBConv, LSBConvErr, @@ -267,6 +275,31 @@ public double TW2P(IndexedTable tab) { return tab.getDoubleValue("tw2pos", this.get_Sector(),this.get_Panel(),this.get_Paddle()); } + @Override + public double TW0E(IndexedTable tab) { + return tab.getDoubleValue("tw0", this.get_Sector(),this.get_Panel(),this.get_Paddle()); + } + + @Override + public double TW1E(IndexedTable tab) { + return tab.getDoubleValue("tw1", this.get_Sector(),this.get_Panel(),this.get_Paddle()); + } + + @Override + public double TW2E(IndexedTable tab) { + return tab.getDoubleValue("tw2", this.get_Sector(),this.get_Panel(),this.get_Paddle()); + } + + @Override + public double TW3E(IndexedTable tab) { + return tab.getDoubleValue("tw3", this.get_Sector(),this.get_Panel(),this.get_Paddle()); + } + + @Override + public double TW4E(IndexedTable tab) { + return tab.getDoubleValue("tw4", this.get_Sector(),this.get_Panel(),this.get_Paddle()); + } + @Override public double HPOSa(IndexedTable tab) { return 0; diff --git a/reconstruction/tof/src/main/java/org/jlab/service/ftof/FTOFEngine.java b/reconstruction/tof/src/main/java/org/jlab/service/ftof/FTOFEngine.java index 117f92a246..b806f341d9 100644 --- a/reconstruction/tof/src/main/java/org/jlab/service/ftof/FTOFEngine.java +++ b/reconstruction/tof/src/main/java/org/jlab/service/ftof/FTOFEngine.java @@ -63,6 +63,7 @@ public boolean init() { "/calibration/ftof/tdc_conv", "/calibration/ftof/time_jitter", "/calibration/ftof/time_walk_pos", + "/calibration/ftof/time_walk_exp", "/calibration/ftof/fadc_offset", }; @@ -127,6 +128,7 @@ public boolean processDataEvent(DataEvent event) { this.getConstantsManager().getConstants(newRun, "/calibration/ftof/tdc_conv"), this.getConstantsManager().getConstants(newRun, "/calibration/ftof/time_jitter"), this.getConstantsManager().getConstants(newRun, "/calibration/ftof/time_walk_pos"), + this.getConstantsManager().getConstants(newRun, "/calibration/ftof/time_walk_exp"), this.getConstantsManager().getConstants(newRun, "/calibration/ftof/fadc_offset")); // 1) get the hits diff --git a/validation/advanced-tests/src/eb/EBTwoTrackTest.java b/validation/advanced-tests/src/eb/EBTwoTrackTest.java index 8f557de043..0d13051307 100644 --- a/validation/advanced-tests/src/eb/EBTwoTrackTest.java +++ b/validation/advanced-tests/src/eb/EBTwoTrackTest.java @@ -385,7 +385,7 @@ public void checkAllRefs(DataEvent ev) { public void checkParticleStatus(DataEvent event) { if (recPartBank==null) return; for (int ipart=0; ipart0.90,true); + if (ftPDG==11) assertEquals(eEff>0.77,true); else if (ftPDG==22) assertEquals(gEff>0.88,true); - assertEquals(hEff>0.50,true); + assertEquals(hEff>0.62,true); } // This is for Forward Tagger; @@ -499,7 +499,7 @@ private void processEventFT(DataEvent event) { nEvents++; - if (recBank==null || recPartBank==null || recFtBank==null) return; + if (recBank==null || recPartBank==null || recFtBank==null || recFtPartBank==null) return; if (debug) { System.out.println("\n\n#############################################################\n"); @@ -510,9 +510,9 @@ private void processEventFT(DataEvent event) { final float startTime=recBank.getFloat("startTime",0); - for (int ii=0; ii0 || fdCharge==0); ii++) { - final int pid = recPartBank.getInt("pid",ii); + for (int ii=0; ii0 || fdCharge==0); ii++) { + final int pid = recFtPartBank.getInt("pid",ii); if (pid==hadronPDG) { final double px=recPartBank.getFloat("px",ii); final double py=recPartBank.getFloat("py",ii); @@ -603,7 +603,7 @@ else if (!isCentral && trkBank.getInt("sector",ii)==hadronSector) { for (int ii = 0; ii < recPartBank.rows(); ii++) { - final short status = recPartBank.getShort("status", ii); + final short status = (short)Math.abs(recPartBank.getShort("status", ii)); final byte charge = recPartBank.getByte("charge", ii); final int pid = recPartBank.getInt("pid", ii); final boolean isFT = status/1000 == 1; diff --git a/version-bump.sh b/version-bump.sh new file mode 100755 index 0000000000..186fb703f5 --- /dev/null +++ b/version-bump.sh @@ -0,0 +1,20 @@ +#!/bin/bash + +if [ -z $2 ] +then + echo Usage: bump-version.sh oldversion newversion + exit +fi + +old=$1 +new=$2 + +if [[ "$OSTYPE" == "darwin"* ]]; then + find . -type f -name pom.xml -exec sed -i '' -e "s/$old-SNAPSHOT/$new-SNAPSHOT/" "{}" \; + find . -type f -name deployDistribution.sh -exec sed -i '' -e "s/$old/$new/" "{}" \; +else + find . -type f -name pom.xml -exec sed -i -e "s/$old-SNAPSHOT/$new-SNAPSHOT/" "{}" \; + find . -type f -name deployDistribution.sh -exec sed -i -e "s/$old/$new/" "{}" \; +fi + +