1   /* Copyright 2011-2012 Space Applications Services
2    * Licensed to CS Communication & Systèmes (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.models.earth.troposphere;
18  
19  import java.util.Collections;
20  import java.util.List;
21  import java.util.regex.Pattern;
22  
23  import org.hipparchus.CalculusFieldElement;
24  import org.hipparchus.Field;
25  import org.hipparchus.analysis.interpolation.BilinearInterpolatingFunction;
26  import org.hipparchus.analysis.interpolation.LinearInterpolator;
27  import org.hipparchus.analysis.polynomials.PolynomialSplineFunction;
28  import org.hipparchus.util.FastMath;
29  import org.orekit.annotation.DefaultDataContext;
30  import org.orekit.bodies.FieldGeodeticPoint;
31  import org.orekit.bodies.GeodeticPoint;
32  import org.orekit.data.DataContext;
33  import org.orekit.data.DataProvidersManager;
34  import org.orekit.errors.OrekitException;
35  import org.orekit.errors.OrekitMessages;
36  import org.orekit.models.earth.weather.ConstantPressureTemperatureHumidityProvider;
37  import org.orekit.models.earth.weather.FieldPressureTemperatureHumidity;
38  import org.orekit.models.earth.weather.HeightDependentPressureTemperatureHumidityConverter;
39  import org.orekit.models.earth.weather.PressureTemperatureHumidity;
40  import org.orekit.models.earth.weather.PressureTemperatureHumidityProvider;
41  import org.orekit.models.earth.weather.water.Wang1988;
42  import org.orekit.time.AbsoluteDate;
43  import org.orekit.time.FieldAbsoluteDate;
44  import org.orekit.utils.FieldTrackingCoordinates;
45  import org.orekit.utils.InterpolationTableLoader;
46  import org.orekit.utils.ParameterDriver;
47  import org.orekit.utils.TrackingCoordinates;
48  
49  /** The modified Saastamoinen model. Estimates the path delay imposed to
50   * electro-magnetic signals by the troposphere according to the formula:
51   * <pre>
52   * δ = 2.277e-3 / cos z * (P + (1255 / T + 0.05) * e - B * tan² z) + δR
53   * </pre>
54   * with the following input data provided to the model:
55   * <ul>
56   * <li>z: zenith angle</li>
57   * <li>P: atmospheric pressure</li>
58   * <li>T: temperature</li>
59   * <li>e: partial pressure of water vapour</li>
60   * <li>B, δR: correction terms</li>
61   * </ul>
62   * <p>
63   * The model supports custom δR correction terms to be read from a
64   * configuration file (saastamoinen-correction.txt) via the
65   * {@link DataProvidersManager}.
66   * </p>
67   * @author Thomas Neidhart
68   * @see "Guochang Xu, GPS - Theory, Algorithms and Applications, Springer, 2007"
69   * @since 12.1
70   */
71  public class ModifiedSaastamoinenModel implements TroposphericModel {
72  
73      /** Default file name for δR correction term table. */
74      public static final String DELTA_R_FILE_NAME = "^saastamoinen-correction\\.txt$";
75  
76      /** Default lowest acceptable elevation angle [rad]. */
77      public static final double DEFAULT_LOW_ELEVATION_THRESHOLD = 0.05;
78  
79      /** Provider for water pressure. */
80      public static final Wang1988 WATER = new Wang1988();
81  
82      /** First pattern for δR correction term table. */
83      private static final Pattern FIRST_DELTA_R_PATTERN = Pattern.compile("^\\^");
84  
85      /** Second pattern for δR correction term table. */
86      private static final Pattern SECOND_DELTA_R_PATTERN = Pattern.compile("\\$$");
87  
88      /** Base delay coefficient. */
89      private static final double L0 = 2.277e-5;
90  
91      /** Temperature numerator. */
92      private static final double T_NUM = 1255;
93  
94      /** Wet offset. */
95      private static final double WET_OFFSET = 0.05;
96  
97      /** X values for the B function. */
98      private static final double[] X_VALUES_FOR_B = {
99          0.0, 500.0, 1000.0, 1500.0, 2000.0, 2500.0, 3000.0, 4000.0, 5000.0
100     };
101 
102     /** Y values for the B function.
103      * <p>
104      * The values have been scaled up by a factor 100.0 due to conversion from hPa to Pa.
105      * </p>
106      */
107     private static final double[] Y_VALUES_FOR_B = {
108         115.6, 107.9, 100.6, 93.8, 87.4, 81.3, 75.7, 65.4, 56.3
109     };
110 
111     /** Interpolation function for the B correction term. */
112     private static final PolynomialSplineFunction B_FUNCTION = new LinearInterpolator().interpolate(X_VALUES_FOR_B, Y_VALUES_FOR_B);
113 
114     /** Interpolation function for the delta R correction term. */
115     private final BilinearInterpolatingFunction deltaRFunction;
116 
117     /** Provider for atmospheric pressure, temperature and humidity at reference altitude. */
118     private final PressureTemperatureHumidityProvider pth0Provider;
119 
120     /** Height dependent converter for pressure, temperature and humidity. */
121     private final HeightDependentPressureTemperatureHumidityConverter converter;
122 
123     /** Lowest acceptable elevation angle [rad]. */
124     private double lowElevationThreshold;
125 
126     /**
127      * Create a new Saastamoinen model for the troposphere using the given environmental
128      * conditions and table from the reference book.
129      *
130      * @param pth0Provider provider for atmospheric pressure, temperature and humidity at reference altitude
131      * @see #ModifiedSaastamoinenModel(PressureTemperatureHumidityProvider, String, DataProvidersManager)
132      */
133     @DefaultDataContext
134     public ModifiedSaastamoinenModel(final PressureTemperatureHumidityProvider pth0Provider) {
135         this(pth0Provider, defaultDeltaR());
136     }
137 
138     /** Create a new Saastamoinen model for the troposphere using the given
139      * environmental conditions. This constructor uses the {@link DataContext#getDefault()
140      * default data context} if {@code deltaRFileName != null}.
141      *
142      * @param pth0Provider provider for atmospheric pressure, temperature and humidity at reference altitude
143      * @param deltaRFileName regular expression for filename containing δR
144      * correction term table (typically {@link #DELTA_R_FILE_NAME}), if null
145      * default values from the reference book are used
146      * @see #ModifiedSaastamoinenModel(PressureTemperatureHumidityProvider, String, DataProvidersManager)
147      */
148     @DefaultDataContext
149     public ModifiedSaastamoinenModel(final PressureTemperatureHumidityProvider pth0Provider,
150                                      final String deltaRFileName) {
151         this(pth0Provider, deltaRFileName,
152              DataContext.getDefault().getDataProvidersManager());
153     }
154 
155     /** Create a new Saastamoinen model for the troposphere using the given
156      * environmental conditions. This constructor allows the user to specify the source of
157      * of the δR file.
158      *
159      * @param pth0Provider provider for atmospheric pressure, temperature and humidity at reference altitude
160      * @param deltaRFileName regular expression for filename containing δR
161      * correction term table (typically {@link #DELTA_R_FILE_NAME}), if null
162      * default values from the reference book are used
163      * @param dataProvidersManager provides access to auxiliary data.
164      */
165     public ModifiedSaastamoinenModel(final PressureTemperatureHumidityProvider pth0Provider,
166                                      final String deltaRFileName,
167                                      final DataProvidersManager dataProvidersManager) {
168         this(pth0Provider,
169              deltaRFileName == null ?
170                      defaultDeltaR() :
171                      loadDeltaR(deltaRFileName, dataProvidersManager));
172     }
173 
174     /** Create a new Saastamoinen model.
175      *
176      * @param pth0Provider provider for atmospheric pressure, temperature and humidity at reference altitude
177      * @param deltaR δR correction term function
178      */
179     private ModifiedSaastamoinenModel(final PressureTemperatureHumidityProvider pth0Provider,
180                                       final BilinearInterpolatingFunction deltaR) {
181         this.pth0Provider          = pth0Provider;
182         this.converter             = new HeightDependentPressureTemperatureHumidityConverter(WATER);
183         this.deltaRFunction        = deltaR;
184         this.lowElevationThreshold = DEFAULT_LOW_ELEVATION_THRESHOLD;
185     }
186 
187     /** Create a new Saastamoinen model using a standard atmosphere model.
188      *
189      * <ul>
190      * <li>altitude: 0m</li>
191      * <li>temperature: 18 degree Celsius</li>
192      * <li>pressure: 1013.25 mbar</li>
193      * <li>humidity: 50%</li>
194      * <li>@link {@link Wang1988 Wang 1988} model to compute water vapor pressure</li>
195      * </ul>
196      *
197      * @return a Saastamoinen model with standard environmental values
198      */
199     @DefaultDataContext
200     public static ModifiedSaastamoinenModel getStandardModel() {
201         final double altitude    = 0;
202         final double pressure    = TroposphericModelUtils.HECTO_PASCAL.toSI(1013.25);
203         final double temperature = 273.15 + 18;
204         final double humidity    = 0.5;
205         final PressureTemperatureHumidity pth = new PressureTemperatureHumidity(altitude,
206                                                                                 pressure,
207                                                                                 temperature,
208                                                                                 WATER.waterVaporPressure(pressure,
209                                                                                                          temperature,
210                                                                                                          humidity),
211                                                                                 Double.NaN,
212                                                                                 Double.NaN);
213         final PressureTemperatureHumidityProvider pth0Provider = new ConstantPressureTemperatureHumidityProvider(pth);
214         return new ModifiedSaastamoinenModel(pth0Provider);
215     }
216 
217     /** Get provider for atmospheric pressure, temperature and humidity at reference altitude.
218      * @return provider for atmospheric pressure, temperature and humidity at reference altitude
219      */
220     public PressureTemperatureHumidityProvider getPth0Provider() {
221         return pth0Provider;
222     }
223 
224     /** {@inheritDoc}
225      * <p>
226      * The Saastamoinen model is not defined for altitudes below 0.0. for continuity
227      * reasons, we use the value for h = 0 when altitude is negative.
228      * </p>
229      * <p>
230      * There are also numerical issues for elevation angles close to zero. For continuity reasons,
231      * elevations lower than a threshold will use the value obtained
232      * for the threshold itself.
233      * </p>
234      * @see #getLowElevationThreshold()
235      * @see #setLowElevationThreshold(double)
236      */
237     @Override
238     public TroposphericDelay pathDelay(final TrackingCoordinates trackingCoordinates,
239                                        final GeodeticPoint point,
240                                        final PressureTemperatureHumidity weather,
241                                        final double[] parameters, final AbsoluteDate date) {
242 
243         // limit the height to model range
244         final double fixedHeight = FastMath.min(FastMath.max(point.getAltitude(), X_VALUES_FOR_B[0]),
245                                                 X_VALUES_FOR_B[X_VALUES_FOR_B.length - 1]);
246 
247         final PressureTemperatureHumidity pth = converter.convert(weather, fixedHeight);
248 
249         // interpolate the b correction term
250         final double B = B_FUNCTION.value(fixedHeight);
251 
252         // calculate the zenith angle from the elevation
253         final double z = FastMath.abs(0.5 * FastMath.PI -
254                                       FastMath.max(trackingCoordinates.getElevation(), lowElevationThreshold));
255 
256         // get correction factor
257         final double deltaR = getDeltaR(fixedHeight, z);
258 
259         // calculate the path delay in m
260         // beware since version 12.1 pressures are in Pa and not in hPa, hence the scaling has changed
261         final double invCos = 1.0 / FastMath.cos(z);
262         final double tan    = FastMath.tan(z);
263         final double zh     = L0 * pth.getPressure();
264         final double zw     = L0 * (T_NUM / pth.getTemperature() + WET_OFFSET) * pth.getWaterVaporPressure();
265         final double sh     = zh * invCos;
266         final double sw     = (zw - L0 * B * tan * tan) * invCos + deltaR;
267         return new TroposphericDelay(zh, zw, sh, sw);
268 
269     }
270 
271     /** {@inheritDoc}
272      * <p>
273      * The Saastamoinen model is not defined for altitudes below 0.0. for continuity
274      * reasons, we use the value for h = 0 when altitude is negative.
275      * </p>
276      * <p>
277      * There are also numerical issues for elevation angles close to zero. For continuity reasons,
278      * elevations lower than a threshold will use the value obtained
279      * for the threshold itself.
280      * </p>
281      * @see #getLowElevationThreshold()
282      * @see #setLowElevationThreshold(double)
283      */
284     @Override
285     public <T extends CalculusFieldElement<T>> FieldTroposphericDelay<T> pathDelay(final FieldTrackingCoordinates<T> trackingCoordinates,
286                                                                                    final FieldGeodeticPoint<T> point,
287                                                                                    final FieldPressureTemperatureHumidity<T> weather,
288                                                                                    final T[] parameters, final FieldAbsoluteDate<T> date) {
289 
290         // limit the height to model range
291         final T fixedHeight = FastMath.min(FastMath.max(point.getAltitude(), X_VALUES_FOR_B[0]),
292                                            X_VALUES_FOR_B[X_VALUES_FOR_B.length - 1]);
293 
294         final FieldPressureTemperatureHumidity<T> pth = converter.convert(weather, fixedHeight);
295 
296         final Field<T> field = date.getField();
297         final T zero = field.getZero();
298 
299         // interpolate the b correction term
300         final T B = B_FUNCTION.value(fixedHeight);
301 
302         // calculate the zenith angle from the elevation
303         final T z = FastMath.abs(FastMath.max(trackingCoordinates.getElevation(),
304                                               zero.newInstance(lowElevationThreshold)).negate().
305                                  add(zero.getPi().multiply(0.5)));
306 
307         // get correction factor
308         final T deltaR = getDeltaR(fixedHeight, z, field);
309 
310         // calculate the path delay in m
311         // beware since version 12.1 pressures are in Pa and not in hPa, hence the scaling has changed
312         final T invCos = FastMath.cos(z).reciprocal();
313         final T tan    = FastMath.tan(z);
314         final T zh     = pth.getPressure().multiply(L0);
315         final T zw     = pth.getTemperature().reciprocal().multiply(T_NUM).add(WET_OFFSET).
316                          multiply(pth.getWaterVaporPressure()).multiply(L0);
317         final T sh     = zh.multiply(invCos);
318         final T sw     = zw.subtract(B.multiply(tan).multiply(tan).multiply(L0)).multiply(invCos).add(deltaR);
319         return new FieldTroposphericDelay<>(zh, zw, sh, sw);
320 
321     }
322 
323     /** Calculates the delta R correction term using linear interpolation.
324      * @param height the height of the station in m
325      * @param zenith the zenith angle of the satellite
326      * @return the delta R correction term in m
327      */
328     private double getDeltaR(final double height, final double zenith) {
329         // limit the height to a range of [0, 5000] m
330         final double h = FastMath.min(FastMath.max(0, height), 5000);
331         // limit the zenith angle to 90 degree
332         // Note: the function is symmetric for negative zenith angles
333         final double z = FastMath.min(Math.abs(zenith), 0.5 * FastMath.PI);
334         return deltaRFunction.value(h, z);
335     }
336 
337     /** Calculates the delta R correction term using linear interpolation.
338      * @param <T> type of the elements
339      * @param height the height of the station in m
340      * @param zenith the zenith angle of the satellite
341      * @param field field used by default
342      * @return the delta R correction term in m
343      */
344     private  <T extends CalculusFieldElement<T>> T getDeltaR(final T height, final T zenith,
345                                                          final Field<T> field) {
346         final T zero = field.getZero();
347         // limit the height to a range of [0, 5000] m
348         final T h = FastMath.min(FastMath.max(zero, height), zero.add(5000));
349         // limit the zenith angle to 90 degree
350         // Note: the function is symmetric for negative zenith angles
351         final T z = FastMath.min(zenith.abs(), zero.getPi().multiply(0.5));
352         return deltaRFunction.value(h, z);
353     }
354 
355     /** Load δR function.
356      * @param deltaRFileName regular expression for filename containing δR
357      * correction term table
358      * @param dataProvidersManager provides access to auxiliary data.
359      * @return δR function
360      */
361     private static BilinearInterpolatingFunction loadDeltaR(
362             final String deltaRFileName,
363             final DataProvidersManager dataProvidersManager) {
364 
365         // read the δR interpolation function from the config file
366         final InterpolationTableLoader loader = new InterpolationTableLoader();
367         dataProvidersManager.feed(deltaRFileName, loader);
368         if (!loader.stillAcceptsData()) {
369             final double[] elevations = loader.getOrdinateGrid();
370             for (int i = 0; i < elevations.length; ++i) {
371                 elevations[i] = FastMath.toRadians(elevations[i]);
372             }
373             return new BilinearInterpolatingFunction(loader.getAbscissaGrid(), elevations,
374                                                      loader.getValuesSamples());
375         }
376         throw new OrekitException(OrekitMessages.UNABLE_TO_FIND_FILE,
377                                   SECOND_DELTA_R_PATTERN.
378                                   matcher(FIRST_DELTA_R_PATTERN.matcher(deltaRFileName).replaceAll("")).
379                                   replaceAll(""));
380     }
381 
382     /** Create the default δR function.
383      * @return δR function
384      */
385     private static BilinearInterpolatingFunction defaultDeltaR() {
386 
387         // the correction table in the referenced book only contains values for an angle of 60 - 80
388         // degree, thus for 0 degree, the correction term is assumed to be 0, for degrees > 80 it
389         // is assumed to be the same value as for 80.
390 
391         // the height in m
392         final double[] xValForR = {
393             0, 500, 1000, 1500, 2000, 3000, 4000, 5000
394         };
395 
396         // the zenith angle
397         final double[] yValForR = {
398             FastMath.toRadians( 0.00), FastMath.toRadians(60.00), FastMath.toRadians(66.00), FastMath.toRadians(70.00),
399             FastMath.toRadians(73.00), FastMath.toRadians(75.00), FastMath.toRadians(76.00), FastMath.toRadians(77.00),
400             FastMath.toRadians(78.00), FastMath.toRadians(78.50), FastMath.toRadians(79.00), FastMath.toRadians(79.50),
401             FastMath.toRadians(79.75), FastMath.toRadians(80.00), FastMath.toRadians(90.00)
402         };
403 
404         final double[][] fval = new double[][] {
405             {
406                 0.000, 0.003, 0.006, 0.012, 0.020, 0.031, 0.039, 0.050, 0.065, 0.075, 0.087, 0.102, 0.111, 0.121, 0.121
407             }, {
408                 0.000, 0.003, 0.006, 0.011, 0.018, 0.028, 0.035, 0.045, 0.059, 0.068, 0.079, 0.093, 0.101, 0.110, 0.110
409             }, {
410                 0.000, 0.002, 0.005, 0.010, 0.017, 0.025, 0.032, 0.041, 0.054, 0.062, 0.072, 0.085, 0.092, 0.100, 0.100
411             }, {
412                 0.000, 0.002, 0.005, 0.009, 0.015, 0.023, 0.029, 0.037, 0.049, 0.056, 0.065, 0.077, 0.083, 0.091, 0.091
413             }, {
414                 0.000, 0.002, 0.004, 0.008, 0.013, 0.021, 0.026, 0.033, 0.044, 0.051, 0.059, 0.070, 0.076, 0.083, 0.083
415             }, {
416                 0.000, 0.002, 0.003, 0.006, 0.011, 0.017, 0.021, 0.027, 0.036, 0.042, 0.049, 0.058, 0.063, 0.068, 0.068
417             }, {
418                 0.000, 0.001, 0.003, 0.005, 0.009, 0.014, 0.017, 0.022, 0.030, 0.034, 0.040, 0.047, 0.052, 0.056, 0.056
419             }, {
420                 0.000, 0.001, 0.002, 0.004, 0.007, 0.011, 0.014, 0.018, 0.024, 0.028, 0.033, 0.039, 0.043, 0.047, 0.047
421             }
422         };
423 
424         // the actual delta R is interpolated using a a bilinear interpolator
425         return new BilinearInterpolatingFunction(xValForR, yValForR, fval);
426 
427     }
428 
429     /** {@inheritDoc} */
430     @Override
431     public List<ParameterDriver> getParametersDrivers() {
432         return Collections.emptyList();
433     }
434 
435     /** Get the low elevation threshold value for path delay computation.
436      * @return low elevation threshold, in rad.
437      * @see #pathDelay(TrackingCoordinates, GeodeticPoint, PressureTemperatureHumidity, double[], AbsoluteDate)
438      * @see #pathDelay(FieldTrackingCoordinates, FieldGeodeticPoint, FieldPressureTemperatureHumidity, CalculusFieldElement[], FieldAbsoluteDate)
439      * @since 10.2
440      */
441     public double getLowElevationThreshold() {
442         return lowElevationThreshold;
443     }
444 
445     /** Set the low elevation threshold value for path delay computation.
446      * @param lowElevationThreshold The new value for the threshold [rad]
447      * @see #pathDelay(TrackingCoordinates, GeodeticPoint, PressureTemperatureHumidity, double[], AbsoluteDate)
448      * @see #pathDelay(FieldTrackingCoordinates, FieldGeodeticPoint, FieldPressureTemperatureHumidity, CalculusFieldElement[], FieldAbsoluteDate)
449      * @since 10.2
450      */
451     public void setLowElevationThreshold(final double lowElevationThreshold) {
452         this.lowElevationThreshold = lowElevationThreshold;
453     }
454 }
455