public void Read_EntityWithOutput_ReturnsCalculationScenarioWithOutput()
        {
            // Setup
            var random       = new Random(31);
            var tangentLines = new RoundedDouble[0];
            var slices       = new MacroStabilityInwardsSlice[0];

            var calculationOutputEntity = new MacroStabilityInwardsCalculationOutputEntity
            {
                SlipPlaneTangentLinesXml = new TangentLineCollectionXmlSerializer().ToXml(tangentLines),
                SlidingCurveSliceXML     = new MacroStabilityInwardsSliceCollectionXmlSerializer().ToXml(slices),
                SlipPlaneLeftGridNrOfHorizontalPoints  = random.Next(1, 100),
                SlipPlaneLeftGridNrOfVerticalPoints    = random.Next(1, 100),
                SlipPlaneRightGridNrOfHorizontalPoints = random.Next(1, 100),
                SlipPlaneRightGridNrOfVerticalPoints   = random.Next(1, 100)
            };

            MacroStabilityInwardsCalculationEntity entity = CreateValidCalculationEntity();

            entity.MacroStabilityInwardsCalculationOutputEntities.Add(calculationOutputEntity);

            var collector = new ReadConversionCollector();

            // Call
            MacroStabilityInwardsCalculationScenario calculation = entity.Read(collector);

            // Assert
            MacroStabilityInwardsOutput output = calculation.Output;

            Assert.IsNotNull(output);
            MacroStabilityInwardsCalculationOutputEntityTestHelper.AssertOutputPropertyValues(output, calculationOutputEntity);
        }
Beispiel #2
0
        /// <summary>
        /// Creates a new instance of <see cref="MacroStabilityInwardsWaterStressesProperties"/>.
        /// </summary>
        /// <param name="data">The data of the properties.</param>
        /// <param name="generalInput">General calculation parameters that are the same across all calculations.</param>
        /// <param name="assessmentLevel">The assessment level at stake.</param>
        /// <param name="propertyChangeHandler">The handler responsible for handling effects of a property change.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="data"/>, <paramref name="generalInput"/>
        /// or <paramref name="propertyChangeHandler"/> is <c>null</c>.</exception>
        public MacroStabilityInwardsWaterStressesProperties(MacroStabilityInwardsInput data,
                                                            GeneralMacroStabilityInwardsInput generalInput,
                                                            RoundedDouble assessmentLevel,
                                                            IObservablePropertyChangeHandler propertyChangeHandler)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            if (generalInput == null)
            {
                throw new ArgumentNullException(nameof(generalInput));
            }

            if (propertyChangeHandler == null)
            {
                throw new ArgumentNullException(nameof(propertyChangeHandler));
            }

            this.data                  = data;
            this.generalInput          = generalInput;
            this.assessmentLevel       = assessmentLevel;
            this.propertyChangeHandler = propertyChangeHandler;
        }
        public void CreateInstance_WithContextThatHasInputWithSpecificWaterLevelType_ExpectedProperties(
            IAssessmentSection assessmentSection,
            Action <WaveConditionsInput> configureInputAction,
            RoundedDouble expectedAssessmentLevel)
        {
            // Setup
            var calculation = new GrassCoverErosionOutwardsWaveConditionsCalculation();

            configureInputAction(calculation.InputParameters);

            var context = new GrassCoverErosionOutwardsWaveConditionsInputContext(calculation.InputParameters,
                                                                                  calculation,
                                                                                  assessmentSection,
                                                                                  Enumerable.Empty <ForeshoreProfile>());

            using (var plugin = new GrassCoverErosionOutwardsPlugin())
            {
                PropertyInfo info = GetInfo(plugin);

                // Call
                IObjectProperties objectProperties = info.CreateInstance(context);

                // Assert
                Assert.IsInstanceOf <GrassCoverErosionOutwardsWaveConditionsInputContextProperties>(objectProperties);
                Assert.AreSame(context, objectProperties.Data);

                Assert.AreEqual(expectedAssessmentLevel, ((GrassCoverErosionOutwardsWaveConditionsInputContextProperties)objectProperties).AssessmentLevel);
            }
        }
        public void CreateCalculationActivitiesForCalculationGroup_WithValidCalculations_ReturnsStabilityStoneCoverWaveConditionsCalculationActivitiesWithParametersSet()
        {
            // Setup
            StabilityStoneCoverFailureMechanism failureMechanism = new StabilityStoneCoverFailureMechanism();
            AssessmentSectionStub assessmentSection = CreateAssessmentSection();

            var hydraulicBoundaryLocation = new TestHydraulicBoundaryLocation();

            SetHydraulicBoundaryLocationToAssessmentSection(assessmentSection, hydraulicBoundaryLocation);
            StabilityStoneCoverWaveConditionsCalculation calculation1 = CreateValidCalculation(hydraulicBoundaryLocation);
            StabilityStoneCoverWaveConditionsCalculation calculation2 = CreateValidCalculation(hydraulicBoundaryLocation);

            var calculations = new CalculationGroup
            {
                Children =
                {
                    calculation1,
                    calculation2
                }
            };

            // Call
            IEnumerable <CalculatableActivity> activities = StabilityStoneCoverWaveConditionsCalculationActivityFactory.CreateCalculationActivities(
                calculations, failureMechanism, assessmentSection);

            // Assert
            CollectionAssert.AllItemsAreInstancesOfType(activities, typeof(StabilityStoneCoverWaveConditionsCalculationActivity));
            Assert.AreEqual(2, activities.Count());

            RoundedDouble             assessmentLevel           = assessmentSection.WaterLevelCalculationsForSignalFloodingProbability.Single().Output.Result;
            HydraulicBoundaryDatabase hydraulicBoundaryDatabase = assessmentSection.HydraulicBoundaryDatabase;

            AssertStabilityStoneCoverWaveConditionsCalculationActivity(activities.First(), calculation1, assessmentLevel, hydraulicBoundaryDatabase);
            AssertStabilityStoneCoverWaveConditionsCalculationActivity(activities.ElementAt(1), calculation2, assessmentLevel, hydraulicBoundaryDatabase);
        }
        /// <summary>
        /// Creates a new instance of <see cref="IllustrationPointControlItem"/>.
        /// </summary>
        /// <param name="source">The wrapped source <see cref="TopLevelIllustrationPointBase"/>.</param>
        /// <param name="windDirectionName">The name of the wind direction.</param>
        /// <param name="closingSituation">The closing situation of the illustration
        ///     point.</param>
        /// <param name="stochasts">The associated stochasts.</param>
        /// <param name="beta">The beta of the illustration point.</param>
        /// <exception cref="ArgumentNullException">Thrown when parameter
        /// <paramref name="source"/>, <paramref name="windDirectionName"/>,
        /// <paramref name="closingSituation"/> or <paramref name="stochasts"/> is
        /// <c>null</c>.</exception>
        public IllustrationPointControlItem(TopLevelIllustrationPointBase source,
                                            string windDirectionName,
                                            string closingSituation,
                                            IEnumerable <Stochast> stochasts,
                                            RoundedDouble beta)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            if (windDirectionName == null)
            {
                throw new ArgumentNullException(nameof(windDirectionName));
            }

            if (closingSituation == null)
            {
                throw new ArgumentNullException(nameof(closingSituation));
            }

            if (stochasts == null)
            {
                throw new ArgumentNullException(nameof(stochasts));
            }

            Source            = source;
            WindDirectionName = windDirectionName;
            ClosingSituation  = closingSituation;
            Beta      = beta;
            Stochasts = stochasts;
        }
