View Javadoc

1   /*
2    * To change this template, choose Tools | Templates
3    * and open the template in the editor.
4    */
5   
6   package org.lcsim.recon.tracking.seedtracker.strategybuilder;
7   
8   import java.io.File;
9   import java.io.FileWriter;
10  import java.io.IOException;
11  import java.io.InputStream;
12  import java.util.Comparator;
13  import java.util.HashMap;
14  import java.util.Map;
15  import java.util.Set;
16  import org.jdom.Attribute;
17  import org.jdom.Document;
18  import org.jdom.Element;
19  import org.jdom.JDOMException;
20  import org.jdom.Namespace;
21  import org.jdom.input.SAXBuilder;
22  import org.jdom.output.Format;
23  import org.jdom.output.XMLOutputter;
24  import org.lcsim.geometry.subdetector.BarrelEndcapFlag;
25  import org.lcsim.util.xml.ClasspathEntityResolver;
26  
27  /**
28   *LayerWeights are used by SubsetScorer and to disambiguate between Seed and 
29   * Confirm layers. 
30   * 
31   * @author cozzy
32   */
33  public class LayerWeight {
34      
35          private double default_weight = 1.0;
36          private double adjacence_multiplier = 1.0;
37          private Map<DumbLayer, Double> weights; 
38          private Map<String, Double> readout_efficiencies; 
39          private double defaultEfficiency = 1.0; 
40          private String targetDetector = "None Specified"; 
41          private boolean divideByTwoInTrackerEndcap = false; 
42          private boolean divideByTwoInTrackerForward = false; 
43          
44          public LayerWeight(){
45              weights = new HashMap<DumbLayer,Double>(); 
46              readout_efficiencies = new HashMap<String,Double>(); 
47          } 
48          
49          public LayerWeight(LayerWeight lw){
50              this.default_weight = lw.default_weight; 
51              this.weights = lw.weights; 
52              this.readout_efficiencies = lw.readout_efficiencies; 
53          }
54      
55          public LayerWeight(DumbLayer[] layers, double[] wghts, String[] readoutNames, double[] readoutEfficiencies){
56              if (layers.length!=wghts.length || readoutNames.length!=readoutEfficiencies.length)
57                  throw new RuntimeException("Array lengths don't match"); 
58              
59              
60              weights = new HashMap<DumbLayer,Double>();
61              
62              for (int i = 0; i < layers.length; i++)
63                  setWeight(layers[i], wghts[i]); 
64              
65              readout_efficiencies = new HashMap<String,Double>(); 
66              for (int i = 0 ; i < layers.length; i++)
67                  setReadoutEfficiency(readoutNames[i],readoutEfficiencies[i]); 
68          }
69          
70          public void setDefaultWeight(double d){
71              default_weight = d; 
72          }
73          
74          public void setDefaultReadoutEfficiency(double d){
75              checkReadoutEfficiencyValid(d);
76              defaultEfficiency = d; 
77          }
78          
79          public void setWeight(DumbLayer lyr, double weight){
80              weights.put(lyr, weight); 
81          }
82          
83          public void setReadoutEfficiency(String readoutName, double eff){
84              checkReadoutEfficiencyValid(eff);
85              readout_efficiencies.put(readoutName, eff); 
86              
87          }
88          public void setTargetDetector(String name){
89              targetDetector = name; 
90          }
91          
92          public String getTargetDetector() {
93              return targetDetector; 
94          }
95          
96          public double getWeight(DumbLayer layer) {
97              if (weights.containsKey(layer)){
98                  return weights.get(layer).doubleValue(); 
99              } else return default_weight; 
100         }
101         
102         public double getReadoutEfficiency(String readoutName) {
103             if (readout_efficiencies.containsKey(readoutName)) {
104                 return readout_efficiencies.get(readoutName); 
105             } else return defaultEfficiency; 
106         }
107         
108         public double getWeight(Set<DumbLayer> set) {
109             double ret = 1.0;
110             
111             for (DumbLayer lyr : set) {
112                 ret*=getWeight(lyr); 
113             }
114             return ret; 
115         }
116         
117         public double getAdjacenceMultiplier() {
118             return adjacence_multiplier;
119         }
120 
121         public void setAdjacenceMultiplier(double adjacence_multiplier) {
122             this.adjacence_multiplier = adjacence_multiplier;
123         }
124 
125         public boolean isDivideByTwoInTrackerEndcap() {
126             return divideByTwoInTrackerEndcap;
127         }
128 
129         public void setDivideByTwoInTrackerEndcap(boolean divideByTwo) {
130             this.divideByTwoInTrackerEndcap = divideByTwo;
131         }
132 
133         public boolean isDivideByTwoInTrackerForward() {
134             return divideByTwoInTrackerForward;
135         }
136 
137         public void setDivideByTwoInTrackerForward(boolean divideByTwo) {
138             this.divideByTwoInTrackerForward = divideByTwo;
139         }
140                 
141         /**
142          * Returns the prefix of the default resource path to where the 
143          * layer weight XML files are stored.
144          * @return default resource path to XML weights
145          */
146         public static String getDefaultResourcePrefix(){
147             return "org/lcsim/recon/tracking/seedtracker/strategybuilder/weights/";
148         }
149         
150         /**
151          * Loads LayerWeight definitions from the resource with the specified name.
152          * The name should be something like /org/lcsim/contrib/seedtracker/strategybuilder/weights/weights.xml
153          * 
154          * getDefaultResourcePrefix() may be helpful. 
155          * 
156          * @param resourceName the full name of the resource file to read
157          * @return the read LayerWeight definitions
158          */
159         public static LayerWeight getLayerWeightFromResource(String resourceName) {    
160             return getLayerWeightFromInputStream(LayerWeight.class.getClassLoader().getResourceAsStream(resourceName)); 
161             
162         }
163         
164         
165         public Comparator getComparator(){
166             return new Comparator(){
167                 public int compare(Object o1, Object o2) {
168                     DumbLayer dl1 = (DumbLayer) o1;
169                     DumbLayer dl2 = (DumbLayer) o2; 
170                     double s1 = LayerWeight.this.getWeight(dl1);
171                     double s2 = LayerWeight.this.getWeight(dl2);
172                     return Double.compare(s1, s2); 
173                 }
174             };
175         }
176         
177         
178         /**
179          * Loads LayerWeight definitions from the specified input stream
180          * @param in an input stream corresponding to a valid XML file 
181          * @return the read LayerWeight definitions
182          */
183         public static LayerWeight getLayerWeightFromInputStream(InputStream in){
184             
185             Document doc; 
186             SAXBuilder builder = new SAXBuilder();
187             builder.setValidation(true); 
188             builder.setFeature("http://apache.org/xml/features/validation/schema", true);
189             builder.setEntityResolver(new ClasspathEntityResolver());
190             try {
191                 doc = builder.build(in);
192             } catch (JDOMException jdom) {
193                 jdom.printStackTrace();
194                 throw new RuntimeException("JDOM exception occurred"); 
195             } catch (IOException io ) {
196                 io.printStackTrace();
197                 throw new RuntimeException("IO Exception occurred"); 
198             }
199             
200             return getLayerWeightFromDocument(doc);
201  
202         }
203         /**
204          * Loads LayerWeight definitions from the specified file. 
205          * @param file a valid XML file specifying layer weights
206          * @return the read LayerWeight definitions
207          */
208         public static LayerWeight getLayerWeightFromFile(File file){
209             
210             if (! file.exists() )
211                 throw new RuntimeException("File "+file.toString()+" not found"); 
212             
213             Document doc; 
214             SAXBuilder builder = new SAXBuilder();
215             builder.setValidation(true); 
216             builder.setFeature("http://apache.org/xml/features/validation/schema", true);
217             builder.setEntityResolver(new ClasspathEntityResolver());
218             try {
219                 doc = builder.build(file);
220             } catch (JDOMException jdom) {
221                 jdom.printStackTrace();
222                 throw new RuntimeException("JDOM exception occurred"); 
223             } catch (IOException io ) {
224                 io.printStackTrace();
225                 throw new RuntimeException("IO Exception occurred"); 
226             }
227             
228             return getLayerWeightFromDocument(doc); 
229         }
230         
231         private void checkReadoutEfficiencyValid(double d){
232             if (d < 0. || d > 1.00000001)
233                 throw new RuntimeException("Readout Efficiency must be between 0 and 1"); 
234         }
235         
236         private static LayerWeight getLayerWeightFromDocument(Document doc) {
237             Element root = doc.getRootElement(); 
238             LayerWeight lw = new LayerWeight(); 
239             
240             try {
241                 lw.setDefaultWeight(Double.valueOf(root.getChildText("DefaultWeight")).doubleValue());
242                 lw.setDefaultReadoutEfficiency(Double.valueOf(root.getChildText("DefaultReadoutEfficiency")));
243                 try {lw.setAdjacenceMultiplier(Double.valueOf(root.getChildText("AdjacenceMultiplier")).doubleValue());} catch(NullPointerException npe){}
244                 try {lw.setTargetDetector(root.getChildText("TargetDetector"));} catch(NullPointerException npe){}
245                 try {lw.setDivideByTwoInTrackerEndcap(Boolean.valueOf(root.getChild("TargetDetector").getAttributeValue("divide_by_two_in_tracker_endcap")));} catch(NullPointerException npe){}
246                 try {lw.setDivideByTwoInTrackerForward(Boolean.valueOf(root.getChild("TargetDetector").getAttributeValue("divide_by_two_in_tracker_forward")));} catch(NullPointerException npe){}
247                 Element layers = root.getChild("Layers"); 
248                 for (Object o : layers.getChildren("Layer")){
249                     
250                     Element e = (Element) o; 
251                     String detName = e.getAttributeValue("detector_name"); 
252                     int layer_number = Integer.valueOf(e.getAttributeValue("layer_number")).intValue(); 
253                     BarrelEndcapFlag beflag = BarrelEndcapFlag.valueOf(e.getAttributeValue("be_flag")); 
254                     DumbLayer dl = new DumbLayer(detName, layer_number, beflag); 
255                     lw.setWeight(dl, Double.valueOf(e.getText()));
256                 } 
257                 
258                 Element ro = root.getChild("ReadoutEfficiencies"); 
259                 
260                 if (ro!=null) {
261                     for (Object o : ro.getChildren("ReadoutEfficiency")){
262                         Element e = (Element) o; 
263                         String readoutName = e.getAttributeValue("readout"); 
264                         lw.setReadoutEfficiency(readoutName, Double.valueOf(e.getText()));
265                     }
266                 }
267                 
268             } catch (Exception e) {
269                 e.printStackTrace();
270                 throw new RuntimeException("Something bad happened when parsing"); 
271             }
272                 
273             return lw; 
274         }
275         /**
276          * Writes this LayerWeight to an XML file with a location specified
277          * by the given file object. 
278          * @param file output File object 
279          * @return true if succesful, false otherwise. 
280          */
281         public boolean writeToFile(File file){
282             Element root = new Element("LayerWeight"); 
283             Document doc = new Document(root); 
284             Namespace xs = Namespace.getNamespace("xs", "http://www.w3.org/2001/XMLSchema-instance");
285             root.addNamespaceDeclaration(xs);
286             root.setAttribute(new Attribute("noNamespaceSchemaLocation","http://lcsim.org/recon/tracking/seedtracker/strategybuilder/strategies.xsd",xs));
287             root.addContent(new Element("DefaultWeight").addContent(String.valueOf(default_weight))); 
288             root.addContent(new Element("DefaultReadoutEfficiency").addContent(String.valueOf(defaultEfficiency)));          
289             root.addContent(new Element("TargetDetector").addContent(String.valueOf(targetDetector)).setAttribute("divide_by_two_in_tracker_endcap", String.valueOf(divideByTwoInTrackerEndcap))); 
290             root.addContent(new Element("TargetDetector").addContent(String.valueOf(targetDetector)).setAttribute("divide_by_two_in_tracker_forward", String.valueOf(divideByTwoInTrackerForward))); 
291             root.addContent(new Element("AdjacenceMultiplier").addContent(String.valueOf(adjacence_multiplier))); 
292             
293             Element ro = new Element("ReadoutEfficiencies"); 
294             
295             for (String readout : readout_efficiencies.keySet()) {
296                 Element re = new Element("ReadoutEfficiency"); 
297                 re.setAttribute("readout",readout); 
298                 re.addContent(String.valueOf(readout_efficiencies.get(readout))); 
299                 ro.addContent(re);
300             }   
301             root.addContent(ro); 
302             
303             Element layers = new Element("Layers"); 
304             for (DumbLayer lyr : weights.keySet()) {
305                 Element layer = new Element("Layer"); 
306                 layer.setAttribute("layer_number", String.valueOf(lyr.layer)); 
307                 layer.setAttribute("detector_name", String.valueOf(lyr.detectorName)); 
308                 layer.setAttribute("be_flag", lyr.be.toString()); 
309                 layer.addContent(String.valueOf(weights.get(lyr))); 
310                 layers.addContent(layer); 
311             }
312             root.addContent(layers); 
313             
314             try {
315                 XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); 
316                 FileWriter fw = new FileWriter(file); 
317                 out.output(doc, fw);
318             } catch (Exception e){
319                 e.printStackTrace();
320                 return false; 
321             }
322             return true; 
323         }
324     }