예제 #1
0
def test_weibull_i_cdf(weibull_shape, weibull_loc, weibull_scale):
    x = np.linspace(0, 1)
    ref_cdf = sts.weibull_min.ppf(x, weibull_shape(None), weibull_loc(None),
                                  weibull_scale(None))
    dist = WeibullDistribution(weibull_shape, weibull_loc, weibull_scale)
    my_cdf = dist.i_cdf(x, x, (None, None, None))
    assert np.allclose(ref_cdf, my_cdf)
예제 #2
0
def test_weibull_draw_sample(weibull_number, weibull_shape, weibull_loc,
                             weibull_scale):
    ref_points = weibull_number
    dist = WeibullDistribution(weibull_shape, weibull_loc, weibull_scale)
    my_points = dist.draw_sample(weibull_number)
    my_points = my_points.size
    assert ref_points == my_points
예제 #3
0
    def test_IForm3d(self):  # TODO what does this test do
        """
        Creating Contour example
        """

        #define dependency tuple
        dep1 = (None, None, None)
        dep2 = (0, None, 0)
        dep3 = (0, None, 0)

        #define parameters
        shape = ConstantParam(1.471)
        loc = ConstantParam(0.8888)
        scale = ConstantParam(2.776)
        par1 = (shape, loc, scale)

        mu = FunctionParam(0.1000, 1.489, 0.1901, "f1")
        sigma = FunctionParam(0.0400, 0.1748, -0.2243, "f2")

        #del shape, loc, scale

        #create distributions
        dist1 = WeibullDistribution(*par1)
        dist2 = LognormalDistribution(mu=mu, sigma=sigma)
        dist3 = LognormalDistribution(mu=mu, sigma=sigma)
        distributions = [dist1, dist2, dist3]
        dependencies = [dep1, dep2, dep3]

        mul_dist = MultivariateDistribution(distributions, dependencies)

        test_contour_IForm = IFormContour(mul_dist, 50, 3, 400)
예제 #4
0
    def test_IForm3d(self): # TODO what does this test do
        """
        3-dimensional IFORM contour.
        """

        # Define dependency tuple.
        dep1 = (None, None, None)
        dep2 = (0, None, 0)
        dep3 = (0, None, 0)

        # Define parameters.
        shape = ConstantParam(1.471)
        loc = ConstantParam(0.8888)
        scale = ConstantParam(2.776)
        par1 = (shape, loc, scale)

        mu = FunctionParam('power3', 0.1000, 1.489, 0.1901)
        sigma = FunctionParam('exp3', 0.0400, 0.1748, -0.2243)

        #del shape, loc, scale

        # Create distributions.
        dist1 = WeibullDistribution(*par1)
        dist2 = LognormalDistribution(mu=mu, sigma=sigma)
        dist3 = LognormalDistribution(mu=mu, sigma=sigma)
        distributions = [dist1, dist2, dist3]
        dependencies = [dep1, dep2, dep3]

        mul_dist = MultivariateDistribution(distributions, dependencies)

        test_contour_IForm = IFormContour(mul_dist, 50, 3, 400)
예제 #5
0
    def _setup(self,
               dep1=(None, None, None),
               dep2=(0, None, 0),
               par1=(ConstantParam(1.471), ConstantParam(0.8888),
                     ConstantParam(2.776)),
               par2=(FunctionParam('exp3', 0.0400, 0.1748, -0.2243), None,
                     FunctionParam('power3', 0.1, 1.489, 0.1901))
               ):
        """
        Creating contour.
        """
        # Define dependency tuple.
        self.dep1 = dep1
        self.dep2 = dep2

        # Define parameters.
        self.par1 = par1
        self.par2 = par2

        # Create distributions.
        dist1 = WeibullDistribution(*par1)
        dist2 = LognormalDistribution(sigma=par2[0], mu=par2[2])

        distributions = [dist1, dist2]
        dependencies = [dep1, dep2]

        mul_dist = MultivariateDistribution(distributions, dependencies)

        # Calculate contour
        dsc = DirectSamplingContour(mul_dist, 10000000, 25, 6, 6)
        test_contour_dsc = dsc.direct_sampling_contour()
        return test_contour_dsc
예제 #6
0
    def test_distribution_loc_None(self):
        """
        Tests if loc is set to default when it has value 'None'.
        """

        # Define parameters.
        shape = ConstantParam(0.8888)
        loc = None
        scale = ConstantParam(2.776)
        par1 = (shape, loc, scale)
        rv_values = [0.8, 1, 8]
        dependencies = (0, 1, 1)

        dist = WeibullDistribution(*par1)
        loc_test = dist._get_parameter_values(rv_values, dependencies)[1]
        self.assertEqual(loc_test, 0)
예제 #7
0
    def test_multivariate_draw_sample(self):
        """
            Create an example MultivariateDistribution (Vanem2012 model).
            """

        # Define dependency tuple.
        dep1 = (None, None, None)
        dep2 = (0, None, 0)

        # Define parameters.
        shape = ConstantParam(1.471)
        loc = ConstantParam(0.8888)
        scale = ConstantParam(2.776)
        par1 = (shape, loc, scale)

        shape = FunctionParam('exp3', 0.0400, 0.1748, -0.2243)
        loc = None
        scale = FunctionParam('power3', 0.1, 1.489, 0.1901)
        par2 = (shape, loc, scale)

        del shape, loc, scale

        # Create distributions.
        dist1 = WeibullDistribution(*par1)
        dist2 = LognormalDistribution(*par2)

        distributions = [dist1, dist2]
        dependencies = [dep1, dep2]
        ref_points = 99119
        mul_var_dist = MultivariateDistribution(distributions, dependencies)
        my_points = mul_var_dist.draw_sample(ref_points)
        my_points0 = my_points[0].size
        my_points1 = my_points[1].size
        assert ref_points == my_points0
        assert ref_points == my_points1