Beispiel #6
0
        public void CreateInstance_WithContextThatHasInputWithSpecificWaterLevelType_ReturnViewWithCorrespondingAssessmentLevel(
            IAssessmentSection assessmentSection,
            Action <WaveConditionsInput> configureInputAction,
            RoundedDouble expectedAssessmentLevel)
        {
            // Setup
            var calculation = new WaveImpactAsphaltCoverWaveConditionsCalculation();

            configureInputAction(calculation.InputParameters);

            var context = new WaveImpactAsphaltCoverWaveConditionsInputContext(
                calculation.InputParameters,
                calculation,
                assessmentSection,
                Array.Empty <ForeshoreProfile>());

            // Call
            var view = (WaveConditionsInputView)info.CreateInstance(context);

            // Assert
            ChartDataCollection chartData = view.Chart.Data;
            var designWaterLevelChartData = (ChartLineData)chartData.Collection.ElementAt(designWaterLevelChartDataIndex);

            if (expectedAssessmentLevel != RoundedDouble.NaN)
            {
                Assert.AreEqual(expectedAssessmentLevel, designWaterLevelChartData.Points.First().Y);
            }
            else
            {
                Assert.IsEmpty(designWaterLevelChartData.Points);
            }
        }
        public void SetProperties_IndividualProperties_UpdateDataAndNotifyObservers()
        {
            // Setup
            const int numberOfChangedProperties = 2;

            var mockRepository = new MockRepository();
            var observer       = mockRepository.StrictMock <IObserver>();

            observer.Expect(o => o.UpdateObserver()).Repeat.Times(numberOfChangedProperties);
            mockRepository.ReplayAll();

            var backgroundData = new BackgroundData(new TestBackgroundDataConfiguration());

            backgroundData.Attach(observer);

            var properties = new BackgroundDataProperties(backgroundData);

            var           random          = new Random(123);
            bool          newVisibility   = random.NextBoolean();
            RoundedDouble newTransparency = random.NextRoundedDouble();

            // Call
            properties.IsVisible    = newVisibility;
            properties.Transparency = newTransparency;

            // Assert
            Assert.AreEqual(newTransparency, properties.Transparency, properties.Transparency.GetAccuracy());
            Assert.AreEqual(newVisibility, properties.IsVisible);

            mockRepository.VerifyAll();
        }
        private static string[] ValidateInput(HydraulicBoundaryDatabase hydraulicBoundaryDatabase,
                                              WaveConditionsInput input,
                                              RoundedDouble assessmentLevel)
        {
            var validationResults = new List <string>();

            string databaseFilePathValidationProblem = HydraulicBoundaryDatabaseConnectionValidator.Validate(hydraulicBoundaryDatabase);

            if (!string.IsNullOrEmpty(databaseFilePathValidationProblem))
            {
                validationResults.Add(databaseFilePathValidationProblem);
            }

            string preprocessorDirectoryValidationProblem = HydraulicBoundaryDatabaseHelper.ValidatePreprocessorDirectory(hydraulicBoundaryDatabase.EffectivePreprocessorDirectory());

            if (!string.IsNullOrEmpty(preprocessorDirectoryValidationProblem))
            {
                validationResults.Add(preprocessorDirectoryValidationProblem);
            }

            if (validationResults.Any())
            {
                return(validationResults.ToArray());
            }

            validationResults.AddRange(ValidateWaveConditionsInput(input, assessmentLevel));

            return(validationResults.ToArray());
        }
        /// <summary>
        /// Creates the input for a calculation for the given <paramref name="waterLevel"/>.
        /// </summary>
        /// <param name="waterLevel">The level of the water.</param>
        /// <param name="a">The 'a' factor decided on failure mechanism level.</param>
        /// <param name="b">The 'b' factor decided on failure mechanism level.</param>
        /// <param name="c">The 'c' factor decided on failure mechanism level.</param>
        /// <param name="targetProbability">The target probability to use.</param>
        /// <param name="input">The input that is different per calculation.</param>
        /// <param name="calculationSettings">The <see cref="HydraulicBoundaryCalculationSettings"/> containing all data
        /// to perform a hydraulic boundary calculation.</param>
        /// <returns>A <see cref="WaveConditionsCalculationInput"/>.</returns>
        /// <exception cref="ArgumentException">Thrown when the hydraulic boundary database file path.
        /// contains invalid characters.</exception>
        /// <exception cref="CriticalFileReadException">Thrown when:
        /// <list type="bullet">
        /// <item>No settings database file could be found at the location of the hydraulic boundary database file path
        /// with the same name.</item>
        /// <item>Unable to open settings database file.</item>
        /// <item>Unable to read required data from database file.</item>
        /// </list>
        /// </exception>
        private static WaveConditionsCosineCalculationInput CreateInput(RoundedDouble waterLevel,
                                                                        RoundedDouble a,
                                                                        RoundedDouble b,
                                                                        RoundedDouble c,
                                                                        double targetProbability,
                                                                        WaveConditionsInput input,
                                                                        HydraulicBoundaryCalculationSettings calculationSettings)
        {
            var waveConditionsCosineCalculationInput = new WaveConditionsCosineCalculationInput(
                1,
                input.Orientation,
                input.HydraulicBoundaryLocation.Id,
                targetProbability,
                HydraRingInputParser.ParseForeshore(input),
                HydraRingInputParser.ParseBreakWater(input),
                waterLevel,
                a,
                b,
                c);

            HydraRingSettingsDatabaseHelper.AssignSettingsFromDatabase(waveConditionsCosineCalculationInput,
                                                                       calculationSettings.HydraulicBoundaryDatabaseFilePath,
                                                                       !string.IsNullOrEmpty(calculationSettings.PreprocessorDirectory));

            return(waveConditionsCosineCalculationInput);
        }
