Example #1
0
        public static ClimateParameter ParseParam(ref int paramNum, string[] args)
        {
            if (paramNum == args.Length)
            {
                throw new ArgumentException("Parameter type is not present");
            }
            string str = args[paramNum++].ToUpper();

            try
            {
                if (Conventions.Namings.ParameterShortNames.Values.Select(v => v.ToUpper()).Contains(str))
                {
                    foreach (var p in Conventions.Namings.ParameterShortNames)
                    {
                        if (str == p.Value)
                        {
                            return(p.Key);
                        }
                    }
                }
                ClimateParameter pa = (ClimateParameter)(Enum.Parse(typeof(ClimateParameter), str, true));
                return(pa);
            }
            catch (ArgumentException exc)
            {
                throw new ArgumentException("Invalid climate parameter name. Check syntax.");
            }
        }
 public FetchClimateSingleResponce FetchClimate(ClimateParameter parameter, double latmin, double latmax, double lonmin, double lonmax, int starthour, int stophour, int startday, int stopday, int startyear, int stopyear, FetchingOptions options)
 {
     AssertFcParameters(latmin, latmax, lonmin, lonmax, starthour, stophour, startday, stopday, startyear, stopyear);
     using (var requestDs = DataSet.Open("msds:memory"))
     {
         FetchClimateRequestBuilder.FillDataSetWithRequest(requestDs, parameter, latmin, latmax, lonmin, lonmax, starthour, stophour, startday, stopday, startyear, stopyear, options);
         using (var result = ServerProcess(requestDs))
         {
             return(FetchClimateRequestBuilder.BuildSingleCellResult(result));
         }
     }
 }
        public double[,] FetchClimateGrid(ClimateParameter parameter, double latmin, double latmax, double lonmin, double lonmax, int hourmin, int hourmax, int daymin, int daymax, int yearmin, int yearmax, double dlat, double dlon, EnvironmentalDataSource ds)
        {
            ClimateParameterValue[,] vals = FetchClimateGrid(parameter, latmin, latmax, lonmin, lonmax, hourmin, hourmax, daymin, daymax, yearmin, yearmax, dlat, dlon, new FetchingOptions(ds)).Values;
            int l0 = vals.GetLength(0);
            int l1 = vals.GetLength(1);

            double[,] doubleVals = new double[l0, l1];
            for (int i = 0; i < l0; i++)
            {
                for (int j = 0; j < l1; j++)
                {
                    doubleVals[i, j] = vals[i, j].GetValueInDefaultClientUnits();
                }
            }
            return(doubleVals);
        }
        public FetchClimateBatchResponce FetchClimate(ClimateParameter parameter, double[] latmin, double[] latmax, double[] lonmin, double[] lonmax, int[] starthour, int[] stophour, int[] startday, int[] stopday, int[] startyear, int[] stopyear, FetchingOptions options, ResearchVariationType variationType)
        {
            if (startday == null)
            {
                startday = Enumerable.Repeat(GlobalConsts.DefaultValue, latmin.Length).ToArray();
            }
            if (stopday == null)
            {
                stopday = Enumerable.Repeat(GlobalConsts.DefaultValue, latmin.Length).ToArray();
            }
            if (starthour == null)
            {
                starthour = Enumerable.Repeat(GlobalConsts.DefaultValue, latmin.Length).ToArray();
            }
            if (stophour == null)
            {
                stophour = Enumerable.Repeat(GlobalConsts.DefaultValue, latmin.Length).ToArray();
            }
            if (startyear == null)
            {
                startyear = Enumerable.Repeat(GlobalConsts.StartYear, latmin.Length).ToArray();
            }
            if (stopyear == null)
            {
                stopyear = Enumerable.Repeat(GlobalConsts.EndYear, latmin.Length).ToArray();
            }

            for (int i = 0; i < latmin.Length; i++)
            {
                AssertFcParameters(latmin[i], latmax[i], lonmin[i], lonmax[i], starthour[i], stophour[i], startday[i], stopday[i], startyear[i], stopyear[i]);
            }

            using (var requestDs = DataSet.Open("msds:memory"))
            {
                FetchClimateRequestBuilder.FillDataSetWithRequest(requestDs, parameter, latmin, latmax, lonmin, lonmax, starthour, stophour, startday, stopday, startyear, stopyear, options);
                requestDs.Metadata[Namings.metadataNameVariationType] = variationType.ToString();
                requestDs.Commit();
                using (var result = ServerProcess(requestDs))
                {
                    return(FetchClimateRequestBuilder.BuildBatchResult(result));
                }
            }
        }
        public static void FillDataSetWithRequest(DataSet ds, ClimateParameter parameter, double[] latmin, double[] latmax, double[] lonmin, double[] lonmax, int[] starthour, int[] stophour, int[] startday, int[] stopday, int[] startyear, int[] stopyear, FetchingOptions options)
        {
            ds.IsAutocommitEnabled = false;

            ds.Metadata[Namings.metadataNameParameter] = Namings.GetParameterName(parameter);
            ds.Metadata[Namings.metadataNameCoverage] = Namings.GetCoverageName(parameter);
            ds.Metadata[Namings.metadataNameProvenanceHint] = options.FetchClimateProvenanceControlStr;

            if (!ds.Variables.Contains(Namings.VarNameLatMax))
                ds.AddVariable<double>(Namings.VarNameLatMax, Namings.dimNameCells);
            if (!ds.Variables.Contains(Namings.VarNameLatMin))
                ds.AddVariable<double>(Namings.VarNameLatMin, Namings.dimNameCells);
            if (!ds.Variables.Contains(Namings.VarNameLonMax))
                ds.AddVariable<double>(Namings.VarNameLonMax, Namings.dimNameCells);
            if (!ds.Variables.Contains(Namings.VarNameLonMin))
                ds.AddVariable<double>(Namings.VarNameLonMin, Namings.dimNameCells);
            if (!ds.Variables.Contains(Namings.VarNameDayMax))
                ds.AddVariable<int>(Namings.VarNameDayMax, Namings.dimNameCells);
            if (!ds.Variables.Contains(Namings.VarNameDayMin))
                ds.AddVariable<int>(Namings.VarNameDayMin, Namings.dimNameCells);
            if (!ds.Variables.Contains(Namings.VarNameHourMax))
                ds.AddVariable<int>(Namings.VarNameHourMax, Namings.dimNameCells);
            if (!ds.Variables.Contains(Namings.VarNameHourMin))
                ds.AddVariable<int>(Namings.VarNameHourMin, Namings.dimNameCells);
            if (!ds.Variables.Contains(Namings.VarNameYearMax))
                ds.AddVariable<int>(Namings.VarNameYearMax, Namings.dimNameCells);
            if (!ds.Variables.Contains(Namings.VarNameYearMin))
                ds.AddVariable<int>(Namings.VarNameYearMin, Namings.dimNameCells);

            ds.Variables[Namings.VarNameDayMax].Append(stopday);
            ds.Variables[Namings.VarNameDayMin].Append(startday);
            ds.Variables[Namings.VarNameHourMax].Append(stophour);
            ds.Variables[Namings.VarNameHourMin].Append(starthour);
            ds.Variables[Namings.VarNameYearMax].Append(stopyear);
            ds.Variables[Namings.VarNameYearMin].Append(startyear);
            ds.Variables[Namings.VarNameLonMax].Append(lonmax);
            ds.Variables[Namings.VarNameLonMin].Append(lonmin);
            ds.Variables[Namings.VarNameLatMax].Append(latmax);
            ds.Variables[Namings.VarNameLatMin].Append(latmin);

            ds.Commit();
        }
        internal double[] FetchClimate(ClimateParameter parameter, double[] latmin, double[] latmax, double[] lonmin, double[] lonmax, int[] starthour, int[] stophour, int[] startday, int[] stopday, int[] startyear, int[] stopyear)
        {
            if (startday == null)
            {
                startday = Enumerable.Repeat(GlobalConsts.DefaultValue, latmin.Length).ToArray();
            }
            if (stopday == null)
            {
                stopday = Enumerable.Repeat(GlobalConsts.DefaultValue, latmin.Length).ToArray();
            }
            if (starthour == null)
            {
                starthour = Enumerable.Repeat(GlobalConsts.DefaultValue, latmin.Length).ToArray();
            }
            if (stophour == null)
            {
                stophour = Enumerable.Repeat(GlobalConsts.DefaultValue, latmin.Length).ToArray();
            }
            if (startyear == null)
            {
                startyear = Enumerable.Repeat(GlobalConsts.StartYear, latmin.Length).ToArray();
            }
            if (stopyear == null)
            {
                stopyear = Enumerable.Repeat(GlobalConsts.EndYear, latmin.Length).ToArray();
            }

            for (int i = 0; i < latmin.Length; i++)
            {
                AssertFcParameters(latmin[i], latmax[i], lonmin[i], lonmax[i], starthour[i], stophour[i], startday[i], stopday[i], startyear[i], stopyear[i]);
            }
            using (var requestDs = DataSet.Open("msds:memory"))
            {
                FetchClimateRequestBuilder.FillDataSetWithRequest(requestDs, parameter, latmin, latmax, lonmin, lonmax, starthour, stophour, startday, stopday, startyear, stopyear, new FetchingOptions());
                using (var result = ServerProcess(requestDs))
                {
                    return(FetchClimateRequestBuilder.BuildBatchResult(result).Values.Select(v => v.GetValueInDefaultClientUnits()).ToArray());
                }
            }
        }
 /// <summary>
 /// Creates new variable with data from the FetchClimate service for the current lat/lon coordinate system and given time.
 /// </summary>
 /// <param name="ds">Target DataSet.</param>
 /// <param name="parameter">A climate parameter to fetch.</param>
 /// <param name="name">Name of the variable.</param>
 /// <param name="lat">Name of the variable that is a latutude axis.</param>
 /// <param name="lon">Name of the variable that is a longitude axis.</param>
 /// <param name="times">Name of the variable that is a time axis.</param>
 /// <returns>New variable instance.</returns>
 /// <remarks>
 /// <para>
 /// The method allows to explicitly specify axes of the coordinate system for the new variable.
 /// See remarks for <see cref="Fetch(DataSet, ClimateParameter, string)"/>
 /// </para>
 /// </remarks>
 public static Variable Fetch(this DataSet ds, ClimateParameter parameter, string name, string lat, string lon, string times, string nameUncertainty = null, string nameProvenance = null, EnvironmentalDataSource dataSource = EnvironmentalDataSource.ANY)
 {
     TimeBounds[] tb = GetClimatologyBounds(ds, ds[times].ID);
     return Fetch(ds, parameter, name, ds[lat], ds[lon], ds[times], nameUncertainty, nameProvenance, dataSource, tb.Length == 0 ? null : tb);
 }
 /// <summary>
 /// Creates new variable with data from the FetchClimate service for the current lat/lon coordinate system and given time.
 /// </summary>
 /// <param name="ds">Target DataSet.</param>
 /// <param name="parameter">A climate parameter to fetch.</param>
 /// <param name="name">Name of the variable.</param>
 /// <param name="lat">Name of the variable that is a latutude axis.</param>
 /// <param name="lon">Name of the variable that is a longitude axis.</param>
 /// <param name="time">Time moment to fetch data for.</param>
 /// <returns>New variable instance.</returns>
 /// <remarks>
 /// <para>
 /// The method allows to explicitly specify axes of the coordinate system for the new variable.
 /// See remarks for <see cref="Fetch(DataSet, ClimateParameter, string, DateTime)"/>
 /// </para>
 /// </remarks>
 public static Variable Fetch(this DataSet ds, ClimateParameter parameter, string name, string lat, string lon, DateTime time, string nameUncertainty = null, string nameProvenance = null, EnvironmentalDataSource dataSource = EnvironmentalDataSource.ANY)
 {
     return Fetch(ds, parameter, name, ds[lat], ds[lon], time, nameUncertainty, nameProvenance, dataSource);
 }
        /// <summary>
        /// Creates new variable with data from the FetchClimate service for the current lat/lon coordinate system and given time.
        /// </summary>
        /// <param name="ds">Target DataSet.</param>
        /// <param name="parameter">A climate parameter to fetch.</param>
        /// <param name="name">Name of the variable.</param>
        /// <param name="time">Time moment to fetch data for.</param>
        /// <returns>New variable instance.</returns>
        /// <remarks>
        /// <para>
        /// The method looks up the <paramref name="ds"/> for the lat/lon coordinate system.
        /// An axis is considered as a latitude grid if at least one of the following conditions are satisfied 
        /// (case is ignored in all rules):
        /// <list type="bullet">
        /// <item><description>axis name starts with either "lat" or "_lat";</description></item>
        /// <item><description>axis name contains substring "latitude";</description></item>
        /// <item><description>axis has attribute Units containing substring "degree" and ends with "n" or "north".</description></item>
        /// </list>
        /// Similar rules for longitude axis:
        /// <list type="bullet">
        /// <item><description>axis name starts with either "lon" or "_lon";</description></item>
        /// <item><description>axis name contains substring "longitude";</description></item>
        /// <item><description>axis has attribute Units containing substring "degree" and ends with "e" or "east".</description></item>
        /// </list>       
        /// </para>
        /// <para>If the axes not found, an exception is thrown.</para>
        /// <para>When a coordinate system is found, the Fetch Climate service is requested using a single batch request;
        /// result is added to the DataSet as 2d-variable depending on lat/lon axes. 
        /// The DisplayName, long_name, Units, MissingValue, Provenance and Time attributes of the variable are set.
        /// </para>
        /// <example>
        /// <code>
        ///  // Fetching climate parameters for fixed time moment
        ///  using (var ds = DataSet.Open("msds:memory"))
        ///  {
        ///      Console.WriteLine("Filling dataset...");
        ///      ds.AddAxis("lon", "degrees East", -12.5, 20.0, 0.5);
        ///      ds.AddAxis("lat", "degrees North", 35.0, 60.0, 0.5);
        ///      
        ///      ds.Fetch(ClimateParameter.FC_TEMPERATURE, "airt", new DateTime(2000, 7, 19, 11, 0, 0)); // time is fixed hence airt is 2d (depends on lat and lon)
        ///      ds.Fetch(ClimateParameter.FC_SOIL_MOISTURE, "soilm", new DateTime(2000, 7, 19, 11, 0, 0));
        ///
        ///      Console.WriteLine("Running DataSet Viewer...");
        ///      ds.View(@"airt(lon,lat) Style:Colormap; Palette:-5=Blue,White=0,#F4EF2F=5,Red=20; MapType:Aerial; Transparency:0.57000000000000006;;soilm(lon,lat) Style:Colormap; Palette:0=#00000000,#827DAAEC=300,#0000A0=800; Transparency:0; MapType:Aerial");
        ///  }
        ///
        ///  // Fetching climate parameters for different time moments
        ///  using (var ds = DataSet.Open("msds:memory"))
        ///  {
        ///      Console.WriteLine("Filling dataset...");
        ///      ds.AddAxis("lon", "degrees East", -12.5, 20.0, 2.0);
        ///      ds.AddAxis("lat", "degrees North", 35.0, 60.0, 2.0);
        ///      ds.AddAxis("time", new DateTime(2000, 7, 19, 0, 0, 0), new DateTime(2000, 7, 19, 23, 0, 0), TimeSpan.FromHours(2));
        ///
        ///      ds.Fetch(ClimateParameter.FC_TEMPERATURE, "airt"); // airt depends on lat,lon,time
        ///      ds.Fetch(ClimateParameter.FC_SOIL_MOISTURE, "soilm");
        ///
        ///      Console.WriteLine("Running DataSet Viewer...");
        ///      ds.View(@"airt(lon,lat) Style:Colormap; Palette:-5=Blue,White=0,#F4EF2F=5,Red=20; MapType:Aerial; Transparency:0.57000000000000006;;soilm(lon,lat) Style:Colormap; Palette:0=#00000000,#827DAAEC=300,#0000A0=800; Transparency:0; MapType:Aerial");
        ///  }
        /// </code>
        /// </example>
        /// </remarks>
        public static Variable Fetch(this DataSet ds, ClimateParameter parameter, string name, DateTime time, string nameUncertainty = null, string nameProvenance = null, EnvironmentalDataSource dataSource = EnvironmentalDataSource.ANY)
        {
            Variable lat = null, lon = null;
            var axisVars = GetDefaultCoordinateSystem(ds);
            if (axisVars.Length > 1)
            {
                for (int i = 0; i < axisVars.Length; i++)
                {
                    var var = axisVars[i];
                    if (lat == null && GeoConventions.IsLatitude(var))
                        lat = var;
                    else if (lon == null && GeoConventions.IsLongitude(var))
                        lon = var;
                }
            }
            else
            {//looking for pointset
                var vars = ds.Variables.Where(v => v.Rank == 1).ToArray();

                for (int i = 0; i < vars.Length; i++)
                {
                    if (!GeoConventions.IsLatitude(vars[i]))
                        continue;
                    lat = vars[i];
                    foreach (Variable posLon in vars.Where((u, j) => j != i))
                        if (GeoConventions.IsLongitude(posLon))
                        {
                            lon = posLon;
                            break;
                        }
                }
            }
            return Fetch(ds, parameter, name, lat, lon, time, nameUncertainty: nameUncertainty, nameProvenance: nameProvenance, dataSource: dataSource);
        }
 public double[,] FetchClimateGrid(ClimateParameter parameter, double latmin, double latmax, double lonmin, double lonmax, int hourmin, int hourmax, int daymin, int daymax, int yearmin, int yearmax, double dlat, double dlon,EnvironmentalDataSource ds)
 {
     ClimateParameterValue[,] vals = FetchClimateGrid(parameter, latmin, latmax, lonmin, lonmax, hourmin, hourmax, daymin, daymax, yearmin, yearmax, dlat, dlon, new FetchingOptions(ds)).Values;
     int l0 = vals.GetLength(0);
     int l1 = vals.GetLength(1);
     double[,] doubleVals = new double[l0, l1];
     for (int i = 0; i < l0; i++)
         for (int j = 0; j < l1; j++)
             doubleVals[i, j] = vals[i, j].GetValueInDefaultClientUnits();
     return doubleVals;
 }
 public FetchClimateBatchResponce FetchClimateHourly(ClimateParameter p, double latmin, double latmax, double lonmin, double lonmax, int hourmin, int hourmax, int daymin, int daymax, int yearmin, int yearmax, int dhour, FetchingOptions options)
 {
     AssertFcParameters(latmin, latmax, lonmin, lonmax, hourmin, hourmax, daymin, daymax, yearmin, yearmax);
     return FetchClimateTimeSeries(p, latmin, latmax, lonmin, lonmax, hourmin, hourmax, daymin, daymax, yearmin, yearmax, dhour, IntervalToSplit.Hours, options);
 }
 public string[] FetchClimateHourlyProvenance(ClimateParameter p, double latmin, double latmax, double lonmin, double lonmax, int hourmin, int hourmax, int daymin, int daymax, int yearmin, int yearmax, int dhour, EnvironmentalDataSource dataSource)
 {
     return (string[])((FetchClimateBatchResponce)FetchClimateHourly(p, latmin, latmax, lonmin, lonmax, hourmin, hourmax, daymin, daymax, yearmin, yearmax, dhour, new FetchingOptions(dataSource))).Values.Select(v => v.Provenance).ToArray();
 }
 public FetchClimateBatchResponce FetchClimateHourly(ClimateParameter p, double latmin, double latmax, double lonmin, double lonmax, int hourmin, int hourmax, int daymin, int daymax, int yearmin, int yearmax, int dhour, FetchingOptions options)
 {
     AssertFcParameters(latmin, latmax, lonmin, lonmax, hourmin, hourmax, daymin, daymax, yearmin, yearmax);
     return(FetchClimateTimeSeries(p, latmin, latmax, lonmin, lonmax, hourmin, hourmax, daymin, daymax, yearmin, yearmax, dhour, IntervalToSplit.Hours, options));
 }
 public double FetchClimate(ClimateParameter parameter, double latmin, double latmax, double lonmin, double lonmax, int starthour, int stophour, int startday, int stopday, int startyear, int stopyear)
 {
     AssertFcParameters(latmin, latmax, lonmin, lonmax, starthour, stophour, startday, stopday, startyear, stopyear);
     return (double)(((FetchClimateSingleResponce)FetchClimate(parameter, latmin, latmax, lonmin, lonmax, starthour, stophour, startday, stopday, startyear, stopyear, new FetchingOptions())).Value.GetValueInDefaultClientUnits());
 }
