MarshallSolarActivityFutureEstimation.java

  1. /* Copyright 2002-2013 CS Systèmes d'Information
  2.  * Licensed to CS Systèmes d'Information (CS) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * CS licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *   http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.orekit.forces.drag;

  18. import java.io.BufferedReader;
  19. import java.io.IOException;
  20. import java.io.InputStream;
  21. import java.io.InputStreamReader;
  22. import java.io.Serializable;
  23. import java.text.ParseException;
  24. import java.util.Arrays;
  25. import java.util.Iterator;
  26. import java.util.SortedSet;
  27. import java.util.TreeSet;
  28. import java.util.regex.Matcher;
  29. import java.util.regex.Pattern;

  30. import org.orekit.data.DataLoader;
  31. import org.orekit.errors.OrekitException;
  32. import org.orekit.errors.OrekitMessages;
  33. import org.orekit.time.AbsoluteDate;
  34. import org.orekit.time.ChronologicalComparator;
  35. import org.orekit.time.DateComponents;
  36. import org.orekit.time.Month;
  37. import org.orekit.time.TimeScale;
  38. import org.orekit.time.TimeScalesFactory;
  39. import org.orekit.time.TimeStamped;

  40. /**
  41.  * This class reads and provides solar activity data needed by
  42.  * atmospheric models: F107 solar flux and Kp indexes.
  43.  * <p>
  44.  * The data are retrieved through the NASA Marshall
  45.  * Solar Activity Future Estimation (MSAFE) as estimates of monthly
  46.  * F10.7 Mean solar flux and Ap geomagnetic parameter.
  47.  * The data can be retrieved at the NASA <a
  48.  * href="http://sail.msfc.nasa.gov/archive_index.htm">
  49.  * Marshall Solar Activity website</a>.
  50.  * Here Kp indices are deduced from Ap indexes, which in turn are tabulated
  51.  * equivalent of retrieved Ap values.
  52.  * </p>
  53.  * <p>
  54.  * If several MSAFE files are available, some dates may appear in several
  55.  * files (for example August 2007 is in all files from the first one
  56.  * published in March 1999 to the February 2008 file). In this case, the
  57.  * data from the most recent file is used and the older ones are discarded.
  58.  * The date of the file is assumed to be 6 months after its first entry
  59.  * (which explains why the file having August 2007 as its first entry is the
  60.  * February 2008 file). This implies that MSAFE files must <em>not</em> be
  61.  * edited to change their time span, otherwise this would break the old
  62.  * entries overriding mechanism.
  63.  * </p>
  64.  * <p>
  65.  * With these data, the {@link #getInstantFlux(AbsoluteDate)} and {@link
  66.  * #getMeanFlux(AbsoluteDate)} methods return the same values and the {@link
  67.  * #get24HoursKp(AbsoluteDate)} and {@link #getThreeHourlyKP(AbsoluteDate)}
  68.  * methods return the same values.
  69.  * </p>
  70.  * @author Bruno Revelin
  71.  * @author Luc Maisonobe
  72.  */
  73. public class MarshallSolarActivityFutureEstimation implements DTM2000InputParameters, DataLoader {

  74.     /** Strength level of activity. */
  75.     public static enum StrengthLevel {

  76.         /** Strong level of activity. */
  77.         STRONG,

  78.         /** Average level of activity. */
  79.         AVERAGE,

  80.         /** Weak level of activity. */
  81.         WEAK

  82.     };

  83.     /** Serializable UID. */
  84.     private static final long serialVersionUID = -5212198874900835369L;

  85.     /** 1/3. */
  86.     private static final double ONE_THIRD = 1.0 / 3.0;

  87.     /** 3 hours geomagnetic indices array. */
  88.     private static final double[] KP_ARRAY = new double[] {
  89.         0, 0 + ONE_THIRD, 1 - ONE_THIRD, 1, 1 + ONE_THIRD, 2 - ONE_THIRD,
  90.         2, 2 + ONE_THIRD, 3 - ONE_THIRD, 3, 3 + ONE_THIRD, 4 - ONE_THIRD,
  91.         4, 4 + ONE_THIRD, 5 - ONE_THIRD, 5, 5 + ONE_THIRD, 6 - ONE_THIRD,
  92.         6, 6 + ONE_THIRD, 7 - ONE_THIRD, 7, 7 + ONE_THIRD, 8 - ONE_THIRD,
  93.         8, 8 + ONE_THIRD, 9 - ONE_THIRD, 9
  94.     };

  95.     /** Mean geomagnetic indices array. */
  96.     private static final double[] AP_ARRAY = new double[] {
  97.         0, 2, 3, 4, 5, 6, 7, 9, 12, 15, 18, 22, 27, 32,
  98.         39, 48, 56, 67, 80, 94, 111, 132, 154 , 179, 207, 236, 300, 400
  99.     };

  100.     /** Pattern for the data fields of MSAFE data. */
  101.     private final Pattern dataPattern;

  102.     /** Data set. */
  103.     private final SortedSet<TimeStamped> data;

  104.     /** Selected strength level of activity. */
  105.     private final StrengthLevel strengthLevel;

  106.     /** First available date. */
  107.     private AbsoluteDate firstDate;

  108.     /** Last available date. */
  109.     private AbsoluteDate lastDate;

  110.     /** Previous set of solar activity parameters. */
  111.     private LineParameters previousParam;

  112.     /** Current set of solar activity parameters. */
  113.     private LineParameters currentParam;

  114.     /** Regular expression for supported files names. */
  115.     private final String supportedNames;

  116.     /** Simple constructor.
  117.      * <p>
  118.      * The original file names used by NASA Marshall space center are of the
  119.      * form: Dec2010F10.txt or Oct1999F10.TXT. So a recommended regular
  120.      * expression for the supported name that work with all published files is:
  121.      * "(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\p{Digit}\\p{Digit}\\p{Digit}\\p{Digit}F10\\.(?:txt|TXT)"
  122.      * </p>
  123.      * @param supportedNames regular expression for supported files names
  124.      * @param strengthLevel selected strength level of activity
  125.      */
  126.     public MarshallSolarActivityFutureEstimation(final String supportedNames,
  127.                                                  final StrengthLevel strengthLevel) {

  128.         firstDate           = null;
  129.         lastDate            = null;
  130.         data                = new TreeSet<TimeStamped>(new ChronologicalComparator());
  131.         this.supportedNames = supportedNames;
  132.         this.strengthLevel  = strengthLevel;

  133.         // the data lines have the following form:
  134.         // 2010.5003   JUL    83.4      81.3      78.7       6.4       5.9       5.2
  135.         // 2010.5837   AUG    87.3      83.4      78.5       7.0       6.1       4.9
  136.         // 2010.6670   SEP    90.8      85.5      79.4       7.8       6.2       4.7
  137.         // 2010.7503   OCT    94.2      87.6      80.4       9.1       6.4       4.9
  138.         final StringBuilder builder = new StringBuilder("^");

  139.         // first group: year
  140.         builder.append("\\p{Blank}*(\\p{Digit}\\p{Digit}\\p{Digit}\\p{Digit})");

  141.         // month as fraction of year, not stored in a group
  142.         builder.append("\\.\\p{Digit}+");

  143.         // second group: month as a three upper case letters abbreviation
  144.         builder.append("\\p{Blank}+(");
  145.         for (final Month month : Month.values()) {
  146.             builder.append(month.getUpperCaseAbbreviation());
  147.             builder.append('|');
  148.         }
  149.         builder.delete(builder.length() - 1, builder.length());
  150.         builder.append(")");

  151.         // third to eighth group: data fields
  152.         for (int i = 0; i < 6; ++i) {
  153.             builder.append("\\p{Blank}+([-+]?[0-9]+\\.[0-9]+)");
  154.         }

  155.         // end of line
  156.         builder.append("\\p{Blank}*$");

  157.         // compile the pattern
  158.         dataPattern = Pattern.compile(builder.toString());

  159.     }

  160.     /** Get the strength level for activity.
  161.      * @return strength level to set
  162.      */
  163.     public StrengthLevel getStrengthLevel() {
  164.         return strengthLevel;
  165.     }

  166.     /** Find the data bracketing a specified date.
  167.      * @param date date to bracket
  168.      * @throws OrekitException if specified date is out of range
  169.      */
  170.     private void bracketDate(final AbsoluteDate date) throws OrekitException {

  171.         if ((date.durationFrom(firstDate) < 0) || (date.durationFrom(lastDate) > 0)) {
  172.             throw new OrekitException(OrekitMessages.OUT_OF_RANGE_EPHEMERIDES_DATE,
  173.                                       date, firstDate, lastDate);
  174.         }

  175.         // don't search if the cached selection is fine
  176.         if ((previousParam != null) &&
  177.             (date.durationFrom(previousParam.getDate()) > 0) &&
  178.             (date.durationFrom(currentParam.getDate()) <= 0 )) {
  179.             return;
  180.         }

  181.         if (date.equals(firstDate)) {
  182.             currentParam  = (LineParameters) data.tailSet(date.shiftedBy(1)).first();
  183.             previousParam = (LineParameters) data.first();
  184.         } else if (date.equals(lastDate)) {
  185.             currentParam  = (LineParameters) data.last();
  186.             previousParam = (LineParameters) data.headSet(date.shiftedBy(-1)).last();
  187.         } else {
  188.             currentParam  = (LineParameters) data.tailSet(date).first();
  189.             previousParam = (LineParameters) data.headSet(date).last();
  190.         }

  191.     }

  192.     /** Get the supported names for data files.
  193.      * @return regular expression for the supported names for data files
  194.      */
  195.     public String getSupportedNames() {
  196.         return supportedNames;
  197.     }

  198.     /** {@inheritDoc} */
  199.     public AbsoluteDate getMinDate() {
  200.         return firstDate;
  201.     }

  202.     /** {@inheritDoc} */
  203.     public AbsoluteDate getMaxDate() {
  204.         return lastDate;
  205.     }

  206.     /** {@inheritDoc} */
  207.     public double getInstantFlux(final AbsoluteDate date) throws OrekitException {
  208.         return getMeanFlux(date);
  209.     }

  210.     /** {@inheritDoc} */
  211.     public double getMeanFlux(final AbsoluteDate date) throws OrekitException {

  212.         // get the neighboring dates
  213.         bracketDate(date);

  214.         // perform a linear interpolation
  215.         final AbsoluteDate previousDate = previousParam.getDate();
  216.         final AbsoluteDate currentDate  = currentParam.getDate();
  217.         final double dt                 = currentDate.durationFrom(previousDate);
  218.         final double previousF107       = previousParam.getF107();
  219.         final double currentF107        = currentParam.getF107();
  220.         final double previousWeight     = currentDate.durationFrom(date)  / dt;
  221.         final double currentWeight      = date.durationFrom(previousDate) / dt;

  222.         return previousF107 * previousWeight + currentF107 * currentWeight;

  223.     }

  224.     /** {@inheritDoc} */
  225.     public double getThreeHourlyKP(final AbsoluteDate date) throws OrekitException {
  226.         return get24HoursKp(date);
  227.     }

  228.     /** Get the date of the file from which data at the specified date comes from.
  229.      * <p>
  230.      * If several MSAFE files are available, some dates may appear in several
  231.      * files (for example August 2007 is in all files from the first one
  232.      * published in March 1999 to the February 2008 file). In this case, the
  233.      * data from the most recent file is used and the older ones are discarded.
  234.      * The date of the file is assumed to be 6 months after its first entry
  235.      * (which explains why the file having August 2007 as its first entry is the
  236.      * February 2008 file). This implies that MSAFE files must <em>not</em> be
  237.      * edited to change their time span, otherwise this would break the old
  238.      * entries overriding mechanism.
  239.      * </p>
  240.      * @param date date of the solar activity data
  241.      * @return date of the file
  242.      * @exception OrekitException if specified date is out of range
  243.      */
  244.     public DateComponents getFileDate(final AbsoluteDate date) throws OrekitException {
  245.         bracketDate(date);
  246.         final double dtP = date.durationFrom(previousParam.getDate());
  247.         final double dtC = currentParam.getDate().durationFrom(date);
  248.         return (dtP < dtC) ? previousParam.getFileDate() : currentParam.getFileDate();
  249.     }

  250.     /** The Kp index is derived from the Ap index.
  251.      * <p>The method used is explained on <a
  252.      * href="http://www.ngdc.noaa.gov/stp/GEOMAG/kp_ap.html">
  253.      * NOAA website.</a> as follows:</p>
  254.      * <p>The scale is 0 to 9 expressed in thirds of a unit, e.g. 5- is 4 2/3,
  255.      * 5 is 5 and 5+ is 5 1/3. The ap (equivalent range) index is derived from
  256.      * the Kp index as follows:</p>
  257.      * <table border="1">
  258.      * <tbody>
  259.      * <tr>
  260.      * <td>Kp</td><td>0o</td><td>0+</td><td>1-</td><td>1o</td><td>1+</td><td>2-</td><td>2o</td><td>2+</td><td>3-</td><td>3o</td><td>3+</td><td>4-</td><td>4o</td><td>4+</td>
  261.      * </tr>
  262.      * <tr>
  263.      * <td>ap</td><td>0</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>9</td><td>12</td><td>15</td><td>18</td><td>22</td><td>27</td><td>32</td>
  264.      * </tr>
  265.      * <tr>
  266.      * <td>Kp</td><td>5-</td><td>5o</td><td>5+</td><td>6-</td><td>6o</td><td>6+</td><td>7-</td><td>7o</td><td>7+</td><td>8-</td><td>8o</td><td>8+</td><td>9-</td><td>9o</td>
  267.      * </tr>
  268.      * <tr>
  269.      * <td>ap</td><td>39</td><td>48</td><td>56</td><td>67</td><td>80</td><td>94</td><td>111</td><td>132</td><td>154</td><td>179</td><td>207</td><td>236</td><td>300</td><td>400</td>
  270.      * </tr>
  271.      * </tbody>
  272.      * </table>
  273.      * @param date date of the Kp data
  274.      * @return the 24H geomagnetic index
  275.      * @exception OrekitException if the date is out of range of available data
  276.      */
  277.     public double get24HoursKp(final AbsoluteDate date) throws OrekitException {

  278.         // get the neighboring dates
  279.         bracketDate(date);

  280.         // perform a linear interpolation
  281.         final AbsoluteDate previousDate = previousParam.getDate();
  282.         final AbsoluteDate currentDate  = currentParam.getDate();
  283.         final double dt                 = currentDate.durationFrom(previousDate);
  284.         final double previousAp         = previousParam.getAp();
  285.         final double currentAp          = currentParam.getAp();
  286.         final double previousWeight     = currentDate.durationFrom(date)  / dt;
  287.         final double currentWeight      = date.durationFrom(previousDate) / dt;
  288.         final double ap                 = previousAp * previousWeight + currentAp * currentWeight;

  289.         // calculating Ap index, then corresponding Kp index
  290.         final int i = Arrays.binarySearch(AP_ARRAY, ap);
  291.         if (i >= 0) {
  292.             // the exact value for ap has been found, return the corresponding Kp
  293.             return KP_ARRAY[i];
  294.         } else {
  295.             // the exact value has not been found, we have an insertion point
  296.             final int jSup = -(i + 1);
  297.             final int jInf = jSup - 1;
  298.             if ((ap - AP_ARRAY[jInf]) < (AP_ARRAY[jSup] - ap)) {
  299.                 return KP_ARRAY[jInf];
  300.             } else {
  301.                 return KP_ARRAY[jSup];
  302.             }
  303.         }

  304.     }

  305.     /** Container class for Solar activity indexes.  */
  306.     private static class LineParameters implements TimeStamped, Serializable {

  307.         /** Serializable UID. */
  308.         private static final long serialVersionUID = 6607862001953526475L;

  309.         /** File date. */
  310.         private final DateComponents fileDate;

  311.         /** Entry date. */
  312.         private  final AbsoluteDate date;

  313.         /** F10.7 flux at date. */
  314.         private final double f107;

  315.         /** Ap index at date. */
  316.         private final double ap;

  317.         /** Simple constructor.
  318.          * @param fileDate file date
  319.          * @param date entry date
  320.          * @param f107 F10.7 flux at date
  321.          * @param ap Ap index at date
  322.          */
  323.         private LineParameters(final DateComponents fileDate, final AbsoluteDate date, final double f107, final double ap) {
  324.             this.fileDate = fileDate;
  325.             this.date     = date;
  326.             this.f107     = f107;
  327.             this.ap       = ap;
  328.         }

  329.         /** Get the file date.
  330.          * @return file date
  331.          */
  332.         public DateComponents getFileDate() {
  333.             return fileDate;
  334.         }

  335.         /** Get the current date.
  336.          * @return current date
  337.          */
  338.         public AbsoluteDate getDate() {
  339.             return date;
  340.         }

  341.         /** Get the F10.0 flux.
  342.          * @return f10.7 flux
  343.          */
  344.         public double getF107() {
  345.             return f107;
  346.         }

  347.         /** Get the Ap index.
  348.          * @return Ap index
  349.          */
  350.         public double getAp() {
  351.             return ap;
  352.         }

  353.     }

  354.     /** {@inheritDoc} */
  355.     public void loadData(final InputStream input, final String name)
  356.         throws IOException, ParseException, OrekitException {

  357.         // select the groups we want to store
  358.         final int f107Group;
  359.         final int apGroup;
  360.         switch (strengthLevel) {
  361.         case STRONG :
  362.             f107Group = 3;
  363.             apGroup   = 6;
  364.             break;
  365.         case AVERAGE :
  366.             f107Group = 4;
  367.             apGroup   = 7;
  368.             break;
  369.         default :
  370.             f107Group = 5;
  371.             apGroup   = 8;
  372.             break;
  373.         }

  374.         // read the data
  375.         final BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
  376.         boolean inData = false;
  377.         final TimeScale utc = TimeScalesFactory.getUTC();
  378.         DateComponents fileDate = null;
  379.         for (String line = reader.readLine(); line != null; line = reader.readLine()) {
  380.             line = line.trim();
  381.             if (line.length() > 0) {
  382.                 final Matcher matcher = dataPattern.matcher(line);
  383.                 if (matcher.matches()) {

  384.                     // we are in the data section
  385.                     inData = true;

  386.                     // extract the data from the line
  387.                     final int year = Integer.parseInt(matcher.group(1));
  388.                     final Month month = Month.parseMonth(matcher.group(2));
  389.                     final AbsoluteDate date = new AbsoluteDate(year, month, 1, utc);
  390.                     if (fileDate == null) {
  391.                         // the first entry of each file correspond exactly to 6 months before file publication
  392.                         // so we compute the file date by adding 6 months to its first entry
  393.                         if (month.getNumber() > 6) {
  394.                             fileDate = new DateComponents(year + 1, month.getNumber() - 6, 1);
  395.                         } else {
  396.                             fileDate = new DateComponents(year, month.getNumber() + 6, 1);
  397.                         }
  398.                     }

  399.                     // check if there is already an entry for this date or not
  400.                     boolean addEntry = false;
  401.                     final Iterator<TimeStamped> iterator = data.tailSet(date).iterator();
  402.                     if (iterator.hasNext()) {
  403.                         final LineParameters existingEntry = (LineParameters) iterator.next();
  404.                         if (existingEntry.getDate().equals(date)) {
  405.                             // there is an entry for this date
  406.                             if (existingEntry.getFileDate().compareTo(fileDate) < 0) {
  407.                                 // the entry was read from an earlier file
  408.                                 // we replace it with the new entry as it is fresher
  409.                                 iterator.remove();
  410.                                 addEntry = true;
  411.                             }
  412.                         } else {
  413.                             // it is the first entry we get for this date
  414.                             addEntry = true;
  415.                         }
  416.                     } else {
  417.                         // it is the first entry we get for this date
  418.                         addEntry = true;
  419.                     }
  420.                     if (addEntry) {
  421.                         // we must add the new entry
  422.                         data.add(new LineParameters(fileDate, date,
  423.                                                     Double.parseDouble(matcher.group(f107Group)),
  424.                                                     Double.parseDouble(matcher.group(apGroup))));
  425.                     }

  426.                 } else {
  427.                     if (inData) {
  428.                         // we have already read some data, so we are not in the header anymore
  429.                         // however, we don't recognize this non-empty line,
  430.                         // we consider the file is corrupted
  431.                         throw new OrekitException(OrekitMessages.NOT_A_MARSHALL_SOLAR_ACTIVITY_FUTURE_ESTIMATION_FILE,
  432.                                                   name);
  433.                     }
  434.                 }
  435.             }
  436.         }

  437.         if (data.isEmpty()) {
  438.             throw new OrekitException(OrekitMessages.NOT_A_MARSHALL_SOLAR_ACTIVITY_FUTURE_ESTIMATION_FILE,
  439.                                       name);
  440.         }
  441.         firstDate = data.first().getDate();
  442.         lastDate  = data.last().getDate();

  443.     }

  444.     /** {@inheritDoc} */
  445.     public boolean stillAcceptsData() {
  446.         return true;
  447.     }

  448. }