Beispiel #10
0
 /// <summary>
 /// Validates whether the <paramref name="value"/> is valid.
 /// </summary>
 /// <param name="value">The value to validate.</param>
 /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="value"/> is not
 /// between [0, 1].</exception>
 public static void ValidateScenarioContribution(RoundedDouble value)
 {
     if (!contributionValidityRange.InRange(value))
     {
         throw new ArgumentOutOfRangeException(null, Resources.Contribution_must_be_in_range);
     }
 }
Beispiel #11
0
        public void Constructor_ExpectedValues()
        {
            // Setup
            const string  name         = "Test";
            var           random       = new Random(21);
            bool          isRelevant   = random.NextBoolean();
            RoundedDouble contribution = random.NextRoundedDouble();

            var mocks = new MockRepository();
            var calculationScenario = mocks.Stub <ICalculationScenario>();

            mocks.ReplayAll();

            calculationScenario.Name         = name;
            calculationScenario.IsRelevant   = isRelevant;
            calculationScenario.Contribution = contribution;

            // Call
            var row = new TestScenarioRow <ICalculationScenario>(calculationScenario);

            // Assert
            Assert.AreSame(calculationScenario, row.CalculationScenario);
            Assert.AreEqual(name, row.Name);
            Assert.AreEqual(isRelevant, row.IsRelevant);
            Assert.AreEqual(2, row.Contribution.NumberOfDecimalPlaces);
            Assert.AreEqual(contribution * 100, row.Contribution, row.Contribution.GetAccuracy());
            TestHelper.AssertTypeConverter <ScenarioRow <ICalculationScenario>, NoProbabilityValueDoubleConverter>(
                nameof(ScenarioRow <ICalculationScenario> .FailureProbability));

            mocks.VerifyAll();
        }
Beispiel #12
0
 public SimpleVariationCoefficientDesignVariableProperties(
     IVariationCoefficientDistribution variationCoefficientLogNormalDistribution,
     RoundedDouble designValue)
     : base(variationCoefficientLogNormalDistribution)
 {
     this.designValue = designValue;
 }
        public void GetDesignValue_ValidLogNormalDistributionWithNonZeroShift_ReturnExpectedValue(
            double expectedValue, double variance, double shift, double percentile,
            double expectedResult)
        {
            // Setup
            const int numberOfDecimalPlaces = 4;
            var       logNormalDistribution = new VariationCoefficientLogNormalDistribution(numberOfDecimalPlaces)
            {
                Mean = (RoundedDouble)expectedValue,
                CoefficientOfVariation = (RoundedDouble)Math.Sqrt(variance),
                Shift = (RoundedDouble)shift
            };

            var designVariable = new VariationCoefficientLogNormalDistributionDesignVariable(logNormalDistribution)
            {
                Percentile = percentile
            };

            // Call
            RoundedDouble result = designVariable.GetDesignValue();

            // Assert
            Assert.AreEqual(numberOfDecimalPlaces, result.NumberOfDecimalPlaces);
            Assert.AreEqual(expectedResult, result, result.GetAccuracy());
        }
