// Copyright (C) Stichting Deltares 2018. All rights reserved. // // This file is part of Ringtoets. // // Ringtoets is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . // // All names, logos, and references to "Deltares" are registered trademarks of // Stichting Deltares and remain full property of Stichting Deltares at all times. // All rights reserved. using System; using Core.Common.Base.IO; using Core.Common.Util; using log4net; using Ringtoets.Common.Data.Exceptions; using Ringtoets.Common.Data.Hydraulics; using Ringtoets.Common.Data.IllustrationPoints; using Ringtoets.Common.Service.IllustrationPoints; using Ringtoets.Common.Service.MessageProviders; using Ringtoets.Common.Service.Properties; using Ringtoets.HydraRing.Calculation.Calculator; using Ringtoets.HydraRing.Calculation.Calculator.Factory; using Ringtoets.HydraRing.Calculation.Data.Input; using Ringtoets.HydraRing.Calculation.Data.Input.Hydraulics; using Ringtoets.HydraRing.Calculation.Exceptions; using HydraRingGeneralResult = Ringtoets.HydraRing.Calculation.Data.Output.IllustrationPoints.GeneralResult; namespace Ringtoets.Common.Service { /// /// Service that provides methods for performing Hydra-Ring calculations for design water level. /// public class DesignWaterLevelCalculationService : TargetProbabilityCalculationService { private static readonly ILog log = LogManager.GetLogger(typeof(DesignWaterLevelCalculationService)); private IDesignWaterLevelCalculator calculator; private bool canceled; /// /// Performs a calculation for the design water level. /// /// The hydraulic boundary location calculation to perform. /// The containing all data /// to perform a hydraulic boundary calculation. /// The norm to use during the calculation. /// The object which is used to build log messages. /// Preprocessing is disabled when the preprocessor directory equals . /// Thrown when , /// or is null. /// Thrown when /// /// the hydraulic boundary database file path contains invalid characters. /// The target probability or the calculated probability falls outside the [0.0, 1.0] range and is not . /// /// Thrown when: /// /// No settings database file could be found at the location of hydraulic boundary database file path. /// with the same name. /// Unable to open settings database file. /// Unable to read required data from database file. /// /// Thrown when an error occurs while performing the calculation. public void Calculate(HydraulicBoundaryLocationCalculation hydraulicBoundaryLocationCalculation, HydraulicBoundaryCalculationSettings calculationSettings, double norm, ICalculationMessageProvider messageProvider) { if (hydraulicBoundaryLocationCalculation == null) { throw new ArgumentNullException(nameof(hydraulicBoundaryLocationCalculation)); } if (calculationSettings == null) { throw new ArgumentNullException(nameof(calculationSettings)); } if (messageProvider == null) { throw new ArgumentNullException(nameof(messageProvider)); } HydraulicBoundaryLocation hydraulicBoundaryLocation = hydraulicBoundaryLocationCalculation.HydraulicBoundaryLocation; CalculationServiceHelper.LogCalculationBegin(); HydraRingCalculationSettings hydraRingCalculationSettings = HydraRingCalculationSettingsFactory.CreateSettings(calculationSettings); calculator = HydraRingCalculatorFactory.Instance.CreateDesignWaterLevelCalculator(hydraRingCalculationSettings); var exceptionThrown = false; try { PerformCalculation(hydraulicBoundaryLocationCalculation, calculationSettings, norm, messageProvider); } catch (HydraRingCalculationException) { if (!canceled) { string lastErrorContent = calculator.LastErrorFileContent; log.Error(string.IsNullOrEmpty(lastErrorContent) ? messageProvider.GetCalculationFailedMessage(hydraulicBoundaryLocation.Name) : messageProvider.GetCalculationFailedWithErrorReportMessage(hydraulicBoundaryLocation.Name, lastErrorContent)); exceptionThrown = true; throw; } } finally { string lastErrorFileContent = calculator.LastErrorFileContent; bool errorOccurred = CalculationServiceHelper.HasErrorOccurred(canceled, exceptionThrown, lastErrorFileContent); if (errorOccurred) { log.Error(messageProvider.GetCalculationFailedWithErrorReportMessage(hydraulicBoundaryLocation.Name, lastErrorFileContent)); } log.InfoFormat(Resources.DesignWaterLevelCalculationService_Calculate_Calculation_temporary_directory_can_be_found_on_location_0, calculator.OutputDirectory); CalculationServiceHelper.LogCalculationEnd(); if (errorOccurred) { throw new HydraRingCalculationException(lastErrorFileContent); } } } /// /// Cancels the currently running design water level calculation. /// public void Cancel() { calculator?.Cancel(); canceled = true; } /// /// Performs a calculation for the design water level. /// /// The hydraulic boundary location calculation to perform. /// The containing all data /// to perform a hydraulic boundary calculation. /// The norm of the assessment section. /// The object which is used to build log messages. /// Thrown when: /// /// No settings database file could be found at the location of the hydraulic boundary database file path /// with the same name. /// Unable to open settings database file. /// Unable to read required data from database file. /// /// Thrown when an error occurs while performing the calculation. private void PerformCalculation(HydraulicBoundaryLocationCalculation hydraulicBoundaryLocationCalculation, HydraulicBoundaryCalculationSettings calculationSettings, double norm, ICalculationMessageProvider messageProvider) { HydraulicBoundaryLocation hydraulicBoundaryLocation = hydraulicBoundaryLocationCalculation.HydraulicBoundaryLocation; AssessmentLevelCalculationInput calculationInput = CreateInput(hydraulicBoundaryLocation.Id, norm, calculationSettings); calculator.Calculate(calculationInput); if (canceled || !string.IsNullOrEmpty(calculator.LastErrorFileContent)) { return; } GeneralResult generalResult = null; try { generalResult = hydraulicBoundaryLocationCalculation.InputParameters.ShouldIllustrationPointsBeCalculated ? GetGeneralResult(calculator.IllustrationPointsResult) : null; } catch (ArgumentException e) { log.Warn(string.Format(Resources.CalculationService_Error_in_reading_illustrationPoints_for_CalculationName_0_with_ErrorMessage_1, hydraulicBoundaryLocation.Name, e.Message)); } HydraulicBoundaryLocationCalculationOutput hydraulicBoundaryLocationCalculationOutput = CreateOutput( messageProvider, hydraulicBoundaryLocation.Name, calculationInput.Beta, norm, calculator.Converged, generalResult); hydraulicBoundaryLocationCalculation.Output = hydraulicBoundaryLocationCalculationOutput; } /// /// Gets a based on the information of . /// /// The to base the /// to create on. /// A . private GeneralResult GetGeneralResult(HydraRingGeneralResult hydraRingGeneralResult) { if (hydraRingGeneralResult == null) { log.Warn(calculator.IllustrationPointsParserErrorMessage); return null; } try { return GeneralResultConverter.ConvertToGeneralResultTopLevelSubMechanismIllustrationPoint(hydraRingGeneralResult); } catch (IllustrationPointConversionException e) { log.Warn(Resources.SetGeneralResult_Converting_IllustrationPointResult_Failed, e); } return null; } /// /// Creates the output of the calculation. /// /// The object which is used to build log messages. /// The name of the hydraulic boundary location. /// The target reliability for the calculation. /// The target probability for the calculation. /// The value indicating whether the calculation converged. /// The general result with illustration points. /// A . /// Thrown when /// or the calculated probability falls outside the [0.0, 1.0] range and is not . private HydraulicBoundaryLocationCalculationOutput CreateOutput(ICalculationMessageProvider messageProvider, string hydraulicBoundaryLocationName, double targetReliability, double targetProbability, bool? calculatorConverged, GeneralResult generalResult) { double designWaterLevel = calculator.DesignWaterLevel; double reliability = calculator.ReliabilityIndex; double probability = StatisticsConverter.ReliabilityToProbability(reliability); CalculationConvergence converged = RingtoetsCommonDataCalculationService.GetCalculationConvergence(calculatorConverged); if (converged != CalculationConvergence.CalculatedConverged) { log.Warn(messageProvider.GetCalculatedNotConvergedMessage(hydraulicBoundaryLocationName)); } return new HydraulicBoundaryLocationCalculationOutput(designWaterLevel, targetProbability, targetReliability, probability, reliability, converged, generalResult); } /// /// Creates the input for a design water level calculation. /// /// The id of the hydraulic boundary location. /// The norm to use during the calculation. /// /// An . /// Thrown when the hydraulic boundary database file path /// contains invalid characters. /// Thrown when: /// /// No settings database file could be found at the location of the hydraulic boundary database file path. /// with the same name. /// Unable to open settings database file. /// Unable to read required data from database file. /// /// private static AssessmentLevelCalculationInput CreateInput(long hydraulicBoundaryLocationId, double norm, HydraulicBoundaryCalculationSettings calculationSettings) { var assessmentLevelCalculationInput = new AssessmentLevelCalculationInput(1, hydraulicBoundaryLocationId, norm); HydraRingSettingsDatabaseHelper.AssignSettingsFromDatabase(assessmentLevelCalculationInput, calculationSettings.HydraulicBoundaryDatabaseFilePath, !string.IsNullOrEmpty(calculationSettings.PreprocessorDirectory)); return assessmentLevelCalculationInput; } } }