Example #15
0
 public static void FillDataSetWithRequest(DataSet ds, ClimateParameter parameter, double latmin, double latmax, double lonmin, double lonmax, int starthour, int stophour, int startday, int stopday, int startyear, int stopyear)
 {
     FillDataSetWithRequest(ds, parameter, latmin, latmax, lonmin, lonmax, starthour, stophour, startday, stopday, startyear, stopyear, new FetchingOptions());
 }
Example #16
0
        /// <summary>
        /// Parse the parameters and returns filled MultiRequestStructure
        /// </summary>
        /// <param name="args">A paramters to parse</param>
        /// <param name="regDelimiter">A delimiter in the latitude values (start:step:stop - ':' is a delimiter)</param>
        /// <returns></returns>
        public static MultipleRequestDescriptor Parse(string[] args, char regDelimiter = ':')
        {
            List <SpatialGrid> queries    = new List <SpatialGrid>();
            ClimateParameter   parameter  = ClimateParameter.FC_TEMPERATURE;
            Tuple <int, int>   days       = new Tuple <int, int>(GlobalConsts.DefaultValue, GlobalConsts.DefaultValue);
            Tuple <int, int>   hours      = new Tuple <int, int>(GlobalConsts.DefaultValue, GlobalConsts.DefaultValue);
            Tuple <int, int>   years      = Tuple.Create(GlobalConsts.StartYear, GlobalConsts.EndYear);
            FetchingTimeModes  activeMode = FetchingTimeModes.Single;
            int currentArgNum             = 0;
            int timeStep             = 1;
            int paramsEnteredCounter = 0;

            while (currentArgNum != args.Length)
            {
                switch (args[currentArgNum++].ToLower()) //  <---- moves the cursor!!!
                {
                case "/ty":
                    if (!int.TryParse(args[currentArgNum++], out timeStep))
                    {
                        throw new ArgumentException("Years step is not an integer in the yearly timeseries specification. Syntax is [/ty YearsStep]");
                    }
                    activeMode = FetchingTimeModes.TsYearly;
                    continue;

                case "/ts":
                    if (!int.TryParse(args[currentArgNum++], out timeStep))
                    {
                        throw new ArgumentException("Days step is not an integer in the seasonly timeseries specification. Syntax is [/ts DaysStep]");
                    }
                    activeMode = FetchingTimeModes.TsSeasonly;
                    continue;

                case "/th":
                    if (!int.TryParse(args[currentArgNum++], out timeStep))
                    {
                        throw new ArgumentException("Hourss step is not an integer in the hourly timeseries specification. Syntax is [/th HoursStep]");
                    }
                    activeMode = FetchingTimeModes.TsHourly;
                    continue;

                case "/years":
                    years = ParseYears(ref currentArgNum, args);
                    continue;

                case "/days":
                    days = ParseDays(ref currentArgNum, args);
                    continue;

                case "/hours":
                    hours = ParseHours(ref currentArgNum, args);
                    continue;

                default:
                    currentArgNum--;     // <---- false cursor moving, moving it back
                    break;
                }
                if (paramsEnteredCounter == 0)
                {
                    parameter = ParseParam(ref currentArgNum, args);
                    paramsEnteredCounter++;
                    continue;
                }
                if (paramsEnteredCounter == 1)
                {
                    queries.Add(ParseRegion(ref currentArgNum, args));
                    paramsEnteredCounter++;
                    continue;
                }
                queries.Add(ParseRegion(ref currentArgNum, args));
            }
            if (paramsEnteredCounter < 1)
            {
                throw new ArgumentException("Climate variable is not set.");
            }
            MultipleRequestDescriptor mrd = new MultipleRequestDescriptor(parameter, new TimeBounds()
            {
                MinDay = days.Item1, MaxDay = days.Item2, MinYear = years.Item1, MaxYear = years.Item2, MinHour = hours.Item1, MaxHour = hours.Item2
            }, activeMode);

            foreach (var q in queries)
            {
                mrd.AddRegion(q);
            }
            mrd.TimeStep = timeStep;
            return(mrd);
        }
        public FetchClimateGridResponce FetchClimateGrid(ClimateParameter parameter, double latmin, double latmax, double lonmin, double lonmax, int hourmin, int hourmax, int daymin, int daymax, int yearmin, int yearmax, double dlat, double dlon, FetchingOptions options)
        {
            int nlat = (int)Math.Round((latmax - latmin) / dlat);
            int nlon = (int)Math.Round((lonmax - lonmin) / dlon);

            double[] latsGrid = new double[nlat + 1];
            double[] lonsGrid = new double[nlon + 1];
            for (int i = 0; i < latsGrid.Length; i++)
            {
                latsGrid[i] = latmin + i * dlat;
            }
            for (int i = 0; i < lonsGrid.Length; i++)
            {
                lonsGrid[i] = lonmin + i * dlon;
            }
            int[]    hourmins = new int[nlat * nlon];
            int[]    hourmaxs = new int[nlat * nlon];
            int[]    daymins = new int[nlat * nlon];
            int[]    daymaxs = new int[nlat * nlon];
            int[]    yearmins = new int[nlat * nlon];
            int[]    yearmaxs = new int[nlat * nlon];
            double[] latmins = new double[nlat * nlon];
            double[] latmaxs = new double[nlat * nlon];
            double[] lonmins = new double[nlat * nlon];
            double[] lonmaxs = new double[nlat * nlon];
            int      rowIndex, colIndex;

            for (int i = 0; i < nlat * nlon; i++)
            {
                rowIndex = i / nlon;
                colIndex = i % nlon;

                lonmins[i] = lonsGrid[colIndex];
                lonmaxs[i] = lonsGrid[colIndex + 1];
                latmins[i] = latsGrid[rowIndex];
                latmaxs[i] = latsGrid[rowIndex + 1];

                hourmins[i] = hourmin;
                hourmaxs[i] = hourmax;
                daymins[i]  = daymin;
                daymaxs[i]  = daymax;
                yearmins[i] = yearmin;
                yearmaxs[i] = yearmax;
            }

            var resB = FetchClimate(parameter, latmins, latmaxs, lonmins, lonmaxs, hourmins, hourmaxs, daymins, daymaxs, yearmins, yearmaxs, options, ResearchVariationType.Spatial);

            ClimateParameterValue[] result = resB.Values;
            ClimateParameterValue[,] result2D = new ClimateParameterValue[nlat, nlon];
            for (int i = 0; i < nlat * nlon; i++)
            {
                rowIndex = i / nlon;
                colIndex = i % nlon;
                result2D[rowIndex, colIndex] = result[i];
            }
            FetchClimateGridResponce res = new FetchClimateGridResponce();

            res.Values         = result2D;
            res.ServiceVersion = resB.ServiceVersion;
            return(res);
        }
 public string[] FetchClimateHourlyProvenance(ClimateParameter p, double latmin, double latmax, double lonmin, double lonmax, int hourmin, int hourmax, int daymin, int daymax, int yearmin, int yearmax, int dhour, EnvironmentalDataSource dataSource)
 {
     return((string[])((FetchClimateBatchResponce)FetchClimateHourly(p, latmin, latmax, lonmin, lonmax, hourmin, hourmax, daymin, daymax, yearmin, yearmax, dhour, new FetchingOptions(dataSource))).Values.Select(v => v.Provenance).ToArray());
 }
        private FetchClimateBatchResponce FetchClimateTimeSeries(ClimateParameter p, double latmin, double latmax, double lonmin, double lonmax, int hourmin, int hourmax, int daymin, int daymax, int yearmin, int yearmax, int divider, IntervalToSplit intervalToSplit, FetchingOptions options)
        {
            int n;

            if (hourmax == GlobalConsts.DefaultValue)
            {
                hourmax = 24;
            }
            if (hourmin == GlobalConsts.DefaultValue)
            {
                hourmin = 0;
            }
            bool isReplaceDayMaxWithDefVal = (yearmax != yearmin && (daymax == GlobalConsts.DefaultValue || daymax == 365));

            if (daymin == GlobalConsts.DefaultValue)
            {
                daymin = 1;
            }
            int effDayMax = daymax;

            if (effDayMax == GlobalConsts.DefaultValue)
            {
                effDayMax = (yearmin == yearmax) ? (DateTime.IsLeapYear(yearmin) ? 366 : 365) : 365;
            }
            ResearchVariationType rvt = ResearchVariationType.Auto;

            switch (intervalToSplit)
            {
            case IntervalToSplit.Years: n = (int)Math.Ceiling((yearmax - yearmin + 1) / (double)divider); rvt = ResearchVariationType.Yearly; break;

            case IntervalToSplit.Days: n = (int)Math.Ceiling((effDayMax - daymin + 1) / (double)divider); rvt = ResearchVariationType.Seasonly; break;

            case IntervalToSplit.Hours: n = (int)Math.Ceiling((hourmax - hourmin + 1) / (double)divider); rvt = ResearchVariationType.Hourly; break;

            default: throw new NotImplementedException();
            }
            double[] latmaxs  = new double[n];
            double[] latmins  = new double[n];
            double[] lonmaxs  = new double[n];
            double[] lonmins  = new double[n];
            int[]    hourmins = new int[n];
            int[]    hourmaxs = new int[n];
            int[]    daymins  = new int[n];
            int[]    daymaxs  = new int[n];
            int[]    yearmins = new int[n];
            int[]    yearmaxs = new int[n];

            int yi = (intervalToSplit == IntervalToSplit.Years) ? 1 : 0;
            int di = (intervalToSplit == IntervalToSplit.Days) ? 1 : 0;
            int hi = (intervalToSplit == IntervalToSplit.Hours) ? 1 : 0;

            for (int i = 0; i < n; i++)
            {
                latmaxs[i]  = latmax;
                latmins[i]  = latmin;
                lonmaxs[i]  = lonmax;
                lonmins[i]  = lonmin;
                hourmins[i] = Math.Min((hi == 0)?hourmin:(hourmin + hi * i * divider), 24);
                hourmaxs[i] = Math.Min((hi == 0) ? hourmax : (hourmin + hi * ((i + 1) * divider - 1)), 24);
                yearmins[i] = (yi == 0) ? yearmin : (yearmin + yi * i * divider);
                yearmaxs[i] = (yi == 0) ? yearmax:(yearmin + yi * ((i + 1) * divider - 1));
                daymins[i]  = Math.Min((di == 0)?daymin:(daymin + di * (i * divider)), (yearmins[i] == yearmaxs[i] && DateTime.IsLeapYear(yearmins[i]))?366:365);
                if (isReplaceDayMaxWithDefVal && intervalToSplit != IntervalToSplit.Days)
                {
                    daymaxs[i] = GlobalConsts.DefaultValue;
                }
                else
                {
                    daymaxs[i] = Math.Min((di == 0) ? daymax : (daymin + di * ((i + 1) * divider - 1)), (yearmins[i] == yearmaxs[i] && DateTime.IsLeapYear(yearmins[i])) ? 366 : 365);
                }
            }
            return(FetchClimate(p, latmins, latmaxs, lonmins, lonmaxs, hourmins, hourmaxs, daymins, daymaxs, yearmins, yearmaxs, options, rvt));
        }
        private static Variable Fetch(this DataSet ds, ClimateParameter parameter, string name, Variable lat, Variable lon, DateTime time, string nameUncertainty, string nameProvenance, EnvironmentalDataSource dataSource)
        {
            if (ds == null) throw new ArgumentNullException("ds");
            if (String.IsNullOrWhiteSpace(name)) throw new ArgumentException("name is incorrect");
            if (lat == null) throw new ArgumentNullException("lat");
            if (lon == null) throw new ArgumentNullException("lon");
            if (lat.Rank != 1) throw new ArgumentException("lat is not one-dimensional");
            if (lon.Rank != 1) throw new ArgumentException("lon is not one-dimensional");

            DataRequest[] req = new DataRequest[2];
            req[0] = DataRequest.GetData(lat);
            req[1] = DataRequest.GetData(lon);
            var resp = ds.GetMultipleData(req);

            double[] _lats = GetDoubles(resp[lat.ID].Data);
            double[] _lons = GetDoubles(resp[lon.ID].Data);
            return Fetch(ds, parameter, name, _lats, _lons, lat.Dimensions[0].Name, lon.Dimensions[0].Name, nameUncertainty: nameUncertainty, nameProvenance: nameProvenance, dataSource: dataSource, timeSlices: new DateTime[] { time });
        }
 internal double[] FetchClimate(ClimateParameter parameter, double[] latmin, double[] latmax, double[] lonmin, double[] lonmax, int[] starthour, int[] stophour, int[] startday, int[] stopday, int[] startyear, int[] stopyear)
 {
     if (startday == null)
         startday = Enumerable.Repeat(GlobalConsts.DefaultValue, latmin.Length).ToArray();
     if (stopday == null)
         stopday = Enumerable.Repeat(GlobalConsts.DefaultValue, latmin.Length).ToArray();
     if (starthour == null)
         starthour = Enumerable.Repeat(GlobalConsts.DefaultValue, latmin.Length).ToArray();
     if (stophour == null)
         stophour = Enumerable.Repeat(GlobalConsts.DefaultValue, latmin.Length).ToArray();
     if (startyear == null)
         startyear = Enumerable.Repeat(GlobalConsts.StartYear, latmin.Length).ToArray();
     if (stopyear == null)
         stopyear = Enumerable.Repeat(GlobalConsts.EndYear, latmin.Length).ToArray();
     
     for (int i = 0; i < latmin.Length; i++)
         AssertFcParameters(latmin[i], latmax[i], lonmin[i], lonmax[i], starthour[i], stophour[i], startday[i], stopday[i], startyear[i], stopyear[i]);
     using (var requestDs = DataSet.Open("msds:memory"))
     {
         FetchClimateRequestBuilder.FillDataSetWithRequest(requestDs, parameter, latmin, latmax, lonmin, lonmax, starthour, stophour, startday, stopday, startyear, stopyear, new FetchingOptions());
         using (var result = ServerProcess(requestDs))
         {
             return FetchClimateRequestBuilder.BuildBatchResult(result).Values.Select(v => v.GetValueInDefaultClientUnits()).ToArray();
         }
     }
 }
        private static Variable Fetch(this DataSet ds, ClimateParameter parameter, string name, double[] latmins, double[] lonmins, string dimLat, string dimLon, double[] latmaxs = null, double[] lonmaxs = null, string dimTime = null, DateTime[] timeSlices = null, TimeBounds[] climatologyIntervals = null, string nameUncertainty = null, string nameProvenance = null, EnvironmentalDataSource dataSource = EnvironmentalDataSource.ANY)
        {
            if (timeSlices == null && climatologyIntervals == null)
                throw new ArgumentNullException("Both timeSlices and ClimatologyIntervals are null");
            if (latmaxs == null ^ lonmaxs == null)
                throw new ArgumentException("Only one of latmax and lonmax is set. please set both of them or none");
            object mv = double.NaN;
            string longName = GetLongName(parameter);

            bool isFetchingGrid = dimLat != dimLon; // otherwise, fetching point set, when all axes depend on the same dimension

            // Preparing FetchClimate method parameters
            int index = 0;
            int[] starthour, stophour, startday, stopday, startyear, stopyear;
            double[] minLats, minLons, maxLats, maxLons;

            int timesN = (climatologyIntervals != null) ? (climatologyIntervals.Length) : (timeSlices.Length);
            if (isFetchingGrid)
            {
                #region Preparing request for grid
                int latN = latmins.Length;
                int lonN = lonmins.Length;
                if (latN <= 0)
                    throw new ArgumentException("lats. Too short latitude axis");
                if (lonN <= 0)
                    throw new ArgumentException("lons. Too short longitude axis");
                int n = latN * lonN * timesN;
                if (n == 0) throw new ArgumentException("Empty region is requested");
                starthour = new int[n]; stophour = new int[n]; startday = new int[n]; stopday = new int[n]; startyear = new int[n]; stopyear = new int[n];
                minLats = new double[n]; minLons = new double[n];
                maxLats = new double[n]; maxLons = new double[n];
                if (climatologyIntervals != null)
                {
                    for (int j = 0; j < latN; j++)
                    {
                        double latmax = (latmaxs == null) ? latmins[j] : latmaxs[j];
                        double latmin = latmins[j];
                        for (int k = 0; k < lonN; k++)
                        {
                            double lonmax = (lonmaxs == null) ? lonmins[k] : lonmaxs[k];
                            double lonmin = lonmins[k];
                            for (int i = 0; i < timesN; i++)
                            {
                                startyear[index] = climatologyIntervals[i].MinYear;
                                startday[index] = climatologyIntervals[i].MinDay;
                                starthour[index] = climatologyIntervals[i].MinHour;

                                stopyear[index] = climatologyIntervals[i].MaxYear;
                                stopday[index] = climatologyIntervals[i].MaxDay;
                                stophour[index] = climatologyIntervals[i].MaxHour;

                                minLats[index] = latmin;
                                minLons[index] = lonmin;

                                maxLats[index] = latmax;
                                maxLons[index] = lonmax;

                                index++;
                            }
                        }
                    }
                }
                else
                {
                    for (int j = 0; j < latN; j++)
                    {
                        double latmin = latmins[j];
                        double latmax = (latmaxs == null) ? latmins[j] : latmaxs[j];
                        for (int k = 0; k < lonN; k++)
                        {
                            double lonmax = (lonmaxs == null) ? lonmins[k] : lonmaxs[k];
                            double lonmin = lonmins[k];

                            for (int i = 0; i < timesN; i++)
                            {
                                starthour[index] = stophour[index] = timeSlices[i].Hour;
                                startday[index] = stopday[index] = timeSlices[i].DayOfYear;
                                startyear[index] = stopyear[index] = timeSlices[i].Year;

                                minLats[index] = latmin;
                                minLons[index] = lonmin;

                                maxLats[index] = latmax;
                                maxLons[index] = lonmax;

                                index++;
                            }
                        }
                    }
                }
                #endregion
            }
            else // preparing request for pointset 
            {
                #region Preparing request for pointset
                int coordN = latmins.Length;
                int n = coordN * timesN;
                if (n == 0) throw new ArgumentException("Empty region is requested");
                if (latmaxs != null || lonmaxs != null)
                    throw new InvalidOperationException("In case of pointset fetching latmaxs and lonmaxs must be omited");
                starthour = new int[n]; stophour = new int[n]; startday = new int[n]; stopday = new int[n]; startyear = new int[n]; stopyear = new int[n];
                minLats = new double[n]; minLons = new double[n];
                maxLats = new double[n]; maxLons = new double[n];
                if (climatologyIntervals != null)
                {
                    for (int i = 0; i < timesN; i++)
                        for (int j = 0; j < coordN; j++)
                        {
                            startyear[index] = climatologyIntervals[i].MinYear;
                            startday[index] = climatologyIntervals[i].MinDay;
                            starthour[index] = climatologyIntervals[i].MinHour;

                            stopyear[index] = climatologyIntervals[i].MaxYear;
                            stopday[index] = climatologyIntervals[i].MaxDay;
                            stophour[index] = climatologyIntervals[i].MaxHour;

                            minLats[index] = maxLats[index] = latmins[j];
                            minLons[index] = maxLons[index] = lonmins[j];
                            index++;
                        }
                }
                else
                {
                    for (int i = 0; i < timesN; i++)
                        for (int j = 0; j < coordN; j++)
                        {
                            starthour[index] = stophour[index] = timeSlices[i].Hour;
                            startday[index] = stopday[index] = timeSlices[i].DayOfYear;
                            startyear[index] = stopyear[index] = timeSlices[i].Year;
                            minLats[index] = maxLats[index] = latmins[j];
                            minLons[index] = maxLons[index] = lonmins[j];
                            index++;
                        }
                }
                #endregion
            }

            // Fetching the data
            var resp = ClimateService.FetchClimateEx(parameter, new FetchingOptions() { DataSourceToUse = dataSource }, minLats, maxLats, minLons, maxLons, starthour, stophour, startday, stopday, startyear, stopyear);
            ClimateParameterValue[] climateData = resp.Values;
            string units = climateData.First().DefaultClientUnitsString;

            // Saving result in the dataset
            bool _ac = ds.IsAutocommitEnabled;
            Variable varData = null, varUncertainty = null, varProv = null;
            bool saveUncertainty = !String.IsNullOrWhiteSpace(nameUncertainty);
            bool saveProv = !String.IsNullOrWhiteSpace(nameProvenance);

            try
            {
                ds.IsAutocommitEnabled = false;
                index = 0;
                if (isFetchingGrid)
                {
                    #region Putting grid data into DataSet
                    int latN = latmins.Length;
                    int lonN = lonmins.Length;
                    if (dimTime != null)
                    {
                        double[, ,] data = new double[timesN, latmins.Length, lonmins.Length];
                        double[, ,] uncertainty = saveUncertainty ? new double[timesN, latmins.Length, lonmins.Length] : null;
                        string[, ,] provenance = saveProv ? new string[timesN, latmins.Length, lonmins.Length] : null;                        
                            for (int j = 0; j < latN; j++)
                                for (int k = 0; k < lonN; k++)
                                    for (int i = 0; i < timesN; i++)                        
                                {
                                    var cd = climateData[index++];
                                    data[i, j, k] = cd.GetValueInDefaultClientUnits();
                                    if (saveUncertainty)
                                        uncertainty[i, j, k] = cd.GetUncertaintyInDefaultClientUnits();
                                    if (saveProv)
                                        provenance[i, j, k] = cd.Provenance;
                                }                        
                        varData = ds.Add(name, units, mv, data, dimTime, dimLat, dimLon);
                        if (saveUncertainty) varUncertainty = ds.Add(nameUncertainty, units, mv, uncertainty, dimTime, dimLat, dimLon);
                        if (saveProv) varProv = ds.Add(nameProvenance, provenance, dimTime, dimLat, dimLon);
                    }
                    else
                    {
                        double[,] data = new double[latmins.Length, lonmins.Length];
                        double[,] uncertainty = saveUncertainty ? new double[latmins.Length, lonmins.Length] : null;
                        string[,] provenance = saveProv ? new string[latmins.Length, lonmins.Length] : null;
                        for (int i = 0; i < latN; i++)
                            for (int j = 0; j < lonN; j++)
                            {
                                var cd = climateData[index++];
                                data[i, j] = cd.GetValueInDefaultClientUnits();
                                if (saveUncertainty)
                                    uncertainty[i, j] = cd.GetUncertaintyInDefaultClientUnits();
                                if (saveProv)
                                    provenance[i, j] = cd.Provenance;
                            }
                        varData = ds.Add(name, units, mv, data, dimLat, dimLon);
                        varData.Metadata["Time"] = timeSlices[0];
                        if (saveUncertainty)
                        {
                            varUncertainty = ds.Add(nameUncertainty, units, mv, uncertainty, dimLat, dimLon);
                            varUncertainty.Metadata["Time"] = timeSlices[0];
                        }
                        if (saveProv)
                        {
                            varProv = ds.Add(nameProvenance, provenance, dimLat, dimLon);
                            varProv.Metadata["Time"] = timeSlices[0];
                        }
                    }
                    #endregion
                }
                else // saving pointset into the dataset
                {
                    #region Putting pointset data into Dataset
                    int coordN = latmins.Length;
                    if (dimTime != null)
                    {
                        double[,] data = new double[timesN, coordN];
                        double[,] uncertainty = saveUncertainty ? new double[timesN, coordN] : null;
                        string[,] provenance = saveProv ? new string[timesN, coordN] : null;
                        for (int i = 0; i < timesN; i++)
                            for (int j = 0; j < coordN; j++)
                            {
                                var cd = climateData[index++];
                                data[i, j] = cd.GetValueInDefaultClientUnits();
                                if (saveUncertainty)
                                    uncertainty[i, j] = cd.GetUncertaintyInDefaultClientUnits();
                                if (saveProv)
                                    provenance[i, j] = cd.Provenance;
                            }
                        varData = ds.Add(name, units, mv, data, dimTime, dimLat);
                        if (saveUncertainty) varUncertainty = ds.Add(nameUncertainty, units, mv, uncertainty, dimTime, dimLat);
                        if (saveProv) varProv = ds.Add(nameProvenance, provenance, dimTime, dimLat);
                    }
                    else
                    {
                        double[] data = new double[coordN];
                        double[] uncertainty = saveUncertainty ? new double[coordN] : null;
                        string[] provenance = saveProv ? new string[coordN] : null;
                        for (int i = 0; i < coordN; i++)
                        {
                            var cd = climateData[index++];
                            data[i] = cd.GetValueInDefaultClientUnits();
                            if (saveUncertainty)
                                uncertainty[i] = cd.GetUncertaintyInDefaultClientUnits();
                            if (saveProv)
                                provenance[i] = cd.Provenance;
                        }
                        varData = ds.Add(name, units, mv, data, dimLat);
                        varData.Metadata["Time"] = timeSlices[0];
                        if (saveUncertainty)
                        {
                            varUncertainty = ds.Add(nameUncertainty, units, mv, uncertainty, dimLat);
                            varUncertainty.Metadata["Time"] = timeSlices[0];
                        }
                        if (saveProv)
                        {
                            varProv = ds.Add(nameProvenance, provenance, dimLat);
                            varProv.Metadata["Time"] = timeSlices[0];
                        }
                    }
                    #endregion
                }

                FillMetadata(varData, climatologyIntervals, resp, longName);
                if (saveUncertainty) FillUncertaintyMetadata(varUncertainty, resp, longName);
                if (saveProv) FillProvenanceMetadata(varProv, resp, longName);
                ds.Commit();
            }
            finally
            {
                ds.IsAutocommitEnabled = _ac;
            }
            return varData;
        }
 public double[] FetchClimateHourly(ClimateParameter p, double latmin, double latmax, double lonmin, double lonmax, int hourmin, int hourmax, int daymin, int daymax, int yearmin, int yearmax, int dhour, EnvironmentalDataSource dataSource)
 {
     return((double[])((FetchClimateBatchResponce)FetchClimateHourly(p, latmin, latmax, lonmin, lonmax, hourmin, hourmax, daymin, daymax, yearmin, yearmax, dhour, new FetchingOptions(dataSource))).Values.Select(v => v.GetValueInDefaultClientUnits()).ToArray());
 }
 /// <summary>
 /// Creates new variable with data from the FetchClimate service for the current lat/lon coordinate system and given time.
 /// </summary>
 /// <param name="ds">Target DataSet.</param>
 /// <param name="parameter">A climate parameter to fetch.</param>
 /// <param name="name">Name of the variable.</param>
 /// <param name="time">Time moment to fetch data for.</param>
 /// <returns>New variable instance.</returns>
 /// <remarks>
 /// <para>
 /// The method looks up the <paramref name="ds"/> for the lat/lon coordinate system.
 /// An axis is considered as a latitude grid if at least one of the following conditions are satisfied
 /// (case is ignored in all rules):
 /// <list type="bullet">
 /// <item><description>axis name starts with either "lat" or "_lat";</description></item>
 /// <item><description>axis name contains substring "latitude";</description></item>
 /// <item><description>axis has attribute Units containing substring "degree" and ends with "n" or "north".</description></item>
 /// </list>
 /// Similar rules for longitude axis:
 /// <list type="bullet">
 /// <item><description>axis name starts with either "lon" or "_lon";</description></item>
 /// <item><description>axis name contains substring "longitude";</description></item>
 /// <item><description>axis has attribute Units containing substring "degree" and ends with "e" or "east".</description></item>
 /// </list>
 /// </para>
 /// <para>If the axes not found, an exception is thrown.</para>
 /// <para>When a coordinate system is found, the Fetch Climate service is requested using a single batch request;
 /// result is added to the DataSet as 2d-variable depending on lat/lon axes.
 /// The DisplayName, long_name, Units, MissingValue, Provenance and Time attributes of the variable are set.
 /// </para>
 /// <example>
 /// <code>
 ///  // Fetching climate parameters for fixed time moment
 ///  using (var ds = DataSet.Open("msds:memory"))
 ///  {
 ///      Console.WriteLine("Filling dataset...");
 ///      ds.AddAxis("lon", "degrees East", -12.5, 20.0, 0.5);
 ///      ds.AddAxis("lat", "degrees North", 35.0, 60.0, 0.5);
 ///
 ///      ds.Fetch(ClimateParameter.FC_TEMPERATURE, "airt", new DateTime(2000, 7, 19, 11, 0, 0)); // time is fixed hence airt is 2d (depends on lat and lon)
 ///      ds.Fetch(ClimateParameter.FC_SOIL_MOISTURE, "soilm", new DateTime(2000, 7, 19, 11, 0, 0));
 ///
 ///      Console.WriteLine("Running DataSet Viewer...");
 ///      ds.View(@"airt(lon,lat) Style:Colormap; Palette:-5=Blue,White=0,#F4EF2F=5,Red=20; MapType:Aerial; Transparency:0.57000000000000006;;soilm(lon,lat) Style:Colormap; Palette:0=#00000000,#827DAAEC=300,#0000A0=800; Transparency:0; MapType:Aerial");
 ///  }
 ///
 ///  // Fetching climate parameters for different time moments
 ///  using (var ds = DataSet.Open("msds:memory"))
 ///  {
 ///      Console.WriteLine("Filling dataset...");
 ///      ds.AddAxis("lon", "degrees East", -12.5, 20.0, 2.0);
 ///      ds.AddAxis("lat", "degrees North", 35.0, 60.0, 2.0);
 ///      ds.AddAxis("time", new DateTime(2000, 7, 19, 0, 0, 0), new DateTime(2000, 7, 19, 23, 0, 0), TimeSpan.FromHours(2));
 ///
 ///      ds.Fetch(ClimateParameter.FC_TEMPERATURE, "airt"); // airt depends on lat,lon,time
 ///      ds.Fetch(ClimateParameter.FC_SOIL_MOISTURE, "soilm");
 ///
 ///      Console.WriteLine("Running DataSet Viewer...");
 ///      ds.View(@"airt(lon,lat) Style:Colormap; Palette:-5=Blue,White=0,#F4EF2F=5,Red=20; MapType:Aerial; Transparency:0.57000000000000006;;soilm(lon,lat) Style:Colormap; Palette:0=#00000000,#827DAAEC=300,#0000A0=800; Transparency:0; MapType:Aerial");
 ///  }
 /// </code>
 /// </example>
 /// </remarks>
 public static Variable Fetch(this DataSet ds, ClimateParameter parameter, string name, DateTime time, string nameUncertainty = null, string nameProvenance = null, EnvironmentalDataSource dataSource = EnvironmentalDataSource.ANY)
 {
     return(Fetch(ds, ClimateService.ClimateParameterToFC2VariableName(parameter), name, time, nameUncertainty, nameProvenance, ClimateService.EnvironmentalDataSourceToArrayOfFC2DataSources(dataSource)));
 }
