View Javadoc
1   package ffx.utilities;
2   
3   import jakarta.xml.bind.annotation.adapters.XmlAdapter;
4   
5   import java.util.logging.Logger;
6   
7   import static java.lang.Double.parseDouble;
8   import static java.lang.String.format;
9   
10  /**
11   * Write/read Histogram data to/from a String.
12   * The String is an array of lines separated by System dependent line separators.
13   * Each line (row) corresponds to a fixed lambda.
14   * The columns are a space-separated list of weights for the dUdL bins.
15   *
16   * @author Michael J. Schnieders
17   * @see jakarta.xml.bind.annotation.adapters.XmlAdapter
18   * @since 1.0
19   */
20  public class HistogramXmlAdapter extends XmlAdapter<String, double[][]> {
21  
22    /**
23     * The logger for this class.
24     */
25    public static final Logger logger = Logger.getLogger(HistogramXmlAdapter.class.getName());
26  
27    /**
28     * Default constructor.
29     */
30    public HistogramXmlAdapter() {
31      // Default constructor.
32    }
33  
34    /**
35     * Convert the histogram data string to a 2D double array.
36     *
37     * @param value String containing the Histogram data.
38     * @return The data.
39     */
40    @Override
41    public double[][] unmarshal(String value) {
42      double[][] data;
43      try {
44        String[] lines = value.split(System.lineSeparator());
45        int lambdaBins = lines.length;
46        data = new double[lambdaBins][];
47        for (int i = 0; i < lambdaBins; i++) {
48          String[] countToks = lines[i].split(" +");
49          int dUdLBins = countToks.length;
50          data[i] = new double[dUdLBins];
51          double[] row = data[i];
52          for (int j = 0; j < dUdLBins; j++) {
53            row[j] = parseDouble(countToks[j]);
54          }
55        }
56      } catch (Exception e) {
57        logger.warning(" Returning a null histogram due to an XML parsing exception:\n " + e);
58        data = null;
59      }
60      return data;
61    }
62  
63    /**
64     * Convert the 2D histogram double array into a String.
65     *
66     * @param data The histogram data.
67     * @return A String representation of the data.
68     */
69    @Override
70    public String marshal(double[][] data) {
71      StringBuilder sb = new StringBuilder();
72      for (double[] row : data) {
73        sb.append(format("%.16e", row[0]));
74        int dUdLBins = row.length;
75        for (int j = 1; j < dUdLBins; j++) {
76          sb.append(" ").append(format("%.16e", row[j]));
77        }
78        sb.append(System.lineSeparator());
79      }
80      return sb.toString();
81    }
82  }
83