// Copyright (C) Stichting Deltares 2017. 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 System.IO;
using Core.Common.Base.IO;
using Core.Common.Utils;
using log4net;
using Ringtoets.Common.Data.Exceptions;
using Ringtoets.Common.Data.Hydraulics;
using Ringtoets.Common.Data.IllustrationPoints;
using Ringtoets.Common.IO.HydraRing;
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.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 marginal wave statistics.
///
public class WaveHeightCalculationService
{
private static readonly ILog log = LogManager.GetLogger(typeof(WaveHeightCalculationService));
private IWaveHeightCalculator calculator;
private bool canceled;
///
/// Performs validation on the given and .
/// Error and status information is logged during the execution of the operation.
///
/// The file path of the hydraulic boundary database file which to validate.
/// The preprocessor directory to validate.
/// True if there were no validation errors; False otherwise.
public static bool Validate(string hydraulicBoundaryDatabaseFilePath, string preprocessorDirectory)
{
var isValid = true;
CalculationServiceHelper.LogValidationBegin();
string databaseFilePathValidationProblem = HydraulicBoundaryDatabaseHelper.ValidatePathForCalculation(hydraulicBoundaryDatabaseFilePath);
if (!string.IsNullOrEmpty(databaseFilePathValidationProblem))
{
CalculationServiceHelper.LogMessagesAsError(Resources.Hydraulic_boundary_database_connection_failed_0_,
new[]
{
databaseFilePathValidationProblem
});
isValid = false;
}
string preprocessorDirectoryValidationProblem = HydraulicBoundaryDatabaseHelper.ValidatePreprocessorDirectory(preprocessorDirectory);
if (!string.IsNullOrEmpty(preprocessorDirectoryValidationProblem))
{
CalculationServiceHelper.LogMessagesAsError(new[]
{
preprocessorDirectoryValidationProblem
});
isValid = false;
}
CalculationServiceHelper.LogValidationEnd();
return isValid;
}
///
/// Performs a calculation for wave height.
///
/// The wave height calculation to use.
/// The path which points to the hydraulic boundary database file.
/// The preprocessor directory.
/// The norm of the assessment section.
/// The object which is used to build log messages.
/// Preprocessing is disabled when equals .
/// Thrown when ,
/// or
/// is null.
/// Thrown when
///
/// - 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
/// 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(IHydraulicBoundaryWrapperCalculation waveHeightCalculation,
string hydraulicBoundaryDatabaseFilePath,
string preprocessorDirectory,
double norm,
ICalculationMessageProvider messageProvider)
{
if (waveHeightCalculation == null)
{
throw new ArgumentNullException(nameof(waveHeightCalculation));
}
string hlcdDirectory = Path.GetDirectoryName(hydraulicBoundaryDatabaseFilePath);
CalculationServiceHelper.LogCalculationBegin();
calculator = HydraRingCalculatorFactory.Instance.CreateWaveHeightCalculator(hlcdDirectory, preprocessorDirectory);
var exceptionThrown = false;
try
{
PerformCalculation(waveHeightCalculation,
hydraulicBoundaryDatabaseFilePath,
!string.IsNullOrEmpty(preprocessorDirectory),
norm,
messageProvider);
}
catch (HydraRingCalculationException)
{
if (!canceled)
{
string lastErrorContent = calculator.LastErrorFileContent;
log.Error(string.IsNullOrEmpty(lastErrorContent)
? messageProvider.GetCalculationFailedMessage(waveHeightCalculation.Name)
: messageProvider.GetCalculationFailedWithErrorReportMessage(waveHeightCalculation.Name,
lastErrorContent));
exceptionThrown = true;
throw;
}
}
finally
{
string lastErrorFileContent = calculator.LastErrorFileContent;
bool errorOccurred = CalculationServiceHelper.HasErrorOccurred(canceled, exceptionThrown, lastErrorFileContent);
if (errorOccurred)
{
log.Error(messageProvider.GetCalculationFailedWithErrorReportMessage(waveHeightCalculation.Name,
lastErrorFileContent));
}
log.InfoFormat(Resources.WaveHeightCalculationService_Calculate_Calculation_temporary_directory_can_be_found_on_location_0, calculator.OutputDirectory);
CalculationServiceHelper.LogCalculationEnd();
if (errorOccurred)
{
throw new HydraRingCalculationException(lastErrorFileContent);
}
}
}
///
/// Cancels any currently running wave height calculation.
///
public void Cancel()
{
calculator?.Cancel();
canceled = true;
}
///
/// Performs a calculation for the wave height.
///
/// The wave height calculation to use.
/// The path which points to the hydraulic boundary database file.
/// Indicator whether to use the preprocessor in the 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
/// 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(IHydraulicBoundaryWrapperCalculation waveHeightCalculation,
string hydraulicBoundaryDatabaseFilePath,
bool usePreprocessor,
double norm,
ICalculationMessageProvider messageProvider)
{
WaveHeightCalculationInput calculationInput = CreateInput(waveHeightCalculation, norm, hydraulicBoundaryDatabaseFilePath, usePreprocessor);
calculator.Calculate(calculationInput);
if (canceled || !string.IsNullOrEmpty(calculator.LastErrorFileContent))
{
return;
}
GeneralResult generalResult = null;
try
{
generalResult = waveHeightCalculation.CalculateIllustrationPoints
? GetGeneralResult(calculator.IllustrationPointsResult)
: null;
}
catch (ArgumentException e)
{
log.Warn(string.Format(Resources.CalculationService_Error_in_reading_illustrationPoints_for_CalculationName_0_with_ErrorMessage_1,
waveHeightCalculation.Name,
e.Message));
}
HydraulicBoundaryLocationOutput hydraulicBoundaryLocationOutput = CreateHydraulicBoundaryLocationOutput(
messageProvider, waveHeightCalculation.Name, calculationInput.Beta, norm, calculator.Converged, generalResult);
waveHeightCalculation.Output = hydraulicBoundaryLocationOutput;
}
///
/// 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 HydraulicBoundaryLocationOutput CreateHydraulicBoundaryLocationOutput(
ICalculationMessageProvider messageProvider,
string hydraulicBoundaryLocationName,
double targetReliability,
double targetProbability,
bool? calculatorConverged,
GeneralResult generalResult)
{
double waveHeight = calculator.WaveHeight;
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 HydraulicBoundaryLocationOutput(waveHeight, targetProbability,
targetReliability, probability, reliability,
converged, generalResult);
}
///
/// Creates the input for an wave height calculation.
///
/// The
/// to create the input from.
/// The norm to use during the calculation.
/// The file path to the hydraulic
/// boundary database.
/// Indicator whether to use the preprocessor in the calculation.
/// A .
/// Thrown when the
/// contains invalid characters.
/// Thrown when:
///
/// - No settings database file could be found at the location of
/// with the same name.
/// - Unable to open settings database file.
/// - Unable to read required data from database file.
///
///
private static WaveHeightCalculationInput CreateInput(IHydraulicBoundaryWrapperCalculation waveHeightCalculation,
double norm,
string hydraulicBoundaryDatabaseFilePath,
bool usePreprocessor)
{
var waveHeightCalculationInput = new WaveHeightCalculationInput(1, waveHeightCalculation.Id, norm);
HydraRingSettingsDatabaseHelper.AssignSettingsFromDatabase(waveHeightCalculationInput, hydraulicBoundaryDatabaseFilePath, usePreprocessor);
return waveHeightCalculationInput;
}
}
}