Example #25
0
 /// <summary>
 /// Split requested area into spatial grid and returns uncertainties for calculated values of the requested parameter.
 /// </summary>
 /// <param name="parameter">A climate parameter that will be evaluated for mean value</param>
 /// <param name="latmin">Minimum latitude of the requested area</param>
 /// <param name="lonmin">Mimimun longatude of the requested area</param>
 /// <param name="latmax">Maximum latitude of the requesed area </param>
 /// <param name="lonmax">Maximum longatude of the requesed area</param>
 /// <param name="yearmin">The first year that will be used to form time intervals of the request</param>
 /// <param name="daymin">The first day of the year (1..365) that will be used to form time intervals of the request</param>
 /// <param name="hourmin">The time in hours of the day (0..24) that will be used as a lower inclusive bound to form time intervals of the request. Use -999 or 0 to specify the begining of the day</param>
 /// <param name="yearmax">The last year(inclusivly) that will be used to form time intervals for request</param>
 /// <param name="daymax">The last day of the year(inclusivly) that will be used to form time intervals of the request. Use -999 to specify the last day of the year.</param>
 /// <param name="hourmax">The time in hours of the day (0..24) that will be used as an upper inclusive bound to form time intervals of the request. Use -999 or 24 to specify the end of the day</param>
 /// <param name="dlat">A step along latitude that will be used to split requested area into grid</param>
 /// <param name="dlon">A step along longatude that will be used to split requested areia into grid</param>
 /// <param name="dataSource">The data source to use for calculation. By default the data source with lowest uncertainty is chosen automaticly</param> 
 public static double[,] FetchUncertaintyGrid(ClimateParameter parameter, double latmin, double latmax, double lonmin, double lonmax, double dlat, double dlon, int hourmin = 0, int hourmax = 24, int daymin = 1, int daymax = GlobalConsts.DefaultValue, int yearmin = 1961, int yearmax = 1990, EnvironmentalDataSource dataSource = EnvironmentalDataSource.ANY)
 {
     return ClientInstance.FetchUncertaintyGrid(parameter, latmin, latmax, lonmin, lonmax, hourmin, hourmax, daymin, daymax, yearmin, yearmax, dlat, dlon, dataSource);
 }
