-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathDigitizationWithPulserDataMergingReadoutDriver.java
More file actions
1903 lines (1691 loc) · 89.7 KB
/
DigitizationWithPulserDataMergingReadoutDriver.java
File metadata and controls
1903 lines (1691 loc) · 89.7 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.hps.digi;
import static org.hps.recon.ecal.EcalUtils.fallTime;
import static org.hps.recon.ecal.EcalUtils.maxVolt;
import static org.hps.recon.ecal.EcalUtils.nBit;
import static org.hps.recon.ecal.EcalUtils.riseTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hps.readout.ReadoutDriver;
import org.hps.readout.ReadoutDataManager;
import org.hps.readout.ReadoutTimestamp;
import org.hps.readout.util.DoubleRingBuffer;
import org.hps.readout.util.IntegerRingBuffer;
import org.hps.readout.util.ObjectRingBuffer;
import org.hps.readout.util.collection.LCIOCollection;
import org.hps.readout.util.collection.LCIOCollectionFactory;
import org.hps.readout.util.collection.TriggeredLCIOData;
import org.hps.recon.ecal.EcalUtils;
import org.hps.util.RandomGaussian;
import org.lcsim.event.CalorimeterHit;
import org.lcsim.event.EventHeader;
import org.lcsim.event.LCRelation;
import org.lcsim.event.MCParticle;
import org.lcsim.event.RawCalorimeterHit;
import org.lcsim.event.RawTrackerHit;
import org.lcsim.event.SimCalorimeterHit;
import org.lcsim.event.base.BaseCalorimeterHit;
import org.lcsim.event.base.BaseLCRelation;
import org.lcsim.event.base.BaseRawCalorimeterHit;
import org.lcsim.event.base.BaseRawTrackerHit;
import org.lcsim.event.base.BaseSimCalorimeterHit;
import org.lcsim.geometry.Detector;
import org.lcsim.geometry.compact.Subdetector;
import org.lcsim.lcio.LCIOConstants;
/**
* Class <code>DigitizationWithPulserDataMergingReadoutDriver</code> performs digitization
* of truth hits from SLIC by converting them into emulated pulses and merges pulser data,
* and then performing pulse integration. The results are output in
* the form of {@link org.lcsim.event.RawCalorimeterHit
* RawCalorimeterHit} objects.
* <br/><br/>
* The truth hit information is retained by also producing an output
* collection of {@link org.lcsim.event.LCRelation LCRelation}
* objects linking the raw hits to the original {@link
* org.lcsim.event.SimCalorimeterHit SimCalorimeterHit} objects from
* which they were generated.
* <br/><br/>
* <code>DigitizationReadoutDriver</code> is itself abstract. It is
* designed with the intent to function for both the hodoscope and
* the calorimeter. As such, it requires its implementing classes to
* handle certain subdetector-specific tasks.
*
* @author Tongtong Cao <caot@jlab.org>
*/
public abstract class DigitizationWithPulserDataMergingReadoutDriver<D extends Subdetector> extends ReadoutDriver {
// ==============================================================
// ==== LCIO Collections ========================================
// ==============================================================
private double debugEnergyThresh=0.25; //only print debug for hits>500 MeV
/**
* Specifies the name of the subdetector geometry object.
*/
private String geometryName = null;
/**
* The name of the input {@link org.lcsim.event.SimCalorimeterHit
* SimCalorimeterHit} truth hit collection from SLIC.
*/
private String truthHitCollectionName = null;
/**
* The name of the input {@link org.lcsim.event.RawTrackerHit
* RawTrackerHit} collection from pulser data.
*/
private String PulserDataCollectionName = null;
/**
* The name of the digitized output {@link
* org.lcsim.event.RawCalorimeterHit RawCalorimeterHit}
* collection.
*/
private String outputHitCollectionName = null;
/**
* The name of the {@link org.lcsim.event.LCRelation LCRelation}
* collection that links output raw hits to the SLIC truth hits
* from which they were generated.
*/
private String truthRelationsCollectionName = null;
/**
* The name of the {@link org.lcsim.event.LCRelation LCRelation}
* collection that links output raw hits to the SLIC truth hits
* from which they were generated. This collection is output for
* trigger path hits, and is never persisted.
*/
private String triggerTruthRelationsCollectionName = null;
/**
* The name of the collection which contains readout hits. The
* class type of this collection will vary based on which mode
* the simulation is set to emulate.
*/
private String readoutCollectionName = null;
// ==============================================================
// ==== Driver Options ==========================================
// ==============================================================
/**
* Indicates whether or not noise should be simulated when
* converting truth energy depositions to the voltage amplitudes.
*/
private boolean addNoise = true;
/**
* Defines the number of photoelectrons per MeV of truth energy
* for the purpose of noise calculation.
*/
private double pePerMeV = Double.NaN;
/**
* Defines a fixed gain to be used for all subdetector channels.
* A negative value will result in gains being pulled from the
* conditions database for the run instead. Units are in MeV/ADC.
*/
private double fixedGain = -1;
/**
* Defines the pulse shape to use when simulating detector truth
* energy deposition response.
*/
private PulseShape pulseShape = PulseShape.ThreePole;
/**
* Defines the pulse time parameter. This influences the shape of
* a pulse generated from truth energy depositions and will vary
* depending on the form of pulse selected. Units are in ns.
*/
private double tp = Double.NaN;
/**
* Defines the ADC threshold needed to initiate pulse integration
* for raw hit creation.
*/
protected int integrationThreshold = 18;
/**
* Defines the number of integration samples that should be
* included in the pulse integral from before the sample that
* exceeds the integration threshold.
*/
protected int numSamplesBefore = 5;
/**
* Defines the number of integration samples that should be
* included in the pulse integral from after the sample that
* exceeds the integration threshold.
* Threshold-crossing sample is part of NSA.
*/
protected int numSamplesAfter = 25;
/**
* The format in which readout hits should be output.
*/
private int mode = 1;
/**
* Specifies whether trigger path hit truth information should be
* included in the driver output.
*/
private boolean writeTriggerTruth = false;
/**
* Specifies whether readout path truth information should be
* included in the driver output.
*/
private boolean writeTruth = false;
private List<Long> debugCellIDWithHits=new ArrayList<Long>();
// ==============================================================
// ==== Driver Parameters =======================================
// ==============================================================
/**
* Defines the length in nanoseconds of a hardware sample.
*/
private static final double READOUT_PERIOD = 4.0;
/**
* Serves as an internal clock variable for the driver. This is
* used to track the number of clock-cycles (1 per {@link
* org.hps.readout.ecal.updated.DigitizationReadoutDriver#READOUT_PERIOD
* READOUT_PERIOD}).
*/
private int readoutCounter = 0;
/**
* A buffer for storing pulse amplitudes representing the signals
* from the preamplifiers. These are stored in units of Volts
* with no pedestal. One buffer exists for each subdetector
* channel.
*/
private Map<Long, DoubleRingBuffer> voltageBufferMap = new HashMap<Long, DoubleRingBuffer>();
/**
* Buffers the truth information for each sample period so that
* truth relations can be retained upon readout.
*/
private Map<Long, ObjectRingBuffer<SimCalorimeterHit>> truthBufferMap = new HashMap<Long, ObjectRingBuffer<SimCalorimeterHit>>();
/**
* A buffer for storing ADC values representing the converted
* voltage values from the voltage buffers. These are stored in
* units of ADC and include a pedestal. One buffer exists for
* each subdetector channel.
*/
private Map<Long, IntegerRingBuffer> adcBufferMap = new HashMap<Long, IntegerRingBuffer>();
/**
* Stores the subdetector geometry object.
*/
private D geometry = null;
/**
* Stores the total ADC sums for each subdetector channel that is
* currently undergoing integration.
*/
private Map<Long, Integer> channelIntegrationSumMap = new HashMap<Long, Integer>();
/**
* Stores the total ADC sums for each subdetector channel that is
* currently undergoing integration.
*/
private Map<Long, Set<SimCalorimeterHit>> channelIntegrationTruthMap = new HashMap<Long, Set<SimCalorimeterHit>>();
/**
* Stores the time at which integration began on a given channel.
* This is used to track when the integration period has ended.
*/
private Map<Long, Integer> channelIntegrationTimeMap = new HashMap<Long, Integer>();
// TODO: Give this documentation.
private Map<Long, List<Integer>> channelIntegrationADCMap = new HashMap<Long, List<Integer>>();
/**
* Defines the time offset of objects produced by this driver
* from the actual true time that they should appear.
*/
private double localTimeOffset = 0;
/**
* Stores the minimum length of that must pass before a new hit
* may be integrated on a given channel.
* Unit: clock-cycle
*/
private static final int CHANNEL_INTEGRATION_DEADTIME = 8;
/**
* Defines the total time range around the trigger time in which
* hits are output into the readout LCIO file. The trigger time
* position within this range is determined by {@link
* org.hps.readout.ecal.updated.DigitizationReadoutDriver#readoutOffset
* readoutOffset}.
*/
protected int readoutWindow = 100;
/**
* Sets how far from the beginning of the readout window trigger
* time should occur. A value of x, for instance would result in
* a window that starts at <code>triggerTime - x</code> and
* extends for a total time <code>readoutWindow</code>.
*/
private int readoutOffset = 36;
/**
* Sets time window of ADC samples in pulser data
*/
protected int pulserDataWindow = 48;
/**
* To make time alignment between Ecal and hodoscope detectors, samples of
* pulser data may need to be shifted according to readout window offset
* difference between Ecal and hodoscope
*/
private int pulserSamplesShift = 0;
/**
* Defines the LCSim collection data for the trigger hits that
* are produced by this driver when it is emulating Mode-1 or
* Mode-3.
*/
private LCIOCollection<RawTrackerHit> mode13HitCollectionParams;
/**
* Defines the LCSim collection data for the trigger hits that
* are produced by this driver when it is emulating Mode-7.
*/
private LCIOCollection<RawCalorimeterHit> mode7HitCollectionParams;
/**
* Defines the LCSim collection data that links SLIC truth hits
* to the their corresponding simulated output hit.
*/
private LCIOCollection<LCRelation> truthRelationsCollectionParams;
/**
* Flag to point out that new integration could be started at a sample
* between <code>CHANNEL_INTEGRATION_DEADTIME</code> and <code>numSamplesAfter</code>
* for the case <CHANNEL_INTEGRATION_DEADTIME> is less than <code>numSamplesAfter</code>
*/
private Map<Long, Boolean> flagStartNewIntegration = new HashMap<>();
/**
* Since new integration could happen between <code>CHANNEL_INTEGRATION_DEADTIME</code> and <code>numSamplesAfter</code>,
* integration time needs to be assigned as parameter of <code>ReadoutDataManager.addData()</code>.
* Global displacement is 0 for dependency.
*/
private double integrationTime = Double.NaN;
// ==============================================================
// ==== To Be Re-Worked =========================================
// ==============================================================
// TODO: We should be able to define these based on the integration parameters.
private static final int BUFFER_LENGTH = 100;
private static final int PIPELINE_LENGTH = 2000;
@Override
public void startOfData() {
// Validate that all the collection names are defined.
if(truthHitCollectionName == null || PulserDataCollectionName == null || outputHitCollectionName == null || truthRelationsCollectionName == null
|| triggerTruthRelationsCollectionName == null || readoutCollectionName == null) {
throw new RuntimeException("One or more collection names is not defined!");
}
// Calculate the correct time offset. This is a function of
// the integration samples and the output delay.
// Threshold-crossing sample is part of NSA.
localTimeOffset = 4 * numSamplesAfter;
// Validate that a real mode was selected.
if(mode != 1 && mode != 3 && mode != 7) {
throw new IllegalArgumentException("Error: Mode " + mode + " is not a supported output mode.");
}
// Add the driver dependencies.
addDependency(truthHitCollectionName);
addDependency(PulserDataCollectionName);
// Define the LCSim collection parameters for this driver's
// output. Note: Since these are not persisted, the flags and
// readout name are probably not necessary.
LCIOCollectionFactory.setCollectionName(outputHitCollectionName);
LCIOCollectionFactory.setProductionDriver(this);
LCIOCollectionFactory.setFlags((0 + (1 << LCIOConstants.CHBIT_LONG) + (1 << LCIOConstants.RCHBIT_ID1)));
LCIOCollectionFactory.setReadoutName(truthHitCollectionName);
LCIOCollection<RawCalorimeterHit> hitCollectionParams = LCIOCollectionFactory.produceLCIOCollection(RawCalorimeterHit.class);
ReadoutDataManager.registerCollection(hitCollectionParams, false);
LCIOCollectionFactory.setCollectionName(triggerTruthRelationsCollectionName);
LCIOCollectionFactory.setProductionDriver(this);
LCIOCollection<LCRelation> triggerTruthCollectionParams = LCIOCollectionFactory.produceLCIOCollection(LCRelation.class);
ReadoutDataManager.registerCollection(triggerTruthCollectionParams, false);
// Define the LCSim collection data for the on-trigger output.
LCIOCollectionFactory.setCollectionName(readoutCollectionName);
LCIOCollectionFactory.setProductionDriver(this);
mode13HitCollectionParams = LCIOCollectionFactory.produceLCIOCollection(RawTrackerHit.class);
LCIOCollectionFactory.setCollectionName(readoutCollectionName);
LCIOCollectionFactory.setProductionDriver(this);
LCIOCollectionFactory.setFlags(1 << LCIOConstants.RCHBIT_TIME);
mode7HitCollectionParams = LCIOCollectionFactory.produceLCIOCollection(RawCalorimeterHit.class);
LCIOCollectionFactory.setCollectionName(truthRelationsCollectionName);
LCIOCollectionFactory.setProductionDriver(this);
truthRelationsCollectionParams = LCIOCollectionFactory.produceLCIOCollection(LCRelation.class);
// Run the superclass method.
super.startOfData();
}
@SuppressWarnings("unchecked")
@Override
public void detectorChanged(Detector detector) {
// Throw an error if the geometry name is not set.
if(geometryName == null) {
throw new RuntimeException("Subdetector name is not defined!");
}
// Get the readout name from the subdetector geometry data.
geometry = (D) detector.getSubdetector(geometryName);
// Update the output LCIO collections data.
LCIOCollectionFactory.setReadoutName(geometry.getReadout().getName());
mode13HitCollectionParams = LCIOCollectionFactory.cloneCollection(mode13HitCollectionParams);
LCIOCollectionFactory.setReadoutName(geometry.getReadout().getName());
mode7HitCollectionParams = LCIOCollectionFactory.cloneCollection(mode7HitCollectionParams);
// Reinstantiate the buffers.
resetBuffers();
}
@Override
public void process(EventHeader event) {
/*
* Get current SLIC hits and current raw hits in pulser data.
*/
// Get current SLIC hits.
Collection<SimCalorimeterHit> hits = ReadoutDataManager.getData(ReadoutDataManager.getCurrentTime(), ReadoutDataManager.getCurrentTime() + 2.0,
truthHitCollectionName, SimCalorimeterHit.class);
// Get current raw hits in pulser data.
Collection<RawTrackerHit> rawHits = ReadoutDataManager.getData(ReadoutDataManager.getCurrentTime(), ReadoutDataManager.getCurrentTime() + 2.0,
PulserDataCollectionName, RawTrackerHit.class);
if(debug)System.out.println("DigiReadout:: "+truthHitCollectionName +" local time = "+ReadoutDataManager.getCurrentTime()+" number of hits = "+hits.size());
// Once an overlaid event is input, reset adcBufferMap to ensure that other overlaid events do not affect the current event.
if(hits.size()!=0 || rawHits.size()!=0) {
// Get the set of all possible channel IDs.
Set<Long> cells = getChannelIDs();
if(debug)System.out.println(this.getClass().getName()+":: resetting adc buffers at time = "+ReadoutDataManager.getCurrentTime());
// Reset adcBufferMap.
for(Long cellID : cells)
adcBufferMap.get(cellID).setAll((int) Math.round(getPedestalConditions(cellID)));
debugCellIDWithHits.clear();
//if we are in no-spacing mode, just clear everything
if(doNoSpacing){
resetBuffers();
channelIntegrationSumMap.clear();
}
}
/* To merge MC data with pulser data, three different cases are handled separately.
* Case 1: If pulser data does not have a channel in MC data, directly buffer samples
*
* Case 2: If MC data does not have a channel in pulser data,
* 1) add noise into MC hits
* 2) convert MC hits into a window of ADC samples
* 3) add pedestal
* 4) buffer samples
*
* Case 3: If MC data has a channel that is also in pulser data,
* 1) convert MC hits into a window of ADC samples
* 2) merge with samples of pulser data
* 3) buffer merged samples
*
* MC hits are digitized into ADC samples with the same time window of pulser data.
* Before the time window, the window is extended with NSB ADC samples, and values of the ADC samples are set as pedestal.
* After the time window, the window is extended with NSA ADC samples, and values of the ADC samples are set as pedestal.
* The extension is allowed since enough empty events are inserted into neighbored overlaid events.
*/
// Add the truth hits to the truth hit buffer. The buffer is
// only incremented when the ADC buffer is incremented, which
// is handled below.
// Save cell IDs of hits as keys in the MC hit Cell ID hash map, and set values as 1.
// The hash map is used to check if MC data has a channel that is also in pulser data.
Map<Long,Integer> hitCellIDMap = new HashMap<Long,Integer>(hits.size());
for(SimCalorimeterHit hit : hits) {
// Store the truth data.
Long hitCellID = hit.getCellID(); // For Ecal, cell ID is geometry ID; For hodo, cell ID is channel ID after hodoscope preprocessing
if(debug)
System.out.println(this.getClass().getName()+":: process:: sim hit energy = "+hit.getRawEnergy()+" on cell = "+hitCellID);
ObjectRingBuffer<SimCalorimeterHit> hitBuffer = truthBufferMap.get(hitCellID);
hitBuffer.addToCell(0, hit);
// Save cell IDs of hits as keys in the hit Cell ID hash map, and set values as 1.
if(hitCellIDMap.get(hitCellID) == null)
hitCellIDMap.put(hitCellID,1);
}
// handle pulser data: case 1.
// If cellID of a raw hit is not included by keys in the MC hit Cell ID hash map for MC hits, directly buffer ADC samples.
// If included, set value as 2 for the corresponding key in the MC hit Cell ID hash map.
// Save raw hits in the raw hit hash map, where keys are raw hit cell IDs and values are raw hits.
// The hash map is used for case 3
Map<Long, RawTrackerHit> rawHitsMap = new HashMap<Long,RawTrackerHit>(rawHits.size());
for(RawTrackerHit rawHit : rawHits) {
Long rawHitID = getID(rawHit); // For Ecal, ID is geometry ID; For hodo, ID is channel ID, which is converted from geometry ID.
if(hitCellIDMap.get(rawHitID) == null) {
// Get the ADC buffer for the channel.
IntegerRingBuffer adcBuffer = adcBufferMap.get(rawHitID);
// Get ADC samples for the channel.
short[] adcSamples = rawHit.getADCValues();
// Length of ADC sample array should be equal to setup for time window of ADC samples
if(adcSamples.length != pulserDataWindow)
throw new RuntimeException("Error: time window of pulser data is not correctly set.");
// Buffer ADC samples in pulser data
for(int i = 0; i < pulserDataWindow; i++)
adcBuffer.setValue(i - pulserSamplesShift, (int)adcSamples[i]);
}
else {
hitCellIDMap.put(rawHitID, 2);
rawHitsMap.put(rawHitID, rawHit);
}
}
// handle MC hits: case 2 and case 3
// In the MC hit Cell ID hash map, if value for cell ID of a MC hit is 1, handle the hit as case 2.
// If value for cell ID of a MC hit is 2, handle the hit as case 3.
for(SimCalorimeterHit hit : hits) {
Long hitCellID = hit.getCellID();
// Check to see if the hit time seems valid. This is done
// by calculating the time of the next readout cycle in
// ns and subtracting the time of the current hit (with
// adjustment for simulation time passed) from it. If the
// hit would fall in a previous readout cycle, something
// is probably wrong.
if(READOUT_PERIOD + readoutTime() - (ReadoutDataManager.getCurrentTime() + hit.getTime()) >= READOUT_PERIOD) {
throw new RuntimeException("Error: Trying to add a hit to the analog pipeline, but the time seems incorrect.");
}
// Get the ADC buffer for the channel.
IntegerRingBuffer adcBuffer = adcBufferMap.get(hitCellID);
// Get the pedestal for the channel.
int pedestal = (int) Math.round(getPedestalConditions(hitCellID));
// Get the buffer for the current truth hit's channel.
DoubleRingBuffer voltageBuffer = voltageBufferMap.get(hitCellID);
// Get the truth hit energy deposition.
double energyAmplitude = hit.getRawEnergy();
if(energyAmplitude>debugEnergyThresh && debug){
System.out.println(this.getClass().getName()+":: process:: Putting sim hits in adcBuffer cellID = "+hitCellID);
System.out.println(this.getClass().getName()+":: process:: adding hits to adcBuffer cellID = "+hitCellID);
System.out.println(this.getClass().getName()+":: process:: ReadoutDataManager Time = "+ReadoutDataManager.getCurrentTime());
System.out.println(this.getClass().getName()+":: process:: hit time = "+hit.getTime());
System.out.println(this.getClass().getName()+":: process:: readouttime() = "+readoutTime());
System.out.println(this.getClass().getName()+":: process:: truth energy = "+energyAmplitude);
debugCellIDWithHits.add(hitCellID);
}
if(hitCellIDMap.get(hitCellID) == 1) {
// If noise should be added, calculate a random value for
// the noise and add it to the truth energy deposition.
if(addNoise) {
energyAmplitude += getAmplitudeFluctuation(hit);
}
// Simulate the pulse for each position in the preamp
// pulse buffer for the subdetector channel on which the
// hit occurred.
for(int i = 0; i < pulserDataWindow; i++) {
// Calculate the voltage deposition for the current
// buffer time.
double voltageDeposition = energyAmplitude * pulseAmplitude((i + 1) * READOUT_PERIOD + readoutTime()
- (ReadoutDataManager.getCurrentTime() + hit.getTime()) - getTimeShiftConditions(hitCellID), hitCellID);
// Increase the current buffer time's voltage value
// by the calculated amount.
voltageBuffer.addToCell(i, voltageDeposition);
// Scale the current value of the preamplifier buffer
// to a 12-bit ADC value where the maximum represents
// a value of maxVolt.
double currentValue = voltageBuffer.getValue(i) * ((Math.pow(2, nBit) - 1) / maxVolt);
// If noise should be added, calculate a random value for
// the noise and add it to the ADC value.
if(addNoise) {
double sigma = getNoiseConditions(hitCellID);
currentValue += RandomGaussian.getGaussian(0, sigma);
}
// An ADC value is not allowed to exceed 4095. If a
// larger value is observed, 4096 (overflow) is given
// instead. (This corresponds to >2 Volts.)
int digitizedValue = Math.min((int) Math.round(pedestal + currentValue), (int) Math.pow(2, nBit));
if(energyAmplitude>debugEnergyThresh&&debug)
System.out.println(this.getClass().getName()+":: process: writing digitized value for sample = "+i
+" post-noise current value = "+currentValue
+"; digitized value = "+digitizedValue);
// Write this value to the ADC buffer.
adcBuffer.setValue(i, digitizedValue);
//
}
}
else {
// Get ADC samples for the channel.
short[] ADCSamples = rawHitsMap.get(hitCellID).getADCValues();
// Get digitized samples for MC hits
int[] digitizedValue = new int[pulserDataWindow];
// Simulate the pulse for each position in the preamp
// pulse buffer for the subdetector channel on which the
// hit occurred.
for(int i = 0; i < pulserDataWindow; i++) {
// Calculate the voltage deposition for the current
// buffer time.
double voltageDeposition = energyAmplitude * pulseAmplitude((i + 1) * READOUT_PERIOD + readoutTime()
- (ReadoutDataManager.getCurrentTime() + hit.getTime()) - getTimeShiftConditions(hitCellID), hitCellID);
// Increase the current buffer time's voltage value
// by the calculated amount.
voltageBuffer.addToCell(i, voltageDeposition);
// Scale the current value of the preamplifier buffer
// to a 12-bit ADC value where the maximum represents
// a value of maxVolt.
double currentValue = voltageBuffer.getValue(i) * ((Math.pow(2, nBit) - 1) / maxVolt);
// An ADC value is not allowed to exceed 4095. If a
// larger value is observed, 4096 (overflow) is given
// instead. (This corresponds to >2 Volts.)
digitizedValue[i] = Math.min((int) Math.round(currentValue), (int) Math.pow(2, nBit));
}
// Write this value to the ADC buffer.
// If pulserSamplesShift is larger than 0, merged sample window is [-pulserSamplesShift, pulserDataWindow]
if(pulserSamplesShift >= 0) {
for(int i = -pulserSamplesShift; i < 0; i++) adcBuffer.setValue(i , (int)ADCSamples[i + pulserSamplesShift]);
for(int i = 0; i < pulserDataWindow - pulserSamplesShift; i++) adcBuffer.setValue(i, digitizedValue[i] + ADCSamples[i + pulserSamplesShift]);
for(int i = pulserDataWindow - pulserSamplesShift; i < pulserDataWindow; i++) adcBuffer.setValue(i, digitizedValue[i]);
}
// If pulserSamplesShift is less than 0, merged sample window is [0, -pulserSamplesShift + pulserDataWindow]
else {
for(int i = 0; i < -pulserSamplesShift; i++) adcBuffer.setValue(i, digitizedValue[i]);
for(int i = -pulserSamplesShift; i < pulserDataWindow; i++) adcBuffer.setValue(i, digitizedValue[i] + ADCSamples[i + pulserSamplesShift]);
for(int i = pulserDataWindow; i < pulserDataWindow - pulserSamplesShift; i++) adcBuffer.setValue(i, (int)ADCSamples[i + pulserSamplesShift]);
}
}
}
/*
* Next step is to integrate hits from the pulses. Hit
* integration is only performed once per readout period. The
* readout period, defined by the hardware, is by default 4
* nanoseconds.
*/
// Check whether the appropriate amount of time has passed to
// perform another integration step. If so, create a list to
// contain any newly integrated hits and perform integration.
List<RawCalorimeterHit> newHits = null;
List<LCRelation> newTruthRelations = null;
if(doNoSpacing){
if(newHits == null) { newHits = new ArrayList<RawCalorimeterHit>(); }
if(newTruthRelations == null) { newTruthRelations = new ArrayList<LCRelation>(); }
readoutCounter=0;
for(int i = 0; i < pulserDataWindow; i++){
// System.out.println(this.getClass().getName()+":: looping over pulse data window readoutCounter = "+readoutCounter);
readHits(newHits, newTruthRelations);
readoutCounter++;
}
}else{
while(ReadoutDataManager.getCurrentTime() - readoutTime() + ReadoutDataManager.getBeamBunchSize() >= READOUT_PERIOD) {
if(newHits == null) { newHits = new ArrayList<RawCalorimeterHit>(); }
if(newTruthRelations == null) { newTruthRelations = new ArrayList<LCRelation>(); }
readHits(newHits, newTruthRelations);
readoutCounter++;
}
}
}
// TODO: Document this.
private void readHits(List<RawCalorimeterHit> newHits, List<LCRelation> newTruthRelations) {
// Perform hit integration as needed for each subdetector
// channel in the buffer map.
for(Long cellID : adcBufferMap.keySet()) {
// Get the ADC buffer for the channel.
IntegerRingBuffer adcBuffer = adcBufferMap.get(cellID);
// Get the pedestal for the channel.
int pedestal = (int) Math.round(getPedestalConditions(cellID));
// Store the pedestal subtracted value so that it may
// be checked against the integration threshold.
int pedestalSubtractedValue = adcBuffer.getValue() - pedestal;
if(pedestalSubtractedValue > integrationThreshold && debug){
System.out.println(this.getClass().getName()+":: readHits:: Looping over adcBufferMap cellID = "+cellID);
System.out.println(this.getClass().getName()+":: readHits:: ped subtracted ADC counts = "+pedestalSubtractedValue);
}
// Get the total ADC value that has been integrated
// on this channel.
Integer sum = channelIntegrationSumMap.get(cellID);
if(pedestalSubtractedValue >integrationThreshold && debug)
System.out.println(this.getClass().getName()+":: readHits:: sum = "+sum);
// If any readout hits exist on this channel, add the
// current ADC values to them.
// If the ADC sum is undefined, then there is not an
// ongoing integration. If the pedestal subtracted
// value is also over the integration threshold, then
// integration should be initiated.
if(sum == null && pedestalSubtractedValue > integrationThreshold) {
// Store the current local time in units of
// events (4 ns). This will indicate when the
// integration started and, in turn, should end.
channelIntegrationTimeMap.put(cellID, readoutCounter);
if(debug)System.out.println(this.getClass().getName()+":: readHits:: Found a hit above threshold = "+cellID);
// Integrate the ADC values for a number of
// samples defined by NSB and threshold
// crossing sample.
int sumBefore = 0;
for(int i = 0; i <= numSamplesBefore; i++) {
sumBefore += adcBuffer.getValue(-(numSamplesBefore - i));
}
if(debug)System.out.println(this.getClass().getName()+":: readHits:: sum before this sample = "+sumBefore);
// This will represent the total integral sum at
// the current point in time. Store it in the sum
// buffer so that it may be incremented later as
// additional samples are read.
channelIntegrationSumMap.put(cellID, sumBefore);
// Collect and store truth information for trigger
// path hits.
channelIntegrationADCMap.put(cellID, new ArrayList<Integer>());
// Get the truth information in the
// integration samples for this channel.
Set<SimCalorimeterHit> truthHits = new HashSet<SimCalorimeterHit>();
for(int i = 0; i < numSamplesBefore + 4; i++) {
channelIntegrationADCMap.get(cellID).add(adcBuffer.getValue(-(numSamplesBefore - i)));
truthHits.addAll(truthBufferMap.get(cellID).getValue(-(numSamplesBefore - i)));
}
// Store all the truth hits that occurred in
// the truth buffer in the integration period
// for this channel as well. These will be
// passed through the chain to allow for the
// accessing of truth information during the
// trigger simulation.
channelIntegrationTruthMap.put(cellID, truthHits);
}
// If the integration sum is defined, then pulse
// integration is ongoing.
if(sum != null) {
if(debug)System.out.println(this.getClass().getName()+":: readHits:: integration is ongoing..."+cellID+" count = "+readoutCounter);
// Three cases are treated separataly
// Case 1: CHANNEL_INTEGRATION_DEADTIME > numSamplesAfter
// Case 2: CHANNEL_INTEGRATION_DEADTIME == numSamplesAfter
// Case 3: CHANNEL_INTEGRATION_DEADTIME < numSamplesAfter
if(CHANNEL_INTEGRATION_DEADTIME > numSamplesAfter) { // Case 1
//Continue integration until NSA, the threshold-crossing sample has been added before.
if(debug)System.out.println(this.getClass().getName()+":: readHits::case 1: channel deadtime > numSamplesAfter "+cellID+" count = "+readoutCounter);
if (channelIntegrationTimeMap.get(cellID) + numSamplesAfter - 1 >= readoutCounter) {
if(debug)System.out.println(this.getClass().getName()+":: readHits::case 1: integration + numSamplesAfter - 1>= readoutCounter "+cellID+" count = "+readoutCounter);
channelIntegrationADCMap.get(cellID).add(adcBuffer.getValue(0));
// Add the new ADC sample.
channelIntegrationSumMap.put(cellID, sum + adcBuffer.getValue(0));
// Add the new truth information, if trigger
// path truth output is enabled.
if (writeTriggerTruth) {
channelIntegrationTruthMap.get(cellID).addAll(truthBufferMap.get(cellID).getValue(0));
}
}
// If integration is complete, a hit may be added
// to data manager.
else if (channelIntegrationTimeMap.get(cellID) + numSamplesAfter - 1 == readoutCounter - 1) {//At NSA + 1, hit is added into data manager
// Add a new calorimeter hit.
if(debug)System.out.println(this.getClass().getName()+":: readHits:: case 1: reached NSA + 1; adding new hit "+cellID+" count = "+readoutCounter);
RawCalorimeterHit newHit = new BaseRawCalorimeterHit(cellID, sum,
64 * channelIntegrationTimeMap.get(cellID));
newHits.add(newHit);
// Cycle-clock for events is 2 ns, while cycle-clock for samples is 4 ns
integrationTime = channelIntegrationTimeMap.get(cellID) * 4 + 2;
// Add the truth relations for this hit, if
// trigger path truth is enabled.
if (writeTriggerTruth) {
Set<SimCalorimeterHit> truthHits = channelIntegrationTruthMap.get(cellID);
for (SimCalorimeterHit truthHit : truthHits) {
newTruthRelations.add(new BaseLCRelation(newHit, truthHit));
}
}
}
// Do not clear the channel for integration until deadtime has passed.
// The threshold-crossing sample counts as the first sample in the deadtime.
else if (channelIntegrationTimeMap.get(cellID) + CHANNEL_INTEGRATION_DEADTIME - 1 <= readoutCounter
- 1) { // No new integration until over deadtime
channelIntegrationSumMap.remove(cellID);
}
} // Case 1 ends
else if(CHANNEL_INTEGRATION_DEADTIME == numSamplesAfter){ // Case 2
// Continue integration until NSA, the threshold-crossing sample has been added before.
if(debug)System.out.println(this.getClass().getName()+":: readHits::case 2: channel deadtime == numSamplesAfter "+cellID+" count = "+readoutCounter);
if (channelIntegrationTimeMap.get(cellID) + numSamplesAfter - 1 >= readoutCounter) {
channelIntegrationADCMap.get(cellID).add(adcBuffer.getValue(0));
if(debug)System.out.println(this.getClass().getName()+":: readHits::Case2: integration + numSamplesAfter - 1>= readoutCounter "+cellID+" count = "+readoutCounter);
// Add the new ADC sample.
channelIntegrationSumMap.put(cellID, sum + adcBuffer.getValue(0));
// Add the new truth information, if trigger
// path truth output is enabled.
if (writeTriggerTruth) {
channelIntegrationTruthMap.get(cellID).addAll(truthBufferMap.get(cellID).getValue(0));
}
}
// If integration is complete, a hit may be added
// to data manager.
else if (channelIntegrationTimeMap.get(cellID) + numSamplesAfter - 1 == readoutCounter - 1) {//At NSA + 1, hit is added into data manager
// Add a new calorimeter hit.
if(debug)System.out.println(this.getClass().getName()+":: readHits:: case 2: reached NSA + 1; adding new hit "+cellID+" count = "+readoutCounter);
RawCalorimeterHit newHit = new BaseRawCalorimeterHit(cellID, sum,
64 * channelIntegrationTimeMap.get(cellID));
newHits.add(newHit);
// Cycle-clock for events is 2 ns, while cycle-clock for samples is 4 ns
integrationTime = channelIntegrationTimeMap.get(cellID) * 4 + 2;
// Add the truth relations for this hit, if
// trigger path truth is enabled.
if (writeTriggerTruth) {
Set<SimCalorimeterHit> truthHits = channelIntegrationTruthMap.get(cellID);
for (SimCalorimeterHit truthHit : truthHits) {
newTruthRelations.add(new BaseLCRelation(newHit, truthHit));
}
}
channelIntegrationSumMap.remove(cellID);
}
} // Case 2 ends
else { // Case 3
if(debug)System.out.println(this.getClass().getName()+":: readHits::case 3: channel deadtime < numSamplesAfter "+cellID+" count = "+readoutCounter);
if (channelIntegrationTimeMap.get(cellID) + CHANNEL_INTEGRATION_DEADTIME - 1 >= readoutCounter) {
if(debug)System.out.println(this.getClass().getName()+":: readHits::Case3: integration + DEADTIME - 1>= readoutCounter "+cellID+" count = "+readoutCounter);
// Continue integration until CHANNEL_INTEGRATION_DEADTIME
channelIntegrationADCMap.get(cellID).add(adcBuffer.getValue(0));
// Add the new ADC sample.
channelIntegrationSumMap.put(cellID, sum + adcBuffer.getValue(0));
// Add the new truth information, if trigger
// path truth output is enabled.
if (writeTriggerTruth) {
channelIntegrationTruthMap.get(cellID).addAll(truthBufferMap.get(cellID).getValue(0));
}
// If sample at the end of deadtime is less than threshold, new integration could be started from next sample
if(channelIntegrationTimeMap.get(cellID) + CHANNEL_INTEGRATION_DEADTIME == readoutCounter && pedestalSubtractedValue <= integrationThreshold)
flagStartNewIntegration.put(cellID, true);
}
else if (channelIntegrationTimeMap.get(cellID) + numSamplesAfter - 1 >= readoutCounter) {
if(debug)System.out.println(this.getClass().getName()+":: readHits::Case3: integration + numSamplesAfter - 1>= readoutCounter "+cellID+" count = "+readoutCounter);
if(flagStartNewIntegration.get(cellID) == true) { // Flag for previous sample is true
if(debug)System.out.println(this.getClass().getName()+":: readHits::Case3: flagStartNewIntegration = true "+cellID+" count = "+readoutCounter);
if(pedestalSubtractedValue <= integrationThreshold) { // If sample is less than threshold, then do not start new integration
channelIntegrationADCMap.get(cellID).add(adcBuffer.getValue(0));
if(debug)System.out.println(this.getClass().getName()+":: readHits::Case3: too small...don't start new integration "+cellID+" count = "+readoutCounter);
// Add the new ADC sample.
channelIntegrationSumMap.put(cellID, sum + adcBuffer.getValue(0));
// Add the new truth information, if trigger
// path truth output is enabled.
if (writeTriggerTruth) {
channelIntegrationTruthMap.get(cellID).addAll(truthBufferMap.get(cellID).getValue(0));
}
}
else { // if sample is larger than threshold, a hit is added into data manager and start new integration
// Add a new calorimeter hit.
if(debug)System.out.println(this.getClass().getName()+":: readHits:: case 3: new hit starting, storing old hit; adding new hit "+cellID+" count = "+readoutCounter);
RawCalorimeterHit newHit = new BaseRawCalorimeterHit(cellID, sum,
64 * channelIntegrationTimeMap.get(cellID));
newHits.add(newHit);
integrationTime = channelIntegrationTimeMap.get(cellID) * 4 + 2;
// Add the truth relations for this hit, if
// trigger path truth is enabled.
if (writeTriggerTruth) {
Set<SimCalorimeterHit> truthHits = channelIntegrationTruthMap.get(cellID);
for (SimCalorimeterHit truthHit : truthHits) {
newTruthRelations.add(new BaseLCRelation(newHit, truthHit));
}
}
//Start new integration
channelIntegrationTimeMap.put(cellID, readoutCounter);
flagStartNewIntegration.put(cellID, false);
// Integrate the ADC values for a number of
// samples defined by NSB from before threshold
// crossing. Note that this stops one sample
// before the current sample. This current sample
// is handled in the subsequent code block.
int sumBefore = 0;
for(int i = 0; i <= numSamplesBefore; i++) {
sumBefore += adcBuffer.getValue(-(numSamplesBefore - i));
}
// This will represent the total integral sum at
// the current point in time. Store it in the sum
// buffer so that it may be incremented later as
// additional samples are read.
channelIntegrationSumMap.put(cellID, sumBefore);
// Collect and store truth information for trigger
// path hits.
channelIntegrationADCMap.put(cellID, new ArrayList<Integer>());
// Get the truth information in the
// integration samples for this channel.
Set<SimCalorimeterHit> truthHits = new HashSet<SimCalorimeterHit>();
for(int i = 0; i < numSamplesBefore + 4; i++) {
channelIntegrationADCMap.get(cellID).add(adcBuffer.getValue(-(numSamplesBefore - i)));
truthHits.addAll(truthBufferMap.get(cellID).getValue(-(numSamplesBefore - i)));
}
// Store all the truth hits that occurred in
// the truth buffer in the integration period
// for this channel as well. These will be
// passed through the chain to allow for the
// accessing of truth information during the
// trigger simulation.
channelIntegrationTruthMap.put(cellID, truthHits);
}
}
else { // Flag for previous sample is false
if(debug)System.out.println(this.getClass().getName()+":: readHits::Case3: flagStartNewIntegration = false "+cellID+" count = "+readoutCounter);
channelIntegrationADCMap.get(cellID).add(adcBuffer.getValue(0));
// Add the new ADC sample.
channelIntegrationSumMap.put(cellID, sum + adcBuffer.getValue(0));
// Add the new truth information, if trigger
// path truth output is enabled.
if (writeTriggerTruth) {
channelIntegrationTruthMap.get(cellID).addAll(truthBufferMap.get(cellID).getValue(0));
}
if(pedestalSubtractedValue <= integrationThreshold)
flagStartNewIntegration.put(cellID, true);
}
}
else if (channelIntegrationTimeMap.get(cellID) + numSamplesAfter - 1 == readoutCounter - 1) {//If reach NSA + 1, hit is added into data manager, and flag is set as false
if(debug)System.out.println(this.getClass().getName()+":: readHits:: case 3: reached NSA + 1; adding new hit "+cellID+" count = "+readoutCounter);
// Add a new calorimeter hit.
RawCalorimeterHit newHit = new BaseRawCalorimeterHit(cellID, sum,
64 * channelIntegrationTimeMap.get(cellID));
newHits.add(newHit);
integrationTime = channelIntegrationTimeMap.get(cellID) * 4 + 2;
// Add the truth relations for this hit, if
// trigger path truth is enabled.
if (writeTriggerTruth) {
Set<SimCalorimeterHit> truthHits = channelIntegrationTruthMap.get(cellID);
for (SimCalorimeterHit truthHit : truthHits) {
newTruthRelations.add(new BaseLCRelation(newHit, truthHit));
}
}
channelIntegrationSumMap.remove(cellID);
flagStartNewIntegration.put(cellID, false);
}
} // Case 3 ends
}
// Step to the next entry in the adc buffer.
adcBuffer.stepForward();
// Step to the next entry in the voltage buffer.
if(voltageBufferMap.get(cellID) != null) { // A channel could be from pulser data, while MC data has no such channel.
DoubleRingBuffer voltageBuffer = voltageBufferMap.get(cellID);
voltageBuffer.clearValue();
voltageBuffer.stepForward();
}
// Step the truth buffer for this channel forward.
// The new cell should be cleared of any old values.
if(truthBufferMap.get(cellID) != null) { // A channel could be from pulser data, while MC data has no such channel.
truthBufferMap.get(cellID).stepForward();
truthBufferMap.get(cellID).clearValue();
}
}
// Write the trigger path output data to the readout data
// manager. Truth data is optional.
//if running no-spacing, set the time to current time+readout
//I'm just replacing integration time here to make it easier
//note...I have no idea how using integration time works
//in the "spacing" readout. It's in local units, but the lookup
//in GTPClusters is in global??? I'm missing something
if(doNoSpacing)
integrationTime=readoutTime()+readoutCounter * READOUT_PERIOD;
if(debug && newHits.size()>0)
System.out.println("DigiReadout:: "+ outputHitCollectionName+" time = "+integrationTime+" adding trigger hits = "+newHits.size());
ReadoutDataManager.addData(outputHitCollectionName, integrationTime, newHits, RawCalorimeterHit.class);
if(doNoSpacing)
newHits.clear();
if(writeTriggerTruth) {
ReadoutDataManager.addData(triggerTruthRelationsCollectionName, integrationTime, newTruthRelations, LCRelation.class);
}
}
/**
* Finds all root particles associated with the interactions that
* created the argument particle.
* @param particle - The particle.
* @return Returns a {@link java.util.List List} containing each
* particle object in the argument particle's particle tree which
* has no parent particle.
*/
private static final List<MCParticle> getRootParticleList(MCParticle particle) {
// If the particle has no parents, it should be added to the
// list and the list returned.