Beispiel #14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GeneralGrassCoverErosionInwardsInput"/> class.
 /// </summary>
 public GeneralGrassCoverErosionInwardsInput()
 {
     n = new RoundedDouble(numberOfDecimalPlacesN, 2.0);
     CriticalOvertoppingModelFactor = 1.0;
     FbFactor = new TruncatedNormalDistribution(2)
     {
         Mean = (RoundedDouble)4.75,
         StandardDeviation = (RoundedDouble)0.5,
         LowerBoundary     = (RoundedDouble)0.0,
         UpperBoundary     = (RoundedDouble)99.0
     };
     FnFactor = new TruncatedNormalDistribution(2)
     {
         Mean = (RoundedDouble)2.6,
         StandardDeviation = (RoundedDouble)0.35,
         LowerBoundary     = (RoundedDouble)0.0,
         UpperBoundary     = (RoundedDouble)99.0
     };
     OvertoppingModelFactor = 1.0;
     FrunupModelFactor      = new TruncatedNormalDistribution(2)
     {
         Mean = (RoundedDouble)1,
         StandardDeviation = (RoundedDouble)0.07,
         LowerBoundary     = (RoundedDouble)0.0,
         UpperBoundary     = (RoundedDouble)99.0
     };
     FshallowModelFactor = new TruncatedNormalDistribution(2)
     {
         Mean = (RoundedDouble)0.92,
         StandardDeviation = (RoundedDouble)0.24,
         LowerBoundary     = (RoundedDouble)0.0,
         UpperBoundary     = (RoundedDouble)99.0
     };
 }
