// 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 log4net;
using Ringtoets.Common.Data.AssessmentSection;
using Ringtoets.Common.Data.Probability;
using Ringtoets.Common.Data.Structures;
using Ringtoets.Common.Service;
using Ringtoets.Common.Service.Structures;
using Ringtoets.HeightStructures.Data;
using Ringtoets.HeightStructures.Service.Properties;
using Ringtoets.HydraRing.Calculation.Calculator;
using Ringtoets.HydraRing.Calculation.Calculator.Factory;
using Ringtoets.HydraRing.Calculation.Data.Input.Structures;
using Ringtoets.HydraRing.Calculation.Exceptions;
namespace Ringtoets.HeightStructures.Service
{
///
/// Service that provides methods for performing Hydra-Ring calculations for height structures.
///
public class HeightStructuresCalculationService : StructuresCalculationServiceBase
{
private static readonly ILog log = LogManager.GetLogger(typeof(HeightStructuresCalculationService));
private IStructuresOvertoppingCalculator calculator;
private bool canceled;
///
/// Cancels any currently running height structures calculation.
///
public void Cancel()
{
calculator?.Cancel();
canceled = true;
}
///
/// Performs a height structures calculation based on the supplied and sets
/// if the calculation was successful. Error and status information is logged during the execution of the operation.
///
/// The that holds all the information required to perform the calculation.
/// The that holds information about the norm used in the calculation.
/// The that holds the information about the contribution
/// and the general inputs used in the calculation.
/// The path which points to the hydraulic boundary database file.
/// Thrown when ,
/// or is null.
/// 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.
///
/// Thrown when an error occurs while performing the calculation.
internal void Calculate(StructuresCalculation calculation,
IAssessmentSection assessmentSection,
HeightStructuresFailureMechanism failureMechanism,
string hydraulicBoundaryDatabaseFilePath)
{
if (calculation == null)
{
throw new ArgumentNullException(nameof(calculation));
}
if (assessmentSection == null)
{
throw new ArgumentNullException(nameof(assessmentSection));
}
if (failureMechanism == null)
{
throw new ArgumentNullException(nameof(failureMechanism));
}
string calculationName = calculation.Name;
StructuresOvertoppingCalculationInput input = CreateInput(calculation, failureMechanism.GeneralInput, hydraulicBoundaryDatabaseFilePath);
string hlcdDirectory = Path.GetDirectoryName(hydraulicBoundaryDatabaseFilePath);
calculator = HydraRingCalculatorFactory.Instance.CreateStructuresOvertoppingCalculator(hlcdDirectory);
CalculationServiceHelper.LogCalculationBegin();
var exceptionThrown = false;
try
{
calculator.Calculate(input);
if (!canceled && string.IsNullOrEmpty(calculator.LastErrorFileContent))
{
ProbabilityAssessmentOutput probabilityAssessmentOutput =
ProbabilityAssessmentService.Calculate(assessmentSection.FailureMechanismContribution.Norm,
failureMechanism.Contribution,
failureMechanism.GeneralInput.N,
calculator.ExceedanceProbabilityBeta);
calculation.Output = new StructuresOutput(probabilityAssessmentOutput);
}
}
catch (HydraRingCalculationException)
{
if (!canceled)
{
string lastErrorContent = calculator.LastErrorFileContent;
if (string.IsNullOrEmpty(lastErrorContent))
{
log.ErrorFormat(Resources.HeightStructuresCalculationService_Calculate_Error_in_HeightStructuresCalculation_0_no_error_report,
calculationName);
}
else
{
log.ErrorFormat(Resources.HeightStructuresCalculationService_Calculate_Error_in_HeightStructuresCalculation_0_click_details_for_last_error_report_1,
calculationName, lastErrorContent);
}
exceptionThrown = true;
throw;
}
}
finally
{
string lastErrorFileContent = calculator.LastErrorFileContent;
bool errorOccurred = CalculationServiceHelper.HasErrorOccurred(canceled, exceptionThrown, lastErrorFileContent);
if (errorOccurred)
{
log.ErrorFormat(Resources.HeightStructuresCalculationService_Calculate_Error_in_HeightStructuresCalculation_0_click_details_for_last_error_report_1,
calculationName, lastErrorFileContent);
}
log.InfoFormat(Resources.HeightStructuresCalculationService_Calculate_Calculation_temporary_directory_can_be_found_on_location_0, calculator.OutputDirectory);
CalculationServiceHelper.LogCalculationEnd();
if (errorOccurred)
{
throw new HydraRingCalculationException(lastErrorFileContent);
}
}
}
///
/// Creates the input for a structures overtopping calculation.
///
/// The calculation to create the input for.
/// The general input to use in the calculation.
/// The path to the hydraulic boundary database file.
/// 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 StructuresOvertoppingCalculationInput CreateInput(
StructuresCalculation calculation,
GeneralHeightStructuresInput generalInput,
string hydraulicBoundaryDatabaseFilePath)
{
var structuresOvertoppingCalculationInput = new StructuresOvertoppingCalculationInput(
calculation.InputParameters.HydraulicBoundaryLocation.Id,
calculation.InputParameters.StructureNormalOrientation,
HydraRingInputParser.ParseForeshore(calculation.InputParameters),
HydraRingInputParser.ParseBreakWater(calculation.InputParameters),
generalInput.GravitationalAcceleration,
generalInput.ModelFactorOvertoppingFlow.Mean, generalInput.ModelFactorOvertoppingFlow.StandardDeviation,
calculation.InputParameters.LevelCrestStructure.Mean, calculation.InputParameters.LevelCrestStructure.StandardDeviation,
calculation.InputParameters.StructureNormalOrientation,
calculation.InputParameters.ModelFactorSuperCriticalFlow.Mean, calculation.InputParameters.ModelFactorSuperCriticalFlow.StandardDeviation,
calculation.InputParameters.AllowedLevelIncreaseStorage.Mean, calculation.InputParameters.AllowedLevelIncreaseStorage.StandardDeviation,
generalInput.ModelFactorStorageVolume.Mean, generalInput.ModelFactorStorageVolume.StandardDeviation,
calculation.InputParameters.StorageStructureArea.Mean, calculation.InputParameters.StorageStructureArea.CoefficientOfVariation,
generalInput.ModelFactorInflowVolume,
calculation.InputParameters.FlowWidthAtBottomProtection.Mean, calculation.InputParameters.FlowWidthAtBottomProtection.StandardDeviation,
calculation.InputParameters.CriticalOvertoppingDischarge.Mean, calculation.InputParameters.CriticalOvertoppingDischarge.CoefficientOfVariation,
calculation.InputParameters.FailureProbabilityStructureWithErosion,
calculation.InputParameters.WidthFlowApertures.Mean, calculation.InputParameters.WidthFlowApertures.StandardDeviation,
calculation.InputParameters.DeviationWaveDirection,
calculation.InputParameters.StormDuration.Mean, calculation.InputParameters.StormDuration.CoefficientOfVariation);
HydraRingSettingsDatabaseHelper.AssignSettingsFromDatabase(structuresOvertoppingCalculationInput, hydraulicBoundaryDatabaseFilePath);
return structuresOvertoppingCalculationInput;
}
}
}