public void Add(SoundSpeed newData)
 {
     foreach (var soundSpeedField in newData.SoundSpeedFields)
     {
         if (this[soundSpeedField.TimePeriod] != null) throw new DataException(string.Format("Unable to add SoundSpeedField for {0}. Data already present.", soundSpeedField.TimePeriod));
         SoundSpeedFields.Add(soundSpeedField);
     }
 }
 public static SoundSpeed Average(SoundSpeed monthlySoundSpeeds, List<TimePeriod> timePeriods)
 {
     var result = new SoundSpeed();
     foreach (var timePeriod in timePeriods)
     {
         var months = Globals.AppSettings.NAVOConfiguration.MonthsInTimePeriod(timePeriod);
         var accumulator = new SoundSpeedFieldAverager { TimePeriod = timePeriod };
         foreach (var month in months) accumulator.Add(monthlySoundSpeeds[month]);
         result.SoundSpeedFields.Add(accumulator.Average);
     }
     return result;
 }
 public static SoundSpeed Deserialize(BinaryReader reader)
 {
     var result = new SoundSpeed();
     var fieldCount = reader.ReadInt32();
     for (var i = 0; i < fieldCount; i++)
         result.SoundSpeedFields.Add(SoundSpeedField.Deserialize(reader));
     return result;
 }
 internal static void VerifyThatTimePeriodsMatch(SoundSpeed data1, SoundSpeed data2)
 {
     foreach (var field1 in data1.SoundSpeedFields.Where(field1 => data2[field1.TimePeriod] == null)) throw new DataException(string.Format("SoundSpeeds do not contain the same time periods. Data 1 has time period {0}, data 2 does not", field1.TimePeriod));
     foreach (var field2 in data2.SoundSpeedFields.Where(field2 => data1[field2.TimePeriod] == null)) throw new DataException(string.Format("SoundSpeeds do not contain the same time periods. Data 2 has time period {0}, data 1 does not", field2.TimePeriod));
 }
 public static SoundSpeedField Average(SoundSpeed monthlySoundSpeeds, TimePeriod timePeriod)
 {
     var months = Globals.AppSettings.NAVOConfiguration.MonthsInTimePeriod(timePeriod).ToList();
     var accumulator = new SoundSpeedFieldAverager { TimePeriod = timePeriod };
     foreach (var month in months) accumulator.Add(monthlySoundSpeeds[month]);
     return accumulator.Average;
 }
        void NewEnvironmentHandler()
        {
            var overlayName = Path.GetFileNameWithoutExtension(SelectedOverlayDescriptor.DataFilename);
            var bathymetryName = Path.GetFileNameWithoutExtension(SelectedBathymetryDescriptor.DataFilename);
            var vm = new EnvironmentExtractionViewModel(overlayName, bathymetryName);
            var result = _visualizerService.ShowDialog("EnvironmentExtractionView", vm);
            if ((!result.HasValue) || (!result.Value)) return;
            var bathymetry = SelectedBathymetryDescriptor.Data;
            var maxDepth = new EarthCoordinate<float>(bathymetry.Minimum, Math.Abs(bathymetry.Minimum.Data));
            var extractionArea = new GeoRect(SelectedOverlayDescriptor.Data.Shapes[0].BoundingBox);
            var tempPath = Path.GetTempPath().Remove(Path.GetTempPath().Length - 1);
            if (!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath);

            var assemblyLocation = Assembly.GetCallingAssembly().Location;
            var extractionPath = Path.GetDirectoryName(assemblyLocation);
            if (extractionPath == null) throw new ApplicationException("Extraction path can't be null!");

            var gdemExtractionProgramPath = Path.Combine(extractionPath, "ImportGDEM.exe");
            var gdemRequiredSupportFiles = new List<string>
            {
                    Path.Combine(extractionPath, "netcdf.dll"),
                    Path.Combine(extractionPath, "NetCDF_Wrapper.dll")
            };

            var extendedMonthlySoundSpeeds = new SoundSpeed();
            var extendedAndAveragedSoundSpeeds = new SoundSpeed();
            var monthlyTemperature = new SoundSpeed();
            var monthlySalinity = new SoundSpeed();

            var soundSpeedExtractors = new List<GDEMBackgroundExtractor>();

            var selectedTimePeriods = vm.EnvironmentDescriptors.Select(t => t.TimePeriod).ToList();
            var requiredMonths = selectedTimePeriods.Select(Globals.AppSettings.NAVOConfiguration.MonthsInTimePeriod).ToList();
            var allMonths = new List<NAVOTimePeriod>();
            foreach (var curPeriod in requiredMonths) allMonths.AddRange(curPeriod);
            var uniqueMonths = allMonths.Distinct().ToList();
            uniqueMonths.Sort();
            var environmentPath = Path.Combine(Globals.AppSettings.ScenarioDataDirectory, SelectedRangeComplexDescriptor.Data.Name, "Environment");
            BackgroundTaskAggregator = new BackgroundTaskAggregator();

            var naemoEnvironmentExporters = selectedTimePeriods.Select(t => new CASSBackgroundExporter
            {
                    WorkerSupportsCancellation = false,
                    BathymetryFileName = Path.GetFileName(SelectedBathymetryDescriptor.DataFilename),
                    OverlayFileName = Path.GetFileName(SelectedOverlayDescriptor.DataFilename),
                    TimePeriod = t,
                    ExtractionArea = extractionArea,
                    NAVOConfiguration = Globals.AppSettings.NAVOConfiguration,
                    DestinationPath = Path.Combine(environmentPath, vm.EnvironmentDescriptors.Find(descriptor => descriptor.TimePeriod == t).EnvironmentName + ".dat"),
                    UseExpandedExtractionArea = false,
                    TaskName = "Export NAEMO environment for " + t,
            }).ToList();
            foreach (var exporter in naemoEnvironmentExporters)
            {
                exporter.RunWorkerCompleted += (s, e) =>
                {
                    var curExporter = (CASSBackgroundExporter)s;
                    var metadataFilename = NAEMOMetadataBase.MetadataFilename(curExporter.DestinationPath);
                    var metadata = new NAEMOEnvironmentMetadata
                    {
                            BathymetryName = Path.GetFileNameWithoutExtension(curExporter.BathymetryFileName),
                            OverlayFilename = Path.GetFileNameWithoutExtension(curExporter.OverlayFileName),
                            TimePeriod = curExporter.TimePeriod,
                            Bounds = extractionArea,
                            Filename = metadataFilename,
                    };
                    metadata.Save();
                    var environmentDescriptor = new NAEMOEnvironmentDescriptor { DataFilename = curExporter.DestinationPath, Metadata = metadata };
                    lock (NAEMOEnvironmentDescriptors)
                    {
                        NAEMOEnvironmentDescriptors.Add(new KeyValuePair<string, NAEMOEnvironmentDescriptor>(Path.GetFileNameWithoutExtension(curExporter.DestinationPath),
                                                                                                             environmentDescriptor));
                        NAEMOBathymetryDescriptors.Sort();
                        SelectedEnvironmentDescriptor = environmentDescriptor;
                    }
                };
            }

            var windExtractor = new SMGCBackgroundExtractor
            {
                    WorkerSupportsCancellation = false,
                    ExtractionArea = extractionArea,
                    SelectedTimePeriods = selectedTimePeriods,
                    NAVOConfiguration = Globals.AppSettings.NAVOConfiguration,
                    UseExpandedExtractionArea = false,
                    TaskName = "Wind data extraction",
            };
            BackgroundTaskAggregator.BackgroundTasks.Add(windExtractor);
            windExtractor.RunWorkerCompleted += (s, e) => { foreach (var naemo in naemoEnvironmentExporters) naemo.Wind = ((SMGCBackgroundExtractor)s).Wind; };

            // Create a sediment extractor
            var sedimentExtractor = new BSTBackgroundExtractor
            {
                    WorkerSupportsCancellation = false,
                    ExtractionArea = extractionArea,
                    NAVOConfiguration = Globals.AppSettings.NAVOConfiguration,
                    UseExpandedExtractionArea = false,
                    TaskName = "Sediment data extraction",
            };
            BackgroundTaskAggregator.BackgroundTasks.Add(sedimentExtractor);
            sedimentExtractor.RunWorkerCompleted += (s, e) => { foreach (var naemo in naemoEnvironmentExporters) naemo.Sediment = ((BSTBackgroundExtractor)s).Sediment; };

            //var temperatureAndSalinityFileWriter = new TemperatureAndSalinityFileWriter
            //{
            //        WorkerSupportsCancellation = false,
            //        DestinationPath = tempPath,
            //        TaskName = "Save soundspeed data"
            //};
            var averagers = selectedTimePeriods.Select(timePeriod => new SoundSpeedBackgroundAverager
            {
                    WorkerSupportsCancellation = false,
                    TimePeriod = timePeriod,
                    ExtractionArea = extractionArea,
                    NAVOConfiguration = Globals.AppSettings.NAVOConfiguration,
                    UseExpandedExtractionArea = false,
                    TaskName = "Calculate extended sound speeds for " + timePeriod,
            }).ToList();

            foreach (var month in uniqueMonths)
            {
                var soundSpeedExtractor = new GDEMBackgroundExtractor
                {
                        WorkerSupportsCancellation = false,
                        TimePeriod = month,
                        ExtractionArea = extractionArea,
                        NAVOConfiguration = Globals.AppSettings.NAVOConfiguration,
                        DestinationPath = tempPath,
                        UseExpandedExtractionArea = false,
                        ExtractionProgramPath = gdemExtractionProgramPath,
                        RequiredSupportFiles = gdemRequiredSupportFiles,
                        MaxDepth = maxDepth,
                };
                soundSpeedExtractor.RunWorkerCompleted += (sender, e) =>
                {
                    var extractor = (GDEMBackgroundExtractor)sender;
                    monthlyTemperature.SoundSpeedFields.Add(extractor.TemperatureField);
                    monthlySalinity.SoundSpeedFields.Add(extractor.SalinityField);
                    extendedMonthlySoundSpeeds.SoundSpeedFields.Add(extractor.ExtendedSoundSpeedField);
                    //Console.WriteLine("soundspeed extractor for {0} complete. {1} extractors are still busy", extractor.TimePeriod, soundSpeedExtractors.Where(s => s.IsBusy).Count());
                    if (soundSpeedExtractors.Any(ssfExtractor => ssfExtractor.IsBusy)) return;
                    //temperatureAndSalinityFileWriter.Temperature = monthlyTemperature;
                    //temperatureAndSalinityFileWriter.Salinity = monthlySalinity;
                    foreach (var averager in averagers) averager.ExtendedMonthlySoundSpeeds = extendedMonthlySoundSpeeds;
                };
                soundSpeedExtractors.Add(soundSpeedExtractor);
                BackgroundTaskAggregator.BackgroundTasks.Add(soundSpeedExtractor);
            }
            //BackgroundTaskAggregator.BackgroundTasks.Add(temperatureAndSalinityFileWriter);
            foreach (var averager in averagers)
            {
                BackgroundTaskAggregator.BackgroundTasks.Add(averager);
                averager.RunWorkerCompleted += (sender, e) =>
                {
                    var avg = (SoundSpeedBackgroundAverager)sender;
                    extendedAndAveragedSoundSpeeds.SoundSpeedFields.Add(avg.ExtendedAverageSoundSpeedField);
                    if (averagers.Any(a => a.IsBusy)) return;
                    foreach (var naemo in naemoEnvironmentExporters) naemo.ExtendedAndAveragedSoundSpeeds = extendedAndAveragedSoundSpeeds;
                };
            }
            foreach (var naemo in naemoEnvironmentExporters)
                BackgroundTaskAggregator.BackgroundTasks.Add(naemo);
            BackgroundTaskAggregator.TaskName = "Environmental data extraction";
        }