Beispiel #15
0
        /// <summary>
        /// Makes a deep clone of the foreshore profile and modifies all the properties,
        /// except the <see cref="ForeshoreProfile.Id"/>.
        /// </summary>
        /// <param name="foreshoreProfile">The foreshore profile to deep clone.</param>
        /// <returns>A deep clone of the <paramref name="foreshoreProfile"/>.</returns>
        private static ForeshoreProfile DeepCloneAndModify(ForeshoreProfile foreshoreProfile)
        {
            var random = new Random(21);

            Point2D originalWorldCoordinate = foreshoreProfile.WorldReferencePoint;
            var     modifiedWorldCoordinate = new Point2D(originalWorldCoordinate.X + random.NextDouble(),
                                                          originalWorldCoordinate.Y + random.NextDouble());

            List <Point2D> modifiedForeshoreGeometry = foreshoreProfile.Geometry.ToList();

            modifiedForeshoreGeometry.Add(new Point2D(1, 2));

            RoundedDouble originalBreakWaterHeight = foreshoreProfile.BreakWater?.Height ?? (RoundedDouble)0.0;
            var           modifiedBreakWater       = new BreakWater(random.NextEnumValue <BreakWaterType>(),
                                                                    originalBreakWaterHeight + random.NextDouble());

            string modifiedName        = $"new_name_{foreshoreProfile.Name}";
            double modifiedOrientation = foreshoreProfile.Orientation + random.NextDouble();
            double modifiedX0          = foreshoreProfile.X0 + random.NextDouble();

            return(new ForeshoreProfile(modifiedWorldCoordinate, modifiedForeshoreGeometry,
                                        modifiedBreakWater,
                                        new ForeshoreProfile.ConstructionProperties
            {
                Name = modifiedName,
                Id = foreshoreProfile.Id,
                Orientation = modifiedOrientation,
                X0 = modifiedX0
            }));
        }
        private static IEnumerable <string> ValidateWaveConditionsInput(WaveConditionsInput input,
                                                                        RoundedDouble assessmentLevel)
        {
            var messages = new List <string>();

            if (input.HydraulicBoundaryLocation == null)
            {
                messages.Add(RiskeerCommonServiceResources.CalculationService_ValidateInput_No_hydraulic_boundary_location_selected);
            }
            else if (double.IsNaN(assessmentLevel))
            {
                messages.Add(Resources.WaveConditionsCalculationService_ValidateInput_No_AssessmentLevel_calculated);
            }
            else
            {
                if (!input.GetWaterLevels(assessmentLevel).Any())
                {
                    messages.Add(Resources.WaveConditionsCalculationService_ValidateInput_No_derived_WaterLevels);
                }

                messages.AddRange(new UseBreakWaterRule(input).Validate());
                messages.AddRange(new NumericInputRule(input.Orientation, ParameterNameExtractor.GetFromDisplayName(RiskeerCommonFormsResources.Orientation_DisplayName)).Validate());
            }

            return(messages);
        }
        public void GivenPropertiesWithData_WhenChangingProperties_ThenPropertiesSetOnInput()
        {
            // Given
            var calculation = new MacroStabilityInwardsCalculationScenario();
            MacroStabilityInwardsInput input = calculation.InputParameters;

            var handler    = new ObservablePropertyChangeHandler(calculation, input);
            var properties = new MacroStabilityInwardsSlipPlaneSettingsProperties(input, handler);

            var           random            = new Random(21);
            bool          createZones       = random.NextBoolean();
            var           determinationType = random.NextEnumValue <MacroStabilityInwardsZoningBoundariesDeterminationType>();
            RoundedDouble boundaryLeft      = random.NextRoundedDouble();
            RoundedDouble boundaryRight     = random.NextRoundedDouble();

            // When
            properties.CreateZones = createZones;
            properties.ZoningBoundariesDeterminationType = determinationType;
            properties.ZoneBoundaryLeft  = boundaryLeft;
            properties.ZoneBoundaryRight = boundaryRight;

            // Then
            Assert.AreEqual(createZones, input.CreateZones);
            Assert.AreEqual(determinationType, input.ZoningBoundariesDeterminationType);
            Assert.AreEqual(boundaryLeft, input.ZoneBoundaryLeft, input.ZoneBoundaryLeft.GetAccuracy());
            Assert.AreEqual(boundaryRight, input.ZoneBoundaryRight, input.ZoneBoundaryRight.GetAccuracy());
        }
        /// <summary>
        /// Performs validation over the given input parameters. Error and status information is logged
        /// during the execution of the operation.
        /// </summary>
        /// <param name="waveConditionsInput">The input of the calculation.</param>
        /// <param name="assessmentLevel">The assessment level to use for determining water levels.</param>
        /// <param name="hydraulicBoundaryDatabase">The hydraulic boundary database to validate.</param>
        /// <returns><c>true</c> if there were no validation errors; <c>false</c> otherwise.</returns>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="waveConditionsInput"/> or
        /// <paramref name="hydraulicBoundaryDatabase"/> is <c>null</c>.</exception>
        public static bool Validate(WaveConditionsInput waveConditionsInput,
                                    RoundedDouble assessmentLevel,
                                    HydraulicBoundaryDatabase hydraulicBoundaryDatabase)
        {
            if (waveConditionsInput == null)
            {
                throw new ArgumentNullException(nameof(waveConditionsInput));
            }

            if (hydraulicBoundaryDatabase == null)
            {
                throw new ArgumentNullException(nameof(hydraulicBoundaryDatabase));
            }

            CalculationServiceHelper.LogValidationBegin();

            string[] messages = ValidateInput(hydraulicBoundaryDatabase,
                                              waveConditionsInput,
                                              assessmentLevel);

            CalculationServiceHelper.LogMessagesAsError(messages);

            CalculationServiceHelper.LogValidationEnd();

            return(!messages.Any());
        }
        public void Cancel_WhenPerformingCalculation_CurrentCalculationForWaterLevelCompletesAndSubsequentCalculationsDidNotRun()
        {
            // Setup
            AssessmentSectionStub assessmentSection = CreateAssessmentSection();

            ConfigureAssessmentSectionWithHydraulicBoundaryOutput(assessmentSection);

            GrassCoverErosionOutwardsWaveConditionsCalculation calculation = CreateValidCalculation(assessmentSection.HydraulicBoundaryDatabase.Locations.First());

            var failureMechanism          = new GrassCoverErosionOutwardsFailureMechanism();
            CalculatableActivity activity = GrassCoverErosionOutwardsCalculationActivityFactory.CreateWaveConditionsCalculationActivity(calculation,
                                                                                                                                        failureMechanism,
                                                                                                                                        assessmentSection);

            var mockRepository    = new MockRepository();
            var calculatorFactory = mockRepository.StrictMock <IHydraRingCalculatorFactory>();

            calculatorFactory.Expect(cf => cf.CreateWaveConditionsCosineCalculator(null))
            .IgnoreArguments()
            .Return(new TestWaveConditionsCosineCalculator());
            mockRepository.ReplayAll();

            using (new HydraRingCalculatorFactoryConfig(calculatorFactory))
            {
                activity.ProgressChanged += (sender, args) =>
                {
                    if (activity.State != ActivityState.Canceled)
                    {
                        // Call
                        activity.Cancel();
                    }
                };

                // Assert
                TestHelper.AssertLogMessages(() => activity.Run(), messages =>
                {
                    string[] msgs = messages.ToArray();
                    RoundedDouble firstWaterLevel = GetWaterLevels(calculation, assessmentSection).First();

                    Assert.AreEqual(10, msgs.Length);
                    Assert.AreEqual($"Golfcondities berekenen voor '{calculation.Name}' is gestart.", msgs[0]);
                    CalculationServiceTestHelper.AssertValidationStartMessage(msgs[1]);
                    CalculationServiceTestHelper.AssertValidationEndMessage(msgs[2]);
                    CalculationServiceTestHelper.AssertCalculationStartMessage(msgs[3]);

                    Assert.AreEqual("Berekening voor golfoploop is gestart.", msgs[4]);
                    Assert.AreEqual($"Berekening voor waterstand '{firstWaterLevel}' is gestart.", msgs[5]);
                    StringAssert.StartsWith("Golfcondities berekening is uitgevoerd op de tijdelijke locatie", msgs[6]);
                    Assert.AreEqual($"Berekening voor waterstand '{firstWaterLevel}' is beëindigd.", msgs[7]);
                    Assert.AreEqual("Berekening voor golfoploop is beëindigd.", msgs[8]);

                    CalculationServiceTestHelper.AssertCalculationEndMessage(msgs[9]);
                });

                Assert.AreEqual(ActivityState.Canceled, activity.State);
                Assert.IsNull(calculation.Output);
            }

            mockRepository.VerifyAll();
        }
