MarshallSolarActivityFutureEstimation.java

  1. /* Copyright 2002-2018 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.atmosphere.data;

  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.Iterator;
  25. import java.util.SortedSet;
  26. import java.util.TreeSet;
  27. import java.util.regex.Matcher;
  28. import java.util.regex.Pattern;

  29. import org.hipparchus.util.FastMath;
  30. import org.orekit.data.DataLoader;
  31. import org.orekit.data.DataProvidersManager;
  32. import org.orekit.errors.OrekitException;
  33. import org.orekit.errors.OrekitMessages;
  34. import org.orekit.forces.drag.atmosphere.DTM2000InputParameters;
  35. import org.orekit.time.AbsoluteDate;
  36. import org.orekit.time.ChronologicalComparator;
  37. import org.orekit.time.DateComponents;
  38. import org.orekit.time.Month;
  39. import org.orekit.time.TimeScale;
  40. import org.orekit.time.TimeScalesFactory;
  41. import org.orekit.time.TimeStamped;

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

  87.     /** Strength level of activity. */
  88.     public enum StrengthLevel {

  89.         /** Strong level of activity. */
  90.         STRONG,

  91.         /** Average level of activity. */
  92.         AVERAGE,

  93.         /** Weak level of activity. */
  94.         WEAK

  95.     }

  96.     /** Serializable UID. */
  97.     private static final long serialVersionUID = -5212198874900835369L;

  98.     /** Pattern for the data fields of MSAFE data. */
  99.     private final Pattern dataPattern;

  100.     /** Data set. */
  101.     private final SortedSet<TimeStamped> data;

  102.     /** Selected strength level of activity. */
  103.     private final StrengthLevel strengthLevel;

  104.     /** First available date. */
  105.     private AbsoluteDate firstDate;

  106.     /** Last available date. */
  107.     private AbsoluteDate lastDate;

  108.     /** Previous set of solar activity parameters. */
  109.     private LineParameters previousParam;

  110.     /** Current set of solar activity parameters. */
  111.     private LineParameters currentParam;

  112.     /** Regular expression for supported files names. */
  113.     private final String supportedNames;

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

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

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

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

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

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

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

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

  155.         // compile the pattern
  156.         dataPattern = Pattern.compile(builder.toString());

  157.     }

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

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

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

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

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

  189.     }

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

  196.     /** {@inheritDoc} */
  197.     public AbsoluteDate getMinDate() throws OrekitException {
  198.         if (firstDate == null) {
  199.             DataProvidersManager.getInstance().feed(getSupportedNames(), this);
  200.         }
  201.         return firstDate;
  202.     }

  203.     /** {@inheritDoc} */
  204.     public AbsoluteDate getMaxDate() throws OrekitException {
  205.         if (firstDate == null) {
  206.             DataProvidersManager.getInstance().feed(getSupportedNames(), this);
  207.         }
  208.         return lastDate;
  209.     }

  210.     /** {@inheritDoc} */
  211.     public double getInstantFlux(final AbsoluteDate date) throws OrekitException {
  212.         return getMeanFlux(date);
  213.     }

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

  216.         // get the neighboring dates
  217.         bracketDate(date);

  218.         // perform a linear interpolation
  219.         final AbsoluteDate previousDate = previousParam.getDate();
  220.         final AbsoluteDate currentDate  = currentParam.getDate();
  221.         final double dt                 = currentDate.durationFrom(previousDate);
  222.         final double previousF107       = previousParam.getF107();
  223.         final double currentF107        = currentParam.getF107();
  224.         final double previousWeight     = currentDate.durationFrom(date)  / dt;
  225.         final double currentWeight      = date.durationFrom(previousDate) / dt;

  226.         return previousF107 * previousWeight + currentF107 * currentWeight;

  227.     }

  228.     /** {@inheritDoc} */
  229.     public double getThreeHourlyKP(final AbsoluteDate date) throws OrekitException {
  230.         return get24HoursKp(date);
  231.     }

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

  254.     /** The Kp index is derived from the Ap index.
  255.      * <p>The method used is explained on <a
  256.      * href="http://www.ngdc.noaa.gov/stp/GEOMAG/kp_ap.html">
  257.      * NOAA website.</a> as follows:</p>
  258.      * <p>The scale is 0 to 9 expressed in thirds of a unit, e.g. 5- is 4 2/3,
  259.      * 5 is 5 and 5+ is 5 1/3. The ap (equivalent range) index is derived from
  260.      * the Kp index as follows:</p>
  261.      * <table border="1">
  262.      * <caption>Kp / Ap Conversion Table</caption>
  263.      * <tbody>
  264.      * <tr>
  265.      * <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>
  266.      * </tr>
  267.      * <tr>
  268.      * <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>
  269.      * </tr>
  270.      * <tr>
  271.      * <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>
  272.      * </tr>
  273.      * <tr>
  274.      * <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>
  275.      * </tr>
  276.      * </tbody>
  277.      * </table>
  278.      * @param date date of the Kp data
  279.      * @return the 24H geomagnetic index
  280.      * @exception OrekitException if the date is out of range of available data
  281.      */
  282.     public double get24HoursKp(final AbsoluteDate date) throws OrekitException {

  283.         // get the neighboring dates
  284.         bracketDate(date);

  285.         // perform a linear interpolation
  286.         final AbsoluteDate previousDate = previousParam.getDate();
  287.         final AbsoluteDate currentDate  = currentParam.getDate();
  288.         final double dt                 = currentDate.durationFrom(previousDate);
  289.         final double previousAp         = previousParam.getAp();
  290.         final double currentAp          = currentParam.getAp();
  291.         final double previousWeight     = currentDate.durationFrom(date)  / dt;
  292.         final double currentWeight      = date.durationFrom(previousDate) / dt;
  293.         final double ap                 = previousAp * previousWeight + currentAp * currentWeight;

  294.         // calculating Ap index, then corresponding Kp index
  295.         // equation 4 in [1] for Ap to Kp conversion
  296.         return 1.89 * FastMath.asinh(0.154 * ap);
  297.     }

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

  300.         /** Serializable UID. */
  301.         private static final long serialVersionUID = 6607862001953526475L;

  302.         /** File date. */
  303.         private final DateComponents fileDate;

  304.         /** Entry date. */
  305.         private  final AbsoluteDate date;

  306.         /** F10.7 flux at date. */
  307.         private final double f107;

  308.         /** Ap index at date. */
  309.         private final double ap;

  310.         /** Simple constructor.
  311.          * @param fileDate file date
  312.          * @param date entry date
  313.          * @param f107 F10.7 flux at date
  314.          * @param ap Ap index at date
  315.          */
  316.         private LineParameters(final DateComponents fileDate, final AbsoluteDate date, final double f107, final double ap) {
  317.             this.fileDate = fileDate;
  318.             this.date     = date;
  319.             this.f107     = f107;
  320.             this.ap       = ap;
  321.         }

  322.         /** Get the file date.
  323.          * @return file date
  324.          */
  325.         public DateComponents getFileDate() {
  326.             return fileDate;
  327.         }

  328.         /** Get the current date.
  329.          * @return current date
  330.          */
  331.         public AbsoluteDate getDate() {
  332.             return date;
  333.         }

  334.         /** Get the F10.0 flux.
  335.          * @return f10.7 flux
  336.          */
  337.         public double getF107() {
  338.             return f107;
  339.         }

  340.         /** Get the Ap index.
  341.          * @return Ap index
  342.          */
  343.         public double getAp() {
  344.             return ap;
  345.         }

  346.     }

  347.     /** {@inheritDoc} */
  348.     public void loadData(final InputStream input, final String name)
  349.         throws IOException, ParseException, OrekitException {

  350.         // select the groups we want to store
  351.         final int f107Group;
  352.         final int apGroup;
  353.         switch (strengthLevel) {
  354.             case STRONG :
  355.                 f107Group = 3;
  356.                 apGroup   = 6;
  357.                 break;
  358.             case AVERAGE :
  359.                 f107Group = 4;
  360.                 apGroup   = 7;
  361.                 break;
  362.             default :
  363.                 f107Group = 5;
  364.                 apGroup   = 8;
  365.                 break;
  366.         }

  367.         // read the data
  368.         final BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
  369.         boolean inData = false;
  370.         final TimeScale utc = TimeScalesFactory.getUTC();
  371.         DateComponents fileDate = null;
  372.         for (String line = reader.readLine(); line != null; line = reader.readLine()) {
  373.             line = line.trim();
  374.             if (line.length() > 0) {
  375.                 final Matcher matcher = dataPattern.matcher(line);
  376.                 if (matcher.matches()) {

  377.                     // we are in the data section
  378.                     inData = true;

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

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

  419.                 } else {
  420.                     if (inData) {
  421.                         // we have already read some data, so we are not in the header anymore
  422.                         // however, we don't recognize this non-empty line,
  423.                         // we consider the file is corrupted
  424.                         throw new OrekitException(OrekitMessages.NOT_A_MARSHALL_SOLAR_ACTIVITY_FUTURE_ESTIMATION_FILE,
  425.                                                   name);
  426.                     }
  427.                 }
  428.             }
  429.         }

  430.         if (data.isEmpty()) {
  431.             throw new OrekitException(OrekitMessages.NOT_A_MARSHALL_SOLAR_ACTIVITY_FUTURE_ESTIMATION_FILE,
  432.                                       name);
  433.         }
  434.         firstDate = data.first().getDate();
  435.         lastDate  = data.last().getDate();

  436.     }

  437.     /** {@inheritDoc} */
  438.     public boolean stillAcceptsData() {
  439.         return true;
  440.     }

  441. }