Example #26
0
        public static void FillDataSetWithRequest(DataSet ds, ClimateParameter parameter, double[] latmin, double[] latmax, double[] lonmin, double[] lonmax, int[] starthour, int[] stophour, int[] startday, int[] stopday, int[] startyear, int[] stopyear, FetchingOptions options)
        {
            ds.IsAutocommitEnabled = false;

            ds.Metadata[Namings.metadataNameParameter]      = Namings.GetParameterName(parameter);
            ds.Metadata[Namings.metadataNameCoverage]       = Namings.GetCoverageName(parameter);
            ds.Metadata[Namings.metadataNameProvenanceHint] = options.FetchClimateProvenanceControlStr;

            if (!ds.Variables.Contains(Namings.VarNameLatMax))
            {
                ds.AddVariable <double>(Namings.VarNameLatMax, Namings.dimNameCells);
            }
            if (!ds.Variables.Contains(Namings.VarNameLatMin))
            {
                ds.AddVariable <double>(Namings.VarNameLatMin, Namings.dimNameCells);
            }
            if (!ds.Variables.Contains(Namings.VarNameLonMax))
            {
                ds.AddVariable <double>(Namings.VarNameLonMax, Namings.dimNameCells);
            }
            if (!ds.Variables.Contains(Namings.VarNameLonMin))
            {
                ds.AddVariable <double>(Namings.VarNameLonMin, Namings.dimNameCells);
            }
            if (!ds.Variables.Contains(Namings.VarNameDayMax))
            {
                ds.AddVariable <int>(Namings.VarNameDayMax, Namings.dimNameCells);
            }
            if (!ds.Variables.Contains(Namings.VarNameDayMin))
            {
                ds.AddVariable <int>(Namings.VarNameDayMin, Namings.dimNameCells);
            }
            if (!ds.Variables.Contains(Namings.VarNameHourMax))
            {
                ds.AddVariable <int>(Namings.VarNameHourMax, Namings.dimNameCells);
            }
            if (!ds.Variables.Contains(Namings.VarNameHourMin))
            {
                ds.AddVariable <int>(Namings.VarNameHourMin, Namings.dimNameCells);
            }
            if (!ds.Variables.Contains(Namings.VarNameYearMax))
            {
                ds.AddVariable <int>(Namings.VarNameYearMax, Namings.dimNameCells);
            }
            if (!ds.Variables.Contains(Namings.VarNameYearMin))
            {
                ds.AddVariable <int>(Namings.VarNameYearMin, Namings.dimNameCells);
            }

            ds.Variables[Namings.VarNameDayMax].Append(stopday);
            ds.Variables[Namings.VarNameDayMin].Append(startday);
            ds.Variables[Namings.VarNameHourMax].Append(stophour);
            ds.Variables[Namings.VarNameHourMin].Append(starthour);
            ds.Variables[Namings.VarNameYearMax].Append(stopyear);
            ds.Variables[Namings.VarNameYearMin].Append(startyear);
            ds.Variables[Namings.VarNameLonMax].Append(lonmax);
            ds.Variables[Namings.VarNameLonMin].Append(lonmin);
            ds.Variables[Namings.VarNameLatMax].Append(latmax);
            ds.Variables[Namings.VarNameLatMin].Append(latmin);

            ds.Commit();
        }