Beispiel #20
0
        private static IEnumerable <RoundedDouble> GetInterPolatedVerticalPositions(RoundedDouble startPoint,
                                                                                    RoundedDouble endPoint,
                                                                                    int nrOfPoints)
        {
            if (nrOfPoints <= 1)
            {
                yield return(startPoint);

                yield break;
            }

            int           nrofInterPolatedPoints = nrOfPoints - 1;
            RoundedDouble deltaZ = endPoint - startPoint;
            RoundedDouble deltaZBetweenPoints = nrOfPoints < 2
                                                    ? (RoundedDouble)0.0
                                                    : (RoundedDouble)(deltaZ / nrofInterPolatedPoints);

            RoundedDouble z = startPoint;
            int           nrOfRepetitions = nrofInterPolatedPoints < 0
                                      ? 0
                                      : nrofInterPolatedPoints;

            for (var i = 0; i < nrOfRepetitions + 1; i++)
            {
                yield return(z);

                z += deltaZBetweenPoints;
            }
        }
        private static IEnumerable <Point2D[]> CreateExpectedSliceParameterAreas(IEnumerable <MacroStabilityInwardsSlice> slices,
                                                                                 Func <MacroStabilityInwardsSlice, RoundedDouble> getParameterFunc,
                                                                                 double scaleFactor)
        {
            var areas = new List <Point2D[]>();

            foreach (MacroStabilityInwardsSlice slice in slices)
            {
                RoundedDouble value  = getParameterFunc(slice);
                double        offset = value * scaleFactor;
                double        length = Math.Sqrt(Math.Pow(slice.BottomLeftPoint.X - slice.BottomRightPoint.X, 2) +
                                                 Math.Pow(slice.BottomLeftPoint.Y - slice.BottomRightPoint.Y, 2));

                areas.Add(new[]
                {
                    slice.BottomLeftPoint,
                    slice.BottomRightPoint,
                    new Point2D(slice.BottomRightPoint.X + offset * (slice.BottomRightPoint.Y - slice.BottomLeftPoint.Y) / length,
                                slice.BottomRightPoint.Y + offset * (slice.BottomLeftPoint.X - slice.BottomRightPoint.X) / length),
                    new Point2D(slice.BottomLeftPoint.X + offset * (slice.BottomRightPoint.Y - slice.BottomLeftPoint.Y) / length,
                                slice.BottomLeftPoint.Y + offset * (slice.BottomLeftPoint.X - slice.BottomRightPoint.X) / length)
                });
            }

            return(areas);
        }
Beispiel #22
0
        private static IEnumerable <Point2D> GetInterPolatedHorizontalPoints(RoundedDouble startPoint,
                                                                             RoundedDouble endPoint,
                                                                             RoundedDouble zPoint,
                                                                             int nrOfPoints)
        {
            if (nrOfPoints <= 1)
            {
                yield return(new Point2D(startPoint, zPoint));

                yield break;
            }

            int           nrofInterPolatedPoints = nrOfPoints - 1;
            RoundedDouble deltaX = endPoint - startPoint;
            RoundedDouble deltaXBetweenPoints = nrOfPoints < 2
                                                    ? (RoundedDouble)0
                                                    : (RoundedDouble)(deltaX / nrofInterPolatedPoints);

            RoundedDouble x = startPoint;
            int           nrOfRepetitions = nrofInterPolatedPoints < 0
                                      ? 0
                                      : nrofInterPolatedPoints;

            for (var i = 0; i < nrOfRepetitions + 1; i++)
            {
                yield return(new Point2D(x, zPoint));

                x += deltaXBetweenPoints;
            }
        }
        public void CreateCalculationActivitiesForFailureMechanism_WithValidData_ExpectedInputSetToActivities()
        {
            // Setup
            AssessmentSectionStub assessmentSection = CreateAssessmentSection();
            StabilityStoneCoverFailureMechanism failureMechanism = new StabilityStoneCoverFailureMechanism();

            var hydraulicBoundaryLocation = new TestHydraulicBoundaryLocation("locationName 1");

            SetHydraulicBoundaryLocationToAssessmentSection(assessmentSection, hydraulicBoundaryLocation);

            StabilityStoneCoverWaveConditionsCalculation calculation1 = CreateValidCalculation(hydraulicBoundaryLocation);
            StabilityStoneCoverWaveConditionsCalculation calculation2 = CreateValidCalculation(hydraulicBoundaryLocation);

            failureMechanism.CalculationsGroup.Children.AddRange(new[]
            {
                calculation1,
                calculation2
            });

            // Call
            IEnumerable <CalculatableActivity> activities =
                StabilityStoneCoverWaveConditionsCalculationActivityFactory.CreateCalculationActivities(
                    failureMechanism,
                    assessmentSection);

            // Assert
            CollectionAssert.AllItemsAreInstancesOfType(activities, typeof(StabilityStoneCoverWaveConditionsCalculationActivity));
            Assert.AreEqual(2, activities.Count());
            RoundedDouble             assessmentLevel           = assessmentSection.WaterLevelCalculationsForSignalFloodingProbability.Single().Output.Result;
            HydraulicBoundaryDatabase hydraulicBoundaryDatabase = assessmentSection.HydraulicBoundaryDatabase;

            AssertStabilityStoneCoverWaveConditionsCalculationActivity(activities.ElementAt(0), calculation1, assessmentLevel, hydraulicBoundaryDatabase);
            AssertStabilityStoneCoverWaveConditionsCalculationActivity(activities.ElementAt(1), calculation2, assessmentLevel, hydraulicBoundaryDatabase);
        }
        public void GivenPropertiesWithData_WhenChangingProperties_ThenPropertiesSetOnGrid()
        {
            // Given
            var calculation = new MacroStabilityInwardsCalculationScenario();
            MacroStabilityInwardsInput input = calculation.InputParameters;
            MacroStabilityInwardsGrid  grid  = input.LeftGrid;

            var handler    = new ObservablePropertyChangeHandler(calculation, input);
            var properties = new MacroStabilityInwardsGridProperties(grid, handler, false);

            var           random  = new Random(21);
            RoundedDouble xLeft   = random.NextRoundedDouble();
            var           xRight  = (RoundedDouble)(1 + random.NextDouble());
            var           zTop    = (RoundedDouble)(1 + random.NextDouble());
            RoundedDouble zBottom = random.NextRoundedDouble();
            int           numberOfHorizontalPoints = random.Next(1, 100);
            int           numberOfVerticalPoints   = random.Next(1, 100);

            // When
            properties.XLeft   = xLeft;
            properties.XRight  = xRight;
            properties.ZTop    = zTop;
            properties.ZBottom = zBottom;
            properties.NumberOfHorizontalPoints = numberOfHorizontalPoints;
            properties.NumberOfVerticalPoints   = numberOfVerticalPoints;

            // Then
            Assert.AreEqual(xLeft, grid.XLeft, grid.XLeft.GetAccuracy());
            Assert.AreEqual(xRight, grid.XRight, grid.XRight.GetAccuracy());
            Assert.AreEqual(zTop, grid.ZTop, grid.ZTop.GetAccuracy());
            Assert.AreEqual(zBottom, grid.ZBottom, grid.ZBottom.GetAccuracy());
            Assert.AreEqual(numberOfHorizontalPoints, grid.NumberOfHorizontalPoints);
            Assert.AreEqual(numberOfVerticalPoints, grid.NumberOfVerticalPoints);
        }
