private LoksimFile LoadFile(L3dFilePath path) { LoksimFile file = null; try { switch (System.IO.Path.GetExtension(path.AbsolutePath).ToLower()) { case ".l3dwth": { WeatherFile f = new WeatherFile(); f.LoadFromFile(path); file = f; } break; case ".l3dsky": { SkyFile f = new SkyFile(); f.LoadFromFile(path); file = f; } break; case ".l3dfst": { DrivingCabFile f = new DrivingCabFile(); f.LoadFromFile(path); file = f; } break; default: Debug.Assert(false, "Unknown File Type"); break; } this.Title = Loksim3D.WetterEdit.Resources.Strings.AppName + " [" + path.Filename + "]"; Settings.RegistrySettings.Default.AddRecentFile(path); } catch (Exception ex) { Mouse.OverrideCursor = null; MessageBox.Show(String.Format(Loksim3D.WetterEdit.Resources.Strings.ErrorLoadingFile_0_Msg_1_, path.Filename, ex.Message), Loksim3D.WetterEdit.Resources.Strings.AppName, MessageBoxButton.OK, MessageBoxImage.Error); } return(file); }
internal void CreateNewFile(string fileToOpen) { if (fileToOpen != null) { string arg0 = _fileToOpen.Trim(); LoksimFile file = null; switch (arg0.ToLower()) { case "-l3dsky": file = new SkyFile(); break; case "-l3dwth": file = WeatherFile.CreateNewDefaultFile(); break; case "-l3dfst": file = new DrivingCabFile(); break; default: file = LoadFile(new L3dFilePath(arg0)); break; } if (file != null) { SetCtrlAndViewModel(file); } } #if DEBUG //TODO Just for driving cab dev /* * else * { * LoksimFile f = new DrivingCabFile(); * SetCtrlAndViewModel(f); * } */ #endif }
public void GenerateWeatherFile50Years() { // name of old style validation xml file. // NB: This is a real YP validation XML file from 2004. string fileName = Path.Combine(filesDirectory, "TestValidation.xml"); // Create a YieldProphet object from our YP xml file YieldProphet spec = YieldProphetUtility.YieldProphetFromFile(fileName); // Read in the rainfall data Utility.ApsimTextFile observedDataFile = new Utility.ApsimTextFile(); observedDataFile.Open(Path.Combine(filesDirectory, "TestValidation.rain")); DataTable observedData = observedDataFile.ToTable(); observedDataFile.Close(); // Write the weather file. string rainFileName = Path.Combine(workingDirectory, spec.Paddock[0].Name) + ".met"; WeatherFile weatherFiles = new WeatherFile(); weatherFiles.CreateLongTerm(rainFileName, spec.Paddock[0].StationNumber, spec.Paddock[0].StartSeasonDate, spec.Paddock[0].StartSeasonDate.AddDays(300), new DateTime(2004, 6, 1), observedData, 50); Assert.AreEqual(weatherFiles.FilesCreated.Length, 50); Assert.AreEqual(Path.GetFileName(weatherFiles.FilesCreated[0]), "2004;A and R Weidemann;Wep 11954.met"); Utility.ApsimTextFile weatherFile = new Utility.ApsimTextFile(); weatherFile.Open(Path.Combine(workingDirectory, weatherFiles.FilesCreated[0])); DataTable weatherData = weatherFile.ToTable(); weatherFile.Close(); Assert.AreEqual(weatherData.Rows.Count, 301); Assert.AreEqual(weatherData.Rows[0]["codes"], "SSSO"); Assert.AreEqual(weatherData.Rows[61]["codes"], "SSSO"); Assert.AreEqual(weatherData.Rows[62]["codes"], "HHHH"); }
private void ButtonOK_Click(object sender, RoutedEventArgs e) { ListViewItem it = listView.SelectedItem as ListViewItem; if (it != null && it.Tag != null) { switch (it.Tag.ToString()) { case "l3dsky": SelectedFile = new SkyFile(); break; case "l3dwth": SelectedFile = WeatherFile.CreateNewDefaultFile(); break; case "l3dfst": SelectedFile = new DrivingCabFile(); break; } DialogResult = true; Close(); } }
public WeatherViewModel(WeatherFile weatherFile, Window parentWindow) : base(weatherFile, parentWindow) { _weatherFile = weatherFile; NewTimeRangeCmd = new RelayCommand(arg => { _weatherFile.WeatherSet.Add(new WeatherTimeRange(WeatherFile)); SelectedTimeRange = _weatherFile.WeatherSet.Last(); } ); DelTimeRangeCmd = new RelayCommand(arg => { _weatherFile.WeatherSet.Remove(SelectedTimeRange); }, arg => { return(SelectedTimeRange != null); } ); AddVariableCmd = new RelayCommand(arg => { if (SelectedTimeRange != null) { SelectedTimeRange.Variables.Add(new L3dVariable(WeatherFile, "Variable", string.Empty)); SelectedVariable = SelectedTimeRange.Variables.Last(); } }, arg => { return(SelectedTimeRange != null); } ); RemoveVariableCmd = new RelayCommand(arg => { if (SelectedTimeRange != null && SelectedVariable != null) { SelectedTimeRange.Variables.Remove(SelectedVariable); SelectedVariable = null; } }, arg => { return(SelectedTimeRange != null && SelectedVariable != null); } ); CopyTimeRange = new RelayCommand(arg => { try { if (SelectedTimeRange != null) { Clipboard.SetText(SelectedTimeRange.ConvertToXml().ToString(), TextDataFormat.UnicodeText); } } catch (Exception) { SystemSounds.Exclamation.Play(); } }, arg => { return(SelectedTimeRange != null); } ); CutTimeRange = new RelayCommand(arg => { try { if (SelectedTimeRange != null) { Clipboard.SetText(SelectedTimeRange.ConvertToXml().ToString(), TextDataFormat.UnicodeText); _weatherFile.WeatherSet.Remove(SelectedTimeRange); } } catch (Exception) { SystemSounds.Exclamation.Play(); } }, arg => { return(SelectedTimeRange != null); } ); PasteTimeRange = new RelayCommand(arg => { var w = WeatherTimeRange.ReadFromXml(Clipboard.GetText(), WeatherFile); if (w != null) { _weatherFile.WeatherSet.Add(w); SelectedTimeRange = w; } }, arg => { try { return(Clipboard.ContainsText() && WeatherTimeRange.ReadFromXml(Clipboard.GetText(), WeatherFile) != null); } catch (Exception) { return(false); } } ); SortTimeRangesCmd = new RelayCommand(arg => { string sortCol = (string)arg; _timerangesView.SortDescriptions.Clear(); if (_timerangesSortAsc) { _timerangesView.SortDescriptions.Add(new SortDescription(sortCol, ListSortDirection.Ascending)); } else { _timerangesView.SortDescriptions.Add(new SortDescription(sortCol, ListSortDirection.Descending)); } _timerangesSortAsc = !_timerangesSortAsc; } ); _weatherCtrl = new WeatherCtrl(); _weatherCtrl.WeatherFile = _weatherFile; _timerangesView = new CollectionViewSource(); _timerangesView.Source = _weatherFile.WeatherSet; SelectedTimeRange = _weatherFile.WeatherSet.FirstOrDefault(); }
/// <summary>Get a rainfall forecast for the specified station number.</summary> /// <param name="stationNumber">The SILO station number.</param> /// <returns>Stream of data.</returns> public Stream Get(int stationNumber, DateTime nowDate, bool rainOnly) { // Get SILO data and write to a temporary file. DateTime startDate = new DateTime(1981, 1, 1); MemoryStream dataStream = WeatherFile.ExtractMetStreamFromSILO(stationNumber, startDate, DateTime.Now); string siloFileName = GetTemporaryFileName(); string forecastFileName = null; try { File.WriteAllBytes(siloFileName, dataStream.ToArray()); ChangeToWorkingDirectory(); // Run the MatLab script over the temporary SILO file. POAMAforecast.Class1 forecast = new POAMAforecast.Class1(); MWArray metFile = new MWCharArray(siloFileName); MWArray rainfallOnly = new MWNumericArray((double)1); if (!rainOnly) { rainfallOnly = new MWNumericArray((double)0); } MWArray writeFiles = new MWNumericArray((double)1.0); MWArray startDay = new MWNumericArray(Convert.ToDouble(nowDate.Day)); MWArray startMonth = new MWNumericArray(Convert.ToDouble(nowDate.Month)); MWArray startYear = new MWNumericArray(Convert.ToDouble(nowDate.Year)); forecast.calsite(metFile, rainfallOnly, writeFiles, startDay, startMonth, startYear); forecastFileName = siloFileName.Replace(".sim", "") + "_" + nowDate.Year + ".sim"; // Get rid of temporary file. File.Delete(siloFileName); if (WebOperationContext.Current != null && WebOperationContext.Current.OutgoingRequest != null) { WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain"; } if (File.Exists(forecastFileName)) { // Read in the forecast data. byte[] bytes = File.ReadAllBytes(forecastFileName); return(new MemoryStream(bytes)); } else { return(null); } } finally { if (File.Exists(siloFileName)) { File.Delete(siloFileName); } if (forecastFileName != null && File.Exists(forecastFileName)) { File.Delete(forecastFileName); } } }
public static string ExportEPW(WeatherFile weatherfile, string outputPath) { if (weatherfile == null) { return(""); } List <string> outputStrings = new List <string>(); // header outputStrings.Add(String.Format("LOCATION,{0},{1},{2},{3},{4},{5},{6},{7},{8}", weatherfile.CityName, weatherfile.StateName, weatherfile.Country, "BHoM custom data", weatherfile.WMOID, weatherfile.SpaceTime.Location.Latitude, weatherfile.SpaceTime.Location.Longitude, weatherfile.SpaceTime.Location.UtcOffset, weatherfile.SpaceTime.Location.Elevation)); outputStrings.Add("DESIGN CONDITIONS,0"); outputStrings.Add("TYPICAL / EXTREME PERIODS,0"); outputStrings.Add("GROUND TEMPERATURES,0"); outputStrings.Add("HOLIDAYS / DAYLIGHT SAVINGS,No,0,0,0"); outputStrings.Add(String.Format("COMMENTS 1, This file was generated using BHoM on {0}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"))); outputStrings.Add("COMMENTS 2, NA"); outputStrings.Add("DATA PERIODS,1,1,Data,Sunday,1 / 1,12 / 31"); // data int n = 0; for (DateTime date = new DateTime(2018, 1, 1, 0, 0, 0); date <= new DateTime(2018, 12, 31, 23, 30, 0); date = date.AddHours(1)) { outputStrings.Add( String.Format( "{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22},{23},{24},{25},{26},{27},{28},{29},{30},{31},{32},{33},{34}", date.Year, date.Month, date.Day, date.Hour + 1, date.Minute + 60, weatherfile.UncertaintyFlag[n], weatherfile.DryBulbTemperature[n], weatherfile.DewPointTemperature[n], weatherfile.RelativeHumidity[n], weatherfile.AtmosphericStationPressure[n], weatherfile.ExtraterrestrialHorizontalRadiation[n], weatherfile.ExtraterrestrialDirectNormalRadiation[n], weatherfile.HorizontalInfraredRadiationIntensity[n], weatherfile.GlobalHorizontalRadiation[n], weatherfile.DirectNormalRadiation[n], weatherfile.DiffuseHorizontalRadiation[n], weatherfile.GlobalHorizontalIlluminance[n], weatherfile.DirectNormalIlluminance[n], weatherfile.DiffuseHorizontalIlluminance[n], weatherfile.ZenithLuminance[n], weatherfile.WindDirection[n], weatherfile.WindSpeed[n], weatherfile.TotalSkyCover[n], weatherfile.OpaqueSkyCover[n], weatherfile.Visibility[n], weatherfile.CeilingHeight[n], weatherfile.PresentWeatherObservation[n], weatherfile.PresentWeatherCodes[n], weatherfile.PrecipitableWater[n], weatherfile.AerosolOpticalDepth[n], weatherfile.SnowDepth[n], weatherfile.DaysSinceLastSnowfall[n], weatherfile.Albedo[n], weatherfile.LiquidPrecipitationDepth[n], weatherfile.LiquidPrecipitationQuantity[n] ) ); n += 1; } // write to file System.IO.File.WriteAllLines(outputPath, outputStrings); return(outputPath); }
public static WeatherFile ImportEPW(string filePath) { // Declare a weatherfile object to which attribtues can be passed WeatherFile epw = new WeatherFile(); // Check that file passed exists, and exit if it doesn't while passing a record of your failure to the Error Log if (!File.Exists(filePath)) { BH.Engine.Reflection.Compute.RecordError("File not found. Did you give the correct path?"); return(null); } // Read all lines of file passed as strings string[] lines = System.IO.File.ReadAllLines(filePath); // Check to see if the file passed contains the requisite number of lines to parse as an EPW (> 8760) if (lines.Count() < 8760) { BH.Engine.Reflection.Compute.RecordError("The file passed has less than 8760 lines. Are you sure it's an EPW?"); return(null); } // Get location data from the EPW file header and pass to EPW object List <String> header = lines[0].Split(',').ToList(); // Check that file header is capable of being parsed as location data if (header.Count() < 10) { BH.Engine.Reflection.Compute.RecordError("The file passed has an odd header structure. Are you sure it's an EPW?"); return(null); } // Load location (and UTC offset) data epw.CityName = header[1]; epw.StateName = header[2]; epw.Country = header[3]; epw.WeatherSource = header[4]; epw.WMOID = header[5]; epw.SpaceTime = new SpaceTime(); epw.SpaceTime.Location.Latitude = System.Convert.ToDouble(header[6]); epw.SpaceTime.Location.Longitude = System.Convert.ToDouble(header[7]); epw.SpaceTime.Location.UtcOffset = System.Convert.ToDouble(header[8]); epw.SpaceTime.Location.Elevation = System.Convert.ToDouble(header[9]); // Create a list of lists from the last 8760 lines of the file, each sublist representing values for an hour of the year List <List <String> > rawData = new List <List <String> >(); for (int i = lines.Count() - 8760; i < lines.Count(); ++i) { rawData.Add(lines[i].Split(',').ToList()); } // Transpose the list of lists into a list of annual hourly variables List <List <String> > data = BH.Engine.Data.Modify.TransposeRectangularCollection(rawData); try { // Populate the EPW object with the hourly variables data epw.Year = data[0].ConvertAll(x => System.Convert.ToInt32(x)).ToList(); epw.Month = data[1].ConvertAll(x => System.Convert.ToInt32(x)).ToList(); epw.Day = data[2].ConvertAll(x => System.Convert.ToInt32(x)).ToList(); epw.Hour = data[3].ConvertAll(x => System.Convert.ToInt32(x) - 1).ToList(); epw.Minute = data[4].ConvertAll(x => System.Convert.ToInt32(x) - 60).ToList(); epw.UncertaintyFlag = data[5]; //A list of string epw.DryBulbTemperature = ConvertData(data, 6, "Dry Bulb Temperature"); epw.DewPointTemperature = ConvertData(data, 7, "Dew Point Temperature"); epw.RelativeHumidity = ConvertData(data, 8, "Relative Humidity"); epw.AtmosphericStationPressure = ConvertData(data, 9, "Atmospheric Station Pressure"); epw.ExtraterrestrialHorizontalRadiation = ConvertData(data, 10, "Extraterrestrial Horizontal Radiation"); epw.ExtraterrestrialDirectNormalRadiation = ConvertData(data, 11, "Extraterrestrial Direct Normal Radiation"); epw.HorizontalInfraredRadiationIntensity = ConvertData(data, 12, "Horizontal Infrared Radiation Intensity"); epw.GlobalHorizontalRadiation = ConvertData(data, 13, "Global Horizontal Radiation"); epw.DirectNormalRadiation = ConvertData(data, 14, "Direct Normal Radiation"); epw.DiffuseHorizontalRadiation = ConvertData(data, 15, "Diffuse Horizontal Radiation"); epw.GlobalHorizontalIlluminance = ConvertData(data, 16, "Global Horizontal Illuminance"); epw.DirectNormalIlluminance = ConvertData(data, 17, "Direct Normal Illuminance"); epw.DiffuseHorizontalIlluminance = ConvertData(data, 18, "Diffuse Horizontal Illuminance"); epw.ZenithLuminance = ConvertData(data, 19, "Zenith Luminance"); epw.WindDirection = ConvertData(data, 20, "Wind Direction"); epw.WindSpeed = ConvertData(data, 21, "Wind Speed"); epw.TotalSkyCover = ConvertData(data, 22, "Total Sky Cover"); epw.OpaqueSkyCover = ConvertData(data, 23, "Opaque Sky Cover"); epw.Visibility = ConvertData(data, 24, "Visibility"); epw.CeilingHeight = ConvertData(data, 25, "Ceiling Height"); epw.PresentWeatherObservation = ConvertData(data, 26, "Present Weather Observation"); epw.PresentWeatherCodes = ConvertData(data, 27, "Present Weather Codes"); epw.PrecipitableWater = ConvertData(data, 28, "Precipitable Water"); epw.AerosolOpticalDepth = ConvertData(data, 29, "Aerosol Optical Depth"); epw.SnowDepth = ConvertData(data, 30, "Snow Depth"); epw.DaysSinceLastSnowfall = ConvertData(data, 31, "Days Since Last Snowfall"); epw.Albedo = ConvertData(data, 32, "Albedo"); epw.LiquidPrecipitationDepth = ConvertData(data, 33, "Liquid Precipitation Depth"); epw.LiquidPrecipitationQuantity = ConvertData(data, 34, "Liquid Precipitation Quantity"); } catch (Exception e) { BH.Engine.Reflection.Compute.RecordError(e.ToString()); return(null); } return(epw); }