예제 #8
0
def test_weibull_param_out_of_bounds(weibull_param_name):
    dist = WeibullDistribution()
    setattr(dist, weibull_param_name, ConstantParam(-np.inf))
    with pytest.raises(ValueError):
        dist.cdf([0, 100], [0, 100], (None, None, None))

    dist = WeibullDistribution()
    setattr(dist, weibull_param_name, ConstantParam(np.inf))
    with pytest.raises(ValueError):
        dist.cdf([0, 100], [0, 100], (None, None, None))
def setup_mul_dist(probabilistic_model: ProbabilisticModel):
    """
    Generates a MultiVariateDistribution from a ProbabilisticModel.

    MultiVariateDistribution objects are used to perform the statistical
    computations in the viroconcom package. ProbabilisticModel objects are used
    in the viroconweb package to be saved in the data base.

    Parameters
    ----------
    probabilistic_model : ProbabilisticModel,
        The probabilistic model, which should be converted.

    Returns
    -------
    mutivar_distribution : MultivariateDistribution,
        The object, which can be used in the viroconcom package.

    """
    distributions_model = DistributionModel.objects.filter(
        probabilistic_model=probabilistic_model)
    distributions = []
    dependencies = []

    for dist in distributions_model:
        dependency = []
        parameters = []
        parameters_model = ParameterModel.objects.filter(distribution=dist)
        for param in parameters_model:
            dependency.append(adjust(param.dependency))

            if adjust(param.function) is not None:
                parameters.append(
                    FunctionParam(float(param.x0), float(param.x1),
                                  float(param.x2), param.function))
            else:
                parameters.append(ConstantParam(float(param.x0)))

        dependencies.append(dependency)

        if dist.distribution == 'Normal':
            distributions.append(NormalDistribution(*parameters))
        elif dist.distribution == 'Weibull':
            distributions.append(WeibullDistribution(*parameters))
        elif dist.distribution == 'Lognormal_SigmaMu':
            distributions.append(
                LognormalDistribution(sigma=parameters[0], mu=parameters[2]))
        elif dist.distribution == 'KernelDensity':
            distributions.append(KernelDensityDistribution(*parameters))
        else:
            raise KeyError('{} is not a matching distribution'.format(
                dist.distribution))

    mutivar_distribution = MultivariateDistribution(distributions,
                                                    dependencies)
    return mutivar_distribution
예제 #10
0
    def test_HDC3d_WLN(self):

        dep1 = (None, None, None)
        dep2 = (0, None, 0)
        dep3 = (None, 0, 0)

        #define parameters
        shape = ConstantParam(1.471)
        loc = ConstantParam(0.8888)
        scale = ConstantParam(2.776)
        par1 = (shape, loc, scale)

        shape = None
        loc = FunctionParam(4, 10, 0.02, "f1")
        scale = FunctionParam(0.1, 0.02, -0.1, "f2")
        par2 = (shape, loc, scale)

        mu = FunctionParam(0.1, 1.5, 0.2, "f1")
        sigma = FunctionParam(0.1, 0.2, -0.2, "f2")

        #create distributions
        dist1 = WeibullDistribution(*par1)
        dist2 = LognormalDistribution(mu=mu, sigma=sigma)
        dist3 = NormalDistribution(*par2)

        distributions = [dist1, dist2, dist3]
        dependencies = [dep1, dep2, dep3]

        mul_dist = MultivariateDistribution(distributions, dependencies)

        del mu, sigma
        #del dist1, dist2, par1, par2, dep1, dep2, dependencies, distributions
        #calc contour
        n_years = 50
        limits = [(0, 20), (0, 20), (0, 20)]
        deltas = [0.5, 0.5, 0.05]
        test_contour_HDC = HighestDensityContour(mul_dist, n_years, 3, limits,
                                                 deltas)

        finaldt3 = pd.DataFrame({
            'x': test_contour_HDC.coordinates[0][0],
            'y': test_contour_HDC.coordinates[0][1],
            'z': test_contour_HDC.coordinates[0][2]
        })

        matlab3 = pd.read_csv(testfiles_path + "/hdc3d_wln.csv",
                              names=['x', 'y', 'z'])

        result3 = pd.read_csv(testfiles_path + "/HDC3dWLN_coordinates.csv")
        for m, n in [(m, n) for m in result3.index for n in result3.columns]:
            self.assertAlmostEqual(result3.loc[m, n],
                                   finaldt3.loc[m, n],
                                   places=8)
예제 #11
0
    def test_draw_sample_distribution(self):
        """
            Create an example MultivariateDistribution (Vanem2012 model).
            """

        # Define dependency tuple.
        dep1 = (None, None, None)
        dep2 = (0, None, 0)

        # Define parameters.
        shape = ConstantParam(1.471)
        loc = ConstantParam(0.8888)
        scale = ConstantParam(2.776)
        par1 = (shape, loc, scale)

        shape = FunctionParam('exp3', 0.0400, 0.1748, -0.2243)
        loc = None
        scale = FunctionParam('power3', 0.1, 1.489, 0.1901)
        par2 = (shape, loc, scale)

        del shape, loc, scale

        # Create distributions.
        dist1 = WeibullDistribution(*par1)
        dist2 = LognormalDistribution(*par2)

        distributions = [dist1, dist2]
        dependencies = [dep1, dep2]
        points = 1000000
        mul_var_dist = MultivariateDistribution(distributions, dependencies)
        my_points = mul_var_dist.draw_sample(points)

        #Fit the sample
        # Describe the distribution that should be fitted to the sample.
        dist_description_0 = {
            'name': 'Weibull',
            'dependency': (None, None, None),
            'width_of_intervals': 2
        }
        dist_description_1 = {
            'name': 'Lognormal',
            'dependency': (0, None, 0),
            'functions': ('exp3', None, 'power3')
        }
        my_fit = Fit([my_points[0], my_points[1]],
                     [dist_description_0, dist_description_1])
        print(my_fit.mul_var_dist.distributions[0].shape(0))
        print(mul_var_dist.distributions[0].shape(0))
        assert np.round(my_fit.mul_var_dist.distributions[0].shape(0),
                        2) == np.round(mul_var_dist.distributions[0].shape(0),
                                       2)