Beispiel #25
0
        public void CreateAssessmentLevelGeometryPoints_WithForeshoreProfile_ReturnsAssessmentLevelGeometryPointsCollection(
            IEnumerable <Point2D> foreshoreProfileGeometry)
        {
            // Setup
            RoundedDouble assessmentLevel = GetValidAssessmentLevel();
            var           input           = new WaveConditionsInput
            {
                ForeshoreProfile = new TestForeshoreProfile(foreshoreProfileGeometry)
            };

            // Call
            IEnumerable <Point2D> points = WaveConditionsChartDataPointsFactory.CreateAssessmentLevelGeometryPoints(input, assessmentLevel);

            // Assert
            Point2D lastGeometryPoint = foreshoreProfileGeometry.Last();
            double  endPointX         = (assessmentLevel - lastGeometryPoint.Y) / 3;

            var expectedPoints = new[]
            {
                new Point2D(foreshoreProfileGeometry.First().X, 6),
                new Point2D(endPointX + lastGeometryPoint.X, 6)
            };

            CollectionAssert.AreEqual(expectedPoints, points);
        }
Beispiel #26
0
        public void Constructor_ExpectedValues()
        {
            // Setup
            var random = new Random(21);

            long          id            = random.Next();
            const string  name          = "DuneLocationName";
            var           location      = new Point2D(random.NextDouble(), random.NextDouble());
            int           coastalAreaId = random.Next();
            RoundedDouble offset        = random.NextRoundedDouble();
            RoundedDouble d50           = random.NextRoundedDouble();
            var           waterLevelCalculationsForTargetProbabilities = new List <Tuple <double, RoundedDouble> >();
            var           waveHeightCalculationsForTargetProbabilities = new List <Tuple <double, RoundedDouble> >();
            var           wavePeriodCalculationsForTargetProbabilities = new List <Tuple <double, RoundedDouble> >();

            // Call
            var aggregatedDuneLocation = new AggregatedDuneLocation(id, name, location, coastalAreaId, offset, d50,
                                                                    waterLevelCalculationsForTargetProbabilities,
                                                                    waveHeightCalculationsForTargetProbabilities,
                                                                    wavePeriodCalculationsForTargetProbabilities);

            // Assert
            Assert.AreEqual(id, aggregatedDuneLocation.Id);
            Assert.AreEqual(name, aggregatedDuneLocation.Name);
            Assert.AreSame(location, aggregatedDuneLocation.Location);
            Assert.AreEqual(coastalAreaId, aggregatedDuneLocation.CoastalAreaId);
            Assert.AreEqual(offset, aggregatedDuneLocation.Offset);
            Assert.AreEqual(d50, aggregatedDuneLocation.D50);
            Assert.AreSame(waterLevelCalculationsForTargetProbabilities, aggregatedDuneLocation.WaterLevelCalculationsForTargetProbabilities);
            Assert.AreSame(waveHeightCalculationsForTargetProbabilities, aggregatedDuneLocation.WaveHeightCalculationsForTargetProbabilities);
            Assert.AreSame(wavePeriodCalculationsForTargetProbabilities, aggregatedDuneLocation.WavePeriodCalculationsForTargetProbabilities);
        }
        public void AreaFlowApertures_Always_ExpectedValues()
        {
            // Setup
            var           random            = new Random(22);
            var           input             = new ClosingStructuresInput();
            RoundedDouble mean              = random.NextRoundedDouble(0.01, 1.0);
            RoundedDouble standardDeviation = random.NextRoundedDouble(0.01, 1.0);
            var           distributionToSet = new LogNormalDistribution(5)
            {
                Mean = mean,
                StandardDeviation = standardDeviation
            };

            // Call
            input.AreaFlowApertures = distributionToSet;

            // Assert
            var expectedDistribution = new LogNormalDistribution(2)
            {
                Mean = mean,
                StandardDeviation = standardDeviation
            };

            DistributionTestHelper.AssertDistributionCorrectlySet(input.AreaFlowApertures, distributionToSet, expectedDistribution);
        }