Example #27
0
 /// <summary>
 /// Provenance of the time series request (splitting daymin-daymax interval by dyear value).
 /// </summary>
 /// <param name="p">A climate parameter that will be evaluated for mean value</param>
 /// <param name="latmin">Minimum latitude of the requested area</param>
 /// <param name="lonmin">Mimimun longatude of the requested area</param>
 /// <param name="latmax">Maximum latitude of the requesed area </param>
 /// <param name="lonmax">Maximum longatude of the requesed area</param>
 /// <param name="yearmin">The first year that will be used to form time intervals of the request</param>
 /// <param name="daymin">The first day of the year (1..365) that will be used to form time intervals of the request</param>
 /// <param name="hourmin">The time in hours of the day (0..24) that will be used as a lower inclusive bound to form time intervals of the request. Use -999 or 0 to specify the begining of the day</param>
 /// <param name="yearmax">The last year(inclusivly) that will be used to form time intervals for request</param>
 /// <param name="daymax">The last day of the year(inclusivly) that will be used to form time intervals of the request. Use -999 to specify the last day of the year.</param>
 /// <param name="hourmax">The time in hours of the day (0..24) that will be used as an upper inclusive bound to form time intervals of the request. Use -999 or 24 to specify the end of the day</param>
 /// <param name="dyear">The step that will be used to spit [daymin,daymax] interval into a separate intervals. The default value is 1</param>
 /// <param name="dataSource">The data source to use for calculation. By default the data source with lowest uncertainty is chosen automaticly</param> 
 public static string[] FetchClimateSeasonlyProvenance(ClimateParameter p, double latmin, double latmax, double lonmin, double lonmax, int hourmin = 0, int hourmax = 24, int daymin = 1, int daymax = GlobalConsts.DefaultValue, int yearmin = 1961, int yearmax = 1990, int dday = 1, EnvironmentalDataSource dataSource = EnvironmentalDataSource.ANY)
 {
     return ClientInstance.FetchClimateSeasonlyProvenance(p, latmin, latmax, lonmin, lonmax, hourmin, hourmax, daymin, daymax, yearmin, yearmax, dday, dataSource);
 }
 public FetchClimateSingleResponce FetchClimate(ClimateParameter parameter, double latmin, double latmax, double lonmin, double lonmax, int starthour, int stophour, int startday, int stopday, int startyear, int stopyear, FetchingOptions options)
 {
     AssertFcParameters(latmin, latmax, lonmin, lonmax, starthour, stophour, startday, stopday, startyear, stopyear);
     using (var requestDs = DataSet.Open("msds:memory"))
     {
         FetchClimateRequestBuilder.FillDataSetWithRequest(requestDs, parameter, latmin, latmax, lonmin, lonmax, starthour, stophour, startday, stopday, startyear, stopyear, options);
         using (var result = ServerProcess(requestDs))
         {
             return FetchClimateRequestBuilder.BuildSingleCellResult(result);
         }
     }
 }
Example #29
0
 /// <summary>
 /// Time series request (splitting hourmin-hourmax interval by dyear value).
 /// </summary>
 /// <param name="p">A climate parameter that will be evaluated for mean value</param>
 /// <param name="latmin">Minimum latitude of the requested area</param>
 /// <param name="lonmin">Mimimun longatude of the requested area</param>
 /// <param name="latmax">Maximum latitude of the requesed area </param>
 /// <param name="lonmax">Maximum longatude of the requesed area</param>
 /// <param name="yearmin">The first year that will be used to form time intervals of the request</param>
 /// <param name="daymin">The first day of the year (1..365) that will be used to form time intervals of the request</param>
 /// <param name="hourmin">The time in hours of the day (0..24) that will be used as a lower inclusive bound to form time intervals of the request. Use -999 or 0 to specify the begining of the day</param>
 /// <param name="yearmax">The last year(inclusivly) that will be used to form time intervals for request</param>
 /// <param name="daymax">The last day of the year(inclusivly) that will be used to form time intervals of the request. Use -999 to specify the last day of the year.</param>
 /// <param name="hourmax">The time in hours of the day (0..24) that will be used as an upper inclusive bound to form time intervals of the request. Use -999 or 24 to specify the end of the day</param>
 /// <param name="dyear">The step that will be used to spit [hourmin,hourmax] interval into a separate intervals. The default value is 1</param>
 /// <param name="dataSource">The data source to use for calculation. By default the data source with lowest uncertainty is chosen automaticly</param> 
 public static double[] FetchClimateHourly(ClimateParameter p, double latmin, double latmax, double lonmin, double lonmax, int hourmin = 0, int hourmax = 24, int daymin = 1, int daymax = GlobalConsts.DefaultValue, int yearmin = 1961, int yearmax = 1990, int dhour = 1, EnvironmentalDataSource dataSource = EnvironmentalDataSource.ANY)
 {
     return ClientInstance.FetchClimateHourly(p, latmin, latmax, lonmin, lonmax, hourmin, hourmax, daymin, daymax, yearmin, yearmax, dhour, dataSource);
 }
        public FetchClimateBatchResponce FetchClimate(ClimateParameter parameter, double[] latmin, double[] latmax, double[] lonmin, double[] lonmax, int[] starthour, int[] stophour, int[] startday, int[] stopday, int[] startyear, int[] stopyear, FetchingOptions options, ResearchVariationType variationType)
        {
            if (startday == null)
                startday = Enumerable.Repeat(GlobalConsts.DefaultValue, latmin.Length).ToArray();
            if (stopday == null)
                stopday = Enumerable.Repeat(GlobalConsts.DefaultValue, latmin.Length).ToArray();
            if (starthour == null)
                starthour = Enumerable.Repeat(GlobalConsts.DefaultValue, latmin.Length).ToArray();
            if (stophour == null)
                stophour = Enumerable.Repeat(GlobalConsts.DefaultValue, latmin.Length).ToArray();
            if (startyear == null)
                startyear = Enumerable.Repeat(GlobalConsts.StartYear, latmin.Length).ToArray();
            if (stopyear == null)
                stopyear = Enumerable.Repeat(GlobalConsts.EndYear, latmin.Length).ToArray();

            for (int i = 0; i < latmin.Length; i++)
                AssertFcParameters(latmin[i], latmax[i], lonmin[i], lonmax[i], starthour[i], stophour[i], startday[i], stopday[i], startyear[i], stopyear[i]);
            
            using (var requestDs = DataSet.Open("msds:memory"))
            {
                FetchClimateRequestBuilder.FillDataSetWithRequest(requestDs, parameter, latmin, latmax, lonmin, lonmax, starthour, stophour, startday, stopday, startyear, stopyear, options);
                requestDs.Metadata[Namings.metadataNameVariationType]=variationType.ToString();
                requestDs.Commit();
                using (var result = ServerProcess(requestDs))
                {
                    return FetchClimateRequestBuilder.BuildBatchResult(result);
                }
            }
        }
Example #31
0
 /// <summary>
 /// Returns mean value of specified climate parameter for the given geographical area at the given time of the day, season and year interval. Takes additional paramter to control the process of calculation. Returns object that contains additional information about calculated result.
 /// </summary>
 /// <param name="parameter">A climate variable that will be evaluated for mean value</param>
 /// <param name="latmin">Minimum latitude of the requested region</param>
 /// <param name="lonmin">Mimimun longatude of the requested region</param>
 /// <param name="latmax">Maximum latitude of the requesed region </param>
 /// <param name="lonmax">Maximum longatude of the requesed region</param>
 /// <param name="startyear">The first year that will be used to form time intervals of the request. Default value is 1961</param>
 /// <param name="startday">The first day of the year (1..365) that will be used to form time intervals of the request. Default value is 1</param>
 /// <param name="starthour">The time in hours of the day (0..24) that will be used as a lower inclusive bound to form time intervals of the request. Default value is 0</param>
 /// <param name="stopyear">The last year(inclusivly) that will be used to form time intervals for request. Default value is 1990</param>
 /// <param name="stopday">The last day of the year(inclusivly) that will be used to form time intervals of the request. Use GlobalConsts.DefaultValue to specify the last day of the year. Default value is "the last day of the year"</param>
 /// <param name="stophour">The time in hours of the day (0..24) that will be used as an upper inclusive bound to form time intervals of the request. Use 24 to specify the end of the day. Default value is 24</param>
 /// <param name="options">An information about how to perform the calculation</param>        
 internal static FetchClimateSingleResponce FetchClimateEx(ClimateParameter parameter, FetchingOptions options, double latmin, double latmax, double lonmin, double lonmax, int starthour = 0, int stophour = 24, int startday = 1, int stopday = GlobalConsts.DefaultValue, int startyear = 1961, int stopyear = 1990)
 {
     return ClientInstance.FetchClimate(parameter, latmin, latmax, lonmin, lonmax, starthour, stophour, startday, stopday, startyear, stopyear, options);
 }
 public double[] FetchClimateHourly(ClimateParameter p, double latmin, double latmax, double lonmin, double lonmax, int hourmin, int hourmax, int daymin, int daymax, int yearmin, int yearmax, int dhour, EnvironmentalDataSource dataSource)
 {            
     return (double[])((FetchClimateBatchResponce)FetchClimateHourly(p, latmin, latmax, lonmin, lonmax, hourmin, hourmax, daymin, daymax, yearmin, yearmax, dhour, new FetchingOptions(dataSource))).Values.Select(v => v.GetValueInDefaultClientUnits()).ToArray();
 }
