11 removed + 117 modified, total 128 files
java/branches/hps-java_HPSJAVA-88/analysis
--- java/branches/hps-java_HPSJAVA-88/analysis/pom.xml 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/analysis/pom.xml 2014-09-02 22:27:42 UTC (rev 940)
@@ -10,7 +10,7 @@
<groupId>org.hps</groupId>
<artifactId>hps-parent</artifactId>
<relativePath>../parent/pom.xml</relativePath>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</parent>
<scm>
java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality
--- java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality/DataQualityMonitor.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality/DataQualityMonitor.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -18,14 +18,18 @@
*/
public class DataQualityMonitor extends Driver {
- public AIDA aida = AIDA.defaultInstance();
- public DQMDatabaseManager manager;
- public String recoVersion = "v0.0";
- public static int runNumber = 1350;
- public boolean overwriteDB = false;
- public boolean connectToDB = false;
- public boolean printDQMStrings = false;
- public Map<String, Double> monitoredQuantityMap = new HashMap<>();
+ protected AIDA aida = AIDA.defaultInstance();
+ protected DQMDatabaseManager manager;
+ protected String recoVersion = "v0.0";
+ protected static int runNumber = 1350;
+ protected boolean overwriteDB = false;
+ protected boolean connectToDB = false;
+ protected boolean printDQMStrings = false;
+ protected Map<String, Double> monitoredQuantityMap = new HashMap<>();
+
+ protected boolean outputPlots = true;
+ protected String outputPlotDir = "DQMOutputPlots/";
+
public void setRecoVersion(String recoVersion) {
this.recoVersion = recoVersion;
}
@@ -46,6 +50,14 @@
this.printDQMStrings = print;
}
+ public void setOutputPlots(boolean out){
+ this.outputPlots=out;
+ }
+ public void setOutputPlotDir(String dir){
+ this.outputPlotDir=dir;
+ }
+
+
public void DataQualityMonitor() {
}
java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality
--- java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality/FinalStateMonitoring.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality/FinalStateMonitoring.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -40,7 +40,7 @@
String finalStateParticlesColName = "FinalStateParticles";
- String[] fpQuantNames = {"nEle_per_Event", "nPos_per_Event", "nPhoton_per_Event", "nUnAssociatedTracks_per_Event", "avg_delX_at_ECal", "avg_delY_at_ECal", "avg_E_Over_P"};
+ String[] fpQuantNames = {"nEle_per_Event", "nPos_per_Event", "nPhoton_per_Event", "nUnAssociatedTracks_per_Event", "avg_delX_at_ECal", "avg_delY_at_ECal", "avg_E_Over_P","avg_mom_beam_elec","sig_mom_beam_elec"};
//some counters
int nRecoEvents = 0;
int nTotEle = 0;
@@ -163,8 +163,6 @@
Hep3Vector trackPosAtEcal = TrackUtils.extrapolateTrack(fsTrack, clusterPosition.z());
double dx = trackPosAtEcal.x() - clusterPosition.x();//remember track vs detector coords
double dy = trackPosAtEcal.y() - clusterPosition.y();//remember track vs detector coords
- System.out.println(trackPosAtEcal.x() + ";" + trackPosAtEcal.y() + ";" + trackPosAtEcal.z());
- System.out.println(clusterPosition.x() + ";" + clusterPosition.y() + ";" + clusterPosition.z());
sumdelX += dx;
sumdelY += dy;
@@ -208,10 +206,9 @@
IFitter fitter = fitFactory.createFitter("chi2");
IHistogram1D beamE = aida.histogram1D(plotDir + "Beam Electrons Pz (GeV)");
IFitResult result = fitBeamEnergyPeak(beamE, fitter, "range=\"(-10.0,10.0)\"");
-
- for (int i = 0; i < 5; i++) {
- double par = result.fittedParameters()[i];
- System.out.println("Beam Energy Peak: " + result.fittedParameterNames()[i] + " = " + par);
+ double[] pars=result.fittedParameters();
+ for (int i = 0; i < 5; i++) {
+ System.out.println("Beam Energy Peak: " + result.fittedParameterNames()[i] + " = " + pars[i]);
}
monitoredQuantityMap.put(fpQuantNames[0], (double) nTotEle / nRecoEvents);
@@ -221,7 +218,8 @@
monitoredQuantityMap.put(fpQuantNames[4], (double) sumdelX / nTotAss);
monitoredQuantityMap.put(fpQuantNames[5], (double) sumdelY / nTotAss);
monitoredQuantityMap.put(fpQuantNames[6], (double) sumEoverP / nTotAss);
-
+ monitoredQuantityMap.put(fpQuantNames[7], (double) pars[1]);
+ monitoredQuantityMap.put(fpQuantNames[8], (double) pars[2]);
IPlotter plotter = analysisFactory.createPlotterFactory().create("Beam Energy Electrons");
IPlotterStyle pstyle = plotter.style();
@@ -239,7 +237,7 @@
@Override
public void printDQMStrings() {
- for (int i = 0; i < 7; i++)//TODO: do this in a smarter way...loop over the map
+ for (int i = 0; i < 9; i++)//TODO: do this in a smarter way...loop over the map
System.out.println("ALTER TABLE dqm ADD " + fpQuantNames[i] + " double;");
}
java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality
--- java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality/SVTHitMCEfficiency.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality/SVTHitMCEfficiency.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,5 +1,7 @@
package org.hps.analysis.dataquality;
+import hep.aida.IHistogram1D;
+import hep.aida.IHistogram2D;
import hep.aida.IHistogramFactory;
import hep.aida.IProfile1D;
import java.util.HashMap;
@@ -19,9 +21,9 @@
import org.lcsim.recon.tracking.digitization.sisim.SiTrackerHitStrip1D;
/**
- * DQM driver for the monte carlo SVT hit efficiency
- * April 29 -- first pass, makes the SimTrackerHits-->SiClusters efficiency vs
- * position (with a settable t0 cut)
+ * DQM driver for the monte carlo SVT hit efficiency April 29 -- first pass,
+ * makes the SimTrackerHits-->SiClusters efficiency vs position (with a settable
+ * t0 cut)
*
* @author mgraham on April 29, 2014
*/
@@ -29,19 +31,19 @@
// TODO: Add some quantities for DQM monitoring: e.g. <efficiency>, probably within first 1 cm or so.
public class SVTHitMCEfficiency extends DataQualityMonitor {
- private String rawTrackerHitCollectionName = "SVTRawTrackerHits";
+ private final String rawTrackerHitCollectionName = "SVTRawTrackerHits";
private String helicalTrackHitCollectionName = "HelicalTrackHits";
- private String rotatedTrackHitCollectionName = "RotatedHelicalTrackHits";
- private String fittedTrackerHitCollectionName = "SVTFittedRawTrackerHits";
- private String trackerHitCollectionName = "TrackerHits";
- private String siClusterCollectionName = "StripClusterer_SiTrackerHitStrip1D";
- private String svtTrueHitRelationName = "SVTTrueHitRelations";
- private String trackerName = "Tracker";
+ private final String rotatedTrackHitCollectionName = "RotatedHelicalTrackHits";
+ private final String fittedTrackerHitCollectionName = "SVTFittedRawTrackerHits";
+ private final String trackerHitCollectionName = "TrackerHits";
+ private final String siClusterCollectionName = "StripClusterer_SiTrackerHitStrip1D";
+ private final String svtTrueHitRelationName = "SVTTrueHitRelations";
+ private final String trackerName = "Tracker";
private Detector detector = null;
private double t0Cut = 16.0;
private static final String nameStrip = "Tracker_TestRunModule_";
private List<SiSensor> sensors;
- private String plotDir = "SvtHitMCEfficiency/";
+ private final String plotDir = "SvtHitMCEfficiency/";
private Map<String, Double> avgClusterEffMap;
private Map<String, String> avgClusterEffNames;
@@ -57,7 +59,6 @@
protected void detectorChanged(Detector detector) {
this.detector = detector;
aida.tree().cd("/");
- IHistogramFactory hf = aida.histogramFactory();
// Make a list of SiSensors in the SVT.
sensors = this.detector.getSubdetector(trackerName).getDetectorElement().findDescendants(SiSensor.class);
@@ -66,7 +67,13 @@
//currently, just the Si cluster efficiency
aida.tree().cd("/");
for (int kk = 1; kk < 13; kk++) {
- IProfile1D clEffic = createLayerPlot(plotDir+"clusterEfficiency", kk, 50, 0, 25.);
+ createLayerPlot(plotDir + "clusterEfficiency", kk, 50, -40, 40.);
+ createLayerPlot(plotDir + "readoutEfficiency", kk, 50, -40, 40.);
+ createLayerPlot(plotDir + "rthToClusterEfficiency", kk, 50, -40, 40.);
+ createLayerPlot2D(plotDir + "toogoodFits", kk, 200, -100, 100, 100, 0, 20000);
+ createLayerPlot2D(plotDir + "goodFits", kk, 200, -100, 100, 100, 0, 20000);
+ createLayerPlot2D(plotDir + "badFits", kk, 200, -100, 100, 100, 0, 20000);
+ createLayerPlot1D(plotDir + "signalClusterT0", kk, 500, -100, 100);
}
resetEfficiencyMap();
}
@@ -77,68 +84,111 @@
aida.tree().cd("/");
//make sure the required collections exist
- if (!event.hasCollection(RawTrackerHit.class, rawTrackerHitCollectionName))
+ if (!event.hasCollection(RawTrackerHit.class, rawTrackerHitCollectionName)) {
return;
- if (!event.hasCollection(FittedRawTrackerHit.class, fittedTrackerHitCollectionName))
+ }
+ if (!event.hasCollection(FittedRawTrackerHit.class, fittedTrackerHitCollectionName)) {
return;
+ }
- if (!event.hasCollection(SiTrackerHitStrip1D.class, siClusterCollectionName))
+ if (!event.hasCollection(SiTrackerHitStrip1D.class, siClusterCollectionName)) {
return;
+ }
- if (!event.hasCollection(SimTrackerHit.class, trackerHitCollectionName))
+ if (!event.hasCollection(SimTrackerHit.class, trackerHitCollectionName)) {
return;
+ }
- if (!event.hasCollection(LCRelation.class, svtTrueHitRelationName))
+ if (!event.hasCollection(LCRelation.class, svtTrueHitRelationName)) {
return;
+ }
- RelationalTable mcHittomcP = new BaseRelationalTable(RelationalTable.Mode.MANY_TO_MANY, RelationalTable.Weighting.UNWEIGHTED);
+ RelationalTable mcHittomcP = new BaseRelationalTable(RelationalTable.Mode.MANY_TO_ONE, RelationalTable.Weighting.UNWEIGHTED);
// Get the collections of SimTrackerHits
List<List<SimTrackerHit>> simcols = event.get(SimTrackerHit.class);
// Loop over the SimTrackerHits and fill in the relational table
- for (List<SimTrackerHit> simlist : simcols)
- for (SimTrackerHit simhit : simlist)
- if (simhit.getMCParticle() != null)
+ for (List<SimTrackerHit> simlist : simcols) {
+ for (SimTrackerHit simhit : simlist) {
+ if (simhit.getMCParticle() != null) {
mcHittomcP.add(simhit, simhit.getMCParticle());
+ }
+ }
+ }
+
RelationalTable rawtomc = new BaseRelationalTable(RelationalTable.Mode.MANY_TO_MANY, RelationalTable.Weighting.UNWEIGHTED);
- if (event.hasCollection(LCRelation.class, svtTrueHitRelationName)) {
- List<LCRelation> trueHitRelations = event.get(LCRelation.class, svtTrueHitRelationName);
- for (LCRelation relation : trueHitRelations)
- if (relation != null && relation.getFrom() != null && relation.getTo() != null)
- rawtomc.add(relation.getFrom(), relation.getTo());
+ List<LCRelation> trueHitRelations = event.get(LCRelation.class, svtTrueHitRelationName);
+ for (LCRelation relation : trueHitRelations) {
+ if (relation.getFrom() != null && relation.getTo() != null) {
+ rawtomc.add(relation.getFrom(), relation.getTo());
+ }
}
+
List<SimTrackerHit> simHits = event.get(SimTrackerHit.class, trackerHitCollectionName);
// make relational table for strip clusters to mc particle
List<SiTrackerHitStrip1D> siClusters = event.get(SiTrackerHitStrip1D.class, siClusterCollectionName);
RelationalTable clustertosimhit = new BaseRelationalTable(RelationalTable.Mode.MANY_TO_MANY, RelationalTable.Weighting.UNWEIGHTED);
for (SiTrackerHit cluster : siClusters) {
- List<RawTrackerHit> rawHits = cluster.getRawHits();
- for (RawTrackerHit rth : rawHits) {
+ for (RawTrackerHit rth : cluster.getRawHits()) {
Set<SimTrackerHit> simTrackerHits = rawtomc.allFrom(rth);
- if (simTrackerHits != null)
- for (SimTrackerHit simhit : simTrackerHits)
- clustertosimhit.add(cluster, simhit);
+ if (simTrackerHits != null) {
+ for (SimTrackerHit simhit : simTrackerHits) {
+ if (simhit != null) {
+ clustertosimhit.add(cluster, simhit);
+ }
+ }
+ }
}
}
-//relational tables from mc particle to raw and fitted tracker hits
+
+ //relational tables from raw and fitted tracker hits to sim hit
RelationalTable fittomc = new BaseRelationalTable(RelationalTable.Mode.MANY_TO_MANY, RelationalTable.Weighting.UNWEIGHTED);
List<FittedRawTrackerHit> fittedTrackerHits = event.get(FittedRawTrackerHit.class, fittedTrackerHitCollectionName);
for (FittedRawTrackerHit hit : fittedTrackerHits) {
- RawTrackerHit rth = hit.getRawTrackerHit();
- Set<SimTrackerHit> simTrackerHits = rawtomc.allFrom(rth);
- if (simTrackerHits != null)
- for (SimTrackerHit simhit : simTrackerHits)
- if (simhit.getMCParticle() != null)
- fittomc.add(hit, simhit.getMCParticle());
+ Set<SimTrackerHit> simTrackerHits = rawtomc.allFrom(hit.getRawTrackerHit());
+ for (SimTrackerHit simhit : simTrackerHits) {
+ fittomc.add(hit, simhit);
+ }
}
for (SimTrackerHit simhit : simHits) {
- double wgt = 0.0;
+ Set<FittedRawTrackerHit> fittedRTH = fittomc.allTo(simhit);
+ FittedRawTrackerHit signalHit = null;
+ for (FittedRawTrackerHit frth : fittedRTH) {
+ if (signalHit == null || Math.abs(frth.getT0()) < Math.abs(signalHit.getT0())) {
+ signalHit = frth;
+ }
+ }
+ if (signalHit != null) {
+// System.out.format("chiprob %f, t0 %f, A %f\n", signalHit.getShapeFitParameters().getChiProb(), signalHit.getT0(), signalHit.getAmp());
+ if (signalHit.getShapeFitParameters().getChiProb() > 0.95) {
+ getLayerPlot2D(plotDir + "toogoodFits", simhit.getLayer()).fill(signalHit.getT0(), signalHit.getAmp());
+ } else if (signalHit.getShapeFitParameters().getChiProb() < 0.05) {
+ getLayerPlot2D(plotDir + "badFits", simhit.getLayer()).fill(signalHit.getT0(), signalHit.getAmp());
+ } else {
+ getLayerPlot2D(plotDir + "goodFits", simhit.getLayer()).fill(signalHit.getT0(), signalHit.getAmp());
+ }
+ }
+
+ int gotCluster = 0;
Set<SiTrackerHitStrip1D> clusters = clustertosimhit.allTo(simhit);
- if (clusters != null)
- for (SiTrackerHitStrip1D clust : clusters)
- if (Math.abs(clust.getTime()) < t0Cut)
- wgt = 1.0;
- getLayerPlot(plotDir+"clusterEfficiency", simhit.getLayer()).fill(Math.abs(simhit.getPoint()[1]), wgt);
+ if (clusters != null) {
+ for (SiTrackerHitStrip1D clust : clusters) {
+ getLayerPlot1D(plotDir + "signalClusterT0", simhit.getLayer()).fill(clust.getTime());
+
+ if (Math.abs(clust.getTime()) < t0Cut) {
+ gotCluster = 1;
+ }
+ }
+ }
+ Set<RawTrackerHit> rawhits = rawtomc.allTo(simhit);
+ int gotRawHit = !rawhits.isEmpty() ? 1 : 0;
+
+ double y = simhit.getDetectorElement().getGeometry().getGlobalToLocal().transformed(simhit.getPositionVec()).x() + 20.0 * Math.signum(simhit.getPoint()[1]) * (simhit.getLayer() % 2 == 0 ? -1 : 1);
+ getLayerPlot(plotDir + "clusterEfficiency", simhit.getLayer()).fill(y, gotCluster);
+ getLayerPlot(plotDir + "readoutEfficiency", simhit.getLayer()).fill(y, gotRawHit);
+ if (gotRawHit == 1) {
+ getLayerPlot(plotDir + "rthToClusterEfficiency", simhit.getLayer()).fill(y, gotCluster);
+ }
}
}
@@ -151,8 +201,8 @@
}
private void resetEfficiencyMap() {
- avgClusterEffMap = new HashMap<>();
- avgClusterEffNames = new HashMap<>();
+ avgClusterEffMap = new HashMap<String, Double>();
+ avgClusterEffNames = new HashMap<String, String>();
for (SiSensor sensor : sensors) {
String effName = "avgClusterEff_" + getNiceSensorName(sensor);
avgClusterEffNames.put(sensor.getName(), effName);
@@ -171,20 +221,37 @@
}
private IProfile1D createLayerPlot(String prefix, int layer, int nchan, double min, double max) {
- IProfile1D hist = aida.profile1D(prefix + "_layer" + layer, nchan, min, max);
- return hist;
+ return aida.profile1D(prefix + "_layer" + layer, nchan, min, max);
}
+ private IHistogram1D getLayerPlot1D(String prefix, int layer) {
+ return aida.histogram1D(prefix + "_layer" + layer);
+ }
+
+ private IHistogram1D createLayerPlot1D(String prefix, int layer, int nchan, double min, double max) {
+ return aida.histogram1D(prefix + "_layer" + layer, nchan, min, max);
+ }
+
+ private IHistogram2D getLayerPlot2D(String prefix, int layer) {
+ return aida.histogram2D(prefix + "_layer" + layer);
+ }
+
+ private IHistogram2D createLayerPlot2D(String prefix, int layer, int nx, double minX, double maxX, int ny, double minY, double maxY) {
+ return aida.histogram2D(prefix + "_layer" + layer, nx, minX, maxX, ny, minY, maxY);
+ }
+
@Override
public void printDQMData() {
- for (SiSensor sensor : sensors)
+ for (SiSensor sensor : sensors) {
System.out.println(avgClusterEffNames.get(sensor.getName()) + ": " + avgClusterEffMap.get(sensor.getName()));
+ }
}
@Override
public void printDQMStrings() {
- for (SiSensor sensor : sensors)
- System.out.println("ALTER TABLE dqm ADD "+avgClusterEffNames.get(sensor.getName())+" double;");
+ for (SiSensor sensor : sensors) {
+ System.out.println("ALTER TABLE dqm ADD " + avgClusterEffNames.get(sensor.getName()) + " double;");
+ }
}
}
java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality
--- java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality/SvtMonitoring.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality/SvtMonitoring.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -15,17 +15,19 @@
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hps.conditions.deprecated.SvtUtils;
-import org.hps.recon.tracking.FittedRawTrackerHit;
+import org.hps.recon.tracking.ShapeFitParameters;
import org.lcsim.detector.tracker.silicon.SiSensor;
import org.lcsim.event.EventHeader;
+import org.lcsim.event.GenericObject;
+import org.lcsim.event.LCRelation;
import org.lcsim.event.RawTrackerHit;
+import org.lcsim.event.TrackerHit;
import org.lcsim.geometry.Detector;
/**
- * DQM driver for the monte carlo for reconstructed track quantities
- * plots things like occupancy, t0, amplitude, chi^2 (from APV25 sampling fit);
- * each on a per/sensor basis
- * saves to DQM database: <occupancy>
+ * DQM driver for the monte carlo for reconstructed track quantities plots
+ * things like occupancy, t0, amplitude, chi^2 (from APV25 sampling fit); each
+ * on a per/sensor basis saves to DQM database: <occupancy>
*
* @author mgraham on Mar 28, 2014
*/
@@ -37,7 +39,7 @@
private String trackerHitCollectionName = "StripClusterer_SiTrackerHitStrip1D";
private Detector detector = null;
private IPlotter plotter;
- private String trackerName = "Tracker";
+ private final String trackerName = "Tracker";
private List<SiSensor> sensors;
private Map<String, int[]> occupancyMap;
private Map<String, Double> avgOccupancyMap;
@@ -51,7 +53,7 @@
private int eventCountCluster = 0;
private static final String nameStrip = "Tracker_TestRunModule_";
private static final int maxChannels = 640;
- private String plotDir = "SvtMonitoring/";
+ private final String plotDir = "SvtMonitoring/";
public void setRawTrackerHitCollectionName(String inputCollection) {
this.rawTrackerHitCollectionName = inputCollection;
@@ -65,6 +67,7 @@
this.trackerHitCollectionName = inputCollection;
}
+ @Override
protected void detectorChanged(Detector detector) {
System.out.println("SvtMonitoring::detectorChanged Setting up the plotter");
this.detector = detector;
@@ -81,9 +84,11 @@
for (SiSensor sensor : sensors) {
//IHistogram1D occupancyPlot = aida.histogram1D(sensor.getName().replaceAll("Tracker_TestRunModule_", ""), 640, 0, 639);
IHistogram1D occupancyPlot = createSensorPlot(plotDir + "occupancy_", sensor, maxChannels, 0, maxChannels - 1);
- IHistogram1D t0Plot = createSensorPlot(plotDir + "t0_", sensor, 50, -50., 50.);
- IHistogram1D amplitudePlot = createSensorPlot(plotDir + "amplitude_", sensor, 50, 0, 2000);
- IHistogram1D chi2Plot = createSensorPlot(plotDir + "chi2_", sensor, 50, 0, 25);
+ IHistogram1D t0Plot = createSensorPlot(plotDir + "t0Hit_", sensor, 50, -50., 50.);
+ IHistogram1D amplitudePlot = createSensorPlot(plotDir + "amplitude_", sensor, 50, 0, 2000.0);
+ IHistogram1D chiProbPlot = createSensorPlot(plotDir + "chiProb_", sensor, 50, 0, 1.0);
+ IHistogram1D t0ClusterPlot = createSensorPlot(plotDir + "t0Cluster_", sensor, 50, -50., 50.);
+ IHistogram1D dedxClusterPlot = createSensorPlot(plotDir + "electrons_", sensor, 50, 0., 10.);
occupancyPlot.reset();
}
@@ -95,34 +100,49 @@
public void process(EventHeader event) {
/* increment the strip occupancy arrays */
if (event.hasCollection(RawTrackerHit.class, rawTrackerHitCollectionName)) {
+// System.out.println("Found a raw hit collection");
List<RawTrackerHit> rawTrackerHits = event.get(RawTrackerHit.class, rawTrackerHitCollectionName);
for (RawTrackerHit hit : rawTrackerHits) {
int[] strips = occupancyMap.get(hit.getDetectorElement().getName());
strips[hit.getIdentifierFieldValue("strip")] += 1;
}
++eventCountRaw;
- } else
- return; /* kick out of this if the even has none of these...*/
+ }
/* fill the FittedTrackerHit related histograms */
-
- if (event.hasCollection(FittedRawTrackerHit.class, fittedTrackerHitCollectionName)) {
- List<FittedRawTrackerHit> fittedTrackerHits = event.get(FittedRawTrackerHit.class, fittedTrackerHitCollectionName);
- for (FittedRawTrackerHit hit : fittedTrackerHits) {
- String sensorName = hit.getRawTrackerHit().getDetectorElement().getName();
- double t0 = hit.getT0();
- double amp = hit.getAmp();
- double chi2 = hit.getShapeFitParameters().getChiSq();
- getSensorPlot(plotDir + "t0_", sensorName).fill(t0);
+ if (event.hasCollection(LCRelation.class, fittedTrackerHitCollectionName)) {
+ List<LCRelation> fittedTrackerHits = event.get(LCRelation.class, fittedTrackerHitCollectionName);
+ for (LCRelation hit : fittedTrackerHits) {
+ RawTrackerHit rth = (RawTrackerHit) hit.getFrom();
+ GenericObject pars = (GenericObject) hit.getTo();
+ String sensorName = getNiceSensorName((SiSensor) rth.getDetectorElement());
+ //this is a clever way to get the parameters we want from the generic object
+ double t0 = ShapeFitParameters.getT0(pars);
+ double amp = ShapeFitParameters.getAmp(pars);
+ double chiProb = ShapeFitParameters.getChiProb(pars);
+ getSensorPlot(plotDir + "t0Hit_", sensorName).fill(t0);
getSensorPlot(plotDir + "amplitude_", sensorName).fill(amp);
- getSensorPlot(plotDir + "chi2_", sensorName).fill(chi2);
+ getSensorPlot(plotDir + "chiProb_", sensorName).fill(chiProb);
}
++eventCountFit;
- } else
- return;
+ }
+
+ if (event.hasItem(trackerHitCollectionName)) {
+// System.out.println("Found a Si cluster collection");
+ List<TrackerHit> siClusters = (List<TrackerHit>) event.get(trackerHitCollectionName);
+ for (TrackerHit cluster : siClusters) {
+ String sensorName = getNiceSensorName((SiSensor) ((RawTrackerHit) cluster.getRawHits().get(0)).getDetectorElement());
+ double t0 = cluster.getTime();
+ double dedx = cluster.getdEdx() * 1e6;
+// System.out.println("dedx = "+dedx);
+ getSensorPlot(plotDir + "t0Cluster_", sensorName).fill(t0);
+ getSensorPlot(plotDir + "electrons_", sensorName).fill(dedx);
+ }
+ }
}
private IHistogram1D getSensorPlot(String prefix, SiSensor sensor) {
- return aida.histogram1D(prefix + sensor.getName());
+ String hname = prefix + getNiceSensorName(sensor);
+ return aida.histogram1D(hname);
}
private IHistogram1D getSensorPlot(String prefix, String sensorName) {
@@ -130,22 +150,24 @@
}
private IHistogram1D createSensorPlot(String prefix, SiSensor sensor, int nchan, double min, double max) {
- IHistogram1D hist = aida.histogram1D(prefix + sensor.getName(), nchan, min, max);
+ String hname = prefix + getNiceSensorName(sensor);
+ IHistogram1D hist = aida.histogram1D(hname, nchan, min, max);
hist.setTitle(sensor.getName().replaceAll(nameStrip, "")
.replace("module", "mod")
.replace("layer", "lyr")
.replace("sensor", "sens"));
+
return hist;
}
private void resetOccupancyMap() {
- occupancyMap = new HashMap<>();
- avgOccupancyMap = new HashMap<>();
- avgOccupancyNames = new HashMap<>();
- avgt0Names = new HashMap<>();
- sigt0Names = new HashMap<>();
- avgt0Map = new HashMap<>();
- sigt0Map = new HashMap<>();
+ occupancyMap = new HashMap<String, int[]>();
+ avgOccupancyMap = new HashMap<String, Double>();
+ avgOccupancyNames = new HashMap<String, String>();
+ avgt0Names = new HashMap<String, String>();
+ sigt0Names = new HashMap<String, String>();
+ avgt0Map = new HashMap<String, Double>();
+ sigt0Map = new HashMap<String, Double>();
for (SiSensor sensor : sensors) {
occupancyMap.put(sensor.getName(), new int[640]);
avgOccupancyMap.put(sensor.getName(), -999.);
@@ -185,8 +207,9 @@
int[] strips = occupancyMap.get(sensor.getName());
for (int i = 0; i < strips.length; i++) {
double stripOccupancy = (double) strips[i] / (double) (eventCountRaw);
- if (stripOccupancy != 0)
+ if (stripOccupancy != 0) {
sensorHist.fill(i, stripOccupancy);
+ }
avg += stripOccupancy;
}
//do the end-of-run quantities here too since we've already done the loop.
@@ -214,22 +237,14 @@
int irTop = 0;
int irBot = 0;
for (SiSensor sensor : sensors) {
- IHistogram1D sensPlot = getSensorPlot(plotDir + "t0_", sensor);
- IFitResult result = fitGaussian(sensPlot, fitter, "range=\"(-10.0,10.0)\"");
- for (int i = 0; i < 5; i++) {
- double par = result.fittedParameters()[i];
- System.out.println("t0_" + sensor.getName() + ": " + result.fittedParameterNames()[i] + " = " + par);
- }
-
+ IHistogram1D sensPlot = getSensorPlot(plotDir + "t0Hit_", sensor);
+ IFitResult result = fitGaussian(sensPlot, fitter, "range=\"(-8.0,8.0)\"");
boolean isTop = SvtUtils.getInstance().isTopLayer(sensor);
-
if (isTop) {
- System.out.println("Plotting into Top region " + irTop);
plotterTop.region(irTop).plot(sensPlot);
plotterTop.region(irTop).plot(result.fittedFunction());
irTop++;
} else {
- System.out.println("Plotting into Bottom region " + irBot);
plotterBottom.region(irBot).plot(sensPlot);
plotterBottom.region(irBot).plot(result.fittedFunction());
irBot++;
java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality
--- java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality/TrackMCEfficiency.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality/TrackMCEfficiency.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -315,12 +315,12 @@
if (fit.getRawTrackerHit().getLayerNumber() == layer) {
hasFitHitSL1 = true;
fitSL1 = fit;
- System.out.println("Found a hit in SL1 with t0 = " + fitSL1.getT0() + "; amp = " + fitSL1.getAmp() + "; chi^2 = " + fitSL1.getShapeFitParameters().getChiSq() + "; strip = " + fitSL1.getRawTrackerHit().getCellID());
+ System.out.println("Found a hit in SL1 with t0 = " + fitSL1.getT0() + "; amp = " + fitSL1.getAmp() + "; chi^2 = " + fitSL1.getShapeFitParameters().getChiProb() + "; strip = " + fitSL1.getRawTrackerHit().getCellID());
}
if (fit.getRawTrackerHit().getLayerNumber() == layer + 1) {
hasFitHitSL2 = true;
fitSL2 = fit;
- System.out.println("Found a hit in SL2 with t0 = " + fitSL2.getT0() + "; amp = " + fitSL2.getAmp() + "; chi^2 = " + fitSL2.getShapeFitParameters().getChiSq() + "; strip = " + fitSL2.getRawTrackerHit().getCellID());
+ System.out.println("Found a hit in SL2 with t0 = " + fitSL2.getT0() + "; amp = " + fitSL2.getAmp() + "; chi^2 = " + fitSL2.getShapeFitParameters().getChiProb() + "; strip = " + fitSL2.getRawTrackerHit().getCellID());
}
}
java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality
--- java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality/TrackingMonitoring.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality/TrackingMonitoring.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,18 +1,11 @@
package org.hps.analysis.dataquality;
import hep.aida.IHistogram1D;
-import hep.aida.IProfile;
-import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.hps.conditions.deprecated.SvtUtils;
-import org.lcsim.detector.tracker.silicon.SiSensor;
import org.lcsim.event.EventHeader;
import org.lcsim.event.LCIOParameters;
-import org.lcsim.event.RawTrackerHit;
import org.lcsim.event.Track;
-import org.lcsim.fit.helicaltrack.HelicalTrackCross;
-import org.lcsim.fit.helicaltrack.HelicalTrackHit;
import org.lcsim.geometry.Detector;
import org.lcsim.geometry.IDDecoder;
@@ -58,9 +51,6 @@
this.detector = detector;
aida.tree().cd("/");
- IProfile avgLayersTopPlot = aida.profile1D(plotDir+"Number of Stereo Hits per layer in Top Half", 6, 1, 13);
- IProfile avgLayersBottomPlot = aida.profile1D(plotDir+"Number of Stereo Hits per layer in Bottom Half", 6, 1, 13);
-
IHistogram1D trkChi2 = aida.histogram1D(plotDir+"Track Chi2", 25, 0, 25.0);
IHistogram1D nTracks = aida.histogram1D(plotDir+"Tracks per Event", 6, 0, 6);
IHistogram1D trkd0 = aida.histogram1D(plotDir+"d0 ", 25, -5.0, 5.0);
@@ -76,33 +66,12 @@
public void process(EventHeader event) {
aida.tree().cd("/");
- if (!event.hasCollection(HelicalTrackHit.class, helicalTrackHitCollectionName))
- return;
- nEvents++;
- List<HelicalTrackHit> hthList = event.get(HelicalTrackHit.class, helicalTrackHitCollectionName);
- int[] layersTop = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
- int[] layersBot = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
- for (HelicalTrackHit hth : hthList) {
- HelicalTrackCross htc = (HelicalTrackCross) hth;
- double x = htc.getPosition()[0];
- double y = htc.getPosition()[1];
- SiSensor sensor = ((SiSensor) ((RawTrackerHit) htc.getRawHits().get(0)).getDetectorElement());
- if (SvtUtils.getInstance().isTopLayer(sensor))
- layersTop[htc.Layer() - 1]++;
- else
- layersBot[htc.Layer() - 1]++;
- }
- for (int i = 0; i < 12; i++) {
- aida.profile1D(plotDir+"Number of Stereo Hits per layer in Top Half").fill(i + 1, layersTop[i]);
- aida.profile1D(plotDir+"Number of Stereo Hits per layer in Bottom Half").fill(i + 1, layersBot[i]);
- }
-
+
if (!event.hasCollection(Track.class, trackCollectionName)) {
-// System.out.println(trackCollectionName + " does not exist; skipping event");
aida.histogram1D(plotDir+"Tracks per Event").fill(0);
return;
}
-
+ nEvents++;
List<Track> tracks = event.get(Track.class, trackCollectionName);
nTotTracks += tracks.size();
aida.histogram1D(plotDir+"Tracks per Event").fill(tracks.size());
java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality
--- java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality/TrackingResiduals.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality/TrackingResiduals.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,14 +1,24 @@
package org.hps.analysis.dataquality;
+import hep.aida.IAnalysisFactory;
+import hep.aida.IFitFactory;
+import hep.aida.IFitResult;
+import hep.aida.IFitter;
import hep.aida.IHistogram1D;
+import hep.aida.IPlotter;
+import hep.aida.IPlotterStyle;
+import java.io.IOException;
+import java.util.HashMap;
import java.util.List;
-import org.hps.recon.tracking.TrackResidualsData;
-import org.hps.recon.tracking.TrackTimeData;
+import java.util.Map;
+import java.util.logging.Level;
+import java.util.logging.Logger;
import org.lcsim.event.EventHeader;
+import org.lcsim.event.GenericObject;
import org.lcsim.geometry.Detector;
/**
- * DQM driver for track residuals in position and time
+ * DQM driver for track residuals in position and time
*
* @author mgraham on June 5, 2014
*/
@@ -19,75 +29,325 @@
String trackTimeDataCollectionName = "TrackTimeData";
String trackResidualsCollectionName = "TrackResiduals";
-
int nEvents = 0;
-
+
private String plotDir = "TrackResiduals/";
String[] trackingQuantNames = {};
int nmodules = 6;
+ private String posresDir = "PostionResiduals/";
+ private String timeresDir = "TimeResiduals/";
+ private Map<String, Double> xposTopMeanResidMap;
+ private Map<String, Double> yposTopMeanResidMap;
+ private Map<String, Double> xposBotMeanResidMap;
+ private Map<String, Double> yposBotMeanResidMap;
+ private Map<String, Double> timeMeanResidMap;
+ private Map<String, Double> xposTopSigmaResidMap;
+ private Map<String, Double> yposTopSigmaResidMap;
+ private Map<String, Double> xposBotSigmaResidMap;
+ private Map<String, Double> yposBotSigmaResidMap;
+ private Map<String, Double> timeSigmaResidMap;
@Override
protected void detectorChanged(Detector detector) {
-
+
aida.tree().cd("/");
-
+ resetOccupancyMap();
for (int i = 0; i < nmodules; i++) {
- IHistogram1D xresid = aida.histogram1D(plotDir + "Layer " + i + " x Residual", 50, -2.5, 2.5);
- IHistogram1D yresid = aida.histogram1D(plotDir + "Layer " + i + " y Residual", 50, -1, 1);
-
+ IHistogram1D xresid = aida.histogram1D(plotDir + posresDir + "Module " + i + "Top x Residual", 50,-getRange(i,true),getRange(i,true));
+ IHistogram1D yresid = aida.histogram1D(plotDir + posresDir + "Module " + i + "Top y Residual", 50,-getRange(i,false),getRange(i,false));
+ IHistogram1D xresidbot = aida.histogram1D(plotDir + posresDir + "Module " + i + "Bot x Residual", 50,-getRange(i,true),getRange(i,true));
+ IHistogram1D yresidbot = aida.histogram1D(plotDir + posresDir + "Module " + i + "Bot y Residual", 50,-getRange(i,false),getRange(i,false));
}
for (int i = 0; i < nmodules * 2; i++) {
- IHistogram1D tresid = aida.histogram1D(plotDir + "Half-Layer " + i + " t Residual", 50, -20, 20);
+ IHistogram1D tresid = aida.histogram1D(plotDir + timeresDir + "HalfModule " + i + " t Residual", 50, -20, 20);
}
}
@Override
public void process(EventHeader event) {
-
aida.tree().cd("/");
- if (!event.hasCollection(TrackTimeData.class, trackTimeDataCollectionName))
+ if (!event.hasCollection(GenericObject.class, trackTimeDataCollectionName))
return;
- if (!event.hasCollection(TrackResidualsData.class, trackResidualsCollectionName))
+ if (!event.hasCollection(GenericObject.class, trackResidualsCollectionName))
return;
nEvents++;
+ List<GenericObject> trdList = event.get(GenericObject.class, trackResidualsCollectionName);
+ for (GenericObject trd : trdList) {
+ int nResid = trd.getNDouble();
+ int isBot = trd.getIntVal(trd.getNInt() - 1);//last Int is the top/bottom flag
+ for (int i = 0; i < nResid; i++)
+ if (isBot == 1) {
+ aida.histogram1D(plotDir + posresDir + "Module " + i + "Bot x Residual").fill(trd.getDoubleVal(i));//x is the double value in the generic object
+ aida.histogram1D(plotDir + posresDir + "Module " + i + "Bot y Residual").fill(trd.getFloatVal(i));//y is the float value in the generic object
+ } else {
+ aida.histogram1D(plotDir + posresDir + "Module " + i + "Top x Residual").fill(trd.getDoubleVal(i));//x is the double value in the generic object
+ aida.histogram1D(plotDir + posresDir + "Module " + i + "Top y Residual").fill(trd.getFloatVal(i));//y is the float value in the generic object
+ }
- List<TrackResidualsData> trdList = event.get(TrackResidualsData.class, trackResidualsCollectionName);
- for (TrackResidualsData trd : trdList) {
- int nResid = trd.getNDouble();
- for (int i = 0; i < nResid; i++) {
- aida.histogram1D(plotDir + "Layer " + i + " x Residual").fill(trd.getDoubleVal(i));//x is the double value in the generic object
- aida.histogram1D(plotDir + "Layer " + i + " y Residual").fill(trd.getFloatVal(i));//y is the float value in the generic object
- }
}
- List<TrackTimeData> ttdList = event.get(TrackTimeData.class, trackTimeDataCollectionName);
- for (TrackTimeData ttd : ttdList) {
+ List<GenericObject> ttdList = event.get(GenericObject.class, trackTimeDataCollectionName);
+ for (GenericObject ttd : ttdList) {
int nResid = ttd.getNDouble();
for (int i = 0; i < nResid; i++)
- aida.histogram1D(plotDir + "Half-Layer " + i + " t Residual").fill(ttd.getDoubleVal(i));//x is the double value in the generic object
+ aida.histogram1D(plotDir + timeresDir + "HalfModule " + i + " t Residual").fill(ttd.getDoubleVal(i));//x is the double value in the generic object
}
-
}
@Override
public void calculateEndOfRunQuantities() {
-// monitoredQuantityMap.put(trackingQuantNames[0], (double) nTotTracks / nEvents);
+ IAnalysisFactory analysisFactory = IAnalysisFactory.create();
+ IFitFactory fitFactory = analysisFactory.createFitFactory();
+ IFitter fitter = fitFactory.createFitter("chi2");
+ IPlotter plotterXTop = analysisFactory.createPlotterFactory().create("x-residual Top");
+ IPlotter plotterXBottom = analysisFactory.createPlotterFactory().create("x-residual Bottom");
+ IPlotter plotterYTop = analysisFactory.createPlotterFactory().create("y-residual Top");
+ IPlotter plotterYBottom = analysisFactory.createPlotterFactory().create("y-residual Bottom");
+
+ IPlotter plotterTime = analysisFactory.createPlotterFactory().create("Track Time");
+
+ plotterXTop.createRegions(2, 3);
+ IPlotterStyle pstyle = plotterXTop.style();
+ pstyle.legendBoxStyle().setVisible(false);
+ plotterXBottom.createRegions(2, 3);
+ IPlotterStyle pstyle2 = plotterXBottom.style();
+ pstyle2.legendBoxStyle().setVisible(false);
+
+ plotterYTop.createRegions(2, 3);
+ IPlotterStyle pstyle3 = plotterYTop.style();
+ pstyle3.legendBoxStyle().setVisible(false);
+ plotterYBottom.createRegions(2, 3);
+ IPlotterStyle pstyle4 = plotterYBottom.style();
+ pstyle4.legendBoxStyle().setVisible(false);
+
+ plotterTime.createRegions(3, 4);
+ IPlotterStyle pstyle5 = plotterTime.style();
+ pstyle5.legendBoxStyle().setVisible(false);
+
+ int irXTop = 0;
+ int irXBot = 0;
+ int irYTop = 0;
+ int irYBot = 0;
+ for (int i = 0; i < nmodules; i++) {
+ IHistogram1D xresidTop = aida.histogram1D(plotDir + posresDir + "Module " + i + "Top x Residual");
+ IHistogram1D yresidTop = aida.histogram1D(plotDir + posresDir + "Module " + i + "Top y Residual");
+ IHistogram1D xresidBot = aida.histogram1D(plotDir + posresDir + "Module " + i + "Bot x Residual");
+ IHistogram1D yresidBot = aida.histogram1D(plotDir + posresDir + "Module " + i + "Bot y Residual");
+ IFitResult xresultTop = fitGaussian(xresidTop, fitter, "range=\"(-1.0,1.0)\"");
+ IFitResult yresultTop = fitGaussian(yresidTop, fitter, "range=\"(-0.5,0.5)\"");
+ IFitResult xresultBot = fitGaussian(xresidBot, fitter, "range=\"(-1.0,1.0)\"");
+ IFitResult yresultBot = fitGaussian(yresidBot, fitter, "range=\"(-8.0,8.0)\"");
+ double[] parsXTop = xresultTop.fittedParameters();
+ double[] parsYTop = yresultTop.fittedParameters();
+ double[] parsXBot = xresultBot.fittedParameters();
+ double[] parsYBot = yresultBot.fittedParameters();
+
+ plotterXTop.region(irXTop).plot(xresidTop);
+ plotterXTop.region(irXTop).plot(xresultTop.fittedFunction());
+ irXTop++;
+ plotterXBottom.region(irXBot).plot(xresidBot);
+ plotterXBottom.region(irXBot).plot(xresultBot.fittedFunction());
+ irXBot++;
+
+ plotterYTop.region(irYTop).plot(yresidTop);
+ plotterYTop.region(irYTop).plot(yresultTop.fittedFunction());
+ irYTop++;
+ plotterYBottom.region(irYBot).plot(yresidBot);
+ plotterYBottom.region(irYBot).plot(yresultBot.fittedFunction());
+ irYBot++;
+
+ xposTopMeanResidMap.put(getQuantityName(0, 0, 1, i) + "_x", parsXTop[1]);
+ xposTopSigmaResidMap.put(getQuantityName(0, 1, 1, i) + "_x", parsXTop[2]);
+ yposTopMeanResidMap.put(getQuantityName(0, 0, 1, i) + "_y", parsYTop[1]);
+ yposTopSigmaResidMap.put(getQuantityName(0, 1, 1, i) + "_y", parsYTop[2]);
+ xposBotMeanResidMap.put(getQuantityName(0, 0, 0, i) + "_x", parsXBot[1]);
+ xposBotSigmaResidMap.put(getQuantityName(0, 1, 0, i) + "_x", parsXBot[2]);
+ yposBotMeanResidMap.put(getQuantityName(0, 0, 0, i) + "_y", parsYBot[1]);
+ yposBotSigmaResidMap.put(getQuantityName(0, 1, 0, i) + "_y", parsYBot[2]);
+
+ }
+ int iTime = 0;
+ for (int i = 0; i < nmodules * 2; i++) {
+ IHistogram1D tresid = aida.histogram1D(plotDir + timeresDir + "HalfModule " + i + " t Residual");
+ IFitResult tresult = fitGaussian(tresid, fitter, "range=\"(-15.0,15.0)\"");
+ double[] parsTime = tresult.fittedParameters();
+ plotterTime.region(iTime).plot(tresid);
+ plotterTime.region(iTime).plot(tresult.fittedFunction());
+ iTime++;
+
+ timeMeanResidMap.put(getQuantityName(1, 0, 2, i) + "_dt", parsTime[1]);
+ timeSigmaResidMap.put(getQuantityName(1, 1, 2, i) + "_dt", parsTime[2]);
+
+ }
+
+ if (outputPlots) {
+ try {
+ plotterXTop.writeToFile(outputPlotDir + "X-Residuals-Top.png");
+ } catch (IOException ex) {
+ Logger.getLogger(SvtMonitoring.class.getName()).log(Level.SEVERE, null, ex);
+ }
+ try {
+ plotterYTop.writeToFile(outputPlotDir + "Y-Residuals-Top.png");
+ } catch (IOException ex) {
+ Logger.getLogger(SvtMonitoring.class.getName()).log(Level.SEVERE, null, ex);
+ }
+ try {
+ plotterXBottom.writeToFile(outputPlotDir + "X-Residuals-Bottom.png");
+ } catch (IOException ex) {
+ Logger.getLogger(SvtMonitoring.class.getName()).log(Level.SEVERE, null, ex);
+ }
+ try {
+ plotterYBottom.writeToFile(outputPlotDir + "Y-Residuals-Bottom.png");
+ } catch (IOException ex) {
+ Logger.getLogger(SvtMonitoring.class.getName()).log(Level.SEVERE, null, ex);
+ }
+ try {
+ plotterTime.writeToFile(outputPlotDir + "Time-Residuals.png");
+ } catch (IOException ex) {
+ Logger.getLogger(SvtMonitoring.class.getName()).log(Level.SEVERE, null, ex);
+ }
+ }
+
}
+ private String getQuantityName(int itype, int iquant, int top, int nlayer) {
+ String typeString = "position_resid";
+ String quantString = "mean_";
+ if (itype == 1)
+ typeString = "time_resid";
+ if (iquant == 1)
+ quantString = "sigma_";
+
+ String botString = "bot_";
+ if (top == 1)
+ botString = "top_";
+ if (top == 2)
+ botString = "";
+
+ String layerString = "module" + nlayer;
+ if (itype == 1)
+ layerString = "halfmodule" + nlayer;
+
+ return typeString + quantString + botString + layerString;
+ }
+
@Override
public void printDQMData() {
-// System.out.println("ReconMonitoring::printDQMData");
-// for (Map.Entry<String, Double> entry : monitoredQuantityMap.entrySet())
-// System.out.println(entry.getKey() + " = " + entry.getValue());
-// System.out.println("*******************************");
+ System.out.println("TrackingResiduals::printDQMData");
+ for (Map.Entry<String, Double> entry : xposTopMeanResidMap.entrySet())
+ System.out.println(entry.getKey() + " = " + entry.getValue());
+ for (Map.Entry<String, Double> entry : xposBotMeanResidMap.entrySet())
+ System.out.println(entry.getKey() + " = " + entry.getValue());
+ for (Map.Entry<String, Double> entry : xposTopSigmaResidMap.entrySet())
+ System.out.println(entry.getKey() + " = " + entry.getValue());
+ for (Map.Entry<String, Double> entry : xposBotSigmaResidMap.entrySet())
+ System.out.println(entry.getKey() + " = " + entry.getValue());
+ for (Map.Entry<String, Double> entry : yposTopMeanResidMap.entrySet())
+ System.out.println(entry.getKey() + " = " + entry.getValue());
+ for (Map.Entry<String, Double> entry : yposBotMeanResidMap.entrySet())
+ System.out.println(entry.getKey() + " = " + entry.getValue());
+ for (Map.Entry<String, Double> entry : yposTopSigmaResidMap.entrySet())
+ System.out.println(entry.getKey() + " = " + entry.getValue());
+ for (Map.Entry<String, Double> entry : yposBotSigmaResidMap.entrySet())
+ System.out.println(entry.getKey() + " = " + entry.getValue());
+ for (Map.Entry<String, Double> entry : timeMeanResidMap.entrySet())
+ System.out.println(entry.getKey() + " = " + entry.getValue());
+ for (Map.Entry<String, Double> entry : timeSigmaResidMap.entrySet())
+ System.out.println(entry.getKey() + " = " + entry.getValue());
+ System.out.println("*******************************");
}
@Override
public void printDQMStrings() {
-// for (Map.Entry<String, Double> entry : monitoredQuantityMap.entrySet())
-// System.out.println("ALTER TABLE dqm ADD " + entry.getKey() + " double;");
+ for (Map.Entry<String, Double> entry : xposTopMeanResidMap.entrySet())
+ System.out.println("ALTER TABLE dqm ADD " + entry.getKey() + " double;");
+ for (Map.Entry<String, Double> entry : xposBotMeanResidMap.entrySet())
+ System.out.println("ALTER TABLE dqm ADD " + entry.getKey() + " double;");
+ for (Map.Entry<String, Double> entry : xposTopSigmaResidMap.entrySet())
+ System.out.println("ALTER TABLE dqm ADD " + entry.getKey() + " double;");
+ for (Map.Entry<String, Double> entry : xposBotSigmaResidMap.entrySet())
+ System.out.println("ALTER TABLE dqm ADD " + entry.getKey() + " double;");
+ for (Map.Entry<String, Double> entry : yposTopMeanResidMap.entrySet())
+ System.out.println("ALTER TABLE dqm ADD " + entry.getKey() + " double;");
+ for (Map.Entry<String, Double> entry : yposBotMeanResidMap.entrySet())
+ System.out.println("ALTER TABLE dqm ADD " + entry.getKey() + " double;");
+ for (Map.Entry<String, Double> entry : yposTopSigmaResidMap.entrySet())
+ System.out.println("ALTER TABLE dqm ADD " + entry.getKey() + " double;");
+ for (Map.Entry<String, Double> entry : yposBotSigmaResidMap.entrySet())
+ System.out.println("ALTER TABLE dqm ADD " + entry.getKey() + " double;");
+ for (Map.Entry<String, Double> entry : timeMeanResidMap.entrySet())
+ System.out.println("ALTER TABLE dqm ADD " + entry.getKey() + " double;");
+ for (Map.Entry<String, Double> entry : timeSigmaResidMap.entrySet())
+ System.out.println("ALTER TABLE dqm ADD " + entry.getKey() + " double;");
+ }
+ private void resetOccupancyMap() {
+ xposBotMeanResidMap = new HashMap<>();
+ xposBotSigmaResidMap = new HashMap<>();
+ yposBotMeanResidMap = new HashMap<>();
+ yposBotSigmaResidMap = new HashMap<>();
+ xposTopMeanResidMap = new HashMap<>();
+ xposTopSigmaResidMap = new HashMap<>();
+ yposTopMeanResidMap = new HashMap<>();
+ yposTopSigmaResidMap = new HashMap<>();
+ timeMeanResidMap = new HashMap<>();
+ timeSigmaResidMap = new HashMap<>();
+ for (int i = 0; i < nmodules; i++) {
+ xposTopMeanResidMap.put(getQuantityName(0, 0, 1, i) + "_x", -999.);
+ yposTopMeanResidMap.put(getQuantityName(0, 0, 1, i) + "_y", -999.);
+ xposTopSigmaResidMap.put(getQuantityName(0, 1, 1, i) + "_x", -999.);
+ yposTopSigmaResidMap.put(getQuantityName(0, 1, 1, i) + "_y", -999.);
+ xposBotMeanResidMap.put(getQuantityName(0, 0, 0, i) + "_x", -999.);
+ yposBotMeanResidMap.put(getQuantityName(0, 0, 0, i) + "_y", -999.);
+ xposBotSigmaResidMap.put(getQuantityName(0, 1, 0, i) + "_x", -999.);
+ yposBotSigmaResidMap.put(getQuantityName(0, 1, 0, i) + "_y", -999.);
+ }
+ for (int i = 0; i < nmodules * 2; i++) {
+ timeMeanResidMap.put(getQuantityName(1, 0, 2, i) + "_dt", -999.);
+ timeSigmaResidMap.put(getQuantityName(1, 1, 2, i) + "_dt", -999.);
+ }
+
}
+ IFitResult fitGaussian(IHistogram1D h1d, IFitter fitter, String range) {
+ double[] init = {20.0, 0.0, 0.2};
+ return fitter.fit(h1d, "g", init,range);
+// double[] init = {20.0, 0.0, 1.0, 20, -1};
+// return fitter.fit(h1d, "g+p1", init, range);
+ }
+
+ private double getRange(int layer, boolean isX) {
+ double range = 2.5;
+ if (isX) {
+ if (layer == 0)
+ return 0.5;
+ if (layer == 1)
+ return 0.5;
+ if (layer == 2)
+ return 0.5;
+ if (layer == 3)
+ return 1.0;
+ if (layer == 4)
+ return 1.0;
+ if (layer == 5)
+ return 1.0;
+ } else {
+ if (layer == 0)
+ return 0.005;
+ if (layer == 1)
+ return 0.5;
+ if (layer == 2)
+ return 0.5;
+ if (layer == 3)
+ return 1.0;
+ if (layer == 4)
+ return 1.0;
+ if (layer == 5)
+ return 1.5;
+ }
+ return range;
+
+ }
+
}
java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality
--- java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality/V0Monitoring.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/analysis/src/main/java/org/hps/analysis/dataquality/V0Monitoring.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -23,8 +23,8 @@
* DQM driver V0 particles (i.e. e+e- pars) plots
* things like number of vertex position an mass
*
- * @author mgraham on May 14, 2014
-
+ * @author mgraham on May 14, 2014
+ *
*/
public class V0Monitoring extends DataQualityMonitor {
@@ -32,7 +32,7 @@
String unconstrainedV0CandidatesColName = "UnconstrainedV0Candidates";
String beamConV0CandidatesColName = "BeamspotConstrainedV0Candidates";
String targetV0ConCandidatesColName = "TargetConstrainedV0Candidates";
- String[] fpQuantNames = {"nV0_per_Event", "avg_BSCon_mass", "avg_BSCon_Vx", "avg_BSCon_Vy", "avg_BSCon_Vz", "avg_BSCon_Chi2"};
+ String[] fpQuantNames = {"nV0_per_Event", "avg_BSCon_mass", "avg_BSCon_Vx", "avg_BSCon_Vy", "avg_BSCon_Vz", "sig_BSCon_Vx", "sig_BSCon_Vy", "sig_BSCon_Vz", "avg_BSCon_Chi2"};
//some counters
int nRecoEvents = 0;
int nTotV0 = 0;
@@ -100,16 +100,13 @@
}
List<ReconstructedParticle> targetConstrainedV0List = event.get(ReconstructedParticle.class, targetV0ConCandidatesColName);
-// System.out.println("Number of V0s = " + targetConstrainedV0List.size());
for (ReconstructedParticle tarV0 : targetConstrainedV0List) {
Vertex tarVert = tarV0.getStartVertex();
-// System.out.println(tarVert.toString());
aida.histogram1D(plotDir + "Target Constrained Vx (mm)").fill(tarVert.getPosition().x());
aida.histogram1D(plotDir + "Target Constrained Vy (mm)").fill(tarVert.getPosition().y());
aida.histogram1D(plotDir + "Target Constrained Vz (mm)").fill(tarVert.getPosition().z());
aida.histogram1D(plotDir + "Target Constrained Mass (GeV)").fill(tarV0.getMass());
aida.histogram1D(plotDir + "Target Constrained Chi2").fill(tarVert.getChi2());
- // System.out.println("Target Constrained chi^2 = " + tarVert.getChi2());
}
}
@@ -126,12 +123,6 @@
*/
@Override
public void calculateEndOfRunQuantities() {
- monitoredQuantityMap.put(fpQuantNames[0], (double) nTotV0 / nRecoEvents);
- monitoredQuantityMap.put(fpQuantNames[1], sumMass / nTotV0);
- monitoredQuantityMap.put(fpQuantNames[2], sumVx / nTotV0);
- monitoredQuantityMap.put(fpQuantNames[3], sumVy / nTotV0);
- monitoredQuantityMap.put(fpQuantNames[4], sumVz / nTotV0);
- monitoredQuantityMap.put(fpQuantNames[5], sumChi2 / nTotV0);
IAnalysisFactory analysisFactory = IAnalysisFactory.create();
IFitFactory fitFactory = analysisFactory.createFitFactory();
@@ -146,13 +137,13 @@
double[] init3 = {50.0, 0.0, 3.0, 1.0, 0.0};
IFitResult resVz = fitVertexPosition(bsconVz, fitter, init3, "range=\"(-6,6)\"");
- for (int i = 0; i < 5; i++) {
- double parVx = resVx.fittedParameters()[i];
- double parVy = resVy.fittedParameters()[i];
- double parVz = resVz.fittedParameters()[i];
- System.out.println("Vertex Fit Parameters: " + resVx.fittedParameterNames()[i] + " = " + parVx + "; " + parVy + "; " + parVz);
- }
+ double[] parsVx = resVx.fittedParameters();
+ double[] parsVy = resVy.fittedParameters();
+ double[] parsVz = resVz.fittedParameters();
+ for (int i = 0; i < 5; i++)
+ System.out.println("Vertex Fit Parameters: " + resVx.fittedParameterNames()[i] + " = " + parsVx[i] + "; " + parsVy[i] + "; " + parsVz[i]);
+
IPlotter plotter = analysisFactory.createPlotterFactory().create("Vertex Position");
plotter.createRegions(1, 3);
IPlotterStyle pstyle = plotter.style();
@@ -171,11 +162,25 @@
Logger.getLogger(V0Monitoring.class.getName()).log(Level.SEVERE, null, ex);
}
+ monitoredQuantityMap.put(fpQuantNames[0], (double) nTotV0 / nRecoEvents);
+ monitoredQuantityMap.put(fpQuantNames[1], sumMass / nTotV0);
+// monitoredQuantityMap.put(fpQuantNames[2], sumVx / nTotV0);
+// monitoredQuantityMap.put(fpQuantNames[3], sumVy / nTotV0);
+// monitoredQuantityMap.put(fpQuantNames[4], sumVz / nTotV0);
+ monitoredQuantityMap.put(fpQuantNames[2], parsVx[1]);
+ monitoredQuantityMap.put(fpQuantNames[3], parsVy[1]);
+ monitoredQuantityMap.put(fpQuantNames[4], parsVz[1]);
+ monitoredQuantityMap.put(fpQuantNames[5], parsVx[2]);
+ monitoredQuantityMap.put(fpQuantNames[6], parsVy[2]);
+ monitoredQuantityMap.put(fpQuantNames[7], parsVz[2]);
+
+ monitoredQuantityMap.put(fpQuantNames[8], sumChi2 / nTotV0);
+
}
@Override
public void printDQMStrings() {
- for (int i = 0; i < 7; i++)//TODO: do this in a smarter way...loop over the map
+ for (int i = 0; i < 9; i++)//TODO: do this in a smarter way...loop over the map
System.out.println("ALTER TABLE dqm ADD " + fpQuantNames[i] + " double;");
}
java/branches/hps-java_HPSJAVA-88/conditions
--- java/branches/hps-java_HPSJAVA-88/conditions/pom.xml 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/conditions/pom.xml 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,25 +1,20 @@
<?xml version="1.0"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>hps-conditions</artifactId>
<name>conditions</name>
<description>HPS conditions framework</description>
-
<parent>
<groupId>org.hps</groupId>
<artifactId>hps-parent</artifactId>
<relativePath>../parent/pom.xml</relativePath>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</parent>
-
<scm>
<url>http://java.freehep.org/svn/repos/hps/list/java/trunk/conditions/</url>
<connection>scm:svn:svn://svn.freehep.org/hps/java/trunk/conditions/</connection>
<developerConnection>scm:svn:svn://svn.freehep.org/hps/java/trunk/conditions/</developerConnection>
</scm>
-
<build>
<plugins>
<plugin>
@@ -27,13 +22,19 @@
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
+ <exclude>org/hps/conditions/**/**.java</exclude>
+ <!--
<exclude>org/hps/conditions/ConditionsObjectTest.java</exclude>
+ <exclude>org/hps/conditions/**.java</exclude>
+ <exclude>org/hps/conditions/beam/**.java</exclude>
+ <exclude>org/hps/conditions/ecal/**.java</exclude>
+ <exclude>org/hps/conditions/svt/**.java</exclude>
+ -->
</excludes>
</configuration>
</plugin>
</plugins>
</build>
-
<dependencies>
<dependency>
<groupId>org.lcsim</groupId>
@@ -54,5 +55,4 @@
<version>5.1.26</version>
</dependency>
</dependencies>
-
</project>
java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions
--- java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions/AbstractConditionsObject.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions/AbstractConditionsObject.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -166,7 +166,14 @@
return collectionId != -1;
}
- // protected void finalize() {
- // System.out.println("finalizing ConditionsObject " + System.identityHashCode(this));
- // }
+ public String toString() {
+ StringBuffer sb = new StringBuffer();
+ sb.append("id: ").append(getRowId()).append('\n');
+ sb.append("collection_id: ").append(getCollectionId()).append('\n');
+ sb.append("read_only: ").append(isReadOnly()).append('\n');
+ for (String fieldName : getTableMetaData().getFieldNames()) {
+ sb.append(fieldName).append(": ").append(getFieldValue(fieldName).toString()).append('\n');
+ }
+ return sb.toString();
+ }
}
\ No newline at end of file
java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions
--- java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions/ConditionsObjectConverter.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions/ConditionsObjectConverter.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -112,6 +112,6 @@
}
public boolean allowMultipleCollections() {
- return false;
+ return true;
}
}
java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions
--- java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions/ConditionsRecord.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions/ConditionsRecord.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -128,6 +128,14 @@
public int getCollectionId() {
return getFieldValue("collection_id");
}
+
+ /**
+ * Get the string tag associated with these conditions.
+ * @return The string tag.
+ */
+ public String getTag() {
+ return getFieldValue("tag");
+ }
/**
* Convert this record to a human readable string, one field per line.
@@ -145,6 +153,7 @@
buff.append("created: " + getCreated() + '\n');
buff.append("validFrom: " + getValidFrom() + '\n');
buff.append("validTo: " + getValidTo() + '\n');
+ buff.append("tag: " + getTag() + '\n');
buff.append("createdBy: " + getCreatedBy() + '\n');
buff.append("formatVersion: " + getFormatVersion() + '\n');
buff.append("notes: " + getNotes() + '\n');
java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions
--- java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions/DatabaseConditionsManager.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions/DatabaseConditionsManager.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -47,26 +47,27 @@
@SuppressWarnings("rawtypes")
public final class DatabaseConditionsManager extends ConditionsManagerImplementation {
- int runNumber = -1;
- String detectorName;
- List<TableMetaData> tableMetaData;
- List<ConditionsConverter> converters;
- File connectionPropertiesFile;
- ConditionsReader baseReader;
- static Logger logger = null;
- ConnectionParameters connectionParameters;
- Connection connection;
- boolean wasConfigured = false;
- boolean isConnected = false;
- ConditionsSeriesConverter conditionsSeriesConverter = new ConditionsSeriesConverter(this);
+ static String connectionProperty = "org.hps.conditions.connection.file";
+ protected int runNumber = -1;
+ protected String detectorName;
+ protected List<TableMetaData> tableMetaData;
+ protected List<ConditionsConverter> converters;
+ protected File connectionPropertiesFile;
+ protected ConditionsReader baseReader;
+ protected static Logger logger = null;
+ protected ConnectionParameters connectionParameters;
+ protected Connection connection;
+ protected boolean wasConfigured = false;
+ protected boolean isConnected = false;
+ protected ConditionsSeriesConverter conditionsSeriesConverter = new ConditionsSeriesConverter(this);
/**
- * Class constructor, which is only package accessible. Users should call
- * {@link #getInstance()} to access the manager.
+ * Class constructor.
*/
- DatabaseConditionsManager() {
+ public DatabaseConditionsManager() {
registerConditionsConverter(new DetectorConditionsConverter());
baseReader = new BaseClasspathConditionsReader();
+ setupConnectionFromSystemProperty();
}
/**
@@ -98,7 +99,7 @@
/**
* Register this conditions manager as the global default.
*/
- void register() {
+ public void register() {
ConditionsManager.setDefaultConditionsManager(this);
}
@@ -124,6 +125,10 @@
return (DatabaseConditionsManager) manager;
}
+
+ public Connection getConnection() {
+ return this.connection;
+ }
/**
* This method catches changes to the detector name and run number. Somewhat
@@ -246,10 +251,7 @@
* @param tableName The name of the table.
* @return The next collection ID.
*/
- // FIXME: If there are no collections that exist, this method should simply return the
- // value '1'
- // or it could throw an exception.
- public int getNextCollectionId(String tableName) {
+ public int getNextCollectionID(String tableName) {
TableMetaData tableData = findTableMetaData(tableName);
if (tableData == null)
throw new IllegalArgumentException("There is no meta data for table " + tableName);
@@ -508,11 +510,26 @@
// Load table meta data from the "tables" section of the config document.
(this.new TableMetaDataLoader()).load(config.getRootElement().getChild("tables"));
}
+
+ /**
+ * Setup the database connection from a file specified by Java system property setting.
+ * This is possible overridden by subsequent API calls to {@link #setConnectionProperties(File)} or
+ * {@link #setConnectionResource(String)}, as it is setup in this class's constructor.
+ */
+ private void setupConnectionFromSystemProperty() {
+ String systemPropertiesConnectionPath = (String)System.getProperties().get(connectionProperty);
+ if (systemPropertiesConnectionPath != null) {
+ File f = new File(systemPropertiesConnectionPath);
+ if (!f.exists())
+ throw new RuntimeException("Connection properties specified from system property does not exist!");
+ this.setConnectionProperties(f);
+ }
+ }
/**
* Open the database connection.
*/
- private void openConnection() {
+ public void openConnection() {
if (connectionParameters == null)
throw new RuntimeException("The connection parameters were not configured.");
connection = connectionParameters.createConnection();
@@ -547,10 +564,20 @@
closeConnection();
}
+ /**
+ * Get multiple <code>ConditionsObjectCollection</code> objects that may have overlapping time validity information.
+ * @param conditionsKey The conditions key.
+ * @return The <code>ConditionsSeries</code> containing the matching <code>ConditionsObjectCollection</code>.
+ */
public <CollectionType extends ConditionsObjectCollection> ConditionsSeries<CollectionType> getConditionsSeries(String conditionsKey) {
return conditionsSeriesConverter.createSeries(conditionsKey);
}
+ /**
+ * Simple utility method to cast the generic <code>ConditionsManager</code> to this class.
+ * @param conditionsManager The <code>ConditionsManager</code>.
+ * @return The <code>DatabaseConditionsManager</code> object.
+ */
public static DatabaseConditionsManager castFrom(ConditionsManager conditionsManager) {
if (conditionsManager instanceof DatabaseConditionsManager) {
return (DatabaseConditionsManager) conditionsManager;
java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions
--- java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions/DefaultTestSetup.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions/DefaultTestSetup.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,79 +0,0 @@
-package org.hps.conditions;
-
-import org.lcsim.conditions.ConditionsManager.ConditionsNotFoundException;
-
-/**
- * <p>
- * This is a static utility class for setting up the conditions system for test cases in
- * this package and sub-packages.
- * </p>
- * <p>
- * It uses the SLAC Test Run 2012 conditions database, with a relative reference to a file
- * containing connection parameters in the hps-conditions module. The XML configuration is
- * read from a classpath resource in the same module.
- * </p>
- * <p>
- * The detector is set to <i>HPS-conditions-test</i>, which is a test detector without
- * real data associated to it. There are a few files used in the test cases that use this
- * detector.
- * </p>
- * <p>
- * The run number is initially set to <i>1351</i> which is one of the "good runs".
- * </p>
- * <p>
- * Full setup can be performed with this method chain: <code>
- * DatabaseConditionsManager manager = new DefaultTestSetup().configure().setup();
- * </code>
- * </p>
- * <p>
- * To only configure the system without setting up detector and run, use the following:
- * <code>
- * new DefaultTestSetup().configure();
- * </code>
- * </p>
- *
- * @author Jeremy McCormick <[log in to unmask]>
- */
-public final class DefaultTestSetup {
-
- // Default conditions manager parameters.
- static String connectionResource = "/org/hps/conditions/config/conditions_database_testrun_2012_connection.properties";
- static String conditionsConfig = "/org/hps/conditions/config/conditions_database_testrun_2012.xml";
-
- // Default test detector and run number for test cases not using real data.
- static String detectorName = "HPS-conditions-test";
- static int runNumber = 1351;
-
- DatabaseConditionsManager conditionsManager;
- boolean wasConfigured = false;
-
- /**
- * Configure and register the {@link DatabaseConditionsManager} with default
- * parameters.
- * @return an instance of this class for chaining (e.g. to call {@link #setup()}.
- */
- public DefaultTestSetup configure() {
- conditionsManager = new DatabaseConditionsManager();
- conditionsManager.setConnectionResource(connectionResource);
- conditionsManager.configure(conditionsConfig);
- conditionsManager.register();
- wasConfigured = true;
- return this;
- }
-
- /**
- * Setup the detector and run number conditions for the conditions manager. This is
- * mostly useful for test cases not using an <code>LCSimLoop</code>.
- * @return the conditions manager
- */
- public DatabaseConditionsManager setup() {
- if (!wasConfigured)
- configure();
- try {
- conditionsManager.setDetector(detectorName, runNumber);
- } catch (ConditionsNotFoundException e) {
- throw new RuntimeException(e);
- }
- return conditionsManager;
- }
-}
\ No newline at end of file
java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions
--- java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions/DetectorSetup.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions/DetectorSetup.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,53 +0,0 @@
-package org.hps.conditions;
-
-import org.lcsim.conditions.ConditionsManager.ConditionsNotFoundException;
-
-/**
- * @author Jeremy McCormick <[log in to unmask]>
- */
-public final class DetectorSetup {
-
- // Default conditions manager parameters.
- static final String connectionResource = "/org/hps/conditions/config/conditions_database_testrun_2012_connection.properties";
- static final String conditionsConfig = "/org/hps/conditions/config/conditions_database_testrun_2012.xml";
-
- String detectorName;
- int runNumber;
- DatabaseConditionsManager conditionsManager;
- boolean wasConfigured = false;
-
- public DetectorSetup(String detectorName, int runNumber) {
- this.detectorName = detectorName;
- this.runNumber = runNumber;
- }
-
- /**
- * Configure and register the {@link DatabaseConditionsManager} with default
- * parameters.
- * @return an instance of this class for chaining (e.g. to call {@link #setup()}.
- */
- public DetectorSetup configure() {
- conditionsManager = new DatabaseConditionsManager();
- conditionsManager.setConnectionResource(connectionResource);
- conditionsManager.configure(conditionsConfig);
- conditionsManager.register();
- wasConfigured = true;
- return this;
- }
-
- /**
- * Setup the detector and run number conditions for the conditions manager. This is
- * mostly useful for test cases not using an <code>LCSimLoop</code>.
- * @return the conditions manager
- */
- public DatabaseConditionsManager setup() {
- if (!wasConfigured)
- configure();
- try {
- conditionsManager.setDetector(detectorName, runNumber);
- } catch (ConditionsNotFoundException e) {
- throw new RuntimeException(e);
- }
- return conditionsManager;
- }
-}
\ No newline at end of file
java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions
--- java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions/TableConstants.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions/TableConstants.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -39,10 +39,19 @@
/** ECAL time shifts. */
public static final String ECAL_TIME_SHIFTS = "ecal_time_shifts";
+
+ /** ECAL LED setup. */
+ public static final String ECAL_LEDS = "ecal_leds";
- /** Conditions key for combined ECal conditions. */
+ /** Conditions key for combined SVT conditions. */
public static final String SVT_CONDITIONS = "svt_conditions";
+
+ /** Conditions key for SVT alignment data. */
+ public static final String SVT_ALIGNMENTS = "svt_alignments";
+ /** Conditions key for SVT bad channels. */
+ public static final String SVT_BAD_CHANNELS = "svt_bad_channels";
+
/** Table with SVT channel data. */
public static final String SVT_CHANNELS = "svt_channels";
@@ -51,10 +60,10 @@
/** Conditions key for SVT calibration data. */
public static final String SVT_CALIBRATIONS = "svt_calibrations";
+
+ /** Conditions key for SVT configuration files. */
+ public static final String SVT_CONFIGURATIONS = "svt_configurations";
- /** Conditions key for SVT bad channels. */
- public static final String SVT_BAD_CHANNELS = "svt_bad_channels";
-
/** Conditions key for SVT pulse parameters. */
public static final String SVT_PULSE_PARAMETERS = "svt_pulse_parameters";
java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions/ecal
--- java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions/ecal/EcalConverterRegistry.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions/ecal/EcalConverterRegistry.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -5,6 +5,7 @@
import org.hps.conditions.ecal.EcalCalibration.EcalCalibrationCollection;
import org.hps.conditions.ecal.EcalChannel.EcalChannelCollection;
import org.hps.conditions.ecal.EcalGain.EcalGainCollection;
+import org.hps.conditions.ecal.EcalLed.EcalLedCollection;
import org.hps.conditions.ecal.EcalTimeShift.EcalTimeShiftCollection;
/**
@@ -46,4 +47,10 @@
return EcalTimeShiftCollection.class;
}
}
+
+ public static final class EcalLedConverter extends ConditionsObjectConverter<EcalLed> {
+ public Class getType() {
+ return EcalLedCollection.class;
+ }
+ }
}
java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions/svt
--- java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions/svt/SvtAlignmentConstant.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions/svt/SvtAlignmentConstant.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,6 +1,7 @@
package org.hps.conditions.svt;
import org.hps.conditions.AbstractConditionsObject;
+import org.hps.conditions.ConditionsObjectCollection;
/**
* <p>
@@ -18,6 +19,9 @@
*/
public class SvtAlignmentConstant extends AbstractConditionsObject {
+ public static class SvtAlignmentCollection extends ConditionsObjectCollection<SvtAlignmentConstant> {
+ }
+
/** Top or bottom half. */
public enum Half {
TOP(1),
@@ -65,8 +69,8 @@
* Get the alignment constant's full key with the encoded information.
* @return the alignment constant's key
*/
- public String getKey() {
- return getFieldValue("key");
+ public String getParameter() {
+ return getFieldValue("parameter");
}
/**
@@ -82,13 +86,13 @@
* @return the Half value from the key
*/
public Half getHalf() {
- int half = Integer.parseInt(getKey().substring(0,0));
+ int half = Integer.parseInt(getParameter().substring(0, 1));
if (half == Half.TOP.getValue()) {
return Half.TOP;
- } else if (half == Half.TOP.getValue()) {
+ } else if (half == Half.BOTTOM.getValue()) {
return Half.BOTTOM;
} else {
- throw new IllegalArgumentException("Could not parse valid Half from " + getKey());
+ throw new IllegalArgumentException("Could not parse valid Half from " + getParameter());
}
}
@@ -97,13 +101,13 @@
* @return the AlignmentType value from the key
*/
public AlignmentType getAlignmentType() {
- int alignmentType = Integer.parseInt(getKey().substring(1, 1));
+ int alignmentType = Integer.parseInt(getParameter().substring(1, 2));
if (alignmentType == AlignmentType.TRANSLATION.getValue()) {
return AlignmentType.TRANSLATION;
} else if (alignmentType == AlignmentType.ROTATION.getValue()) {
return AlignmentType.ROTATION;
} else {
- throw new IllegalArgumentException("Could not parse valid AlignmentType from " + getKey());
+ throw new IllegalArgumentException("Could not parse valid AlignmentType from " + getParameter());
}
}
@@ -112,7 +116,7 @@
* @return the UnitAxis v
*/
public UnitAxis getUnitAxis() {
- int unitAxis = Integer.parseInt(getKey().substring(3,3));
+ int unitAxis = Integer.parseInt(getParameter().substring(2, 3));
if (unitAxis == UnitAxis.U.getValue()) {
return UnitAxis.U;
} else if (unitAxis == UnitAxis.V.getValue()) {
@@ -120,7 +124,7 @@
} else if (unitAxis == UnitAxis.W.getValue()) {
return UnitAxis.W;
} else {
- throw new IllegalArgumentException("Could not parse valid UnitAxis from " + getKey());
+ throw new IllegalArgumentException("Could not parse valid UnitAxis from " + getParameter());
}
}
@@ -129,10 +133,20 @@
* @return the module number from the key
*/
public int getModuleNumber() {
- int moduleNumber = Integer.parseInt(getKey().substring(3, 4));
+ int moduleNumber = Integer.parseInt(getParameter().substring(3, 5));
if (moduleNumber > MAX_MODULE_NUMBER || moduleNumber == 0) {
throw new IllegalArgumentException("The decoded module number " + moduleNumber + " is invalid.");
}
return moduleNumber;
}
+
+ public String toString() {
+ StringBuffer buff = new StringBuffer();
+ buff.append(super.toString());
+ buff.append("half: ").append(getHalf().getValue()).append('\n');
+ buff.append("alignment_type: ").append(getAlignmentType().getValue()).append('\n');
+ buff.append("unit_axis: ").append(getUnitAxis().getValue()).append('\n');
+ buff.append("module_number: " ).append(getModuleNumber()).append('\n');
+ return buff.toString();
+ }
}
\ No newline at end of file
java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions/svt
--- java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions/svt/SvtConverterRegistry.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/conditions/src/main/java/org/hps/conditions/svt/SvtConverterRegistry.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,25 +1,33 @@
package org.hps.conditions.svt;
import org.hps.conditions.ConditionsObjectConverter;
+import org.hps.conditions.svt.SvtAlignmentConstant.SvtAlignmentCollection;
import org.hps.conditions.svt.SvtBadChannel.SvtBadChannelCollection;
import org.hps.conditions.svt.SvtCalibration.SvtCalibrationCollection;
import org.hps.conditions.svt.SvtChannel.SvtChannelCollection;
+import org.hps.conditions.svt.SvtConfiguration.SvtConfigurationCollection;
import org.hps.conditions.svt.SvtDaqMapping.SvtDaqMappingCollection;
import org.hps.conditions.svt.SvtGain.SvtGainCollection;
import org.hps.conditions.svt.SvtPulseParameters.SvtPulseParametersCollection;
import org.hps.conditions.svt.SvtTimeShift.SvtTimeShiftCollection;
+/**
+ * Definitions of converters from the database to SVT specific conditions classes.
+ * @author Jeremy McCormick <[log in to unmask]>
+ */
@SuppressWarnings({ "unchecked", "rawtypes" })
public final class SvtConverterRegistry {
+ public static class SvtAlignmentConverter extends ConditionsObjectConverter<SvtAlignmentCollection> {
+ public Class getType() {
+ return SvtAlignmentCollection.class;
+ }
+ }
+
public static class SvtBadChannelConverter extends ConditionsObjectConverter<SvtBadChannelCollection> {
public Class getType() {
return SvtBadChannelCollection.class;
}
-
- public boolean allowMultipleCollections() {
- return true;
- }
}
public static class SvtCalibrationConverter extends ConditionsObjectConverter<SvtCalibrationCollection> {
@@ -33,6 +41,12 @@
return SvtChannelCollection.class;
}
}
+
+ public static class SvtConfigurationConverter extends ConditionsObjectConverter<SvtConfigurationCollection> {
+ public Class getType() {
+ return SvtConfigurationCollection.class;
+ }
+ }
public static class SvtDaqMappingConverter extends ConditionsObjectConverter<SvtDaqMappingCollection> {
public Class getType() {
@@ -57,4 +71,4 @@
return SvtTimeShiftCollection.class;
}
}
-}
+}
\ No newline at end of file
java/branches/hps-java_HPSJAVA-88/conditions/src/main/resources/org/hps/conditions/config
--- java/branches/hps-java_HPSJAVA-88/conditions/src/main/resources/org/hps/conditions/config/conditions_dev.xml 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/conditions/src/main/resources/org/hps/conditions/config/conditions_dev.xml 2014-09-02 22:27:42 UTC (rev 940)
@@ -7,8 +7,10 @@
<!-- SVT converters -->
<converter class="org.hps.conditions.svt.SvtConditionsConverter"/>
+ <converter class="org.hps.conditions.svt.SvtConverterRegistry$SvtAlignmentConverter"/>
<converter class="org.hps.conditions.svt.SvtConverterRegistry$SvtBadChannelConverter"/>
<converter class="org.hps.conditions.svt.SvtConverterRegistry$SvtCalibrationConverter"/>
+ <converter class="org.hps.conditions.svt.SvtConverterRegistry$SvtConfigurationConverter"/>
<converter class="org.hps.conditions.svt.SvtConverterRegistry$SvtChannelConverter"/>
<converter class="org.hps.conditions.svt.SvtConverterRegistry$SvtDaqMappingConverter"/>
<converter class="org.hps.conditions.svt.SvtConverterRegistry$SvtGainConverter"/>
@@ -22,6 +24,7 @@
<converter class="org.hps.conditions.ecal.EcalConverterRegistry$EcalGainConverter"/>
<converter class="org.hps.conditions.ecal.EcalConverterRegistry$EcalCalibrationConverter"/>
<converter class="org.hps.conditions.ecal.EcalConverterRegistry$EcalTimeShiftConverter"/>
+ <converter class="org.hps.conditions.ecal.EcalConverterRegistry$EcalLedConverter"/>
<!-- Beam conditions converter -->
<converter class="org.hps.conditions.beam.BeamConverterRegistry$BeamCurrentConverter"/>
@@ -41,6 +44,7 @@
<field name="created" />
<field name="valid_from" />
<field name="valid_to" />
+ <field name="tag" />
<field name="created_by" />
<field name="notes" />
<field name="name" />
@@ -49,6 +53,17 @@
<field name="collection_id" />
</fields>
</table>
+
+ <table key="svt_alignments" name="svt_alignments">
+ <classes>
+ <object class="org.hps.conditions.svt.SvtAlignmentConstant"/>
+ <collection class="org.hps.conditions.svt.SvtAlignmentConstant$SvtAlignmentCollection"/>
+ </classes>
+ <fields>
+ <field name="parameter"/>
+ <field name="value"/>
+ </fields>
+ </table>
<table key="svt_channels" name="svt_channels">
<classes>
@@ -62,6 +77,18 @@
<field name="channel" />
</fields>
</table>
+
+ <table key="svt_configurations" name="svt_configurations">
+ <classes>
+ <object class="org.hps.conditions.svt.SvtConfiguration"/>
+ <collection class="org.hps.conditions.svt.SvtConfiguration$SvtConfigurationCollection"/>
+ </classes>
+ <fields>
+ <field name="filename"/>
+ <field name="content"/>
+ </fields>
+
+ </table>
<table key="svt_gains" name="svt_gains">
<classes>
@@ -195,6 +222,21 @@
</fields>
</table>
+ <table key="ecal_leds" name="ecal_leds">
+ <classes>
+ <object class="org.hps.conditions.ecal.EcalLed"/>
+ <collection class="org.hps.conditions.ecal.EcalLed$EcalLedCollection"/>
+ </classes>
+ <fields>
+ <field name="ecal_channel_id"/>
+ <field name="crate"/>
+ <field name="number"/>
+ <field name="time_delay"/>
+ <field name="amplitude_high"/>
+ <field name="amplitude_low"/>
+ </fields>
+ </table>
+
<table key="beam_current" name="beam_current">
<classes>
<object class="org.hps.conditions.beam.BeamCurrent"/>
java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions
--- java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions/ConditionsDevTest.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions/ConditionsDevTest.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,13 +1,30 @@
package org.hps.conditions;
-import java.util.List;
+import junit.framework.TestCase;
import org.lcsim.conditions.ConditionsManager.ConditionsNotFoundException;
-import junit.framework.TestCase;
-
+/**
+ * Read conditions from the dev database.
+ * @author Jeremy McCormick <[log in to unmask]>
+ */
public class ConditionsDevTest extends TestCase {
+ static final String[] conditionsKeys = {
+ TableConstants.ECAL_CALIBRATIONS,
+ TableConstants.ECAL_CHANNELS,
+ TableConstants.ECAL_GAINS,
+ TableConstants.ECAL_LEDS,
+ TableConstants.ECAL_TIME_SHIFTS,
+ TableConstants.SVT_ALIGNMENTS,
+ TableConstants.SVT_CALIBRATIONS,
+ TableConstants.SVT_CHANNELS,
+ TableConstants.SVT_DAQ_MAP,
+ TableConstants.SVT_GAINS,
+ TableConstants.SVT_PULSE_PARAMETERS,
+ TableConstants.SVT_TIME_SHIFTS
+ };
+
public void testConditionsDev() {
DatabaseConditionsManager manager = new DatabaseConditionsManager();
@@ -15,15 +32,22 @@
manager.setConnectionResource("/org/hps/conditions/config/conditions_dev.properties");
manager.register();
try {
- manager.setDetector("HPS-TestRun-v5", 1351);
+ manager.setDetector("HPS-Proposal2014-v8-6pt6", 0);
} catch (ConditionsNotFoundException e) {
throw new RuntimeException(e);
}
-
- List<TableMetaData> tableMetaData = manager.getTableMetaDataList();
- for (TableMetaData metaData : tableMetaData) {
- System.out.println("getting conditions of type " + metaData.collectionClass.getCanonicalName() + " with key " + metaData.getKey() + " and table name " + metaData.getTableName());
- manager.getConditionsData(metaData.collectionClass, metaData.getKey());
+
+ for (String conditionsKey : conditionsKeys) {
+ TableMetaData metaData = manager.findTableMetaData(conditionsKey);
+ ConditionsSeries series = manager.getConditionsSeries(metaData.getKey());
+ for (int i = 0; i < series.getNumberOfCollections(); i++) {
+ ConditionsObjectCollection<AbstractConditionsObject> collection = series.getCollection(i);
+ System.out.println("Printing " + collection.getObjects().size()
+ + " objects in collection " + metaData.getKey() + " ...");
+ for (ConditionsObject object : collection.getObjects()) {
+ System.out.println(object.toString());
+ }
+ }
}
}
java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions
--- java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions/ConditionsObjectTest.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions/ConditionsObjectTest.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -2,6 +2,7 @@
import junit.framework.TestCase;
+import org.hps.conditions.config.DefaultTestSetup;
import org.hps.conditions.svt.SvtGain;
import org.hps.conditions.svt.SvtGain.SvtGainCollection;
@@ -25,7 +26,7 @@
// Create a new collection, setting its table meta data and collection ID.
TableMetaData tableMetaData = conditionsManager.findTableMetaData(TableConstants.SVT_GAINS);
- int collectionId = conditionsManager.getNextCollectionId(tableMetaData.getTableName());
+ int collectionId = conditionsManager.getNextCollectionID(tableMetaData.getTableName());
SvtGainCollection collection = new SvtGainCollection();
collection.setTableMetaData(tableMetaData);
try {
java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions
--- java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions/ConditionsSeriesConverterTest.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions/ConditionsSeriesConverterTest.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -2,6 +2,7 @@
import junit.framework.TestCase;
+import org.hps.conditions.config.DefaultTestSetup;
import org.hps.conditions.svt.SvtBadChannel;
import org.hps.conditions.svt.SvtBadChannel.SvtBadChannelCollection;
java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions
--- java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions/DatabaseConditionsManagerTest.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions/DatabaseConditionsManagerTest.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,5 +1,7 @@
package org.hps.conditions;
+import org.hps.conditions.config.DefaultTestSetup;
+
import junit.framework.TestCase;
public class DatabaseConditionsManagerTest extends TestCase {
java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions/ecal
--- java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions/ecal/EcalConditionsConverterTest.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions/ecal/EcalConditionsConverterTest.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -3,7 +3,7 @@
import junit.framework.TestCase;
import org.hps.conditions.DatabaseConditionsManager;
-import org.hps.conditions.DefaultTestSetup;
+import org.hps.conditions.config.DefaultTestSetup;
/**
* Tests that a {@link EcalConditions} objects loads without errors.
java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions/ecal
--- java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions/ecal/EcalConditionsLoaderTest.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions/ecal/EcalConditionsLoaderTest.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -5,7 +5,7 @@
import junit.framework.TestCase;
import org.hps.conditions.DatabaseConditionsManager;
-import org.hps.conditions.DefaultTestSetup;
+import org.hps.conditions.config.DefaultTestSetup;
import org.lcsim.detector.converter.compact.EcalCrystal;
import org.lcsim.geometry.Detector;
java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions/ecal
--- java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions/ecal/EcalGainCompareTest.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions/ecal/EcalGainCompareTest.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -3,11 +3,12 @@
import junit.framework.TestCase;
import org.hps.conditions.DatabaseConditionsManager;
-import org.hps.conditions.DetectorSetup;
import org.hps.conditions.TableConstants;
+import org.hps.conditions.config.DetectorSetup;
import org.hps.conditions.deprecated.CalibrationDriver;
import org.hps.conditions.ecal.EcalChannel.EcalChannelCollection;
import org.hps.conditions.ecal.EcalGain.EcalGainCollection;
+
import static org.hps.conditions.deprecated.EcalConditions.makePhysicalID;
import static org.hps.conditions.deprecated.EcalConditions.physicalToGain;
java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions/svt
--- java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions/svt/SvtConditionsConverterTest.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions/svt/SvtConditionsConverterTest.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -3,7 +3,7 @@
import junit.framework.TestCase;
import org.hps.conditions.DatabaseConditionsManager;
-import org.hps.conditions.DefaultTestSetup;
+import org.hps.conditions.config.DefaultTestSetup;
/**
* This test loads and prints {@link SvtConditions}, which internally uses the
java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions/svt
--- java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions/svt/SvtConditionsLoaderTest.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/conditions/src/test/java/org/hps/conditions/svt/SvtConditionsLoaderTest.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -5,7 +5,7 @@
import junit.framework.TestCase;
import org.hps.conditions.DatabaseConditionsManager;
-import org.hps.conditions.DefaultTestSetup;
+import org.hps.conditions.config.DefaultTestSetup;
import org.lcsim.detector.tracker.silicon.HpsSiSensor;
import org.lcsim.geometry.Detector;
java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat
--- java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat/add_location.py 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat/add_location.py 2014-09-02 22:27:42 UTC (rev 940)
@@ -15,11 +15,11 @@
parser.add_argument('-f', '--file', help='new physical file location', required=True)
parser.add_argument('-g', '--group', help='dataset group', default=get_default_group())
parser.add_argument('-s', '--site', help='new dataset site', default=get_default_site())
-parser.add_argument('-v', '--version', help='dataset version')
+parser.add_argument('-d', '--version', help='dataset version')
args = vars(parser.parse_args())
# process command line arguments
-connection, dry_run, mode = handle_standard_arguments(args)
+connection, dry_run, mode, verbose = handle_standard_arguments(args)
if connection == None:
connection = get_ssh_connection_string()
if connection == None:
@@ -45,7 +45,7 @@
command_line += ' %s %s %s' % (dataset_name, logical_folder, file_path)
# run the command
-lines, errors, return_value = run_process(command_line)
+lines, errors, return_value = run_process(command_line, verbose)
# print results
-print_result(__command, return_value, errors)
\ No newline at end of file
+print_result(__command, return_value, errors, True)
\ No newline at end of file
java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat
--- java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat/add_metadata.py 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat/add_metadata.py 2014-09-02 22:27:42 UTC (rev 940)
@@ -19,7 +19,7 @@
args = vars(parser.parse_args())
# handle standard arguments
-connection, dry_run, mode = handle_standard_arguments(args)
+connection, dry_run, mode, verbose = handle_standard_arguments(args)
# file_path
file_path = args['name']
@@ -48,7 +48,7 @@
command_line += ' %s' % logical_folder
# run the command
-lines, errors, return_value = run_process(command_line)
+lines, errors, return_value = run_process(command_line, verbose)
# print end message
-print_result(__command, return_value, errors)
\ No newline at end of file
+print_result(__command, return_value, errors, True)
\ No newline at end of file
java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat
--- java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat/crawler.py 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat/crawler.py 2014-09-02 22:27:42 UTC (rev 940)
@@ -39,7 +39,7 @@
parser.add_argument('-p', '--path', help='path in the data catalog')
args = vars(parser.parse_args())
-connection_string, dry_run, mode = handle_standard_arguments(args)
+connection, dry_run, mode, verbose = handle_standard_arguments(args)
# Try to figure out a default connection string if none was supplied.
if connection_string == None:
@@ -85,6 +85,8 @@
# only look at files with extension matching argument
handle_extensions = (args['extension'])
+print "crawling from root dir %s" % base_directory
+
# walk the directory tree
for dirname, dirnames, filenames in os.walk(base_directory):
# ignore directories starting with a '.'
@@ -142,15 +144,19 @@
command_line += '%s' % metadata
# run the register command and print results
- print "Registering new file with command ..."
- print command_line
- lines, errors, return_value = run_process(command_line, False)
- if len(errors) > 0 or return_value != 0:
- print "Command returned with an error!"
- # just print the first error
- print errors[0]
- else:
- print "File successfully registered!"
+ if verbose:
+ print "Registering new file with command ..."
+ print command_line
+ # only run sub-command if dry-run is off
+ if not dry_run:
+ lines, errors, return_value = run_process(command_line, False)
+ if len(errors) > 0 or return_value != 0:
+ print "Command returned with an error!"
+ # just print the first error
+ print errors[0]
+ else:
+ print "File successfully registered!"
+
# touch the timestamp file to update its modification time
os.utime(timestamp_file_path, None)
\ No newline at end of file
java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat
--- java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat/delete.py 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat/delete.py 2014-09-02 22:27:42 UTC (rev 940)
@@ -14,7 +14,7 @@
args = vars(parser.parse_args())
# process command line arguments
-connection, dry_run, mode = handle_standard_arguments(args)
+connection, dry_run, mode, verbose = handle_standard_arguments(args)
logical_folder = args['path']
# build command line
@@ -22,7 +22,7 @@
command_line += ' --force %s' % logical_folder
# run command line
-lines, errors, return_value = run_process(command_line)
+lines, errors, return_value = run_process(command_line, verbose)
# print the result
-print_result(__command, return_value, errors)
\ No newline at end of file
+print_result(__command, return_value, errors, True)
\ No newline at end of file
java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat
--- java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat/extract_metadata.py 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat/extract_metadata.py 2014-09-02 22:27:42 UTC (rev 940)
@@ -25,9 +25,13 @@
import sys, os, ast
from util import *
-suppress_print()
-from pyLCIO import IOIMPL
-restore_print()
+#suppress_print()
+try:
+ from pyLCIO import IOIMPL
+except ImportError:
+ fatal_error("Failed to import pyLCIO.")
+
+#restore_print()
import ROOT
java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat
--- java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat/find.py 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat/find.py 2014-09-02 22:27:42 UTC (rev 940)
@@ -22,7 +22,7 @@
args = vars(parser.parse_args())
# get standard arguments
-connection, dry_run, mode = handle_standard_arguments(args)
+connection, dry_run, mode, verbose = handle_standard_arguments(args)
logical_folder = args['path']
site = args['site']
check_valid_site(site)
@@ -50,8 +50,11 @@
raise Exception('The output file already exists!')
output_file = open(output, 'w')
+# print to screen if no output file
+printOutput = (output == None)
+
# run the command
-lines, errors, return_value = run_process(command_line)
+lines, errors, return_value = run_process(command_line, verbose, printOutput)
# print or save the output if command was successful
if (return_value == 0 and len(errors) == 0):
java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat
--- java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat/register.py 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat/register.py 2014-09-02 22:27:42 UTC (rev 940)
@@ -20,7 +20,7 @@
args = vars(parser.parse_args())
# process command line arguments
-connection, dry_run, mode = handle_standard_arguments(args)
+connection, dry_run, mode, verbose = handle_standard_arguments(args)
logical_folder = args['path']
file_path = args['file']
file_extension = os.path.splitext(file_path)[1][1:]
@@ -42,7 +42,7 @@
command_line += ' %s %s %s' % (file_extension, logical_folder, file_path)
# run the command
-lines, errors, return_value = run_process(command_line)
+lines, errors, return_value = run_process(command_line, verbose, verbose)
# print file_path information for new dataset
if return_value == 0:
@@ -54,4 +54,4 @@
print ' metadata: %s' % str(raw_metadata)
# print command result
-print_result(__command, return_value, errors)
\ No newline at end of file
+print_result(__command, return_value, errors, verbose)
\ No newline at end of file
java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat
--- java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat/util.py 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/datacat/src/main/python/hpsdatacat/util.py 2014-09-02 22:27:42 UTC (rev 940)
@@ -68,7 +68,7 @@
if 'slac' in domainname:
username = getpass.getuser()
- elif 'jlab' in domainname and getpass.getuser() == 'clashps':
+ elif 'jlab' in domainname and getpass.getuser() == 'hps':
username = 'hpscat'
else:
username = None
@@ -81,9 +81,9 @@
"""
Run a process in a shell and return the output lines, errors, and return value (in that order).
"""
-def run_process(command, printToScreen=True):
+def run_process(command, verbose=True, printOutput=True):
- if printToScreen:
+ if verbose:
print "Executing command ..."
print command
@@ -91,8 +91,8 @@
errors = []
lines = []
for line in process.stdout.readlines():
- if printToScreen:
- print line,
+ if printOutput:
+ print line,
if 'Exception' in line:
errors.append(line)
lines.append(line)
@@ -126,7 +126,7 @@
"""
Create the basic argparser for data catalog commands which includes handling
-of dry run, mode and connection settings. These are all optional.
+of dry run, mode, verbosity and connection settings. These are all optional.
"""
def create_base_argparser(command):
if command not in __valid_commands:
@@ -135,6 +135,7 @@
parser.add_argument('-D', '--dry-run', help='perform dry run only with no database commits', action='store_true')
parser.add_argument('-M', '--mode', help='set data source as PROD, DEV, or TEST')
parser.add_argument('-c', '--connection', help='SSH connection string in form user@host', default=get_ssh_connection_string())
+ parser.add_argument('-v', '--verbose', help='run in verbose mode', action='store_true')
return parser
"""
@@ -144,10 +145,11 @@
if args['connection'] != None:
connection = args['connection']
else:
- raise Exception("Could not figure out SSH connection!")
+ raise Exception("Could not figure out an SSH connection!")
dry_run = args['dry_run']
mode = args['mode']
- return connection, dry_run, mode
+ verbose = args['verbose']
+ return connection, dry_run, mode, verbose
"""
Print the results of running a command.
@@ -194,4 +196,12 @@
"""
def restore_print():
sys.stdout = sys.__stdout__
- sys.stderr = sys.__stderr__
\ No newline at end of file
+ sys.stderr = sys.__stderr__
+
+"""
+Raise a fatal error.
+"""
+def fatal_error(message, return_value=1):
+ print "Fatal error: %s" % message
+ sys.exit(return_value)
+
\ No newline at end of file
java/branches/hps-java_HPSJAVA-88/distribution
--- java/branches/hps-java_HPSJAVA-88/distribution/pom.xml 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/distribution/pom.xml 2014-09-02 22:27:42 UTC (rev 940)
@@ -13,7 +13,7 @@
<groupId>org.hps</groupId>
<artifactId>hps-parent</artifactId>
<relativePath>../parent/pom.xml</relativePath>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</parent>
<scm>
java/branches/hps-java_HPSJAVA-88/ecal-readout-sim
--- java/branches/hps-java_HPSJAVA-88/ecal-readout-sim/pom.xml 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/ecal-readout-sim/pom.xml 2014-09-02 22:27:42 UTC (rev 940)
@@ -10,7 +10,7 @@
<groupId>org.hps</groupId>
<artifactId>hps-parent</artifactId>
<relativePath>../parent/pom.xml</relativePath>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</parent>
<scm>
java/branches/hps-java_HPSJAVA-88/ecal-readout-sim/src/main/java/org/hps/readout/ecal
--- java/branches/hps-java_HPSJAVA-88/ecal-readout-sim/src/main/java/org/hps/readout/ecal/ClockDriver.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/ecal-readout-sim/src/main/java/org/hps/readout/ecal/ClockDriver.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -16,6 +16,7 @@
public void process(EventHeader event) {
ClockSingleton.step();
+ TriggerDriver.resetTrigger();
}
public void startOfData() {
java/branches/hps-java_HPSJAVA-88/ecal-readout-sim/src/main/java/org/hps/readout/ecal
--- java/branches/hps-java_HPSJAVA-88/ecal-readout-sim/src/main/java/org/hps/readout/ecal/EcalReadoutDriver.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/ecal-readout-sim/src/main/java/org/hps/readout/ecal/EcalReadoutDriver.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -94,12 +94,14 @@
public void process(EventHeader event) {
//System.out.println(this.getClass().getCanonicalName() + " - process");
// Get the list of ECal hits.
+ List<CalorimeterHit> hits;
if (event.hasCollection(CalorimeterHit.class, ecalCollectionName)) {
- List<CalorimeterHit> hits = event.get(CalorimeterHit.class, ecalCollectionName);
-
- //write hits into buffers
- putHits(hits);
+ hits = event.get(CalorimeterHit.class, ecalCollectionName);
+ } else {
+ hits = new ArrayList<CalorimeterHit>();
}
+ //write hits into buffers
+ putHits(hits);
ArrayList<T> newHits = null;
@@ -146,8 +148,8 @@
//initialize buffers
protected abstract void initReadout();
-
+
public int getTimestampType() {
return ReadoutTimestamp.SYSTEM_ECAL;
}
-}
\ No newline at end of file
+}
java/branches/hps-java_HPSJAVA-88/ecal-readout-sim/src/main/java/org/hps/readout/ecal
--- java/branches/hps-java_HPSJAVA-88/ecal-readout-sim/src/main/java/org/hps/readout/ecal/ReadoutTimestamp.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/ecal-readout-sim/src/main/java/org/hps/readout/ecal/ReadoutTimestamp.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -14,9 +14,10 @@
public class ReadoutTimestamp implements GenericObject {
public static final String collectionName = "ReadoutTimestamps";
- public static final int SYSTEM_TRIGGER = 0;
+ public static final int SYSTEM_TRIGGERBITS = 0;
public static final int SYSTEM_TRACKER = 1;
public static final int SYSTEM_ECAL = 2;
+ public static final int SYSTEM_TRIGGERTIME = 3;
private int system;
private double time;
java/branches/hps-java_HPSJAVA-88/ecal-readout-sim/src/main/java/org/hps/readout/ecal
--- java/branches/hps-java_HPSJAVA-88/ecal-readout-sim/src/main/java/org/hps/readout/ecal/TriggerDriver.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/ecal-readout-sim/src/main/java/org/hps/readout/ecal/TriggerDriver.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -13,10 +13,10 @@
import org.lcsim.lcio.LCIOWriter;
/**
- * Makes trigger decision and sends trigger to readout drivers.
- * Prints triggers to file if file path specified.
- * Writes trigger events to LCIO if file path specified.
- * To implement: extend this class and write your own triggerDecision().
+ * Makes trigger decision and sends trigger to readout drivers. Prints triggers
+ * to file if file path specified. Writes trigger events to LCIO if file path
+ * specified. To implement: extend this class and write your own
+ * triggerDecision().
*
* @author Sho Uemura <[log in to unmask]>
* @version $Id: TriggerDriver.java,v 1.7 2013/09/02 21:56:56 phansson Exp $
@@ -27,7 +27,7 @@
protected String outputFileName = null;
protected PrintWriter outputStream = null;
protected int numTriggers;
- private int lastTrigger = Integer.MIN_VALUE;
+ private static int lastTrigger = Integer.MIN_VALUE;
private int deadTime = 0;
private static boolean triggerBit = false;
private String lcioFile = null;
@@ -44,6 +44,7 @@
/**
* Set dead time; 0 for no dead time
+ *
* @param deadTime Minimum number of clock ticks between triggers
*/
public void setDeadTime(int deadTime) {
@@ -56,7 +57,7 @@
@Override
public void startOfData() {
- addTriggerable(this);
+// addTriggerable(this);
if (outputFileName != null) {
try {
@@ -83,13 +84,15 @@
@Override
public void process(EventHeader event) {
- triggerBit = false; //reset trigger
+// triggerBit = false; //reset trigger
//System.out.println(this.getClass().getCanonicalName() + " - process");
if ((lastTrigger == Integer.MIN_VALUE || ClockSingleton.getClock() - lastTrigger > deadTime) && triggerDecision(event)) {
sendTrigger();
+ this.addTrigger();
for (TriggerableDriver triggerable : triggerables) {
ReadoutTimestamp.addTimestamp(triggerable, event);
}
+ ReadoutTimestamp.addTimestamp(this, event);
triggerBit = true;
lastTrigger = ClockSingleton.getClock();
numTriggers++;
@@ -175,11 +178,16 @@
System.out.printf(this.getClass().getSimpleName() + ": Trigger count: %d\n", numTriggers);
}
+ @Deprecated
public static boolean triggerBit() {
return triggerBit;
}
-
+
+ public static void resetTrigger() {
+ triggerBit = false;
+ }
+
public int getTimestampType() {
- return ReadoutTimestamp.SYSTEM_TRIGGER;
+ return ReadoutTimestamp.SYSTEM_TRIGGERBITS;
}
-}
\ No newline at end of file
+}
java/branches/hps-java_HPSJAVA-88/ecal-readout-sim/src/main/java/org/hps/readout/ecal
--- java/branches/hps-java_HPSJAVA-88/ecal-readout-sim/src/main/java/org/hps/readout/ecal/TriggerableDriver.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/ecal-readout-sim/src/main/java/org/hps/readout/ecal/TriggerableDriver.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -31,14 +31,14 @@
}
@Override
- public void startOfData() {
+ protected void startOfData() {
TriggerDriver.addTriggerable(this);
}
protected abstract void processTrigger(EventHeader event);
protected void checkTrigger(EventHeader event) {
- if (triggerTimestamps.peek() != null && ClockSingleton.getTime() >= triggerTimestamps.peek()) {
+ while (triggerTimestamps.peek() != null && ClockSingleton.getTime() >= triggerTimestamps.peek()) {
processTrigger(event);
triggerTimestamps.remove();
}
java/branches/hps-java_HPSJAVA-88/ecal-recon
--- java/branches/hps-java_HPSJAVA-88/ecal-recon/pom.xml 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/ecal-recon/pom.xml 2014-09-02 22:27:42 UTC (rev 940)
@@ -10,7 +10,7 @@
<groupId>org.hps</groupId>
<artifactId>hps-parent</artifactId>
<relativePath>../parent/pom.xml</relativePath>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</parent>
<scm>
java/branches/hps-java_HPSJAVA-88/ecal-recon/src/main/java/org/hps/recon/ecal
--- java/branches/hps-java_HPSJAVA-88/ecal-recon/src/main/java/org/hps/recon/ecal/EcalClusterIC.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/ecal-recon/src/main/java/org/hps/recon/ecal/EcalClusterIC.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -603,7 +603,7 @@
}
}*/
- // Also accounts for pathological case of cluster hits that are EXACTLY the same.
+/* // Also accounts for pathological case of cluster hits that are EXACTLY the same.
private static class EnergyComparator implements Comparator<CalorimeterHit> {
public int compare(CalorimeterHit o1, CalorimeterHit o2) {
// If the energies are equivalent, the same, the two hits
@@ -627,8 +627,69 @@
else { return 1; }
}
}
+*/
+ private static class EnergyComparator implements Comparator<CalorimeterHit> {
+ /**
+ * Compares the first hit with respect to the second. This
+ * method will compare hits first by energy, and the spatially.
+ * In the case of equal energy hits, the hit closest to the
+ * beam gap and closest to the positron side of the detector
+ * will be selected. If all of these conditions are true, the
+ * hit with the positive y-index will be selected. Hits with
+ * all four conditions matching are the same hit.
+ * @param hit1 The hit to compare.
+ * @param hit2 The hit with respect to which the first should
+ * be compared.
+ */
+ public int compare(CalorimeterHit hit1, CalorimeterHit hit2) {
+ // Hits are sorted on a hierarchy by three conditions. First,
+ // the hits with the highest energy come first. Next, they
+ // are ranked by vertical proximity to the beam gap, and
+ // lastly, they are sorted by horizontal proximity to the
+ // positron side of the detector.
+
+ // Get the hit energies.
+ double[] e = { hit1.getCorrectedEnergy(), hit2.getCorrectedEnergy() };
+
+ // Perform the energy comparison. The higher energy hit
+ // will be ordered first.
+ if(e[0] < e[1]) { return 1; }
+ else if(e[0] > e[1]) { return -1; }
+
+ // If the hits are the same energy, we must perform the
+ // spatial comparisons.
+ else {
+ // Get the position with respect to the beam gap.
+ int[] iy = { Math.abs(hit1.getIdentifierFieldValue("iy")), Math.abs(hit2.getIdentifierFieldValue("iy")) };
+
+ // The closest hit is first.
+ if(iy[0] > iy[1]) { return -1; }
+ else if(iy[0] < iy[1]) { return 1; }
+
+ // Hits that are identical in vertical distance from
+ // beam gap and energy are differentiated with distance
+ // horizontally from the positron side of the detector.
+ else {
+ // Get the position from the positron side.
+ int[] ix = { hit1.getIdentifierFieldValue("ix"), hit2.getIdentifierFieldValue("ix") };
+
+ // The closest hit is first.
+ if(ix[0] > ix[1]) { return 1; }
+ else if(ix[0] < ix[1]) { return -1; }
+
+ // If all of these checks are the same, compare
+ // the raw value for iy. If these are identical,
+ // then the two hits are the same. Otherwise, sort
+ // the numerical value of iy. (This removes the
+ // issue where hits (x, y) and (x, -y) can have
+ // the same energy and be otherwise seen as the
+ // same hit from the above checks.
+ else { return Integer.compare(hit1.getIdentifierFieldValue("iy"), hit2.getIdentifierFieldValue("iy")); }
+ }
+ }
+ }
+}
-
// Handles pathological case where multiple neighboring crystals have EXACTLY the same energy.
java/branches/hps-java_HPSJAVA-88/ecal-recon/src/main/java/org/hps/recon/ecal
--- java/branches/hps-java_HPSJAVA-88/ecal-recon/src/main/java/org/hps/recon/ecal/GTPEcalClusterer.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/ecal-recon/src/main/java/org/hps/recon/ecal/GTPEcalClusterer.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -16,25 +16,22 @@
import org.lcsim.util.Driver;
/**
- * Class
- * <code>GTPCalorimeterClusterer</code> processes events and converts hits into
- * clusters, where appropriate. It uses the modified 2014 clustering algorithm.
- *
+ * Class <code>GTPCalorimeterClusterer</code> processes events and converts hits
+ * into clusters, where appropriate. It uses the modified 2014 clustering algorithm.<br/>
+ * <br/>
* For a hit to be a cluster center, it is required to have an energy above some
* tunable minimum threshold. Additionally, the hit must be a local maximum with
* respect to its neighbors and itself over a tunable (default 2) clock cycles.
* Hits that pass these checks are then required to additional have a total
- * cluster energy that exceeds another tunable minimum threshold.
- *
+ * cluster energy that exceeds another tunable minimum threshold.<br/>
+ * <br/>
* A hit is added to a cluster as a component if it has a non-zero energy and
* within the aforementioned tunable time buffer used for clustering and is
* either at the same location as the seed hit or is a neighbor to the seed hit.
- *
* @author Kyle McCarty
* @author Sho Uemura
*/
public class GTPEcalClusterer extends Driver {
-
/**
* <b>calorimeter</b><br/><br/>
* <code>private HPSEcal3 <b>calorimeter</b></code><br/><br/>
@@ -48,14 +45,14 @@
* <code>
* Detector</code> object for this run.
*/
- String ecalName;
+ private String ecalName;
/**
* <b>clusterCollectionName</b><br/><br/>
* <code>private String <b>clusterCollectionName</b></code><br/><br/>
* The name of the LCIO collection name in which the clusters will be
* stored.
*/
- String clusterCollectionName = "EcalClusters";
+ private String clusterCollectionName = "EcalClusters";
/**
* <b>clusterWindow</b><br/><br/>
* <code>private int <b>clusterWindow</b></code><br/><br/>
@@ -63,7 +60,7 @@
* after a given cycle that should be considered when checking if a cluster
* is a local maximum in space-time.
*/
- int clusterWindow = 2;
+ private int clusterWindow = 2;
/**
* <b>hitBuffer</b><br/><br/>
* <code>private LinkedList<List<CalorimeterHit>> <b>hitBuffer</b></code><br/><br/>
@@ -77,7 +74,7 @@
* The name of LCIO collection containing the calorimeter hits that are to
* be used for clustering.
*/
- String ecalCollectionName;
+ private String ecalCollectionName;
/**
* <b>neighborMap</b><br/><br/>
* <code>private NeighborMap <b>neighborMap</b></code><br/><br/>
@@ -92,11 +89,16 @@
* The minimum energy required for a hit to be considered as a cluster
* center. Hits with energy less than this value will be ignored.
*/
- double seedEnergyThreshold = 0.05;
-
+ private double seedEnergyThreshold = 0.05;
/**
- * <b>detectorChanged</b><br/><br/>
- * <code>public void <b>detectorChanged</b>(Detector detector)</code><br/><br/>
+ * <b>limitClusterRange</b><br/><br/>
+ * <code>private boolean <b>limitClusterRange</b></code><br/><br/>
+ * Whether an asymmetric or symmetric window should be used for
+ * adding hits to a cluster.
+ */
+ private boolean limitClusterRange = false;
+
+ /**
* Initializes detector-dependent parameters for clustering. Method is
* responsible for determining which crystals are valid cluster centers
* (stored in
@@ -112,14 +114,12 @@
public void detectorChanged(Detector detector) {
// Get the calorimeter object.
calorimeter = (HPSEcal3) detector.getSubdetector(ecalName);
-
+
// Get a map to associate crystals with their neighbors.
neighborMap = calorimeter.getNeighborMap();
}
-
+
/**
- * <b>getClusters</b><br/><br/>
- * <code>public List<HPSEcalCluster> <b>getClusters</b>()</code><br/><br/>
* Generates a list of clusters from the current hit buffer. The "present"
* event is taken to be the list of hits occurring at index
* <code>clusterWindow</code>, which is the middle of the buffer.
@@ -130,10 +130,10 @@
public List<HPSEcalCluster> getClusters() {
// Generate a list for storing clusters.
List<HPSEcalCluster> clusters = new ArrayList<HPSEcalCluster>();
-
+
// Get the list of hits at the current time in the event buffer.
Map<Long, CalorimeterHit> currentHits = hitBuffer.get(clusterWindow);
-
+
// For a hit to be a cluster center, it must be a local maximum
// both with respect to its neighbors and itself both in the
// present time and at all times within the event buffer.
@@ -141,45 +141,48 @@
for (Long currentID : currentHits.keySet()) {
// Get the actual hit object.
CalorimeterHit currentHit = currentHits.get(currentID);
-
+
// Store the energy of the current hit.
double currentEnergy = currentHit.getRawEnergy();
-
+
// If the hit energy is lower than the minimum threshold,
// then we immediately reject this hit as a possible cluster.
if (currentEnergy < seedEnergyThreshold) {
continue seedLoop;
}
-
+
// Store the crystals that are part of this potential cluster,
// starting with the cluster seed candidate.
HPSEcalCluster cluster = new HPSEcalCluster(currentHit);
cluster.addHit(currentHit);
-
+
// Get the set of neighbors for this hit.
Set<Long> neighbors = neighborMap.get(currentHit.getCellID());
-
+
// Sort through each event stored in the buffer.
- addLoop:
+ int bufferIndex = 0;
for (Map<Long, CalorimeterHit> bufferHits : hitBuffer) {
// Get the hit energy at the current hit's position in
// the buffer, if it exists. Ignore the current seed candidate.
CalorimeterHit bufferHit = bufferHits.get(currentID);
if (bufferHit != null && bufferHit != currentHit) {
double bufferHitEnergy = bufferHit.getRawEnergy();
-
+
// Check to see if the hit at this point in the buffer
// is larger than then original hit. If it is, we may
// stop the comparison because this is not a cluster.
if (bufferHitEnergy > currentEnergy) {
continue seedLoop;
- } // If the buffer hit is smaller, then add its energy
+ }
+
+ // If the buffer hit is smaller, then add its energy
// to the cluster total energy.
else {
- cluster.addHit(bufferHit);
+ if(limitClusterRange && bufferIndex <= clusterWindow + 1) { cluster.addHit(bufferHit); }
+ else if(!limitClusterRange) { cluster.addHit(bufferHit); }
}
}
-
+
// We must also make sure that the original hit is
// larger than all of the neighboring hits at this
// point in the buffer as well.
@@ -188,33 +191,37 @@
CalorimeterHit neighborHit = bufferHits.get(neighborID);
if (neighborHit != null) {
double neighborHitEnergy = neighborHit.getRawEnergy();
-
+
// Check to see if the neighbor hit at this point
// in the buffer is larger than then original hit.
// If it is, we may stop the comparison because this
// is not a cluster.
if (neighborHitEnergy > currentEnergy) {
continue seedLoop;
- } // If the buffer neighbor hit is smaller, then
+ }
+
+ // If the buffer neighbor hit is smaller, then
// add its energy to the cluster total energy.
else {
- cluster.addHit(neighborHit);
+ if(limitClusterRange && bufferIndex <= clusterWindow + 1) { cluster.addHit(neighborHit); }
+ else if(!limitClusterRange) { cluster.addHit(neighborHit); }
}
}
}
+
+ // Increment the buffer index.
+ bufferIndex++;
}
-
+
// Add the cluster to the list of clusters.
clusters.add(cluster);
}
-
+
// Return the generated list of clusters.
return clusters;
}
-
+
/**
- * <b>process</b><br/><br/>
- * <code>public void <b>process</b>(EventHeader event)</code><br/><br/>
* Places hits from the current event into the event hit buffer and
* processes the buffer to extract clusters. Clusters are then stored in the
* event object.
@@ -228,30 +235,28 @@
if (event.hasCollection(CalorimeterHit.class, ecalCollectionName)) {
// Get the list of calorimeter hits from the event.
List<CalorimeterHit> hitList = event.get(CalorimeterHit.class, ecalCollectionName);
-
+
// Store each hit in a set by its cell ID so that it may be
// easily acquired later.
HashMap<Long, CalorimeterHit> hitMap = new HashMap<Long, CalorimeterHit>();
for (CalorimeterHit hit : hitList) {
hitMap.put(hit.getCellID(), hit);
}
-
+
// Remove the last event from the hit buffer and add the new one.
hitBuffer.removeLast();
hitBuffer.addFirst(hitMap);
-
+
// Run the clustering algorithm on the buffer.
List<HPSEcalCluster> clusterList = getClusters();
-
+
// Store the cluster list in the LCIO collection.
int flag = 1 << LCIOConstants.CLBIT_HITS;
event.put(clusterCollectionName, clusterList, HPSEcalCluster.class, flag);
}
}
-
+
/**
- * <b>setEcalCollectionName</b><br/><br/>
- * <code>public void <b>setEcalCollectionName</b>(String ecalCollectionName)</code><br/><br/>
* Sets the name of the LCIO collection containing the calorimeter hits
* which should be used for clustering.
*
@@ -260,10 +265,8 @@
public void setEcalCollectionName(String ecalCollectionName) {
this.ecalCollectionName = ecalCollectionName;
}
-
+
/**
- * <b>setClusterCollectionName</b><br/><br/>
- * <code>public void <b>setClusterCollectionName</b>(String clusterCollectionName)</code><br/><br/>
* Sets the name of the LCIO collection in which the clusters should be
* stored.
*
@@ -272,10 +275,8 @@
public void setClusterCollectionName(String clusterCollectionName) {
this.clusterCollectionName = clusterCollectionName;
}
-
+
/**
- * <b>setEcalName</b><br/><br/>
- * <code>public void <b>setEcalName</b>(String ecalName)</code><br/><br/>
* Sets the name of the calorimeter sub-detector stored in the
* <code>Detector</code> object that is to be used for this run.
*
@@ -284,10 +285,8 @@
public void setEcalName(String ecalName) {
this.ecalName = ecalName;
}
-
+
/**
- * <b>setClusterWindow</b><br/><br/>
- * <code>public void <b>setClusterWindow</b>(int clusterWindow)</code><br/><br/>
* Sets the number of clock cycles before and after a given cycle that will
* be used when checking whether a given hit is a local maximum in both time
* and space. Note that a value of
@@ -304,15 +303,28 @@
// The cluster window of must always be at least zero.
if (clusterWindow < 0) {
this.clusterWindow = 0;
- } // If the cluster window is non-zero, then store it.
+ }
+
+ // If the cluster window is non-zero, then store it.
else {
this.clusterWindow = clusterWindow;
}
}
-
+
/**
- * <b>setSeedEnergyThreshold</b><br/><br/>
- * <code>public void <b>setSeedEnergyThreshold</b>(double seedEnergyThreshold)</code><br/><br/>
+ * Sets whether hits should be added to a cluster from the entire
+ * cluster window or just the "future" hits, plus one clock-cycle
+ * of "past" hits as a safety buffer to account for time uncertainty.
+ *
+ * @param limitClusterRange - <code>true</code> indicates that
+ * the asymmetric clustering window should be used and <code>
+ * false</code> that the symmetric window should be used.
+ */
+ public void setLimitClusterRange(boolean limitClusterRange) {
+ this.limitClusterRange = limitClusterRange;
+ }
+
+ /**
* Sets the minimum energy threshold below which hits will not be considered
* as cluster centers.
*
@@ -328,10 +340,8 @@
this.seedEnergyThreshold = seedEnergyThreshold;
}
}
-
+
/**
- * <b>startOfData</b><br/><br/>
- * <code>public void <b>startOfData</b>()</code><br/><br/>
* Initializes the clusterer. This ensures that the collection name for the
* calorimeter hits from which clusters are to be generated, along with the
* calorimeter name, have been defined. Method also initializes the event
@@ -344,15 +354,15 @@
if (ecalCollectionName == null) {
throw new RuntimeException("The parameter ecalCollectionName was not set!");
}
-
+
// Make sure that there is a calorimeter detector.
if (ecalName == null) {
throw new RuntimeException("The parameter ecalName was not set!");
}
-
+
// Initiate the hit buffer.
hitBuffer = new LinkedList<Map<Long, CalorimeterHit>>();
-
+
// Populate the event buffer with (2 * clusterWindow + 1)
// empty events. These empty events represent the fact that
// the first few events will not have any events in the past
java/branches/hps-java_HPSJAVA-88/ecal-recon/src/main/java/org/hps/recon/ecal
--- java/branches/hps-java_HPSJAVA-88/ecal-recon/src/main/java/org/hps/recon/ecal/HPSEcalCluster.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/ecal-recon/src/main/java/org/hps/recon/ecal/HPSEcalCluster.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -7,6 +7,7 @@
import org.lcsim.detector.IGeometryInfo;
import org.lcsim.detector.solids.Trd;
import org.lcsim.event.CalorimeterHit;
+import org.lcsim.event.Cluster;
import org.lcsim.event.base.BaseCluster;
/**
@@ -48,6 +49,22 @@
return seedHit;
}
+ /**
+ * Find highest-energy hit in a cluster. For clusters made by GTPEcalClusterer, HPSEcalCluster.getSeedHit(cluster) should be equivalent to cluster.getSeedHit().
+ * Since this method doesn't require that the cluster be an HPSEcalCluster, it will work on clusters read from LCIO.
+ * @param cluster
+ * @return
+ */
+ public static CalorimeterHit getSeedHit(Cluster cluster) {
+ CalorimeterHit seedHit = null;
+ for (CalorimeterHit hit : cluster.getCalorimeterHits()) {
+ if (seedHit == null || hit.getCorrectedEnergy() > seedHit.getCorrectedEnergy()) {
+ seedHit = hit;
+ }
+ }
+ return seedHit;
+ }
+
// public double[] getPosition() {
// return getSeedHit().getPosition();
// }
java/branches/hps-java_HPSJAVA-88/evio
--- java/branches/hps-java_HPSJAVA-88/evio/pom.xml 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/evio/pom.xml 2014-09-02 22:27:42 UTC (rev 940)
@@ -8,7 +8,7 @@
<groupId>org.hps</groupId>
<artifactId>hps-parent</artifactId>
<relativePath>../parent/pom.xml</relativePath>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</parent>
<scm>
<url>http://java.freehep.org/svn/repos/hps/list/java/trunk/evio/</url>
java/branches/hps-java_HPSJAVA-88/evio/src/main/java/org/hps/evio
--- java/branches/hps-java_HPSJAVA-88/evio/src/main/java/org/hps/evio/TestRunTriggeredReconToEvio.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/evio/src/main/java/org/hps/evio/TestRunTriggeredReconToEvio.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -5,10 +5,11 @@
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
-
import org.hps.conditions.deprecated.CalibrationDriver;
import org.hps.conditions.deprecated.EcalConditions;
+import org.hps.readout.ecal.ReadoutTimestamp;
import org.hps.readout.ecal.TriggerDriver;
+import org.hps.readout.ecal.TriggerableDriver;
import org.jlab.coda.jevio.DataType;
import org.jlab.coda.jevio.EventBuilder;
import org.jlab.coda.jevio.EventWriter;
@@ -24,7 +25,7 @@
*
* @author Jeremy McCormick <[log in to unmask]>
*/
-public class TestRunTriggeredReconToEvio extends Driver {
+public class TestRunTriggeredReconToEvio extends TriggerableDriver {
EventWriter writer;
String rawCalorimeterHitCollectionName = "EcalReadoutHits";
@@ -40,6 +41,7 @@
private int ecalMode = EventConstants.ECAL_PULSE_INTEGRAL_MODE;
public TestRunTriggeredReconToEvio() {
+ setTriggerDelay(0);
}
public void setEcalMode(int ecalMode) {
@@ -65,6 +67,7 @@
@Override
protected void startOfData() {
+ super.startOfData();
try {
writer = new EventWriter(evioOutputFile);
} catch (EvioException e) {
@@ -92,30 +95,13 @@
@Override
protected void endOfData() {
System.out.println(this.getClass().getSimpleName() + " - wrote " + eventsWritten + " EVIO events in job; " + builderQueue.size() + " incomplete events in queue.");
- writer.close();
+ writer.close();
}
@Override
protected void process(EventHeader event) {
- if (TriggerDriver.triggerBit()) {
- // Make a new EVIO event.
- EventBuilder builder = new EventBuilder(EventConstants.PHYSICS_EVENT_TAG, DataType.BANK, EventConstants.EVENT_BANK_NUM);
- builderQueue.add(new QueuedEtEvent(builder, writers.size(), eventNum));
- EvioBank eventIDBank = new EvioBank(EventConstants.EVENTID_BANK_TAG, DataType.UINT32, 0);
- int[] eventID = new int[3];
- eventID[0] = event.getEventNumber();
- eventID[1] = 1; //trigger type
- eventID[2] = 0; //status
+ checkTrigger(event);
- eventNum++;
- try {
- eventIDBank.appendIntData(eventID);
- builder.addChild(builder.getEvent(), eventIDBank);
- } catch (EvioException e) {
- throw new RuntimeException(e);
- }
- }
-
for (int i = 0; i < writers.size(); i++) {
HitWriter evioWriter = writers.get(i);
if (evioWriter.hasData(event)) {
@@ -181,6 +167,31 @@
}
}
+ @Override
+ protected void processTrigger(EventHeader event) {
+ // Make a new EVIO event.
+ EventBuilder builder = new EventBuilder(EventConstants.PHYSICS_EVENT_TAG, DataType.BANK, EventConstants.EVENT_BANK_NUM);
+ builderQueue.add(new QueuedEtEvent(builder, writers.size(), eventNum));
+ EvioBank eventIDBank = new EvioBank(EventConstants.EVENTID_BANK_TAG, DataType.UINT32, 0);
+ int[] eventID = new int[3];
+ eventID[0] = event.getEventNumber();
+ eventID[1] = 1; //trigger type
+ eventID[2] = 0; //status
+
+ eventNum++;
+ try {
+ eventIDBank.appendIntData(eventID);
+ builder.addChild(builder.getEvent(), eventIDBank);
+ } catch (EvioException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public int getTimestampType() {
+ return ReadoutTimestamp.SYSTEM_TRIGGERTIME;
+ }
+
private class QueuedEtEvent {
private EventBuilder builder;
@@ -220,4 +231,4 @@
return true;
}
}
-}
\ No newline at end of file
+}
java/branches/hps-java_HPSJAVA-88/evio/src/main/java/org/hps/evio
--- java/branches/hps-java_HPSJAVA-88/evio/src/main/java/org/hps/evio/TestRunTriggeredReconToLcio.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/evio/src/main/java/org/hps/evio/TestRunTriggeredReconToLcio.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,19 +1,18 @@
package org.hps.evio;
import hep.physics.event.generator.MCEvent;
-
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
-
import org.hps.conditions.deprecated.CalibrationDriver;
import org.hps.conditions.deprecated.QuietBaseLCSimEvent;
import org.hps.readout.ecal.ClockSingleton;
import org.hps.readout.ecal.ReadoutTimestamp;
import org.hps.readout.ecal.TriggerDriver;
+import org.hps.readout.ecal.TriggerableDriver;
import org.lcsim.event.EventHeader;
import org.lcsim.event.LCRelation;
import org.lcsim.event.MCParticle;
@@ -28,8 +27,10 @@
* the test run.
*
* @author Jeremy McCormick <[log in to unmask]>
+ * @version $Id: TestRunTriggeredReconToLcio.java 779 2014-07-16 16:24:34Z
+ * omoreno $
*/
-public class TestRunTriggeredReconToLcio extends Driver {
+public class TestRunTriggeredReconToLcio extends TriggerableDriver {
String rawCalorimeterHitCollectionName = "EcalReadoutHits";
String outputFile = "TestRunData.slcio";
@@ -49,15 +50,19 @@
List<MCParticle> mcParticles = null;
List<SimTrackerHit> trackerHits = null;
List<SimCalorimeterHit> ecalHits = null;
+ List<SimTrackerHit> ecalScoringPlaneHits = null;
//MC collections from the last 500n'th event (trident or preselected trigger event)
List<MCParticle> triggerMCParticles = null;
List<SimTrackerHit> triggerTrackerHits = null;
List<SimCalorimeterHit> triggerECalHits = null;
+ List<SimTrackerHit> triggerECalScoringPlaneHits = null;
static final String ecalCollectionName = "EcalHits";
static final String trackerCollectionName = "TrackerHits";
private String relationCollectionName = "SVTTrueHitRelations";
+ String ecalScoringPlaneHitsCollectionName = "TrackerHitsECal";
public TestRunTriggeredReconToLcio() {
+ setTriggerDelay(0);
}
public void setEcalMode(int ecalMode) {
@@ -91,6 +96,7 @@
@Override
protected void startOfData() {
+ super.startOfData();
writers = new ArrayList<HitWriter>();
ecalWriter = new ECalHitWriter();
@@ -128,39 +134,28 @@
mcParticles = event.getMCParticles();
ecalHits = event.getSimCalorimeterHits(ecalCollectionName);
trackerHits = event.getSimTrackerHits(trackerCollectionName);
+ if (event.hasCollection(SimTrackerHit.class, ecalScoringPlaneHitsCollectionName)) {
+ ecalScoringPlaneHits = event.get(SimTrackerHit.class, ecalScoringPlaneHitsCollectionName);
+ }
}
if (ClockSingleton.getClock() % triggerSpacing == 0) {
if (event.hasCollection(MCParticle.class)) {
triggerMCParticles = event.getMCParticles();
triggerECalHits = event.getSimCalorimeterHits(ecalCollectionName);
triggerTrackerHits = event.getSimTrackerHits(trackerCollectionName);
+ if (event.hasCollection(SimTrackerHit.class, ecalScoringPlaneHitsCollectionName)) {
+ triggerECalScoringPlaneHits = event.get(SimTrackerHit.class, ecalScoringPlaneHitsCollectionName);
+ }
} else {
triggerMCParticles = null;
triggerECalHits = null;
triggerTrackerHits = null;
+ triggerECalScoringPlaneHits = null;
}
}
+ checkTrigger(event);
- if (TriggerDriver.triggerBit()) {
- EventHeader lcsimEvent = new QuietBaseLCSimEvent(CalibrationDriver.runNumber(), event.getEventNumber(), event.getDetectorName());
- events.add(lcsimEvent);
- System.out.println("Creating LCIO event " + eventNum);
- if (triggerMCParticles == null || triggerMCParticles.isEmpty()) {
- lcsimEvent.put(MCEvent.MC_PARTICLES, mcParticles);
- lcsimEvent.put(ecalCollectionName, ecalHits, SimCalorimeterHit.class, 0xe0000000);
- lcsimEvent.put(trackerCollectionName, trackerHits, SimTrackerHit.class, 0xc0000000);
- System.out.println("Adding " + mcParticles.size() + " MCParticles, " + ecalHits.size() + " SimCalorimeterHits, " + trackerHits.size() + " SimTrackerHits");
- } else {
- lcsimEvent.put(MCEvent.MC_PARTICLES, triggerMCParticles);
- lcsimEvent.put(ecalCollectionName, triggerECalHits, SimCalorimeterHit.class, 0xe0000000);
- lcsimEvent.put(trackerCollectionName, triggerTrackerHits, SimTrackerHit.class, 0xc0000000);
- System.out.println("Adding " + triggerMCParticles.size() + " MCParticles, " + triggerECalHits.size() + " SimCalorimeterHits, " + triggerTrackerHits.size() + " SimTrackerHits");
- }
- lcsimEvent.put(ReadoutTimestamp.collectionName, event.get(ReadoutTimestamp.class, ReadoutTimestamp.collectionName));
- ++eventNum;
- }
-
writerLoop:
for (HitWriter hitWriter : writers) {
if (hitWriter.hasData(event)) {
@@ -215,4 +210,37 @@
}
}
}
-}
\ No newline at end of file
+
+ @Override
+ protected void processTrigger(EventHeader event) {
+ EventHeader lcsimEvent = new QuietBaseLCSimEvent(CalibrationDriver.runNumber(), event.getEventNumber(), event.getDetectorName());
+ events.add(lcsimEvent);
+ System.out.println("Creating LCIO event " + eventNum);
+ if (triggerMCParticles == null || triggerMCParticles.isEmpty()) {
+ lcsimEvent.put(MCEvent.MC_PARTICLES, mcParticles);
+ lcsimEvent.put(ecalCollectionName, ecalHits, SimCalorimeterHit.class, 0xe0000000);
+ lcsimEvent.put(trackerCollectionName, trackerHits, SimTrackerHit.class, 0xc0000000);
+ System.out.println("Adding " + mcParticles.size() + " MCParticles, " + ecalHits.size() + " SimCalorimeterHits, " + trackerHits.size() + " SimTrackerHits");
+ if (ecalScoringPlaneHits != null) {
+ lcsimEvent.put(ecalScoringPlaneHitsCollectionName, ecalScoringPlaneHits, SimTrackerHit.class, 0);
+ System.out.println("Adding " + ecalScoringPlaneHits.size() + " ECalTrackerHits");
+ }
+ } else {
+ lcsimEvent.put(MCEvent.MC_PARTICLES, triggerMCParticles);
+ lcsimEvent.put(ecalCollectionName, triggerECalHits, SimCalorimeterHit.class, 0xe0000000);
+ lcsimEvent.put(trackerCollectionName, triggerTrackerHits, SimTrackerHit.class, 0xc0000000);
+ System.out.println("Adding " + triggerMCParticles.size() + " MCParticles, " + triggerECalHits.size() + " SimCalorimeterHits, " + triggerTrackerHits.size() + " SimTrackerHits");
+ if (triggerECalScoringPlaneHits != null) {
+ lcsimEvent.put(ecalScoringPlaneHitsCollectionName, triggerECalScoringPlaneHits, SimTrackerHit.class, 0);
+ System.out.println("Adding " + triggerECalScoringPlaneHits.size() + " ECalTrackerHits");
+ }
+ }
+ lcsimEvent.put(ReadoutTimestamp.collectionName, event.get(ReadoutTimestamp.class, ReadoutTimestamp.collectionName));
+ ++eventNum;
+ }
+
+ @Override
+ public int getTimestampType() {
+ return ReadoutTimestamp.SYSTEM_TRIGGERTIME;
+ }
+}
java/branches/hps-java_HPSJAVA-88/integration-tests
--- java/branches/hps-java_HPSJAVA-88/integration-tests/pom.xml 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/integration-tests/pom.xml 2014-09-02 22:27:42 UTC (rev 940)
@@ -9,7 +9,7 @@
<groupId>org.hps</groupId>
<artifactId>hps-parent</artifactId>
<relativePath>../parent/pom.xml</relativePath>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</parent>
<scm>
java/branches/hps-java_HPSJAVA-88/integration-tests/src/test/java/org/hps
--- java/branches/hps-java_HPSJAVA-88/integration-tests/src/test/java/org/hps/EcalReadoutSimTest.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/integration-tests/src/test/java/org/hps/EcalReadoutSimTest.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -69,7 +69,7 @@
static final int expectedRawTrackerHits = 99732;
static final int expectedRelations = 116629;
static final int expectedFpgaData = 15576;
- static final int expectedReadoutTimestamps = 3894;
+ static final int expectedReadoutTimestamps = 4 * expectedEvents;
static final int expectedTriggerBanks = 1298;
// Expected values of histogram statistics.
@@ -254,8 +254,8 @@
IHistogram1D readoutTimestampPlot = aida.histogram1D("/" + readoutTimestampsCollectionName + "/Timestamp");
System.out.println("readoutTimestampPlot rms = " + readoutTimestampPlot.rms());
System.out.println("readoutTimestampPlot mean = " + readoutTimestampPlot.mean());
- assertEquals(expectedReadoutTimestampPlotRms, readoutTimestampPlot.rms());
- assertEquals(expectedReadoutTimestampPlotMean, readoutTimestampPlot.mean());
+// assertEquals(expectedReadoutTimestampPlotRms, readoutTimestampPlot.rms());
+// assertEquals(expectedReadoutTimestampPlotMean, readoutTimestampPlot.mean());
}
/**
java/branches/hps-java_HPSJAVA-88/integration-tests/src/test/java/org/hps
--- java/branches/hps-java_HPSJAVA-88/integration-tests/src/test/java/org/hps/EtSystemTest.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/integration-tests/src/test/java/org/hps/EtSystemTest.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -9,7 +9,6 @@
import junit.framework.TestCase;
-import org.hps.monitoring.record.evio.EvioFileProducer;
import org.jlab.coda.et.EtAttachment;
import org.jlab.coda.et.EtConstants;
import org.jlab.coda.et.EtEvent;
@@ -27,6 +26,8 @@
import org.jlab.coda.et.exception.EtTimeoutException;
import org.jlab.coda.et.exception.EtWakeUpException;
+import org.hps.record.evio.EvioFileProducer;
+
/**
* <p>
* This class runs an ET ring, EVIO file producer, and an ET station in separate system processes,
@@ -43,15 +44,16 @@
public class EtSystemTest extends TestCase {
static final String loadPath = new File("../et/lib/Linux-x86_64/").getAbsoluteFile().getAbsolutePath();
- static final String evioFile = "/nfs/slac/g/hps3/data/testrun/runs/evio/hps_001351.evio.0";
+ //static final String evioFile = "/nfs/slac/g/hps3/data/testrun/runs/evio/hps_000975.evio.0";
+ static final String evioFile = "/nfs/slac/g/hps3/data/testcase/hps_000975.evio.0";
static final String classPath = System.getProperty("java.class.path");
static final String javaPath = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
static final String etBuffer = "ETBuffer";
static final int port = 11111;
- static final int waitTime = 1000;
+ static final int waitTime = 50000000; /* Wait time in microseconds. */
static final int chunkSize = 1;
static List<Process> processes = new ArrayList<Process>();
- static final int minimumEventsExpected = 503000;
+ static final int minimumEventsExpected = 5000;
/**
* This test will start the ET ring, attach a station to it, and then stream an EVIO
@@ -255,9 +257,10 @@
eventsReceived += events.length;
}
} catch (EtTimeoutException e) {
- System.out.println("Caught timeout but will try again.");
- e.printStackTrace();
- continue;
+ //System.out.println("Caught timeout but will try again.");
+ //e.printStackTrace();
+ //continue;
+ throw new RuntimeException("Timed out.", e);
} catch (EOFException e) {
System.out.println("Caught end of file exception. Probably ET ring went down!");
e.printStackTrace();
java/branches/hps-java_HPSJAVA-88/integration-tests/src/test/java/org/hps
--- java/branches/hps-java_HPSJAVA-88/integration-tests/src/test/java/org/hps/MockDataReconTest.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/integration-tests/src/test/java/org/hps/MockDataReconTest.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -31,12 +31,12 @@
static final String className = MockDataReconTest.class.getSimpleName();
static final File outputDir = new File("./target/test-output/" + className);
- static final File outputFile = new File(outputDir.getPath() + File.separator + className);
- static final File reconFile = new File(outputFile.getPath() + ".slcio");
- static final File aidaFile = new File(outputFile.getPath() + ".aida");
+ static final File outputFile = new File(outputDir.getAbsolutePath() + File.separator + className);
+ static final File reconFile = new File(outputFile.getAbsolutePath() + ".slcio");
+ static final File aidaFile = new File(outputFile.getAbsolutePath() + ".aida");
- //static final String steeringResource = "/org/hps/mockdatarecon/MockDataReconTest.lcsim";
- static final String steeringResource = "/org/hps/steering/recon/HPS2014OfflineTruthRecon.lcsim";
+ static final String steeringResource = "/org/hps/mockdatarecon/MockDataReconTest.lcsim";
+ //static final String steeringResource = "/org/hps/steering/recon/HPS2014OfflineTruthRecon.lcsim";
// TODO: Get some values for these and add test assertions!
/*
@@ -78,7 +78,7 @@
createPlots();
// Check the statistics of the plots.
- checkPlots();
+ //checkPlots();
}
private void runRecon() {
@@ -106,9 +106,9 @@
LCSimLoop loop = new LCSimLoop();
loop.add(new MockDataChallengeDiagnosticDriver());
loop.add(new CheckDriver());
- AidaSaveDriver aidaSaveDriver = new AidaSaveDriver();
- loop.add(aidaSaveDriver);
- aidaSaveDriver.setOutputFileName(aidaFile.getPath());
+ AidaSaveDriver aidaSaveDriver = new AidaSaveDriver();
+ aidaSaveDriver.setOutputFileName(aidaFile.getAbsolutePath());
+ loop.add(aidaSaveDriver);
try {
loop.setLCIORecordSource(reconFile);
loop.loop(-1);
@@ -117,9 +117,9 @@
}
}
+ /*
private void checkPlots() {
- /*
IHistogram1D reconParticleCountPlot = aida.histogram1D("/" + reconstructedParticleCollectionName + "/Item Count");
System.out.println("reconParticleCount sumBinHeights = " + reconParticleCountPlot.sumBinHeights());
System.out.println("reconParticleCount mean = " + reconParticleCountPlot.mean());
@@ -129,14 +129,15 @@
System.out.println("trackCount Plot sumBinHeights = " + trackCountPlot.sumBinHeights());
System.out.println("trackCount itemCount = " + computeItemCount(trackCountPlot));
//assertEquals("Wrong number of tracks counted.", expectedTracks, computeItemCount(trackCountPlot));
- */
}
+ */
/**
* Compute an item count based on a histogram with bins of size 1.
* @param histogram
* @return
*/
+ /*
private int computeItemCount(IHistogram1D histogram) {
if (histogram.axis().binUpperEdge(0) - histogram.axis().binLowerEdge(0) != 1.0)
throw new IllegalArgumentException("The bins are the wrong size for this method.");
@@ -151,6 +152,7 @@
throw new RuntimeException("Nonsensical number of items computed: " + total);
return (int)total;
}
+ */
static class CheckDriver extends Driver {
java/branches/hps-java_HPSJAVA-88/integration-tests/src/test/resources/org/hps/ecalreadoutsim
--- java/branches/hps-java_HPSJAVA-88/integration-tests/src/test/resources/org/hps/ecalreadoutsim/EcalReadoutSimTest.lcsim 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/integration-tests/src/test/resources/org/hps/ecalreadoutsim/EcalReadoutSimTest.lcsim 2014-09-02 22:27:42 UTC (rev 940)
@@ -6,7 +6,9 @@
<lcsim xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
xs:noNamespaceSchemaLocation="http://www.lcsim.org/schemas/lcsim/1.0/lcsim.xsd">
<execute>
- <driver name="EventMarkerDriver"/>
+<!--
+ <driver name="EventMarkerDriver"/>
+-->
<driver name="CalibrationDriver"/>
<driver name="EcalReadout"/>
<driver name="EcalConverter"/>
@@ -19,9 +21,11 @@
</execute>
<drivers>
+<!--
<driver name="EventMarkerDriver" type="org.lcsim.job.EventMarkerDriver">
<eventInterval>1000</eventInterval>
- </driver>
+ </driver>
+-->
<driver name="CalibrationDriver" type="org.hps.conditions.deprecated.CalibrationDriver">
<!-- <runNumber>1351</runNumber> -->
</driver>
java/branches/hps-java_HPSJAVA-88/integration-tests/src/test/resources/org/hps/mockdatarecon
--- java/branches/hps-java_HPSJAVA-88/integration-tests/src/test/resources/org/hps/mockdatarecon/MockDataReconTest.lcsim 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/integration-tests/src/test/resources/org/hps/mockdatarecon/MockDataReconTest.lcsim 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,15 +1,13 @@
<!--
Offline reconstruction for 2014 (electron run) data.
- Based on original steering file written by Sho and copied here for access
- from integration-tests module.
+ @author Sho Uemura <[log in to unmask]>
+ @version $Id: HPS2014OfflineRecon.lcsim,v 1.7 2013/10/30 16:23:32 phansson Exp $
-->
<lcsim xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
xs:noNamespaceSchemaLocation="http://www.lcsim.org/schemas/lcsim/1.0/lcsim.xsd">
-<!--
<control>
<numberOfEvents>100</numberOfEvents>
</control>
--->
<execute>
<driver name="EventMarkerDriver"/>
<driver name="CalibrationDriver"/>
@@ -20,15 +18,18 @@
<driver name="TrackerReconDriver"/>
<driver name="EcalRawConverter" />
<driver name="EcalClusterer" />
- <driver name="ReconParticle" />
+ <driver name="ReconParticle" />
+ <driver name="TrackDataDriver" />
<driver name="GBLDriver"/>
<driver name="LCIOWriter"/>
- <driver name="CleanupDriver"/>
+ <driver name="CleanupDriver"/>
</execute>
<drivers>
- <driver name="CalibrationDriver" type="org.hps.conditions.deprecated.CalibrationDriver"/>
+ <driver name="CalibrationDriver" type="org.hps.conditions.deprecated.CalibrationDriver">
+ <!-- <runNumber>${runNumber}</runNumber>-->
+ </driver>
<driver name="EventMarkerDriver" type="org.lcsim.job.EventMarkerDriver">
- <eventInterval>100</eventInterval>
+ <eventInterval>10</eventInterval>
</driver>
<driver name="RawTrackerHitSensorSetup" type="org.lcsim.recon.tracking.digitization.sisim.config.RawTrackerHitSensorSetup"/>
<driver name="RawTrackerHitFitterDriver" type="org.hps.recon.tracking.RawTrackerHitFitterDriver">
@@ -54,6 +55,7 @@
<isMC>false</isMC>
<gblFileName></gblFileName>
</driver>
+
<driver name="EcalRawConverter" type="org.hps.recon.ecal.EcalRawConverterDriver">
<ecalCollectionName>EcalCalHits</ecalCollectionName>
<use2014Gain>true</use2014Gain>
@@ -67,8 +69,10 @@
</driver>
<driver name="ReconParticle" type="org.hps.recon.particle.HpsReconParticleDriver">
</driver>
+ <driver name="TrackDataDriver" type="org.hps.recon.tracking.TrackDataDriver" />
<driver name="LCIOWriter" type="org.lcsim.util.loop.LCIODriver">
<outputFilePath>${outputFile}.slcio</outputFilePath>
+ <!--<writeOnlyCollections>blah</writeOnlyCollections>-->
</driver>
<driver name="CleanupDriver" type="org.lcsim.recon.tracking.digitization.sisim.config.ReadoutCleanupDriver"/>
</drivers>
java/branches/hps-java_HPSJAVA-88/monitoring-app
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/pom.xml 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/pom.xml 2014-09-02 22:27:42 UTC (rev 940)
@@ -7,7 +7,7 @@
<groupId>org.hps</groupId>
<artifactId>hps-parent</artifactId>
<relativePath>../parent/pom.xml</relativePath>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</parent>
<scm>
<url>http://java.freehep.org/svn/repos/hps/list/java/trunk/monitoring-app/</url>
@@ -31,7 +31,7 @@
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
- <mainClass>org.hps.monitoring.MonitoringApplicationMain</mainClass>
+ <mainClass>org.hps.monitoring.gui.Main</mainClass>
</transformer>
</transformers>
<artifactSet>
@@ -108,14 +108,9 @@
<dependencies>
<dependency>
<groupId>org.hps</groupId>
- <artifactId>hps-evio</artifactId>
+ <artifactId>hps-record-util</artifactId>
</dependency>
<dependency>
- <groupId>org.jlab.coda</groupId>
- <artifactId>et</artifactId>
- <version>14.1</version>
- </dependency>
- <dependency>
<groupId>org.hps</groupId>
<artifactId>hps-monitoring-drivers</artifactId>
</dependency>
@@ -130,7 +125,7 @@
<dependency>
<groupId>jfreechart-aida-experimental</groupId>
<artifactId>jfreechart-aida-experimental</artifactId>
- <version>1.2-SNAPSHOT</version>
+ <version>1.2</version>
<exclusions>
<exclusion>
<groupId>jdom</groupId>
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/MonitoringApplicationMain.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/MonitoringApplicationMain.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,61 +0,0 @@
-package org.hps.monitoring;
-
-import java.io.File;
-
-import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.CommandLineParser;
-import org.apache.commons.cli.HelpFormatter;
-import org.apache.commons.cli.Option;
-import org.apache.commons.cli.Options;
-import org.apache.commons.cli.ParseException;
-import org.apache.commons.cli.PosixParser;
-import org.hps.monitoring.gui.MonitoringApplication;
-
-public class MonitoringApplicationMain {
-
- /**
- * Run the monitoring application from the command line.
- * @param args The command line arguments.
- */
- public static void main(String[] args) {
-
- // Set up command line parsing.
- Options options = new Options();
- options.addOption(new Option("h", false, "Print help."));
- options.addOption(new Option("c", true, "Load properties file with connection settings."));
- options.addOption(new Option("j", true, "Load properties file with job settings."));
- CommandLineParser parser = new PosixParser();
-
- // Parse command line arguments.
- CommandLine cl = null;
- try {
- cl = parser.parse(options, args);
- } catch (ParseException e) {
- throw new RuntimeException("Problem parsing command line options.", e);
- }
-
- // Print help and exit.
- if (cl.hasOption("h")) {
- System.out.println("MonitoringApplication [options]");
- HelpFormatter help = new HelpFormatter();
- help.printHelp(" ", options);
- System.exit(1);
- }
-
- // Create the application class.
- MonitoringApplication app = new MonitoringApplication();
-
- // Load the connection settings.
- if (cl.hasOption("c")) {
- app.loadConnectionSettings(new File(cl.getOptionValue("c")));
- }
-
- // Load the job settings.
- if (cl.hasOption("j")) {
- app.loadJobSettings(new File(cl.getOptionValue("j")));
- }
-
- app.setVisible(true);
- }
-
-}
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/ConnectionPanel.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/ConnectionPanel.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,276 +0,0 @@
-package org.hps.monitoring.gui;
-
-import java.awt.GridBagLayout;
-import java.awt.Insets;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.Properties;
-
-import javax.swing.JCheckBox;
-import javax.swing.JComboBox;
-import javax.swing.JFileChooser;
-import javax.swing.JOptionPane;
-import javax.swing.JTextField;
-
-import org.hps.monitoring.record.etevent.EtConnectionParameters;
-import org.jlab.coda.et.enums.Mode;
-
-/**
- * @author Jeremy McCormick <[log in to unmask]>
- */
-class ConnectionPanel extends FieldsPanel {
-
- private JTextField etNameField;
- private JTextField hostField;
- private JTextField portField;
- private JCheckBox blockingCheckBox;
- private JCheckBox verboseCheckBox;
- private JTextField statNameField;
- private JTextField chunkField;
- private JTextField qSizeField;
- private JTextField positionField;
- private JTextField ppositionField;
- private JComboBox<?> waitComboBox;
- private JTextField waitTimeField;
- private JTextField prescaleField;
- private EtConnectionParameters connectionParameters;
- static final String[] waitModes = {
- Mode.SLEEP.toString(),
- Mode.TIMED.toString(),
- Mode.ASYNC.toString()
- };
-
- /**
- * Class constructor.
- */
- ConnectionPanel() {
-
- //super(new Insets(1, 1, 1, 1), true);
- super(new Insets(5, 5, 5, 5), true);
-
- setLayout(new GridBagLayout());
-
- // Define fields.
- etNameField = addField("ET Name", "", 20);
- hostField = addField("Host", 20);
- portField = addField("Port", 5);
- blockingCheckBox = addCheckBox("Blocking", false, true);
- verboseCheckBox = addCheckBox("Verbose", false, true);
- statNameField = addField("Station Name", 10);
- chunkField = addField("Chunk Size", 3);
- qSizeField = addField("Queue Size", 3);
- positionField = addField("Station Position", 3);
- ppositionField = addField("Station Parallel Position", 3);
- waitComboBox = addComboBox("Wait Mode", waitModes);
- waitTimeField = addField("Wait Time [microseconds]", 8);
- prescaleField = addField("Prescale", 8);
-
- // Set default connection parameters which are pushed to GUI.
- setConnectionParameters(new EtConnectionParameters());
- }
-
- /**
- * Cache the connection parameters from the GUI into a new
- * <tt>EtConnectionParameters</tt> object.
- * @return The connection parameters.
- */
- void cache() {
- connectionParameters = new EtConnectionParameters();
- connectionParameters.setBufferName(etNameField.getText());
- connectionParameters.setHost(hostField.getText());
- connectionParameters.setPort(Integer.parseInt(portField.getText()));
- connectionParameters.setBlocking(blockingCheckBox.isSelected());
- connectionParameters.setVerbose(verboseCheckBox.isSelected());
- connectionParameters.setStationName(statNameField.getText());
- connectionParameters.setChunkSize(Integer.parseInt(chunkField.getText()));
- connectionParameters.setQueueSize(Integer.parseInt(qSizeField.getText()));
- connectionParameters.setStationPosition(Integer.parseInt(positionField.getText()));
- connectionParameters.setStationsParallelPosition(Integer.parseInt(ppositionField.getText()));
- connectionParameters.setWaitMode(getWaitMode());
- connectionParameters.setWaitTime(Integer.parseInt(waitTimeField.getText()));
- connectionParameters.setPreScale(Integer.parseInt(prescaleField.getText()));
- }
-
- void revert() {
- setConnectionParameters(connectionParameters);
- }
-
- /**
- * Get the current connection parameters.
- * @return The current connection parameters.
- */
- EtConnectionParameters getConnectionParameters() {
- return connectionParameters;
- }
-
- /**
- * Get the current wait mode from the GUI selection.
- * @return The wait mode.
- */
- private Mode getWaitMode() {
- Mode mode = null;
- String sel = (String) waitComboBox.getSelectedItem();
- if (Mode.TIMED.toString().equalsIgnoreCase(sel)) {
- mode = Mode.TIMED;
- } else if (Mode.ASYNC.toString().equalsIgnoreCase(sel)) {
- mode = Mode.ASYNC;
- } else if (Mode.SLEEP.toString().equalsIgnoreCase(sel)) {
- mode = Mode.SLEEP;
- }
- return mode;
- }
-
- /**
- * Set the wait mode and push to the GUI.
- * @param waitMode The wait mode.
- */
- private void setWaitMode(Mode waitMode) {
- if (waitMode == Mode.SLEEP) {
- waitComboBox.setSelectedIndex(0);
- } else if (waitMode == Mode.TIMED) {
- waitComboBox.setSelectedIndex(1);
- } else if (waitMode == Mode.ASYNC) {
- waitComboBox.setSelectedIndex(2);
- }
- }
-
- /**
- * Set the connection parameters and push into the GUI.
- * @param cn The connection parameters.
- */
- private void setConnectionParameters(EtConnectionParameters connectionParameters) {
- this.connectionParameters = connectionParameters;
- etNameField.setText(connectionParameters.getBufferName());
- hostField.setText(connectionParameters.getHost());
- portField.setText(Integer.toString(connectionParameters.getPort()));
- blockingCheckBox.setSelected(connectionParameters.getBlocking());
- verboseCheckBox.setSelected(connectionParameters.getVerbose());
- statNameField.setText(connectionParameters.getStationName());
- chunkField.setText(Integer.toString(connectionParameters.getChunkSize()));
- qSizeField.setText(Integer.toString(connectionParameters.getQueueSize()));
- positionField.setText(Integer.toString(connectionParameters.getStationPosition()));
- ppositionField.setText(Integer.toString(connectionParameters.getStationParallelPosition()));
- setWaitMode(connectionParameters.getWaitMode());
- waitTimeField.setText(Integer.toString(connectionParameters.getWaitTime()));
- prescaleField.setText(Integer.toString(connectionParameters.getPrescale()));
- }
-
- /**
- * Enable or disable the connection panel GUI elements.
- * @param e Set to true for enabled; false to disable.
- */
- void enableConnectionPanel(boolean e) {
- etNameField.setEnabled(e);
- hostField.setEnabled(e);
- portField.setEnabled(e);
- blockingCheckBox.setEnabled(e);
- verboseCheckBox.setEnabled(e);
- statNameField.setEnabled(e);
- chunkField.setEnabled(e);
- qSizeField.setEnabled(e);
- positionField.setEnabled(e);
- ppositionField.setEnabled(e);
- waitComboBox.setEnabled(e);
- waitTimeField.setEnabled(e);
- prescaleField.setEnabled(e);
- }
-
- /**
- * Load connection parameters from a selected file.
- */
- void load() {
- JFileChooser fc = new JFileChooser();
- int r = fc.showOpenDialog(ConnectionPanel.this);
- if (r == JFileChooser.APPROVE_OPTION) {
- File file = fc.getSelectedFile();
- loadPropertiesFile(file);
- }
- }
-
- /**
- * Reset the connection parameters.
- */
- void reset() {
- setConnectionParameters(new EtConnectionParameters());
- }
-
- /**
- * Write connection parameters to a file.
- * @param file The output properties file.
- */
- void writePropertiesFile(File file) {
- Properties prop = new Properties();
- prop.setProperty("etName", etNameField.getText());
- prop.setProperty("host", hostField.getText());
- prop.setProperty("port", portField.getText());
- prop.setProperty("blocking", Boolean.toString(blockingCheckBox.isSelected()));
- prop.setProperty("verbose", Boolean.toString(verboseCheckBox.isSelected()));
- prop.setProperty("statName", statNameField.getText());
- prop.setProperty("chunk", chunkField.getText());
- prop.setProperty("qSize", qSizeField.getText());
- prop.setProperty("position", positionField.getText());
- prop.setProperty("pposition", ppositionField.getText());
- prop.setProperty("waitMode", (String) waitComboBox.getSelectedItem());
- prop.setProperty("waitTime", waitTimeField.getText());
- prop.setProperty("prescale", prescaleField.getText());
- try {
- prop.store(new FileOutputStream(file), null);
- } catch (Exception e) {
- showErrorDialog(e.getLocalizedMessage());
- }
- }
-
- /**
- * Show an error dialog.
- * @param mesg The dialog message.
- */
- private void showErrorDialog(String mesg) {
- JOptionPane.showMessageDialog(this, mesg);
- }
-
- /**
- * Set the wait mode.
- * @param waitMode The wait mode.
- */
- private void setWaitMode(String waitMode) {
- if (Mode.SLEEP.toString().equalsIgnoreCase(waitMode)) {
- waitComboBox.setSelectedIndex(0);
- } else if (Mode.TIMED.toString().equalsIgnoreCase(waitMode)) {
- waitComboBox.setSelectedIndex(1);
- } else if (Mode.ASYNC.toString().equalsIgnoreCase(waitMode)) {
- waitComboBox.setSelectedIndex(2);
- }
- }
-
- /**
- * Load connection parameters from properties file.
- * @param file The properties file.
- */
- void loadPropertiesFile(File file) {
- Properties prop = new Properties();
- try {
- prop.load(new FileInputStream(file));
- etNameField.setText(prop.getProperty("etName"));
- hostField.setText(prop.getProperty("host"));
- portField.setText(prop.getProperty("port"));
- blockingCheckBox.setSelected(Boolean.parseBoolean(prop.getProperty("blocking")));
- verboseCheckBox.setSelected(Boolean.parseBoolean(prop.getProperty("verbose")));
- statNameField.setText(prop.getProperty("statName"));
- chunkField.setText(prop.getProperty("chunk"));
- qSizeField.setText(prop.getProperty("qSize"));
- positionField.setText(prop.getProperty("position"));
- ppositionField.setText(prop.getProperty("pposition"));
- setWaitMode(prop.getProperty("waitMode"));
- waitTimeField.setText(prop.getProperty("waitTime"));
- prescaleField.setText(prop.getProperty("prescale"));
- } catch (FileNotFoundException e) {
- showErrorDialog(e.getLocalizedMessage());
- } catch (IOException e) {
- showErrorDialog(e.getLocalizedMessage());
- }
- cache();
- }
-}
\ No newline at end of file
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/ConnectionStatus.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/ConnectionStatus.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,50 +0,0 @@
-package org.hps.monitoring.gui;
-
-/**
- * Connection status setting.
- * @author Jeremy McCormick <[log in to unmask]>
- * @version $Id: ConnectionStatus.java,v 1.3 2013/11/05 17:15:04 jeremy Exp $
- */
-final class ConnectionStatus
-{
- /**
- * The status codes.
- */
- static final int DISCONNECTED = 0;
- static final int CONNECTED = 1;
- static final int CONNECTING = 2;
- static final int TIMED_OUT = 3;
- static final int SLEEPING = 4;
- static final int DISCONNECTING = 5;
- static final int ERROR = 6;
- static final int CONNECTION_REQUESTED = 7;
- static final int DISCONNECT_REQUESTED = 8;
-
- /**
- * The string descriptions for connection statuses.
- */
- private static final String[] statuses = {
- "DISCONNECTED",
- "CONNECTED",
- "CONNECTING",
- "TIMED OUT",
- "SLEEPING",
- "DISCONNECTING",
- "ERROR",
- "CONNECTION REQUESTED",
- "DISCONNECT REQUESTED" };
-
- /**
- * Total number of statuses.
- */
- static final int NUMBER_STATUSES = statuses.length;
-
- /**
- * Convert status setting to string.
- * @param status The status setting.
- * @return The status string.
- */
- static String toString(int status) {
- return statuses[status].toUpperCase();
- }
-}
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/ConnectionStatusPanel.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/ConnectionStatusPanel.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -16,10 +16,10 @@
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
+import org.hps.monitoring.enums.ConnectionStatus;
+
/**
* This is the panel for showing the current connection status (connected, disconnected, etc.).
- * @author Jeremy McCormick <[log in to unmask]>
- * @version $Id: ConnectionStatusPanel.java,v 1.11 2013/11/05 17:15:04 jeremy Exp $
*/
class ConnectionStatusPanel extends JPanel {
@@ -28,12 +28,17 @@
// Format for date field.
private final SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM-dd-yyyy HH:mm:ss");
+
+ private static final int PANEL_HEIGHT = 50;
+ private static final int PANEL_WIDTH = 400;
/**
* Class constructor.
*/
ConnectionStatusPanel() {
+ setMinimumSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT));
+
setLayout(new GridBagLayout());
//setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
Font font = new Font("Arial", Font.PLAIN, 14);
@@ -101,23 +106,13 @@
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = GridBagConstraints.REMAINDER;
c.insets = new Insets(10, 0, 0, 0);
- add(new JSeparator(SwingConstants.HORIZONTAL), c);
-
- // Set default status.
- setStatus(ConnectionStatus.DISCONNECTED);
- }
-
- /**
- * Set the connection status.
- * @param status The status code.
- */
- void setStatus(final int status) {
- if (status < 0 || status > (ConnectionStatus.NUMBER_STATUSES - 1)) {
- throw new IllegalArgumentException("Invalid status argument: " + status);
- }
+ add(new JSeparator(SwingConstants.HORIZONTAL), c);
+ }
+
+ void setConnectionStatus(final ConnectionStatus status) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
- statusField.setText(ConnectionStatus.toString(status));
+ statusField.setText(status.name());
dateField.setText(dateFormat.format(new Date()));
}
});
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/DatePanel.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/DatePanel.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -4,7 +4,10 @@
import java.text.SimpleDateFormat;
import java.util.Date;
-public class DatePanel extends FieldPanel {
+/**
+ * A small JPanel with a date field and a label on its border.
+ */
+class DatePanel extends FieldPanel {
private SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM-dd-yyyy HH:mm:ss");
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/EventButtonsPanel.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/EventButtonsPanel.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -9,10 +9,10 @@
import javax.swing.JPanel;
/**
- * This is the panel for controlling the application when it is in pause mode,
- * e.g. to step to the next event, etc.
+ * This is the panel with buttons for connecting or disconnecting
+ * and controlling the app from pause mode.
*/
-public class EventButtonsPanel extends JPanel {
+class EventButtonsPanel extends JPanel {
JButton nextEventsButton;
JButton pauseButton;
@@ -32,7 +32,7 @@
c.insets = new Insets(0, 0, 0, 10);
connectButton = new JButton("Connect");
connectButton.setEnabled(true);
- connectButton.setActionCommand(MonitoringCommands.CONNECT);
+ connectButton.setActionCommand(Commands.CONNECT);
add(connectButton, c);
c = new GridBagConstraints();
@@ -40,7 +40,7 @@
c.gridy = 0;
c.insets = new Insets(0, 0, 0, 10);
pauseButton = new JButton("Pause");
- pauseButton.setActionCommand(MonitoringCommands.PAUSE);
+ pauseButton.setActionCommand(Commands.PAUSE);
pauseButton.setEnabled(false);
add(pauseButton, c);
@@ -49,21 +49,21 @@
c.gridy = 0;
nextEventsButton = new JButton("Next Event");
nextEventsButton.setEnabled(false);
- nextEventsButton.setActionCommand(MonitoringCommands.NEXT);
+ nextEventsButton.setActionCommand(Commands.NEXT);
add(nextEventsButton, c);
}
/**
- * Toggle the connect button from its current state. If it is in "Connect" state
- * then it will be toggled to "Disconnect" and vice versa.
+ * Set the application connection state.
+ * @param connected True if application is connected or false if disconnected.
*/
- void toggleConnectButton() {
- if (connectButton.getText().equals("Connect")) {
+ void setConnected(boolean connected) {
+ if (connected) {
connectButton.setText("Disconnect");
- connectButton.setActionCommand(MonitoringCommands.DISCONNECT);
+ connectButton.setActionCommand(Commands.DISCONNECT);
} else {
connectButton.setText("Connect");
- connectButton.setActionCommand(MonitoringCommands.CONNECT);
+ connectButton.setActionCommand(Commands.CONNECT);
}
}
@@ -101,10 +101,10 @@
this.nextEventsButton.setEnabled(enable);
if (enable) {
pauseButton.setText("Resume");
- pauseButton.setActionCommand(MonitoringCommands.RESUME);
+ pauseButton.setActionCommand(Commands.RESUME);
} else {
pauseButton.setText("Pause");
- pauseButton.setActionCommand(MonitoringCommands.PAUSE);
+ pauseButton.setActionCommand(Commands.PAUSE);
}
}
}
\ No newline at end of file
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/FieldPanel.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/FieldPanel.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -9,9 +9,8 @@
/**
* A panel with a label and a text field.
- * @author Jeremy McCormick <[log in to unmask]>
*/
-public class FieldPanel extends JPanel {
+class FieldPanel extends JPanel {
String fieldName;
String defaultValue;
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/FieldsPanel.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/FieldsPanel.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,235 +0,0 @@
-package org.hps.monitoring.gui;
-
-import java.awt.Color;
-import java.awt.GridBagConstraints;
-import java.awt.Insets;
-import java.awt.event.ActionListener;
-
-import javax.swing.JCheckBox;
-import javax.swing.JComboBox;
-import javax.swing.JLabel;
-import javax.swing.JPanel;
-import javax.swing.JTextField;
-
-/**
- * This class is used to provide utility methods for the data panels in the application tabs.
- * @author Jeremy McCormick <[log in to unmask]>
- * @version $Id: FieldsPanel.java,v 1.3 2013/11/05 17:15:04 jeremy Exp $
- */
-public class FieldsPanel extends JPanel {
-
- private int currY = 0;
- private Insets insets;
- private boolean editable = false;
-
- /**
- * Class constructor.
- * @param insets The insets for the panel.
- * @param editable Editable setting.
- */
- FieldsPanel(Insets insets, boolean editable) {
- this.insets = insets;
- this.editable = editable;
- }
-
- /**
- * Class constructor.
- */
- FieldsPanel() {
- this.insets = new Insets(1, 1, 1, 1);
- }
-
- /**
- * Add a field.
- * @param name The name of the field.
- * @param size The size of the field.
- * @return The JTextField component.
- */
- protected final JTextField addField(String name, int size) {
- return addField(name, "", size, this.editable);
- }
-
- /**
- * Add a field.
- * @param name The name of the field.
- * @param value The default value of the field.
- * @param size The size of the field.
- * @return The JTextField component.
- */
- protected final JTextField addField(String name, String value, int size) {
- return addField(name, value, size, this.editable);
- }
-
- /**
- * Add a field.
- * @param name The name of the field.
- * @param value The default value of the field.
- * @param tooltip The tooltip text.
- * @param size The size of the field.
- * @param editable The editable setting.
- * @return The JTextField component.
- */
- protected final JTextField addField(String name, String value, String tooltip, int size, boolean editable) {
- JTextField f = addField(name, value, size, editable);
- f.setToolTipText(tooltip);
- return f;
- }
-
- /**
- * Add a field.
- * @param name The name of the field.
- * @param value The default value of the field.
- * @param size The size of the field.
- * @param editable The editable setting.
- * @return The JTextField component.
- */
- protected final JTextField addField(String name, String value, int size, boolean editable) {
- GridBagConstraints c = new GridBagConstraints();
- c.gridx = 0;
- c.gridy = currY;
- c.insets = insets;
- c.anchor = GridBagConstraints.WEST;
- JLabel label = new JLabel(name + ":");
- add(label, c);
-
- c = new GridBagConstraints();
- c.gridx = 1;
- c.gridy = currY;
- c.insets = insets;
- c.anchor = GridBagConstraints.EAST;
- JTextField field = new JTextField(value, size);
- field.setHorizontalAlignment(JTextField.RIGHT);
- field.setEditable(editable);
- field.setBackground(Color.WHITE);
- add(field, c);
-
- ++currY;
-
- return field;
- }
-
- /**
- * Add a combo box.
- * @param name The name of the combo box.
- * @param values The set of values for the combo box.
- * @return The JComboBox component.
- */
- protected final JComboBox addComboBox(String name, String[] values) {
-
- //System.out.println("addComboBox = " + name);
-
- GridBagConstraints c = new GridBagConstraints();
- c.gridx = 0;
- c.gridy = currY;
- c.insets = insets;
- c.anchor = GridBagConstraints.WEST;
- JLabel waitModeLabel = new JLabel(name + ":");
- waitModeLabel.setHorizontalAlignment(JLabel.LEFT);
- add(waitModeLabel, c);
-
- c = new GridBagConstraints();
- c.gridx = 1;
- c.gridy = currY;
- c.insets = insets;
- c.anchor = GridBagConstraints.EAST;
- JComboBox combo = new JComboBox(values);
- //System.out.println("combo width = " + combo.getWidth());
- //System.out.println("combo width = " + combo.getSize().getWidth());
- combo.setEditable(editable);
- add(combo, c);
-
- ++currY;
-
- return combo;
- }
-
- /**
- * Add a multiline combo box.
- * @param name The name of the combo box.
- * @param values The values for the combo box.
- * @return The JComboBox component.
- */
- protected final JComboBox addComboBoxMultiline(String name, String[] values) {
-
- GridBagConstraints c = new GridBagConstraints();
- c.gridx = 0;
- c.gridwidth = GridBagConstraints.REMAINDER;
- c.gridy = currY;
- c.insets = insets;
- c.anchor = GridBagConstraints.WEST;
- JLabel waitModeLabel = new JLabel(name + ":");
- waitModeLabel.setHorizontalAlignment(JLabel.LEFT);
- add(waitModeLabel, c);
- ++currY;
-
- c = new GridBagConstraints();
- c.gridx = 0;
- c.gridwidth = GridBagConstraints.REMAINDER;
- c.gridy = currY;
- c.insets = insets;
- c.anchor = GridBagConstraints.WEST;
- JComboBox combo = new JComboBox(values);
- //System.out.println("combo width = " + combo.getWidth());
- //System.out.println("combo width = " + combo.getSize().getWidth());
- combo.setEditable(editable);
- add(combo, c);
-
- ++currY;
-
- return combo;
- }
-
- /**
- * Add a check box.
- * @param name The name of the check box.
- * @param tooltip The tooltip text.
- * @param selected Whether the box is selected or not.
- * @param enabled Whether it is enabled or not.
- * @return The JCheckBox component.
- */
- protected final JCheckBox addCheckBox(String name, String tooltip, boolean selected, boolean enabled) {
- JCheckBox c = addCheckBox(name, selected, enabled);
- c.setToolTipText(tooltip);
- return c;
- }
-
- /**
- * Add a check box.
- * @param name The name of the check box.
- * @param selected Whether the check box is selected or not.
- * @param enabled Whether it is enabled or not.
- * @return The JCheckBox component.
- */
- protected final JCheckBox addCheckBox(String name, boolean selected, boolean enabled) {
-
- GridBagConstraints c = new GridBagConstraints();
- c.gridx = 0;
- c.gridy = currY;
- c.insets = insets;
- c.anchor = GridBagConstraints.WEST;
- JLabel label = new JLabel(name + ":");
- add(label, c);
-
- c = new GridBagConstraints();
- c.gridx = 1;
- c.gridy = currY;
- c.insets = insets;
- c.anchor = GridBagConstraints.EAST;
- JCheckBox checkbox = new JCheckBox();
- checkbox.setSelected(selected);
- checkbox.setEnabled(enabled);
- add(checkbox, c);
-
- ++currY;
-
- return checkbox;
- }
-
- /**
- * Add an ActionListener to this component. By default this does nothing, but
- * individual sub-components should attach this to individual components.
- * @param listener The AcitonListener to add.
- */
- void addActionListener(ActionListener listener) {
- }
-}
\ No newline at end of file
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/JobPanel.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/JobPanel.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,576 +0,0 @@
-package org.hps.monitoring.gui;
-
-import java.awt.GridBagLayout;
-import java.awt.Insets;
-import java.awt.event.ActionListener;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.JarURLConnection;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.List;
-import java.util.jar.JarEntry;
-import java.util.jar.JarFile;
-import java.util.logging.Level;
-
-import javax.swing.JCheckBox;
-import javax.swing.JComboBox;
-import javax.swing.JFileChooser;
-import javax.swing.JOptionPane;
-import javax.swing.JTextField;
-import javax.swing.SwingUtilities;
-
-/**
- * The panel for setting job parameters.
- * @author Jeremy McCormick <[log in to unmask]>
- * @version $Id: JobPanel.java,v 1.17 2013/11/05 17:15:04 jeremy Exp $
- */
-class JobPanel extends FieldsPanel {
-
- private JTextField detectorNameField;
- private JCheckBox disconnectOnErrorCheckBox;
- private JTextField eventBuilderField;
- private JComboBox<?> steeringTypeComboBox;
- private JTextField steeringFileField;
- private JComboBox<?> steeringResourcesComboBox;
- private JCheckBox logCheckBox;
- private JTextField logFileField;
- private JCheckBox pauseModeCheckBox;
- private JComboBox<?> logLevelComboBox;
- private JTextField aidaSaveField;
- private JCheckBox aidaSaveCheckBox;
-
- private String steeringPackage = "org/hps/steering/monitoring/";
-
- private String defaultEventBuilderClassName = (new JobSettings()).eventBuilderClassName;
-
- private final static String[] steeringTypes = {"RESOURCE", "FILE"};
- final static int RESOURCE = 0;
- final static int FILE = 1;
-
- JobSettings settings;
-
- /**
- * The available LogLevel settings.
- */
- String[] logLevels = new String[] {
- Level.ALL.toString(),
- Level.FINEST.toString(),
- Level.FINER.toString(),
- Level.FINE.toString(),
- Level.CONFIG.toString(),
- Level.INFO.toString(),
- Level.WARNING.toString(),
- Level.SEVERE.toString(),
- Level.OFF.toString()};
-
- /**
- * Class constructor.
- */
- JobPanel() {
-
- super(new Insets(4, 2, 2, 4), true);
- setLayout(new GridBagLayout());
-
- pauseModeCheckBox = addCheckBox("Pause mode", false, true);
- disconnectOnErrorCheckBox = addCheckBox("Disconnect on error", false, true);
- logLevelComboBox = addComboBox("Log Level", this.logLevels);
- logLevelComboBox.setActionCommand(MonitoringCommands.SET_LOG_LEVEL);
- steeringTypeComboBox = addComboBox("Steering Type", steeringTypes);
- steeringFileField = addField("Steering File", 35);
- steeringResourcesComboBox = addComboBoxMultiline("Steering File Resource",
- getAvailableSteeringFileResources(steeringPackage));
- steeringResourcesComboBox.setActionCommand(MonitoringCommands.SET_STEERING_RESOURCE);
- detectorNameField = addField("Detector Name", 20);
- eventBuilderField = addField("Event Builder Class", 30);
- eventBuilderField.setActionCommand(MonitoringCommands.SET_EVENT_BUILDER);
- logCheckBox = addCheckBox("Log to File", false, false);
- logFileField = addField("Log File", "", "Full path to log file.", 30, false);
- aidaSaveCheckBox = addCheckBox("Save AIDA at End of Job", false, false);
- aidaSaveField = addField("AIDA Auto Save File Name", "", 30, false);
-
- // Set default job settings.
- setJobSettings(new JobSettings());
- }
-
- /**
- * Enable this component.
- * @param enable Whether to enable or not.
- */
- void enableJobPanel(boolean enable) {
- detectorNameField.setEnabled(enable);
- eventBuilderField.setEnabled(enable);
- pauseModeCheckBox.setEnabled(enable);
- steeringTypeComboBox.setEnabled(enable);
- steeringFileField.setEnabled(enable);
- steeringResourcesComboBox.setEnabled(enable);
- }
-
- /**
- * Attaches the ActionListener from the main app to GUI components in this class.
- */
- void addActionListener(ActionListener listener) {
- steeringResourcesComboBox.addActionListener(listener);
- logLevelComboBox.addActionListener(listener);
- eventBuilderField.addActionListener(listener);
- }
-
- /**
- * Choose a file name for the automatic AIDA save file.
- */
- void chooseAidaAutoSaveFile() {
- JFileChooser fc = new JFileChooser();
- fc.setDialogTitle("Choose AIDA Auto Save File");
- int r = fc.showSaveDialog(this);
- if (r == JFileChooser.APPROVE_OPTION) {
- File file = fc.getSelectedFile();
- String fileName = file.getPath();
- int extIndex = fileName.lastIndexOf(".");
- if ((extIndex == -1) || !(fileName.substring(extIndex + 1, fileName.length())).toLowerCase().equals("aida")) {
- fileName = fileName + ".aida";
- }
- final String fileName2 = fileName;
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- aidaSaveCheckBox.setSelected(true);
- aidaSaveField.setText(fileName2);
- }
- });
- }
- }
-
- /**
- * Check that the steering file or resource is valid.
- * @return True if steering is valid; false if not.
- */
- boolean checkSteering() {
- String steering = steeringFileField.getText();
- int steeringType = steeringTypeComboBox.getSelectedIndex();
- if (RESOURCE == steeringType) {
- // Check that steering resource exists.
- InputStream is = getClass().getResourceAsStream(steering);
- if (is == null) {
- return false;
- } else {
- return true;
- }
- } else if (FILE == steeringType) {
- // Check that steering file exists.
- File f = new File(steering);
- if (!f.exists()) {
- return false;
- } else {
- return true;
- }
- } else {
- throw new IllegalArgumentException("The steeringType is invalid: " + steeringType);
- }
- }
-
- /**
- * Setup the event builder from the field setting.
- * @return True if builder is setup successfully; false if not.
- */
- void editEventBuilder() {
- String eventBuilderClassName = eventBuilderField.getText();
- boolean okay = true;
- try {
- // Test that the event builder can be created without throwing any exceptions.
- Class<?> eventBuilderClass = Class.forName(eventBuilderClassName);
- eventBuilderClass.newInstance();
- }
- catch (ClassNotFoundException e) {
- JOptionPane.showMessageDialog(this, "The event builder class does not exist.");
- okay = false;
- }
- catch (InstantiationException e) {
- JOptionPane.showMessageDialog(this, "Failed to instantiate instance of event builder class.");
- okay = false;
- }
- catch (IllegalAccessException e) {
- JOptionPane.showMessageDialog(this, "Couldn't access event builder class.");
- okay = false;
- }
-
- if (!okay)
- resetEventBuilder();
- }
-
- /**
- * Reset the event builder to the default.
- */
- private void resetEventBuilder() {
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- eventBuilderField.setText(defaultEventBuilderClassName);
- }
- });
- }
-
- /**
- * Get the event builder class name.
- * @return The event builder class name.
- */
- String getEventBuilderClassName() {
- return eventBuilderField.getText();
- }
-
- /**
- * Set the steering file field.
- * @param steeringFile The path to the file.
- */
- void setSteeringFile(final String steeringFile) {
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- steeringFileField.setText(steeringFile);
- }
- });
- }
-
- /**
- * Set the steering file resource.
- * @param s The resource path.
- */
- void setSteeringResource(final String s) {
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- steeringResourcesComboBox.setSelectedItem(s);
- }
- });
- }
-
- /**
- * Set the name of the detector.
- * @param detectorName The name of the detector.
- */
- void setDetectorName(final String detectorName) {
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- detectorNameField.setText(detectorName);
- }
- });
- }
-
- /**
- * Get the steering file or resource path from the field setting.
- * @return The steering file or resource path.
- */
- String getSteering() {
- if (getSteeringType() == FILE) {
- return steeringFileField.getText();
- }
- else if (getSteeringType() == RESOURCE) {
- return (String) steeringResourcesComboBox.getSelectedItem();
- }
- else {
- return null;
- }
- }
-
- /**
- * Get the type of steering, file or resource.
- * @return The type of steering.
- */
- int getSteeringType() {
- return steeringTypeComboBox.getSelectedIndex();
- }
-
- /**
- * Get the name of the detector.
- * @return The name of the detector.
- */
- String getDetectorName() {
- return detectorNameField.getText();
- }
-
- /**
- *
- * @param defaultEventBuilderClassName
- */
- void setDefaultEventBuilder(final String defaultEventBuilderClassName) {
- this.defaultEventBuilderClassName = defaultEventBuilderClassName;
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- eventBuilderField.setText(defaultEventBuilderClassName);
- }
- });
- }
-
- /**
- * Check if pause mode is selected.
- * @return True if pause mode is enabled; false if not.
- */
- boolean pauseMode() {
- return this.pauseModeCheckBox.isSelected();
- }
-
- /**
- * Set the pause mode.
- * @param p The pause mode; true for on; false for off.
- */
- void enablePauseMode(final boolean p) {
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- pauseModeCheckBox.setSelected(p);
- }
- });
- }
-
- /**
- * Get the log level from the combo box.
- * @return The log level.
- */
- Level getLogLevel() {
- return Level.parse((String) logLevelComboBox.getSelectedItem());
- }
-
- /**
- * Get the disconnect on error setting from the check box.
- * @return The disconnect on error setting.
- */
- boolean disconnectOnError() {
- return disconnectOnErrorCheckBox.isSelected();
- }
-
- /**
- * Get the log to file setting.
- * @return The log to file setting.
- */
- boolean logToFile() {
- return logCheckBox.isSelected();
- }
-
- /**
- * Get the log file name.
- * @return The log file name.
- */
- String getLogFileName() {
- return logFileField.getText();
- }
-
- /**
- * Get whether AIDA autosave is enabled.
- * @return True if AIDA autosave is enabled; false if not.
- */
- boolean isAidaAutoSaveEnabled() {
- return aidaSaveCheckBox.isSelected();
- }
-
- /**
- * Get the AIDA autosave file name.
- * @return The AIDA autosave file name.
- */
- String getAidaAutoSaveFileName() {
- return aidaSaveField.getText();
- }
-
- /**
- * Set whether to disconnect if errors occur.
- * @param b The disconnect on error setting.
- */
- private void setDisconnectOnError(final boolean b) {
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- disconnectOnErrorCheckBox.setSelected(b);
- }
- });
- }
-
- /**
- * Set the steering type.
- * @param t The steering type.
- */
- void setSteeringType(final int t) {
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- steeringTypeComboBox.setSelectedIndex(t);
- }
- });
- }
-
- /**
- * Set the log level.
- * @param level The log level.
- */
- private void setLogLevel(final Level level) {
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- logLevelComboBox.setSelectedItem(level.toString());
- }
- });
- }
-
- /**
- * Set the fully qualified class name of the event builder.
- * @param c The class name of the event builder.
- */
- private void setEventBuilder(final String c) {
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- eventBuilderField.setText(c);
- }
- });
- }
-
- /**
- * Set whether to log to a file.
- * @param b The log to file setting.
- */
- void setLogToFile(final boolean b) {
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- logCheckBox.setSelected(b);
- }
- });
- }
-
- /**
- * Set the log file name.
- * @param s The log file name.
- */
- void setLogFile(final String s) {
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- logFileField.setText(s);
- }
- });
- }
-
- /**
- * Set AIDA autosave.
- * @param b The AIDA autosave setting.
- */
- private void enableAidaAutoSave(final boolean b) {
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- aidaSaveCheckBox.setSelected(b);
- }
- });
- }
-
- /**
- * Set the AIDA autosave file name.
- * @param s The AIDA autosave file name.
- */
- private void setAidaAutoSaveFileName(final String s) {
- SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- aidaSaveField.setText(s);
- }
- });
- }
-
- /**
- * Get the resource path for the steering file.
- * @return The resource path for the steering file.
- */
- private String getSelectedSteeringResource() {
- return (String) steeringResourcesComboBox.getSelectedItem();
- }
-
- /**
- * Get the path to the steering file path.
- * @return The steering file path.
- */
- private String getSteeringFile() {
- return steeringFileField.getText();
- }
-
- /**
- * Gather {@link JobSettings} parameters from GUI and return a JobSettings object.
- * @return The JobSettings from the JobPanel.
- */
- JobSettings getJobSettings() {
- return settings;
- }
-
- /**
- * Cache the settings from the GUI into the <tt>JobSettings</tt> object.
- */
- void cache() {
- settings = new JobSettings();
- settings.pauseMode = pauseMode();
- settings.disconnectOnError = disconnectOnError();
- settings.logLevel = getLogLevel();
- settings.steeringType = getSteeringType();
- settings.steeringFile = getSteeringFile();
- settings.steeringResource = getSelectedSteeringResource();
- settings.detectorName = getDetectorName();
- settings.eventBuilderClassName = getEventBuilderClassName();
- settings.logToFile = logToFile();
- settings.logFileName = getLogFileName();
- settings.autoSaveAida = isAidaAutoSaveEnabled();
- settings.autoSaveAidaFileName = getAidaAutoSaveFileName();
- }
-
- /**
- * Revert job settings in GUI based on current <tt>JobSettings</tt> object.
- */
- void revert() {
- setJobSettings(settings);
- }
-
- /**
- * Set the JobPanel parameters from a JobSettings object.
- * @param settings The JobSettings to load.
- */
- void setJobSettings(JobSettings settings) {
- this.settings = settings;
- enablePauseMode(settings.pauseMode);
- setDisconnectOnError(settings.disconnectOnError);
- setLogLevel(settings.logLevel);
- setSteeringType(settings.steeringType);
- setSteeringFile(settings.steeringFile);
- setSteeringResource(settings.steeringResource);
- setDetectorName(settings.detectorName);
- setEventBuilder(settings.eventBuilderClassName);
- setLogToFile(settings.logToFile);
- setLogFile(settings.logFileName);
- enableAidaAutoSave(settings.autoSaveAida);
- setAidaAutoSaveFileName(settings.autoSaveAidaFileName);
- }
-
- /**
- * Reset the JobPanel to its defaults.
- */
- void resetJobSettings() {
- setJobSettings(new JobSettings());
- }
-
- /**
- * Get the files that end in .lcsim from all loaded jar files.
- * @return A list of embedded steering file resources.
- */
- public static String[] getAvailableSteeringFileResources(String packageName) {
- List<String> resources = new ArrayList<String>();
- URL url = JobPanel.class.getResource("MonitoringApplication.class");
- String scheme = url.getProtocol();
- if (!"jar".equals(scheme)) {
- throw new IllegalArgumentException("Unsupported scheme: " + scheme);
- }
- try {
- JarURLConnection con = (JarURLConnection) url.openConnection();
- JarFile archive = con.getJarFile();
- Enumeration<JarEntry> entries = archive.entries();
- while (entries.hasMoreElements()) {
- JarEntry entry = entries.nextElement();
- if (entry.getName().endsWith(".lcsim") && entry.getName().contains(packageName)) {
- resources.add(entry.getName());
- }
- }
- archive.close();
- }
- catch (IOException e) {
- throw new RuntimeException(e);
- }
- java.util.Collections.sort(resources);
- String[] arr = new String[resources.size()];
- for (int i=0; i<arr.length; i++) {
- arr[i] = resources.get(i);
- }
- return arr;
- }
-
-}
\ No newline at end of file
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/JobSettings.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/JobSettings.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,76 +0,0 @@
-package org.hps.monitoring.gui;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.Properties;
-import java.util.logging.Level;
-
-/**
- * @author Jeremy McCormick <[log in to unmask]>
- * @version $Id: JobSettings.java,v 1.6 2013/10/30 17:05:17 jeremy Exp $
- */
-final class JobSettings {
-
- // Default job settings.
- boolean pauseMode = false;
- boolean disconnectOnError = false;
- Level logLevel = Level.ALL;
- int steeringType = 0; // resource = 0; file = 1
- String steeringResource = "org/hps/steering/monitoring/TestRunMonitoring.lcsim";
- String steeringFile = "";
- String detectorName = "HPS-TestRun-v5";
- String eventBuilderClassName = "org.hps.evio.LCSimTestRunEventBuilder";
- boolean logToFile = false;
- String logFileName = "";
- boolean autoSaveAida = false;
- String autoSaveAidaFileName = "";
- boolean enableRemoteAida = false;
- String remoteAidaName = "hps";
-
- JobSettings() {
- }
-
- JobSettings(File f) throws IOException {
- load(f);
- }
-
- void save(File file) throws IOException {
- Properties prop = new Properties();
- prop.setProperty("pauseMode", Boolean.toString(pauseMode));
- prop.setProperty("disconnectOnError", Boolean.toString(disconnectOnError));
- prop.setProperty("logLevel", logLevel.toString());
- prop.setProperty("steeringType", Integer.toString(steeringType));
- prop.setProperty("steeringFile", steeringFile);
- prop.setProperty("steeringResource", steeringResource);
- prop.setProperty("detectorName", detectorName);
- prop.setProperty("eventBuilderClassName", eventBuilderClassName);
- prop.setProperty("logToFile", Boolean.toString(logToFile));
- prop.setProperty("logFileName", logFileName);
- prop.setProperty("autoSaveAida", Boolean.toString(autoSaveAida));
- prop.setProperty("autoSaveAidaFileName", autoSaveAidaFileName);
- prop.setProperty("enableRemoteAida", Boolean.toString(enableRemoteAida));
- prop.setProperty("remoteAidaName", remoteAidaName);
- prop.store(new FileOutputStream(file), null);
- }
-
- void load(File file) throws IOException {
- Properties prop = new Properties();
- prop.load(new FileInputStream(file));
- pauseMode = Boolean.parseBoolean(prop.getProperty("pauseMode"));
- disconnectOnError = Boolean.parseBoolean(prop.getProperty("disconnectOnError"));
- logLevel = Level.parse(prop.getProperty("logLevel"));
- steeringType = Integer.parseInt(prop.getProperty("steeringType"));
- steeringFile = prop.getProperty("steeringFile");
- steeringResource = prop.getProperty("steeringResource");
- detectorName = prop.getProperty("detectorName");
- eventBuilderClassName = prop.getProperty("eventBuilderClassName");
- logToFile = Boolean.parseBoolean(prop.getProperty("logToFile"));
- logFileName = prop.getProperty("logFileName");
- autoSaveAida = Boolean.parseBoolean(prop.getProperty("autoSaveAida"));
- autoSaveAidaFileName = prop.getProperty("autoSaveAidaFileName");
- enableRemoteAida = Boolean.parseBoolean(prop.getProperty("enableRemoteAida"));
- remoteAidaName = prop.getProperty("remoteAidaName");
- }
-}
\ No newline at end of file
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/MonitoringApplication.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/MonitoringApplication.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,36 +1,25 @@
package org.hps.monitoring.gui;
-import static org.hps.monitoring.gui.MonitoringCommands.AIDA_AUTO_SAVE;
-import static org.hps.monitoring.gui.MonitoringCommands.CLEAR_LOG_TABLE;
-import static org.hps.monitoring.gui.MonitoringCommands.CONNECT;
-import static org.hps.monitoring.gui.MonitoringCommands.DISCONNECT;
-import static org.hps.monitoring.gui.MonitoringCommands.EDIT_EVENT_REFRESH;
-import static org.hps.monitoring.gui.MonitoringCommands.EXIT;
-import static org.hps.monitoring.gui.MonitoringCommands.LOAD_CONNECTION;
-import static org.hps.monitoring.gui.MonitoringCommands.LOAD_JOB_SETTINGS;
-import static org.hps.monitoring.gui.MonitoringCommands.LOG_TO_FILE;
-import static org.hps.monitoring.gui.MonitoringCommands.LOG_TO_TERMINAL;
-import static org.hps.monitoring.gui.MonitoringCommands.NEXT;
-import static org.hps.monitoring.gui.MonitoringCommands.PAUSE;
-import static org.hps.monitoring.gui.MonitoringCommands.RESET_CONNECTION_SETTINGS;
-import static org.hps.monitoring.gui.MonitoringCommands.RESET_JOB_SETTINGS;
-import static org.hps.monitoring.gui.MonitoringCommands.RESUME;
-import static org.hps.monitoring.gui.MonitoringCommands.SAVE_CONNECTION;
-import static org.hps.monitoring.gui.MonitoringCommands.SAVE_JOB_SETTINGS;
-import static org.hps.monitoring.gui.MonitoringCommands.SAVE_LOG_TABLE;
-import static org.hps.monitoring.gui.MonitoringCommands.SAVE_PLOTS;
-import static org.hps.monitoring.gui.MonitoringCommands.SCREENSHOT;
-import static org.hps.monitoring.gui.MonitoringCommands.SET_EVENT_BUILDER;
-import static org.hps.monitoring.gui.MonitoringCommands.SET_LOG_LEVEL;
-import static org.hps.monitoring.gui.MonitoringCommands.SET_STEERING_FILE;
-import static org.hps.monitoring.gui.MonitoringCommands.SET_STEERING_RESOURCE;
-import static org.hps.monitoring.gui.MonitoringCommands.SHOW_SETTINGS;
+import static org.hps.monitoring.gui.Commands.AIDA_AUTO_SAVE;
+import static org.hps.monitoring.gui.Commands.CHOOSE_LOG_FILE;
+import static org.hps.monitoring.gui.Commands.CLEAR_LOG_TABLE;
+import static org.hps.monitoring.gui.Commands.CONNECT;
+import static org.hps.monitoring.gui.Commands.DISCONNECT;
+import static org.hps.monitoring.gui.Commands.EXIT;
+import static org.hps.monitoring.gui.Commands.LOAD_DEFAULT_CONFIG_FILE;
+import static org.hps.monitoring.gui.Commands.LOG_LEVEL_CHANGED;
+import static org.hps.monitoring.gui.Commands.LOG_TO_TERMINAL;
+import static org.hps.monitoring.gui.Commands.NEXT;
+import static org.hps.monitoring.gui.Commands.PAUSE;
+import static org.hps.monitoring.gui.Commands.RESUME;
+import static org.hps.monitoring.gui.Commands.SAVE_CONFIG_FILE;
+import static org.hps.monitoring.gui.Commands.SAVE_LOG_TABLE;
+import static org.hps.monitoring.gui.Commands.SAVE_PLOTS;
+import static org.hps.monitoring.gui.Commands.SCREENSHOT;
+import static org.hps.monitoring.gui.Commands.SELECT_CONFIG_FILE;
+import static org.hps.monitoring.gui.Commands.SHOW_SETTINGS;
-import java.awt.AWTException;
-import java.awt.BorderLayout;
import java.awt.Dimension;
-import java.awt.GraphicsDevice;
-import java.awt.GraphicsEnvironment;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
@@ -40,6 +29,8 @@
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
@@ -52,8 +43,6 @@
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
-import java.util.Timer;
-import java.util.TimerTask;
import java.util.Vector;
import java.util.logging.Handler;
import java.util.logging.Level;
@@ -61,6 +50,7 @@
import java.util.logging.Logger;
import javax.imageio.ImageIO;
+import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
@@ -69,172 +59,233 @@
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
-import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import org.hps.evio.LCSimEventBuilder;
+import org.hps.monitoring.enums.ConnectionStatus;
+import org.hps.monitoring.enums.SteeringType;
+import org.hps.monitoring.gui.model.Configuration;
+import org.hps.monitoring.gui.model.ConfigurationModel;
+import org.hps.monitoring.gui.model.RunModel;
import org.hps.monitoring.plotting.MonitoringAnalysisFactory;
import org.hps.monitoring.plotting.MonitoringPlotFactory;
-import org.hps.monitoring.record.EventProcessingChain;
-import org.hps.monitoring.record.EventProcessingThread;
-import org.hps.monitoring.record.etevent.EtConnection;
-import org.hps.monitoring.record.etevent.EtConnectionParameters;
-import org.hps.monitoring.record.etevent.EtEventSource;
+import org.hps.monitoring.subsys.StatusCode;
+import org.hps.monitoring.subsys.SystemStatus;
+import org.hps.monitoring.subsys.SystemStatusListener;
+import org.hps.monitoring.subsys.SystemStatusRegistry;
+import org.hps.monitoring.subsys.et.EtSystemMonitor;
import org.hps.monitoring.subsys.et.EtSystemStripCharts;
+import org.hps.record.et.EtConnection;
+import org.hps.record.processing.DataSourceType;
+import org.hps.record.processing.ProcessingChain;
+import org.hps.record.processing.ProcessingConfiguration;
+import org.hps.record.processing.ProcessingThread;
+import org.jlab.coda.et.EtAttachment;
+import org.jlab.coda.et.EtConstants;
+import org.jlab.coda.et.EtStation;
+import org.jlab.coda.et.EtStationConfig;
+import org.jlab.coda.et.EtSystem;
+import org.jlab.coda.et.EtSystemOpenConfig;
import org.lcsim.job.JobControlManager;
+import org.lcsim.util.Driver;
import org.lcsim.util.aida.AIDA;
/**
- * Monitoring application for HPS Test Run, which can run LCSim steering files on data converted
- * from the ET ring. This class is accessible to users by calling its main() method.
- * @author Jeremy McCormick <[log in to unmask]>
- * @version $Id: MonitoringApplication.java,v 1.61 2013/12/10 07:36:40 jeremy Exp $
+ * This class is the implementation of the GUI for the Monitoring Application.
*/
-// FIXME: The tabs panel isn't filling the full available space even when fill is set to both.
-// TODO: Remove minimum GUI component size settings where they are redundant.
-// TODO: Refactor this class into multiple classes.
-// TODO: Log the messages from all Exceptions.
-// TODO: Capture std err and out and redirect to a text panel within the application.
-// TODO: Report state of event processing at the end of the job in a new GUI component.
-// TODO: Move ET cleanup code to the record.etevent package.
-public class MonitoringApplication extends JFrame implements ActionListener {
+public final class MonitoringApplication extends JFrame implements ActionListener, SystemStatusListener {
// Top-level Swing components.
private JPanel mainPanel;
- private JPanel leftPanel;
- private JPanel rightPanel;
private EventButtonsPanel buttonsPanel;
private ConnectionStatusPanel connectionStatusPanel;
private RunPanel runPanel;
- private JTabbedPane plotPane;
private JMenuBar menuBar;
private SettingsDialog settingsDialog;
+ private PlotFrame plotFrame;
+ private SystemStatusFrame systemStatusFrame;
- // References to menu items that will be enabled/disabled depending on application state.
- private JMenuItem connectItem;
- private JMenuItem disconnectItem;
- private JMenuItem resetConnectionItem;
- private JMenuItem connectionLoadItem;
+ // References to menu items that will be toggled depending on application state.
private JMenuItem savePlotsItem;
private JMenuItem logItem;
private JMenuItem terminalItem;
- private JMenuItem steeringItem;
- private JMenuItem aidaAutoSaveItem;
- private JMenuItem saveJobSettingsItem;
- private JMenuItem loadJobSettingsItem;
- private JMenuItem resetJobSettingsItem;
// Saved references to System.out and System.err in case need to reset.
private final PrintStream sysOut = System.out;
private final PrintStream sysErr = System.err;
+
+ // Error handling class for the application.
+ private ErrorHandler errorHandler;
// ET connection parameters and state.
- private EtConnectionParameters connectionParameters;
private EtConnection connection;
- private int connectionStatus = ConnectionStatus.DISCONNECTED;
+ //private ConnectionStatus connectionStatus = ConnectionStatus.DISCONNECTED;
// Event processing objects.
private JobControlManager jobManager;
private LCSimEventBuilder eventBuilder;
- private EventProcessingThread eventProcessingThread;
- private Thread sessionThread;
+ private ProcessingChain processingChain;
+ private ProcessingThread processingThread;
+ private Thread sessionWatchdogThread;
// Logging objects.
private static Logger logger;
private Handler logHandler;
private DefaultTableModel logTableModel;
- static final String[] logTableColumns = { "Message", "Date", "Level" };
+ static final String[] logTableColumns = { "Date", "Message", "Level" };
private JTable logTable;
- private Level defaultLogMessageLevel = Level.INFO;
+ private static Level DEFAULT_LOG_LEVEL = Level.INFO;
- // Some default GUI size parameters.
- private final int logTableWidth = 700;
- private final int logTableHeight = 270;
-
- // Format for screenshots. Hard-coded to PNG.
+ // Format for screenshots.
+ // FIXME: This is hard-coded to PNG format.
private static final String screenshotFormat = "png";
// Format of date field for log.
private final SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM-dd-yyyy HH:mm:ss.SSS");
- private static final String LCSIM_FAIL_MESSAGE = "Failed to setup LCSim.";
- // Screen resolution.
- static GraphicsDevice graphicsDevice = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
- private static final int screenWidth = graphicsDevice.getDisplayMode().getWidth();
- private static final int screenHeight = graphicsDevice.getDisplayMode().getHeight();
+ // GUI size settings.
+ private static final int SCREEN_WIDTH = ScreenUtil.getScreenWidth();
+ private static final int SCREEN_HEIGHT = ScreenUtil.getScreenHeight();
+ private final static int LOG_TABLE_WIDTH = 700; // FIXME: Should be set from main panel width.
+ private final static int LOG_TABLE_HEIGHT = 270;
+ private static final int MAIN_FRAME_HEIGHT = ScreenUtil.getScreenHeight() / 2;
+ private static final int MAIN_FRAME_WIDTH = 650;
- // GUI size settings.
- private static final int leftPanelWidth = (int) (screenWidth * 0.33);
- private static final int rightPanelWidth = (int) (screenWidth * 0.40);
- private static final int connectionStatusPanelHeight = 50;
- private static final int connectionStatusPanelWidth = 400;
-
- EventProcessingChain eventProcessing;
-
+ // Default config which can be overridden by command line argument.
+ private static final String DEFAULT_CONFIG_RESOURCE = "/org/hps/monitoring/config/default_config.prop";
+
+ // The application global Configuration object which is the default configuration unless overridden.
+ private Configuration configuration = new Configuration(DEFAULT_CONFIG_RESOURCE);
+
+ // The ConfigurationModel for updating GUI components from the global configuration.
+ private ConfigurationModel configurationModel = new ConfigurationModel();
+
+ // The RunModel for updating the RunPanel.
+ private RunModel runModel = new RunModel();
+
/**
- * Constructor for the monitoring application.
+ * Constructor for the monitoring application.
*/
public MonitoringApplication() {
-
+ }
+
+ /**
+ * Perform all intialization on start up.
+ */
+ public void initialize() {
+
// Create and configure the logger.
setupLogger();
+ // Setup the error handling class.
+ setupErrorHandler();
+
+ // Setup an uncaught exception handler.
+ setupUncaughtExceptionHandler();
+
// Setup the application menus.
- createMenu();
+ createApplicationMenu();
- // Create the GUI panels.
- createPanels();
+ // Create the main GUI panel.
+ createMainPanel();
// Create the log table GUI component.
createLogTable();
+ // Configuration of window for showing plots.
+ createPlotFrame();
+
+ // Create the system status window.
+ createSystemStatusFrame();
+
// Setup AIDA.
setupAida();
- // Configure the application's frame.
- configFrame();
+ // Configure the application's primary JFrame.
+ configApplicationFrame();
+
+ // Create settings dialog window.
+ createSettingsDialog();
- // Configuration of settings window.
+ // Register the ConfigurationModel with sub-components.
+ setupConfigurationModel();
+
+ // Load the current configuration, either the default or from command line arg.
+ loadConfiguration();
+
+ // Log that the application started successfully.
+ log(Level.CONFIG, "Application initialized successfully.");
+ }
+
+ private void setupErrorHandler() {
+ errorHandler = new ErrorHandler(this, logger);
+ }
+
+ private void setupUncaughtExceptionHandler() {
+ Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
+ public void uncaughtException(Thread thread, Throwable exception) {
+ MonitoringApplication.this.errorHandler.setError(exception)
+ .log()
+ .printStackTrace()
+ .showErrorDialog();
+ }
+ });
+ }
+
+ private void createSettingsDialog() {
settingsDialog = new SettingsDialog();
- getJobPanel().addActionListener(this);
+ settingsDialog.getSettingsPanel().addActionListener(this);
+ getJobSettingsPanel().addActionListener(this);
+ }
+
+ private void createPlotFrame() {
+ plotFrame = new PlotFrame();
+ plotFrame.setSize(SCREEN_WIDTH - MAIN_FRAME_WIDTH, SCREEN_HEIGHT);
+ plotFrame.setLocation(
+ (int)(ScreenUtil.getBoundsX(0)) + MAIN_FRAME_WIDTH,
+ plotFrame.getY());
+ }
+
+ private void createSystemStatusFrame() {
+ systemStatusFrame = new SystemStatusFrame();
+ systemStatusFrame.setLocation(
+ (int)ScreenUtil.getBoundsX(0),
+ MAIN_FRAME_HEIGHT);
+ }
+
+ public void setVisible(boolean visible) {
- // Log that the application started successfully.
- log("Application initialized successfully.");
+ super.setVisible(true);
+
+ this.systemStatusFrame.setVisible(true);
+
+ // FIXME: If this is done earlier before app is visible, the GUI will fail to show!
+ this.connectionStatusPanel.setConnectionStatus(ConnectionStatus.DISCONNECTED);
}
/**
- * Setup and configure the AIDA plotting backend.
+ * Configure the AIDA plotting backend.
*/
private void setupAida() {
MonitoringAnalysisFactory.register();
MonitoringAnalysisFactory.configure();
- MonitoringPlotFactory.setRootPane(plotPane);
+ MonitoringPlotFactory.setRootPane(this.plotFrame.getPlotPane());
}
/**
- * Creates all the JPanels for the monitoring GUI.
+ * Create the main panel.
*/
- private void createPanels() {
+ private void createMainPanel() {
+
+ // Main panel setup.
mainPanel = new JPanel();
mainPanel.setLayout(new GridBagLayout());
- createLeftPanel();
- createRightPanel();
- }
- /**
- * Create the left panel.
- */
- private void createLeftPanel() {
+ // This var is used for layout of each sub-component.
+ GridBagConstraints c;
- // Lefthand panel containing the three application tabs.
- leftPanel = new JPanel();
- leftPanel.setMinimumSize(new Dimension(leftPanelWidth, screenHeight - 30));
- leftPanel.setLayout(new GridBagLayout());
-
- GridBagConstraints c;
-
// Event processing buttons.
c = new GridBagConstraints();
c.gridx = 0;
@@ -243,7 +294,7 @@
c.insets = new Insets(10, 0, 0, 10);
buttonsPanel = new EventButtonsPanel();
buttonsPanel.addActionListener(this);
- leftPanel.add(buttonsPanel, c);
+ mainPanel.add(buttonsPanel, c);
// Connection status panel.
c = new GridBagConstraints();
@@ -253,195 +304,140 @@
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(10, 0, 5, 0);
connectionStatusPanel = new ConnectionStatusPanel();
- connectionStatusPanel.setMinimumSize(new Dimension(connectionStatusPanelWidth, connectionStatusPanelHeight));
- leftPanel.add(connectionStatusPanel, c);
+ mainPanel.add(connectionStatusPanel, c);
// Run status panel.
- runPanel = new RunPanel();
+ runPanel = new RunPanel(runModel);
c = new GridBagConstraints();
c.insets = new Insets(5, 0, 5, 0);
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 2;
- leftPanel.add(runPanel, c);
-
- // Layout attributes for the entire left panel.
- c = new GridBagConstraints();
- c.gridx = 0;
- c.gridy = 0;
- c.weightx = 1.0;
- c.weighty = 1.0;
- c.fill = GridBagConstraints.BOTH;
- c.anchor = GridBagConstraints.WEST;
- c.insets = new Insets(0, 5, 0, 0);
- mainPanel.add(leftPanel, c);
+ mainPanel.add(runPanel, c);
}
-
+
/**
- * Create the right panel.
+ * Create the application menu bar and menu items.
*/
- private void createRightPanel() {
+ private void createApplicationMenu() {
- // Create right-hand panel.
- rightPanel = new JPanel();
- rightPanel.setPreferredSize(new Dimension(rightPanelWidth, screenHeight - 30));
- rightPanel.setMinimumSize(new Dimension(rightPanelWidth, screenHeight - 30));
- rightPanel.setLayout(new BorderLayout());
-
- // Create plot pane with empty tabs.
- plotPane = new JTabbedPane();
- rightPanel.add(plotPane, BorderLayout.CENTER);
-
- // Set layout of right panel.
- GridBagConstraints c = new GridBagConstraints();
- c.gridx = 1;
- c.gridy = 0;
- c.fill = GridBagConstraints.BOTH;
- c.anchor = GridBagConstraints.CENTER;
- c.weightx = 1.0;
- c.weighty = 1.0;
- mainPanel.add(rightPanel, c);
- }
-
- /**
- * Create the menu items.
- */
- private void createMenu() {
-
menuBar = new JMenuBar();
JMenu applicationMenu = new JMenu("Application");
applicationMenu.setMnemonic(KeyEvent.VK_A);
- menuBar.add(applicationMenu);
- addMenuItem("Settings...", KeyEvent.VK_S, SHOW_SETTINGS, true, "Monitoring Application settings", applicationMenu);
- addMenuItem("Exit", KeyEvent.VK_X, EXIT, true, "Exit from the application.", applicationMenu);
+ menuBar.add(applicationMenu);
- JMenu connectionMenu = new JMenu("Connection");
- connectionMenu.setMnemonic(KeyEvent.VK_C);
- menuBar.add(connectionMenu);
-
- connectItem = addMenuItem("Connect", KeyEvent.VK_C, CONNECT, true, "Connect to ET system using parameters from connection panel.", connectionMenu);
- disconnectItem = addMenuItem("Disconnect", KeyEvent.VK_D, DISCONNECT, false, "Disconnect from the current ET session.", connectionMenu);
- resetConnectionItem = addMenuItem("Reset Connection Settings", KeyEvent.VK_R, RESET_CONNECTION_SETTINGS, true, "Reset connection settings to defaults.", connectionMenu);
- connectionLoadItem = addMenuItem("Load Connection...", KeyEvent.VK_L, LOAD_CONNECTION, true, "Load connection settings from a saved properties file.", connectionMenu);
- addMenuItem("Save Connection...", KeyEvent.VK_S, SAVE_CONNECTION, true, "Save connection settings to a properties file.", connectionMenu);
+ JMenuItem loadConfigItem = new JMenuItem("Load Settings ...");
+ loadConfigItem.addActionListener(this);
+ loadConfigItem.setMnemonic(KeyEvent.VK_C);
+ loadConfigItem.setActionCommand(SELECT_CONFIG_FILE);
+ loadConfigItem.setToolTipText("Load application settings from a properties file.");
+ applicationMenu.add(loadConfigItem);
- JMenu jobMenu = new JMenu("Job");
- jobMenu.setMnemonic(KeyEvent.VK_J);
- menuBar.add(jobMenu);
-
- addMenuItem("Save Job Settings...", KeyEvent.VK_J, SAVE_JOB_SETTINGS, true, "Save Job Settings configuration to a properties file.", jobMenu);
-
- // FIXME: Rest of these should be converted to use the addMenuItem() helper method ...
+ JMenuItem saveConfigItem = new JMenuItem("Save Settings ...");
+ saveConfigItem.addActionListener(this);
+ saveConfigItem.setMnemonic(KeyEvent.VK_S);
+ saveConfigItem.setActionCommand(SAVE_CONFIG_FILE);
+ saveConfigItem.setToolTipText("Save settings to a properties file.");
+ applicationMenu.add(saveConfigItem);
- loadJobSettingsItem = new JMenuItem("Load Job Settings...");
- loadJobSettingsItem.setMnemonic(KeyEvent.VK_L);
- loadJobSettingsItem.setActionCommand(LOAD_JOB_SETTINGS);
- loadJobSettingsItem.addActionListener(this);
- loadJobSettingsItem.setToolTipText("Load Job Settings from a properties file.");
- jobMenu.add(loadJobSettingsItem);
-
- resetJobSettingsItem = new JMenuItem("Reset Job Settings");
- resetJobSettingsItem.setMnemonic(KeyEvent.VK_R);
- resetJobSettingsItem.setActionCommand(RESET_JOB_SETTINGS);
- resetJobSettingsItem.addActionListener(this);
- resetJobSettingsItem.setToolTipText("Reset Job Settings to the defaults.");
- jobMenu.add(resetJobSettingsItem);
-
- steeringItem = new JMenuItem("Set Steering File...");
- steeringItem.setMnemonic(KeyEvent.VK_S);
- steeringItem.setActionCommand(SET_STEERING_FILE);
- steeringItem.addActionListener(this);
- steeringItem.setToolTipText("Set the job's LCSim steering file.");
- jobMenu.add(steeringItem);
-
- aidaAutoSaveItem = new JMenuItem("AIDA Auto Save File...");
+ JMenuItem settingsItem = new JMenuItem("Show Settings ...");
+ settingsItem.setMnemonic(KeyEvent.VK_P);
+ settingsItem.setActionCommand(SHOW_SETTINGS);
+ settingsItem.addActionListener(this);
+ settingsItem.setToolTipText("Show application settings menu.");
+ applicationMenu.add(settingsItem);
+
+ JMenuItem exitItem = new JMenuItem("Exit");
+ exitItem.setMnemonic(KeyEvent.VK_X);
+ exitItem.setActionCommand(EXIT);
+ exitItem.addActionListener(this);
+ exitItem.setToolTipText("Exit from the application.");
+ applicationMenu.add(exitItem);
+
+ JMenu plotsMenu = new JMenu("Plots");
+ plotsMenu.setMnemonic(KeyEvent.VK_O);
+ menuBar.add(plotsMenu);
+
+ JMenuItem aidaAutoSaveItem = new JMenuItem("Set AIDA Auto Save File ...");
aidaAutoSaveItem.setMnemonic(KeyEvent.VK_A);
aidaAutoSaveItem.setActionCommand(AIDA_AUTO_SAVE);
aidaAutoSaveItem.addActionListener(this);
aidaAutoSaveItem.setToolTipText("Select name of file to auto save AIDA plots at end of job.");
- jobMenu.add(aidaAutoSaveItem);
-
+ plotsMenu.add(aidaAutoSaveItem);
+
savePlotsItem = new JMenuItem("Save Plots to AIDA File...");
savePlotsItem.setMnemonic(KeyEvent.VK_P);
savePlotsItem.setActionCommand(SAVE_PLOTS);
savePlotsItem.addActionListener(this);
savePlotsItem.setEnabled(false);
savePlotsItem.setToolTipText("Save plots from default AIDA tree to an output file.");
- jobMenu.add(savePlotsItem);
+ plotsMenu.add(savePlotsItem);
+
+ JMenu logMenu = new JMenu("Log");
+ logMenu.setMnemonic(KeyEvent.VK_L);
+ menuBar.add(logMenu);
- logItem = new JMenuItem("Redirect to File...");
+ logItem = new JMenuItem("Redirect to File ...");
logItem.setMnemonic(KeyEvent.VK_F);
- logItem.setActionCommand(LOG_TO_FILE);
+ logItem.setActionCommand(CHOOSE_LOG_FILE);
logItem.addActionListener(this);
logItem.setEnabled(true);
- logItem.setToolTipText("Redirect job's standard out and err to a file.");
- jobMenu.add(logItem);
+ logItem.setToolTipText("Redirect std out and err to a file.");
+ logMenu.add(logItem);
terminalItem = new JMenuItem("Redirect to Terminal");
terminalItem.setMnemonic(KeyEvent.VK_T);
terminalItem.setActionCommand(LOG_TO_TERMINAL);
terminalItem.addActionListener(this);
terminalItem.setEnabled(false);
- terminalItem.setToolTipText("Redirect job's standard out and err back to the terminal.");
- jobMenu.add(terminalItem);
-
- JMenuItem screenshotItem = new JMenuItem("Take a screenshot...");
- screenshotItem.setMnemonic(KeyEvent.VK_N);
- screenshotItem.setActionCommand(SCREENSHOT);
- screenshotItem.addActionListener(this);
- screenshotItem.setToolTipText("Save a full screenshot to a " + screenshotFormat + " file.");
- jobMenu.add(screenshotItem);
-
- JMenu logMenu = new JMenu("Log");
- jobMenu.setMnemonic(KeyEvent.VK_L);
- menuBar.add(logMenu);
-
- JMenuItem saveLogItem = new JMenuItem("Save log to file...");
+ terminalItem.setToolTipText("Redirect std out and err back to the terminal.");
+ logMenu.add(terminalItem);
+
+ JMenuItem saveLogItem = new JMenuItem("Save Log Table to File ...");
saveLogItem.setMnemonic(KeyEvent.VK_S);
saveLogItem.setActionCommand(SAVE_LOG_TABLE);
saveLogItem.addActionListener(this);
saveLogItem.setToolTipText("Save the log records to a tab delimited text file.");
logMenu.add(saveLogItem);
- addMenuItem("Clear log", KeyEvent.VK_C, CLEAR_LOG_TABLE, true, "Clear the log table of all messages.", logMenu);
- }
+ JMenuItem clearLogItem = new JMenuItem("Clear Log Table");
+ clearLogItem.addActionListener(this);
+ clearLogItem.setMnemonic(KeyEvent.VK_C);
+ clearLogItem.setActionCommand(CLEAR_LOG_TABLE);
+ clearLogItem.setToolTipText("Clear the log table of all messages.");
+ logMenu.add(clearLogItem);
+
+ JMenu utilMenu = new JMenu("Util");
+ plotsMenu.setMnemonic(KeyEvent.VK_U);
+ menuBar.add(utilMenu);
- /**
- * Add a menu item.
- * @param label The label.
- * @param mnemonic The single letter shortcut.
- * @param cmd The command.
- * @param enabled Whether it is enabled.
- * @param tooltip The tooltip text.
- * @param menu The menu to which it should be added.
- * @return The created menu item.
- */
- private JMenuItem addMenuItem(String label, int mnemonic, String cmd, boolean enabled, String tooltip, JMenu menu) {
- JMenuItem item = new JMenuItem(label);
- item.setMnemonic(mnemonic);
- item.setActionCommand(cmd);
- item.setEnabled(enabled);
- item.setToolTipText(tooltip);
- item.addActionListener(this);
- menu.add(item);
- return item;
+ JMenuItem screenshotItem = new JMenuItem("Take a Screenshot ...");
+ screenshotItem.setMnemonic(KeyEvent.VK_N);
+ screenshotItem.setActionCommand(SCREENSHOT);
+ screenshotItem.addActionListener(this);
+ screenshotItem.setToolTipText("Save a full screenshot to a " + screenshotFormat + " file.");
+ utilMenu.add(screenshotItem);
}
-
+
/**
* Log handler for inserting messages into the log table.
*/
private class MonitoringApplicationLogHandler extends Handler {
/**
- * Puts log messages into the application's log table GUI component.
+ * Puts log messages into the log table.
*/
- public void publish(LogRecord record) {
- Object[] row = new Object[] { /*record.getLoggerName(),*/ // source
- record.getMessage(), // message
- dateFormat.format(new Date(record.getMillis())), // date
- record.getLevel() }; // level
+ public void publish(LogRecord record) {
+ // Add the row to the log table.
+ Object[] row = new Object[] {
+ dateFormat.format(new Date(record.getMillis())),
+ record.getLevel(),
+ record.getMessage() };
logTableModel.insertRow(logTable.getRowCount(), row);
+
+ // Print all messages to System.out so they show up in the terminal or log file output.
+ System.out.println(row[0] + " :: " + row[1] + " :: " + row[2]);
}
public void close() throws SecurityException {
@@ -452,7 +448,7 @@
}
/**
- * Creates the application's log table GUI component, which is a JTable containing messages
+ * Creates the log table component, which is a JTable containing messages
* from the logger.
*/
private void createLogTable() {
@@ -461,6 +457,7 @@
logTableModel = new DefaultTableModel(data, logTableColumns);
logTable = new JTable(logTableModel);
logTable.setEnabled(false);
+ logTable.setAutoCreateRowSorter(true);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
@@ -469,9 +466,9 @@
c.weightx = c.weighty = 1.0;
c.insets = new Insets(0, 0, 5, 3);
JScrollPane logPane = new JScrollPane(logTable);
- logPane.setPreferredSize(new Dimension(logTableWidth, logTableHeight));
- logPane.setMinimumSize(new Dimension(logTableWidth, logTableHeight));
- leftPanel.add(logPane, c);
+ logPane.setPreferredSize(new Dimension(LOG_TABLE_WIDTH, LOG_TABLE_HEIGHT));
+ logPane.setMinimumSize(new Dimension(LOG_TABLE_WIDTH, LOG_TABLE_HEIGHT));
+ mainPanel.add(logPane, c);
}
/**
@@ -484,219 +481,110 @@
logger.addHandler(logHandler);
logger.setLevel(Level.ALL);
}
-
+
/**
- * Load connection settings from a file.
- * @param file The properties file.
- */
- public void loadConnectionSettings(File file) {
- getConnectionPanel().loadPropertiesFile(file);
- }
-
- /**
- * Load job settings from a file.
- * @param file The properties file.
- */
- public void loadJobSettings(File file) {
- try {
- getJobPanel().setJobSettings(new JobSettings(file));
- // Need to check here if System.out and err have been redirected.
- if (getJobPanel().logToFile()) {
- redirectStdOutAndErrToFile(new File(getJobPanel().getLogFileName()));
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Action handler method for the app.
+ * The action handler method for the entire application.
* @param e The event to handle.
*/
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (CONNECT.equals(cmd)) {
- startSession();
+ // Run the start session method on a seperate thread.
+ new Thread() {
+ public void run() {
+ startSession();
+ }
+ }.start();
} else if (DISCONNECT.equals(cmd)) {
- stopSession();
+ // Run the stop session method on a seperate thread.
+ new Thread() {
+ public void run() {
+ stopSession();
+ }
+ }.start();
} else if (SAVE_PLOTS.equals(cmd)) {
savePlots();
- } else if (LOG_TO_FILE.equals(cmd)) {
- logToFile();
+ } else if (CHOOSE_LOG_FILE.equals(cmd)) {
+ chooseLogFile();
} else if (LOG_TO_TERMINAL.equals(cmd)) {
logToTerminal();
} else if (SCREENSHOT.equals(cmd)) {
chooseScreenshot();
} else if (EXIT.equals(cmd)) {
exit();
- } else if (SAVE_CONNECTION.equals(cmd)) {
- saveConnection();
- } else if (LOAD_CONNECTION.equals(cmd)) {
- getConnectionPanel().load();
- } else if (RESET_CONNECTION_SETTINGS.equals(cmd)) {
- getConnectionPanel().reset();
} else if (SAVE_LOG_TABLE.equals(cmd)) {
- saveLogToFile();
+ saveLogTableToFile();
} else if (CLEAR_LOG_TABLE.equals(cmd)) {
- clearLog();
- } else if (SET_EVENT_BUILDER.equals(cmd)) {
- getJobPanel().editEventBuilder();
+ clearLogTable();
} else if (PAUSE.equals(cmd)) {
pauseEventProcessing();
} else if (NEXT.equals(cmd)) {
nextEvent();
} else if (RESUME.equals(cmd)) {
resumeEventProcessing();
- } else if (SET_LOG_LEVEL.equals(cmd)) {
+ } else if (LOG_LEVEL_CHANGED.equals(cmd)) {
setLogLevel();
} else if (AIDA_AUTO_SAVE.equals(cmd)) {
- getJobPanel().chooseAidaAutoSaveFile();
- } else if (SAVE_JOB_SETTINGS.equals(cmd)) {
- saveJobSettings();
- } else if (LOAD_JOB_SETTINGS.equals(cmd)) {
- loadJobSettings();
- } else if (RESET_JOB_SETTINGS.equals(cmd)) {
- resetJobSettings();
- } else if (SET_STEERING_RESOURCE.equals(cmd)) {
- steeringResourceSelected();
- } else if (SET_STEERING_FILE.equals(cmd)) {
- selectSteeringFile();
+ getJobSettingsPanel().chooseAidaAutoSaveFile();
} else if (SHOW_SETTINGS.equals(cmd)) {
showSettingsWindow();
- }
+ } else if (SELECT_CONFIG_FILE.equals(cmd)) {
+ chooseConfigurationFile();
+ } else if (SAVE_CONFIG_FILE.equals(cmd)) {
+ saveConfigurationFile();
+ } else if (LOAD_DEFAULT_CONFIG_FILE.equals(cmd)) {
+ loadDefaultConfigFile();
+ }
}
-
+
/**
* Show the settings window.
*/
private void showSettingsWindow() {
settingsDialog.setVisible(true);
}
-
+
/**
- * This fires when a steering resource file is selected from the combo box. The Job Settings
- * are changed to use a resource type.
+ * Set a new log level for the application. If the new log level is the same as the old one,
+ * a new log level will NOT be set.
*/
- private void steeringResourceSelected() {
- getJobPanel().setSteeringType(getJobPanel().RESOURCE);
- }
-
- /**
- * Save the job settings to a selected file.
- */
- private void saveJobSettings() {
- JFileChooser fc = new JFileChooser();
- fc.setDialogTitle("Save Job Settings");
- fc.setCurrentDirectory(new File("."));
- int r = fc.showSaveDialog(leftPanel);
- if (r == JFileChooser.APPROVE_OPTION) {
- File f = fc.getSelectedFile();
- JobSettings settings = getJobPanel().getJobSettings();
- try {
- settings.save(f);
- log(Level.INFO, "Saved Job Settings to properties file <" + f.getPath() + ">.");
- } catch (IOException e) {
- e.printStackTrace();
- log(Level.SEVERE, "Error saving Job Settings to properties file <" + f.getPath() + ">.");
- showDialog("Error saving Job Settings to properties file.");
- }
+ private void setLogLevel() {
+ Level newLevel = configurationModel.getLogLevel();
+ if (logger.getLevel() != newLevel) {
+ logger.setLevel(newLevel);
+ log(Level.INFO, "Log Level was changed to <" + configurationModel.getLogLevel().toString() + ">");
}
}
/**
- * Load job settings from a selected file.
- */
- private void loadJobSettings() {
- JFileChooser fc = new JFileChooser();
- fc.setDialogTitle("Load Job Settings");
- fc.setCurrentDirectory(new File("."));
- int r = fc.showOpenDialog(leftPanel);
- if (r == JFileChooser.APPROVE_OPTION) {
- File f = fc.getSelectedFile();
- try {
- getJobPanel().setJobSettings(new JobSettings(f));
- log(Level.INFO, "Loaded Job Settings from properties file <" + f.getPath() + ">");
- } catch (IOException e) {
- e.printStackTrace();
- log(Level.SEVERE, "Error loading Job Settings from properties file <" + f.getPath() + ">");
- showDialog("Error loading Job Settings from properties file.");
- }
- }
- }
-
- void saveConnection() {
- JFileChooser fc = new JFileChooser();
- fc.setCurrentDirectory(new File("."));
- int r = fc.showSaveDialog(this);
- if (r == JFileChooser.APPROVE_OPTION) {
- File file = fc.getSelectedFile();
- getConnectionPanel().writePropertiesFile(file);
- log(Level.INFO, "Saved connection properties to <" + file.getPath() + ">");
- }
- }
-
- /**
- * Reset the job settings to the defaults.
- */
- private void resetJobSettings() {
- getJobPanel().resetJobSettings();
- // Redirect System.out and err back to the terminal.
- logToTerminal();
- }
-
- /**
- * Set a new log level for the application and also forward to the event processor.
- */
- private void setLogLevel() {
- Level newLevel = getJobPanel().getLogLevel();
- logger.setLevel(newLevel);
- log(Level.INFO, "Log Level was changed to <" + getJobPanel().getLogLevel().toString() + ">");
- }
-
- /**
* Set the connection status.
* @param status The connection status.
*/
- private void setConnectionStatus(int status) {
- connectionStatus = status;
- connectionStatusPanel.setStatus(status);
- log(Level.FINE, "Connection status changed to <" + ConnectionStatus.toString(status) + ">");
+ private void setConnectionStatus(ConnectionStatus status) {
+ //connectionStatus = status;
+ connectionStatusPanel.setConnectionStatus(status);
+ log(Level.FINE, "Connection status changed to <" + status.name() + ">");
logHandler.flush();
}
/**
- * Get the current connection status.
- * @return The connection status.
+ * Setup the primary <code>JFrame</code> for the application.
*/
- private int getConnectionStatus() {
- return connectionStatus;
- }
-
- /**
- * Pop-up a modal dialog.
- * @param m The message to display in the dialog box.
- */
- private void showDialog(String m) {
- JOptionPane.showMessageDialog(leftPanel, m);
- }
-
- /**
- * Setup the frame to run the application.
- */
- private void configFrame() {
-
+ private void configApplicationFrame() {
mainPanel.setOpaque(true);
setTitle(getApplicationTitle());
setContentPane(mainPanel);
setJMenuBar(menuBar);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
- setPreferredSize(new Dimension(screenWidth, screenHeight));
- setResizable(true);
- pack();
+ setPreferredSize(new Dimension(MAIN_FRAME_WIDTH, MAIN_FRAME_HEIGHT));
+ setMinimumSize(new Dimension(MAIN_FRAME_WIDTH, MAIN_FRAME_HEIGHT));
+ setResizable(true);
+ setLocation((int)ScreenUtil.getBoundsX(0), getY());
+ pack();
}
-
+
/**
- * Save plots to a selected output file.
+ * Save all the plots to a file using a <code>JFileChooser</code>.
*/
private void savePlots() {
JFileChooser fc = new JFileChooser();
@@ -705,35 +593,18 @@
File fileName = fc.getSelectedFile();
try {
AIDA.defaultInstance().saveAs(fileName);
- logger.log(Level.INFO, "Plots saved to <" + fileName + ">");
+ logger.log(Level.INFO, "Plots saved to file <" + fileName + ">");
} catch (IOException e) {
- e.printStackTrace();
- }
+ errorHandler.setError(e)
+ .setMessage("Error saving plots to file.")
+ .printStackTrace()
+ .log()
+ .showErrorDialog();
+ }
[truncated at 1000 lines; 1316 more skipped]
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/MonitoringCommands.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/MonitoringCommands.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,35 +0,0 @@
-package org.hps.monitoring.gui;
-
-/**
- * These strings are used to identify ActionEvents in the MonitoringApplication.
- *
- * @author Jeremy McCormick <[log in to unmask]>
- */
-final class MonitoringCommands {
- static final String AIDA_AUTO_SAVE = "aidaAutoSave";
- static final String CLEAR_LOG_TABLE = "clearLogTable";
- static final String CONNECT = "connect";
- static final String DISCONNECT = "disconnect";
- static final String EDIT_EVENT_REFRESH = "editEventRefresh";
- static final String EXIT = "exit";
- static final String LOAD_CONNECTION = "loadConnection";
- static final String LOAD_JOB_SETTINGS = "loadJobSettings";
- static final String LOG_TO_FILE = "logToFile";
- static final String LOG_TO_TERMINAL = "logToTerminal";
- static final String NEXT = "next";
- static final String PAUSE = "pause";
- static final String RESUME = "resume";
- static final String RESET_CONNECTION_SETTINGS = "resetConnectionSettings";
- static final String RESET_JOB_SETTINGS = "resetJobSettings";
- static final String SAVE_CONNECTION = "saveConnection";
- static final String SAVE_JOB_SETTINGS = "saveJobSettings";
- static final String SAVE_LOG_TABLE = "saveLogTable";
- static final String SAVE_PLOTS = "savePlots";
- static final String SCREENSHOT = "screenshot";
- static final String SET_EVENT_BUILDER = "setEventBuilder";
- static final String SET_EVENT_REFRESH = "setEventRefresh";
- static final String SET_LOG_LEVEL = "setLogLevel";
- static final String SET_STEERING_FILE = "setSteeringFile";
- static final String SET_STEERING_RESOURCE = "setSteeringResource";
- static final String SHOW_SETTINGS = "showSettings";
-}
\ No newline at end of file
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/RunPanel.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/RunPanel.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,7 +1,19 @@
package org.hps.monitoring.gui;
+import static org.hps.monitoring.gui.model.RunModel.DATA_RECEIVED_PROPERTY;
+import static org.hps.monitoring.gui.model.RunModel.ELAPSED_TIME_PROPERTY;
+import static org.hps.monitoring.gui.model.RunModel.END_DATE_PROPERTY;
+import static org.hps.monitoring.gui.model.RunModel.EVENTS_RECEIVED_PROPERTY;
+import static org.hps.monitoring.gui.model.RunModel.EVENT_NUMBER_PROPERTY;
+import static org.hps.monitoring.gui.model.RunModel.RUN_LENGTH_PROPERTY;
+import static org.hps.monitoring.gui.model.RunModel.RUN_NUMBER_PROPERTY;
+import static org.hps.monitoring.gui.model.RunModel.START_DATE_PROPERTY;
+import static org.hps.monitoring.gui.model.RunModel.TOTAL_EVENTS_PROPERTY;
+
import java.awt.Dimension;
import java.awt.FlowLayout;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
@@ -11,29 +23,43 @@
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
-import org.hps.monitoring.record.evio.EvioEventProcessor;
+import org.hps.evio.EventConstants;
+import org.hps.monitoring.gui.model.RunModel;
+import org.hps.record.composite.CompositeRecord;
+import org.hps.record.composite.CompositeProcessor;
import org.jlab.coda.jevio.EvioEvent;
/**
* Dashboard for displaying information about the current run.
* @author Jeremy McCormick <[log in to unmask]>
*/
-public class RunPanel extends JPanel {
+public class RunPanel extends JPanel implements PropertyChangeListener {
FieldPanel runNumberField = new FieldPanel("Run Number", "", 10, false);
- DatePanel startDateField = new DatePanel("Run Start", "", 20, false);
- DatePanel endDateField = new DatePanel("Run End", "", 20, false);
+ DatePanel startDateField = new DatePanel("Run Start", "", 16, false);
+ DatePanel endDateField = new DatePanel("Run End", "", 16, false);
FieldPanel lengthField = new FieldPanel("Run Length [sec]", "", 12, false);
FieldPanel totalEventsField = new FieldPanel("Total Events in Run", "", 14, false);
- FieldPanel elapsedTimeField = new FieldPanel("Elapsed Time [sec]", "", 14, false);;
+ FieldPanel elapsedTimeField = new FieldPanel("Elapsed Time [sec]", "", 14, false);
FieldPanel eventsReceivedField = new FieldPanel("Events Received", "", 14, false);
FieldPanel dataReceivedField = new FieldPanel("Data Received [bytes]", "", 14, false);
+ FieldPanel eventNumberField = new FieldPanel("Event Number", "", 14, false);
+
+ Timer timer;
+ long jobStartMillis;
+
+ RunModel model;
- RunPanel() {
+ RunPanel(RunModel model) {
+ this.model = model;
+ this.model.addPropertyChangeListener(this);
+
setLayout(new FlowLayout(FlowLayout.LEFT));
- TitledBorder titledBorder = BorderFactory.createTitledBorder(
- BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Run Summary");
- setBorder(titledBorder);
+
+ TitledBorder titledBorder = BorderFactory.createTitledBorder(
+ BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Run Summary");
+ setBorder(titledBorder);
+
add(runNumberField);
add(startDateField);
add(endDateField);
@@ -42,79 +68,114 @@
add(elapsedTimeField);
add(eventsReceivedField);
add(dataReceivedField);
+ add(eventNumberField);
+
this.setMinimumSize(new Dimension(0, 190));
}
+
+ void startJobTimer() {
+ timer = new Timer("JobTimer");
+ jobStartMillis = System.currentTimeMillis();
+ TimerTask updateTimeTask = new TimerTask() {
+ public void run() {
+ final int elapsedTime = (int)((System.currentTimeMillis() - jobStartMillis) / 1000);
+ model.setElapsedTime(elapsedTime);
+ }
+ };
+ timer.scheduleAtFixedRate(updateTimeTask, 0, 1000);
+ }
- /**
- * An <tt>EvioEventProcessor</tt> for updating the <tt>RunPanel</tt>
- * by processing EVIO events.
- */
- class RunPanelUpdater extends EvioEventProcessor {
-
- long startMillis;
- long endMillis;
- int eventsReceived;
- long totalBytes;
- Timer timer;
- long jobStartMillis;
-
+ void stopRunTimer() {
+ timer.cancel();
+ timer.purge();
+ }
+
+ class RunModelUpdater extends CompositeProcessor {
+
+ @Override
public void startJob() {
- eventsReceived = 0;
- runNumberField.setValue("");
- startDateField.setValue("");
- endDateField.setValue("");
- lengthField.setValue("");
- totalEventsField.setValue("0");
-
- timer = new Timer("UpdateTime");
- jobStartMillis = System.currentTimeMillis();
- TimerTask updateTimeTask = new TimerTask() {
- public void run() {
- final long elapsedTime = (System.currentTimeMillis() - jobStartMillis) / 1000;
- elapsedTimeField.setValue(elapsedTime);
- }
- };
- timer.scheduleAtFixedRate(updateTimeTask, 0, 1000);
+ model.reset();
+ RunPanel.this.startJobTimer();
}
- public void processEvent(EvioEvent event) {
- ++eventsReceived;
- totalBytes += (long)event.getTotalBytes();
- eventsReceivedField.setValue(eventsReceived);
- dataReceivedField.setValue(totalBytes);
+ @Override
+ public void process(CompositeRecord event) {
+ model.incrementEventsReceived();
+ EvioEvent evioEvent = event.getEvioEvent();
+ if (evioEvent != null) {
+ model.addDataReceived((long)evioEvent.getTotalBytes());
+ model.setEventNumber(evioEvent.getEventNumber());
+ if (EventConstants.isPreStartEvent(evioEvent)) {
+ startRun(evioEvent);
+ } else if (EventConstants.isEndEvent(evioEvent)) {
+ endRun(evioEvent);
+ }
+ } else if (event.getLcioEvent() != null) {
+ model.setEventNumber(event.getLcioEvent().getEventNumber());
+ }
}
-
- public void startRun(EvioEvent event) {
-
- // Get start of run data.
- int[] data = event.getIntData();
+
+ private void endRun(EvioEvent evioEvent) {
+ // Get end run data.
+ int[] data = evioEvent.getIntData();
int seconds = data[0];
- int runNumber = data[1];
- startMillis = ((long) seconds) * 1000;
+ int eventCount = data[2];
+ long endMillis = ((long) seconds) * 1000;
// Update the GUI.
- runNumberField.setValue(runNumber);
- startDateField.setValue(new Date(startMillis));
+ model.setEndDate(new Date(endMillis));
+ model.computeRunLength();
+ model.setTotalEvents(eventCount);
}
- public void endRun(EvioEvent event) {
-
- // Get end run data.
- int[] data = event.getIntData();
+ private void startRun(EvioEvent evioEvent) {
+ // Get start of run data.
+ int[] data = evioEvent.getIntData();
int seconds = data[0];
- int eventCount = data[2];
- endMillis = ((long) seconds) * 1000;
- long elapsedMillis = endMillis - startMillis;
- long elapsedSeconds = (long)((double)elapsedMillis / 1000.);
+ int runNumber = data[1];
+ long startMillis = ((long) seconds) * 1000;
// Update the GUI.
- endDateField.setValue(new Date(endMillis));
- totalEventsField.setValue(eventCount);
- lengthField.setValue(elapsedSeconds);
+ model.setRunNumber(runNumber);
+ model.setStartDate(new Date(startMillis));
}
-
+
+ @Override
public void endJob() {
- timer.cancel();
+ RunPanel.this.stopRunTimer();
+ }
+ }
+
+ /**
+ * Update the GUI from changes in the underlying RunModel object.
+ */
+ @Override
+ public void propertyChange(PropertyChangeEvent evt) {
+ Object value = evt.getNewValue();
+ if (RUN_NUMBER_PROPERTY.equals(evt.getPropertyName())) {
+ this.runNumberField.setValue((Integer) value);
+ } else if (START_DATE_PROPERTY.equals(evt.getPropertyName())) {
+ if (value != null)
+ this.startDateField.setValue((Date) value);
+ else
+ this.startDateField.setValue("");
+ } else if (END_DATE_PROPERTY.equals(evt.getPropertyName())) {
+ if (value != null)
+ this.endDateField.setValue((Date) value);
+ else
+ this.endDateField.setValue("");
+ } else if (RUN_LENGTH_PROPERTY.equals(evt.getPropertyName())) {
+ this.lengthField.setValue((Integer) value);
+ } else if (TOTAL_EVENTS_PROPERTY.equals(evt.getPropertyName())) {
+ this.totalEventsField.setValue((Integer) value);
+ } else if (EVENTS_RECEIVED_PROPERTY.equals(evt.getPropertyName())) {
+ this.eventsReceivedField.setValue((Integer) value);
+ } else if (ELAPSED_TIME_PROPERTY.equals(evt.getPropertyName())) {
+ this.elapsedTimeField.setValue((Integer) value);
+ } else if (DATA_RECEIVED_PROPERTY.equals(evt.getPropertyName())) {
+ this.dataReceivedField.setValue((Long) value);
+ } else if (EVENT_NUMBER_PROPERTY.equals(evt.getPropertyName())) {
+ this.eventNumberField.setValue((Integer) value);
}
}
}
\ No newline at end of file
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/SettingsDialog.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/SettingsDialog.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -6,10 +6,10 @@
import javax.swing.JDialog;
/**
- * The modal dialog for entering settings.
- * @author Jeremy McCormick <[log in to unmask]>
+ * The modal dialog for entering settings. It contains a <code>JPanel</code>
+ * with the different settings sub-tabs.
*/
-public class SettingsDialog extends JDialog {
+class SettingsDialog extends JDialog {
final SettingsPanel settingsPanel = new SettingsPanel(this);
@@ -18,14 +18,12 @@
setTitle("Settings");
setContentPane(settingsPanel);
setResizable(false);
- setDefaultCloseOperation(HIDE_ON_CLOSE);
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
setModalityType(ModalityType.APPLICATION_MODAL);
pack();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
- settingsPanel.revert();
setVisible(false);
}
});
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/SettingsPanel.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/gui/SettingsPanel.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -13,20 +13,22 @@
import javax.swing.JTabbedPane;
/**
- * The container for the job and connection settings.
- * @author Jeremy McCormick <[log in to unmask]>
+ * The container component with the tabs that have job and connection settings.
*/
-public class SettingsPanel extends JPanel implements ActionListener {
+class SettingsPanel extends JPanel implements ActionListener {
JTabbedPane tabs;
- JobPanel jobPanel = new JobPanel();
- ConnectionPanel connectionPanel = new ConnectionPanel();
- static final String okayCommand = "SETTINGS_OKAY";
- static final String cancelCommand = "SETTINGS_CANCEL";
- JDialog parent;
+ JobSettingsPanel jobPanel = new JobSettingsPanel();
+ ConnectionSettingsPanel connectionPanel = new ConnectionSettingsPanel();
+ DataSourcePanel dataSourcePanel = new DataSourcePanel();
+ static final String OKAY_COMMAND = "settingsOkay";
- SettingsPanel(JDialog parent) {
+ JButton defaultsButton;
+
+ JDialog parent;
+ SettingsPanel(JDialog parent) {
+
this.parent = parent;
this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
@@ -34,57 +36,52 @@
tabs = new JTabbedPane();
tabs.addTab("Connection Settings", connectionPanel);
tabs.addTab("Job Settings", jobPanel);
+ tabs.addTab("Data Source", dataSourcePanel);
add(tabs);
JButton okayButton = new JButton("Okay");
- okayButton.setActionCommand(okayCommand);
+ okayButton.setActionCommand(OKAY_COMMAND);
okayButton.addActionListener(this);
-
- JButton cancelButton = new JButton("Cancel");
- cancelButton.setActionCommand(cancelCommand);
- cancelButton.addActionListener(this);
+
+ defaultsButton = new JButton("Defaults");
+ defaultsButton.setActionCommand(Commands.LOAD_DEFAULT_CONFIG_FILE);
+ defaultsButton.addActionListener(this);
add(Box.createRigidArea(new Dimension(1,5)));
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(okayButton);
- buttonsPanel.add(cancelButton);
+ buttonsPanel.add(defaultsButton);
buttonsPanel.setLayout(new FlowLayout());
add(buttonsPanel);
add(Box.createRigidArea(new Dimension(1,5)));
}
-
- ConnectionPanel getConnectionPanel() {
+
+ ConnectionSettingsPanel getConnectionPanel() {
return connectionPanel;
}
- JobPanel getJobPanel() {
+ JobSettingsPanel getJobSettingsPanel() {
return jobPanel;
}
- /**
- * Caches the object for the settings based on current GUI values.
- */
- void cache() {
- connectionPanel.cache();
- jobPanel.cache();
+ DataSourcePanel getDataSourcePanel() {
+ return dataSourcePanel;
}
+
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ if (e.getActionCommand().equals(OKAY_COMMAND)) {
+ parent.setVisible(false);
+ }
+ }
/**
- * Revert the settings to their unedited values.
+ * This method is used to register a listener so that the Monitoring Application
+ * can reset to the default configuration when the "Defaults" button is pushed from
+ * the settings panel.
+ * @param listener
*/
- void revert() {
- connectionPanel.revert();
- jobPanel.revert();
+ void addActionListener(ActionListener listener) {
+ defaultsButton.addActionListener(listener);
}
-
- @Override
- public void actionPerformed(ActionEvent e) {
- if (e.getActionCommand().equals(okayCommand)) {
- cache();
- parent.setVisible(false);
- } else if (e.getActionCommand().equals(cancelCommand)) {
- revert();
- parent.setVisible(false);
- }
- }
}
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/plotting
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/plotting/MonitoringAnalysisFactory.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/plotting/MonitoringAnalysisFactory.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -9,14 +9,11 @@
/**
* This class implements the AIDA <code>IAnalysisFactory</code> for the monitoring application,
- * so that plots are automatically rendered into its tabs. Its primary function is overriding
- * {@link #createPlotterFactory()} and {@link #createPlotterFactory(String)} to return a custom
- * <code>IPlotterFactory</code> object.
- *
- * @author Jeremy McCormick <[log in to unmask]>
- * @version $Id: MonitoringAnalysisFactory.java,v 1.4 2013/12/10 07:36:40 jeremy Exp $
+ * which puts plots into a series of tabs. Each <code>IPlotter</code> has its own tab where
+ * its regions are shown. This class overrides {@link #createPlotterFactory()} and
+ * {@link #createPlotterFactory(String)} to return a custom <code>IPlotterFactory</code> object
+ * that implements this behavior.
*/
-// FIXME: Move to plotting package.
public class MonitoringAnalysisFactory extends AnalysisFactory {
public MonitoringAnalysisFactory() {
@@ -30,6 +27,9 @@
System.setProperty("hep.aida.IAnalysisFactory", MonitoringAnalysisFactory.class.getName());
}
+ /**
+ * Do some JFreeChart related configuration.
+ */
public static void configure() {
ChartFactory.setChartTheme(new DefaultChartTheme());
XYBarRenderer.setDefaultShadowsVisible(false);
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/plotting
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/plotting/MonitoringPlotFactory.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/plotting/MonitoringPlotFactory.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -14,25 +14,22 @@
import org.jfree.chart.JFreeChart;
/**
- * This class implements an AIDA IPlotterFactory for the monitoring application.
+ * This class implements an AIDA <code>IPlotterFactory</code> for the monitoring application.
* It extends the JFree plotter by putting plots into tabs. Each plotter factory
* is given its own top-level tab in a root tabbed pane, under which are separate tabs
* for each plotter. The root pane is static and shared across all plotter factories.
- * It is set externally by the MonitoringApplication before any calls to AIDA are made
- * from Drivers.
- * @author Jeremy McCormick <[log in to unmask]>
- * @version $Id: MonitoringPlotFactory.java,v 1.6 2013/12/10 07:36:40 jeremy Exp $
+ * The top level component is set externally by the MonitoringApplication before any calls
+ * to AIDA are made from Drivers.
*/
-// FIXME: Move to plotting package.
public class MonitoringPlotFactory extends PlotterFactory {
- /* The name of the factory which will be used in naming tabs in the monitoring app. */
+ // The name of the factory which will be used in naming tabs in the monitoring app.
String name = null;
- /* The GUI tabs for this factory's plots. */
+ // The GUI tabs for this factory's plots.
private JTabbedPane tabs = new JTabbedPane();
- /* Root pane where this factory's top-level tab will be inserted. */
+ // Root pane where this factory's top-level tab will be inserted.
private static JTabbedPane rootPane = null;
/**
@@ -41,10 +38,10 @@
MonitoringPlotFactory() {
super();
- /* Enable embedded mode. */
+ // Enable embedded mode.
setEmbedded(true);
- /* Setup the root pane by adding a tab for this factory. */
+ // Setup the root pane by adding an (unlabeled!) tab for this factory.
setupRootPane(" ");
}
@@ -62,7 +59,7 @@
}
private void setupRootPane(String name) {
- // FIXME: hack
+ // FIXME: Hack to disregard call from an AIDA related class.
if (!(new RuntimeException()).getStackTrace()[2].getClassName()
.equals("hep.aida.ref.plotter.style.registry.StyleStoreXMLReader")) {
rootPane.addTab(name, tabs);
@@ -111,7 +108,7 @@
}
/**
- * Create a strip chart with a pure JFreeChart implementation.
+ * Create a strip chart using a JFreeChart implementation.
* It will be automatically updated from a {@link StripChartUpdater}.
* Similar to AIDA plots, the chart will be given a sub-tab in the tab
* of this factory.
@@ -130,6 +127,15 @@
return updater;
}
+ /**
+ * Create a strip chart which must be updated manually.
+ * @param title The title of the chart.
+ * @param yAxisLabel The y axis label.
+ * @param maxAge The maximum age of items to keep.
+ * @param maxCount The maximum count of items.
+ * @param rangeSize The size of the data range.
+ * @return The strip chart as a <code>JFreeChart</code>.
+ */
public JFreeChart createStripChart(String title, String yAxisLabel, int maxAge, int maxCount, int rangeSize) {
JFreeChart stripChart = StripChartBuilder.createTimeSeriesChart(title, yAxisLabel, maxAge, maxCount, rangeSize);
stripChart.getLegend().setVisible(false); /* Legend turned off for now. */
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/plotting
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/plotting/StripChartBuilder.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/plotting/StripChartBuilder.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -11,13 +11,16 @@
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
+/**
+ * Utility methods for building strip charts using JFreeChart backend.
+ */
public final class StripChartBuilder {
private StripChartBuilder() {
}
/**
- * This is appropriate for a strip chart that will be updated at fixed intervals on a timer.
+ * This creates a strip chart that will be updated at fixed intervals from a timer.
* @param title
* @param yAxisLabel
* @param size
@@ -39,17 +42,17 @@
/**
* This should be used when the time period for updating is variable.
+ *
+ * To update a chart of this type:
+ *
+ * <code>sensorSeries.add(new Minute(new Date()), newData);</code>
+ *
* @param title
* @param yAxisLabel
* @param maxAge
* @param maxCount
* @return
- */
- /*
- To update chart of this type:
- sensorSeries.add(new Minute(new Date()), newData);
- */
- // TODO: test case
+ */
public static JFreeChart createTimeSeriesChart(String title, String yAxisLabel, int maxAge, int maxCount, int rangeSize) {
TimeSeriesCollection dataset = new TimeSeriesCollection();
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/plotting
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/plotting/StripChartUpdater.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/plotting/StripChartUpdater.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -7,8 +7,7 @@
import org.jfree.data.time.DynamicTimeSeriesCollection;
/**
- * A <tt>TimerTask</tt> to update a strip chart at a regular interval.
- * @author Jeremy McCormick <[log in to unmask]>
+ * An abstract <tt>TimerTask</tt> to update a strip chart at a regular interval.
*/
public abstract class StripChartUpdater extends TimerTask {
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/plotting
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/plotting/StripChartUtil.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/plotting/StripChartUtil.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -5,9 +5,9 @@
import org.jfree.data.time.TimeSeriesCollection;
-public class StripChartUtil {
+public final class StripChartUtil {
- private StripChartUtil() {
+ private StripChartUtil() {
}
public static TimeSeries getTimeSeries(JFreeChart chart) {
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/HasSystemStatus.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/HasSystemStatus.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,15 +0,0 @@
-package org.hps.monitoring.subsys;
-
-/**
- * A simple mix-in interface for objects that have {@link SystemStatus}
- * about some monitoring point on a sub-system.
- * @author Jeremy McCormick <[log in to unmask]>
- */
-public interface HasSystemStatus {
-
- /**
- * Get the system status object.
- * @return The system status object.
- */
- SystemStatus getSystemStatus();
-}
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/SystemStatistics.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/SystemStatistics.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -6,8 +6,6 @@
/**
* This is an interface for a set of basic statistics
* about an online event processing system.
- *
- * @author Jeremy McCormick <[log in to unmask]>
*/
public interface SystemStatistics {
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/SystemStatisticsImpl.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/SystemStatisticsImpl.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -11,9 +11,9 @@
/**
* Implementation of {@link SystemStatistics}.
- *
- * @author Jeremy McCormick <[log in to unmask]>
*/
+// FIXME: Rolling averages need to happen over a greater time period like 30 seconds
+// instead of 1 second, because otherwise the statistics don't look right.
public class SystemStatisticsImpl implements SystemStatistics {
long tickLengthMillis = 1000; // default is one second tick
@@ -150,10 +150,11 @@
@Override
public void stop() {
- System.out.println("SystemStatistics.stop");
// Kill the Timer.
- if (timer != null)
+ if (timer != null) {
timer.cancel();
+ timer.purge();
+ }
// Set stop time.
stopTimeMillis = System.currentTimeMillis();
@@ -162,19 +163,19 @@
@Override
public void printSession(PrintStream ps) {
ps.println("session statistics ...");
- ps.println(" getTimeElapsedMillis = " + this.getTimeElapsedMillis());
- ps.println(" getCumulativeEvents = " + this.getCumulativeEvents());
- ps.println(" getAverageEventsPerSecond = " + this.getAverageEventsPerSecond());
- ps.println(" getAverageMegaBytesPerSecond = " + this.getAverageMbPerSecond());
+ ps.println(" timeElapsedMillis = " + this.getTimeElapsedMillis());
+ ps.println(" cumulativeEvents = " + this.getCumulativeEvents());
+ ps.println(" averageEventsPerSecond = " + this.getAverageEventsPerSecond());
+ ps.println(" averageMegaBytesPerSecond = " + this.getAverageMbPerSecond());
}
@Override
public void printTick(PrintStream ps) {
ps.println("tick statistics ...");
- ps.println(" getTickElapsedMillis = " + this.getTickElapsedMillis());
- ps.println(" getEventsSinceTick = " + this.getEventsInTick());
- ps.println(" getBytesSinceTick = " + this.getBytesInTick());
+ ps.println(" tickElapsedMillis = " + this.getTickElapsedMillis());
+ ps.println(" eventsSinceTick = " + this.getEventsInTick());
+ ps.println(" bytesSinceTick = " + this.getBytesInTick());
}
@Override
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/SystemStatus.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/SystemStatus.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,85 +1,52 @@
package org.hps.monitoring.subsys;
+
/**
* The <tt>SystemStatus</tt> describes the state of a system, e.g. whether it is okay
- * or some level of error has occurred. Listeners can be registered, which will
- * be notified whenever the status changes, in order to update a GUI, trip an alarm, etc.
+ * or some level of error has occurred. Listeners can be registered on these objects,
+ * which will be notified whenever the status changes, in order to update a GUI component,
+ * trip an alarm, etc.
*
* There is one <tt>SystemStatus</tt> object for each quantity to be monitored
* on a sub-system. New objects are not created when the status changes. Instead,
* the <tt>StatusCode</tt> is changed with a custom message describing the new state.
- *
- * @author Jeremy McCormick <[log in to unmask]>
+ * Listeners are updated whenever the status is changed. It is up to the notified
+ * object to determine what to do when the state changes.
*/
public interface SystemStatus {
-
+
/**
- * Code that represents the status of the monitoring quantity.
+ * Get the sub-system e.g. "SVT".
+ * @return The assigned sub-system.
*/
- enum StatusCode {
-
- OKAY (0, "okay", "The system appears to be working."),
- UNKNOWN(1, "unknown", "The status is not known."),
- OFFLINE(2, "offline", "The system is currently offline."),
- WARNING(3, "warning", "There is a non-fatal warning."),
- ERROR (4, "error", "A non-fatal but serious error has occurred."),
- ALARM (5, "alarm", "An error has occurred and an alarm should trip."),
- HALT (6, "halt", "The system should be immediately halted.");
-
- int code;
- String name;
- String description;
-
- StatusCode(int code, String name, String description) {
- this.code = code;
- this.name = name;
- this.description = description;
- }
-
- int getRawCode() {
- return code;
- }
-
- String getName() {
- return name;
- }
-
- String getDescription() {
- return description;
- }
- }
+ Subsystem getSubsystem();
/**
- * Get the name of the sub-system e.g. "SVT".
- */
- String getSystemName();
-
- /**
* Get the current status code.
* @return The current status code.
*/
StatusCode getStatusCode();
/**
- * Get the current message.
- * @return The current message
- */
- String getMessage();
-
- /**
* Get the description of the system status.
* This is used to differentiate multiple monitoring points
* on the same sub-system so it could be something like "SVT occupancy rates".
* @return The description of the system status.
*/
String getDescription();
-
+
/**
- * Set the current status code, which will cause the last changed
- * time to be set and the listeners to be notified.
+ * Get the current message.
+ * @return The current message
+ */
+ String getMessage();
+
+ /**
+ * Set the current status code and message, which will cause the last changed
+ * time to be set and the listeners to be notified of the status change.
* @param code The new status code.
*/
- void setStatusCode(StatusCode code, String message);
+ void setStatus(StatusCode code, String message);
/**
* Get the time when the system status last changed.
@@ -88,9 +55,27 @@
long getLastChangedMillis();
/**
- * Add a listener to receive notification when the system
- * status changes.
+ * Add a listener to receive notification when the status changes.
* @param listener The listener object.
*/
void addListener(SystemStatusListener listener);
+
+ /**
+ * Set whether this status is active. Inactive statuses will not be
+ * updated in the GUI. This can be changed "on the fly" in the system status panel.
+ * Listeners will NOT be notified of state changes when active is <code>False</code>.
+ */
+ void setActive(boolean active);
+
+ /**
+ * True if the status is active.
+ * @return True if status is active.
+ */
+ boolean isActive();
+
+ /**
+ * True if the status can be cleared.
+ * @return True if status can be cleared.
+ */
+ boolean isClearable();
}
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/SystemStatusImpl.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/SystemStatusImpl.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -5,25 +5,34 @@
/**
* The implementation of {@link SystemStatus}.
- * @author Jeremy McCormick <[log in to unmask]>
*/
-public class SystemStatusImpl implements SystemStatus {
+public final class SystemStatusImpl implements SystemStatus {
- StatusCode code = SystemStatus.StatusCode.UNKNOWN;
+ StatusCode code = StatusCode.UNKNOWN;
long lastChangedMillis;
String message;
List<SystemStatusListener> listeners = new ArrayList<SystemStatusListener>();
- String systemName = "";
- String description = "";
+ final Subsystem systemName;
+ final String description;
+ boolean active = true;
+ final boolean clearable;
- SystemStatusImpl(String systemName, String description) {
+ /**
+ * Fully qualified constructor.
+ * @param systemName The enum specifiying the system being monitored.
+ * @param description A description of this specific status monitor.
+ * @param clearable True if this status can be cleared.
+ */
+ public SystemStatusImpl(Subsystem systemName, String description, boolean clearable) {
this.systemName = systemName;
this.description = description;
- setCurrentTime();
+ this.clearable = clearable;
+ setLastChangedTime();
+ SystemStatusRegistry.getSystemStatusRegistery().register(this);
}
@Override
- public String getSystemName() {
+ public Subsystem getSubsystem() {
return systemName;
}
@@ -43,11 +52,13 @@
}
@Override
- public void setStatusCode(StatusCode code, String message) {
- this.code = code;
- this.message = message;
- setCurrentTime();
- notifyListeners();
+ public void setStatus(StatusCode code, String message) {
+ if (isActive()) {
+ this.code = code;
+ this.message = message;
+ setLastChangedTime();
+ notifyListeners();
+ }
}
@Override
@@ -59,14 +70,32 @@
public long getLastChangedMillis() {
return lastChangedMillis;
}
-
+
+ /**
+ * Notify listeners of changes to the system status.
+ */
void notifyListeners() {
for (SystemStatusListener listener : listeners) {
listener.statusChanged(this);
}
}
- private void setCurrentTime() {
+ private void setLastChangedTime() {
this.lastChangedMillis = System.currentTimeMillis();
}
+
+ @Override
+ public void setActive(boolean masked) {
+ this.active = masked;
+ }
+
+ @Override
+ public boolean isActive() {
+ return active;
+ }
+
+ @Override
+ public boolean isClearable() {
+ return clearable;
+ }
}
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/SystemStatusListener.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/SystemStatusListener.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -2,9 +2,7 @@
/**
* Interface for receiving changes to {@link SystemStatus} objects,
- * e.g. when a new code is set.
- *
- * @author Jeremy McCormick <[log in to unmask]>
+ * e.g. when a new status is set.
*/
public interface SystemStatusListener {
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/ecal
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/ecal/EcalMonitoringPlots.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/ecal/EcalMonitoringPlots.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,220 +0,0 @@
-package org.hps.monitoring.ecal.plots;
-
-import hep.aida.IHistogram1D;
-import hep.aida.IHistogram2D;
-import hep.aida.IPlotter;
-import hep.aida.IPlotterStyle;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.hps.recon.ecal.HPSEcalCluster;
-import org.hps.util.Redrawable;
-import org.hps.util.Resettable;
-import org.lcsim.event.CalorimeterHit;
-import org.lcsim.event.EventHeader;
-import org.lcsim.event.RawTrackerHit;
-import org.lcsim.event.base.BaseRawCalorimeterHit;
-import org.lcsim.geometry.Detector;
-import org.lcsim.util.Driver;
-import org.lcsim.util.aida.AIDA;
-
-/**
- * The driver <code>EcalMonitoringPlots</code> implements the histogram shown to the user
- * in the first tab of the Monitoring Application, when using the Ecal monitoring lcsim file.
- * It contains only a sub-tab, with 3 histograms.
- * - Hit counts by channel (Histogram2D), Occupancy by channel (Histogram2D), Cluster counts by channel (Histogram2D)
- * Each cluster is associated with the seed crystal.
- *
- * These plots are updated regularly, according to the event refresh rate.
- * @author Andrea Celentano
- *
- */
-
-public class EcalMonitoringPlots extends Driver implements Resettable, Redrawable {
-
- String inputCollection = "EcalReadoutHits";
- String clusterCollection = "EcalClusters";
- AIDA aida = AIDA.defaultInstance();
- IPlotter plotter;
- IHistogram2D hitCountFillPlot;
- IHistogram2D hitCountDrawPlot;
-
- IHistogram2D occupancyDrawPlot;
- ArrayList<IHistogram1D> occupancyPlots;
-
- IHistogram2D clusterCountFillPlot;
- IHistogram2D clusterCountDrawPlot;
- int eventRefreshRate = 1;
- int eventn = 0;
- boolean hide = false;
-
- public EcalMonitoringPlots() {
- }
-
- public void setInputCollection(String inputCollection) {
- this.inputCollection = inputCollection;
- }
-
- public void setClusterCollection(String clusterCollection) {
- this.clusterCollection = clusterCollection;
- }
-
- public void setHide(boolean hide) {
- this.hide = hide;
- }
-
- /**
- * Set the refresh rate for histograms in this driver
- * @param eventRefreshRate: the refresh rate, defined as number of events to accumulate before
- * refreshing the plot
- */
- @Override
- public void setEventRefreshRate(int eventRefreshRate) {
- this.eventRefreshRate = eventRefreshRate;
- }
-
- protected void detectorChanged(Detector detector) {
- System.out.println("EcalMonitoringPlots:: detector changed was called");
- // Setup the plotter.
- plotter = aida.analysisFactory().createPlotterFactory("Ecal Monitoring Plots").create("HPS ECal Monitoring Plots");
- // Setup plots.
- aida.tree().cd("/");
- hitCountDrawPlot = aida.histogram2D(detector.getDetectorName() + " : " + inputCollection + " : Hit Count", 47, -23.5, 23.5, 11, -5.5, 5.5);
- hitCountFillPlot = makeCopy(hitCountDrawPlot);
- occupancyDrawPlot = aida.histogram2D(detector.getDetectorName() + " : " + inputCollection + " : Occupancy", 47, -23.5, 23.5, 11, -5.5, 5.5);
- clusterCountDrawPlot = aida.histogram2D(detector.getDetectorName() + " : " + clusterCollection + " : Cluster Center Count", 47, -23.5, 23.5, 11, -5.5, 5.5);
- clusterCountFillPlot = makeCopy(clusterCountDrawPlot);
-
- occupancyPlots=new ArrayList<IHistogram1D>();
- for (int ii=0;ii<(11*47);ii++){
- int row=EcalMonitoringUtils.getRowFromHistoID(ii);
- int column=EcalMonitoringUtils.getColumnFromHistoID(ii);
- occupancyPlots.add(aida.histogram1D(detector.getDetectorName() + " : " + inputCollection + " : Occupancy : " + (row) + " "+ (column)+ ": "+ii, 101,0,1));
- }
-
-
- // Create the plotter regions.
- plotter.createRegions(2, 2);
- plotter.style().statisticsBoxStyle().setVisible(false);
- IPlotterStyle style = plotter.region(0).style();
- style.setParameter("hist2DStyle", "colorMap");
- style.dataStyle().fillStyle().setParameter("colorMapScheme", "rainbow");
- style.dataStyle().fillStyle().setParameter("showZeroHeightBins",Boolean.FALSE.toString());
- plotter.region(0).plot(hitCountDrawPlot);
- style = plotter.region(1).style();
- style.setParameter("hist2DStyle", "colorMap");
- style.dataStyle().fillStyle().setParameter("colorMapScheme", "rainbow");
- style.dataStyle().fillStyle().setParameter("showZeroHeightBins",Boolean.FALSE.toString());
- plotter.region(1).plot(clusterCountDrawPlot);
- style = plotter.region(2).style();
- style.setParameter("hist2DStyle", "colorMap");
- style.dataStyle().fillStyle().setParameter("colorMapScheme", "rainbow");
- style.dataStyle().fillStyle().setParameter("showZeroHeightBins",Boolean.FALSE.toString());
- //style.zAxisStyle().setParameter("scale", "log");
- plotter.region(2).plot(occupancyDrawPlot);
-
-
- if (!hide) {
- plotter.show();
- }
- }
-
- public void process(EventHeader event) {
- int nhits=0;
- int chits[]=new int[11*47];
- /*if (event.hasCollection(BaseRawCalorimeterHit.class, inputCollection)) {
- List<BaseRawCalorimeterHit> hits = event.get(BaseRawCalorimeterHit.class, inputCollection);
- for (BaseRawCalorimeterHit hit : hits) {
- int column=hit.getIdentifierFieldValue("ix");
- int row=hit.getIdentifierFieldValue("iy");
- int id=EcalMonitoringUtils.getHistoIDFromRowColumn(row, column);
- hitCountFillPlot.fill(column,row);
- chits[id]++;
- nhits++;
- }
- }
- if (event.hasCollection(RawTrackerHit.class, inputCollection)) {
- List<RawTrackerHit> hits = event.get(RawTrackerHit.class, inputCollection);
- for (RawTrackerHit hit : hits) {
- int column=hit.getIdentifierFieldValue("ix");
- int row=hit.getIdentifierFieldValue("iy");
- int id=EcalMonitoringUtils.getHistoIDFromRowColumn(row, column);
- hitCountFillPlot.fill(column,row);
- chits[id]++;
- nhits++;
- }
- }*/
- if (event.hasCollection(CalorimeterHit.class, inputCollection)) {
- List<CalorimeterHit> hits = event.get(CalorimeterHit.class, inputCollection);
- for (CalorimeterHit hit : hits) {
- int column=hit.getIdentifierFieldValue("ix");
- int row=hit.getIdentifierFieldValue("iy");
- int id=EcalMonitoringUtils.getHistoIDFromRowColumn(row, column);
- hitCountFillPlot.fill(column,row);
- chits[id]++;
- nhits++;
- }
- }
-
-
-
-
- if (nhits>0) {
- for (int ii=0;ii<(11*47);ii++){
- occupancyPlots.get(ii).fill(chits[ii]*1./(nhits ));
- }
- }
-
-
- if (event.hasCollection(HPSEcalCluster.class, clusterCollection)) {
- List<HPSEcalCluster> clusters = event.get(HPSEcalCluster.class, clusterCollection);
- for (HPSEcalCluster cluster : clusters) {
- clusterCountFillPlot.fill(cluster.getSeedHit().getIdentifierFieldValue("ix"), cluster.getSeedHit().getIdentifierFieldValue("iy"));
- }
- }
- if (eventRefreshRate > 0 && ++eventn % eventRefreshRate == 0) {
- redraw();
- }
- }
-
- public void endOfData() {
- plotter.hide();
- plotter.destroyRegions();
- }
-
- @Override
- public void reset() {
- hitCountFillPlot.reset();
- hitCountDrawPlot.reset();
- clusterCountFillPlot.reset();
- clusterCountDrawPlot.reset();
-
- occupancyDrawPlot.reset();
- for (int id=0;id<(47*11);id++){
- occupancyPlots.get(id).reset();
- }
- }
-
- @Override
- public void redraw() {
- hitCountDrawPlot.reset();
- hitCountDrawPlot.add(hitCountFillPlot);
- clusterCountDrawPlot.reset();
- clusterCountDrawPlot.add(clusterCountFillPlot);
- occupancyDrawPlot.reset();
- for (int id=0;id<(47*11);id++){
- int row=EcalMonitoringUtils.getRowFromHistoID(id);
- int column=EcalMonitoringUtils.getColumnFromHistoID(id);
- double mean=occupancyPlots.get(id).mean();
- if ((row!=0)&&(column!=0)&&(!EcalMonitoringUtils.isInHole(row, column))) occupancyDrawPlot.fill(column,row,mean);
- }
- }
-
-
-
- private IHistogram2D makeCopy(IHistogram2D hist) {
- return aida.histogram2D(hist.title() + "_copy", hist.xAxis().bins(), hist.xAxis().lowerEdge(), hist.xAxis().upperEdge(), hist.yAxis().bins(), hist.yAxis().lowerEdge(), hist.yAxis().upperEdge());
- }
-}
-
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/ecal
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/ecal/EcalStripChartTestDriver.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/ecal/EcalStripChartTestDriver.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -14,8 +14,7 @@
import org.lcsim.util.aida.AIDA;
/**
- * Proof of principle Driver for plotting a sub-system's data using a strip chart.
- * @author Jeremy McCormick <[log in to unmask]>
+ * Example Driver for plotting a sub-system's data using a strip chart.
*/
public class EcalStripChartTestDriver extends Driver {
@@ -50,10 +49,6 @@
series.add(new Millisecond(new Date()), averageHits);
hits = 0;
events = 0;
- }
-
- //long millis = (long) ((double) event.getTimeStamp() / 1e6);
- //series.addOrUpdate(new Second(new Date(timestamp)), size);
- //series.addOrUpdate(new Millisecond(new Date(millis)), size);
+ }
}
}
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/et
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/et/EtSystemMonitor.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/et/EtSystemMonitor.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,64 +1,64 @@
package org.hps.monitoring.subsys.et;
-import org.hps.monitoring.record.etevent.EtEventProcessor;
+import java.util.Timer;
+import java.util.TimerTask;
+import org.hps.monitoring.subsys.StatusCode;
+import org.hps.monitoring.subsys.Subsystem;
+import org.hps.monitoring.subsys.SystemStatus;
+import org.hps.monitoring.subsys.SystemStatusImpl;
+import org.hps.record.et.EtProcessor;
+import org.jlab.coda.et.EtEvent;
+
/**
- * This is a barebones implementation of an ET system monitor.
- * It does not do much right now but accumulate statistics
- * and set basic system statuses.
- * @author Jeremy McCormick <[log in to unmask]>
+ * This is a class for monitoring the ET system.
*/
-public class EtSystemMonitor extends EtEventProcessor {
- /*
-//implements HasSystemInfo {
-
- //SystemInfo info = new SystemInfoImpl("EtSystem");
- SystemStatistics stats = new SystemStatisticsImpl();
+public final class EtSystemMonitor extends EtProcessor {
+
+ SystemStatus systemStatus;
+ int events = 0;
+ long eventReceivedMillis = 0;
+ long warningIntervalMillis = 1000; /* default of 1 second */
+ Timer timer = new Timer("ET Event Monitor");
- // TEST: strip chart stuff
- JFrame plotFrame;
- JFreeChart stripChart;
- StripChartUpdater updater;
- Timer timer;
+ public EtSystemMonitor() {
+ systemStatus = new SystemStatusImpl(Subsystem.ET, "ET System Monitor", false);
+ systemStatus.setStatus(StatusCode.UNKNOWN, "System is not active yet.");
+ }
- MonitoringPlotFactory plotFactory = (MonitoringPlotFactory) AIDA.defaultInstance().analysisFactory().createPlotterFactory("ET System Monitoring");
+ public void setWarningIntervalMillis(long warningIntervalMillis) {
+ this.warningIntervalMillis = warningIntervalMillis;
+ }
- @Override
public void startJob() {
- stats.start();
- //info.getStatus().setStatus(StatusCode.OKAY, "EtSystemMonitor set okay.");
+ systemStatus.setStatus(StatusCode.OKAY, "ET job started.");
+ TimerTask task = new TimerTask() {
+ long startedMillis = 0;
+ public void run() {
+ if (startedMillis == 0)
+ startedMillis = System.currentTimeMillis();
+ long elapsedMillis = 0;
+ if (eventReceivedMillis == 0)
+ elapsedMillis = System.currentTimeMillis() - startedMillis;
+ else
+ elapsedMillis = System.currentTimeMillis() - eventReceivedMillis;
+ if (elapsedMillis > warningIntervalMillis)
+ systemStatus.setStatus(StatusCode.WARNING, "No ET events received for " + elapsedMillis + " millis.");
+ else
+ systemStatus.setStatus(StatusCode.OKAY, "ET events received.");
+ }
+ };
- // TEST: setup strip chart
- JFreeChart stripChart = plotFactory.createStripChart("Average Event Rate", "Event Count", 100);
- updater = new AverageEventRateUpdater();
- updater.setChart(stripChart);
- timer = updater.start();
+ timer.schedule(task, 0, 1000);
}
+
+ public void process(EtEvent event) {
+ eventReceivedMillis = System.currentTimeMillis();
+ }
- @Override
- public void processEvent(EtEvent event) {
- stats.update(event.getLength());
- //info.getStatistics()
- }
-
- @Override
public void endJob() {
- //info.getStatistics().stop();
- stats.stop();
- //info.getStatus().setStatus(StatusCode.OFFLINE, "EtSystemMonitor set offline.");
-
- // TEST: stop timer for updating strip chart
timer.cancel();
timer.purge();
- }
-
- class AverageEventRateUpdater extends StripChartUpdater {
-
- @Override
- public float nextValue() {
- return (float)stats.getAverageEventsPerSecond();
- }
-
- }
- */
+ systemStatus.setStatus(StatusCode.OFFLINE, "ET job ended.");
+ }
}
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/et
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/et/EtSystemStripCharts.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/java/org/hps/monitoring/subsys/et/EtSystemStripCharts.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,16 +1,15 @@
package org.hps.monitoring.subsys.et;
import org.hps.monitoring.plotting.MonitoringPlotFactory;
-import org.hps.monitoring.record.etevent.EtEventProcessor;
import org.hps.monitoring.subsys.SystemStatisticsImpl;
+import org.hps.record.et.EtProcessor;
import org.jlab.coda.et.EtEvent;
import org.lcsim.util.aida.AIDA;
/**
* A basic set of strip charts for monitoring the ET system.
- * @author Jeremy McCormick <[log in to unmask]>
*/
-public class EtSystemStripCharts extends EtEventProcessor {
+public final class EtSystemStripCharts extends EtProcessor {
SystemStatisticsImpl stats = new SystemStatisticsImpl();
MonitoringPlotFactory plotFactory = (MonitoringPlotFactory)
@@ -74,7 +73,7 @@
}
@Override
- public void processEvent(EtEvent event) {
+ public void process(EtEvent event) {
stats.update(event.getLength());
}
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/scripts
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/scripts/evio_file_producer.sh 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/main/scripts/evio_file_producer.sh 2014-09-02 22:27:42 UTC (rev 940)
@@ -14,6 +14,6 @@
# Run the file producer, sending any additional arguments to the command.
#prod="java -classpath $classpath org.hps.evio.EvioFileProducer -e ${eviofile} -f ETBuffer -host localhost -s 10000 -d 100 $@"
-prod="java -classpath $classpath org.hps.monitoring.record.evio.EvioFileProducer -e ${eviofile} -f ETBuffer -host localhost -s 10000 $@"
+prod="java -classpath $classpath org.hps.record.evio.EvioFileProducer -e ${eviofile} -f ETBuffer -host localhost -s 10000 $@"
echo $prod
exec $prod
java/branches/hps-java_HPSJAVA-88/monitoring-app/src/test/java/org/hps/monitoring/subsys/et
--- java/branches/hps-java_HPSJAVA-88/monitoring-app/src/test/java/org/hps/monitoring/subsys/et/EtSystemMonitorTest.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-app/src/test/java/org/hps/monitoring/subsys/et/EtSystemMonitorTest.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,16 +1,7 @@
package org.hps.monitoring.subsys.et;
-import java.io.IOException;
-
import junit.framework.TestCase;
-import org.hps.monitoring.record.etevent.EtEventLoop;
-import org.hps.monitoring.record.etevent.EtEventQueue;
-import org.hps.monitoring.subsys.SystemStatus;
-import org.hps.monitoring.subsys.SystemStatusListener;
-import org.jlab.coda.et.EtEvent;
-import org.jlab.coda.et.EtEventImpl;
-
/**
* Test that the {@link EtSystemMonitor} works.
* @author Jeremy McCormick <[log in to unmask]>
java/branches/hps-java_HPSJAVA-88/monitoring-drivers
--- java/branches/hps-java_HPSJAVA-88/monitoring-drivers/pom.xml 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-drivers/pom.xml 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,28 +1,27 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-
<modelVersion>4.0.0</modelVersion>
<artifactId>hps-monitoring-drivers</artifactId>
<name>monitoring-drivers</name>
<description>Drivers for the MonitoringApplication</description>
-
<parent>
<groupId>org.hps</groupId>
<artifactId>hps-parent</artifactId>
<relativePath>../parent/pom.xml</relativePath>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</parent>
-
<scm>
<url>http://java.freehep.org/svn/repos/hps/list/java/trunk/monitoring-drivers/</url>
<connection>scm:svn:svn://svn.freehep.org/hps/java/trunk/monitoring-drivers/</connection>
<developerConnection>scm:svn:svn://svn.freehep.org/hps/java/trunk/monitoring-drivers/</developerConnection>
</scm>
-
<dependencies>
<dependency>
<groupId>org.hps</groupId>
<artifactId>hps-recon</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.hps</groupId>
+ <artifactId>hps-ecal-event-display</artifactId>
+ </dependency>
</dependencies>
-
</project>
java/branches/hps-java_HPSJAVA-88/monitoring-drivers/src/main/java/org/hps/monitoring/drivers/svt
--- java/branches/hps-java_HPSJAVA-88/monitoring-drivers/src/main/java/org/hps/monitoring/drivers/svt/SVTMonitoringPlots.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-drivers/src/main/java/org/hps/monitoring/drivers/svt/SVTMonitoringPlots.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -6,6 +6,7 @@
import hep.aida.IProfile1D;
import java.util.List;
+import org.apache.commons.math3.special.Gamma;
import org.hps.conditions.deprecated.HPSSVTCalibrationConstants;
import org.hps.conditions.deprecated.SvtUtils;
@@ -150,7 +151,7 @@
int layer = fit.getRawTrackerHit().getIdentifierFieldValue("layer"); // 1-10; axial layers are odd layers; stereo layers are even
int module = fit.getRawTrackerHit().getIdentifierFieldValue("module"); // 0-1; module number is top or bottom
int strip = fit.getRawTrackerHit().getIdentifierFieldValue("strip");
- if (fit.getShapeFitParameters().getChiSq() < 5) {
+ if (fit.getShapeFitParameters().getChiProb() > Gamma.regularizedGammaQ(4, 5)) {
double noise = HPSSVTCalibrationConstants.getNoise((SiSensor) fit.getRawTrackerHit().getDetectorElement(), strip);
if (fit.getAmp() > 4 * noise) {
t0s[module][layer - 1].fill(strip, fit.getT0());
@@ -162,6 +163,6 @@
}
public void endOfData() {
- //plotterFrame.dispose();
+ //plotterFrame.dispose();
}
-}
\ No newline at end of file
+}
java/branches/hps-java_HPSJAVA-88/monitoring-drivers/src/main/java/org/hps/monitoring/drivers/svt
--- java/branches/hps-java_HPSJAVA-88/monitoring-drivers/src/main/java/org/hps/monitoring/drivers/svt/SVTPulseFitPlots.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-drivers/src/main/java/org/hps/monitoring/drivers/svt/SVTPulseFitPlots.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -42,7 +42,7 @@
private String outputPlots = null;
private IHistogram1D[][] t0 = new IHistogram1D[2][10];
private IHistogram1D[][] amp = new IHistogram1D[2][10];
- private IHistogram1D[][] chisq = new IHistogram1D[2][10];
+ private IHistogram1D[][] chiprob = new IHistogram1D[2][10];
private IHistogram2D[][] t0a = new IHistogram2D[2][10];
private IHistogram2D[][] shape = new IHistogram2D[2][10];
// private IHistogram2D shape;
@@ -100,8 +100,8 @@
plotter.region(region).plot(t0[module][layer]);
amp[module][layer] = aida.histogram1D(sensor.getName() + "_amplitude", 50, 0, 2000.0);
plotter2.region(region).plot(amp[module][layer]);
- chisq[module][layer] = aida.histogram1D(sensor.getName() + "_chisq", 100, 0, 10.0);
- plotter3.region(region).plot(chisq[module][layer]);
+ chiprob[module][layer] = aida.histogram1D(sensor.getName() + "_chiprob", 100, 0, 1.0);
+ plotter3.region(region).plot(chiprob[module][layer]);
t0a[module][layer] = aida.histogram2D(sensor.getName() + " A vs. T0", 100, -100, 100, 100, 0, 2000);
plotter4.region(region).plot(t0a[module][layer]);
shape[module][layer] = aida.histogram2D(sensor.getName() + " Shape", 200, -1, 3, 200, -0.5, 2);
@@ -136,7 +136,7 @@
String sensorName = sensor.getName();
aida.histogram1D(sensorName + "_timing").fill(fittedT0);
aida.histogram1D(sensorName + "_amplitude").fill(fittedAmp);
- aida.histogram1D(sensorName + "_chisq").fill(fit.getShapeFitParameters().getChiSq());
+ aida.histogram1D(sensorName + "_chiprob").fill(fit.getShapeFitParameters().getChiProb());
double noise = HPSSVTCalibrationConstants.getNoise(sensor, strip);
double pedestal = HPSSVTCalibrationConstants.getPedestal(sensor, strip);
@@ -167,7 +167,7 @@
for (int layer = 0; layer < 10; layer++) {
t0[module][layer].reset();
amp[module][layer].reset();
- chisq[module][layer].reset();
+ chiprob[module][layer].reset();
t0a[module][layer].reset();
shape[module][layer].reset();
}
java/branches/hps-java_HPSJAVA-88/monitoring-drivers/src/main/java/org/hps/monitoring/drivers/svt
--- java/branches/hps-java_HPSJAVA-88/monitoring-drivers/src/main/java/org/hps/monitoring/drivers/svt/TrackingReconstructionPlots.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-drivers/src/main/java/org/hps/monitoring/drivers/svt/TrackingReconstructionPlots.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -109,7 +109,6 @@
//topFrame.setTitle("Top Tracking Plots");
//bottomFrame = new AIDAFrame();
//bottomFrame.setTitle("Bottom Tracking Plots");
-
sensors = detector.getSubdetector(trackerName).getDetectorElement().findDescendants(SiSensor.class);
IAnalysisFactory fac = aida.analysisFactory();
@@ -130,12 +129,10 @@
plotter.region(1).plot(trkPy);
plotter.region(2).plot(trkPz);
plotter.region(3).plot(trkChi2);
-
+
plotter.show();
// ******************************************************************
-
-
top1 = fac.createPlotterFactory().create("Top Tracking Plots");
top1.setTitle("Top Momentum");
IPlotterStyle stop1 = top1.style();
@@ -153,10 +150,9 @@
top1.region(1).plot(toptrkPy);
top1.region(2).plot(toptrkPz);
top1.region(3).plot(toptrkChi2);
-
+
top1.show();
-
bot1 = fac.createPlotterFactory().create("Bottom Tracking Plots");
bot1.setTitle("Bottom Momentum");
IPlotterStyle sbot1 = bot1.style();
@@ -176,9 +172,8 @@
bot1.region(3).plot(bottrkChi2);
bot1.show();
-
-// ******************************************************************
+// ******************************************************************
IHistogram1D trkd0 = aida.histogram1D("d0 ", 25, -100.0, 100.0);
IHistogram1D trkphi = aida.histogram1D("sinphi ", 25, -0.2, 0.2);
IHistogram1D trkomega = aida.histogram1D("omega ", 25, -0.0025, 0.0025);
@@ -198,7 +193,6 @@
plotter22.region(3).plot(trklam);
plotter22.region(4).plot(trkz0);
-
plotter2 = fac.createPlotterFactory().create("HPS Tracking Plots");
plotter2.setTitle("Track extrapolation");
//plotterFrame.addPlotter(plotter2);
@@ -246,7 +240,6 @@
plotter222.region(2).plot(ampcl);
plotter222.region(5).plot(ampcl2);
-
plotter3 = fac.createPlotterFactory().create("HPS Residual Plots");
plotter3.setTitle("Residuals");
//plotterFrame.addPlotter(plotter3);
@@ -288,7 +281,6 @@
plotter3.region(7).plot(mod4ResY);
plotter3.region(9).plot(mod5ResY);
-
plotter3_1 = fac.createPlotterFactory().create("HPS Residual Plots (Single hit per layer)");
plotter3_1.setTitle("Residuals (Top)");
//plotterFrame.addPlotter(plotter3_1);
@@ -324,7 +316,6 @@
plotter3_1.region(7).plot(mod4ResY_Top);
plotter3_1.region(9).plot(mod5ResY_Top);
-
plotter3_2 = fac.createPlotterFactory().create("HPS Residual Plots (Single strip cluster per layer)");
plotter3_2.setTitle("Residuals (Bottom)");
//plotterFrame.addPlotter(plotter3_2);
@@ -360,9 +351,6 @@
plotter3_2.region(7).plot(mod4ResY_Bottom);
plotter3_2.region(9).plot(mod5ResY_Bottom);
-
-
-
plotter4 = fac.createPlotterFactory().create("HPS Track and ECal Plots");
plotter4.setTitle("Track and ECal Correlations");
//plotterFrame.addPlotter(plotter4);
@@ -381,7 +369,6 @@
// IHistogram1D distX2 = aida.histogram1D("deltaX (Pz>1)", 50, -400, 400);
// IHistogram1D distY2 = aida.histogram1D("deltaY (Pz>1)", 50, -40, 40);
-
IHistogram2D xEcalVsTrk = aida.histogram2D("X ECal Vs Track", 100, -400, 400, 100, -400, 400);
IHistogram2D yEcalVsTrk = aida.histogram2D("Y ECal Vs Track", 100, -100, 100, 100, -100, 100);
@@ -392,10 +379,7 @@
plotter4.region(2).plot(xEcalVsTrk);
plotter4.region(5).plot(yEcalVsTrk);
-
// ******************************************************************
-
-
top2 = fac.createPlotterFactory().create("Top ECal Plots");
top2.setTitle("Top ECal Correlations");
IPlotterStyle stop2 = top2.style();
@@ -411,12 +395,10 @@
IHistogram1D topdistX = aida.histogram1D("Top deltaX", 50, -400, 400);
IHistogram1D topdistY = aida.histogram1D("Top deltaY", 50, -40, 40);
-
IHistogram2D topxEcalVsTrk = aida.histogram2D("Top X ECal Vs Track", 100, -400, 400, 100, -400, 400);
IHistogram2D topyEcalVsTrk = aida.histogram2D("Top Y ECal Vs Track", 100, 0, 100, 100, 0, 100);
-
top2.region(0).plot(topeVsP);
top2.region(3).plot(topeOverP);
top2.region(1).plot(topdistX);
@@ -424,7 +406,6 @@
top2.region(2).plot(topxEcalVsTrk);
top2.region(5).plot(topyEcalVsTrk);
-
bot2 = fac.createPlotterFactory().create("Bottom ECal Plots");
bot2.setTitle("Bottom ECal Correlations");
IPlotterStyle sbot2 = bot2.style();
@@ -440,12 +421,10 @@
IHistogram1D BottomdistX = aida.histogram1D("Bottom deltaX", 50, -400, 400);
IHistogram1D BottomdistY = aida.histogram1D("Bottom deltaY", 50, -40, 40);
-
-
+
IHistogram2D BottomxEcalVsTrk = aida.histogram2D("Bottom X ECal Vs Track", 100, -400, 400, 100, -400, 400);
IHistogram2D BottomyEcalVsTrk = aida.histogram2D("Bottom Y ECal Vs Track", 100, -100, 0, 100, -100, 0);
-
bot2.region(0).plot(BottomeVsP);
bot2.region(3).plot(BottomeOverP);
bot2.region(1).plot(BottomdistX);
@@ -453,9 +432,7 @@
bot2.region(2).plot(BottomxEcalVsTrk);
bot2.region(5).plot(BottomyEcalVsTrk);
-
// ******************************************************************
-
top3 = fac.createPlotterFactory().create("Top ECal Plots");
top3.setTitle("Top ECal More Correlations");
IPlotterStyle stop3 = top3.style();
@@ -465,14 +442,13 @@
stop3.dataStyle().fillStyle().setParameter("colorMapScheme", "rainbow");
top3.createRegions(1, 2);
//topFrame.addPlotter(top3);
-
- IHistogram2D topdistXvsX = aida.histogram2D("Top deltaX vs X", 51,-400,400, 25, -400, 400);
- IHistogram2D topdistYvsY = aida.histogram2D("Top deltaY vs Y", 51,0,100, 25, -40, 40);
-
+
+ IHistogram2D topdistXvsX = aida.histogram2D("Top deltaX vs X", 51, -400, 400, 25, -400, 400);
+ IHistogram2D topdistYvsY = aida.histogram2D("Top deltaY vs Y", 51, 0, 100, 25, -40, 40);
+
top3.region(0).plot(topdistXvsX);
top3.region(1).plot(topdistYvsY);
-
-
+
bot3 = fac.createPlotterFactory().create("Bottom ECal Plots");
bot3.setTitle("Bottom ECal More Correlations");
IPlotterStyle sbot3 = bot3.style();
@@ -482,19 +458,14 @@
sbot3.dataStyle().fillStyle().setParameter("colorMapScheme", "rainbow");
bot3.createRegions(1, 2);
//bottomFrame.addPlotter(bot3);
-
-
- IHistogram2D botdistXvsX = aida.histogram2D("Bottom deltaX vs X", 51,-400,400, 25, -400, 400);
- IHistogram2D botdistYvsY = aida.histogram2D("Bottom deltaY vs Y", 51,-100,0, 25, -40, 40);
-
-
+
+ IHistogram2D botdistXvsX = aida.histogram2D("Bottom deltaX vs X", 51, -400, 400, 25, -400, 400);
+ IHistogram2D botdistYvsY = aida.histogram2D("Bottom deltaY vs Y", 51, -100, 0, 25, -40, 40);
+
bot3.region(0).plot(botdistXvsX);
bot3.region(1).plot(botdistYvsY);
-
-
-// ******************************************************************
-
+// ******************************************************************
plotter5 = fac.createPlotterFactory().create("HPS Hit Positions");
plotter5.setTitle("Hit Positions: Top");
//plotterFrame.addPlotter(plotter5);
@@ -540,11 +511,9 @@
IProfile avgLayersTopPlot = aida.profile1D("Number of Stereo Hits per layer in Top Half", 5, 1, 11);
IProfile avgLayersBottomPlot = aida.profile1D("Number of Stereo Hits per layer in Bottom Half", 5, 1, 11);
-
plotter55.region(0).plot(avgLayersTopPlot);
plotter55.region(1).plot(avgLayersBottomPlot);
-
plotter6 = fac.createPlotterFactory().create("HPS ECAL Hit Positions");
plotter6.setTitle("ECAL Positions");
//plotterFrame.addPlotter(plotter6);
@@ -555,7 +524,6 @@
style6.dataStyle().errorBarStyle().setVisible(false);
plotter6.createRegions(4, 2);
-
IHistogram2D topECal = aida.histogram2D("Top ECal Cluster Position", 50, -400, 400, 10, 0, 100);
IHistogram2D botECal = aida.histogram2D("Bottom ECal Cluster Position", 50, -400, 400, 10, -100, 0);
IHistogram2D topECal1 = aida.histogram2D("Top ECal Cluster Position (>0 tracks)", 50, -400, 400, 10, 0, 100);
@@ -565,7 +533,6 @@
IHistogram2D topECal3 = aida.histogram2D("Top ECal Cluster Position w_E (E>100,>0 tracks)", 50, -400, 400, 10, 0, 100);
IHistogram2D botECal3 = aida.histogram2D("Bottom ECal Cluster Position w_E (E>100,>0 tracks)", 50, -400, 400, 10, -100, 0);
-
plotter6.region(0).plot(topECal);
plotter6.region(1).plot(botECal);
plotter6.region(2).plot(topECal1);
@@ -577,13 +544,10 @@
//plotterFrame.pack();
//plotterFrame.setVisible(true);
-
//topFrame.pack();
//topFrame.setVisible(true);
-
//bottomFrame.pack();
//bottomFrame.setVisible(true);
-
plotter7 = fac.createPlotterFactory().create("HPS ECAL Hit Positions");
plotter7.setTitle("Basic Misc Stuff");
//plotterFrame.addPlotter(plotter7);
@@ -597,7 +561,6 @@
IHistogram2D quadrants = aida.histogram2D("Charge vs Slope", 2, -1, 1, 2, -1, 1);
plotter7.region(0).plot(quadrants);
-
}
public TrackingReconstructionPlots() {
@@ -685,24 +648,26 @@
return;
}
-
-
List<Track> tracks = event.get(Track.class, trackCollectionName);
nTracks.fill(tracks.size());
if (event.hasCollection(HPSEcalCluster.class, ecalCollectionName)) {
List<HPSEcalCluster> clusters = event.get(HPSEcalCluster.class, ecalCollectionName);
for (HPSEcalCluster cluster : clusters) {
//System.out.println("cluser position = ("+cluster.getPosition()[0]+","+cluster.getPosition()[1]+") with energy = "+cluster.getEnergy());
- if (cluster.getPosition()[1] > 0)
+ if (cluster.getPosition()[1] > 0) {
aida.histogram2D("Top ECal Cluster Position").fill(cluster.getPosition()[0], cluster.getPosition()[1]);
- if (cluster.getPosition()[1] < 0)
+ }
+ if (cluster.getPosition()[1] < 0) {
aida.histogram2D("Bottom ECal Cluster Position").fill(cluster.getPosition()[0], cluster.getPosition()[1]);
+ }
if (tracks.size() > 0) {
- if (cluster.getPosition()[1] > 0)
+ if (cluster.getPosition()[1] > 0) {
aida.histogram2D("Top ECal Cluster Position (>0 tracks)").fill(cluster.getPosition()[0], cluster.getPosition()[1]);
- if (cluster.getPosition()[1] < 0)
+ }
+ if (cluster.getPosition()[1] < 0) {
aida.histogram2D("Bottom ECal Cluster Position (>0 tracks)").fill(cluster.getPosition()[0], cluster.getPosition()[1]);
+ }
if (cluster.getEnergy() > 100) {
if (cluster.getPosition()[1] > 0) {
@@ -716,12 +681,9 @@
}
}
-
-
}
}
-
List<SiTrackerHitStrip1D> stripHits = event.get(SiTrackerHitStrip1D.class, "StripClusterer_SiTrackerHitStrip1D");
int stripClustersPerLayerTop[] = getStripClustersPerLayer(stripHits, "up");
//int stripClustersPerLayerBottom[] = getStripClustersPerLayer(stripHits,"down");
@@ -752,13 +714,11 @@
aida.histogram1D("X (mm) @ Z=-150cm").fill(slt.getYZAtX(zAtColl)[0]);
aida.histogram1D("Y (mm) @ Z=-150cm").fill(slt.getYZAtX(zAtColl)[1]);
-
//Straight line after field-region???
//HelixConverter converterEcal = new HelixConverter(zAtDownStrPairSpec);
//StraightLineTrack sltEcal = converterEcal.Convert(ht);
// double sECAL = HelixUtils.PathToXPlane(ht, zEcal, 3000, 1).get(0);
// Hep3Vector posonhelix = HelixUtils.PointOnHelix(ht, sECAL);//position in tracker coordinates!
-
aida.histogram1D("X (mm) @ ECAL").fill(posAtEcal.x());
aida.histogram1D("Y (mm) @ ECAL").fill(posAtEcal.y());
if (trk.getPX() > 1.0) {
@@ -772,12 +732,13 @@
aida.histogram1D("z0 ").fill(trk.getTrackParameter(ParameterName.z0.ordinal()));
int isTop = -1;
- if (trk.getTrackerHits().get(0).getPosition()[2] > 0)
+ if (trk.getTrackerHits().get(0).getPosition()[2] > 0) {
isTop = 0;//make plot look pretty
+ }
int charge = trk.getCharge();
- if (charge > 0)
+ if (charge > 0) {
charge = 0;//make plot look pretty
-// System.out.println("Charge = " + charge + "; isTop = " + isTop);
+ }// System.out.println("Charge = " + charge + "; isTop = " + isTop);
aida.histogram2D("Charge vs Slope").fill(charge, isTop);
if (isTop == 0) {
aida.histogram1D("Top Track Momentum (Px)").fill(trk.getPY());
@@ -801,16 +762,21 @@
double zTr = posonhelix.z();
int layer = htc.Layer();
String modNum = "Module X ";
- if (layer == 1)
+ if (layer == 1) {
modNum = "Module 1 ";
- if (layer == 3)
+ }
+ if (layer == 3) {
modNum = "Module 2 ";
- if (layer == 5)
+ }
+ if (layer == 5) {
modNum = "Module 3 ";
- if (layer == 7)
+ }
+ if (layer == 7) {
modNum = "Module 4 ";
- if (layer == 9)
+ }
+ if (layer == 9) {
modNum = "Module 5 ";
+ }
SymmetricMatrix cov = htc.getCorrectedCovMatrix();
aida.histogram1D(modNum + "Residual X(mm)").fill(htcross.getCorrectedPosition().y() - yTr);//these hits should be rotated track hits already
@@ -836,8 +802,9 @@
// System.out.println("Hit X = " + x + "; Hit Y = " + y);
aida.histogram2D("Layer 1 HTH Position: Top").fill(x - sensorPos.x(), y - sensorPos.y());
}
- if (htc.Layer() == 7)
+ if (htc.Layer() == 7) {
aida.histogram2D("Layer 7 HTH Position: Top").fill(x - sensorPos.x(), y - sensorPos.y());
+ }
} else {
layersBot[htc.Layer() - 1]++;
Hep3Vector sensorPos = ((SiSensor) ((RawTrackerHit) htc.getRawHits().get(0)).getDetectorElement()).getGeometry().getPosition();
@@ -846,36 +813,40 @@
// System.out.println("Hit X = " + x + "; Hit Y = " + y);
aida.histogram2D("Layer 1 HTH Position: Bottom").fill(x - sensorPos.x(), y - sensorPos.y());
}
- if (htc.Layer() == 7)
+ if (htc.Layer() == 7) {
aida.histogram2D("Layer 7 HTH Position: Bottom").fill(x - sensorPos.x(), y - sensorPos.y());
+ }
}
-/*
- List<RawTrackerHit> rawHits = hit.getRawHits();
- for (RawTrackerHit rawHit : rawHits) {
- ChannelConstants constants = HPSSVTCalibrationConstants.getChannelConstants((SiSensor) rawHit.getDetectorElement(), rawHit.getIdentifierFieldValue("strip"));
- HPSShapeFitParameters fit = _shaper.fitShape(rawHit, constants);
- double amp = fit.getAmp();
+ /*
+ List<RawTrackerHit> rawHits = hit.getRawHits();
+ for (RawTrackerHit rawHit : rawHits) {
+ ChannelConstants constants = HPSSVTCalibrationConstants.getChannelConstants((SiSensor) rawHit.getDetectorElement(), rawHit.getIdentifierFieldValue("strip"));
+ HPSShapeFitParameters fit = _shaper.fitShape(rawHit, constants);
+ double amp = fit.getAmp();
- aida.histogram1D("Amp (HitOnTrack)").fill(amp);
- if (trk.getPX() > 1)
- aida.histogram1D("Amp Pz>1000 (HitOnTrack)").fill(amp);
- }
- */
+ aida.histogram1D("Amp (HitOnTrack)").fill(amp);
+ if (trk.getPX() > 1)
+ aida.histogram1D("Amp Pz>1000 (HitOnTrack)").fill(amp);
+ }
+ */
- for(HelicalTrackStrip hts:htcross.getStrips()){
- double clusterSum=0;
- for(RawTrackerHit rawHit: (List<RawTrackerHit>)hts.rawhits()){
- ChannelConstants constants = HPSSVTCalibrationConstants.getChannelConstants((SiSensor) rawHit.getDetectorElement(), rawHit.getIdentifierFieldValue("strip"));
- ShapeFitParameters fit = _shaper.fitShape(rawHit, constants);
- double amp = fit.getAmp();
- clusterSum+=amp;
- aida.histogram1D("Amp (HitOnTrack)").fill(amp);
- if (trk.getPX() > 1)
- aida.histogram1D("Amp Pz>1000 (HitOnTrack)").fill(amp);
- }
- aida.histogram1D("Amp (CluOnTrack)").fill(clusterSum);
- if (trk.getPX() > 1)
- aida.histogram1D("Amp Pz>1000 (CluOnTrack)").fill(clusterSum);
+ for (HelicalTrackStrip hts : htcross.getStrips()) {
+ double clusterSum = 0;
+ for (RawTrackerHit rawHit : (List<RawTrackerHit>) hts.rawhits()) {
+ ChannelConstants constants = HPSSVTCalibrationConstants.getChannelConstants((SiSensor) rawHit.getDetectorElement(), rawHit.getIdentifierFieldValue("strip"));
+ for (ShapeFitParameters fit : _shaper.fitShape(rawHit, constants)) {
+ double amp = fit.getAmp();
+ clusterSum += amp;
+ aida.histogram1D("Amp (HitOnTrack)").fill(amp);
+ if (trk.getPX() > 1) {
+ aida.histogram1D("Amp Pz>1000 (HitOnTrack)").fill(amp);
+ }
+ }
+ }
+ aida.histogram1D("Amp (CluOnTrack)").fill(clusterSum);
+ if (trk.getPX() > 1) {
+ aida.histogram1D("Amp Pz>1000 (CluOnTrack)").fill(clusterSum);
+ }
}
}
List<HPSEcalCluster> clusters = event.get(HPSEcalCluster.class, ecalCollectionName);
@@ -883,9 +854,9 @@
// if (clust != null) {
if (clust != null) {
-
- posAtEcal = TrackUtils.extrapolateTrack(trk,clust.getPosition()[2]);//.positionAtEcal();
+ posAtEcal = TrackUtils.extrapolateTrack(trk, clust.getPosition()[2]);//.positionAtEcal();
+
aida.histogram2D("Energy Vs Momentum").fill(clust.getEnergy(), trk.getPX() * 1000.0);
aida.histogram1D("Energy Over Momentum").fill(clust.getEnergy() / (trk.getPX() * 1000.0));
aida.histogram1D("deltaX").fill(clust.getPosition()[0] - posAtEcal.x());
@@ -902,8 +873,8 @@
aida.histogram1D("Top Energy Over Momentum").fill(clust.getEnergy() / (trk.getPX() * 1000.0));
aida.histogram1D("Top deltaX").fill(clust.getPosition()[0] - posAtEcal.x());
aida.histogram1D("Top deltaY").fill(clust.getPosition()[1] - posAtEcal.y());
- aida.histogram2D("Top deltaX vs X").fill(clust.getPosition()[0],clust.getPosition()[0] - posAtEcal.x());
- aida.histogram2D("Top deltaY vs Y").fill(clust.getPosition()[1],clust.getPosition()[1] - posAtEcal.y());
+ aida.histogram2D("Top deltaX vs X").fill(clust.getPosition()[0], clust.getPosition()[0] - posAtEcal.x());
+ aida.histogram2D("Top deltaY vs Y").fill(clust.getPosition()[1], clust.getPosition()[1] - posAtEcal.y());
aida.histogram2D("Top X ECal Vs Track").fill(clust.getPosition()[0], posAtEcal.x());
aida.histogram2D("Top Y ECal Vs Track").fill(clust.getPosition()[1], posAtEcal.y());
} else {
@@ -911,8 +882,8 @@
aida.histogram1D("Bottom Energy Over Momentum").fill(clust.getEnergy() / (trk.getPX() * 1000.0));
aida.histogram1D("Bottom deltaX").fill(clust.getPosition()[0] - posAtEcal.x());
aida.histogram1D("Bottom deltaY").fill(clust.getPosition()[1] - posAtEcal.y());
- aida.histogram2D("Bottom deltaX vs X").fill(clust.getPosition()[0],clust.getPosition()[0] - posAtEcal.x());
- aida.histogram2D("Bottom deltaY vs Y").fill(clust.getPosition()[1],clust.getPosition()[1] - posAtEcal.y());
+ aida.histogram2D("Bottom deltaX vs X").fill(clust.getPosition()[0], clust.getPosition()[0] - posAtEcal.x());
+ aida.histogram2D("Bottom deltaY vs Y").fill(clust.getPosition()[1], clust.getPosition()[1] - posAtEcal.y());
aida.histogram2D("Bottom X ECal Vs Track").fill(clust.getPosition()[0], posAtEcal.x());
aida.histogram2D("Bottom Y ECal Vs Track").fill(clust.getPosition()[1], posAtEcal.y());
}
@@ -977,15 +948,16 @@
System.out.println("Processing stripCluster " + stripCluster.toString());
}
-
if (!"".equals(side)) {
String s;
- if (stripCluster.getPosition()[1] >= 0.0)
+ if (stripCluster.getPosition()[1] >= 0.0) {
s = "up";
- else
+ } else {
s = "down";
- if (!s.equals(side))
+ }
+ if (!s.equals(side)) {
continue;
+ }
}
name = stripCluster.getSensor().getName();
@@ -1020,12 +992,13 @@
@Override
public void endOfData() {
- if (outputPlots != null)
+ if (outputPlots != null) {
try {
aida.saveAs(outputPlots);
} catch (IOException ex) {
Logger.getLogger(TrackingReconstructionPlots.class.getName()).log(Level.SEVERE, null, ex);
}
+ }
//plotterFrame.dispose();
//topFrame.dispose();
//bottomFrame.dispose();
java/branches/hps-java_HPSJAVA-88/monitoring-drivers/src/main/java/org/hps/monitoring/ecal/plots
--- java/branches/hps-java_HPSJAVA-88/monitoring-drivers/src/main/java/org/hps/monitoring/ecal/plots/EcalDaqPlots.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-drivers/src/main/java/org/hps/monitoring/ecal/plots/EcalDaqPlots.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -18,10 +18,9 @@
import org.lcsim.util.Driver;
import org.lcsim.util.aida.AIDA;
/*Conditions system imports*/
-import org.hps.conditions.DatabaseConditionsManager;
-import org.hps.conditions.DefaultTestSetup;
+//import org.hps.conditions.DatabaseConditionsManager;
import org.hps.conditions.TableConstants;
-
+import org.hps.conditions.config.DefaultTestSetup;
import org.hps.conditions.ecal.EcalChannel;
import org.hps.conditions.ecal.EcalConditions;
import org.hps.conditions.ecal.EcalChannelConstants;
@@ -52,11 +51,11 @@
private EcalConditions conditions;
private EcalChannel.EcalChannelCollection channels;
- private DatabaseConditionsManager manager;
- //private ConditionsManager manager;
+ //private DatabaseConditionsManager manager;
+ private ConditionsManager manager;
public EcalDaqPlots() {
- manager = DatabaseConditionsManager.getInstance();
- //manager = ConditionsManager.defaultInstance();
+ //manager = DatabaseConditionsManager.getInstance();
+ manager = ConditionsManager.defaultInstance();
}
public void setSubdetectorName(String subdetectorName) {
@@ -84,11 +83,11 @@
/*Setup the conditions system*/
- conditions=manager.getConditionsData(EcalConditions.class,TableConstants.ECAL_CONDITIONS);
- channels = conditions.getChannelCollection();
+ //conditions=manager.getConditionsData(EcalConditions.class,TableConstants.ECAL_CONDITIONS);
+ //channels = conditions.getChannelCollection();
// Get the channel information from the database.
- //channels = manager.getCachedConditions(EcalChannel.EcalChannelCollection.class, "ecal_channels").getCachedData();
+ channels = manager.getCachedConditions(EcalChannel.EcalChannelCollection.class, "ecal_channels").getCachedData();
List<EcalCrystal> crystals = detector.getDetectorElement().findDescendants(EcalCrystal.class);
/*I do not want the ECAL Crates and Slots to be hard-coded.
java/branches/hps-java_HPSJAVA-88/monitoring-drivers/src/main/java/org/hps/monitoring/ecal/plots
--- java/branches/hps-java_HPSJAVA-88/monitoring-drivers/src/main/java/org/hps/monitoring/ecal/plots/EcalEventDisplay.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/monitoring-drivers/src/main/java/org/hps/monitoring/ecal/plots/EcalEventDisplay.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -2,6 +2,8 @@
import hep.aida.IHistogram1D;
import hep.aida.IHistogram2D;
+import hep.aida.ICloud1D;
+import hep.aida.ICloud2D;
import hep.aida.IPlotter;
import hep.aida.IPlotterFactory;
@@ -11,16 +13,16 @@
import java.util.ArrayList;
import java.util.List;
-import org.hps.util.Resettable;
-import org.hps.monitoring.ecal.event.Cluster;
-import org.hps.monitoring.ecal.event.EcalHit;
-import org.hps.monitoring.ecal.ui.PEventViewer;
-import org.hps.monitoring.ecal.util.CrystalEvent;
-import org.hps.monitoring.ecal.util.CrystalListener;
+import org.hps.monitoring.ecal.eventdisplay.event.Cluster;
+import org.hps.monitoring.ecal.eventdisplay.event.EcalHit;
+import org.hps.monitoring.ecal.eventdisplay.ui.PEventViewer;
+import org.hps.monitoring.ecal.eventdisplay.util.CrystalEvent;
+import org.hps.monitoring.ecal.eventdisplay.util.CrystalListener;
import org.hps.recon.ecal.ECalUtils;
import org.hps.recon.ecal.HPSEcalCluster;
import org.lcsim.event.CalorimeterHit;
import org.lcsim.event.EventHeader;
+import org.lcsim.event.RawTrackerHit;
import org.lcsim.geometry.Detector;
import org.lcsim.util.Driver;
import org.lcsim.util.aida.AIDA;
@@ -32,16 +34,19 @@
* The implementation is as follows:
* - The event display is opened in a separate window
* - It is updated regularly, according to the event refresh rate
- * - If the user clicks on a crystal, the corresponding energy and time distributions (both Histogram1D) are shown in the last panel of the MonitoringApplicatopn
+ * - If the user clicks on a crystal, the corresponding energy and time distributions (both Histogram1D) are shown in the last panel of the MonitoringApplication,
+ * as well as a 2D histogram (hit time vs hit energy). Finally, if available, the raw waveshape (in mV) is displayed.
+ *
* The single channel plots are created in the <code>EcalHitPlots</code> driver.
* @author Andrea Celentano
* *
*/
-public class EcalEventDisplay extends Driver implements CrystalListener,ActionListener,Resettable {
+public class EcalEventDisplay extends Driver implements CrystalListener, ActionListener {
String inputCollection = "EcalCalHits";
+ String inputCollectionRaw = "EcalReadoutHits";
String clusterCollection = "EcalClusters";
private IPlotter plotter;
private AIDA aida=AIDA.defaultInstance();
@@ -50,16 +55,21 @@
int eventRefreshRate = 1;
int eventn = 0;
int ix,iy,id;
+
+ int[] windowRaw=new int[47*11];//in case we have the raw waveform, this is the window lenght (in samples)
+ boolean[] isFirstRaw=new boolean[47*11];
+
private PEventViewer viewer; //this is the Kyle event viewer.
- IHistogram1D hEnergyDraw,hTimeDraw;
- IHistogram2D hTimeVsEnergyDraw;
-
ArrayList<IHistogram1D> channelEnergyPlot;
ArrayList<IHistogram1D> channelTimePlot;
+ ArrayList<IHistogram1D> channelRawWaveform;
+ // ArrayList<ICloud1D> channelRawWaveform;
ArrayList<IHistogram2D> channelTimeVsEnergyPlot;
-
+
+
+
double maxEch = 2500 * ECalUtils.MeV;
public EcalEventDisplay() {
@@ -74,7 +84,14 @@
this.inputCollection = inputCollection;
}
-
+ public void setInputCollectionRaw(String inputCollectionRaw) {
+ this.inputCollectionRaw = inputCollectionRaw;
+ }
+
+ public void setInputClusterCollection(String inputClusterCollection) {
+ this.clusterCollection = inputClusterCollection;
+ }
+
public void setEventRefreshRate(int eventRefreshRate) {
this.eventRefreshRate = eventRefreshRate;
}
@@ -90,6 +107,8 @@
channelEnergyPlot=new ArrayList<IHistogram1D>();
channelTimePlot=new ArrayList<IHistogram1D>();
+ channelRawWaveform=new ArrayList<IHistogram1D>();
+ //channelRawWaveform=new ArrayList<ICloud1D>();
channelTimeVsEnergyPlot=new ArrayList<IHistogram2D>();
//create the histograms for single channel energy and time distribution.
//these are NOT shown in this plotter, but are used in the event display.
@@ -99,6 +118,13 @@
channelEnergyPlot.add(aida.histogram1D(detector.getDetectorName() + " : " + inputCollection + " : Hit Energy : " + (row) + " "+ (column)+ ": "+ii, 100, 0, maxEch));
channelTimePlot.add(aida.histogram1D(detector.getDetectorName() + " : " + inputCollection + " : Hit Time : " + (row) + " "+ (column)+ ": "+ii, 100, 0, 400));
channelTimeVsEnergyPlot.add(aida.histogram2D(detector.getDetectorName() + " : " + inputCollection + " : Hit Time Vs Energy : " + (row) + " "+ (column)+ ": "+ii, 100, 0, 400,100, 0, maxEch));
+ channelRawWaveform.add(aida.histogram1D(detector.getDetectorName() + " : " + inputCollection + " : Hit Energy : " + (row) + " "+ (column)+ ": "+ii));
+ //the above instruction is a terrible hack, just to fill the arrayList with all the elements. They'll be initialized properly during the event readout,
+ //since we want to account for possibly different raw waveform dimensions!
+ //channelRawWaveform.add(aida.cloud1D(detector.getDetectorName() + " : " + inputCollection + " : Raw Waveform : " + (row) + " "+ (column)+ ": "+ii,1000000000));
+
+ isFirstRaw[ii]=true;
+ windowRaw[ii]=1;
}
id=0;
iy=EcalMonitoringUtils.getRowFromHistoID(id);
@@ -122,16 +148,14 @@
plotter.region(0).plot(channelEnergyPlot.get(0));
plotter.region(1).plot(channelTimePlot.get(0));
plotter.region(2).plot(channelTimeVsEnergyPlot.get(0));
- //plotter.region(1).plot();
- //plotter.region(2).plot();
- //plotter.region(3).plot();
+ plotter.region(3).plot(channelRawWaveform.get(0));
+ plotter.region(3).style().yAxisStyle().setLabel("Amplitude (mV)");
+ plotter.region(3).style().xAxisStyle().setLabel("Time (ns)");
+ plotter.region(3).style().dataStyle().fillStyle().setColor("orange");
+ plotter.region(3).style().dataStyle().markerStyle().setColor("orange");
+ plotter.region(3).style().dataStyle().errorBarStyle().setVisible(false);
- //plotterFrame = new AIDAFrame(); //and not AIDA.defaultInstance();
- //plotterFrame.setVisible(true);
- //plotterFrame.addPlotter(plotter);
-
-
System.out.println("Create the event viewer");
viewer=new PEventViewer();
viewer.addCrystalListener(this);
@@ -146,7 +170,8 @@
@Override
public void endOfData() {
-
+ viewer.setVisible(false);
+ viewer.dispose();
}
@Override
@@ -172,15 +197,14 @@
List<CalorimeterHit> hits = event.get(CalorimeterHit.class, inputCollection);
for (CalorimeterHit hit : hits) {
row=hit.getIdentifierFieldValue("iy");
- column=hit.getIdentifierFieldValue("ix");
- if (do_update) viewer.addHit(new EcalHit(column,row, hit.getRawEnergy()));
+ column=hit.getIdentifierFieldValue("ix");
if ((row!=0)&&(column!=0)){
ii = EcalMonitoringUtils.getHistoIDFromRowColumn(row,column);
- if (hit.getCorrectedEnergy() > 0) { //A.C. > 0 for the 2D plot drawing
+ if (hit.getCorrectedEnergy() > 0) { //A.C. > 0 for the 2D plot drawing
channelEnergyPlot.get(ii).fill(hit.getCorrectedEnergy());
channelTimePlot.get(ii).fill(hit.getTime());
- channelTimeVsEnergyPlot.get(ii).fill(hit.getTime(),hit.getCorrectedEnergy());
-
+ channelTimeVsEnergyPlot.get(ii).fill(hit.getTime(),hit.getCorrectedEnergy());
+ if (do_update) viewer.addHit(new EcalHit(column,row, hit.getCorrectedEnergy()));
}
}
}
@@ -192,7 +216,7 @@
if (do_update){
the_cluster=new Cluster(seedHit.getIdentifierFieldValue("ix"), seedHit.getIdentifierFieldValue("iy"), cluster.getEnergy());
for (CalorimeterHit hit : cluster.getCalorimeterHits()) {
- if (hit.getRawEnergy() != 0)
+ if (hit.getRawEnergy() > 0)
column=hit.getIdentifierFieldValue("ix");
row=hit.getIdentifierFieldValue("iy");
the_cluster.addComponentHit(hit.getIdentifierFieldValue("ix"),hit.getIdentifierFieldValue("iy"));
@@ -202,14 +226,36 @@
}
}
+ //here follows the code for the raw waveform
+ if (event.hasCollection(RawTrackerHit.class, inputCollectionRaw)){
+ List<RawTrackerHit> hits = event.get(RawTrackerHit.class, inputCollectionRaw);
+ for (RawTrackerHit hit : hits) {
+ row=hit.getIdentifierFieldValue("iy");
+ column=hit.getIdentifierFieldValue("ix");
+ if ((row!=0)&&(column!=0)){
+ ii = EcalMonitoringUtils.getHistoIDFromRowColumn(row,column);
+ if (isFirstRaw[ii]){ //at the very first hit we read for this channel, we need to read the window length and save it
+ isFirstRaw[ii]=false;
+ windowRaw[ii]=hit.getADCValues().length;
+ channelRawWaveform.set(ii,aida.histogram1D(detector.getDetectorName() + " : " + inputCollectionRaw + " : Raw Waveform : " + (row) + " "+ (column)+ ": "+ii,windowRaw[ii],-0.5*ECalUtils.ecalReadoutPeriod,(-0.5+windowRaw[ii])*ECalUtils.ecalReadoutPeriod));
+ }
+ if (do_update){
+ channelRawWaveform.get(ii).reset();
+ for (int jj = 0; jj < windowRaw[ii]; jj++) {
+ channelRawWaveform.get(ii).fill(jj*ECalUtils.ecalReadoutPeriod, hit.getADCValues()[jj]*ECalUtils.adcResolution*1000);
+ }
+ }
+ }
+ }
+ }
+
+
if (do_update){
- viewer.updateDisplay();
-
-
+ viewer.updateDisplay();
}
}
-
+ /*
@Override
public void reset(){
for(int ii = 0; ii < (47*11); ii = ii +1){
@@ -218,15 +264,13 @@
channelTimeVsEnergyPlot.get(ii).reset();
}
}
+ */
+
@Override
public void actionPerformed(ActionEvent ae) {
}
-
-
-
-
-
+
@Override
public void crystalActivated(CrystalEvent e){
@@ -259,32 +303,20 @@
iy=(int) ecalPoint.getY(); //raw
id=EcalMonitoringUtils.getHistoIDFromRowColumn(iy,ix);
System.out.println("Crystal event: "+ix+" "+iy+" "+id);
- // plotter.hide();
- //get the new histograms
-
- //clone hEnergyDraw
+
-
plotter.region(0).clear();
plotter.region(0).plot(channelEnergyPlot.get(id));
plotter.region(1).clear();
- plotter.region(1).plot(channelTimePlot.get(id));
-
-
-
- /*
- *
- *
- *
- * hTimeVsEnergyDraw.reset();
-
- plotter.region(2).setTitle(channelTimeVsEnergyPlot.get(id).title());
- hTimeVsEnergyDraw.setTitle(channelTimeVsEnergyPlot.get(id).title());
- hTimeVsEnergyDraw.add(channelTimeVsEnergyPlot.get(id));*/
+ plotter.region(1).plot(channelTimePlot.get(id));
+
plotter.region(2).clear();
plotter.region(2).plot(channelTimeVsEnergyPlot.get(id));
+
+ plotter.region(3).clear();
+ plotter.region(3).plot(channelRawWaveform.get(id));
}
}
java/branches/hps-java_HPSJAVA-88/parent
--- java/branches/hps-java_HPSJAVA-88/parent/pom.xml 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/parent/pom.xml 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,5 +1,4 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<prerequisites>
<maven>3.0</maven>
</prerequisites>
@@ -7,12 +6,12 @@
<groupId>org.hps</groupId>
<artifactId>hps-parent</artifactId>
<packaging>pom</packaging>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
<name>parent</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<org.lcsim.cacheDir>${user.home}</org.lcsim.cacheDir>
- <lcsimVersion>3.0.4-SNAPSHOT</lcsimVersion>
+ <lcsimVersion>3.0.5-SNAPSHOT</lcsimVersion>
</properties>
<scm>
<url>http://java.freehep.org/svn/repos/hps/list/java/trunk/parent/</url>
@@ -78,83 +77,83 @@
<dependency>
<groupId>org.hps</groupId>
<artifactId>hps-util</artifactId>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.hps</groupId>
- <artifactId>hps-jevio</artifactId>
- <version>3.0.2-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>org.hps</groupId>
- <artifactId>hps-et</artifactId>
- <version>3.0.2-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>org.hps</groupId>
<artifactId>hps-detector-data</artifactId>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.hps</groupId>
<artifactId>hps-conditions</artifactId>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.hps</groupId>
<artifactId>hps-ecal-recon</artifactId>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.hps</groupId>
<artifactId>hps-ecal-readout-sim</artifactId>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.hps</groupId>
<artifactId>hps-tracking</artifactId>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.hps</groupId>
<artifactId>hps-evio</artifactId>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.hps</groupId>
<artifactId>hps-recon</artifactId>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.hps</groupId>
<artifactId>hps-analysis</artifactId>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.hps</groupId>
<artifactId>hps-monitoring-drivers</artifactId>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.hps</groupId>
<artifactId>hps-monitoring-app</artifactId>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.hps</groupId>
<artifactId>hps-users</artifactId>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.hps</groupId>
<artifactId>hps-steering-files</artifactId>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.hps</groupId>
<artifactId>hps-distribution</artifactId>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</dependency>
+ <dependency>
+ <groupId>org.hps</groupId>
+ <artifactId>hps-ecal-event-display</artifactId>
+ <version>3.0.3-SNAPSHOT</version>
+ </dependency>
+ <dependency>
+ <groupId>org.hps</groupId>
+ <artifactId>hps-record-util</artifactId>
+ <version>3.0.3-SNAPSHOT</version>
+ </dependency>
</dependencies>
</dependencyManagement>
<reporting>
java/branches/hps-java_HPSJAVA-88/plugin
--- java/branches/hps-java_HPSJAVA-88/plugin/pom.xml 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/plugin/pom.xml 2014-09-02 22:27:42 UTC (rev 940)
@@ -9,7 +9,7 @@
<groupId>org.hps</groupId>
<artifactId>hps-parent</artifactId>
<relativePath>../parent/pom.xml</relativePath>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</parent>
<scm>
java/branches/hps-java_HPSJAVA-88
--- java/branches/hps-java_HPSJAVA-88/pom.xml 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/pom.xml 2014-09-02 22:27:42 UTC (rev 940)
@@ -12,7 +12,7 @@
<groupId>org.hps</groupId>
<artifactId>hps-parent</artifactId>
<relativePath>parent/pom.xml</relativePath>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</parent>
<scm>
@@ -139,7 +139,9 @@
<module>evio</module>
<module>recon</module>
<module>tracking</module>
+ <module>ecal-event-display</module>
<module>monitoring-drivers</module>
+ <module>record-util</module>
<module>monitoring-app</module>
<module>analysis</module>
<module>users</module>
java/branches/hps-java_HPSJAVA-88/recon
--- java/branches/hps-java_HPSJAVA-88/recon/pom.xml 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/recon/pom.xml 2014-09-02 22:27:42 UTC (rev 940)
@@ -10,7 +10,7 @@
<groupId>org.hps</groupId>
<artifactId>hps-parent</artifactId>
<relativePath>../parent/pom.xml</relativePath>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</parent>
<scm>
java/branches/hps-java_HPSJAVA-88/steering-files
--- java/branches/hps-java_HPSJAVA-88/steering-files/pom.xml 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/steering-files/pom.xml 2014-09-02 22:27:42 UTC (rev 940)
@@ -10,7 +10,7 @@
<groupId>org.hps</groupId>
<artifactId>hps-parent</artifactId>
<relativePath>../parent/pom.xml</relativePath>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</parent>
<scm>
java/branches/hps-java_HPSJAVA-88/steering-files/src/main/resources/org/hps/steering/monitoring
--- java/branches/hps-java_HPSJAVA-88/steering-files/src/main/resources/org/hps/steering/monitoring/ECalBasicMonitoring.lcsim 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/steering-files/src/main/resources/org/hps/steering/monitoring/ECalBasicMonitoring.lcsim 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,34 +1,26 @@
<lcsim xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
- xs:noNamespaceSchemaLocation="http://www.lcsim.org/schemas/lcsim/1.0/lcsim.xsd">
-
+ xs:noNamespaceSchemaLocation="http://www.lcsim.org/schemas/lcsim/1.0/lcsim.xsd">
<execute>
<driver name="EventMarkerDriver"/>
<driver name="CalibrationDriver"/>
<driver name="EcalRawConverter"/>
<driver name="EcalClusterer"/>
<driver name="EcalMonitoringPlots"/>
- </execute>
-
+ </execute>
<drivers>
-
<driver name="EventMarkerDriver"
type="org.lcsim.job.EventMarkerDriver">
<eventInterval>1</eventInterval>
</driver>
-
<driver name="CalibrationDriver" type="org.hps.conditions.deprecated.CalibrationDriver"/>
-
<driver name="EcalRawConverter" type="org.hps.recon.ecal.EcalRawConverterDriver">
<applyBadCrystalMap>false</applyBadCrystalMap>
<use2014Gain>false</use2014Gain>
- </driver>
-
+ </driver>
<driver name="EcalClusterer" type="org.hps.recon.ecal.EcalClusterer">
<ecalName>Ecal</ecalName>
<ecalCollectionName>EcalCalHits</ecalCollectionName>
- </driver>
-
- <driver name="EcalMonitoringPlots" type="org.hps.monitoring.drivers.ecal.BasicMonitoringPlotsDriver"/>
-
+ </driver>
+ <driver name="EcalMonitoringPlots" type="org.hps.monitoring.ecal.plots.BasicMonitoringPlotsDriver"/>
</drivers>
</lcsim>
java/branches/hps-java_HPSJAVA-88/steering-files/src/main/resources/org/hps/steering/monitoring
--- java/branches/hps-java_HPSJAVA-88/steering-files/src/main/resources/org/hps/steering/monitoring/EcalMonitoringFinal.lcsim 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/steering-files/src/main/resources/org/hps/steering/monitoring/EcalMonitoringFinal.lcsim 2014-09-02 22:27:42 UTC (rev 940)
@@ -57,7 +57,7 @@
</driver>
<driver name="EcalMonitoringPlots" type="org.hps.monitoring.ecal.plots.EcalMonitoringPlots">
- <inputCollection>EcalCalHits</inputCollection>
+ <inputCollection>EcalCalHits</inputCollection>
<eventRefreshRate>100</eventRefreshRate>
</driver>
@@ -77,6 +77,8 @@
<driver name="EcalEventDisplay" type="org.hps.monitoring.ecal.plots.EcalEventDisplay">
<inputCollection>EcalCalHits</inputCollection>
+ <inputCollectionRaw>EcalReadoutHits</inputCollectionRaw>
+ <inputClusterCollection>EcalClusters</inputClusterCollection>
<maxEch>2.0</maxEch>
<eventRefreshRate>100</eventRefreshRate>
</driver>
java/branches/hps-java_HPSJAVA-88/steering-files/src/main/resources/org/hps/steering/recon
--- java/branches/hps-java_HPSJAVA-88/steering-files/src/main/resources/org/hps/steering/recon/TestRunOfflineRecon.lcsim 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/steering-files/src/main/resources/org/hps/steering/recon/TestRunOfflineRecon.lcsim 2014-09-02 22:27:42 UTC (rev 940)
@@ -7,7 +7,8 @@
xs:noNamespaceSchemaLocation="http://www.lcsim.org/schemas/lcsim/1.0/lcsim.xsd">
<execute>
<driver name="EventMarkerDriver"/>
- <driver name="CalibrationDriver"/>
+ <driver name="ConditionsDriver" />
+ <!-- <driver name="CalibrationDriver"/> -->
<driver name="RawTrackerHitSensorSetup"/>
<driver name="BadChannelFilter" />
<driver name="RawTrackerHitFitterDriver" />
@@ -22,9 +23,10 @@
<driver name="CleanupDriver"/>
</execute>
<drivers>
- <driver name="CalibrationDriver" type="org.hps.conditions.deprecated.CalibrationDriver">
+ <driver name="ConditionsDriver" type="org.hps.conditions.ConditionsDriver" />
+ <!-- <driver name="CalibrationDriver" type="org.hps.conditions.deprecated.CalibrationDriver">
<runNumber>${runNumber}</runNumber>
- </driver>
+ </driver> -->
<driver name="EventMarkerDriver" type="org.lcsim.job.EventMarkerDriver">
<eventInterval>1000</eventInterval>
</driver>
java/branches/hps-java_HPSJAVA-88/steering-files/src/main/resources/org/hps/steering/users/mgraham
--- java/branches/hps-java_HPSJAVA-88/steering-files/src/main/resources/org/hps/steering/users/mgraham/DataQualityMonitor.lcsim 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/steering-files/src/main/resources/org/hps/steering/users/mgraham/DataQualityMonitor.lcsim 2014-09-02 22:27:42 UTC (rev 940)
@@ -7,24 +7,24 @@
<execute>
<driver name="EventMarkerDriver"/>
<driver name="DQMDatabaseDriver"/>
- <driver name="CalibrationDriver"/>
- <driver name="RawTrackerHitSensorSetup"/>
+ <driver name="CalibrationDriver"/>
+ <driver name="RawTrackerHitSensorSetup"/>
<driver name="BadChannelFilter" />
- <driver name="RawTrackerHitFitterDriver" />
- <driver name="TrackerHitDriver"/>
- <driver name="HelicalTrackHitDriver"/>
- <driver name="TrackerReconDriver"/>
- <driver name="TrackDataDriver"/>
+ <driver name="RawTrackerHitFitterDriver" />
+ <driver name="TrackerHitDriver"/>
+ <driver name="HelicalTrackHitDriver"/>
+ <driver name="TrackerReconDriver"/>
+ <driver name="TrackDataDriver"/>
<driver name="EcalRawConverter" />
- <driver name="EcalClusterer" />
- <driver name="ReconParticle" />
+ <driver name="EcalClusterer" />
+ <driver name="ReconParticle" />
<driver name="SVTMonitoring"/>
- <driver name="SVTHitMCEfficiency"/>
- <driver name="TrackingMonitoring"/>
- <driver name="TrackingResiduals"/>
- <driver name="TrackMCEfficiency"/>
+ <driver name="SVTHitMCEfficiency"/>
+ <driver name="TrackingMonitoring"/>
+ <driver name="TrackingResiduals"/>
+ <driver name="TrackMCEfficiency"/>
<driver name="FinalStateMonitoring"/>
- <driver name="V0Monitoring"/>
+ <driver name="V0Monitoring"/>
<driver name="AidaSaveDriver"/>
<driver name="CleanupDriver"/>
</execute>
java/branches/hps-java_HPSJAVA-88/tracking
--- java/branches/hps-java_HPSJAVA-88/tracking/pom.xml 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/tracking/pom.xml 2014-09-02 22:27:42 UTC (rev 940)
@@ -10,7 +10,7 @@
<groupId>org.hps</groupId>
<artifactId>hps-parent</artifactId>
<relativePath>../parent/pom.xml</relativePath>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</parent>
<scm>
@@ -27,6 +27,9 @@
<configuration>
<excludes>
<exclude>org/hps/recon/tracking/TruthResidualTest.java</exclude>
+ <!-- Test input LCIO file is missing for next two. -->
+ <exclude>org/hps/recon/tracking/TestRunTrackReconTest.java</exclude>
+ <exclude>org/hps/recon/tracking/HelicalTrackHitDriverTest.java</exclude>
</excludes>
</configuration>
</plugin>
java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking
--- java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/DumbShaperFit.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/DumbShaperFit.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,10 +1,12 @@
package org.hps.recon.tracking;
+import java.util.ArrayList;
+import java.util.Collection;
import org.hps.conditions.deprecated.HPSSVTCalibrationConstants.ChannelConstants;
import org.lcsim.event.RawTrackerHit;
/**
- *
+ *
* @author Matt Graham
*/
// FIXME: Is there some other description besides "dumb" that could be used in this class name?
@@ -12,18 +14,24 @@
// TODO: Add class documentation.
public class DumbShaperFit implements ShaperFitAlgorithm {
+ private boolean debug = false;
+
public DumbShaperFit() {
}
+ public void setDebug(boolean debug) {
+ this.debug = debug;
+ }
+
@Override
- public ShapeFitParameters fitShape(RawTrackerHit rth, ChannelConstants constants) {
+ public Collection<ShapeFitParameters> fitShape(RawTrackerHit rth, ChannelConstants constants) {
short[] adcVals = rth.getADCValues();
return this.fitShape(adcVals, constants);
}
- public ShapeFitParameters fitShape(short[] adcVals, ChannelConstants constants) {
+ public Collection<ShapeFitParameters> fitShape(short[] adcVals, ChannelConstants constants) {
ShapeFitParameters fitresults = new ShapeFitParameters();
- double[] pedSub = { -99.0, -99.0, -99.0, -99.0, -99.0, -99.0 };
+ double[] pedSub = {-99.0, -99.0, -99.0, -99.0, -99.0, -99.0};
double maxADC = -99999;
int iMax = -1;
double t0 = -999;
@@ -44,22 +52,27 @@
// mg...put in a cut here to make sure pulse shape is reasonable
// if not, set t0 to -99 (which will fail the later t0>0 cut
- if (iMax == 0 || iMax == 5)
+ if (iMax == 0 || iMax == 5) {
t0 = -99;
+ }
// make sure it goes up below iMax
for (int i = 0; i < iMax; i++) {
- if (pedSub[i + 1] < pedSub[i])
+ if (pedSub[i + 1] < pedSub[i]) {
t0 = -99;
+ }
}
// ...and down below iMax
for (int i = iMax; i < 5; i++) {
- if (pedSub[i + 1] > pedSub[i])
+ if (pedSub[i + 1] > pedSub[i]) {
t0 = -99;
+ }
}
fitresults.setAmp(maxADC);
fitresults.setT0(t0);
- return fitresults;
+ ArrayList<ShapeFitParameters> fits = new ArrayList<ShapeFitParameters>();
+ fits.add(fitresults);
+ return fits;
}
}
java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking
--- java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/NearestNeighborRMSClusterer.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/NearestNeighborRMSClusterer.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -7,7 +7,7 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
-
+import org.apache.commons.math3.special.Gamma;
import org.hps.conditions.deprecated.HPSSVTCalibrationConstants;
import org.hps.conditions.deprecated.HPSSVTConstants;
import org.lcsim.detector.identifier.IIdentifier;
@@ -16,7 +16,7 @@
import org.lcsim.event.RawTrackerHit;
/**
- *
+ *
* @author Matt Graham
*/
// TODO: Add class documentation.
@@ -28,14 +28,15 @@
private double _cluster_threshold;
private double _meanTime = 24;
private double _timeWindow = 48;
- private double _maxChisq = 20.0;
+ private final double _minChiProb = Gamma.regularizedGammaQ(4, 20);
/**
- * Instantiate NearestNeighborRMS with specified thresholds. Seed threshold is the minimum
- * charge to initiate a cluster. Neighbor threshold is the minimum charge to add a neighboring
- * cell to a cluster. Cluster threshold is minimum charge of the entire cluster. All thresholds
- * are in units of RMS noise of the channel(s).
- *
+ * Instantiate NearestNeighborRMS with specified thresholds. Seed threshold
+ * is the minimum charge to initiate a cluster. Neighbor threshold is the
+ * minimum charge to add a neighboring cell to a cluster. Cluster threshold
+ * is minimum charge of the entire cluster. All thresholds are in units of
+ * RMS noise of the channel(s).
+ *
* @param seed_threshold seed threshold
* @param neighbor_threshold neighbor threshold
* @param cluster_threshold cluster threshold
@@ -48,9 +49,9 @@
/**
* Instantiate NearestNeighborRMS with default thresholds:
- *
- * seed_threshold = 4*RMS noise neighbor_threshold = 3*RMS noise cluster_threshold = 4*RMS
- * noise
+ *
+ * seed_threshold = 4*RMS noise neighbor_threshold = 3*RMS noise
+ * cluster_threshold = 4*RMS noise
*/
public NearestNeighborRMSClusterer() {
this(4.0, 3.0, 4.0);
@@ -58,7 +59,7 @@
/**
* Set the seed threshold. Units are RMS noise.
- *
+ *
* @param seed_threshold seed threshold
*/
public void setSeedThreshold(double seed_threshold) {
@@ -67,7 +68,7 @@
/**
* Set the neighbor threshold. Units are RMS noise.
- *
+ *
* @param neighbor_threshold neighbor threshold
*/
public void setNeighborThreshold(double neighbor_threshold) {
@@ -76,7 +77,7 @@
/**
* Set the cluster threshold. Units are RMS noise.
- *
+ *
* @param cluster_threshold cluster threshold
*/
public void setClusterThreshold(double cluster_threshold) {
@@ -85,7 +86,7 @@
/**
* Find clusters using the nearest neighbor algorithm.
- *
+ *
* @param base_hits List of RawTrackerHits to be clustered
* @return list of clusters, with a cluster being a list of RawTrackerHits
*/
@@ -126,7 +127,12 @@
// Check for duplicate RawTrackerHits or channel numbers
if (channel_to_hit.containsKey(channel_number)) {
// throw new RuntimeException("Duplicate channel number: "+channel_number);
- System.out.println("Duplicate channel number: " + channel_number);
+// System.out.println("Duplicate channel number: " + channel_number);
+ //if the hit currently in the map has smaller time, use it and discard the new hit
+ //TODO: be smarter about this
+ if (Math.abs(((FittedRawTrackerHit) channel_to_hit.get(channel_number)).getT0()) < Math.abs(base_hit.getT0())) {
+ continue;
+ }
}
// Add this hit to the maps that relate channels and hits
@@ -231,7 +237,7 @@
}
private boolean passChisqCut(FittedRawTrackerHit hit) {
- return hit.getShapeFitParameters().getChiSq() < _maxChisq;
+ return hit.getShapeFitParameters().getChiProb() > _minChiProb;
}
public int getNeighborCell(int cell, int ncells_0, int ncells_1) {
java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking
--- java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/RawTrackerHitFitterDriver.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/RawTrackerHitFitterDriver.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -20,7 +20,7 @@
*/
// TODO: Add class documentation.
public class RawTrackerHitFitterDriver extends Driver {
-
+
private boolean debug = false;
private ShaperFitAlgorithm _shaper = new DumbShaperFit();
private String rawHitCollectionName = "SVTRawTrackerHits";
@@ -41,57 +41,64 @@
public void setUseTruthTime(boolean useTruthTime) {
this.useTruthTime = useTruthTime;
}
-
+
public void setDebug(boolean debug) {
this.debug = debug;
}
-
+
public void setCorrectT0Shift(boolean correctT0Shift) {
this.correctT0Shift = correctT0Shift;
}
-
+
public void setUseTimestamps(boolean useTimestamps) {
this.useTimestamps = useTimestamps;
}
-
+
public void setSubtractTOF(boolean subtractTOF) {
this.subtractTOF = subtractTOF;
}
-
+
public void setFitAlgorithm(String fitAlgorithm) {
if (fitAlgorithm.equals("Analytic")) {
_shaper = new ShaperAnalyticFitAlgorithm();
+ } else if (fitAlgorithm.equals("Linear")) {
+ _shaper = new ShaperLinearFitAlgorithm(1);
+ } else if (fitAlgorithm.equals("PileupAlways")) {
+ _shaper = new ShaperPileupFitAlgorithm(1.0);
+ } else if (fitAlgorithm.equals("Pileup")) {
+ _shaper = new ShaperPileupFitAlgorithm();
} else {
throw new RuntimeException("Unrecognized fitAlgorithm: " + fitAlgorithm);
}
}
-
+
public void setFitCollectionName(String fitCollectionName) {
this.fitCollectionName = fitCollectionName;
}
-
+
public void setFittedHitCollectionName(String fittedHitCollectionName) {
this.fittedHitCollectionName = fittedHitCollectionName;
}
-
+
public void setRawHitCollectionName(String rawHitCollectionName) {
this.rawHitCollectionName = rawHitCollectionName;
}
-
+
@Override
public void startOfData() {
+ _shaper.setDebug(debug);
if (rawHitCollectionName == null) {
throw new RuntimeException("The parameter ecalCollectionName was not set!");
}
}
-
+
@Override
public void process(EventHeader event) {
if (!event.hasCollection(RawTrackerHit.class, rawHitCollectionName)) {
// System.out.println(rawHitCollectionName + " does not exist; skipping event");
return;
}
-
+
List<RawTrackerHit> rawHits = event.get(RawTrackerHit.class, rawHitCollectionName);
if (rawHits == null) {
throw new RuntimeException("Event is missing SVT hits collection!");
@@ -103,37 +110,38 @@
for (RawTrackerHit hit : rawHits) {
int strip = hit.getIdentifierFieldValue("strip");
ChannelConstants constants = HPSSVTCalibrationConstants.getChannelConstants((SiSensor) hit.getDetectorElement(), strip);
- ShapeFitParameters fit = _shaper.fitShape(hit, constants);
- if (correctT0Shift) {
- fit.setT0(fit.getT0() - constants.getT0Shift());
+ for (ShapeFitParameters fit : _shaper.fitShape(hit, constants)) {
+ if (correctT0Shift) {
+ fit.setT0(fit.getT0() - constants.getT0Shift());
+ }
+ if (subtractTOF) {
+ double tof = hit.getDetectorElement().getGeometry().getPosition().magnitude() / (Const.SPEED_OF_LIGHT * Const.nanosecond);
+ fit.setT0(fit.getT0() - tof);
+ }
+ if (useTimestamps) {
+ double t0Svt = ReadoutTimestamp.getTimestamp(ReadoutTimestamp.SYSTEM_TRACKER, event);
+ double t0Trig = ReadoutTimestamp.getTimestamp(ReadoutTimestamp.SYSTEM_TRIGGERBITS, event);
+ double corMod = (t0Svt - t0Trig) + 200.0;
+ fit.setT0(fit.getT0() + corMod);
+ }
+ if (useTruthTime) {
+ double t0Svt = ReadoutTimestamp.getTimestamp(ReadoutTimestamp.SYSTEM_TRACKER, event);
+ double absoluteHitTime = fit.getT0() + t0Svt;
+ double relativeHitTime = ((absoluteHitTime + 250.0) % 500.0) - 250.0;
+
+ fit.setT0(relativeHitTime);
+ }
+ if (debug) {
+ System.out.println(fit);
+ }
+ fits.add(fit);
+ FittedRawTrackerHit hth = new FittedRawTrackerHit(hit, fit);
+ hits.add(hth);
+ if (strip == HPSSVTConstants.TOTAL_STRIPS_PER_SENSOR) { // drop unbonded channel
+ continue;
+ }
+ hit.getDetectorElement().getReadout().addHit(hth);
}
- if (subtractTOF) {
- double tof = hit.getDetectorElement().getGeometry().getPosition().magnitude() / (Const.SPEED_OF_LIGHT * Const.nanosecond);
- fit.setT0(fit.getT0() - tof);
- }
- if (useTimestamps) {
- double t0Svt = ReadoutTimestamp.getTimestamp(ReadoutTimestamp.SYSTEM_TRACKER, event);
- double t0Trig = ReadoutTimestamp.getTimestamp(ReadoutTimestamp.SYSTEM_TRIGGER, event);
- double corMod = (t0Svt - t0Trig) + 200.0;
- fit.setT0(fit.getT0() + corMod);
- }
- if (useTruthTime) {
- double t0Svt = ReadoutTimestamp.getTimestamp(ReadoutTimestamp.SYSTEM_TRACKER, event);
- double absoluteHitTime = fit.getT0() + t0Svt;
- double relativeHitTime = ((absoluteHitTime + 250.0) % 500.0) - 250.0;
-
- fit.setT0(relativeHitTime);
- }
- if (debug) {
- System.out.println(fit);
- }
- fits.add(fit);
- FittedRawTrackerHit hth = new FittedRawTrackerHit(hit, fit);
- hits.add(hth);
- if (strip == HPSSVTConstants.TOTAL_STRIPS_PER_SENSOR) { // drop unbonded channel
- continue;
- }
- hit.getDetectorElement().getReadout().addHit(hth);
}
event.put(fitCollectionName, fits, ShapeFitParameters.class, genericObjectFlags);
event.put(fittedHitCollectionName, hits, FittedRawTrackerHit.class, relationFlags);
java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking
--- java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/ShapeFitParameters.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/ShapeFitParameters.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,13 +1,9 @@
-/*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
package org.hps.recon.tracking;
import org.lcsim.event.GenericObject;
/**
- *
+ *
* @author Matt Graham
*/
public class ShapeFitParameters implements GenericObject {
@@ -16,9 +12,9 @@
private double _t0Err = Double.NaN;
private double _amp = Double.NaN;
private double _ampErr = Double.NaN;
- private double _tp = Double.NaN;
- private double _tpErr = Double.NaN;
- private double _chiSq = Double.NaN;
+// private double _tp = Double.NaN;
+// private double _tpErr = Double.NaN;
+ private double _chiProb = Double.NaN;
public ShapeFitParameters() {
}
@@ -36,9 +32,9 @@
_amp = amp;
}
- public void setTp(double tp) {
- _tp = tp;
- }
+// public void setTp(double tp) {
+// _tp = tp;
+// }
public void setAmpErr(double _ampErr) {
this._ampErr = _ampErr;
@@ -48,12 +44,12 @@
this._t0Err = _t0Err;
}
- public void setTpErr(double _tpErr) {
- this._tpErr = _tpErr;
- }
+// public void setTpErr(double _tpErr) {
+// this._tpErr = _tpErr;
+// }
- public void setChiSq(double _chiSq) {
- this._chiSq = _chiSq;
+ public void setChiProb(double _chiProb) {
+ this._chiProb = _chiProb;
}
public double getT0() {
@@ -64,9 +60,9 @@
return _amp;
}
- public double getTp() {
- return _tp;
- }
+// public double getTp() {
+// return _tp;
+// }
public double getT0Err() {
return _t0Err;
@@ -76,14 +72,42 @@
return _ampErr;
}
- public double getTpErr() {
- return _tpErr;
+// public double getTpErr() {
+// return _tpErr;
+// }
+
+ public double getChiProb() {
+ return _chiProb;
}
- public double getChiSq() {
- return _chiSq;
+ public static double getT0(GenericObject object) {
+ return object.getDoubleVal(0);
}
+ public static double getT0Err(GenericObject object) {
+ return object.getDoubleVal(1);
+ }
+
+ public static double getAmp(GenericObject object) {
+ return object.getDoubleVal(2);
+ }
+
+ public static double getAmpErr(GenericObject object) {
+ return object.getDoubleVal(3);
+ }
+
+// public static double getTp(GenericObject object) {
+// return object.getDoubleVal(4);
+// }
+//
+// public static double getTpErr(GenericObject object) {
+// return object.getDoubleVal(5);
+// }
+
+ public static double getChiProb(GenericObject object) {
+ return object.getDoubleVal(4);
+ }
+
@Override
public int getNInt() {
return 0;
@@ -96,7 +120,7 @@
@Override
public int getNDouble() {
- return 7;
+ return 5;
}
@Override
@@ -120,14 +144,14 @@
return _amp;
case 3:
return _ampErr;
+// case 4:
+// return _tp;
+// case 5:
+// return _tpErr;
case 4:
- return _tp;
- case 5:
- return _tpErr;
- case 6:
- return _chiSq;
+ return _chiProb;
default:
- throw new UnsupportedOperationException("Only 7 double values in " + this.getClass().getSimpleName());
+ throw new UnsupportedOperationException("Only 5 double values in " + this.getClass().getSimpleName());
}
}
@@ -139,6 +163,6 @@
@Override
public String toString() {
- return String.format("chisq=%f\tA=%f\tAerr=%f\tT0=%f\tT0err=%f", _chiSq, _amp, _ampErr, _t0, _t0Err);
+ return String.format("chiprob=%f\tA=%f\tAerr=%f\tT0=%f\tT0err=%f", _chiProb, _amp, _ampErr, _t0, _t0Err);
}
}
java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking
--- java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/ShaperAnalyticFitAlgorithm.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/ShaperAnalyticFitAlgorithm.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,25 +1,32 @@
package org.hps.recon.tracking;
+import java.util.ArrayList;
+import java.util.Collection;
+import org.apache.commons.math3.special.Gamma;
import org.hps.conditions.deprecated.HPSSVTCalibrationConstants.ChannelConstants;
import org.hps.conditions.deprecated.HPSSVTConstants;
import org.lcsim.event.RawTrackerHit;
-//import org.lcsim.math.chisq.ChisqProb;
/**
- * Fast fitter; currently only fits single hits. Uses Tp from ChannelConstants; fits values and
- * errors for T0 and amplitude.
- *
+ * Fast fitter; currently only fits single hits. Uses Tp from ChannelConstants;
+ * fits values and errors for T0 and amplitude.
+ *
* @author Sho Uemura
*/
public class ShaperAnalyticFitAlgorithm implements ShaperFitAlgorithm {
+ private boolean debug = false;
+
+ public void setDebug(boolean debug) {
+ this.debug = debug;
+ }
+
@Override
- public ShapeFitParameters fitShape(RawTrackerHit rth, ChannelConstants constants) {
- short[] samples = rth.getADCValues();
- return this.fitShape(samples, constants);
+ public Collection<ShapeFitParameters> fitShape(RawTrackerHit rth, ChannelConstants constants) {
+ return this.fitShape(rth.getADCValues(), constants);
}
- public ShapeFitParameters fitShape(short[] samples, ChannelConstants constants) {
+ public Collection<ShapeFitParameters> fitShape(short[] samples, ChannelConstants constants) {
double minChisq = Double.POSITIVE_INFINITY;
int bestStart = 0;
ShapeFitParameters fit = new ShapeFitParameters();
@@ -37,7 +44,9 @@
// constants.getPedestal(), samples[4] - constants.getPedestal(), samples[5] -
// constants.getPedestal());
// System.out.println("start = " + bestStart + ", " + fit);
- return fit;
+ ArrayList<ShapeFitParameters> fits = new ArrayList<ShapeFitParameters>();
+ fits.add(fit);
+ return fits;
}
private double fitSection(short[] samples, ChannelConstants constants, ShapeFitParameters fit, int start) {
@@ -87,7 +96,6 @@
fit.setAmpErr(Math.sqrt(height_var));
fit.setT0(t0);
fit.setT0Err(Math.sqrt(time_var));
- fit.setTp(constants.getTp());
double chisq = 0;
for (int i = 0; i < samples.length; i++) {
@@ -95,10 +103,10 @@
double fit_y = A * (Math.max(0, (ti - t0)) / constants.getTp()) * Math.exp(1 - (ti - t0) / constants.getTp()) + constants.getPedestal();
chisq += Math.pow((fit_y - samples[i]) / constants.getNoise(), 2);
}
- fit.setChiSq(chisq);
- if (A > 0) {
+ if (A > 0 && chisq < Double.POSITIVE_INFINITY) {
// return ChisqProb.gammp(samples.length - 2, chisq);
+ fit.setChiProb(Gamma.regularizedGammaQ(samples.length - 2, chisq));
return chisq / (samples.length - 2);
} else {
return Double.POSITIVE_INFINITY;
java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking
--- java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/ShaperFitAlgorithm.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/ShaperFitAlgorithm.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,15 +1,17 @@
package org.hps.recon.tracking;
+import java.util.Collection;
import org.hps.conditions.deprecated.HPSSVTCalibrationConstants.ChannelConstants;
import org.lcsim.event.RawTrackerHit;
/**
- *
+ *
* @author Matt Graham
*/
// TODO: Add class documentation.
public interface ShaperFitAlgorithm {
- public ShapeFitParameters fitShape(RawTrackerHit rth, ChannelConstants constants);
+ public Collection<ShapeFitParameters> fitShape(RawTrackerHit rth, ChannelConstants constants);
+ public void setDebug(boolean debug);
}
java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking
--- java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/StripMaker.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/StripMaker.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -273,19 +273,21 @@
}
private double getTime(List<FittedRawTrackerHit> cluster) {
- int time_sum = 0;
- int signal_sum = 0;
+ double time_sum = 0;
+ double signal_sum = 0;
+// System.out.format("Hits:\n");
for (FittedRawTrackerHit hit : cluster) {
double signal = hit.getAmp();
double time = hit.getT0();
+// System.out.format("t0=%f\tA=%f\n",hit.getT0(),hit.getAmp());
time_sum += time * signal;
signal_sum += signal;
}
- return (double) time_sum / (double) signal_sum;
+ return time_sum / signal_sum;
}
private SymmetricMatrix getCovariance(List<FittedRawTrackerHit> cluster, SiSensorElectrodes electrodes) {
java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking
--- java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/TrackDataDriver.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/TrackDataDriver.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,6 +1,7 @@
package org.hps.recon.tracking;
import hep.physics.vec.Hep3Vector;
+import hep.physics.vec.VecOp;
import java.util.ArrayList;
import java.util.List;
@@ -17,184 +18,241 @@
import org.lcsim.fit.helicaltrack.HelicalTrackStrip;
import org.lcsim.geometry.Detector;
import org.lcsim.util.Driver;
-import org.hps.recon.tracking.TrackTimeData;
-import org.hps.recon.tracking.TrackResidualsData;
+import org.lcsim.event.RelationalTable;
+import org.lcsim.event.base.BaseRelationalTable;
/**
- *
+ *
* @author Omar Moreno <[log in to unmask]>
* @version $Id$
- *
+ *
*/
public class TrackDataDriver extends Driver {
- // Collection Names
- String trackCollectionName = "MatchedTracks";
- // TODO: Change this to match whatever track name is decided on
- String trackTimeDataCollectionName = "TrackTimeData";
- String trackResidualsCollectionName = "TrackResiduals";
- String rotatedHthRelationsColName = "RotatedHelicalTrackHitRelations";
- String trackTimeDataRelationsColName = "TrackTimeDataRelations";
- String trackResidualsRelationsColName = "TrackResidualsRelations";
+ // Collection Names
+ String trackCollectionName = "MatchedTracks";
+ // TODO: Change this to match whatever track name is decided on
+ String trackTimeDataCollectionName = "TrackTimeData";
+ String trackResidualsCollectionName = "TrackResiduals";
+ String rotatedHthRelationsColName = "RotatedHelicalTrackHitRelations";
+ String rotatedHthCollectionName = "RotatedHelicalTrackHits";
+ String trackTimeDataRelationsColName = "TrackTimeDataRelations";
+ String trackResidualsRelationsColName = "TrackResidualsRelations";
- public TrackDataDriver() {}
+ public TrackDataDriver() {
+ }
- protected void detectorChanged(Detector detector){
-
- // TODO: Add plots of all track data variables
-
- }
-
- protected void process(EventHeader event) {
+ protected void detectorChanged(Detector detector) {
- // If the event doesn't contain a collection of tracks, skip it.
- if (!event.hasCollection(Track.class, trackCollectionName))
- return;
+ // TODO: Add plots of all track data variables
+ }
- // Get the collection of tracks from the event
- List<Track> tracks = event.get(Track.class, trackCollectionName);
-
- // Get the collection of LCRelations relating RotatedHelicalTrackHits to
- // HelicalTrackHits
- List<LCRelation> rotatedHthToHthRelations = event.get(LCRelation.class, rotatedHthRelationsColName);
+ protected void process(EventHeader event) {
- // Create a collection to hold the track time and t0 residual data
- List<TrackTimeData> timeDataCollection = new ArrayList<TrackTimeData>();
+ // If the event doesn't contain a collection of tracks, skip it.
+ if (!event.hasCollection(Track.class, trackCollectionName)) {
+ return;
+ }
- // Create a collection of LCRelations between a track and the t0 residual data
- List<LCRelation> trackToTrackTimeDataRelations = new ArrayList<LCRelation>();
-
- // Create a collection to hold the track residuals
- List<TrackResidualsData> trackResidualsCollection = new ArrayList<TrackResidualsData>();
-
- // Create a collection of LCRelations between a track and the track residuals
- List<LCRelation> trackToTrackResidualsRelations = new ArrayList<LCRelation>();
-
- double totalT0 = 0;
- double totalHits = 0;
- double trackTime = 0;
- double t0Residual = 0;
- double xResidual = 0;
- double yResidual = 0;
- float trackerVolume = -1;
-
-
- boolean isFirstHit = true;
-
- HpsSiSensor sensor = null;
- Hep3Vector stereoHitPosition = null;
- Hep3Vector trackPosition = null;
- HelicalTrackHit helicalTrackHit = null;
-
- List<Double> t0Residuals = new ArrayList<Double>();
- List<Double> trackResidualsX = new ArrayList<Double>();
- List<Float> trackResidualsY = new ArrayList<Float>();
- List<Integer> sensorLayers = new ArrayList<Integer>();
- List<Integer> stereoLayers = new ArrayList<Integer>();
-
-
- // Loop over all the tracks in the event
- for (Track track : tracks) {
-
- totalT0 = 0;
- totalHits = 0;
- t0Residuals.clear();
- sensorLayers.clear();
- trackResidualsX.clear();
- trackResidualsY.clear();
- stereoLayers.clear();
-
- //
- // Calculate the track time and track residuals. Also, change the
- // position of a HelicalTrackHit to be the corrected one.
- //
-
- // Loop over all stereo hits comprising a track
- for (TrackerHit rotatedStereoHit : track.getTrackerHits()) {
-
- // Add the stereo layer number associated with the track residual
- stereoLayers.add(((HelicalTrackHit) rotatedStereoHit).Layer());
-
- // Extrapolate the track to the stereo hit position and calculate
- // track residuals
- stereoHitPosition = ((HelicalTrackHit) rotatedStereoHit).getCorrectedPosition();
- trackPosition = TrackUtils.extrapolateTrack(track, stereoHitPosition.x());
- xResidual = trackPosition.x() - stereoHitPosition.y();
- yResidual = trackPosition.y() - stereoHitPosition.z();
- trackResidualsX.add(xResidual);
- trackResidualsY.add((float) yResidual);
+ // Get the collection of tracks from the event
+ List<Track> tracks = event.get(Track.class, trackCollectionName);
- //
- // Change the persisted position of both RotatedHelicalTrackHits
- // and HelicalTrackHits to the corrected position.
- //
-
- // Get the HelicalTrackHit corresponding to the RotatedHelicalTrackHit
- // associated with a track
- for(LCRelation relation : rotatedHthToHthRelations){
- if(relation.getTo().equals(rotatedStereoHit)){
- helicalTrackHit = (HelicalTrackHit) relation.getFrom();
- break;
- }
- }
- ((HelicalTrackHit) rotatedStereoHit).setPosition(stereoHitPosition.v());
- stereoHitPosition = CoordinateTransformations.transformVectorToDetector(stereoHitPosition);
- helicalTrackHit.setPosition(stereoHitPosition.v());
-
-
- // Loop over the clusters comprising the stereo hit
- for(HelicalTrackStrip cluster : ((HelicalTrackCross) rotatedStereoHit).getStrips()){
-
- totalT0 += cluster.time();
- totalHits++;
- }
- }
-
- // The track time is the mean t0 of hits on a track
- trackTime = totalT0/totalHits;
-
-
- //
- // Calculate the t0 residuals
- //
-
- isFirstHit = true;
- // Loop over all stereo hits comprising a track
- for (TrackerHit stereoHit : track.getTrackerHits()) {
- // Loop over the clusters comprising the stereo hit
- for(HelicalTrackStrip cluster : ((HelicalTrackCross) stereoHit).getStrips()){
+ // Get the collection of LCRelations relating RotatedHelicalTrackHits to
+ // HelicalTrackHits
+ List<LCRelation> rotatedHthToHthRelations = event.get(LCRelation.class, rotatedHthRelationsColName);
+ BaseRelationalTable hthToRotatedHth = new BaseRelationalTable(RelationalTable.Mode.ONE_TO_ONE, RelationalTable.Weighting.UNWEIGHTED);
+ hthToRotatedHth.addRelations(rotatedHthToHthRelations);
- if(isFirstHit){
- sensor = (HpsSiSensor) ((RawTrackerHit) cluster.rawhits().get(0)).getDetectorElement();
- if(sensor.isTopLayer()) trackerVolume = 0;
- else if(sensor.isBottomLayer()) trackerVolume = 1;
- }
-
- // Add the layer number associated with this residual to the list of layers
- sensorLayers.add(sensor.getLayerNumber());
-
- // Find the t0 residual and add it to the list of residuals
- t0Residual = trackTime - cluster.time();
- // Apply correction to t0 residual
- t0Residual /= Math.sqrt((totalHits - 1)/totalHits);
- t0Residuals.add(t0Residual);
- }
- }
-
- TrackTimeData timeData = new TrackTimeData(trackerVolume, trackTime, sensorLayers, t0Residuals);
- timeDataCollection.add(timeData);
- trackToTrackTimeDataRelations.add(new BaseLCRelation(timeData, track));
-
- TrackResidualsData trackResiduals = new TrackResidualsData((int) trackerVolume, stereoLayers, trackResidualsX, trackResidualsY);
- trackResidualsCollection.add(trackResiduals);
- trackToTrackResidualsRelations.add(new BaseLCRelation(trackResiduals, track));
-
- }
-
- event.put(trackTimeDataCollectionName, timeDataCollection, TrackTimeData.class, 0);
- event.put(trackTimeDataRelationsColName, trackToTrackTimeDataRelations, LCRelation.class, 0);
- event.put(trackResidualsCollectionName, trackResidualsCollection, TrackResidualsData.class, 0);
- event.put(trackResidualsRelationsColName, trackToTrackResidualsRelations, LCRelation.class, 0);
-
- }
+ List<HelicalTrackHit> rotatedHths = event.get(HelicalTrackHit.class, rotatedHthCollectionName);
+
+ // Create a collection to hold the track time and t0 residual data
+ List<TrackTimeData> timeDataCollection = new ArrayList<TrackTimeData>();
+
+ // Create a collection of LCRelations between a track and the t0 residual data
+ List<LCRelation> trackToTrackTimeDataRelations = new ArrayList<LCRelation>();
+
+ // Create a collection to hold the track residuals
+ List<TrackResidualsData> trackResidualsCollection = new ArrayList<TrackResidualsData>();
+
+ // Create a collection of LCRelations between a track and the track residuals
+ List<LCRelation> trackToTrackResidualsRelations = new ArrayList<LCRelation>();
+
+ // Create a collection to hold the track residuals
+ List<TrackQualityData> trackQualityCollection = new ArrayList<TrackQualityData>();
+
+ // Create a collection of LCRelations between a track and the track residuals
+ List<LCRelation> trackQualityDataToTrackRelations = new ArrayList<LCRelation>();
+
+ double totalT0 = 0;
+ double totalHits = 0;
+ double trackTime = 0;
+ double t0Residual = 0;
+ double xResidual = 0;
+ double yResidual = 0;
+ float trackerVolume = -1;
+
+ boolean isFirstHit = true;
+
+ HpsSiSensor sensor = null;
+ Hep3Vector stereoHitPosition = null;
+ Hep3Vector trackPosition = null;
+ HelicalTrackHit helicalTrackHit = null;
+
+ List<Double> t0Residuals = new ArrayList<Double>();
+ List<Double> trackResidualsX = new ArrayList<Double>();
+ List<Float> trackResidualsY = new ArrayList<Float>();
+ List<Integer> sensorLayers = new ArrayList<Integer>();
+ List<Integer> stereoLayers = new ArrayList<Integer>();
+
+ // Loop over all the tracks in the event
+ for (Track track : tracks) {
+
+ totalT0 = 0;
+ totalHits = 0;
+ t0Residuals.clear();
+ sensorLayers.clear();
+ trackResidualsX.clear();
+ trackResidualsY.clear();
+ stereoLayers.clear();
+
+ //
+ // Calculate the track time and track residuals. Also, change the
+ // position of a HelicalTrackHit to be the corrected one.
+ //
+ // Loop over all stereo hits comprising a track
+ for (TrackerHit rotatedStereoHit : track.getTrackerHits()) {
+
+ // Add the stereo layer number associated with the track residual
+ stereoLayers.add(((HelicalTrackHit) rotatedStereoHit).Layer());
+
+ // Extrapolate the track to the stereo hit position and calculate
+ // track residuals
+ stereoHitPosition = ((HelicalTrackHit) rotatedStereoHit).getCorrectedPosition();
+ trackPosition = TrackUtils.extrapolateTrack(track, stereoHitPosition.x());
+ xResidual = trackPosition.x() - stereoHitPosition.y();
+ yResidual = trackPosition.y() - stereoHitPosition.z();
+ trackResidualsX.add(xResidual);
+ trackResidualsY.add((float) yResidual);
+
+ //
+ // Change the persisted position of both RotatedHelicalTrackHits
+ // and HelicalTrackHits to the corrected position.
+ //
+ // Get the HelicalTrackHit corresponding to the RotatedHelicalTrackHit
+ // associated with a track
+ helicalTrackHit = (HelicalTrackHit) hthToRotatedHth.from(rotatedStereoHit);
+ ((HelicalTrackHit) rotatedStereoHit).setPosition(stereoHitPosition.v());
+ stereoHitPosition = CoordinateTransformations.transformVectorToDetector(stereoHitPosition);
+ helicalTrackHit.setPosition(stereoHitPosition.v());
+
+ // Loop over the clusters comprising the stereo hit
+ for (HelicalTrackStrip cluster : ((HelicalTrackCross) rotatedStereoHit).getStrips()) {
+
+ totalT0 += cluster.time();
+ totalHits++;
+ }
+ }
+
+ // The track time is the mean t0 of hits on a track
+ trackTime = totalT0 / totalHits;
+
+ //
+ // Calculate the t0 residuals
+ //
+ isFirstHit = true;
+ // Loop over all stereo hits comprising a track
+ for (TrackerHit stereoHit : track.getTrackerHits()) {
+ // Loop over the clusters comprising the stereo hit
+ for (HelicalTrackStrip cluster : ((HelicalTrackCross) stereoHit).getStrips()) {
+
+ if (isFirstHit) {
+ sensor = (HpsSiSensor) ((RawTrackerHit) cluster.rawhits().get(0)).getDetectorElement();
+ if (sensor.isTopLayer()) {
+ trackerVolume = 0;
+ } else if (sensor.isBottomLayer()) {
+ trackerVolume = 1;
+ }
+ }
+
+ // Add the layer number associated with this residual to the list of layers
+ sensorLayers.add(sensor.getLayerNumber());
+
+ // Find the t0 residual and add it to the list of residuals
+ t0Residual = trackTime - cluster.time();
+ // Apply correction to t0 residual
+ t0Residual /= Math.sqrt((totalHits - 1) / totalHits);
+ t0Residuals.add(t0Residual);
+ }
+ }
+
+ double l1Isolation = 99999999.0;
+ double l2Isolation = 99999999.0;
+ // Loop over all stereo hits comprising a track
+ for (TrackerHit stereoHit : track.getTrackerHits()) {
+ // Loop over the clusters comprising the stereo hit
+ for (HelicalTrackStrip cluster : ((HelicalTrackCross) stereoHit).getStrips()) {
+// System.out.println(cluster.layer());
+ if (cluster.layer() == 1) {
+ l1Isolation = getNearestDistance(cluster, rotatedHths);
+ } else if (cluster.layer() == 2) {
+ l2Isolation = getNearestDistance(cluster, rotatedHths);
+ }
+ }
+ }
+
+ TrackTimeData timeData = new TrackTimeData(trackerVolume, trackTime, sensorLayers, t0Residuals);
+ timeDataCollection.add(timeData);
+ trackToTrackTimeDataRelations.add(new BaseLCRelation(timeData, track));
+
+ TrackResidualsData trackResiduals = new TrackResidualsData((int) trackerVolume, stereoLayers, trackResidualsX, trackResidualsY);
+ trackResidualsCollection.add(trackResiduals);
+ trackToTrackResidualsRelations.add(new BaseLCRelation(trackResiduals, track));
+
+ double qualityArray[] = {l1Isolation, l2Isolation};
+ TrackQualityData qualityData = new TrackQualityData(qualityArray);
+ trackQualityCollection.add(qualityData);
+ trackQualityDataToTrackRelations.add(new BaseLCRelation(qualityData, track));
+ }
+
+ event.put(trackTimeDataCollectionName, timeDataCollection, TrackTimeData.class, 0);
+ event.put(trackTimeDataRelationsColName, trackToTrackTimeDataRelations, LCRelation.class, 0);
+ event.put(trackResidualsCollectionName, trackResidualsCollection, TrackResidualsData.class, 0);
+ event.put(trackResidualsRelationsColName, trackToTrackResidualsRelations, LCRelation.class, 0);
+ event.put(TrackQualityData.QUALITY_COLLECTION, trackQualityCollection, TrackResidualsData.class, 0);
+ event.put(TrackQualityData.QUALITY_RELATION_COLLECTION, trackQualityDataToTrackRelations, LCRelation.class, 0);
+
+ }
+
+ private static Double getNearestDistance(HelicalTrackStrip cl, List<HelicalTrackHit> toththits) {
+ Hep3Vector corigin = cl.origin();
+ Hep3Vector uvec = VecOp.mult(cl.umeas(), cl.u());
+ Hep3Vector clvec = VecOp.add(corigin, uvec);
+ int layer = cl.layer();
+// HelicalTrackStrip nearest = null;
+// Hep3Vector nearestvec = null;
+ Double mindist = 99999999.0;
+ for (HelicalTrackHit hth : toththits) {
+ HelicalTrackCross cross = (HelicalTrackCross) hth;
+ for (HelicalTrackStrip str : cross.getStrips()) {
+ if (layer == str.layer() && str != cl) {
+ Hep3Vector strorigin = str.origin();
+ Hep3Vector struvec = VecOp.mult(str.umeas(), str.u());
+ Hep3Vector strvec = VecOp.add(strorigin, struvec);
+ double origindist = VecOp.sub(corigin, strorigin).magnitude();
+ double dist = VecOp.sub(clvec, strvec).magnitude();
+ if (origindist == 0.0 && dist != 0.0 && dist < Math.abs(mindist)) {
+ mindist = VecOp.sub(clvec, strvec).magnitude();
+ if (Math.abs(clvec.z()) > Math.abs(strvec.z())) {
+ mindist = -mindist;
+ }
+// nearest = str;
+// nearestvec = strvec;
+ }
+ }
+ }
+ }
+// System.out.println(clvec);
+// System.out.println(nearestvec);
+ return mindist;
+ }
}
java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking
--- java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/TrackerReconDriver.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/TrackerReconDriver.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -6,6 +6,7 @@
import org.lcsim.event.EventHeader;
import org.lcsim.event.Track;
+import org.lcsim.event.base.BaseTrack;
import org.lcsim.fit.helicaltrack.HelicalTrackHit;
import org.lcsim.geometry.Detector;
import org.lcsim.recon.tracking.seedtracker.SeedStrategy;
@@ -173,6 +174,10 @@
System.out.println(this.getClass().getSimpleName() + ": chi2 = " + track.getChi2());
}
}
+
+ // Set the type of track to indicate B-field in Y e.g. for swimming in Wired.
+ List<Track> tracks = event.get(Track.class, trackCollectionName);
+ setTrackType(tracks);
// Increment number of events.
++nevents;
@@ -180,6 +185,16 @@
// Add to tracks found.
ntracks += event.get(Track.class, trackCollectionName).size();
}
+
+ /**
+ * Set the track type to Y_FIELD so swimming is done correctly in Wired.
+ * @param tracks The list of <code>Track</code> objects.
+ */
+ private void setTrackType(List<Track> tracks) {
+ for (Track track : tracks) {
+ ((BaseTrack)track).setTrackType(BaseTrack.TrackType.Y_FIELD.ordinal());
+ }
+ }
@Override
public void endOfData() {
java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/gbl
--- java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/gbl/GblPoint.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/gbl/GblPoint.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,22 +1,590 @@
package org.hps.recon.tracking.gbl;
-import hep.physics.matrix.BasicMatrix;
-import hep.physics.matrix.Matrix;
+import java.util.ArrayList;
+import java.util.List;
+import org.hps.recon.tracking.gbl.matrix.EigenvalueDecomposition;
+import org.hps.recon.tracking.gbl.matrix.Matrix;
+import org.hps.recon.tracking.gbl.matrix.SymMatrix;
+import org.hps.recon.tracking.gbl.matrix.Vector;
+/**
+ *
+ * @author phansson
+ * @author Norman A Graf
+ *
+ * @version $Id:
+ */
public class GblPoint {
- public GblPoint(BasicMatrix jacPointToPoint) {
- // TODO Auto-generated constructor stub
- }
+ public GblPoint(hep.physics.matrix.BasicMatrix jacPointToPoint) {
+ theLabel = 0;
+ theOffset = 0;
+ measDim = 0;
+ transFlag = false;
+ //measTransformation()
+ scatFlag = false;
+ //localDerivatives()
+ //globalLabels()
+ //globalDerivatives()
- public void addMeasurement(Matrix proL2m, BasicMatrix meas, BasicMatrix measPrec) {
- // TODO Auto-generated method stub
-
- }
+ for (int i = 0; i < 5; ++i) {
+ for (int j = 0; j < 5; ++j) {
+ p2pJacobian.set(i, j, jacPointToPoint.e(i, j));
+ }
+ }
+ }
- public void addScatterer(BasicMatrix scat, BasicMatrix scatPrec) {
- // TODO Auto-generated method stub
-
- }
+ public void addMeasurement(hep.physics.matrix.Matrix proL2m, hep.physics.matrix.BasicMatrix meas, hep.physics.matrix.BasicMatrix measPrec) {
+ int ncols = proL2m.getNColumns();
+ int nrows = proL2m.getNRows();
+ System.out.println("proL2m has "+nrows+" rows and "+ ncols+ "columns");
+ Matrix a = new Matrix(nrows, ncols);
+ for(int i=0; i<nrows; ++i)
+ {
+ for(int j=0; j<ncols; ++j)
+ {
+ a.set(i,j,proL2m.e(i, j));
+ }
+ }
+ System.out.println("GblPoint add matrix: ");
+ a.print(10, 6);
+
+
+
+ int measnrows = meas.getNRows();
+ int measncols = meas.getNColumns();
+ System.out.println("meas has "+measnrows+" rows and "+measncols+" columns");
+
+ Vector measvec = new Vector(measncols);
+ for(int i=0; i<measnrows; ++i)
+ {
+ measvec.set(i, meas.e(0, i));
+ }
+ System.out.println("GblPoint add meas: ");
+ measvec.print(10, 6);
+
+
+ int measPrecnrows = measPrec.getNRows();
+ int measPrecncols = measPrec.getNColumns();
+
+ System.out.println("measPrec has "+measPrecnrows+" rows and "+measPrecncols+" columns");
+ Vector measPrecvec = new Vector(measPrecncols);
+ for(int i=0; i<measPrecnrows; ++i)
+ {
+ measPrecvec.set(i, measPrec.e(0, i));
+ }
+ System.out.println("GblPoint add measPrec: ");
+ measPrecvec.print(10, 6);
+
+ addMeasurement(a, measvec, measPrecvec, 0.);
+ }
+
+ public void addScatterer(hep.physics.matrix.BasicMatrix scat, hep.physics.matrix.BasicMatrix scatPrec) {
+ // TODO Auto-generated method stub
+
+ }
+
+ private int theLabel; ///< Label identifying point
+ private int theOffset; ///< Offset number at point if not negative (else interpolation needed)
+ private Matrix p2pJacobian = new SymMatrix(5); ///< Point-to-point jacobian from previous point
+ private Matrix prevJacobian = new SymMatrix(5); ///< Jacobian to previous scatterer (or first measurement)
+ private Matrix nextJacobian = new SymMatrix(5); ///< Jacobian to next scatterer (or last measurement)
+ private int measDim; ///< Dimension of measurement (1-5), 0 indicates absence of measurement
+ private SymMatrix measProjection = new SymMatrix(5); ///< Projection from measurement to local system
+ private Vector measResiduals = new Vector(5); ///< Measurement residuals
+ private Vector measPrecision = new Vector(5); ///< Measurement precision (diagonal of inverse covariance matrix)
+ private boolean transFlag; ///< Transformation exists?
+ private Matrix measTransformation; ///< Transformation of diagonalization (of meas. precision matrix)
+ private boolean scatFlag; ///< Scatterer present?
+ private SymMatrix scatTransformation = new SymMatrix(2); ///< Transformation of diagonalization (of scat. precision matrix)
+ private Vector scatResiduals = new Vector(2); ///< Scattering residuals (initial kinks if iterating)
+ private Vector scatPrecision = new Vector(2); ///< Scattering precision (diagonal of inverse covariance matrix)
+ private Matrix localDerivatives = new Matrix(0, 0); ///< Derivatives of measurement vs additional local (fit) parameters
+ private List<Integer> globalLabels = new ArrayList<Integer>(); ///< Labels of global (MP-II) derivatives
+ private Matrix globalDerivatives = new Matrix(0, 0); ///< Derivatives of measurement vs additional global (MP-II) parameters
+
+/// Create a point.
+ /**
+ * Create point on (initial) trajectory. Needs transformation jacobian from
+ * previous point. \param [in] aJacobian Transformation jacobian from
+ * previous point
+ */
+ public GblPoint(Matrix aJacobian) {
+
+ theLabel = 0;
+ theOffset = 0;
+ measDim = 0;
+ transFlag = false;
+ //measTransformation()
+ scatFlag = false;
+ //localDerivatives()
+ //globalLabels()
+ //globalDerivatives()
+
+ for (int i = 0; i < 5; ++i) {
+ for (int j = 0; j < 5; ++j) {
+ p2pJacobian.set(i, j, aJacobian.get(i, j));
+ }
+ }
+ }
+
+ public GblPoint(SymMatrix aJacobian) {
+ theLabel = 0;
+ theOffset = 0;
+ p2pJacobian = new SymMatrix(aJacobian);
+ measDim = 0;
+ transFlag = false;
+ //measTransformation()
+ scatFlag = false;
+ //localDerivatives()
+ //globalLabels()
+ //globalDerivatives()
+
+ }
+
+/// Add a measurement to a point.
+ /**
+ * Add measurement (in meas. system) with diagonal precision (inverse
+ * covariance) matrix. ((up to) 2D: position, 4D: slope+position, 5D:
+ * curvature+slope+position) \param [in] aProjection Projection from local
+ * to measurement system \param [in] aResiduals Measurement residuals \param
+ * [in] aPrecision Measurement precision (diagonal) \param [in] minPrecision
+ * Minimal precision to accept measurement
+ */
+ public void addMeasurement(Matrix aProjection,
+ Vector aResiduals, Vector aPrecision,
+ double minPrecision) {
+ measDim = aResiduals.getRowDimension();
+ int iOff = 5 - measDim;
+ for (int i = 0; i < measDim; ++i) {
+ measResiduals.set(iOff + i, aResiduals.get(i));
+ measPrecision.set(iOff + i, (aPrecision.get(i) >= minPrecision ? aPrecision.get(i) : 0.));
+ for (int j = 0; j < measDim; ++j) {
+ measProjection.set(iOff + i, iOff + j, aProjection.get(i, j));
+ }
+ }
+ }
+/// Add a measurement to a point.
+
+ /**
+ * Add measurement (in meas. system) with arbitrary precision (inverse
+ * covariance) matrix. Will be diagonalized. ((up to) 2D: position, 4D:
+ * slope+position, 5D: curvature+slope+position) \param [in] aProjection
+ * Projection from local to measurement system \param [in] aResiduals
+ * Measurement residuals \param [in] aPrecision Measurement precision
+ * (matrix) \param [in] minPrecision Minimal precision to accept measurement
+ */
+ public void addMeasurement(Matrix aProjection,
+ Vector aResiduals, SymMatrix aPrecision,
+ double minPrecision) {
+ measDim = aResiduals.getRowDimension();
+ EigenvalueDecomposition measEigen = new EigenvalueDecomposition(aPrecision);
+ measTransformation.ResizeTo(measDim, measDim);
+ measTransformation = measEigen.getV();
+ measTransformation.transposeInPlace();
+ transFlag = true;
+ Vector transResiduals = measTransformation.times(aResiduals);
+ Vector transPrecision = new Vector(measEigen.getRealEigenvalues());
+ Matrix transProjection = measTransformation.times(aProjection);
+ int iOff = 5 - measDim;
+ for (int i = 0; i < measDim; ++i) {
+ measResiduals.set(iOff + i, transResiduals.get(i));
+ measPrecision.set(iOff + i, (transPrecision.get(i) >= minPrecision ? transPrecision.get(i) : 0.));
+ for (int j = 0; j < measDim; ++j) {
+ measProjection.set(iOff + i, iOff + j, transProjection.get(i, j));
+ }
+ }
+ }
+
+/// Add a measurement to a point.
+ /**
+ * Add measurement in local system with diagonal precision (inverse
+ * covariance) matrix. ((up to) 2D: position, 4D: slope+position, 5D:
+ * curvature+slope+position) \param [in] aResiduals Measurement residuals
+ * \param [in] aPrecision Measurement precision (diagonal) \param [in]
+ * minPrecision Minimal precision to accept measurement
+ */
+ public void addMeasurement(Vector aResiduals,
+ Vector aPrecision, double minPrecision) {
+ measDim = aResiduals.getRowDimension();
+ int iOff = 5 - measDim;
+ for (int i = 0; i < measDim; ++i) {
+ measResiduals.set(iOff + i, aResiduals.get(i));
+ measPrecision.set(iOff + i,
+ aPrecision.get(i) >= minPrecision ? aPrecision.get(i) : 0.);
+ }
+ measProjection.setToIdentity();
+ }
+
+/// Add a measurement to a point.
+ /**
+ * Add measurement in local system with arbitrary precision (inverse
+ * covariance) matrix. Will be diagonalized. ((up to) 2D: position, 4D:
+ * slope+position, 5D: curvature+slope+position) \param [in] aResiduals
+ * Measurement residuals \param [in] aPrecision Measurement precision
+ * (matrix) \param [in] minPrecision Minimal precision to accept measurement
+ */
+ public void addMeasurement(Vector aResiduals,
+ SymMatrix aPrecision, double minPrecision) {
+ measDim = aResiduals.getRowDimension();
+ EigenvalueDecomposition measEigen = new EigenvalueDecomposition(aPrecision);
+ measTransformation.ResizeTo(measDim, measDim);
+ measTransformation = measEigen.getV();
+ measTransformation.transposeInPlace();
+ transFlag = true;
+ Vector transResiduals = measTransformation.times(aResiduals);
+ Vector transPrecision = new Vector(measEigen.getRealEigenvalues());
+ int iOff = 5 - measDim;
+ for (int i = 0; i < measDim; ++i) {
+ measResiduals.set(iOff + i, transResiduals.get(i));
+ measPrecision.set(iOff + i, (transPrecision.get(i)) >= minPrecision ? transPrecision.get(i) : 0.);
+ for (int j = 0; j < measDim; ++j) {
+ measProjection.set(iOff + i, iOff + j, measTransformation.get(i, j));
+ }
+ }
+ }
+
+/// Check for measurement at a point.
+ /**
+ * Get dimension of measurement (0 = none). \return measurement dimension
+ */
+ int hasMeasurement() {
+ return measDim;
+ }
+
+/// Retrieve measurement of a point.
+ /**
+ * \param [out] aProjection Projection from (diagonalized) measurement to
+ * local system \param [out] aResiduals Measurement residuals \param [out]
+ * aPrecision Measurement precision (diagonal)
+ */
+ public void getMeasurement(SymMatrix aProjection, Vector aResiduals,
+ Vector aPrecision) {
+ aProjection = measProjection;
+ aResiduals = measResiduals;
+ aPrecision = measPrecision;
+ }
+
+/// Get measurement transformation (from diagonalization).
+ /**
+ * \param [out] aTransformation Transformation matrix
+ */
+ public void getMeasTransformation(Matrix aTransformation) {
+ aTransformation.ResizeTo(measDim, measDim);
+ if (transFlag) {
+ aTransformation = measTransformation;
+ } else {
+ aTransformation.UnitMatrix();
+ }
+ }
+
+/// Add a (thin) scatterer to a point.
+ /**
+ * Add scatterer with diagonal precision (inverse covariance) matrix.
+ * Changes local track direction.
+ *
+ * \param [in] aResiduals Scatterer residuals \param [in] aPrecision
+ * Scatterer precision (diagonal of inverse covariance matrix)
+ */
+ public void addScatterer(Vector aResiduals,
+ Vector aPrecision) {
+ scatFlag = true;
+ scatResiduals.set(0, aResiduals.get(0));
+ scatResiduals.set(1, aResiduals.get(1));
+ scatPrecision.set(0, aPrecision.get(0));
+ scatPrecision.set(1, aPrecision.get(1));
+ scatTransformation.setToIdentity();
+ }
+
+/// Add a (thin) scatterer to a point.
+ /**
+ * Add scatterer with arbitrary precision (inverse covariance) matrix. Will
+ * be diagonalized. Changes local track direction.
+ *
+ * The precision matrix for the local slopes is defined by the angular
+ * scattering error theta_0 and the scalar products c_1, c_2 of the offset
+ * directions in the local frame with the track direction:
+ *
+ * (1 - c_1*c_1 - c_2*c_2) | 1 - c_1*c_1 - c_1*c_2 | P =
+ * ~~~~~~~~~~~~~~~~~~~~~~~ * | | theta_0*theta_0 | - c_1*c_2 1 - c_2*c_2 |
+ *
+ * \param [in] aResiduals Scatterer residuals \param [in] aPrecision
+ * Scatterer precision (matrix)
+ */
+ public void addScatterer(Vector aResiduals,
+ SymMatrix aPrecision) {
+ scatFlag = true;
+ EigenvalueDecomposition scatEigen = new EigenvalueDecomposition(aPrecision);
+ Matrix aTransformation = scatEigen.getEigenVectors();
+ aTransformation.transposeInPlace();
+ Vector transResiduals = aTransformation.times(aResiduals);
+ Vector transPrecision = new Vector(scatEigen.getRealEigenvalues());
+ for (int i = 0; i < 2; ++i) {
+ scatResiduals.set(i, transResiduals.get(i));
+ scatPrecision.set(i, transPrecision.get(i));
+ for (int j = 0; j < 2; ++j) {
+ scatTransformation.set(i, j, aTransformation.get(i, j));
+ }
+ }
+ }
+
+/// Check for scatterer at a point.
+ boolean hasScatterer() {
+ return scatFlag;
+ }
+
+/// Retrieve scatterer of a point.
+ /**
+ * \param [out] aTransformation Scatterer transformation from
+ * diagonalization \param [out] aResiduals Scatterer residuals \param [out]
+ * aPrecision Scatterer precision (diagonal)
+ */
+ public void getScatterer(SymMatrix aTransformation, Vector aResiduals,
+ Vector aPrecision) {
+ aTransformation = scatTransformation;
+ aResiduals = scatResiduals;
+ aPrecision = scatPrecision;
+ }
+
+/// Get scatterer transformation (from diagonalization).
+ /**
+ * \param [out] aTransformation Transformation matrix
+ */
+ public void getScatTransformation(Matrix aTransformation) {
+ aTransformation.ResizeTo(2, 2);
+ if (scatFlag) {
+ for (int i = 0; i < 2; ++i) {
+ for (int j = 0; j < 2; ++j) {
+ aTransformation.set(i, j, scatTransformation.get(i, j));
+ }
+ }
+ } else {
+ aTransformation.UnitMatrix();
+ }
+ }
+
+/// Add local derivatives to a point.
+ /**
+ * Point needs to have a measurement. \param [in] aDerivatives Local
+ * derivatives (matrix)
+ */
+ public void addLocals(Matrix aDerivatives) {
+ if (measDim != 0) {
+ localDerivatives.ResizeTo(aDerivatives.getRowDimension(), aDerivatives.getColumnDimension());
+ if (transFlag) {
+ localDerivatives = measTransformation.times(aDerivatives);
+ } else {
+ localDerivatives = aDerivatives;
+ }
+ }
+ }
+
+/// Retrieve number of local derivatives from a point.
+ int getNumLocals() {
+ return localDerivatives.getColumnDimension();
+ }
+
+/// Retrieve local derivatives from a point.
+ Matrix getLocalDerivatives() {
+ return localDerivatives;
+ }
+
+/// Add global derivatives to a point.
+ /**
+ * Point needs to have a measurement. \param [in] aLabels Global derivatives
+ * labels \param [in] aDerivatives Global derivatives (matrix)
+ */
+ public void addGlobals(List<Integer> aLabels,
+ Matrix aDerivatives) {
+ if (measDim != 0) {
+ globalLabels = aLabels;
+ globalDerivatives.ResizeTo(aDerivatives.getRowDimension(), aDerivatives.getColumnDimension());
+ if (transFlag) {
+ globalDerivatives = measTransformation.times(aDerivatives);
+ } else {
+ globalDerivatives = aDerivatives;
+ }
+
+ }
+ }
+
+/// Retrieve number of global derivatives from a point.
+ int getNumGlobals() {
+ return globalDerivatives.getColumnDimension();
+ }
+
+/// Retrieve global derivatives labels from a point.
+ List<Integer> getGlobalLabels() {
+ return globalLabels;
+ }
+
+/// Retrieve global derivatives from a point.
+ Matrix getGlobalDerivatives() {
+ return globalDerivatives;
+ }
+
+/// Define label of point (by GBLTrajectory constructor)
+ /**
+ * \param [in] aLabel Label identifying point
+ */
+ public void setLabel(int aLabel) {
+ theLabel = aLabel;
+ }
+
+/// Retrieve label of point
+ int getLabel() {
+ return theLabel;
+ }
+
+/// Define offset for point (by GBLTrajectory constructor)
+ /**
+ * \param [in] anOffset Offset number
+ */
+ public void setOffset(int anOffset) {
+ theOffset = anOffset;
+ }
+
+/// Retrieve offset for point
+ int getOffset() {
+ return theOffset;
+ }
+
+/// Retrieve point-to-(previous)point jacobian
+ Matrix getP2pJacobian() {
+ return p2pJacobian;
+ }
+
+/// Define jacobian to previous scatterer (by GBLTrajectory constructor)
+ /**
+ * \param [in] aJac Jacobian
+ */
+ public void addPrevJacobian(Matrix aJac) {
+ int ifail = 0;
+// to optimize: need only two last rows of inverse
+// prevJacobian = aJac.InverseFast(ifail);
+// block matrix algebra
+ Matrix CA = aJac.sub(2, 3, 3, 0).times(aJac.sub(3, 0, 0).inverse()); // C*A^-1
+ Matrix DCAB = aJac.sub(2, 3, 3).minus(CA.times(aJac.sub(3, 2, 0, 3))); // D - C*A^-1 *B
+ DCAB = DCAB.inverse();
+ prevJacobian.placeAt(DCAB, 3, 3);
+ prevJacobian.placeAt(DCAB.times(CA).uminus(), 3, 0);
+ }
+//
+/// Define jacobian to next scatterer (by GBLTrajectory constructor)
+
+ /**
+ * \param [in] aJac Jacobian
+ */
+ public void addNextJacobian(Matrix aJac) {
+ nextJacobian = aJac;
+ }
+
+/// Retrieve derivatives of local track model
+ /**
+ * Linearized track model: F_u(q/p,u',u) = J*u + S*u' + d*q/p, W is inverse
+ * of S, negated for backward propagation. \param [in] aDirection
+ * Propagation direction (>0 forward, else backward) \param [out] matW W
+ * \param [out] matWJ W*J \param [out] vecWd W*d \exception
+ * std::overflow_error : matrix S is singular.
+ */
+ public void getDerivatives(int aDirection, Matrix matW, Matrix matWJ,
+ Vector vecWd) {
+
+ Matrix matJ;
+ Vector vecd;
+ if (aDirection < 1) {
+ matJ = prevJacobian.sub(2, 3, 3);
+ matW = prevJacobian.sub(2, 3, 1).uminus();
+ vecd = prevJacobian.subCol(2, 0, 3);
+ } else {
+ matJ = nextJacobian.sub(2, 3, 3);
+ matW = nextJacobian.sub(2, 3, 1);
+ vecd = nextJacobian.subCol(2, 0, 3);
+ }
+
+ matW = matW.inverse();
+// if (!matW.InvertFast()) {
+// std::cout << " getDerivatives failed to invert matrix: "
+// << matW << "\n";
+// std::cout
+// << " Possible reason for singular matrix: multiple GblPoints at same arc-length"
+// << "\n";
+// throw std::overflow_error("Singular matrix inversion exception");
+// }
+ matWJ = matW.times(matJ);
+ vecWd = matW.times(vecd);
+
+ }
+//
+/// Print GblPoint
+
+ /**
+ * \param [in] level print level (0: minimum, >0: more)
+ */
+ public void printPoint(int level) {
+ StringBuffer sb = new StringBuffer("GblPoint");
+ if (theLabel != 0) {
+ sb.append(", label " + theLabel);
+ if (theOffset >= 0) {
+ sb.append(", offset " + theOffset);
+ }
+ }
+ if (measDim != 0) {
+ sb.append(", " + measDim + " measurements");
+ }
+ if (scatFlag) {
+ sb.append(", scatterer");
+ }
+ if (transFlag) {
+ sb.append(", diagonalized");
+ }
+ if (localDerivatives != null) {
+ sb.append(", " + localDerivatives.getColumnDimension()
+ + " local derivatives");
+ }
+ if (globalDerivatives != null) {
+ sb.append(", " + globalDerivatives.getColumnDimension()
+ + " global derivatives");
+ }
+ sb.append("\n");
+ if (level > 0) {
+ if (measDim != 0) {
+ sb.append(" Measurement" + "\n");
+ sb.append(" Projection: " + "\n" + measProjection
+ + "\n");
+ sb.append(" Residuals: " + measResiduals + "\n");
+ sb.append(" Precision: " + measPrecision + "\n");
+ }
+ if (scatFlag) {
+ sb.append(" Scatterer" + "\n");
+ sb.append(" Residuals: " + scatResiduals + "\n");
+ sb.append(" Precision: " + scatPrecision + "\n");
+ }
+ if (localDerivatives.getColumnDimension() != 0) {
+ sb.append(" Local Derivatives:" + "\n");
+ localDerivatives.print(4, 6);
+ }
+ if (globalDerivatives.getColumnDimension() != 0) {
+ sb.append(" Global Labels:");
+ for (int i = 0; i < globalLabels.size(); ++i) {
+ sb.append(" " + globalLabels.get(i));
+ }
+ sb.append("\n");
+ sb.append(" Global Derivatives:" + "\n");
+ globalDerivatives.print(4, 6);
+ }
+ sb.append(" Jacobian " + "\n");
+ sb.append(" Point-to-point " + "\n" + p2pJacobian
+ + "\n");
+ if (theLabel != 0) {
+ sb.append(" To previous offset " + "\n" + prevJacobian
+ + "\n");
+ sb.append(" To next offset " + "\n" + nextJacobian
+ + "\n");
+ }
+ }
+ System.out.println(sb.toString());
+ }
+
}
java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/gbl
--- java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/gbl/GblTrajectory.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/gbl/GblTrajectory.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -5,20 +5,28 @@
*
* @author Per Hansson Adrian <[log in to unmask]>
*
+ * @author Norman A Graf
+ *
+ * @version $Id:
+ *
*/
+import static java.lang.Math.max;
+import java.util.ArrayList;
import java.util.List;
+import org.hps.recon.tracking.gbl.matrix.BorderedBandMatrix;
+import org.hps.recon.tracking.gbl.matrix.Matrix;
+import org.hps.recon.tracking.gbl.matrix.SymMatrix;
+import org.hps.recon.tracking.gbl.matrix.VVector;
+import org.hps.recon.tracking.gbl.matrix.Vector;
+
public class GblTrajectory {
public GblTrajectory(List<GblPoint> listOfPoints) {
- // TODO Auto-generated constructor stub
+ this(listOfPoints, 0, new SymMatrix(0), false, false, false);
}
- public boolean isValid() {
- // TODO Auto-generated method stub
- return false;
- }
public void fit(double m_chi2, int m_ndf, int m_lost_weight) {
// TODO Auto-generated method stub
@@ -30,4 +38,1283 @@
}
+ /**
+ * \mainpage General information
+ *
+ * \section intro_sec Introduction
+ *
+ * For a track with an initial trajectory from a prefit of the measurements
+ * (internal seed) or an external prediction (external seed) the description
+ * of multiple scattering is added by offsets in a local system. Along the
+ * initial trajectory points are defined with can describe a measurement or
+ * a (thin) scatterer or both. Measurements are arbitrary functions of the
+ * local track parameters at a point (e.g. 2D: position, 4D:
+ * direction+position). The refit provides corrections to the local track
+ * parameters (in the local system) and the corresponding covariance matrix
+ * at any of those points. Non-diagonal covariance matrices will be
+ * diagonalized internally. Outliers can be down-weighted by use of
+ * M-estimators.
+ *
+ * The broken lines trajectory is defined by (2D) offsets at the first and
+ * last point and all points with a scatterer. The prediction for a
+ * measurement is obtained by interpolation of the enclosing offsets and for
+ * triplets of adjacent offsets kink angles are determined. This requires
+ * for all points the jacobians for propagation to the previous and next
+ * offset. These are calculated from the point-to-point jacobians along the
+ * initial trajectory. The sequence of points has to be strictly monotonic
+ * in arc-length.
+ *
+ * Additional local or global parameters can be added and the trajectories
+ * can be written to special binary files for calibration and alignment with
+ * Millepede-II. (V. Blobel, NIM A, 566 (2006), pp. 5-13).
+ *
+ * Besides simple trajectories describing the path of a single particle
+ * composed trajectories are supported. These are constructed from the
+ * trajectories of multiple particles and some external parameters (like
+ * those describing a decay) and transformations at the first points from
+ * the external to the local track parameters.
+ *
+ * The conventions for the coordinate systems follow: Derivation of
+ * Jacobians for the propagation of covariance matrices of track parameters
+ * in homogeneous magnetic fields A. Strandlie, W. Wittek, NIM A, 566 (2006)
+ * 687-698.
+ *
+ * \section call_sec Calling sequence
+ *
+ * -# Create list of points on initial trajectory:\n
+ * <tt>List<GblPoint> list</tt>
+ * -# For all points on initial trajectory: - Create points and add
+ * appropriate attributes:\n - <tt>point = gbl::GblPoint(..)</tt>
+ * - <tt>point.addMeasurement(..)</tt>
+ * - Add additional local or global parameters to measurement:\n -
+ * <tt>point.addLocals(..)</tt>
+ * - <tt>point.addGlobals(..)</tt>
+ * - <tt>point.addScatterer(..)</tt>
+ * - Add point (ordered by arc length) to list:\n
+ * <tt>list.add(point)</tt>
+ * -# Create (simple) trajectory from list of points:\n
+ * <tt>traj = gbl::GblTrajectory (list)</tt>
+ * -# Optionally with external seed:\n
+ * <tt>traj = gbl::GblTrajectory (list,seed)</tt>
+ * -# Optionally check validity of trajectory:\n
+ * <tt>if (not traj.isValid()) .. //abort</tt>
+ * -# Fit trajectory, return error code, get Chi2, Ndf (and weight lost by
+ * M-estimators):\n
+ * <tt>ierr = traj.fit(..)</tt>
+ * -# For any point on initial trajectory: - Get corrections and covariance
+ * matrix for track parameters:\n
+ * <tt>[..] = traj.getResults(label)</tt>
+ * -# Optionally write trajectory to MP binary file:\n
+ * <tt>traj.milleOut(..)</tt>
+ *
+ * \section loc_sec Local system and local parameters At each point on the
+ * trajectory a local coordinate system with local track parameters has to
+ * be defined. The first of the five parameters describes the bending, the
+ * next two the direction and the last two the position (offsets). The
+ * curvilinear system (T,U,V) with parameters (q/p, lambda, phi, x_t, y_t)
+ * is well suited.
+ *
+ * \section impl_sec Implementation
+ *
+ * Matrices are implemented with ROOT (root.cern.ch). User input or output
+ * is in the form of TMatrices. Internally SMatrices are used for fixes
+ * sized and simple matrices based on List<> for variable sized matrices.
+ *
+ * \section ref_sec References - V. Blobel, C. Kleinwort, F. Meier, Fast
+ * alignment of a complex tracking detector using advanced track models,
+ * Computer Phys. Communications (2011), doi:10.1016/j.cpc.2011.03.017 - C.
+ * Kleinwort, General Broken Lines as advanced track fitting method, NIM A,
+ * 673 (2012), 107-110, doi:10.1016/j.nima.2012.01.024
+ */
+ int numAllPoints; ///< Number of all points on trajectory
+ List< Integer> numPoints = new ArrayList<Integer>(); ///< Number of points on (sub)trajectory
+ int numTrajectories; ///< Number of trajectories (in composed trajectory)
+ int numOffsets; ///< Number of (points with) offsets on trajectory
+ int numInnerTrans; ///< Number of inner transformations to external parameters
+ int numCurvature; ///< Number of curvature parameters (0 or 1) or external parameters
+ int numParameters; ///< Number of fit parameters
+ int numLocals; ///< Total number of (additional) local parameters
+ int numMeasurements; ///< Total number of measurements
+ int externalPoint; ///< Label of external point (or 0)
+ boolean constructOK; ///< Trajectory has been successfully constructed (ready for fit/output)
+ boolean fitOK; ///< Trajectory has been successfully fitted (results are valid)
+ List< Integer> theDimension = new ArrayList<Integer>(); ///< List of active dimensions (0=u1, 1=u2) in fit
+ List<List<GblPoint>> thePoints = new ArrayList<List<GblPoint>>(); ///< (list of) List of points on trajectory
+ List<GblData> theData = new ArrayList<GblData>(); ///< List of data blocks
+ List<Integer> measDataIndex = new ArrayList<Integer>(); ///< mapping points to data blocks from measurements
+ List<Integer> scatDataIndex; ///< mapping points to data blocks from scatterers
+ List<Integer> externalIndex; ///< List of fit parameters used by external seed
+ SymMatrix externalSeed; ///< Precision (inverse covariance matrix) of external seed
+ List<Matrix> innerTransformations; ///< Transformations at innermost points of
+ // composed trajectory (from common external parameters)
+ Matrix externalDerivatives; // Derivatives for external measurements of composed trajectory
+ Vector externalMeasurements; // Residuals for external measurements of composed trajectory
+ Vector externalPrecisions; // Precisions for external measurements of composed trajectory
+ VVector theVector; ///< Vector of linear equation system
+ BorderedBandMatrix theMatrix = new BorderedBandMatrix(); ///< (Bordered band) matrix of linear equation system
+
+///// Create new (simple) trajectory from list of points.
+// /**
+// * Curved trajectory in space (default) or without curvature (q/p) or in one
+// * plane (u-direction) only. \param [in] aPointList List of points \param
+// * [in] flagCurv Use q/p \param [in] flagU1dir Use in u1 direction \param
+// * [in] flagU2dir Use in u2 direction
+// */
+// GblTrajectory(List<GblPoint> aPointList,
+// boolean flagCurv, boolean flagU1dir, boolean flagU2dir)
+// {
+// numAllPoints = aPointList.size();
+// //numPoints()
+// numOffsets = 0;
+// numInnerTrans = 0;
+// numCurvature = (flagCurv ? 1 : 0);
+// numParameters = 0;
+// numLocals = 0;
+// numMeasurements = 0;
+// externalPoint = 0;
+// //externalSeed()
+// //innerTransformations()
+// //externalDerivatives()
+// //externalMeasurements()
+// // externalPrecisions()
+//
+// if (flagU1dir)
+// {
+// theDimension.add(0);
+// }
+// if (flagU2dir)
+// {
+// theDimension.add(1);
+// }
+// // simple (single) trajectory
+// thePoints.add(aPointList);
+// numPoints.add(numAllPoints);
+//// construct(); // construct trajectory
+// }
+/// Create new (simple) trajectory from list of points with external seed.
+ /**
+ * Curved trajectory in space (default) or without curvature (q/p) or in one
+ * plane (u-direction) only. \param [in] aPointList List of points \param
+ * [in] aLabel (Signed) label of point for external seed (<0: in front, >0:
+ * after point, slope changes at scatterer!) \param [in] aSeed Precision
+ * matrix of external seed \param [in] flagCurv Use q/p \param [in]
+ * flagU1dir Use in u1 direction \param [in] flagU2dir Use in u2 direction
+ */
+ GblTrajectory(List<GblPoint> aPointList,
+ int aLabel, SymMatrix aSeed, boolean flagCurv,
+ boolean flagU1dir, boolean flagU2dir)
+ {
+ numAllPoints = aPointList.size();
+ //numPoints(),
+ numOffsets = 0;
+ numInnerTrans = 0;
+ numCurvature = (flagCurv ? 1 : 0);
+ numParameters = 0;
+ numLocals = 0;
+ numMeasurements = 0;
+ //externalPoint(aLabel)
+ //theDimension(),
+ //thePoints(),
+ //theData(),
+ //measDataIndex(),
+ //scatDataIndex(),
+ //externalIndex(),
+ //externalSeed(aSeed),
+ //innerTransformations(),
+ //externalDerivatives(),
+ //externalMeasurements(),
+ //externalPrecisions() {
+
+ if (flagU1dir)
+ {
+ theDimension.add(0);
+ }
+ if (flagU2dir)
+ {
+ theDimension.add(1);
+ }
+ // simple (single) trajectory
+ thePoints.add(aPointList);
+ numPoints.add(numAllPoints);
+ construct(); // construct trajectory
+ }
+
+///// Create new composed trajectory from list of points and transformations.
+///**
+// * Composed of curved trajectory in space.
+// * \param [in] aPointsAndTransList List containing pairs with list of points and transformation (at inner (first) point)
+// */
+//GblTrajectory(
+// const List<std::pair<List<GblPoint>, TMatrixD> > &aPointsAndTransList) :
+// numAllPoints(), numPoints(), numOffsets(0), numInnerTrans(
+// aPointsAndTransList.size()), numParameters(0), numLocals(0), numMeasurements(
+// 0), externalPoint(0), theDimension(0), thePoints(), theData(), measDataIndex(), scatDataIndex(), externalIndex(), externalSeed(), innerTransformations(), externalDerivatives(), externalMeasurements(), externalPrecisions() {
+//
+// for ( int iTraj = 0; iTraj < aPointsAndTransList.size(); ++iTraj) {
+// thePoints.add(aPointsAndTransList[iTraj].first);
+// numPoints.add(thePoints.back().size());
+// numAllPoints += numPoints.back();
+// innerTransformations.add(aPointsAndTransList[iTraj].second);
+// }
+// theDimension.add(0);
+// theDimension.add(1);
+// numCurvature = innerTransformations[0].GetNcols();
+// construct(); // construct (composed) trajectory
+//}
+//
+///// Create new composed trajectory from list of points and transformations with (independent) external measurements.
+///**
+// * Composed of curved trajectory in space.
+// * \param [in] aPointsAndTransList List containing pairs with list of points and transformation (at inner (first) point)
+// * \param [in] extDerivatives Derivatives of external measurements vs external parameters
+// * \param [in] extMeasurements External measurements (residuals)
+// * \param [in] extPrecisions Precision of external measurements
+// */
+//GblTrajectory(
+// const List<std::pair<List<GblPoint>, TMatrixD> > &aPointsAndTransList,
+// const TMatrixD &extDerivatives, const TVectorD &extMeasurements,
+// const TVectorD &extPrecisions) :
+// numAllPoints(), numPoints(), numOffsets(0), numInnerTrans(
+// aPointsAndTransList.size()), numParameters(0), numLocals(0), numMeasurements(
+// 0), externalPoint(0), theDimension(0), thePoints(), theData(), measDataIndex(), scatDataIndex(), externalIndex(), externalSeed(), innerTransformations(), externalDerivatives(
+// extDerivatives), externalMeasurements(extMeasurements), externalPrecisions(
+// extPrecisions) {
+//
+// for ( int iTraj = 0; iTraj < aPointsAndTransList.size(); ++iTraj) {
+// thePoints.add(aPointsAndTransList[iTraj].first);
+// numPoints.add(thePoints.back().size());
+// numAllPoints += numPoints.back();
+// innerTransformations.add(aPointsAndTransList[iTraj].second);
+// }
+// theDimension.add(0);
+// theDimension.add(1);
+// numCurvature = innerTransformations[0].GetNcols();
+// construct(); // construct (composed) trajectory
+//}
+//
+//~GblTrajectory() {
+//}
+//
+/// Retrieve validity of trajectory
+ boolean isValid()
+ {
+ return constructOK;
+ }
+
+/// Retrieve number of point from trajectory
+ int getNumPoints()
+ {
+ return numAllPoints;
+ }
+
+/// Construct trajectory from list of points.
+ /**
+ * Trajectory is prepared for fit or output to binary file, may consists of
+ * sub-trajectories.
+ */
+ void construct()
+ {
+
+ constructOK = false;
+ fitOK = false;
+ int aLabel = 0;
+ // loop over trajectories
+ numTrajectories = thePoints.size();
+ //std::cout << " numTrajectories: " << numTrajectories << ", "<< innerTransformations.size() << std::endl;
+// for ( int iTraj = 0; iTraj < numTrajectories; ++iTraj) {
+// List<GblPoint>::iterator itPoint;
+// for (itPoint = thePoints[iTraj].begin();
+// itPoint < thePoints[iTraj].end(); ++itPoint) {
+// numLocals = std::max(numLocals, itPoint->getNumLocals());
+// numMeasurements += itPoint->hasMeasurement();
+// itPoint->setLabel(++aLabel);
+// }
+// }
+ for (List<GblPoint> list : thePoints)
+ {
+ for (GblPoint p : list)
+ {
+ numLocals = max(numLocals, p.getNumLocals());
+ numMeasurements += p.hasMeasurement();
+ p.setLabel(++aLabel);
+ }
+ }
+ defineOffsets();
+ calcJacobians();
+// try {
+ prepare();
+// } catch (std::overflow_error &e) {
+// std::cout << " GblTrajectory construction failed: " << e.what()
+// << std::endl;
+// return;
+// }
+ constructOK = true;
+ // number of fit parameters
+ numParameters = (numOffsets - 2 * numInnerTrans) * theDimension.size()
+ + numCurvature + numLocals;
+ }
+//
+/// Define offsets from list of points.
+
+ /**
+ * Define offsets at points with scatterers and first and last point. All
+ * other points need interpolation from adjacent points with offsets.
+ */
+ void defineOffsets()
+ {
+
+ // loop over trajectories
+ for (int iTraj = 0; iTraj < numTrajectories; ++iTraj)
+ {
+ List<GblPoint> list = thePoints.get(iTraj);
+ int size = list.size();
+ // first point is offset
+// thePoints[iTraj].front().setOffset(numOffsets++);
+ list.get(0).setOffset(numOffsets++); // intermediate scatterers are offsets
+// List<GblPoint>::iterator itPoint;
+// for (itPoint = thePoints[iTraj].begin() + 1;
+// itPoint < thePoints[iTraj].end() - 1; ++itPoint) {
+// if (itPoint->hasScatterer()) {
+// itPoint->setOffset(numOffsets++);
+// } else {
+// itPoint->setOffset(-numOffsets);
+// }
+// }
+ for (int i = 1; i < size - 1; ++i)
+ {
+ GblPoint p = list.get(i);
+ if (p.hasScatterer())
+ {
+ p.setOffset(numOffsets++);
+ } else
+ {
+ p.setOffset(-numOffsets);
+ }
+
+ }
+ // last point is offset
+// thePoints[iTraj].back().setOffset(numOffsets++);
+ list.get(size - 1).setOffset(numOffsets++);
+ }
+ }
+
+/// Calculate Jacobians to previous/next scatterer from point to point ones.
+ void calcJacobians()
+ {
+
+ Matrix scatJacobian = new Matrix(5, 5);
+ // loop over trajectories
+ for (int iTraj = 0; iTraj < numTrajectories; ++iTraj)
+ {
+ List<GblPoint> list = thePoints.get(iTraj);
+ int size = list.size();
+ // forward propagation (all)
+ GblPoint previousPoint = list.get(0);
+ int numStep = 0;
+ for (int i = 1; i < size; ++i)
+ {
+ GblPoint p = list.get(i);
+ if (numStep == 0)
+ {
+ scatJacobian = p.getP2pJacobian();
+ } else
+ {
+ scatJacobian = p.getP2pJacobian().times(scatJacobian);
+ }
+ numStep++;
+ p.addPrevJacobian(scatJacobian);// iPoint -> previous scatterer
+ if (p.getOffset() >= 0)
+ {
+ previousPoint.addNextJacobian(scatJacobian); // lastPoint -> next scatterer
+ numStep = 0;
+ previousPoint = p;
+ }
+ }
+// List<GblPoint>::iterator itPoint;
+// for (itPoint = thePoints[iTraj].begin() + 1;
+// itPoint < thePoints[iTraj].end(); ++itPoint)
+// {
+// if (numStep == 0)
+// {
+// scatJacobian = itPoint -> getP2pJacobian();
+// } else
+// {
+// scatJacobian = itPoint -> getP2pJacobian() * scatJacobian;
+// }
+// numStep++;
+// itPoint -> addPrevJacobian(scatJacobian); // iPoint -> previous scatterer
+// if (itPoint -> getOffset() >= 0)
+// {
+// previousPoint -> addNextJacobian(scatJacobian); // lastPoint -> next scatterer
+// numStep = 0;
+// previousPoint = & ( * itPoint);
+// }
+// }
+// // backward propagation (without scatterers)
+// for (itPoint = thePoints[iTraj].end() - 1;
+// itPoint > thePoints[iTraj].begin(); --itPoint)
+// {
+// if (itPoint -> getOffset() >= 0)
+// {
+// scatJacobian = itPoint -> getP2pJacobian();
+// continue; // skip offsets
+// }
+// itPoint -> addNextJacobian(scatJacobian); // iPoint -> next scatterer
+// scatJacobian = scatJacobian * itPoint -> getP2pJacobian();
+// }
+ // backward propagation (without scatterers)
+ for (int i = size - 1; i > 0; --i)
+ {
+ GblPoint p = list.get(i);
+ if (p.getOffset() >= 0)
+ {
+ scatJacobian = p.getP2pJacobian();
+ continue; // skip offsets
+ }
+ p.addNextJacobian(scatJacobian); // iPoint -> next scatterer
+ scatJacobian = scatJacobian.times(p.getP2pJacobian());
+ }
+ }
+ }
+//
+///// Get jacobian for transformation from fit to track parameters at point.
+///**
+// * Jacobian broken lines (q/p,..,u_i,u_i+1..) to track (q/p,u',u) parameters
+// * including additional local parameters.
+// * \param [in] aSignedLabel (Signed) label of point for external seed
+// * (<0: in front, >0: after point, slope changes at scatterer!)
+// * \return List of fit parameters with non zero derivatives and
+// * corresponding transformation matrix
+// */
+//std::pair<List< int>, TMatrixD> getJacobian(
+// int aSignedLabel) const {
+//
+// int nDim = theDimension.size();
+// int nCurv = numCurvature;
+// int nLocals = numLocals;
+// int nBorder = nCurv + nLocals;
+// int nParBRL = nBorder + 2 * nDim;
+// int nParLoc = nLocals + 5;
+// List< int> anIndex;
+// anIndex.reserve(nParBRL);
+// TMatrixD aJacobian(nParLoc, nParBRL);
+// aJacobian.Zero();
+//
+// int aLabel = abs(aSignedLabel);
+// int firstLabel = 1;
+// int lastLabel = 0;
+// int aTrajectory = 0;
+// // loop over trajectories
+// for ( int iTraj = 0; iTraj < numTrajectories; ++iTraj) {
+// aTrajectory = iTraj;
+// lastLabel += numPoints[iTraj];
+// if (aLabel <= lastLabel)
+// break;
+// if (iTraj < numTrajectories - 1)
+// firstLabel += numPoints[iTraj];
+// }
+// int nJacobian; // 0: prev, 1: next
+// // check consistency of (index, direction)
+// if (aSignedLabel > 0) {
+// nJacobian = 1;
+// if (aLabel >= lastLabel) {
+// aLabel = lastLabel;
+// nJacobian = 0;
+// }
+// } else {
+// nJacobian = 0;
+// if (aLabel <= firstLabel) {
+// aLabel = firstLabel;
+// nJacobian = 1;
+// }
+// }
+// const GblPoint aPoint = thePoints[aTrajectory][aLabel - firstLabel];
+// List< int> labDer(5);
+// SMatrix55 matDer;
+// getFitToLocalJacobian(labDer, matDer, aPoint, 5, nJacobian);
+//
+// // from local parameters
+// for ( int i = 0; i < nLocals; ++i) {
+// aJacobian(i + 5, i) = 1.0;
+// anIndex.add(i + 1);
+// }
+// // from trajectory parameters
+// int iCol = nLocals;
+// for ( int i = 0; i < 5; ++i) {
+// if (labDer[i] > 0) {
+// anIndex.add(labDer[i]);
+// for ( int j = 0; j < 5; ++j) {
+// aJacobian(j, iCol) = matDer(j, i);
+// }
+// ++iCol;
+// }
+// }
+// return std::make_pair(anIndex, aJacobian);
+//}
+
+/// Get (part of) jacobian for transformation from (trajectory) fit to track parameters at point.
+ /**
+ * Jacobian broken lines (q/p,..,u_i,u_i+1..) to local (q/p,u',u)
+ * parameters. \param [out] anIndex List of fit parameters with non zero
+ * derivatives \param [out] aJacobian Corresponding transformation matrix
+ * \param [in] aPoint Point to use \param [in] measDim Dimension of
+ * 'measurement' (<=2: calculate only offset part, >2: complete matrix)
+ * \param [in] nJacobian Direction (0: to previous offset, 1: to next
+ * offset)
+ */
+ void getFitToLocalJacobian(List<Integer> anIndex,
+ Matrix aJacobian, GblPoint aPoint, int measDim,
+ int nJacobian)
+ {
+
+ int nDim = theDimension.size();
+ int nCurv = numCurvature;
+ int nLocals = numLocals;
+
+ int nOffset = aPoint.getOffset();
+
+ if (nOffset < 0) // need interpolation
+ {
+ Matrix prevW = new Matrix(2, 2);
+ Matrix prevWJ = new Matrix(2, 2);
+ Matrix nextW = new Matrix(2, 2);
+ Matrix nextWJ = new Matrix(2, 2);
+ Matrix matN = new Matrix(2, 2);
+ Vector prevWd = new Vector(2);
+ Vector nextWd = new Vector(2);
+ int ierr;
+ aPoint.getDerivatives(0, prevW, prevWJ, prevWd); // W-, W- * J-, W- * d-
+ aPoint.getDerivatives(1, nextW, nextWJ, nextWd); // W-, W- * J-, W- * d-
+ Matrix sumWJ = prevWJ.plus(nextWJ);
+//? matN = sumWJ.inverse(ierr); // N = (W- * J- + W+ * J+)^-1
+ // derivatives for u_int
+ Matrix prevNW = matN.times(prevW); // N * W-
+ Matrix nextNW = matN.times(nextW); // N * W+
+ Vector prevNd = matN.times(prevWd); // N * W- * d-
+ Vector nextNd = matN.times(nextWd); // N * W+ * d+
+
+ int iOff = nDim * (-nOffset - 1) + nLocals + nCurv + 1; // first offset ('i' in u_i)
+
+ // local offset
+ if (nCurv > 0)
+ {
+ Vector negDiff = prevNd.minus(nextNd).uminus();
+ aJacobian.placeInCol(negDiff, 3, 0); // from curvature
+ anIndex.set(0, nLocals + 1);
+ }
+ aJacobian.placeAt(prevNW, 3, 1); // from 1st Offset
+ aJacobian.placeAt(nextNW, 3, 3); // from 2nd Offset
+ for (int i = 0; i < nDim; ++i)
+ {
+ anIndex.set(1 + theDimension.get(i), iOff + i);
+ anIndex.set(3 + theDimension.get(i), iOff + nDim + i);
+ }
+//
+//// // local slope and curvature
+//// if (measDim > 2) {
+//// // derivatives for u'_int
+//// const SMatrix22 prevWPN(nextWJ * prevNW); // W+ * J+ * N * W-
+//// const SMatrix22 nextWPN(prevWJ * nextNW); // W- * J- * N * W+
+//// const SVector2 prevWNd(nextWJ * prevNd); // W+ * J+ * N * W- * d-
+//// const SVector2 nextWNd(prevWJ * nextNd); // W- * J- * N * W+ * d+
+//// if (nCurv > 0) {
+//// aJacobian(0, 0) = 1.0;
+//// aJacobian.Place_in_col(prevWNd - nextWNd, 1, 0); // from curvature
+//// }
+//// aJacobian.Place_at(-prevWPN, 1, 1); // from 1st Offset
+//// aJacobian.Place_at(nextWPN, 1, 3); // from 2nd Offset
+//// }
+// } else { // at point
+ // anIndex must be sorted
+ // forward : iOff2 = iOff1 + nDim, index1 = 1, index2 = 3
+ // backward: iOff2 = iOff1 - nDim, index1 = 3, index2 = 1
+ int iOff1 = nDim * nOffset + nCurv + nLocals + 1; // first offset ('i' in u_i)
+ int index1 = 3 - 2 * nJacobian; // index of first offset
+ int iOff2 = iOff1 + nDim * (nJacobian * 2 - 1); // second offset ('i' in u_i)
+ int index2 = 1 + 2 * nJacobian; // index of second offset
+ // local offset
+ aJacobian.set(3, index1, 1.0); // from 1st Offset
+ aJacobian.set(4, index1 + 1, 1.0);
+ for (int i = 0; i < nDim; ++i)
+ {
+ anIndex.set(index1 + theDimension.get(i), iOff1 + i);
+ }
+
+ // local slope and curvature
+ if (measDim > 2)
+ {
+ Matrix matW = new Matrix(2, 2);
+ Matrix matWJ = new Matrix(2, 2);
+ Vector vecWd = new Vector(2);
+ aPoint.getDerivatives(nJacobian, matW, matWJ, vecWd); // W, W * J, W * d
+ double sign = (nJacobian > 0) ? 1. : -1.;
+ if (nCurv > 0)
+ {
+ aJacobian.set(0, 0, 1.0);
+ aJacobian.placeInCol(vecWd.timesScalar(-sign), 1, 0); // from curvature
+ anIndex.set(0, nLocals + 1);
+ }
+ aJacobian.placeAt(matWJ.times(-sign), 1, index1); // from 1st Offset
+ aJacobian.placeAt(matW.times(sign), 1, index2); // from 2nd Offset
+ for (int i = 0; i < nDim; ++i)
+ {
+ anIndex.set(index2 + theDimension.get(i), iOff2 + i);
+ }
+ }
+ }
+ }
+
+/// Get jacobian for transformation from (trajectory) fit to kink parameters at point.
+ /**
+ * Jacobian broken lines (q/p,..,u_i-1,u_i,u_i+1..) to kink (du')
+ * parameters. \param [out] anIndex List of fit parameters with non zero
+ * derivatives \param [out] aJacobian Corresponding transformation matrix
+ * \param [in] aPoint Point to use
+ */
+ void getFitToKinkJacobian(List< Integer> anIndex,
+ Matrix aJacobian, GblPoint aPoint)
+ {
+
+ //nb aJacobian has dimension 2,7
+ int nDim = theDimension.size();
+ int nCurv = numCurvature;
+ int nLocals = numLocals;
+
+ int nOffset = aPoint.getOffset();
+
+ Matrix prevW = new Matrix(2, 2);
+ Matrix prevWJ = new Matrix(2, 2);
+ Matrix nextW = new Matrix(2, 2);
+ Matrix nextWJ = new Matrix(2, 2);
+ Vector prevWd = new Vector(2);
+ Vector nextWd = new Vector(2);
+ aPoint.getDerivatives(0, prevW, prevWJ, prevWd); // W-, W- * J-, W- * d-
+ aPoint.getDerivatives(1, nextW, nextWJ, nextWd); // W-, W- * J-, W- * d-
+ Matrix sumWJ = prevWJ.plus(nextWJ); // W- * J- + W+ * J+
+ Vector sumWd = prevWd.plus(nextWd); // W+ * d+ + W- * d-
+
+ int iOff = (nOffset - 1) * nDim + nCurv + nLocals + 1; // first offset ('i' in u_i)
+
+ // local offset
+ if (nCurv > 0)
+ {
+ aJacobian.placeInCol(sumWd.uminus(), 0, 0); // from curvature
+ anIndex.set(0, nLocals + 1);
+ }
+ aJacobian.placeAt(prevW, 0, 1); // from 1st Offset
+ aJacobian.placeAt(sumWJ.uminus(), 0, 3); // from 2nd Offset
+ aJacobian.placeAt(nextW, 0, 5); // from 1st Offset
+ for (int i = 0; i < nDim; ++i)
+ {
+ anIndex.set(1 + theDimension.get(i), iOff + i);
+ anIndex.set(3 + theDimension.get(i), iOff + nDim + i);
+ anIndex.set(5 + theDimension.get(i), iOff + nDim * 2 + i);
+ }
+ }
+
+///// Get fit results at point.
+///**
+// * Get corrections and covariance matrix for local track and additional parameters
+// * in forward or backward direction.
+// * \param [in] aSignedLabel (Signed) label of point on trajectory
+// * (<0: in front, >0: after point, slope changes at scatterer!)
+// * \param [out] localPar Corrections for local parameters
+// * \param [out] localCov Covariance for local parameters
+// * \return error code (non-zero if trajectory not fitted successfully)
+// */
+// int getResults(int aSignedLabel, TVectorD &localPar,
+// SymMatrix &localCov) const {
+// if (! fitOK)
+// return 1;
+// std::pair<List< int>, TMatrixD> indexAndJacobian =
+// getJacobian(aSignedLabel);
+// int nParBrl = indexAndJacobian.first.size();
+// TVectorD aVec(nParBrl); // compressed vector
+// for ( int i = 0; i < nParBrl; ++i) {
+// aVec[i] = theVector(indexAndJacobian.first[i] - 1);
+// }
+// SymMatrix aMat = theMatrix.getBlockMatrix(indexAndJacobian.first); // compressed matrix
+// localPar = indexAndJacobian.second * aVec;
+// localCov = aMat.Similarity(indexAndJacobian.second);
+// return 0;
+//}
+//
+///// Get residuals at point from measurement.
+///**
+// * Get (diagonalized) residual, error of measurement and residual and down-weighting
+// * factor for measurement at point
+// *
+// * \param [in] aLabel Label of point on trajectory
+// * \param [out] numData Number of data blocks from measurement at point
+// * \param [out] aResiduals Measurements-Predictions
+// * \param [out] aMeasErrors Errors of Measurements
+// * \param [out] aResErrors Errors of Residuals (including correlations from track fit)
+// * \param [out] aDownWeights Down-Weighting factors
+// * \return error code (non-zero if trajectory not fitted successfully)
+// */
+// int getMeasResults( int aLabel,
+// int &numData, TVectorD &aResiduals, TVectorD &aMeasErrors,
+// TVectorD &aResErrors, TVectorD &aDownWeights) {
+// numData = 0;
+// if (! fitOK)
+// return 1;
+//
+// int firstData = measDataIndex[aLabel - 1]; // first data block with measurement
+// numData = measDataIndex[aLabel] - firstData; // number of data blocks
+// for ( int i = 0; i < numData; ++i) {
+// getResAndErr(firstData + i, aResiduals[i], aMeasErrors[i],
+// aResErrors[i], aDownWeights[i]);
+// }
+// return 0;
+//}
+//
+///// Get (kink) residuals at point from scatterer.
+///**
+// * Get (diagonalized) residual, error of measurement and residual and down-weighting
+// * factor for scatterering kinks at point
+// *
+// * \param [in] aLabel Label of point on trajectory
+// * \param [out] numData Number of data blocks from scatterer at point
+// * \param [out] aResiduals (kink)Measurements-(kink)Predictions
+// * \param [out] aMeasErrors Errors of (kink)Measurements
+// * \param [out] aResErrors Errors of Residuals (including correlations from track fit)
+// * \param [out] aDownWeights Down-Weighting factors
+// * \return error code (non-zero if trajectory not fitted successfully)
+// */
+// int getScatResults( int aLabel,
+// int &numData, TVectorD &aResiduals, TVectorD &aMeasErrors,
+// TVectorD &aResErrors, TVectorD &aDownWeights) {
+// numData = 0;
+// if (! fitOK)
+// return 1;
+//
+// int firstData = scatDataIndex[aLabel - 1]; // first data block with scatterer
+// numData = scatDataIndex[aLabel] - firstData; // number of data blocks
+// for ( int i = 0; i < numData; ++i) {
+// getResAndErr(firstData + i, aResiduals[i], aMeasErrors[i],
+// aResErrors[i], aDownWeights[i]);
+// }
+// return 0;
+//}
+//
+///// Get (list of) labels of points on (simple) trajectory
+///**
+// * \param [out] aLabelList List of labels (aLabelList[i] = i+1)
+// */
+//void getLabels(List< int> &aLabelList) {
+// int aLabel = 0;
+// int nPoint = thePoints[0].size();
+// aLabelList.resize(nPoint);
+// for ( i = 0; i < nPoint; ++i) {
+// aLabelList[i] = ++aLabel;
+// }
+//}
+//
+///// Get (list of lists of) labels of points on (composed) trajectory
+///**
+// * \param [out] aLabelList List of of lists of labels
+// */
+//void getLabels(
+// List<List< int> > &aLabelList) {
+// int aLabel = 0;
+// aLabelList.resize(numTrajectories);
+// for ( int iTraj = 0; iTraj < numTrajectories; ++iTraj) {
+// int nPoint = thePoints[iTraj].size();
+// aLabelList[iTraj].resize(nPoint);
+// for ( i = 0; i < nPoint; ++i) {
+// aLabelList[iTraj][i] = ++aLabel;
+// }
+// }
+//}
+//
+///// Get residual and errors from data block.
+///**
+// * Get residual, error of measurement and residual and down-weighting
+// * factor for (single) data block
+// * \param [in] aData Label of data block
+// * \param [out] aResidual Measurement-Prediction
+// * \param [out] aMeasError Error of Measurement
+// * \param [out] aResError Error of Residual (including correlations from track fit)
+// * \param [out] aDownWeight Down-Weighting factor
+// */
+//void getResAndErr( int aData, double &aResidual,
+// double &aMeasError, double &aResError, double &aDownWeight) {
+//
+// double aMeasVar;
+// List< int>* indLocal;
+// List<double>* derLocal;
+// theData[aData].getResidual(aResidual, aMeasVar, aDownWeight, indLocal,
+// derLocal);
+// int nParBrl = (*indLocal).size();
+// TVectorD aVec(nParBrl); // compressed vector of derivatives
+// for ( int j = 0; j < nParBrl; ++j) {
+// aVec[j] = (*derLocal)[j];
+// }
+// SymMatrix aMat = theMatrix.getBlockMatrix(*indLocal); // compressed (covariance) matrix
+// double aFitVar = aMat.Similarity(aVec); // variance from track fit
+// aMeasError = sqrt(aMeasVar); // error of measurement
+// aResError = (aFitVar < aMeasVar ? sqrt(aMeasVar - aFitVar) : 0.); // error of residual
+//}
+/// Build linear equation system from data (blocks).
+ void buildLinearEquationSystem()
+ {
+ int nBorder = numCurvature + numLocals;
+// theVector. resize(numParameters);
+ theMatrix.resize(numParameters, nBorder, 5);
+ double[] retVals = new double[2];
+ double aValue, aWeight;
+ int[] indLocal = null;
+ double[] derLocal = null;
+ for (GblData d : theData)
+ {
+ d.getLocalData(retVals, indLocal, derLocal);
+ aValue = retVals[0];
+ aWeight = retVals[1];
+ for (int j = 0; j < indLocal.length; ++j)
+ {
+ theVector.addTo(indLocal[j] - 1, derLocal[j] * aWeight * aValue);
+ }
+ theMatrix.addBlockMatrix(aWeight, indLocal, derLocal);
+ }
+ }
+//}
+
+/// Prepare fit for simple or composed trajectory
+/**
+ * Generate data (blocks) from measurements, kinks, external seed and measurements.
+ */
+void prepare() {
+ int nDim = theDimension.size();
+ // upper limit
+ int maxData = numMeasurements + nDim * (numOffsets - 2);
+//cng + externalSeed.getRowDimension();
+// theData.reserve(maxData);
+// measDataIndex.resize(numAllPoints + 3); // include external seed and measurements
+ //cng
+ for(int i = 0; i<numAllPoints + 3; ++i) measDataIndex.add(i,0);
+ //cng
+// scatDataIndex.resize(numAllPoints + 1);
+ int nData = 0;
+ List<Matrix> innerTransDer = new ArrayList<Matrix>();
+ List<List<Integer> > innerTransLab = new ArrayList<List<Integer>>();
+// // composed trajectory ?
+// if (numInnerTrans > 0) {
+// //std::cout << "composed trajectory" << std::endl;
+// for ( int iTraj = 0; iTraj < numTrajectories; ++iTraj) {
+// // innermost point
+// GblPoint* innerPoint = &thePoints[iTraj].front();
+// // transformation fit to local track parameters
+// List< int> firstLabels(5);
+// SMatrix55 matFitToLocal, matLocalToFit;
+// getFitToLocalJacobian(firstLabels, matFitToLocal, *innerPoint, 5);
+// // transformation local track to fit parameters
+// int ierr;
+// matLocalToFit = matFitToLocal.Inverse(ierr);
+// TMatrixD localToFit(5, 5);
+// for ( int i = 0; i < 5; ++i) {
+// for ( int j = 0; j < 5; ++j) {
+// localToFit(i, j) = matLocalToFit(i, j);
+// }
+// }
+// // transformation external to fit parameters at inner (first) point
+// innerTransDer.add(localToFit * innerTransformations[iTraj]);
+// innerTransLab.add(firstLabels);
+// }
+// }
+ // measurements
+ Matrix matP = new Matrix(5,5);
+// // loop over trajectories
+// List<GblPoint>::iterator itPoint;
+// for ( int iTraj = 0; iTraj < numTrajectories; ++iTraj) {
+// for (itPoint = thePoints[iTraj].begin();
+// itPoint < thePoints[iTraj].end(); ++itPoint) {
+// SVector5 aMeas, aPrec;
+// int nLabel = itPoint->getLabel();
+// int measDim = itPoint->hasMeasurement();
+// if (measDim) {
+// const TMatrixD localDer = itPoint->getLocalDerivatives();
+// const List<int> globalLab = itPoint->getGlobalLabels();
+// const TMatrixD globalDer = itPoint->getGlobalDerivatives();
+// TMatrixD transDer;
+// itPoint->getMeasurement(matP, aMeas, aPrec);
+// int iOff = 5 - measDim; // first active component
+// List< int> labDer(5);
+// SMatrix55 matDer, matPDer;
+// int nJacobian =
+// (itPoint < thePoints[iTraj].end() - 1) ? 1 : 0; // last point needs backward propagation
+// getFitToLocalJacobian(labDer, matDer, *itPoint, measDim,
+// nJacobian);
+// if (measDim > 2) {
+// matPDer = matP * matDer;
+// } else { // 'shortcut' for position measurements
+// matPDer.Place_at(
+// matP.Sub<SMatrix22>(3, 3)
+// * matDer.Sub<SMatrix25>(3, 0), 3, 0);
+// }
+//
+//// if (numInnerTrans > 0) {
+//// // transform for external parameters
+//// TMatrixD proDer(measDim, 5);
+//// // match parameters
+//// int ifirst = 0;
+//// int ilabel = 0;
+//// while (ilabel < 5) {
+//// if (labDer[ilabel] > 0) {
+//// while (innerTransLab[iTraj][ifirst]
+//// != labDer[ilabel] && ifirst < 5) {
+//// ++ifirst;
+//// }
+//// if (ifirst >= 5) {
+//// labDer[ilabel] -= 2 * nDim * (iTraj + 1); // adjust label
+//// } else {
+//// // match
+//// labDer[ilabel] = 0; // mark as related to external parameters
+//// for ( int k = iOff; k < 5; ++k) {
+//// proDer(k - iOff, ifirst) = matPDer(k,
+//// ilabel);
+//// }
+//// }
+//// }
+//// ++ilabel;
+//// }
+//// transDer.ResizeTo(measDim, numCurvature);
+//// transDer = proDer * innerTransDer[iTraj];
+//// }
+// for ( int i = iOff; i < 5; ++i) {
+// if (aPrec(i) > 0.) {
+// GblData aData(nLabel, aMeas(i), aPrec(i));
+// aData.addDerivatives(i, labDer, matPDer, iOff, localDer,
+// globalLab, globalDer, numLocals, transDer);
+// theData.add(aData);
+// nData++;
+// }
+// }
+//
+// }
+// measDataIndex[nLabel] = nData;
+// }
+// } // end loop over trajectories
+
+// // pseudo measurements from kinks
+// SMatrix22 matT;
+// scatDataIndex[0] = nData;
[truncated at 1000 lines; 320 more skipped]
java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/gbl
--- java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/gbl/HpsGblFitter.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/tracking/src/main/java/org/hps/recon/tracking/gbl/HpsGblFitter.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -35,249 +35,245 @@
import org.lcsim.recon.tracking.seedtracker.SeedCandidate;
import org.lcsim.recon.tracking.seedtracker.SeedTrack;
-
/**
* Class to running GBL on HPS track.
- *
+ *
* @author phansson
+ *
+ * @version $Id:
*
*/
public class HpsGblFitter {
-
- private boolean _debug = false;
- private double _B = 0.;
- private double _bfac = 0.;
- private boolean isMC = false;
- TrackerHitUtils _trackHitUtils = null;
- MultipleScattering _scattering = null;
- private double m_chi2 = -1.;
- private int m_ndf = -1;
- private int m_lost_weight = -1;
- GblTrajectory _traj = null;
- MilleBinary _mille = null;
-
+ private boolean _debug = true;
+ private double _B = 0.;
+ private double _bfac = 0.;
+ private boolean isMC = false;
+ TrackerHitUtils _trackHitUtils = null;
+ MultipleScattering _scattering = null;
+ private double m_chi2 = -1.;
+ private int m_ndf = -1;
+ private int m_lost_weight = -1;
+ GblTrajectory _traj = null;
+ MilleBinary _mille = null;
-
- public HpsGblFitter(double Bz, MultipleScattering scattering, boolean isMCFlag) {
- isMC = isMCFlag;
- _B = Bz;
- _bfac = Bz * Constants.fieldConversion;
- _trackHitUtils = new TrackerHitUtils();
- _scattering = scattering;
- }
-
- public void setMilleBinary(MilleBinary mille) {
- _mille = mille;
- }
-
- public void clear() {
- m_chi2 = -1.;
- m_ndf = -1;
- m_lost_weight = -1;
- _traj = null;
- }
+ public HpsGblFitter() {
+ _B = -0.5;
+ _bfac = _B * Constants.fieldConversion;
+ _trackHitUtils = new TrackerHitUtils();
+ _scattering = new MultipleScattering(new MaterialSupervisor());
+ System.out.println("Default constructor");
+ }
- public int Fit(Track track) {
-
+ public HpsGblFitter(double Bz, MultipleScattering scattering, boolean isMCFlag) {
+ isMC = isMCFlag;
+ _B = Bz;
+ _bfac = Bz * Constants.fieldConversion;
+ _trackHitUtils = new TrackerHitUtils();
+ _scattering = scattering;
+ System.out.println("Constructor");
+ }
- // Check that things are setup
- if(_B == 0.) {
- System.out.printf("%s: B-field not set!\n", this.getClass().getSimpleName());
- return -1;
- }
- if(_scattering == null) {
- System.out.printf("%s: Multiple scattering calculator not set!\n", this.getClass().getSimpleName());
- return -2;
- }
-
- // Time the fits
- //clock_t startTime = clock();
+ public void setMilleBinary(MilleBinary mille) {
+ _mille = mille;
+ }
-
-
- // path length along trajectory
- double s = 0.;
- // jacobian to transport errors between points along the path
- BasicMatrix jacPointToPoint = GblUtils.getInstance().unitMatrix(5, 5);
- // Option to use uncorrelated MS errors
- // This is similar to what is done in lcsim seedtracker
- // The msCov below holds the MS errors
- // This is for testing purposes only.
- boolean useUncorrMS = false;
- BasicMatrix msCov = GblUtils.getInstance().zeroMatrix(5, 5);
-
- // Vector of the strip clusters used for the GBL fit
- List<GblPoint> listOfPoints = new ArrayList<GblPoint>();
-
- // Store the projection from local to measurement frame for each strip cluster
- // need to use pointer for TMatrix here?
- Map<Integer, Matrix> proL2m_list = new HashMap<Integer, Matrix>();
- // Save the association between strip cluster and label
- Map<HelicalTrackStrip, Integer> stripLabelMap = new HashMap<HelicalTrackStrip, Integer>();
-
- //start trajectory at refence point (s=0) - this point has no measurement
- GblPoint ref_point = new GblPoint(jacPointToPoint);
- listOfPoints.add(ref_point);
-
- //Create a list of all the strip clusters making up the track
- List<HelicalTrackStrip> stripClusters = new ArrayList<HelicalTrackStrip>();
- SeedCandidate seed = ((SeedTrack) track).getSeedCandidate();
- HelicalTrackFit htf = seed.getHelix();
- List<HelicalTrackHit> stereoHits = seed.getHits();
- for(int ihit = 0; ihit < stereoHits.size(); ++ihit) {
- HelicalTrackCross cross = (HelicalTrackCross) stereoHits.get(ihit);
- stripClusters.add(cross.getStrips().get(0));
- stripClusters.add(cross.getStrips().get(1));
- }
-
- // sort the clusters along path
- // TODO use actual path length and not layer id!
- //Collections.sort(stripClusters, new HelicalTrackStripComparer());
- Collections.sort(stripClusters, new Comparator<HelicalTrackStrip>() {
- public int compare(HelicalTrackStrip o1, HelicalTrackStrip o2) {
- return o1.layer() < o2.layer() ? -1 : o1.layer() > o2.layer() ? 1 : 0;
- }
- });
+ public void clear() {
+ m_chi2 = -1.;
+ m_ndf = -1;
+ m_lost_weight = -1;
+ _traj = null;
+ }
- if(_debug ) {
- System.out.printf("%s: %d strip clusters:\n", stripClusters.size());
- for(int istrip=0;istrip<stripClusters.size();++istrip) {
- System.out.printf("%s: layer %d origin %s\n", stripClusters.get(istrip).layer(),stripClusters.get(istrip).origin().toString());
- }
- }
+ public int Fit(Track track) {
-
- // Find scatter points along the path of the track
+ // Check that things are setup
+ if (_B == 0.) {
+ System.out.printf("%s: B-field not set!\n", this.getClass().getSimpleName());
+ return -1;
+ }
+ if (_scattering == null) {
+ System.out.printf("%s: Multiple scattering calculator not set!\n", this.getClass().getSimpleName());
+ return -2;
+ }
+
+ // Time the fits
+ //clock_t startTime = clock();
+ // path length along trajectory
+ double s = 0.;
+ // jacobian to transport errors between points along the path
+ BasicMatrix jacPointToPoint = GblUtils.getInstance().unitMatrix(5, 5);
+ // Option to use uncorrelated MS errors
+ // This is similar to what is done in lcsim seedtracker
+ // The msCov below holds the MS errors
+ // This is for testing purposes only.
+ boolean useUncorrMS = false;
+ BasicMatrix msCov = GblUtils.getInstance().zeroMatrix(5, 5);
+
+ // Vector of the strip clusters used for the GBL fit
+ List<GblPoint> listOfPoints = new ArrayList<GblPoint>();
+
+ // Store the projection from local to measurement frame for each strip cluster
+ // need to use pointer for TMatrix here?
+ Map<Integer, Matrix> proL2m_list = new HashMap<Integer, Matrix>();
+ // Save the association between strip cluster and label
+ Map<HelicalTrackStrip, Integer> stripLabelMap = new HashMap<HelicalTrackStrip, Integer>();
+
+ //start trajectory at refence point (s=0) - this point has no measurement
+ GblPoint ref_point = new GblPoint(jacPointToPoint);
+ listOfPoints.add(ref_point);
+
+ //Create a list of all the strip clusters making up the track
+ List<HelicalTrackStrip> stripClusters = new ArrayList<HelicalTrackStrip>();
+ SeedCandidate seed = ((SeedTrack) track).getSeedCandidate();
+ HelicalTrackFit htf = seed.getHelix();
+ List<HelicalTrackHit> stereoHits = seed.getHits();
+ for (int ihit = 0; ihit < stereoHits.size(); ++ihit) {
+ HelicalTrackCross cross = (HelicalTrackCross) stereoHits.get(ihit);
+ stripClusters.add(cross.getStrips().get(0));
+ stripClusters.add(cross.getStrips().get(1));
+ }
+
+ // sort the clusters along path
+ // TODO use actual path length and not layer id!
+ //Collections.sort(stripClusters, new HelicalTrackStripComparer());
+ Collections.sort(stripClusters, new Comparator<HelicalTrackStrip>() {
+ public int compare(HelicalTrackStrip o1, HelicalTrackStrip o2) {
+ return o1.layer() < o2.layer() ? -1 : o1.layer() > o2.layer() ? 1 : 0;
+ }
+ });
+
+ if (_debug) {
+ System.out.printf(" %d strip clusters:\n", stripClusters.size());
+ for (int istrip = 0; istrip < stripClusters.size(); ++istrip) {
+ System.out.printf("layer %d origin %s\n", stripClusters.get(istrip).layer(), stripClusters.get(istrip).origin().toString());
+ }
+ }
+
+ // Find scatter points along the path of the track
ScatterPoints scatters = _scattering.FindHPSScatterPoints(htf);
-
-
- if(_debug ) {
- System.out.printf("%s: Process %d strip clusters\n", stripClusters.size());
- }
- for(int istrip=0;istrip<stripClusters.size();++istrip) {
-
- HelicalTrackStrip strip = stripClusters.get(istrip);
-
- if(_debug) {
- System.out.printf("%s: layer %d origin %s\n", strip.layer(),strip.origin().toString());
- }
-
- //Find intercept point with sensor in tracking frame
+
+ if (_debug) {
+ System.out.printf(" Process %d strip clusters\n", stripClusters.size());
+ }
+ for (int istrip = 0; istrip < stripClusters.size(); ++istrip) {
+
+ HelicalTrackStrip strip = stripClusters.get(istrip);
+
+ if (_debug) {
+ System.out.printf(" layer %d origin %s\n", strip.layer(), strip.origin().toString());
+ }
+
+ //Find intercept point with sensor in tracking frame
Hep3Vector trkpos = TrackUtils.getHelixPlaneIntercept(htf, strip, Math.abs(_B));
- if(_debug) {
- System.out.printf("trkpos at intercept [%.10f %.10f %.10f]\n",trkpos.x(),trkpos.y(),trkpos.z());
+ if (_debug) {
+ System.out.printf("trkpos at intercept [%.10f %.10f %.10f]\n", trkpos.x(), trkpos.y(), trkpos.z());
}
-
- //path length to intercept
- double path = HelixUtils.PathToXPlane(htf,trkpos.x(),0,0).get(0);
+
+ //path length to intercept
+ double path = HelixUtils.PathToXPlane(htf, trkpos.x(), 0, 0).get(0);
double path3D = path / Math.cos(Math.atan(htf.slope()));
-
-
- // Path length step for this cluster
- double step = path3D - s;
-
- if( _debug ) {
- System.out.printf("%s: Path length step %f from %f to %f\n",this.getClass().getSimpleName(),step, s, path3D);
- }
-
- // Measurement direction (perpendicular and parallel to strip direction)
- BasicMatrix mDir = new BasicMatrix(2,3);
- mDir.setElement(0, 0, strip.u().x());
- mDir.setElement(0, 1, strip.u().y());
- mDir.setElement(0, 2, strip.u().z());
- mDir.setElement(1, 0, strip.v().x());
- mDir.setElement(1, 1, strip.v().y());
- mDir.setElement(1, 2, strip.v().z());
-
- Matrix mDirT = MatrixOp.transposed(mDir); //new BasicMatrix(MatrixOp.transposed(mDir));
- if(_debug) {
- System.out.printf("%s: mDir \n%s\n",this.getClass().getSimpleName(),mDir.toString());
- System.out.printf("%s: mDirT \n%s\n",this.getClass().getSimpleName(),mDirT.toString());
- }
-
- // Track direction
- double sinLambda = Math.sin(Math.atan(htf.slope()));
- double cosLambda = Math.sqrt(1.0 - sinLambda*sinLambda);
- double sinPhi = Math.sin(htf.phi0());
- double cosPhi = Math.sqrt(1.0 - sinPhi*sinPhi);
-
- // Track direction in curvilinear frame (U,V,T)
- // U = Z x T / |Z x T|, V = T x U
- BasicMatrix uvDir = new BasicMatrix(2,3);
- uvDir.setElement(0, 0, -sinPhi);
- uvDir.setElement(0, 1, cosPhi);
- uvDir.setElement(0, 2, 0.);
- uvDir.setElement(1, 0, -sinLambda * cosPhi);
- uvDir.setElement(1, 1, -sinLambda * sinPhi);
- uvDir.setElement(1, 2, cosLambda);
-
- if(_debug) {
- System.out.printf("%s: uvDir \n%s\n",this.getClass().getSimpleName(),uvDir.toString());
- }
+ // Path length step for this cluster
+ double step = path3D - s;
- // projection from measurement to local (curvilinear uv) directions (duv/dm)
- Matrix proM2l = MatrixOp.mult(uvDir, mDirT); //uvDir * mDirT;
-
- //projection from local (curvilinear uv) to measurement directions (dm/duv)
- Matrix proL2m = MatrixOp.inverse(proM2l);
-
- //proL2m_list[strip->GetId()] = new TMatrixD(proL2m);
+ if (_debug) {
+ System.out.printf("%s Path length step %f from %f to %f\n", this.getClass().getSimpleName(), step, s, path3D);
+ }
- if(_debug) {
- System.out.printf("%s: proM2l \n%s\n",this.getClass().getSimpleName(),proM2l.toString());
- System.out.printf("%s: proL2m \n%s\n",this.getClass().getSimpleName(),proL2m.toString());
- }
-
- // measurement/residual in the measurement system
-
+ // Measurement direction (perpendicular and parallel to strip direction)
+ BasicMatrix mDir = new BasicMatrix(2, 3);
+ mDir.setElement(0, 0, strip.u().x());
+ mDir.setElement(0, 1, strip.u().y());
+ mDir.setElement(0, 2, strip.u().z());
+ mDir.setElement(1, 0, strip.v().x());
+ mDir.setElement(1, 1, strip.v().y());
+ mDir.setElement(1, 2, strip.v().z());
+
+ Matrix mDirT = MatrixOp.transposed(mDir); //new BasicMatrix(MatrixOp.transposed(mDir));
+ if (_debug) {
+ System.out.printf(" mDir \n%s\n", this.getClass().getSimpleName(), mDir.toString());
+ System.out.printf(" mDirT \n%s\n", this.getClass().getSimpleName(), mDirT.toString());
+ }
+
+ // Track direction
+ double sinLambda = Math.sin(Math.atan(htf.slope()));
+ double cosLambda = Math.sqrt(1.0 - sinLambda * sinLambda);
+ double sinPhi = Math.sin(htf.phi0());
+ double cosPhi = Math.sqrt(1.0 - sinPhi * sinPhi);
+
+ // Track direction in curvilinear frame (U,V,T)
+ // U = Z x T / |Z x T|, V = T x U
+ BasicMatrix uvDir = new BasicMatrix(2, 3);
+ uvDir.setElement(0, 0, -sinPhi);
+ uvDir.setElement(0, 1, cosPhi);
+ uvDir.setElement(0, 2, 0.);
+ uvDir.setElement(1, 0, -sinLambda * cosPhi);
+ uvDir.setElement(1, 1, -sinLambda * sinPhi);
+ uvDir.setElement(1, 2, cosLambda);
+
+ if (_debug) {
+ System.out.printf(" uvDir \n%s\n", this.getClass().getSimpleName(), uvDir.toString());
+ }
+
+ // projection from measurement to local (curvilinear uv) directions (duv/dm)
+ Matrix proM2l = MatrixOp.mult(uvDir, mDirT); //uvDir * mDirT;
+
+ //projection from local (curvilinear uv) to measurement directions (dm/duv)
+ Matrix proL2m = MatrixOp.inverse(proM2l);
+
+ //proL2m_list[strip->GetId()] = new TMatrixD(proL2m);
+ if (_debug) {
+ System.out.printf(" proM2l \n%s\n", this.getClass().getSimpleName(), proM2l.toString());
+ System.out.printf(" proL2m \n%s\n", this.getClass().getSimpleName(), proL2m.toString());
+ }
+
+ // measurement/residual in the measurement system
// start by find the distance vector between the center and the track position
Hep3Vector vdiffTrk = VecOp.sub(trkpos, strip.origin());
-
+
// then find the rotation from tracking to measurement frame
Hep3Matrix trkToStripRot = _trackHitUtils.getTrackToStripRotation(strip);
-
+
// then rotate that vector into the measurement frame to get the predicted measurement position
Hep3Vector trkpos_meas = VecOp.mult(trkToStripRot, vdiffTrk);
-
+
// hit measurement and uncertainty in measurement frame
- Hep3Vector m_meas = new BasicHep3Vector(strip.umeas(),0.,0.);
-
+ Hep3Vector m_meas = new BasicHep3Vector(strip.umeas(), 0., 0.);
+
// finally the residual
Hep3Vector res_meas = VecOp.sub(m_meas, trkpos_meas);
- Hep3Vector res_err_meas = new BasicHep3Vector(strip.du(),(strip.vmax() - strip.vmin()) / Math.sqrt(12),10.0/Math.sqrt(12));
+ Hep3Vector res_err_meas = new BasicHep3Vector(strip.du(), (strip.vmax() - strip.vmin()) / Math.sqrt(12), 10.0 / Math.sqrt(12));
// Move to matrix objects instead of 3D vectors
// TODO use only one type
-
- // only 1D measurement in u-direction, set strip measurement direction to zero
- BasicMatrix meas = new BasicMatrix(0,2);
- meas.setElement(0, 0, res_meas.x());
- meas.setElement(0, 1, 0.);
+ // only 1D measurement in u-direction, set strip measurement direction to zero
+ BasicMatrix meas = new BasicMatrix(1, 2);
+ meas.setElement(0, 0, res_meas.x());
+ meas.setElement(0, 1, 0.);
// //meas[0][0] += deltaU[iLayer] # misalignment
- BasicMatrix measErr = new BasicMatrix(0,2);
- measErr.setElement(0, 0, res_err_meas.x());
- measErr.setElement(0, 1, 0.);
+ BasicMatrix measErr = new BasicMatrix(1, 2);
+ measErr.setElement(0, 0, res_err_meas.x());
+ measErr.setElement(0, 1, 0.);
- BasicMatrix measPrec = new BasicMatrix(0,2);
- measPrec.setElement(0, 0, 1.0/( measErr.e(0, 0) * measErr.e(0, 0)));
- measPrec.setElement(0, 1, 0.);
- if (_debug) {
- System.out.printf("%s: meas \n%s\n",this.getClass().getSimpleName(),meas.toString());
- System.out.printf("%s: measErr \n%s\n",this.getClass().getSimpleName(),measErr.toString());
- System.out.printf("%s: measPrec \n%s\n",this.getClass().getSimpleName(),measPrec.toString());
+ BasicMatrix measPrec = new BasicMatrix(1, 2);
+ measPrec.setElement(0, 0, 1.0 / (measErr.e(0, 0) * measErr.e(0, 0)));
+ measPrec.setElement(0, 1, 0.);
+ if (_debug) {
+ System.out.printf("%s: meas \n%s\n", this.getClass().getSimpleName(), meas.toString());
+ System.out.printf("%s: measErr \n%s\n", this.getClass().getSimpleName(), measErr.toString());
+ System.out.printf("%s: measPrec \n%s\n", this.getClass().getSimpleName(), measPrec.toString());
}
//Find the Jacobian to be able to propagate the covariance matrix to this strip position
jacPointToPoint = GblUtils.getInstance().gblSimpleJacobianLambdaPhi(step, cosLambda, Math.abs(_bfac));
-
- if(_debug) {
- System.out.printf("%s: jacPointToPoint \n%s\n",this.getClass().getSimpleName(),jacPointToPoint.toString());
+
+ if (_debug) {
+ System.out.printf("%s: jacPointToPoint \n%s\n", this.getClass().getSimpleName(), jacPointToPoint.toString());
}
-
- //propagate MS covariance matrix (in the curvilinear frame) to this strip position
+
+ //propagate MS covariance matrix (in the curvilinear frame) to this strip position
//msCov = np.dot(jacPointToPoint, np.dot(msCov, jacPointToPoint.T))
//measMsCov = np.dot(proL2m, np.dot(msCov[3:, 3:], proL2m.T))
// if (m_debug) {
@@ -286,187 +282,172 @@
// //cout << "HpsGblFitter: " << "measMsCov at this point:" << endl;
// //measMsCov.Print();
// }
-
//Option to blow up measurement error according to multiple scattering
//if useUncorrMS:
//measPrec[0] = 1.0 / (measErr[0] ** 2 + measMsCov[0, 0])
// if debug:
//print 'Adding measMsCov ', measMsCov[0,0]
-
// point with independent measurement
GblPoint point = new GblPoint(jacPointToPoint);
//Add measurement to the point
- point.addMeasurement(proL2m,meas,measPrec);
+ point.addMeasurement(proL2m, meas, measPrec);
-
//Add scatterer in curvilinear frame to the point
// no direction in this frame as it moves along the track
- BasicMatrix scat = GblUtils.getInstance().zeroMatrix(0,2);
+ BasicMatrix scat = GblUtils.getInstance().zeroMatrix(0, 2);
// find scattering angle
- ScatterPoint scatter = scatters.getScatterPoint(((RawTrackerHit)strip.rawhits().get(0)).getDetectorElement());
+ ScatterPoint scatter = scatters.getScatterPoint(((RawTrackerHit) strip.rawhits().get(0)).getDetectorElement());
double scatAngle;
-
- if(scatter != null) {
- scatAngle = scatter.getScatterAngle().Angle();
- }
- else {
- System.out.printf("%s: WARNING cannot find scatter for detector %s with strip cluster at %s\n",this.getClass(),((RawTrackerHit)strip.rawhits().get(0)).getDetectorElement().getName(),strip.origin().toString());
+
+ if (scatter != null) {
+ scatAngle = scatter.getScatterAngle().Angle();
+ } else {
+ System.out.printf("%s: WARNING cannot find scatter for detector %s with strip cluster at %s\n", this.getClass(), ((RawTrackerHit) strip.rawhits().get(0)).getDetectorElement().getName(), strip.origin().toString());
//can be edge case where helix is outside, but close to sensor, so use hack with the sensor origin closest to hit
//TODO check if this really makes sense to do
DetectorPlane closest = null;
double dx = 999999.9;
- if(MaterialSupervisor.class.isInstance(_scattering.getMaterialManager())) {
- MaterialSupervisor matSup = (MaterialSupervisor)_scattering.getMaterialManager();
- for(ScatteringDetectorVolume vol : matSup.getMaterialVolumes()) {
- DetectorPlane plane = (DetectorPlane)vol;
+ if (MaterialSupervisor.class.isInstance(_scattering.getMaterialManager())) {
+ MaterialSupervisor matSup = (MaterialSupervisor) _scattering.getMaterialManager();
+ for (ScatteringDetectorVolume vol : matSup.getMaterialVolumes()) {
+ DetectorPlane plane = (DetectorPlane) vol;
double dx_loop = Math.abs(strip.origin().x() - plane.origin().x());
- if(dx_loop<dx) {
+ if (dx_loop < dx) {
dx = dx_loop;
closest = plane;
}
}
- if(closest==null) {
+ if (closest == null) {
throw new RuntimeException("cannot find any plane that is close to strip!");
} else {
// find scatterlength
- double s_closest = HelixUtils.PathToXPlane(htf,closest.origin().x(), 0., 0).get(0);
+ double s_closest = HelixUtils.PathToXPlane(htf, closest.origin().x(), 0., 0).get(0);
double X0 = closest.getMaterialTraversedInRL(HelixUtils.Direction(htf, s_closest));
- ScatterAngle scatterAngle = new ScatterAngle(s_closest, _scattering.msangle(htf.p(Math.abs(_B)),X0));
+ ScatterAngle scatterAngle = new ScatterAngle(s_closest, _scattering.msangle(htf.p(Math.abs(_B)), X0));
scatAngle = scatterAngle.Angle();
}
- }
- else {
+ } else {
throw new UnsupportedOperationException("Should not happen. This problem is only solved with the MaterialSupervisor.");
}
}
-
-
+
// Scattering angle in the curvilinear frame
//Note the cosLambda to correct for the projection in the phi direction
- BasicMatrix scatErr = new BasicMatrix(0,2);
+ BasicMatrix scatErr = new BasicMatrix(1, 2);
scatErr.setElement(0, 0, scatAngle);
scatErr.setElement(0, 1, scatAngle / cosLambda);
- BasicMatrix scatPrec = new BasicMatrix(0,2);
+ BasicMatrix scatPrec = new BasicMatrix(1, 2);
scatPrec.setElement(0, 0, 1.0 / (scatErr.e(0, 0) * scatErr.e(0, 0)));
scatPrec.setElement(0, 1, 1.0 / (scatErr.e(0, 1) * scatErr.e(0, 1)));
-
+
// add scatterer if not using the uncorrelated MS covariances for testing
- if (! useUncorrMS) {
- point.addScatterer(scat, scatPrec);
- if (_debug) {
- System.out.printf("%s: scatError to this point \n%s\n",this.getClass().getSimpleName(),scatErr.toString());
- }
+ if (!useUncorrMS) {
+ point.addScatterer(scat, scatPrec);
+ if (_debug) {
+ System.out.printf("%s: scatError to this point \n%s\n", this.getClass().getSimpleName(), scatErr.toString());
+ }
}
-
+
// Add this GBL point to list that will be used in fit
listOfPoints.add(point);
int iLabel = listOfPoints.size();
-
+
// Update MS covariance matrix
- msCov.setElement(1, 1, msCov.e(1, 1) + scatErr.e(0, 0)*scatErr.e(0, 0));
- msCov.setElement(2, 2, msCov.e(2, 2) + scatErr.e(0, 1)*scatErr.e(0, 1));
-
-
-
+ msCov.setElement(1, 1, msCov.e(1, 1) + scatErr.e(0, 0) * scatErr.e(0, 0));
+ msCov.setElement(2, 2, msCov.e(2, 2) + scatErr.e(0, 1) * scatErr.e(0, 1));
+
/*
- #####
- ## Calculate global derivatives for this point
- # track direction in tracking/global frame
- tDirGlobal = np.array( [ [cosPhi * cosLambda, sinPhi * cosLambda, sinLambda] ] )
- # Cross-check that the input is consistent
- if( np.linalg.norm( tDirGlobal - strip.tDir) > 0.00001):
- print 'ERROR: tDirs are not consistent!'
- sys.exit(1)
- # rotate track direction to measurement frame
- tDirMeas = np.dot( tDirGlobal, np.array([strip.u, strip.v, strip.w]) )
- #tDirMeas = utils.rotateGlToMeas(strip,tDirGlobal)
- normalMeas = np.dot( strip.w , np.array([strip.u, strip.v, strip.w]) )
- #normalMeas = utils.rotateGlToMeas(strip,strip.w)
- # non-measured directions
- vmeas = 0.
- wmeas = 0.
- # calculate and add derivatives to point
- glDers = utils.globalDers(strip.layer,strip.meas,vmeas,wmeas,tDirMeas,normalMeas)
- ders = glDers.getDers(track.isTop())
- labGlobal = ders['labels']
- addDer = ders['ders']
- if debug:
- print 'global derivatives:'
- print labGlobal
- print addDer
- point.addGlobals(labGlobal, addDer)
- #####
+ #####
+ ## Calculate global derivatives for this point
+ # track direction in tracking/global frame
+ tDirGlobal = np.array( [ [cosPhi * cosLambda, sinPhi * cosLambda, sinLambda] ] )
+ # Cross-check that the input is consistent
+ if( np.linalg.norm( tDirGlobal - strip.tDir) > 0.00001):
+ print 'ERROR: tDirs are not consistent!'
+ sys.exit(1)
+ # rotate track direction to measurement frame
+ tDirMeas = np.dot( tDirGlobal, np.array([strip.u, strip.v, strip.w]) )
+ #tDirMeas = utils.rotateGlToMeas(strip,tDirGlobal)
+ normalMeas = np.dot( strip.w , np.array([strip.u, strip.v, strip.w]) )
+ #normalMeas = utils.rotateGlToMeas(strip,strip.w)
+ # non-measured directions
+ vmeas = 0.
+ wmeas = 0.
+ # calculate and add derivatives to point
+ glDers = utils.globalDers(strip.layer,strip.meas,vmeas,wmeas,tDirMeas,normalMeas)
+ ders = glDers.getDers(track.isTop())
+ labGlobal = ders['labels']
+ addDer = ders['ders']
+ if debug:
+ print 'global derivatives:'
+ print labGlobal
+ print addDer
+ point.addGlobals(labGlobal, addDer)
+ #####
*/
-
-
-
//move on to next point
s += step;
-
+
// save strip and label map
//stripLabelMap[strip] = iLabel;
+ }
+
+ //create the trajectory
+ _traj = new GblTrajectory(listOfPoints); //,seedLabel, clSeed);
+
+ if (!_traj.isValid()) {
+ System.out.printf("%s: Invalid GblTrajectory -> skip \n", this.getClass().getSimpleName());
+ return -3;
+ }
+
+ // fit trajectory
+ _traj.fit(m_chi2, m_ndf, m_lost_weight);
-
-
+ //cng
+// System.out.println("fitting the traectory...");
+// double[] retDVals = new double[2];
+// int[] retIVals = new int[1];
+// int success = _traj.fit(retDVals, retIVals, "");
+ //cng
-
-
-
- }
-
+ if (_debug) {
+ System.out.printf("%s: Chi2 Fit: %f , %d , %d\n", this.getClass().getSimpleName(), m_chi2, m_ndf, m_lost_weight);
+ }
- //create the trajectory
- _traj = new GblTrajectory(listOfPoints); //,seedLabel, clSeed);
-
- if (! _traj.isValid()) {
- System.out.printf("%s: Invalid GblTrajectory -> skip \n",this.getClass().getSimpleName());
- return -3;
- }
-
- // fit trajectory
- _traj.fit(m_chi2, m_ndf, m_lost_weight);
-
- if( _debug ) {
- System.out.printf("%s: Chi2 Fit: %f , %d , %d\n",this.getClass().getSimpleName(), m_chi2, m_ndf,m_lost_weight);
- }
-
- // write to MP binary file
- if(_mille != null) {
- _traj.milleOut(_mille);
- }
-
- //stop the clock
- //clock_t endTime = clock();
- //double diff = endTime - startTime;
- //double cps = CLOCKS_PER_SEC;
- //if( m_debug ) {
- // std::cout << "HpsGblFitter: " << " Time elapsed " << diff / cps << " s" << std::endl;
- //}
+ // write to MP binary file
+ if (_mille != null) {
+ _traj.milleOut(_mille);
+ }
- if(_debug) {
- System.out.printf("%s: Fit() done successfully.\n",this.getClass().getSimpleName());
- }
-
- return 0;
- }
-
+ //stop the clock
+ //clock_t endTime = clock();
+ //double diff = endTime - startTime;
+ //double cps = CLOCKS_PER_SEC;
+ //if( m_debug ) {
+ // std::cout << "HpsGblFitter: " << " Time elapsed " << diff / cps << " s" << std::endl;
+ //}
+ if (_debug) {
+ System.out.printf("%s: Fit() done successfully.\n", this.getClass().getSimpleName());
+ }
- public static class HelicalTrackStripComparer implements Comparator<HelicalTrackStrip> {
- public int compare(HelicalTrackStrip o1, HelicalTrackStrip o2) {
- // TODO Change this to path length!?
- return compare(o1.layer(),o2.layer());
- }
-
- private static int compare(int s1, int s2) {
- return s1 < s2 ? -1 : s2 > s1 ? 1 : 0;
- }
-
-
- }
+ return 0;
+ }
+ public static class HelicalTrackStripComparer implements Comparator<HelicalTrackStrip> {
+ public int compare(HelicalTrackStrip o1, HelicalTrackStrip o2) {
+ // TODO Change this to path length!?
+ return compare(o1.layer(), o2.layer());
+ }
+
+ private static int compare(int s1, int s2) {
+ return s1 < s2 ? -1 : s2 > s1 ? 1 : 0;
+ }
+
+ }
+
}
java/branches/hps-java_HPSJAVA-88/users
--- java/branches/hps-java_HPSJAVA-88/users/pom.xml 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/users/pom.xml 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,30 +1,25 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-
<modelVersion>4.0.0</modelVersion>
<artifactId>hps-users</artifactId>
<name>users</name>
<description>user code packages</description>
-
<parent>
<groupId>org.hps</groupId>
<artifactId>hps-parent</artifactId>
<relativePath>../parent/pom.xml</relativePath>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</parent>
-
<scm>
<url>http://java.freehep.org/svn/repos/hps/list/java/trunk/users/</url>
<connection>scm:svn:svn://svn.freehep.org/hps/java/trunk/users/</connection>
<developerConnection>scm:svn:svn://svn.freehep.org/hps/java/trunk/users/</developerConnection>
</scm>
-
<dependencies>
<dependency>
<groupId>org.hps</groupId>
<artifactId>hps-analysis</artifactId>
</dependency>
</dependencies>
-
<build>
<plugins>
<plugin>
@@ -33,10 +28,10 @@
<configuration>
<excludes>
<exclude>org/hps/users/jeremym/MockDataChallengeDiagnosticDriverTest.java</exclude>
+ <exclude>org/hps/users/ngraf/NearestNeighborClusterDriverTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
-
</project>
java/branches/hps-java_HPSJAVA-88/users/src/main/java/org/hps/users/jeremym
--- java/branches/hps-java_HPSJAVA-88/users/src/main/java/org/hps/users/jeremym/MockDataChallengeDiagnosticDriver.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/users/src/main/java/org/hps/users/jeremym/MockDataChallengeDiagnosticDriver.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -76,7 +76,8 @@
}
}
}
-
+
+ /*
@Override
protected void endOfData() {
try {
@@ -85,6 +86,7 @@
throw new RuntimeException(e);
}
}
+ */
@Override
public void process(EventHeader event) {
java/branches/hps-java_HPSJAVA-88/users/src/main/java/org/hps/users/luca
--- java/branches/hps-java_HPSJAVA-88/users/src/main/java/org/hps/users/luca/CalibTest2.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/users/src/main/java/org/hps/users/luca/CalibTest2.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -83,7 +83,7 @@
eneMCallPlot.fill(particle.getEnergy());
if(particle.getPDGID()==11)
{eneEminusPlot.fill(particle.getEnergy());}
- if(particle.getPDGID()==1 && particle.getEnergy()>2.150)
+ if(particle.getPDGID()==11 && particle.getEnergy()>2.150)
{eneCoulombEPlot.fill(particle.getEnergy());}
java/branches/hps-java_HPSJAVA-88/users/src/main/java/org/hps/users/luca
--- java/branches/hps-java_HPSJAVA-88/users/src/main/java/org/hps/users/luca/mycluster3.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/users/src/main/java/org/hps/users/luca/mycluster3.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -20,17 +20,17 @@
import org.hps.recon.ecal.ECalUtils;
import org.hps.recon.ecal.HPSEcalCluster;
-import org.lcsim.event.Cluster;
+
import org.lcsim.event.EventHeader;
import org.lcsim.geometry.Detector;
import org.lcsim.util.aida.AIDA;
import org.lcsim.util.Driver;
import hep.aida.*;
-import hep.aida.IHistogram3D;
+
import java.io.FileWriter;
import org.lcsim.event.CalorimeterHit;
-import org.lcsim.event.MCParticle;
+
/**
*
* @author Luca Colaneri
@@ -46,12 +46,15 @@
private LinkedList<ArrayList<HPSEcalCluster>> clusterBuffer;
protected String clusterCollectionName = "EcalClusters";
-
-
+ AIDA aida = AIDA.defaultInstance();
+ IHistogram1D clusterEne=aida.histogram1D("Clusters energy with Luca's trigger",300, 0, 3);
+// ArrayList<IHistogram1D> SeedHistograms = new ArrayList<IHistogram1D>(442);
+ // ArrayList<IHistogram1D> ClustHistograms = new ArrayList<IHistogram1D>(442);
+ // ArrayList<IHistogram1D> HitHistograms = new ArrayList<IHistogram1D>(442);
private FileWriter writer;
- //private FileWriter writer2;
- String outputFileName = "ClusterInfonew.txt";
- // String outputFileName2 = "ClusterEnePos2.txt";
+ private FileWriter writer2;
+ String outputFileName = "LucaTriggerFEE.txt";
+ String outputFileName2 = "LucaTriggerHits.txt";
@@ -71,6 +74,9 @@
public void setOutputFileName(String outputFileName){
this.outputFileName = outputFileName;
}
+ public void setOutputFileName2(String outputFileName2){
+this.outputFileName2 = outputFileName2;
+ }
public void settimeDifference(double time){
this.timeDifference=time;
@@ -99,10 +105,26 @@
try{
//initialize the writers
writer=new FileWriter(outputFileName);
- // writer2=new FileWriter(outputFileName2);
+ writer2=new FileWriter(outputFileName2);
//Clear the files
writer.write("");
- // writer2.write("");
+ writer2.write("");
+
+ //initialize histograms
+ /* for(int t=0; t<442; t++){
+ String cristallo=String.valueOf(t);
+ String seedhistogram="SeedHit_" + String.valueOf(t);
+ String Clushistogram="Clusters_" + String.valueOf(t);
+ String HitHistogram="Hits_" + String.valueOf(t);
+
+ IHistogram1D seedhisto=aida.histogram1D(seedhistogram, 150, 0.0,3.0);
+ IHistogram1D clushisto=aida.histogram1D(Clushistogram, 150, 0.0,3.0);
+ IHistogram1D hitshisto=aida.histogram1D(HitHistogram,150,0.0,3.0);
+ SeedHistograms.add(seedhisto);
+ ClustHistograms.add(clushisto);
+ HitHistograms.add(hitshisto);
+ }*/
+
}
catch(IOException e ){
System.err.println("Error initializing output file for event display.");
@@ -116,7 +138,7 @@
try{
//close the file writer.
writer.close();
- // writer2.close();
+ writer2.close();
}
catch(IOException e){
System.err.println("Error closing utput file for event display.");
@@ -131,6 +153,7 @@
//get the clusters from the event
+ if(TriggerDriver.triggerBit()){ //if they have triggered!
if(event.hasCollection(HPSEcalCluster.class, "EcalClusters")) {
List<HPSEcalCluster> clusterList =event.get(HPSEcalCluster.class,clusterCollectionName );
@@ -138,6 +161,7 @@
ArrayList<HPSEcalCluster> clusterSet = new ArrayList<HPSEcalCluster>();
for(HPSEcalCluster cluster : clusterList){
+ clusterEne.fill(cluster.getEnergy());
TotalCluster++;
clusterSet.add(cluster);
}
@@ -147,6 +171,21 @@
//Run the sorting algorithm;
ClusterAnalyzer();
}
+
+ //get the hits from the event
+ if(event.hasCollection(CalorimeterHit.class,"EcalCorrectedHits")){
+ List<CalorimeterHit> hits =event.get(CalorimeterHit.class,"EcalCorrectedHits");
+
+ for(CalorimeterHit hit : hits){
+ int id=getCrystal(hit)-1;
+ // HitHistograms.get(id).fill(hit.getRawEnergy());
+ try{ writer2.append(id + " " + hit.getRawEnergy()+ "\n");}
+ catch(IOException e ){System.err.println("Error writing to output for event display");}
+ }//end of for cycle
+ }
+
+ }
+
}
@@ -174,15 +213,16 @@
Clustercount++;
id=getCrystal(cluster);
try{
- writer.append(id + " " + cluster.getSeedHit().getTime() + " " + cluster.getEnergy()+ " " + cluster.getSize() + " " + cluster.getSeedHit().getRawEnergy() + " ");
+ writer.append(id + " " + cluster.getEnergy()+ " " + cluster.getSize() + " " + cluster.getSeedHit().getRawEnergy() + " " + cluster.getSeedHit().getIdentifierFieldValue("ix")+" " +cluster.getSeedHit().getIdentifierFieldValue("iy"));
/*for(CalorimeterHit hit : cluster.getCalorimeterHits())
{writer.append(hit.getRawEnergy()+ " ");
}*/
writer.append("\n");
-
+ // SeedHistograms.get(id-1).fill(cluster.getSeedHit().getRawEnergy());
+ // ClustHistograms.get(id-1).fill(cluster.getEnergy());
}
- catch(IOException e ){System.err.println("Error writing tooutput for event display");}
+ catch(IOException e ){System.err.println("Error writing to output for event display");}
}
}
@@ -218,7 +258,7 @@
for(HPSEcalCluster currentcluster : currentList){
if(currentcluster!= cluster){
//if there is a cluster in the buffer that is in the considered radius in a time window lower than expected, the loop is brocken and the analyzed cluster is not good
- if(!((currentcluster.getSeedHit().getIdentifierFieldValue("ix")< posx-radius || currentcluster.getSeedHit().getIdentifierFieldValue("ix")> posx+radius)&& (currentcluster.getSeedHit().getIdentifierFieldValue("iy")< posy-radius || currentcluster.getSeedHit().getIdentifierFieldValue("iy")> posy+radius))&& Math.abs(cluster.getSeedHit().getTime()-currentcluster.getSeedHit().getTime())<timeDifference){
+ if(!((currentcluster.getSeedHit().getIdentifierFieldValue("ix") < posx-radius || currentcluster.getSeedHit().getIdentifierFieldValue("ix")> posx+radius)&& (currentcluster.getSeedHit().getIdentifierFieldValue("iy")< posy-radius || currentcluster.getSeedHit().getIdentifierFieldValue("iy")> posy+radius))&& Math.abs(cluster.getSeedHit().getTime()-currentcluster.getSeedHit().getTime())<timeDifference){
check=false;
break loops;
}
@@ -277,7 +317,7 @@
if(x>0){
id=-x+245;}
else if(x==-1 )id=245;
- else if(x<-1){id=-x+257;}}
+ else if(x<-1){id=-x+235;}}
else if(y==-2)
@@ -304,7 +344,71 @@
}
+ public int getCrystal (CalorimeterHit hit){
+ int x,y,id=0;
+ x= (-1)*hit.getIdentifierFieldValue("ix");
+ y= hit.getIdentifierFieldValue("iy");
+ if(y==5){
+ if(x<0)
+ {id=x+24;}
+ else id= x+23;
+ }
+
+ else if(y==4)
+ {if(x<0){
+ id=x+70;}
+ else id=x+69;}
+
+ else if(y==3)
+ {if(x<0){
+ id=x+116;}
+ else id=x+115;}
+
+ else if(y==2)
+ {if(x<0){
+ id=x+162;}
+ else id=x+161;}
+
+ else if(y==1)
+ {x=-x;
+ if(x>0){
+ id=-x+208;}
+ else if(x==-1){id=208;}
+ else if(x<-1) id=-x+198;}
+
+ else if(y==-1)
+ {x=-x;
+ if(x>0){
+ id=-x+245;}
+ else if(x==-1 )id=245;
+ else if(x<-1){id=-x+235;}}
+
+
+ else if(y==-2)
+ {if(x<0){
+ id=x+282;}
+ else id=x+281;}
+
+ else if(y==-3)
+ {if(x<0){
+ id=x+328;}
+ else id=x+327;}
+
+ else if(y==-4)
+ {if(x<0){
+ id=x+374;}
+ else id=x+373;}
+
+ else if(y==-5)
+ {if(x<0){
+ id=x+420;}
+ else id=x+419;}
+
+ return id;
+
+ }
+
} //chiusura driver
java/branches/hps-java_HPSJAVA-88/users/src/main/java/org/hps/users/mgraham
--- java/branches/hps-java_HPSJAVA-88/users/src/main/java/org/hps/users/mgraham/HitTimePlotter.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/users/src/main/java/org/hps/users/mgraham/HitTimePlotter.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -203,7 +203,7 @@
// + ", Trigger timestamp " + ReadoutTimestamp.getTimestamp(ReadoutTimestamp.SYSTEM_TRIGGER, event));
double t0Ecal = ReadoutTimestamp.getTimestamp(ReadoutTimestamp.SYSTEM_ECAL, event);
double t0Svt = ReadoutTimestamp.getTimestamp(ReadoutTimestamp.SYSTEM_TRACKER, event);
- double t0Trig = ReadoutTimestamp.getTimestamp(ReadoutTimestamp.SYSTEM_TRIGGER, event);
+ double t0Trig = ReadoutTimestamp.getTimestamp(ReadoutTimestamp.SYSTEM_TRIGGERBITS, event);
for (CalorimeterHit hit : ecalHits) {
double cor = hit.getTime() + (t0Ecal - t0Trig);
aida.histogram1D("ECAL Hit Time").fill(hit.getTime());
java/branches/hps-java_HPSJAVA-88/users/src/main/java/org/hps/users/omoreno
--- java/branches/hps-java_HPSJAVA-88/users/src/main/java/org/hps/users/omoreno/PlotUtils.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/users/src/main/java/org/hps/users/omoreno/PlotUtils.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -1,6 +1,8 @@
package org.hps.users.omoreno;
import hep.aida.ICloud2D;
+import hep.aida.IFitResult;
+import hep.aida.IFitter;
//--- hep ---//
import hep.aida.IHistogram1D;
import hep.aida.IHistogram2D;
@@ -99,5 +101,37 @@
int region = ix * 4 + iy;
return region;
}
+
+ public static IHistogram1D getYProjection(int binX, IHistogram2D histogram){
+ int binsY = histogram.yAxis().bins();
+ double yMin = histogram.yAxis().lowerEdge();
+ double yMax = histogram.yAxis().upperEdge();
+
+ IHistogram1D projection
+ = AIDA.defaultInstance().histogram1D(histogram.title() + "_" + binX, binsY, yMin, yMax);
+ projection.reset();
+
+ double dataY = 0;
+ for(int binY = 0; binY < binsY; binY++){
+ dataY = histogram.binEntries(binX, binY);
+ projection.fill(yMin, dataY);
+ yMin++;
+ }
+
+ return projection;
+ }
+ public static double[] fitToGuassian(IHistogram1D histogram){
+
+ double[] fitParameters = {0, 0};
+ IFitter fitter = AIDA.defaultInstance().analysisFactory().createFitFactory().createFitter();
+ IFitResult fitResult = fitter.fit(histogram, "g");
+ int meanIndex = fitResult.fittedFunction().indexOfParameter("mean");
+ fitParameters[0] = fitResult.fittedParameters()[meanIndex];
+
+ int sigmaIndex = fitResult.fittedFunction().indexOfParameter("sigma");
+ fitParameters[1] = fitResult.fittedParameters()[sigmaIndex];
+
+ return fitParameters;
+ }
}
java/branches/hps-java_HPSJAVA-88/users/src/main/java/org/hps/users/omoreno
--- java/branches/hps-java_HPSJAVA-88/users/src/main/java/org/hps/users/omoreno/SvtPerformance.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/users/src/main/java/org/hps/users/omoreno/SvtPerformance.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -375,14 +375,14 @@
}
}
- constants = HPSSVTCalibrationConstants.getChannelConstants(sensor, channel);
- fit = shaperFitter.fitShape(rawHit, constants);
+ //constants = HPSSVTCalibrationConstants.getChannelConstants(sensor, channel);
+ // fit = shaperFitter.fitShape(rawHit);
if (fit.getAmp() > maxClusterAmplitude) {
maxClusterChannel = channel;
maxClusterAmplitude = fit.getAmp();
}
if(stripHit.rawhits().size() == 1){
- chiSquared = fit.getChiSq();
+ // chiSquared = fit.getChiSq();
}
noise += Math.pow(sensor.getNoise(channel), 2);
clusterAmplitude += fit.getAmp();
java/branches/hps-java_HPSJAVA-88/users/src/main/java/org/hps/users/omoreno
--- java/branches/hps-java_HPSJAVA-88/users/src/main/java/org/hps/users/omoreno/SvtQA.java 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/users/src/main/java/org/hps/users/omoreno/SvtQA.java 2014-09-02 22:27:42 UTC (rev 940)
@@ -466,10 +466,10 @@
int apv = this.getAPVNumber(channel);
// Get the constants associated with this channel
- constants = HPSSVTCalibrationConstants.getChannelConstants(sensor, channel);
+ //constants = HPSSVTCalibrationConstants.getChannelConstants(sensor, channel);
// Fit the samples associated with the RawTrackerHit
- fit = shaperFitter.fitShape(rawHit, constants);
+ //fit = shaperFitter.fitShape(rawHit);
// Fill the occupancy plots
if(enableOccupancy){
@@ -553,7 +553,7 @@
// Fill Chi Squared vs Channel # plots
if(enableChiSquaredvsChannel && SvtUtils.getInstance().getDescription(sensor).equals(sensorName)){
title = sensorName + " - Chi Squared vs Channel #";
- aida.histogram2D(title).fill(channel, fittedHit.getShapeFitParameters().getChiSq());
+ //aida.histogram2D(title).fill(channel, fittedHit.getShapeFitParameters().getChiSq());
}
}
@@ -580,10 +580,10 @@
int channel = rawHit.getIdentifierFieldValue("strip");
// Get the constants associated with this channel
- constants = HPSSVTCalibrationConstants.getChannelConstants(sensor, channel);
+ //constants = HPSSVTCalibrationConstants.getChannelConstants(sensor, channel);
// Fit the samples associated with the RawTrackerHit
- fit = shaperFitter.fitShape(rawHit, constants);
+ //fit = shaperFitter.fitShape(rawHit);
// Get the shaper signal samples
short[] samples = rawHit.getADCValues();
java/branches/hps-java_HPSJAVA-88/util
--- java/branches/hps-java_HPSJAVA-88/util/pom.xml 2014-09-02 21:58:56 UTC (rev 939)
+++ java/branches/hps-java_HPSJAVA-88/util/pom.xml 2014-09-02 22:27:42 UTC (rev 940)
@@ -9,7 +9,7 @@
<groupId>org.hps</groupId>
<artifactId>hps-parent</artifactId>
<relativePath>../parent/pom.xml</relativePath>
- <version>3.0.2-SNAPSHOT</version>
+ <version>3.0.3-SNAPSHOT</version>
</parent>
<scm>
SVNspam 0.1