예제 #12
0
    def test_HDC2d_WL(self):
        """
        2-d HDC with Weibull and Lognormal distribution.

        The used probabilistic model is described in Vanem and Bitner-Gregersen
        (2012), DOI: 10.1016/j.apor.2012.05.006
        """

        #define dependency tuple
        dep1 = (None, None, None)
        dep2 = (0, None, 0)

        #define parameters
        shape = ConstantParam(1.471)
        loc = ConstantParam(0.8888)
        scale = ConstantParam(2.776)
        par1 = (shape, loc, scale)

        mu = FunctionParam(0.1000, 1.489, 0.1901, 'power3')
        sigma = FunctionParam(0.0400, 0.1748, -0.2243, 'exp3')

        #del shape, loc, scale

        #create distributions
        dist1 = WeibullDistribution(*par1)
        dist2 = LognormalDistribution(mu=mu, sigma=sigma)

        distributions = [dist1, dist2]
        dependencies = [dep1, dep2]

        mul_dist = MultivariateDistribution(distributions, dependencies)

        #del dist1, dist2, par1, par2, dep1, dep2, dependencies, distributions
        #calc contour
        n_years = 50
        limits = [(0, 20), (0, 18)]
        deltas = [0.1, 0.1]
        test_contour_HDC = HighestDensityContour(mul_dist, n_years, 3, limits,
                                                 deltas)

        finaldt0 = pd.DataFrame({
            'x': test_contour_HDC.coordinates[0][0],
            'y': test_contour_HDC.coordinates[0][1]
        })

        result0 = pd.read_csv(testfiles_path + "/HDC2dWL_coordinates.csv")

        for g, h in [(g, h) for g in result0.index for h in result0.columns]:
            self.assertAlmostEqual(result0.loc[g, h],
                                   finaldt0.loc[g, h],
                                   places=8)
예제 #13
0
    def test_HDC3d_WLL(self):
        """
        Creating Contour example for 3-d HDC with Weibull, Lognormal and
        Lognormal distribution
        """

        dep1 = (None, None, None)
        dep2 = (0, None, 0)
        dep3 = (0, None, 0)

        #define parameters
        shape = ConstantParam(1.471)
        loc = ConstantParam(0.8888)
        scale = ConstantParam(2.776)
        par1 = (shape, loc, scale)

        mu = FunctionParam(0.1000, 1.489, 0.1901, "f1")
        sigma = FunctionParam(0.0400, 0.1748, -0.2243, "f2")

        #del shape, loc, scale

        #create distributions
        dist1 = WeibullDistribution(*par1)
        dist2 = LognormalDistribution(mu=mu, sigma=sigma)
        dist3 = LognormalDistribution(mu=mu, sigma=sigma)

        distributions = [dist1, dist2, dist3]
        dependencies = [dep1, dep2, dep3]

        mul_dist = MultivariateDistribution(distributions, dependencies)

        #del dist1, dist2, par1, par2, dep1, dep2, dependencies, distributions
        #calc contour
        n_years = 50
        limits = [(0, 20), (0, 18), (0, 18)]
        deltas = [1, 1, 1]

        test_contour_HDC = HighestDensityContour(mul_dist, n_years, 3, limits,
                                                 deltas)

        finaldt = pd.DataFrame({
            'x': test_contour_HDC.coordinates[0][0],
            'y': test_contour_HDC.coordinates[0][1],
            'z': test_contour_HDC.coordinates[0][2]
        })

        result = pd.read_csv(testfiles_path + "/HDC3dWLL_coordinates.csv")
        for i, j in [(i, j) for i in result.index for j in result.columns]:
            self.assertAlmostEqual(result.loc[i, j],
                                   finaldt.loc[i, j],
                                   places=8)
예제 #14
0
    def test_HDC2d_WN(self):
        """
        Creating Contour example
        """

        #define dependency tuple
        dep1 = (None, None, None)
        dep2 = (None, 0, 0)

        #define parameters
        shape = ConstantParam(1.471)
        loc = ConstantParam(0.8888)
        scale = ConstantParam(2.776)
        par1 = (shape, loc, scale)

        shape = None
        loc = FunctionParam(4, 10, 0.02, "f1")
        scale = FunctionParam(0.1, 0.02, -0.1, "f2")
        par2 = (shape, loc, scale)

        #del shape, loc, scale

        #create distributions
        dist1 = WeibullDistribution(*par1)
        dist2 = NormalDistribution(*par2)

        distributions = [dist1, dist2]
        dependencies = [dep1, dep2]

        mul_dist = MultivariateDistribution(distributions, dependencies)

        #del dist1, dist2, par1, par2, dep1, dep2, dependencies, distributions
        #calc contour
        n_years = 50
        limits = [(0, 20), (0, 20)]
        deltas = [0.05, 0.01]
        test_contour_HDC = HighestDensityContour(mul_dist, n_years, 3, limits,
                                                 deltas)

        finaldt2 = pd.DataFrame({
            'x': test_contour_HDC.coordinates[0][0],
            'y': test_contour_HDC.coordinates[0][1]
        })

        result2 = pd.read_csv(testfiles_path + "/HDC2dWN_coordinates.csv")

        for k, l in [(k, l) for k in result2.index for l in result2.columns]:
            self.assertAlmostEqual(result2.loc[k, l],
                                   finaldt2.loc[k, l],
                                   places=8)