Beispiel #28
0
 private static void ValidateEntryExitPoint(RoundedDouble entryPointLocalXCoordinate, RoundedDouble exitPointLocalXCoordinate)
 {
     if (entryPointLocalXCoordinate >= exitPointLocalXCoordinate)
     {
         throw new ArgumentOutOfRangeException(null, Resources.PipingInput_EntryPointL_greater_or_equal_to_ExitPointL);
     }
 }
Beispiel #29
0
        private static IEnumerable <string> ValidateZoneBoundaries(MacroStabilityInwardsInput inputParameters)
        {
            if (!inputParameters.CreateZones ||
                inputParameters.ZoningBoundariesDeterminationType == MacroStabilityInwardsZoningBoundariesDeterminationType.Automatic)
            {
                yield break;
            }

            RoundedDouble zoneBoundaryLeft  = inputParameters.ZoneBoundaryLeft;
            RoundedDouble zoneBoundaryRight = inputParameters.ZoneBoundaryRight;

            if (zoneBoundaryLeft > zoneBoundaryRight)
            {
                yield return(Resources.MacroStabilityInwardsInputValidator_ValidateZoneBoundaries_ZoneBoundaries_BoundaryLeft_should_be_smaller_than_or_equal_to_BoundaryRight);
            }

            MacroStabilityInwardsSurfaceLine surfaceLine = inputParameters.SurfaceLine;

            if (!surfaceLine.ValidateInRange(zoneBoundaryLeft) || !surfaceLine.ValidateInRange(zoneBoundaryRight))
            {
                var validityRange = new Range <double>(surfaceLine.LocalGeometry.First().X, surfaceLine.LocalGeometry.Last().X);
                yield return(string.Format(Resources.MacroStabilityInwardsInputValidator_ValidateZoneBoundaries_ZoneBoundaries_must_be_in_Range_0,
                                           validityRange.ToString(FormattableConstants.ShowAtLeastOneDecimal, CultureInfo.CurrentCulture)));
            }
        }
Beispiel #30
0
        /// <summary>
        /// Gets the height of the projected <see cref="MechanismSurfaceLineBase"/> at a L=<paramref name="l"/>.
        /// </summary>
        /// <param name="l">The L coordinate from where to take the height of the <see cref="MechanismSurfaceLineBase"/>.</param>
        /// <returns>The height of the <see cref="MechanismSurfaceLineBase"/> at L=<paramref name="l"/>.</returns>
        /// <exception cref="MechanismSurfaceLineException">Thrown when the <see cref="MechanismSurfaceLineBase"/>
        /// intersection point at <paramref name="l"/> have a significant difference in their y coordinate.</exception>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="l"/> is not in range of the LZ-projected <see cref="Points"/>.</exception>
        /// <exception cref="InvalidOperationException">Thrown when <see cref="Points"/> is empty.</exception>
        public double GetZAtL(RoundedDouble l)
        {
            ValidateHasPoints();

            if (!ValidateInRange(l))
            {
                var    localRangeL       = new Range <double>(LocalGeometry.First().X, LocalGeometry.Last().X);
                string outOfRangeMessage = string.Format(Resources.MechanismSurfaceLineBase_0_L_needs_to_be_in_Range_1_,
                                                         Resources.MechanismSurfaceLineBase_GetZAtL_Cannot_determine_height,
                                                         localRangeL.ToString(FormattableConstants.ShowAtLeastOneDecimal, CultureInfo.CurrentCulture));
                throw new ArgumentOutOfRangeException(null, outOfRangeMessage);
            }

            var segments = new Collection <Segment2D>();

            for (var i = 1; i < LocalGeometry.Count(); i++)
            {
                segments.Add(new Segment2D(LocalGeometry.ElementAt(i - 1), LocalGeometry.ElementAt(i)));
            }

            IEnumerable <Point2D> intersectionPoints = Math2D.SegmentsIntersectionWithVerticalLine(segments, l).OrderBy(p => p.Y).ToArray();

            const double intersectionTolerance = 1e-2;
            bool         equalIntersections    = Math.Abs(intersectionPoints.First().Y - intersectionPoints.Last().Y) < intersectionTolerance;

            if (equalIntersections)
            {
                return(intersectionPoints.First().Y);
            }

            string message = string.Format(Resources.MechanismSurfaceLineBase_Cannot_determine_reliable_z_when_surface_line_is_vertical_in_l, l);

            throw new MechanismSurfaceLineException(message);
        }