Example #33
0
 /// <summary>
 /// Batch version of single fetch climate request. The parameteras are passed as a seperate arrays. Takes additional paramter to control the process of calculation. Returns object that contains additional information about calculated result.
 /// </summary>
 /// <param name="parameter">A climate parameter that will be evaluated for mean value</param>
 /// <param name="latmin">Minimum latitude of the requested region</param>
 /// <param name="lonmin">Mimimun longatude of the requested region</param>
 /// <param name="latmax">Maximum latitude of the requesed region </param>
 /// <param name="lonmax">Maximum longatude of the requesed region</param>
 /// <param name="startyear">The first year that will be used to form time intervals of the request. The null value means 1961 (default)</param>
 /// <param name="startday">The first day of the year (1..365) that will be used to form time intervals of the request. The null value means 1</param>
 /// <param name="starthour">The time in hours of the day (0..24) that will be used as a lower inclusive bound to form time intervals of the request. The null value means 0</param>
 /// <param name="stopyear">The last year(inclusivly) that will be used to form time intervals for request. The null value means 1990</param>
 /// <param name="stopday">The last day of the year(inclusivly) that will be used to form time intervals of the request. Use GlobalConsts.DefaultValue to specify the last day of the year. The null value means "the last day of the year"</param>
 /// <param name="stophour">The time in hours of the day (0..24) that will be used as an upper inclusive bound to form time intervals of the request. Use 24 to specify the end of the day. The null value means 24</param>
 /// <param name="options">An information about how to perform the calculation</param>
 internal static FetchClimateBatchResponce FetchClimateEx(ClimateParameter parameter, FetchingOptions options, double[] latmin, double[] latmax, double[] lonmin, double[] lonmax, int[] starthour = null, int[] stophour = null, int[] startday = null, int[] stopday = null, int[] startyear = null, int[] stopyear = null)
 {
     int len = latmin.Length;
     return ClientInstance.FetchClimate(parameter, latmin, latmax, lonmin, lonmax,
         (starthour!=null)?(starthour):(Enumerable.Repeat(0,len).ToArray()),
         (stophour!=null)?(stophour):(Enumerable.Repeat(24,len).ToArray()),
         (startday != null) ? (startday) : (Enumerable.Repeat(1, len).ToArray()),
         (stopday != null) ? (stopday) : (Enumerable.Repeat(GlobalConsts.DefaultValue, len).ToArray()),
         (startyear != null) ? (startyear) : (Enumerable.Repeat(GlobalConsts.StartYear, len).ToArray()),
         (stopyear != null) ? (stopyear) : (Enumerable.Repeat(GlobalConsts.EndYear, len).ToArray()),
         options,ResearchVariationType.Auto);
 }
        private FetchClimateBatchResponce FetchClimateTimeSeries(ClimateParameter p, double latmin, double latmax, double lonmin, double lonmax, int hourmin, int hourmax, int daymin, int daymax, int yearmin, int yearmax, int divider, IntervalToSplit intervalToSplit, FetchingOptions options)
        {
            int n;
            if (hourmax == GlobalConsts.DefaultValue)
                hourmax = 24;
            if (hourmin == GlobalConsts.DefaultValue)
                hourmin = 0;
            bool isReplaceDayMaxWithDefVal = (yearmax!=yearmin && (daymax==GlobalConsts.DefaultValue || daymax==365));            
            if (daymin == GlobalConsts.DefaultValue)
                daymin = 1;
            int effDayMax = daymax;
            if (effDayMax == GlobalConsts.DefaultValue)
                effDayMax = (yearmin == yearmax) ? (DateTime.IsLeapYear(yearmin) ? 366 : 365) : 365;
            ResearchVariationType rvt = ResearchVariationType.Auto;
            switch (intervalToSplit)
            {
                case IntervalToSplit.Years: n = (int)Math.Ceiling((yearmax - yearmin + 1) / (double)divider); rvt = ResearchVariationType.Yearly; break;
                case IntervalToSplit.Days: n = (int)Math.Ceiling((effDayMax - daymin + 1) / (double)divider); rvt = ResearchVariationType.Seasonly; break;
                case IntervalToSplit.Hours: n = (int)Math.Ceiling((hourmax - hourmin + 1) / (double)divider); rvt = ResearchVariationType.Hourly; break;
                default: throw new NotImplementedException();
            }
            double[] latmaxs = new double[n];
            double[] latmins = new double[n];
            double[] lonmaxs = new double[n];
            double[] lonmins = new double[n];
            int[] hourmins = new int[n];
            int[] hourmaxs = new int[n];
            int[] daymins = new int[n];
            int[] daymaxs = new int[n];
            int[] yearmins = new int[n];
            int[] yearmaxs = new int[n];

            int yi = (intervalToSplit == IntervalToSplit.Years) ? 1 : 0;
            int di = (intervalToSplit == IntervalToSplit.Days) ? 1 : 0;
            int hi = (intervalToSplit == IntervalToSplit.Hours) ? 1 : 0;

            for (int i = 0; i < n; i++)
            {
                latmaxs[i] = latmax;
                latmins[i] = latmin;
                lonmaxs[i] = lonmax;
                lonmins[i] = lonmin;
                hourmins[i] = Math.Min((hi==0)?hourmin:(hourmin + hi * i * divider),24);
                hourmaxs[i] = Math.Min((hi == 0) ? hourmax : (hourmin + hi * ((i + 1) * divider-1)), 24);
                yearmins[i] = (yi == 0) ? yearmin : (yearmin + yi * i * divider);
                yearmaxs[i] = (yi == 0) ? yearmax:(yearmin + yi * ((i + 1) * divider-1));
                daymins[i] = Math.Min((di==0)?daymin:(daymin + di *(i * divider)),(yearmins[i]==yearmaxs[i] && DateTime.IsLeapYear(yearmins[i]))?366:365);
                if (isReplaceDayMaxWithDefVal && intervalToSplit!=IntervalToSplit.Days)                                    
                    daymaxs[i] = GlobalConsts.DefaultValue;
                else
                    daymaxs[i] = Math.Min((di == 0) ? daymax : (daymin + di * ((i + 1) * divider - 1)), (yearmins[i] == yearmaxs[i] && DateTime.IsLeapYear(yearmins[i])) ? 366 : 365);
                
            }
            return FetchClimate(p, latmins, latmaxs, lonmins, lonmaxs, hourmins, hourmaxs, daymins, daymaxs, yearmins, yearmaxs, options,rvt);
        }
Example #35
0
 /// <summary>
 /// Split requested area into spatial grid and returns mean values of the requested parameter for its cells. Takes additional paramter to control the process of calculation. Returns object that contains additional information about calculated result.
 /// </summary>
 /// <param name="parameter">A climate parameter that will be evaluated for mean value</param>
 /// <param name="latmin">Minimum latitude of the requested area</param>
 /// <param name="lonmin">Mimimun longatude of the requested area</param>
 /// <param name="latmax">Maximum latitude of the requesed area </param>
 /// <param name="lonmax">Maximum longatude of the requesed area</param>
 /// <param name="yearmin">The first year that will be used to form time intervals of the request</param>
 /// <param name="daymin">The first day of the year (1..365) that will be used to form time intervals of the request</param>
 /// <param name="hourmin">The time in hours of the day (0..24) that will be used as a lower inclusive bound to form time intervals of the request. Use -999 or 0 to specify the begining of the day</param>
 /// <param name="yearmax">The last year(inclusivly) that will be used to form time intervals for request</param>
 /// <param name="daymax">The last day of the year(inclusivly) that will be used to form time intervals of the request. Use -999 to specify the last day of the year.</param>
 /// <param name="hourmax">The time in hours of the day (0..24) that will be used as an upper inclusive bound to form time intervals of the request. Use -999 or 24 to specify the end of the day</param>
 /// <param name="dlat">A step along latitude that will be used to split requested area into grid</param>
 /// <param name="dlon">A step along longatude that will be used to split requested areia into grid</param>
 /// <param name="options">An information about how to perform the calculation</param>        
 internal static FetchClimateGridResponce FetchClimateGridEx(ClimateParameter parameter, FetchingOptions options, double latmin, double latmax, double lonmin, double lonmax, double dlat, double dlon, int hourmin = 0, int hourmax = 24, int daymin = 1, int daymax = GlobalConsts.DefaultValue, int yearmin = 1961, int yearmax = 1990)
 {
     return ClientInstance.FetchClimateGrid(parameter, latmin, latmax, lonmin, lonmax, hourmin, hourmax, daymin, daymax, yearmin, yearmax, dlat, dlon, options);
 }
        public FetchClimateGridResponce FetchClimateGrid(ClimateParameter parameter, double latmin, double latmax, double lonmin, double lonmax, int hourmin, int hourmax, int daymin, int daymax, int yearmin, int yearmax, double dlat, double dlon, FetchingOptions options)
        {
            int nlat = (int)Math.Round((latmax - latmin) / dlat);
            int nlon = (int)Math.Round((lonmax - lonmin) / dlon);
            double[] latsGrid = new double[nlat + 1];
            double[] lonsGrid = new double[nlon + 1];
            for (int i = 0; i < latsGrid.Length; i++)
                latsGrid[i] = latmin + i * dlat;
            for (int i = 0; i < lonsGrid.Length; i++)
                lonsGrid[i] = lonmin + i * dlon;
            int[] hourmins = new int[nlat * nlon];
            int[] hourmaxs = new int[nlat * nlon];
            int[] daymins = new int[nlat * nlon];
            int[] daymaxs = new int[nlat * nlon];
            int[] yearmins = new int[nlat * nlon];
            int[] yearmaxs = new int[nlat * nlon];
            double[] latmins = new double[nlat * nlon];
            double[] latmaxs = new double[nlat * nlon];
            double[] lonmins = new double[nlat * nlon];
            double[] lonmaxs = new double[nlat * nlon];
            int rowIndex, colIndex;
            for (int i = 0; i < nlat * nlon; i++)
            {
                rowIndex = i / nlon;
                colIndex = i % nlon;

                lonmins[i] = lonsGrid[colIndex];
                lonmaxs[i] = lonsGrid[colIndex + 1];
                latmins[i] = latsGrid[rowIndex];
                latmaxs[i] = latsGrid[rowIndex + 1];

                hourmins[i] = hourmin;
                hourmaxs[i] = hourmax;
                daymins[i] = daymin;
                daymaxs[i] = daymax;
                yearmins[i] = yearmin;
                yearmaxs[i] = yearmax;
            }

            var resB = FetchClimate(parameter, latmins, latmaxs, lonmins, lonmaxs, hourmins, hourmaxs, daymins, daymaxs, yearmins, yearmaxs, options, ResearchVariationType.Spatial);

            ClimateParameterValue[] result = resB.Values;
            ClimateParameterValue[,] result2D = new ClimateParameterValue[nlat, nlon];
            for (int i = 0; i < nlat * nlon; i++)
            {
                rowIndex = i / nlon;
                colIndex = i % nlon;
                result2D[rowIndex, colIndex] = result[i];
            }
            FetchClimateGridResponce res = new FetchClimateGridResponce();
            res.Values = result2D;
            res.ServiceVersion = resB.ServiceVersion;
            return res;
        }
Example #37
0
 /// <summary>
 /// Time series request (splitting hourmin-hourmax interval by dyear value). Takes additional paramter to control the process of calculation. Returns object that contains additional information about calculated result.
 /// </summary>
 /// <param name="p">A climate parameter that will be evaluated for mean value</param>
 /// <param name="latmin">Minimum latitude of the requested area</param>
 /// <param name="lonmin">Mimimun longatude of the requested area</param>
 /// <param name="latmax">Maximum latitude of the requesed area </param>
 /// <param name="lonmax">Maximum longatude of the requesed area</param>
 /// <param name="yearmin">The first year that will be used to form time intervals of the request</param>
 /// <param name="daymin">The first day of the year (1..365) that will be used to form time intervals of the request</param>
 /// <param name="hourmin">The time in hours of the day (0..24) that will be used as a lower inclusive bound to form time intervals of the request. Use -999 or 0 to specify the begining of the day</param>
 /// <param name="yearmax">The last year(inclusivly) that will be used to form time intervals for request</param>
 /// <param name="daymax">The last day of the year(inclusivly) that will be used to form time intervals of the request. Use -999 to specify the last day of the year.</param>
 /// <param name="hourmax">The time in hours of the day (0..24) that will be used as an upper inclusive bound to form time intervals of the request. Use -999 or 24 to specify the end of the day</param>
 /// <param name="dyear">The step that will be used to spit [hourmin,hourmax] interval into a separate intervals. The default value is 1</param>
 /// <param name="options">An information about how to perform the calculation</param>        
 internal static FetchClimateBatchResponce FetchClimateHourlyEx(ClimateParameter p, FetchingOptions options, double latmin, double latmax, double lonmin, double lonmax, int hourmin = 0, int hourmax = 24, int daymin = 1, int daymax = GlobalConsts.DefaultValue, int yearmin = 1961, int yearmax = 1990, int dhour = 1)
 {
     return ClientInstance.FetchClimateHourly(p, latmin, latmax, lonmin, lonmax, hourmin, hourmax, daymin, daymax, yearmin, yearmax, dhour, options);
 }
        /// <summary>
        /// Creates new variable with data from the FetchClimate service for the current lat/lon/time coordinate system.
        /// </summary>
        /// <param name="ds">Target DataSet.</param>
        /// <param name="parameter">A climate parameter to fetch.</param>
        /// <param name="name">Name of the variable.</param>
        /// <returns>New variable instance.</returns>
        /// <remarks>
        /// <para>
        /// The method looks up the <paramref name="ds"/> for the lat/lon/time coordinate system.
        /// An axis is considered as a latitude grid if at least one of the following conditions are satisfied 
        /// (case is ignored in all rules):
        /// <list type="bullet">
        /// <item><description>axis name starts with either "lat" or "_lat";</description></item>
        /// <item><description>axis name contains substring "latitude";</description></item>
        /// <item><description>axis has attribute Units containing substring "degree" and ends with "n" or "north".</description></item>
        /// </list></para>
        /// <para>
        /// Similar rules for the longitude axis:
        /// <list type="bullet">
        /// <item><description>axis name starts with either "lon" or "_lon";</description></item>
        /// <item><description>axis name contains substring "longitude";</description></item>
        /// <item><description>axis has attribute Units containing substring "degree" and ends with "e" or "east".</description></item>
        /// </list></para>
        /// <para>
        /// Rules for the time axis:
        /// <list type="bullet">
        /// <item><description>axis name starts with "time".</description></item>
        /// </list>       
        /// </para>
        /// <para>If the axes not found, an exception is thrown.</para>
        /// <para>When a coordinate system is found, the Fetch Climate service is requested using a single batch request;
        /// result is added to the DataSet as 3d-variable depending on time,lat,lon axes.
        /// The DisplayName, long_name, Units, MissingValue and Provenance attributes of the variable are set.
        /// </para>
        /// <example>
        /// <code>
        ///  // Fetching climate parameters for fixed time moment
        ///  using (var ds = DataSet.Open("msds:memory"))
        ///  {
        ///      Console.WriteLine("Filling dataset...");
        ///      ds.AddAxis("lon", "degrees East", -12.5, 20.0, 0.5);
        ///      ds.AddAxis("lat", "degrees North", 35.0, 60.0, 0.5);
        ///      
        ///      ds.Fetch(ClimateParameter.FC_TEMPERATURE, "airt", new DateTime(2000, 7, 19, 11, 0, 0)); // time is fixed hence airt is 2d (depends on lat and lon)
        ///      ds.Fetch(ClimateParameter.FC_SOIL_MOISTURE, "soilm", new DateTime(2000, 7, 19, 11, 0, 0));
        ///
        ///      Console.WriteLine("Running DataSet Viewer...");
        ///      ds.View(@"airt(lon,lat) Style:Colormap; Palette:-5=Blue,White=0,#F4EF2F=5,Red=20; MapType:Aerial; Transparency:0.57000000000000006;;soilm(lon,lat) Style:Colormap; Palette:0=#00000000,#827DAAEC=300,#0000A0=800; Transparency:0; MapType:Aerial");
        ///  }
        ///
        ///  // Fetching climate parameters for different time moments
        ///  using (var ds = DataSet.Open("msds:memory"))
        ///  {
        ///      Console.WriteLine("Filling dataset...");
        ///      ds.AddAxis("lon", "degrees East", -12.5, 20.0, 2.0);
        ///      ds.AddAxis("lat", "degrees North", 35.0, 60.0, 2.0);
        ///      ds.AddAxis("time", new DateTime(2000, 7, 19, 0, 0, 0), new DateTime(2000, 7, 19, 23, 0, 0), TimeSpan.FromHours(2));
        ///
        ///      ds.Fetch(ClimateParameter.FC_TEMPERATURE, "airt"); // airt depends on lat,lon,time
        ///      ds.Fetch(ClimateParameter.FC_SOIL_MOISTURE, "soilm");
        ///
        ///      Console.WriteLine("Running DataSet Viewer...");
        ///      ds.View(@"airt(lon,lat) Style:Colormap; Palette:-5=Blue,White=0,#F4EF2F=5,Red=20; MapType:Aerial; Transparency:0.57000000000000006;;soilm(lon,lat) Style:Colormap; Palette:0=#00000000,#827DAAEC=300,#0000A0=800; Transparency:0; MapType:Aerial");
        ///  }
        /// </code>
        /// </example>
        /// </remarks>
        public static Variable Fetch(this DataSet ds, ClimateParameter parameter, string name, string nameUncertainty = null, string nameProvenance = null, EnvironmentalDataSource dataSource = EnvironmentalDataSource.ANY)
        {
            Variable lat = null, lon = null, times = null;
            TimeBounds[] climBounds = GetClimatologyBounds(ds);
            var axisVars = GetDefaultCoordinateSystem(ds);
            if (axisVars.Length > 1)
            {
                for (int i = 0; i < axisVars.Length; i++)
                {
                    var var = axisVars[i];
                    if (lat == null && GeoConventions.IsLatitude(var))
                        lat = var;
                    else if (lon == null && GeoConventions.IsLongitude(var))
                        lon = var;
                    else if (times == null && IsTimes(var))
                        times = var;
                }
            }
            else
            {//looking for pointset
                var vars = ds.Variables.Where(v => v.Rank == 1).ToArray();

                for (int i = 0; i < vars.Length; i++)
                {
                    if (times == null && IsTimes(vars[i]))
                    {
                        times = vars[i];
                        continue;
                    }
                    if (!GeoConventions.IsLatitude(vars[i]))
                        continue;
                    lat = vars[i];
                    foreach (Variable posLon in vars.Take(i).Union(vars.Skip(i + 1)))
                        if (GeoConventions.IsLongitude(posLon))
                        {
                            lon = posLon;
                            break;
                        }
                }
            }
            if (times == null)
                throw new InvalidOperationException("The dataset doesn't contain a time information. Please add time axis and climatology bounds if needed");
            if (lat == null)
                throw new InvalidOperationException("The dataset doesn't contain a latitude information. Please add latitude axis to the dataset beforehand");
            if (lon == null)
                throw new InvalidOperationException("The dataset doesn't contain a longitude information. Please add longitude axis to the dataset beforehand");
            if (climBounds.Length == 0)
                return Fetch(ds, parameter, name, lat, lon, times, nameUncertainty, nameProvenance, dataSource);
            else
                return Fetch(ds, parameter, name, lat, lon, times, nameUncertainty, nameProvenance, dataSource, climatologyBounds: climBounds);
        }