예제 #15
0
    def test_IForm2d_WL(self):
        """
        2-d IFORM contour.

        The used probabilistic model is described in Vanem and Bitner-Gregersen
        (2012), DOI: 10.1016/j.apor.2012.05.006
        """

        # Define dependency tuple
        dep1 = (None, None, None)
        dep2 = (0, None, 0)

        # Define parameters
        shape = ConstantParam(1.471)
        loc = ConstantParam(0.8888)
        scale = ConstantParam(2.776)
        par1 = (shape, loc, scale)

        mu = FunctionParam(0.1000, 1.489, 0.1901, "power3")
        sigma = FunctionParam(0.0400, 0.1748, -0.2243, "exp3")

        # Create distributions
        dist1 = WeibullDistribution(*par1)
        dist2 = LognormalDistribution(mu=mu, sigma=sigma)

        distributions = [dist1, dist2]
        dependencies = [dep1, dep2]

        mul_dist = MultivariateDistribution(distributions, dependencies)

        test_contour_IForm = IFormContour(mul_dist, 50, 3, 50)

        calculated_coordinates = pd.DataFrame({
            'x':
            test_contour_IForm.coordinates[0][0],
            'y':
            test_contour_IForm.coordinates[0][1]
        })
        #calculated_coordinates.to_csv('save_this_file.csv', sep=',', header=['x', 'y'], index=False)

        true_coordinates = pd.read_csv(testfiles_path +
                                       "/IForm2dWL_coordinates.csv")
        for o, p in [(o, p) for o in true_coordinates.index
                     for p in true_coordinates.columns]:
            self.assertAlmostEqual(calculated_coordinates.loc[o, p],
                                   true_coordinates.loc[o, p],
                                   places=8)
예제 #16
0
    def test_IForm2d_WN(self):
        """
        2-d IFORM contour.
        """

        # Define dependency tuple.
        dep1 = (None, None, None)
        dep2 = (None, 0, 0)

        # Define parameters.
        shape = ConstantParam(1.471)
        loc = ConstantParam(0.8888)
        scale = ConstantParam(2.776)
        par1 = (shape, loc, scale)

        shape = None
        loc = FunctionParam(7, 1.489, 0.1901, "power3")
        scale = FunctionParam(1.5, 0.1748, -0.2243, "exp3")
        par2 = (shape, loc, scale)

        # Create distributions.
        dist1 = WeibullDistribution(*par1)
        dist2 = NormalDistribution(*par2)

        distributions = [dist1, dist2]
        dependencies = [dep1, dep2]

        mul_dist = MultivariateDistribution(distributions, dependencies)

        test_contour_IForm = IFormContour(mul_dist, 50, 3, 50)

        calculated_coordinates = pd.DataFrame({
            'x':
            test_contour_IForm.coordinates[0][0],
            'y':
            test_contour_IForm.coordinates[0][1]
        })

        true_coordinates = pd.read_csv(testfiles_path +
                                       "/IForm2dWN_coordinates.csv")

        for r, s in [(r, s) for r in true_coordinates.index
                     for s in true_coordinates.columns]:
            self.assertAlmostEqual(calculated_coordinates.loc[r, s],
                                   true_coordinates.loc[r, s],
                                   places=8)
예제 #17
0
    def test_IForm2d_WN(self):
        """
        Creating Contour example
        """

        #define dependency tuple
        dep1 = (None, None, None)
        dep2 = (None, 0, 0)

        #define parameters
        shape = ConstantParam(1.471)
        loc = ConstantParam(0.8888)
        scale = ConstantParam(2.776)
        par1 = (shape, loc, scale)

        shape = None
        loc = FunctionParam(7, 1.489, 0.1901, "f1")
        scale = FunctionParam(1.5, 0.1748, -0.2243, "f2")
        par2 = (shape, loc, scale)

        #del shape, loc, scale

        #create distributions
        dist1 = WeibullDistribution(*par1)
        dist2 = NormalDistribution(*par2)

        distributions = [dist1, dist2]
        dependencies = [dep1, dep2]

        mul_dist = MultivariateDistribution(distributions, dependencies)

        test_contour_IForm = IFormContour(mul_dist, 50, 3, 400)

        finaldt5 = pd.DataFrame({
            'x': test_contour_IForm.coordinates[0][0],
            'y': test_contour_IForm.coordinates[0][1]
        })

        result5 = pd.read_csv(testfiles_path + "/IForm2dWN_coordinates.csv")

        for r, s in [(r, s) for r in result5.index for s in result5.columns]:
            self.assertAlmostEqual(result5.loc[r, s],
                                   finaldt5.loc[r, s],
                                   places=8)
예제 #18
0
    def test_HDC4d_WLLL(self):
        """
        Creating Contour example for 4-d HDC with Weibull, Lognormal,
        Lognormal and Lognormal distribution
        """

        #define dependency tuple
        dep1 = (None, None, None)
        dep2 = (0, None, 0)
        dep3 = (0, None, 0)
        dep4 = (0, None, 0)

        #define parameters
        shape = ConstantParam(2.776)
        loc = ConstantParam(1.471)
        scale = ConstantParam(0.8888)
        par1 = (shape, loc, scale)

        mu = FunctionParam(0.1000, 1.489, 0.1901, "f1")
        sigma = FunctionParam(0.0400, 0.1748, -0.2243, "f2")

        #create distributions
        dist1 = WeibullDistribution(*par1)
        dist2 = LognormalDistribution(mu=mu, sigma=sigma)
        dist3 = LognormalDistribution(mu=mu, sigma=sigma)
        dist4 = LognormalDistribution(mu=mu, sigma=sigma)

        distributions = [dist1, dist2, dist3, dist4]
        dependencies = [dep1, dep2, dep3, dep4]

        mul_dist = MultivariateDistribution(distributions, dependencies)

        #del dist1, dist2, par1, par2, dep1, dep2, dependencies, distributions
        #calc contour
        n_years = 50
        limits = [(0, 20), (0, 18), (0, 18), (0, 18)]
        deltas = [1, 1, 1, 1]

        test_contour_HDC = HighestDensityContour(mul_dist, n_years, 3, limits,
                                                 deltas)
