コード例 #1
0
def test_mc_sampling_errors(method, ninvar, seed):
    with pytest.raises(ValueError):
        sampling(ndraws=512,
                 method=method,
                 ninvar=ninvar,
                 ninvar_max=None,
                 seed=seed)
コード例 #2
0
def test_mc_sampling(method, ninvar, seed, ans):
    pcts = sampling(ndraws=512,
                    method=method,
                    ninvar=ninvar,
                    ninvar_max=None,
                    seed=seed)
    assert pcts[0] == pytest.approx(ans)
コード例 #3
0
ファイル: mc_var.py プロジェクト: scottshambaugh/Monaco
    def draw(self,
             ninvar_max : int = None,
             ) -> None:
        """
        Perform the random draws based on the sampling method and the
        statistical distribution, and map those draws to values.

        Parameters
        ----------
        ninvar_max : int
            The total number of input variables for the simulation.
        """
        self.pcts = []
        self.nums = []
        dist = self.dist(**self.distkwargs)

        if self.firstcaseismedian:
            self.ncases = self.ndraws + 1
            self.pcts.append(0.5)
            self.nums.append(np.array(self.getDistMedian()))

        pcts = sampling(ndraws=self.ndraws, method=self.samplemethod,
                        ninvar=self.ninvar, ninvar_max=ninvar_max,
                        seed=self.seed)
        self.pcts.extend(pcts)
        self.nums.extend([np.array(x) for x in dist.ppf(pcts)])

        if any(np.isinf(self.nums)):
            warn( 'Infinite value drawn. Check distribution and parameters: ' +
                 f'{self.dist=}, {self.distkwargs=}')
            if self.samplemethod in (SampleMethod.SOBOL, SampleMethod.HALTON):
                warn(f'Infinite value draw may happen with {self.dist=} for the ' +
                     f'first point of the {self.samplemethod} sampling method. ' +
                     f'Consider using {SampleMethod.SOBOL_RANDOM} instead.')

        if any(np.isnan(num) for num in self.nums):
            raise ValueError( 'Invalid draw. Check distribution and parameters: ' +
                             f'{self.dist=}, {self.distkwargs=}')

        self.mapNums()
コード例 #4
0
                1, n + 1))**dimension / np.arange(1, n + 1)
            error1sig = error1sig_sobol

        # Leading zeros will throw off plots, fill with reasonable dummy data
        error1sig[error1sig == 0] = max(error1sig)

    error = error1sig * pct2sig(conf)
    return error


samplepointsrandom = []
samplepointssobol = []
for i in range(d):
    samplepointsrandom.append(
        sampling(ndraws=n,
                 method=SampleMethod.RANDOM,
                 ninvar=i + 1,
                 seed=seed + i))  # Need different seed for random draws
    samplepointssobol.append(
        sampling(ndraws=n,
                 method=SampleMethod.SOBOL,
                 ninvar=i + 1,
                 seed=None,
                 ninvar_max=d))

# Discrepancy calculations take too long
'''
samplepointsrandom = np.array(samplepointsrandom).transpose()
samplepointsrandom = np.reshape(samplepointsrandom, (n, d))
errrandom = scipy.stats.qmc.discrepancy(samplepointsrandom)
samplepointssobol = np.array(samplepointssobol).transpose()
samplepointssobol = np.reshape(samplepointssobol, (n, d))
コード例 #5
0
    def plot_sampling_test(ndraws, method, seeds, genplot=True):
        import scipy.stats

        pcts = np.array([
            sampling(ndraws=ndraws,
                     method=method,
                     ninvar=1,
                     ninvar_max=2,
                     seed=seeds[0]),
            sampling(ndraws=ndraws,
                     method=method,
                     ninvar=2,
                     ninvar_max=2,
                     seed=seeds[1])
        ])

        if genplot:
            fig, axs = plt.subplots(1, 3)
            fig.suptitle(f"samplemethod = '{method}'", fontweight='bold')
            fig.set_dpi(96)
            fig.set_size_inches(16, 5)

            axs[0].set_title('Uniform')
            axs[0].scatter(pcts[0], pcts[1], alpha=0.5)
            square = plt.Rectangle((0, 0), 1, 1, color='k', fill=False)
            axs[0].add_patch(square)
            axs[0].set_xlim([-0.1, 1.1])
            axs[0].set_ylim([-0.1, 1.1])
            axs[0].set_aspect('equal')

            axs[1].set_title('Normal')
            axs[1].scatter(scipy.stats.norm.ppf(pcts[0]),
                           scipy.stats.norm.ppf(pcts[1]),
                           alpha=0.5)
            circle1 = plt.Circle((0, 0), 1, color='k', fill=False)
            circle2 = plt.Circle((0, 0), 2, color='k', fill=False)
            circle3 = plt.Circle((0, 0), 3, color='k', fill=False)
            axs[1].add_patch(circle1)
            axs[1].add_patch(circle2)
            axs[1].add_patch(circle3)
            axs[1].set_xlim([-3.5, 3.5])
            axs[1].set_ylim([-3.5, 3.5])
            axs[1].set_aspect('equal')

            axs[2].set_title('Frequency Spectra')
            ndraws_freq = 10000
            # ndraws_freq = 1000000  # For better frequency plots
            n_freq_grid = 2**8
            f_max = n_freq_grid / 2
            pcts_freq = np.array([
                sampling(ndraws=ndraws_freq,
                         method=method,
                         ninvar=1,
                         ninvar_max=2,
                         seed=seeds[0]),
                sampling(ndraws=ndraws_freq,
                         method=method,
                         ninvar=2,
                         ninvar_max=2,
                         seed=seeds[1])
            ])
            pcts_freq_int = np.round(pcts_freq * (n_freq_grid - 1)).astype(int)
            S = np.zeros([n_freq_grid, n_freq_grid])
            for i in range(ndraws_freq):
                S[pcts_freq_int[0, i], pcts_freq_int[1, i]] += 1
            FS = np.fft.fft2(S)
            axs[2].imshow(np.log(np.abs(np.fft.fftshift(FS))**2),
                          cmap='Blues_r',
                          extent=[-f_max, f_max, -f_max, f_max],
                          aspect="equal")

            # fig.savefig(f'../docs/{method}_sampling.png')

        return pcts