Example #39
0
 /// <summary>
 /// Returns an uncertainty of the value calculated by FetchClimate of specified climate parameter for the given geographical region at the given time of the day, season and years interval.
 /// </summary>
 /// <param name="parameter">A climate variable that will be evaluated for mean value</param>
 /// <param name="latmin">Minimum latitude of the requested region</param>
 /// <param name="lonmin">Mimimun longatude of the requested region</param>
 /// <param name="latmax">Maximum latitude of the requesed region </param>
 /// <param name="lonmax">Maximum longatude of the requesed region</param>
 /// <param name="startyear">The first year that will be used to form time intervals of the request. Default value is 1961</param>
 /// <param name="startday">The first day of the year (1..365) that will be used to form time intervals of the request. Default value is 1</param>
 /// <param name="starthour">The time in hours of the day (0..24) that will be used as a lower inclusive bound to form time intervals of the request. Default value is 0</param>
 /// <param name="stopyear">The last year(inclusivly) that will be used to form time intervals for request. Default value is 1990</param>
 /// <param name="stopday">The last day of the year(inclusivly) that will be used to form time intervals of the request. Use GlobalConsts.DefaultValue to specify the last day of the year. Default value is "the last day of the year"</param>
 /// <param name="stophour">The time in hours of the day (0..24) that will be used as an upper inclusive bound to form time intervals of the request. Use 24 to specify the end of the day. Default value is 24</param>
 /// <param name="dataSource">The data source to use for calculation. By default the data source with lowest uncertainty is chosen automaticly</param>
 public static double FetchClimateUncertainty(ClimateParameter parameter, double latmin, double latmax, double lonmin, double lonmax, int starthour = 0, int stophour = 24, int startday = 1, int stopday = GlobalConsts.DefaultValue, int startyear = 1961, int stopyear = 1990, EnvironmentalDataSource dataSource = EnvironmentalDataSource.ANY)
 {
     return ((FetchClimateSingleResponce)(FetchClimateEx(parameter, new FetchingOptions(dataSource), latmin, latmax, lonmin, lonmax, starthour, stophour, startday, stopday, startyear, stopyear))).Value.GetUncertaintyInDefaultClientUnits();
 }
 /// <summary>
 /// Creates new variable with data from the FetchClimate service for the current lat/lon coordinate system and given time.
 /// </summary>
 /// <param name="ds">Target DataSet.</param>
 /// <param name="parameter">A climate parameter to fetch.</param>
 /// <param name="name">Name of the variable.</param>
 /// <param name="latID">ID of the variable that is a latutude axis.</param>
 /// <param name="lonID">ID of the variable that is a longitude axis.</param>
 /// <param name="time">Time moment to fetch data for.</param>
 /// <returns>New variable instance.</returns>
 /// <remarks>
 /// <para>
 /// The method allows to explicitly specify axes of the coordinate system for the new variable.
 /// See remarks for <see cref="Fetch(DataSet, ClimateParameter, string, DateTime)"/>
 /// </para>
 /// </remarks>
 public static Variable Fetch(this DataSet ds, ClimateParameter parameter, string name, int latID, int lonID, DateTime time, string nameUncertainty = null, string nameProvenance = null, EnvironmentalDataSource dataSource = EnvironmentalDataSource.ANY)
 {
     return Fetch(ds, parameter, name, ds.Variables.GetByID(latID), ds.Variables.GetByID(lonID), time, nameUncertainty, nameProvenance, dataSource);
 }
Example #41
0
 public MultipleRequestDescriptor(ClimateParameter p, TimeBounds tb, FetchingTimeModes mode)
 {
     parameter  = p;
     timeBounds = tb;
     timeMode   = mode;
 }
 /// <summary>
 /// Creates new variable with data from the FetchClimate service for the current lat/lon coordinate system and given time.
 /// </summary>
 /// <param name="ds">Target DataSet.</param>
 /// <param name="parameter">A climate parameter to fetch.</param>
 /// <param name="name">Name of the variable.</param>
 /// <param name="latID">ID of the variable that is a latutude axis.</param>
 /// <param name="lonID">ID of the variable that is a longitude axis.</param>
 /// <param name="timeID">ID of the variable that is a time axis.</param>
 /// <returns>New variable instance.</returns>
 /// <remarks>
 /// <para>
 /// The method allows to explicitly specify axes of the coordinate system for the new variable.
 /// See remarks for <see cref="Fetch(DataSet, ClimateParameter, string, string, string)"/>
 /// </para>
 /// </remarks>
 public static Variable Fetch(this DataSet ds, ClimateParameter parameter, string name, int latID, int lonID, int timeID, string nameUncertainty = null, string nameProvenance = null, EnvironmentalDataSource dataSource = EnvironmentalDataSource.ANY)
 {
     TimeBounds[] tb = GetClimatologyBounds(ds, timeID);
     if (tb.Length == 0) tb = null;
     return Fetch(ds, parameter, name, ds.Variables.GetByID(latID), ds.Variables.GetByID(lonID), ds.Variables.GetByID(timeID), climatologyBounds: tb, nameUncertainty: nameUncertainty, nameProvenance: nameProvenance, dataSource: dataSource);
 }