예제 #19
0
    def _setup(self,
               limits=[(0, 20), (0, 20)],
               deltas=[0.05, 0.05],
               n_years = 25,
               dep1=(None, None, None),
               dep2=(0, None, 0),
               par1=(ConstantParam(1.471), ConstantParam(0.8888),
                     ConstantParam(2.776)),
               par2=(FunctionParam('exp3', 0.0400, 0.1748, -0.2243), None,
                     FunctionParam('power3', 0.1, 1.489, 0.1901))
               ):
        """
        Creating a contour (same as in DOI: 10.1016/j.coastaleng.2017.03.002).
        """

        self.limits = limits
        self.deltas = deltas
        self.n_years = n_years

        # Define dependency tuple.
        self.dep1 = dep1
        self.dep2 = dep2

        # Define parameters.
        self.par1 = par1
        self.par2 = par2

        # Create distributions.
        dist1 = WeibullDistribution(*par1)
        dist2 = LognormalDistribution(*par2)

        distributions = [dist1, dist2]
        dependencies = [dep1, dep2]

        mul_dist = MultivariateDistribution(distributions, dependencies)

        # Compute contour.
        test_contour_HDC = HighestDensityContour(mul_dist, n_years, 3,
                                                 limits, deltas)
        return test_contour_HDC
예제 #20
0
    def test_HDC4d_WLLL(self):
        """
        Contour example for a 4-dimensinal HDC with Weibull, Lognormal,
        Lognormal and Lognormal distribution.
        """

        # Define dependency tuple.
        dep1 = (None, None, None)
        dep2 = (0, None, 0)
        dep3 = (0, None, 0)
        dep4 = (0, None, 0)

        # Define parameters.
        shape = ConstantParam(2.776)
        loc = ConstantParam(1.471)
        scale = ConstantParam(0.8888)
        par1 = (shape, loc, scale)

        mu = FunctionParam('power3', 0.1000, 1.489, 0.1901)
        sigma = FunctionParam('exp3', 0.0400, 0.1748, -0.2243)

        # Create distributions.
        dist1 = WeibullDistribution(*par1)
        dist2 = LognormalDistribution(mu=mu, sigma=sigma)
        dist3 = LognormalDistribution(mu=mu, sigma=sigma)
        dist4 = LognormalDistribution(mu=mu, sigma=sigma)


        distributions = [dist1, dist2, dist3, dist4]
        dependencies = [dep1, dep2, dep3, dep4]

        mul_dist = MultivariateDistribution(distributions, dependencies)

        # Compute contour.
        n_years = 50
        limits = [(0, 20), (0, 18), (0, 18), (0, 18)]
        deltas = [1, 1, 1, 1]

        test_contour_HDC = HighestDensityContour(mul_dist, n_years, 3,
                                                 limits, deltas)
예제 #21
0
    def test_plot_contour_without_sample(self):
        """
        Plots a contour in the most basic way.
        """

        # Define dependency tuple.
        dep1 = (None, None, None)
        dep2 = (0, None, 0)

        # Define parameters.
        shape = ConstantParam(1.471)
        loc = ConstantParam(0.8888)
        scale = ConstantParam(2.776)
        par1 = (shape, loc, scale)

        mu = FunctionParam('power3', 0.1000, 1.489, 0.1901)
        sigma = FunctionParam('exp3', 0.0400, 0.1748, -0.2243)

        # Create distributions.
        dist1 = WeibullDistribution(*par1)
        dist2 = LognormalDistribution(mu=mu, sigma=sigma)

        distributions = [dist1, dist2]
        dependencies = [dep1, dep2]

        mul_dist = MultivariateDistribution(distributions, dependencies)

        test_contour_IForm = IFormContour(mul_dist, 50, 3, 50)
        contour_hs = test_contour_IForm.coordinates[0][0]
        contour_tz = test_contour_IForm.coordinates[0][1]

        fig = plt.figure()
        ax = fig.add_subplot(111)

        plot_contour(contour_hs, contour_tz, ax)
        #plt.show()

        x_plot, y_plot = ax.lines[0].get_xydata().T
        self.assertAlmostEqual(y_plot[0], contour_tz[0], delta=0.001)
예제 #22
0
    def test_IForm2d_WL(self):
        """
        Creating Contour example
        """

        #define dependency tuple
        dep1 = (None, None, None)
        dep2 = (0, None, 0)

        #define parameters
        shape = ConstantParam(1.471)
        loc = ConstantParam(0.8888)
        scale = ConstantParam(2.776)
        par1 = (shape, loc, scale)

        mu = FunctionParam(0.1000, 1.489, 0.1901, "f1")
        sigma = FunctionParam(0.0400, 0.1748, -0.2243, "f2")

        #create distributions
        dist1 = WeibullDistribution(*par1)
        dist2 = LognormalDistribution(mu=mu, sigma=sigma)

        distributions = [dist1, dist2]
        dependencies = [dep1, dep2]

        mul_dist = MultivariateDistribution(distributions, dependencies)

        test_contour_IForm = IFormContour(mul_dist, 50, 3, 400)

        finaldt4 = pd.DataFrame({
            'x': test_contour_IForm.coordinates[0][0],
            'y': test_contour_IForm.coordinates[0][1]
        })

        result4 = pd.read_csv(testfiles_path + "/IForm2dWL_coordinates.csv")
        for o, p in [(o, p) for o in result4.index for p in result4.columns]:
            self.assertAlmostEqual(result4.loc[o, p],
                                   finaldt4.loc[o, p],
                                   places=8)
예제 #23
0
    def _setup(self,
               limits=[(0, 20), (0, 20)],
               deltas=[0.05, 0.05],
               n_years=25,
               dep1=(None, None, None),
               dep2=(0, None, 0),
               par1=(ConstantParam(1.471), ConstantParam(0.8888),
                     ConstantParam(2.776)),
               par2=(FunctionParam(0.0400, 0.1748, -0.2243, "f2"), None,
                     FunctionParam(0.1, 1.489, 0.1901, "f1"))):
        """
        Creating Contour example
        """

        self.limits = limits
        self.deltas = deltas
        self.n_years = n_years

        #define dependency tuple
        self.dep1 = dep1
        self.dep2 = dep2

        #define parameters
        self.par1 = par1
        self.par2 = par2

        #create distributions
        dist1 = WeibullDistribution(*par1)
        dist2 = LognormalDistribution(*par2)

        distributions = [dist1, dist2]
        dependencies = [dep1, dep2]

        mul_dist = MultivariateDistribution(distributions, dependencies)

        #calc contour
        test_contour_HDC = HighestDensityContour(mul_dist, n_years, 3, limits,
                                                 deltas)
        return test_contour_HDC
예제 #24
0
    def test_check_parameter_value(self):
        """
        Tests if the right exception is raised when the given parameters are
        not in the valid range of numbers.
        """

        shape = None
        loc = ConstantParam(0.8888)
        scale = ConstantParam(-2.776)
        par1 = (shape, loc, scale)

        dist = WeibullDistribution(*par1)

        with self.assertRaises(ValueError):
            dist._check_parameter_value(2, -2.776)
        with self.assertRaises(ValueError):
            dist._check_parameter_value(2, np.inf)
예제 #25
0
from viroconcom.params import ConstantParam, FunctionParam
from viroconcom.distributions import WeibullDistribution, LognormalDistribution, \
    MultivariateDistribution
from viroconcom.contours import IFormContour, ISormContour, HighestDensityContour
import matplotlib.pyplot as plt

# Define the multivariate distribution given in the paper by Vanem and
# Bitner-Gregersen (2012; doi: 10.1016/j.apor.2012.05.006)
shape = ConstantParam(1.471)
loc = ConstantParam(0.889)
scale = ConstantParam(2.776)
dist0 = WeibullDistribution(shape, loc, scale)
dep0 = (None, None, None) # All three parameters are independent.
my_sigma = FunctionParam('exp3', 0.040, 0.175, -0.224)
my_mu = FunctionParam('power3', 0.100, 1.489, 0.190)
dist1 = LognormalDistribution(sigma=my_sigma, mu=my_mu)
dep1 = (0, None, 0) # Parameter one and three depend on dist0.
distributions = [dist0, dist1]
dependencies = [dep0, dep1]
mul_dist = MultivariateDistribution(distributions, dependencies)

# Compute an IFORM, an ISORM and a highest density contour.
return_period = 50 # In years
sea_state_duration = 6 # In hours
iform_contour = IFormContour(mul_dist, return_period, sea_state_duration, 100)
isorm_contour = ISormContour(mul_dist, return_period, sea_state_duration, 100)
limits = [(0, 20), (0, 20)] # Limits of the computational domain
deltas = [0.005, 0.005] # Dimensions of the grid cells
hdens_contour = HighestDensityContour(
    mul_dist, return_period, sea_state_duration, limits, deltas)
예제 #26
0
# Define a hs - steepness bivariate model
dist_description_hs = {
    'name': 'Weibull_Exp'
}  # Order: shape, loc, scale, shape2
dist_description_s = {'name': 'Weibull_3p'}

from scipy.stats import weibull_min
from viroconcom.distributions import WeibullDistribution
from viroconcom.distributions import ExponentiatedWeibullDistribution
from viroconcom.distributions import MultivariateDistribution
from viroconcom.params import FunctionParam

params = weibull_min.fit(steepness, floc=0.005)
my_loc = FunctionParam('poly1', 0.0015, 0.002, None)
dist_s = WeibullDistribution(shape=params[0], loc=my_loc, scale=params[2])
dist_hs = ExponentiatedWeibullDistribution()
dist_hs.fit(hs)
joint_dist = MultivariateDistribution(distributions=[dist_hs, dist_s],
                                      dependencies=[(None, None, None, None),
                                                    (None, 0, None)])

# Fit the model to the data.
#fit = Fit((hs, steepness),
#          (dist_description_hs, dist_description_s))
#joint_dist = fit.mul_var_dist