Example #43
0
        public void TestParameterIgnoringProvenance(ClimateParameter p, EnvironmentalDataSource ds)
        {
            ClimateService.ServiceUrl = "http://fetchclimate2.cloudapp.net/";

            const double MoscowLat = 55.7;
            const double MoscowLon = 37.5;

            const double PacificLat = -20;
            const double PacificLon = 170;

            const double PacificLatA = -15;
            const double PacificLonA = 175;

            const double KrasnoyarskLat = 56.017;
            const double KrasnoyarskLon = 92.867;

            const double AroundKrasnoyarskLatMin = 55;
            const double AroundKrasnoyarskLonMin = 91;

            const double AroundKrasnoyarskLatMax = 60;
            const double AroundKrasnoyarskLonMax = 95;

            const double SriLankaLatMin = 5;
            const double SriLankaLonMin = 70;

            const double SriLankaLatMax = 20;
            const double SriLankaLonMax = 87;

            string varName = ClimateService.ClimateParameterToFC2VariableName(p);

            Assert.AreNotEqual("", varName, string.Format("Mapping for {0} does not exist.", p.ToString()));

            string[] sources = ClimateService.EnvironmentalDataSourceToArrayOfFC2DataSources(ds);

            //Single point fetch
            var tr1 = new TimeRegion(1961, 1990);
            var tr2 = new TimeRegion(1990, 2000);
            //Moscow
            var request1 = new FetchRequest(
                varName,
                FetchDomain.CreatePoints(
                    new double[] { MoscowLat },
                    new double[] { MoscowLon },
                    tr1),
                sources);
            var    result1 = ClimateService.FetchAsync(request1).Result;
            double sd1     = ((double[])result1["sd"].GetData())[0];
            double value1  = ((double[])result1["values"].GetData())[0];

            Assert.AreEqual(sd1, ClimateService.FetchClimateUncertainty(p, MoscowLat, MoscowLat, MoscowLon, MoscowLon, dataSource: ds));
            Assert.AreEqual(value1, ClimateService.FetchClimate(p, MoscowLat, MoscowLat, MoscowLon, MoscowLon, dataSource: ds));

            //somewhere in Pacific Ocean
            var request2 = new FetchRequest(
                varName,
                FetchDomain.CreatePoints(
                    new double[] { PacificLat },
                    new double[] { PacificLon },
                    tr1),
                sources);
            var    result2 = ClimateService.FetchAsync(request2).Result;
            double sd2     = ((double[])result2["sd"].GetData())[0];
            double value2  = ((double[])result2["values"].GetData())[0];

            Assert.AreEqual(sd2, ClimateService.FetchClimateUncertainty(p, PacificLat, PacificLat, PacificLon, PacificLon, dataSource: ds));
            Assert.AreEqual(value2, ClimateService.FetchClimate(p, PacificLat, PacificLat, PacificLon, PacificLon, dataSource: ds));

            //Cell around Krasnoyarsk
            var request3 = new FetchRequest(
                varName,
                FetchDomain.CreateCells(
                    new double[] { AroundKrasnoyarskLatMin },
                    new double[] { AroundKrasnoyarskLonMin },
                    new double[] { AroundKrasnoyarskLatMax },
                    new double[] { AroundKrasnoyarskLonMax },
                    tr2),
                sources);
            var    result3 = ClimateService.FetchAsync(request3).Result;
            double sd3     = ((double[])result3["sd"].GetData())[0];
            double value3  = ((double[])result3["values"].GetData())[0];

            Assert.AreEqual(sd3, ClimateService.FetchClimateUncertainty(p, AroundKrasnoyarskLatMin, AroundKrasnoyarskLatMax, AroundKrasnoyarskLonMin, AroundKrasnoyarskLonMax, startyear: 1990, stopyear: 2000, dataSource: ds));
            Assert.AreEqual(value3, ClimateService.FetchClimate(p, AroundKrasnoyarskLatMin, AroundKrasnoyarskLatMax, AroundKrasnoyarskLonMin, AroundKrasnoyarskLonMax, startyear: 1990, stopyear: 2000, dataSource: ds));

            //Cell somewhere in Pacific Ocean
            var request4 = new FetchRequest(
                varName,
                FetchDomain.CreateCells(
                    new double[] { PacificLat },
                    new double[] { PacificLon },
                    new double[] { PacificLatA },
                    new double[] { PacificLonA },
                    tr2),
                sources);
            var    result4 = ClimateService.FetchAsync(request4).Result;
            double sd4     = ((double[])result4["sd"].GetData())[0];
            double value4  = ((double[])result4["values"].GetData())[0];

            Assert.AreEqual(sd4, ClimateService.FetchClimateUncertainty(p, PacificLat, PacificLatA, PacificLon, PacificLonA, startyear: 1990, stopyear: 2000, dataSource: ds));
            Assert.AreEqual(value4, ClimateService.FetchClimate(p, PacificLat, PacificLatA, PacificLon, PacificLonA, startyear: 1990, stopyear: 2000, dataSource: ds));

            //batch request
            double[] batchLonMin    = new double[] { PacificLon, AroundKrasnoyarskLonMin };
            double[] batchLonMax    = new double[] { PacificLon, AroundKrasnoyarskLonMax };
            double[] batchLatMin    = new double[] { PacificLat, AroundKrasnoyarskLatMin };
            double[] batchLatMax    = new double[] { PacificLat, AroundKrasnoyarskLatMax };
            int[]    batchStartYear = new int[] { 1961, 1990 };
            int[]    batchStopYear  = new int[] { 1990, 2000 };

            double[] sdGuess1    = ClimateService.FetchClimateUncertainty(p, batchLatMin, batchLatMax, batchLonMin, batchLonMax, null, null, null, null, batchStartYear, batchStopYear, ds);
            double[] valueGuess1 = ClimateService.FetchClimate(p, batchLatMin, batchLatMax, batchLonMin, batchLonMax, null, null, null, null, batchStartYear, batchStopYear, ds);

            Assert.AreEqual(sd2, sdGuess1[0]);
            Assert.AreEqual(sd3, sdGuess1[1]);
            Assert.AreEqual(value2, valueGuess1[0]);
            Assert.AreEqual(value3, valueGuess1[1]);

            //grid request
            var request5 = new FetchRequest(
                varName,
                FetchDomain.CreateCellGrid(
                    Enumerable.Range(0, (int)Math.Round((SriLankaLatMax - SriLankaLatMin) / 1) + 1).Select(i => SriLankaLatMin + i).ToArray(),
                    Enumerable.Range(0, (int)Math.Round((SriLankaLonMax - SriLankaLonMin) / 1) + 1).Select(i => SriLankaLonMin + i).ToArray(),
                    tr2),
                sources);
            var result5 = ClimateService.FetchAsync(request5).Result;

            double[,] gridSds    = (double[, ])result5["sd"].GetData();
            double[,] gridValues = (double[, ])result5["values"].GetData();
            int len0 = gridSds.GetLength(0), len1 = gridSds.GetLength(1);

            double[,] sdGuess2    = ClimateService.FetchUncertaintyGrid(p, SriLankaLatMin, SriLankaLatMax, SriLankaLonMin, SriLankaLonMax, 1, 1, yearmin: 1990, yearmax: 2000, dataSource: ds);
            double[,] valueGuess2 = ClimateService.FetchClimateGrid(p, SriLankaLatMin, SriLankaLatMax, SriLankaLonMin, SriLankaLonMax, 1, 1, yearmin: 1990, yearmax: 2000, dataSource: ds);

            //in FC2 grid is lon x lat while in FC1 it was lat x lon
            Assert.AreEqual(len0, sdGuess2.GetLength(1));
            Assert.AreEqual(len1, sdGuess2.GetLength(0));
            Assert.AreEqual(len0, valueGuess2.GetLength(1));
            Assert.AreEqual(len1, valueGuess2.GetLength(0));
            for (int i = 0; i < len0; ++i)
            {
                for (int j = 0; j < len1; ++j)
                {
                    Assert.AreEqual(gridSds[i, j], sdGuess2[j, i]);
                    Assert.AreEqual(gridValues[i, j], valueGuess2[j, i]);
                }
            }

            //Yearly TimeSeries for Krasnoyarsk
            var tr3      = new TimeRegion().GetYearlyTimeseries(1990, 2000);
            var request6 = new FetchRequest(
                varName,
                FetchDomain.CreatePoints(
                    new double[] { KrasnoyarskLat },
                    new double[] { KrasnoyarskLon },
                    tr3),
                sources);
            var result6 = ClimateService.FetchAsync(request6).Result;

            double[,] seriesSds1    = (double[, ])result6["sd"].GetData();
            double[,] seriesValues1 = (double[, ])result6["values"].GetData();

            double[] seriesSdsGuess1    = ClimateService.FetchClimateYearlyUncertainty(p, KrasnoyarskLat, KrasnoyarskLat, KrasnoyarskLon, KrasnoyarskLon, yearmin: 1990, yearmax: 2000, dataSource: ds);
            double[] seriesValuesGuess1 = ClimateService.FetchClimateYearly(p, KrasnoyarskLat, KrasnoyarskLat, KrasnoyarskLon, KrasnoyarskLon, yearmin: 1990, yearmax: 2000, dataSource: ds);

            Assert.AreEqual(seriesSds1.Length, seriesSdsGuess1.Length);
            Assert.AreEqual(seriesValues1.Length, seriesValuesGuess1.Length);
            for (int i = 0; i < seriesValues1.Length; ++i)
            {
                Assert.AreEqual(seriesSds1[0, i], seriesSdsGuess1[i]);
                Assert.AreEqual(seriesValues1[0, i], seriesValuesGuess1[i]);
            }

            //Monthly TimeSeries for Krasnoyarsk
            var tr4      = new TimeRegion(1990, 1991).GetSeasonlyTimeseries(30, 40);
            var request7 = new FetchRequest(
                varName,
                FetchDomain.CreatePoints(
                    new double[] { KrasnoyarskLat },
                    new double[] { KrasnoyarskLon },
                    tr4),
                sources);
            var result7 = ClimateService.FetchAsync(request7).Result;

            double[,] seriesSds2    = (double[, ])result7["sd"].GetData();
            double[,] seriesValues2 = (double[, ])result7["values"].GetData();

            double[] seriesSdsGuess2    = ClimateService.FetchClimateSeasonlyUncertainty(p, KrasnoyarskLat, KrasnoyarskLat, KrasnoyarskLon, KrasnoyarskLon, daymin: 30, daymax: 40, yearmin: 1990, yearmax: 1991, dataSource: ds);
            double[] seriesValuesGuess2 = ClimateService.FetchClimateSeasonly(p, KrasnoyarskLat, KrasnoyarskLat, KrasnoyarskLon, KrasnoyarskLon, daymin: 30, daymax: 40, yearmin: 1990, yearmax: 1991, dataSource: ds);

            Assert.AreEqual(seriesSds2.Length, seriesSdsGuess2.Length);
            Assert.AreEqual(seriesValues2.Length, seriesValuesGuess2.Length);
            for (int i = 0; i < seriesValues2.Length; ++i)
            {
                Assert.AreEqual(seriesSds2[0, i], seriesSdsGuess2[i]);
                Assert.AreEqual(seriesValues2[0, i], seriesValuesGuess2[i]);
            }

            //Hourly TimeSeries for Krasnoyarsk
            var tr5      = new TimeRegion(1990, 1991, 30, 31).GetHourlyTimeseries(isIntervalTimeseries: true);
            var request8 = new FetchRequest(
                varName,
                FetchDomain.CreatePoints(
                    new double[] { KrasnoyarskLat },
                    new double[] { KrasnoyarskLon },
                    tr5),
                sources);
            var result8 = ClimateService.FetchAsync(request8).Result;

            double[,] seriesSds3    = (double[, ])result8["sd"].GetData();
            double[,] seriesValues3 = (double[, ])result8["values"].GetData();

            double[] seriesSdsGuess3    = ClimateService.FetchClimateHourlyUncertainty(p, KrasnoyarskLat, KrasnoyarskLat, KrasnoyarskLon, KrasnoyarskLon, daymin: 30, daymax: 31, yearmin: 1990, yearmax: 1991, dataSource: ds);
            double[] seriesValuesGuess3 = ClimateService.FetchClimateHourly(p, KrasnoyarskLat, KrasnoyarskLat, KrasnoyarskLon, KrasnoyarskLon, daymin: 30, daymax: 31, yearmin: 1990, yearmax: 1991, dataSource: ds);

            Assert.AreEqual(seriesSds3.Length, seriesSdsGuess3.Length);
            Assert.AreEqual(seriesValues3.Length, seriesValuesGuess3.Length);
            for (int i = 0; i < seriesValues3.Length; ++i)
            {
                Assert.AreEqual(seriesSds3[0, i], seriesSdsGuess3[i]);
                Assert.AreEqual(seriesValues3[0, i], seriesValuesGuess3[i]);
            }
        }
        private static Variable Fetch(this DataSet ds, ClimateParameter parameter, string name, Variable lat, Variable lon, Variable timeSlices, string nameUncertainty, string nameProvenance, EnvironmentalDataSource dataSource, TimeBounds[] climatologyBounds = null)
        {
            if (ds == null) throw new ArgumentNullException("ds");
            if (String.IsNullOrWhiteSpace(name)) throw new ArgumentException("name is incorrect");
            if (lat == null) throw new ArgumentNullException("lat");
            if (lon == null) throw new ArgumentNullException("lon");
            if (timeSlices == null) throw new ArgumentNullException("timeSlices");
            if (lat.Rank != 1) throw new ArgumentException("lat is not one-dimensional");
            if (lon.Rank != 1) throw new ArgumentException("lon is not one-dimensional");
            if (timeSlices.Rank != 1) throw new ArgumentException("time is not one-dimensional");

            DataRequest[] req = null;
            MultipleDataResponse resp = null;
            if (climatologyBounds == null)
            {
                req = new DataRequest[3];
                req[0] = DataRequest.GetData(lat);
                req[1] = DataRequest.GetData(lon);
                req[2] = DataRequest.GetData(timeSlices);
                resp = ds.GetMultipleData(req);
            }
            else
            {
                req = new DataRequest[2];
                req[0] = DataRequest.GetData(lat);
                req[1] = DataRequest.GetData(lon);
                resp = ds.GetMultipleData(req);
            }

            double[] _latmaxs = null;
            double[] _lonmaxs = null;
            double[] _latmins = null;
            double[] _lonmins = null;
            if (lat.Metadata.ContainsKey("bounds") && lon.Metadata.ContainsKey("bounds")) //case of cells
            {
                Variable latBounds = ds.Variables[(string)lat.Metadata["bounds"]];
                Variable lonBounds = ds.Variables[(string)lon.Metadata["bounds"]];
                if (latBounds.Rank == 2 && lonBounds.Rank == 2
                    && lonBounds.Dimensions[0].Name == lon.Dimensions[0].Name
                    && latBounds.Dimensions[0].Name == lat.Dimensions[0].Name)
                {
                    Array latBoundsData = latBounds.GetData();
                    Array lonBoundsData = lonBounds.GetData();
                    int dimLatLen = latBounds.Dimensions[0].Length;
                    int dimLonLen = lonBounds.Dimensions[0].Length;
                    _latmins = new double[dimLatLen];
                    _latmaxs = new double[dimLatLen];
                    _lonmins = new double[dimLonLen];
                    _lonmaxs = new double[dimLonLen];
                    for (int i = 0; i < dimLatLen; i++)
                    {
                        _latmins[i] = Convert.ToDouble(latBoundsData.GetValue(i, 0));
                        _latmaxs[i] = Convert.ToDouble(latBoundsData.GetValue(i, 1));
                    }
                    for (int i = 0; i < dimLonLen; i++)
                    {
                        _lonmins[i] = Convert.ToDouble(lonBoundsData.GetValue(i, 0));
                        _lonmaxs[i] = Convert.ToDouble(lonBoundsData.GetValue(i, 1));
                    }
                }
            }
            if (_latmins == null || _lonmins == null) //case of grid without cells
            {
                _latmins = GetDoubles(resp[lat.ID].Data);
                _lonmins = GetDoubles(resp[lon.ID].Data);
            }
            DateTime[] _times = null;
            if (climatologyBounds == null)
                _times = (DateTime[])resp[timeSlices.ID].Data;

            if (climatologyBounds != null)
                return Fetch(ds, parameter, name, _latmins, _lonmins, lat.Dimensions[0].Name, lon.Dimensions[0].Name, dimTime: timeSlices.Dimensions[0].Name, latmaxs: _latmaxs, lonmaxs: _lonmaxs, climatologyIntervals: climatologyBounds, nameUncertainty: nameUncertainty, nameProvenance: nameProvenance, dataSource: dataSource);
            else
                return Fetch(ds, parameter, name, _latmins, _lonmins, lat.Dimensions[0].Name, lon.Dimensions[0].Name, dimTime: timeSlices.Dimensions[0].Name, latmaxs: _latmaxs, lonmaxs: _lonmaxs, timeSlices: _times, nameUncertainty: nameUncertainty, nameProvenance: nameProvenance, dataSource: dataSource);
        }
 public static void FillDataSetWithRequest(DataSet ds, ClimateParameter parameter, double[] latmin, double[] latmax, double[] lonmin, double[] lonmax, int[] starthour, int[] stophour, int[] startday, int[] stopday, int[] startyear, int[] stopyear)
 {
     FillDataSetWithRequest(ds, parameter, latmin, latmax, lonmin, lonmax, starthour, stophour, startday, stopday, startyear, stopyear, new FetchingOptions());
 }
 private static string GetLongName(ClimateParameter parameter)
 {
     switch (parameter)
     {
         case ClimateParameter.FC_TEMPERATURE:
             return "Air temperature near surface";
         case ClimateParameter.FC_LAND_AIR_TEMPERATURE:
             return "Air temperature near surface (land area)";
         case ClimateParameter.FC_OCEAN_AIR_TEMPERATURE:
             return "Air temperature near surface (ocean area)";
         case ClimateParameter.FC_PRECIPITATION:
             return "Precipitation rate";
         case ClimateParameter.FC_ELEVATION:
             return "Earth surface elevation";
         case ClimateParameter.FC_LAND_ELEVATION:
             return "Land elevation above sea level";
         case ClimateParameter.FC_LAND_FROST_DAY_FREQUENCY:
             return "Frost day frequency";
         case ClimateParameter.FC_LAND_WET_DAY_FREQUENCY:
             return "Wet day frequency";
         case ClimateParameter.FC_OCEAN_DEPTH:
             return "Bathymetry";
         case ClimateParameter.FC_SOIL_MOISTURE:
             return "Soil moisture";
         case ClimateParameter.FC_RELATIVE_HUMIDITY:
             return "Air relative humidity";
         case ClimateParameter.FC_LAND_AIR_RELATIVE_HUMIDITY:
             return "Air relative humidity (land area)";
         case ClimateParameter.FC_LAND_WIND_SPEED:
             return "Near surface wind speed";
         case ClimateParameter.FC_LAND_DIURNAL_TEMPERATURE_RANGE:
             return "Diurnal temperature range";
         case ClimateParameter.FC_LAND_SUN_PERCENTAGE:
             return "Percent of maximum possible sunshine";
         default:
             return parameter.ToString();
     }
 }
 public double FetchClimate(ClimateParameter parameter, double latmin, double latmax, double lonmin, double lonmax, int starthour, int stophour, int startday, int stopday, int startyear, int stopyear)
 {
     AssertFcParameters(latmin, latmax, lonmin, lonmax, starthour, stophour, startday, stopday, startyear, stopyear);
     return((double)(((FetchClimateSingleResponce)FetchClimate(parameter, latmin, latmax, lonmin, lonmax, starthour, stophour, startday, stopday, startyear, stopyear, new FetchingOptions())).Value.GetValueInDefaultClientUnits()));
 }