trs = [1, 50, 250]
fms = np.empty(shape=(3, 1))
for i, tr in enumerate(trs):
    HDC = HighestDensityContour(joint_dist,
예제 #27
0
class MultivariateDistributionTest(unittest.TestCase):
    """
    Create an example MultivariateDistribution (Vanem2012 model).
    """

    # Define dependency tuple.
    dep1 = (None, 0, None)
    dep2 = (0, None, 0)

    # Define parameters.
    shape = ConstantParam(1.471)
    loc = ConstantParam(0.8888)
    scale = ConstantParam(2.776)
    par1 = (shape, loc, scale)

    shape = FunctionParam(0.0400, 0.1748, -0.2243, "exp3")
    loc = None
    scale = FunctionParam(0.1, 1.489, 0.1901, "power3")
    par2 = (shape, loc, scale)

    del shape, loc, scale

    # Create distributions.
    dist1 = WeibullDistribution(*par1)
    dist2 = LognormalDistribution(*par2)

    distributions = [dist1, dist2]
    dependencies = [dep1, dep2]

    def test_add_distribution_err_msg(self):
        """
        Tests if the right exception is raised when distribution1 has a
        dependency.
        """

        with self.assertRaises(ValueError):
            MultivariateDistribution(self.distributions, self.dependencies)

    def test_add_distribution_iter(self):
        """
        Tests if an exception is raised by the function add_distribution when
        distributions isn't iterable but dependencies is and the other way around.
        """

        distributions = 1
        with self.assertRaises(ValueError):
            MultivariateDistribution(distributions, self.dependencies)
        dependencies = 0
        with self.assertRaises(ValueError):
            MultivariateDistribution(self.distributions, dependencies)

    def test_add_distribution_length(self):
        """
        Tests if an exception is raised when distributions and dependencies
        are of unequal length.
        """

        dep3 = (0, None, None)
        dependencies = [self.dep1, self.dep2, dep3]
        with self.assertRaises(ValueError):
            MultivariateDistribution(self.distributions, dependencies)

    def test_add_distribution_dependencies_length(self):
        """
        Tests if an exception is raised when a tuple in dependencies
        has not length 3.
        """

        dep1 = (None, None)
        dependencies = [dep1, self.dep2]
        with self.assertRaises(ValueError):
            MultivariateDistribution(self.distributions, dependencies)

    def test_add_distribution_dependencies_value(self):
        """
        Tests if an exception is raised when dependencies has an invalid value.
        """

        dep1 = (-3, None, None)
        dependencies = [dep1, self.dep2]
        with self.assertRaises(ValueError):
            MultivariateDistribution(self.distributions, dependencies)

    def test_add_distribution_not_iterable(self):
        """
        Tests the function when both distributions and dependencies
        are not iterable.
        """

        distributions = 1
        dependencies = 2
        with self.assertRaises(ValueError):
            MultivariateDistribution(distributions, dependencies)

    def test_latex_representation(self):
        """
        Tests if the latex representation is correct.
        """
        dep1 = (None, None, None)
        dep2 = (0, None, 0)
        dependencies = [dep1, dep2]
        m = MultivariateDistribution(self.distributions, dependencies)
        computed_latex = m.latex_repr(['Hs', 'Tp'])
        correct_latex = \
            ['\\text{ joint PDF: }',
             'f(h_{s},t_{p})=f_{H_{s}}(h_{s})f_{T_{p}|H_{s}}(t_{p}|h_{s})',
             '',
             '1\\text{. variable, }H_{s}: ',
             'f_{H_{s}}(h_{s})=\\dfrac{\\beta_{h_{s}}}{\\alpha_{h_{s}}}'
             '\\left(\\dfrac{h_{s}-\\gamma_{h_{s}}}{\\alpha_{h_{s}}}'
             '\\right)^{\\beta_{h_{s}}-1}\\exp\\left[-\\left(\\dfrac{h_{s}-'
             '\\gamma_{h_{s}}}{\\alpha_{h_{s}}}\\right)^{\\beta_{h_{s}}}\\right]',
             '\\quad\\text{ with }\\alpha_{h_{s}}=2.776,',
             '\\quad\\qquad\\;\\; \\beta_{h_{s}}=1.471,',
             '\\quad\\qquad\\;\\; \\gamma_{h_{s}}=0.8888.',
             '',
             '2\\text{. variable, }T_{p}: ',
             'f_{T_{p}|H_{s}}(t_{p}|h_{s})=\\dfrac{1}{t_{p}\\tilde{\\sigma}_'
             '{t_{p}}\\sqrt{2\\pi}}\\exp\\left[-\\dfrac{(\\ln t_{p}-\\tilde{'
             '\\mu}_{t_{p}})^2}{2\\tilde{\\sigma}_{t_{p}}^2}\\right]',
             '\\quad\\text{ with }\\exp{\\tilde{\\mu}}_{t_{p}}='
             '0.1+1.489h_{s}^{0.1901},',
             '\\quad\\qquad\\;\\; \\tilde{\\sigma}_{t_{p}}='
             '0.04+0.1748e^{-0.2243h_{s}}.']
        assert (computed_latex, correct_latex)
예제 #28
0
class MultivariateDistributionTest(unittest.TestCase):
    """
    Create an example MultivariateDistribution (Vanem2012 model).
    """

    # Define dependency tuple.
    dep1 = (None, 0, None)
    dep2 = (0, None, 0)

    # Define parameters.
    shape = ConstantParam(1.471)
    loc = ConstantParam(0.8888)
    scale = ConstantParam(2.776)
    par1 = (shape, loc, scale)

    shape = FunctionParam('exp3', 0.0400, 0.1748, -0.2243)
    loc = None
    scale = FunctionParam('power3', 0.1, 1.489, 0.1901)
    par2 = (shape, loc, scale)

    del shape, loc, scale

    # Create distributions.
    dist1 = WeibullDistribution(*par1)
    dist2 = LognormalDistribution(*par2)

    distributions = [dist1, dist2]
    dependencies = [dep1, dep2]

    def test_add_distribution_err_msg(self):
        """
        Tests if the right exception is raised when distribution1 has a
        dependency.
        """

        with self.assertRaises(ValueError):
            MultivariateDistribution(self.distributions, self.dependencies)

    def test_multivariate_draw_sample(self):
        """
            Create an example MultivariateDistribution (Vanem2012 model).
            """

        # Define dependency tuple.
        dep1 = (None, None, None)
        dep2 = (0, None, 0)

        # Define parameters.
        shape = ConstantParam(1.471)
        loc = ConstantParam(0.8888)
        scale = ConstantParam(2.776)
        par1 = (shape, loc, scale)

        shape = FunctionParam('exp3', 0.0400, 0.1748, -0.2243)
        loc = None
        scale = FunctionParam('power3', 0.1, 1.489, 0.1901)
        par2 = (shape, loc, scale)

        del shape, loc, scale

        # Create distributions.
        dist1 = WeibullDistribution(*par1)
        dist2 = LognormalDistribution(*par2)

        distributions = [dist1, dist2]
        dependencies = [dep1, dep2]
        ref_points = 99119
        mul_var_dist = MultivariateDistribution(distributions, dependencies)
        my_points = mul_var_dist.draw_sample(ref_points)
        my_points0 = my_points[0].size
        my_points1 = my_points[1].size
        assert ref_points == my_points0
        assert ref_points == my_points1

    def test_draw_sample_distribution(self):
        """
            Create an example MultivariateDistribution (Vanem2012 model).
            """

        # Define dependency tuple.
        dep1 = (None, None, None)
        dep2 = (0, None, 0)

        # Define parameters.
        shape = ConstantParam(1.471)
        loc = ConstantParam(0.8888)
        scale = ConstantParam(2.776)
        par1 = (shape, loc, scale)

        shape = FunctionParam('exp3', 0.0400, 0.1748, -0.2243)
        loc = None
        scale = FunctionParam('power3', 0.1, 1.489, 0.1901)
        par2 = (shape, loc, scale)

        del shape, loc, scale

        # Create distributions.
        dist1 = WeibullDistribution(*par1)
        dist2 = LognormalDistribution(*par2)

        distributions = [dist1, dist2]
        dependencies = [dep1, dep2]
        points = 1000000
        mul_var_dist = MultivariateDistribution(distributions, dependencies)
        my_points = mul_var_dist.draw_sample(points)

        #Fit the sample
        # Describe the distribution that should be fitted to the sample.
        dist_description_0 = {
            'name': 'Weibull',
            'dependency': (None, None, None),
            'width_of_intervals': 2
        }
        dist_description_1 = {
            'name': 'Lognormal',
            'dependency': (0, None, 0),
            'functions': ('exp3', None, 'power3')
        }
        my_fit = Fit([my_points[0], my_points[1]],
                     [dist_description_0, dist_description_1])
        print(my_fit.mul_var_dist.distributions[0].shape(0))
        print(mul_var_dist.distributions[0].shape(0))
        assert np.round(my_fit.mul_var_dist.distributions[0].shape(0),
                        2) == np.round(mul_var_dist.distributions[0].shape(0),
                                       2)

    def test_add_distribution_iter(self):
        """
        Tests if an exception is raised by the function add_distribution when
        distributions isn't iterable but dependencies is and the other way around.
        """

        distributions = 1
        with self.assertRaises(ValueError):
            MultivariateDistribution(distributions, self.dependencies)
        dependencies = 0
        with self.assertRaises(ValueError):
            MultivariateDistribution(self.distributions, dependencies)

    def test_add_distribution_length(self):
        """
        Tests if an exception is raised when distributions and dependencies
        are of unequal length.
        """

        dep3 = (0, None, None)
        dependencies = [self.dep1, self.dep2, dep3]
        with self.assertRaises(ValueError):
            MultivariateDistribution(self.distributions, dependencies)

    def test_add_distribution_dependencies_length(self):
        """
        Tests if an exception is raised when a tuple in dependencies
        has not length 3.
        """

        dep1 = (None, None)
        dependencies = [dep1, self.dep2]
        with self.assertRaises(ValueError):
            MultivariateDistribution(self.distributions, dependencies)

    def test_add_distribution_dependencies_value(self):
        """
        Tests if an exception is raised when dependencies has an invalid value.
        """

        dep1 = (-3, None, None)
        dependencies = [dep1, self.dep2]
        with self.assertRaises(ValueError):
            MultivariateDistribution(self.distributions, dependencies)

    def test_add_distribution_not_iterable(self):
        """
        Tests the function when both distributions and dependencies
        are not iterable.
        """

        distributions = 1
        dependencies = 2
        with self.assertRaises(ValueError):
            MultivariateDistribution(distributions, dependencies)

    def test_latex_representation(self):
        """
        Tests if the latex representation is correct.
        """
        dep1 = (None, None, None)
        dep2 = (0, None, 0)
        dependencies = [dep1, dep2]
        m = MultivariateDistribution(self.distributions, dependencies)
        computed_latex = m.latex_repr(['Hs', 'Tp'])
        correct_latex = \
            ['\\text{ joint PDF: }',
             'f(h_{s},t_{p})=f_{H_{s}}(h_{s})f_{T_{p}|H_{s}}(t_{p}|h_{s})',
             '',
             '1\\text{. variable, }H_{s}: ',
             'f_{H_{s}}(h_{s})=\\dfrac{\\beta_{h_{s}}}{\\alpha_{h_{s}}}'
             '\\left(\\dfrac{h_{s}-\\gamma_{h_{s}}}{\\alpha_{h_{s}}}'
             '\\right)^{\\beta_{h_{s}}-1}\\exp\\left[-\\left(\\dfrac{h_{s}-'
             '\\gamma_{h_{s}}}{\\alpha_{h_{s}}}\\right)^{\\beta_{h_{s}}}\\right]',
             '\\quad\\text{ with }\\alpha_{h_{s}}=2.776,',
             '\\quad\\qquad\\;\\; \\beta_{h_{s}}=1.471,',
             '\\quad\\qquad\\;\\; \\gamma_{h_{s}}=0.8888.',
             '',
             '2\\text{. variable, }T_{p}: ',
             'f_{T_{p}|H_{s}}(t_{p}|h_{s})=\\dfrac{1}{t_{p}\\tilde{\\sigma}_'
             '{t_{p}}\\sqrt{2\\pi}}\\exp\\left[-\\dfrac{(\\ln t_{p}-\\tilde{'
             '\\mu}_{t_{p}})^2}{2\\tilde{\\sigma}_{t_{p}}^2}\\right]',
             '\\quad\\text{ with }\\exp{\\tilde{\\mu}}_{t_{p}}='
             '0.1+1.489h_{s}^{0.1901},',
             '\\quad\\qquad\\;\\; \\tilde{\\sigma}_{t_{p}}='
             '0.04+0.1748e^{-0.2243h_{s}}.']
        assert computed_latex, correct_latex