Esempio n. 1
0
File: sim.py Progetto: GenosW/NSSC2
def Epot_lj(positions, L: float, M: int):
    """Potential energy for Lennard-Jones potential in reduced units.
        In this system of units, epsilon=1 and sigma=2**(-1. / 6.). 
        
        The function accepts numpy arrays of shape (M, 3) [2D] or (M*3) [1D]."""
    if (positions.ndim != 2 or positions.shape[1] != 3
        ) and not (positions.ndim == 1 and positions.size == M * 3):
        raise ValueError(
            "positions must be an Mx3 array or a 1D array that can be reshaped to Mx3!"
        )
    if positions.ndim == 1 and positions.size == M * 3:
        positions = positions.reshape((M, 3))  # Reshape to Mx3
    #sig = 1 / np.power(2, 1 / 6)
    sig = 1.

    # Compute all squared distances between pairs
    delta = positions[:, np.newaxis, :] - positions
    delta = delta - L * np.around(delta / L, decimals=0)
    r2 = (delta * delta).sum(axis=2)  # r^2 ...squared distances

    # Take only the upper triangle (combinations of two atoms).
    indices = np.triu_indices(r2.shape[0], k=1)
    rm2 = sig * sig / r2[indices]  # (sig/r)^2
    # Compute the potental energy recycling as many calculations as possible.
    rm6 = rm2 * rm2 * rm2  # (sig/r)^6
    rm12 = rm6 * rm6  # (sig/r)^12
    return (rm12 - 2. * rm6).sum()
Esempio n. 2
0
    def analyze(self, path=None, num_samples=50, start=0., stop=1):
        """Analyze a trajectory file (=path) in .xyz format"""
        if not path:
            path = self.path

        # Volume of the simulation box
        V = self.sim.L * self.sim.L * self.sim.L
        # Lines in file per snapshot
        lines_per_snap = self.sim.M + 3
        # Number of lines in the file
        lines_in_file = self.sim.getNumLines(path)

        print("Lines in file:", lines_in_file)
        print("Lines per snap:", lines_per_snap)

        # Number of snapshots in the file (=N...number of steps in evolve.py)
        num_snaps = lines_in_file / lines_per_snap
        print("Number of snaps: ", num_snaps)
        if isinstance(num_snaps, float):
            assert (num_snaps.is_integer())
            num_snaps = int(num_snaps)
        elif isinstance(num_snaps, int):
            pass
        else:
            raise TypeError(
                "There is something wrong with the input file...cannot analyze!"
            )

        # <num_samples> samples evenly spaced on the intervall [0, L/2]
        # There can still be particles outside of this sphere with raidus r=L/2!
        samples, dr = np.linspace(0,
                                  self.sim.L / 2 * numpy.sqrt(3),
                                  num=num_samples,
                                  retstep=True)
        # Array containing pair correlation function
        pcf = numpy.zeros_like(samples)

        start_offset = int(start * num_snaps *
                           lines_per_snap)  # end of first 25% of frames
        stop_offset = stop * num_snaps * lines_per_snap  # Snapshot number to stop at
        offset = 0  # ...line in file to access to get the next snapshot
        j = 0
        # For the first 25%, we only calculate energies
        while self.sim.loadSnapshotIntoBox(path, offset=offset):
            self.calculateEnergies()
            j += 1
            offset = j * lines_per_snap
            if offset >= start_offset:
                break
        offset = start_offset
        i = 0  # Counter for snapshots that contribute to PCF
        print("offset:", offset)
        # For the remaining 75%, we calculate energies + the pair density function (not normalized yet)
        while self.sim.loadSnapshotIntoBox(path, offset=offset):
            # Snapshots are loaded one at a time from the file...much slower but should scale better for larger systems
            self.calculateEnergies()

            # Calculate distance in Minimum Image convention
            delta = self.sim.positions[:, np.newaxis, :] - self.sim.positions
            delta = delta - self.sim.L * np.around(delta / self.sim.L,
                                                   decimals=0)

            # Calculate correspending index number in PCF
            bins = numpy.trunc(numpy.sqrt((delta * delta).sum(axis=2)) / dr)
            bins = bins.astype(int)  # save array as array of ints
            # only want upper triangle --> no double counting of distances
            indices = numpy.triu_indices(bins.shape[0], k=1)
            for k in bins[indices]:
                # There can still be particles outside of sphere with raidus r=L/2!
                if k >= num_samples:  # only needed if r sampled from [0, L/2]
                    pass
                    #print(k)
                else:
                    pcf[k] += 1

            # Offset (in file) for next snapshot
            i += 1
            offset = start_offset + i * lines_per_snap
            if offset >= stop_offset:  # if last snapshot to analyze
                break
        print("Snaps for used for PCF:", i)
        return samples, pcf, (i, self.sim.M, self.sim.L)
Esempio n. 3
0
    def showPlot(self):
        if self.method == Method.MRRCensored2p:
            xmin = self.est_data[['time', 'lb', 'ub']].min().min() - (
                self.est_data[['time', 'lb', 'ub']].min().min() * 0.2)
            xmax = self.est_data[['time', 'lb', 'ub']].max().max() * 1.2
            method_text = 'MRR 2P'
            conf_test = 'MR'

            xx = jnp.array(self.est_data['time'] - self.loc)  #failures
            yy = jnp.log(1.0 / (1.0 - jnp.array(self.est_data['cdf'])))

            x = jnp.arange(xmin, xmax, (xmax - xmin) / 200)
            est_cdf = jnp.log(1.0 / (1.0 - self.cdf(x)))

            y = yy
            t_lb = self.est_data['lb']
            t_ub = self.est_data['ub']
            xtics = 5 * jnp.around(
                jnp.arange(xmin, xmax,
                           (xmax - xmin) / 10) / 5)  # round to nearest 5

        elif self.method == Method.MLECensored2p:
            method_text = 'MLE 2P'
            conf_test = 'FM'
            xmin = self.bLive(0.01)
            xmax = self.bLive(0.99)

            xx = jnp.array(self.est_data['time'] - self.loc)
            yy = jnp.log(1.0 / (1.0 - jnp.array(self.est_data['cdf'])))

            x = jnp.arange(xmin, xmax, (xmax - xmin) / 200)
            est_cdf = jnp.log(1.0 / (1.0 - self.cdf(x)))

            y = est_cdf
            t_lb = self.bLiveCL(1.0 - self.cdf(x), Bound.OSLB)
            t_ub = self.bLiveCL(1.0 - self.cdf(x), Bound.OSUB)
            t_tlb = self.bLiveCL(1.0 - self.cdf(x), Bound.TSLB)
            t_tub = self.bLiveCL(1.0 - self.cdf(x), Bound.TSUB)
            xmin = self.bLive(0.01)
            xmax = self.bLive(0.99)
            xtics = 5 * jnp.around(
                jnp.arange(xmin, xmax,
                           (xmax - xmin) / 10) / 5)  # round to nearest 5

        fig = plt.figure(num=None,
                         figsize=(6, 9),
                         dpi=80,
                         facecolor='w',
                         edgecolor='k')
        ax = fig.add_subplot(1, 1, 1)
        ax.set_xscale('log')
        ax.set_yscale('log')
        fig.canvas.draw()
        ax.plot(xx, yy, 'rX', label='Failures (MMR)')  #failures
        ax.plot(x, est_cdf, label='Reference line')  #estimated
        ax.plot(t_lb, y, label='Lower bound - ' +
                str(round(1.0 - self.CL, 3)))  # lower bound
        ax.plot(t_ub, y, label='Upper bound - ' +
                str(round(1.0 - self.CL, 3)))  # upper bound
        if self.method == Method.MLECensored2p:
            # only for MLE
            ax.fill_betweenx(y,
                             t_tlb,
                             t_tub,
                             facecolor='tan',
                             alpha=0.3,
                             label='2 side bound 2 x ' +
                             str(round((1.0 - self.CL) / 2, 3)))
        ax.set_xticks(xtics)
        ax.set_xlabel(xtics)
        ax.set_xticklabels(xtics, rotation=45)

        ax.set_yticks([
            0.010050336, 0.051293294, 0.105360516, 0.223143551, 0.356674944,
            0.510825624, 0.693147181, 0.916290732, 1.203972804, 1.609437912,
            2.302585093, 4.605170186
        ])
        ax.set_yticklabels([
            '1%', '5%', '10%', '20%', '30%', '40%', '50%', '60%', '70%', '80%',
            '90%', '99%'
        ])
        ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
        ax.grid(True, which="both")
        ax.set_xlabel('Sample data (time/cycle)')
        ax.set_ylabel('Weibull probability')
        ax.set_title("Weibull probability plot "
                     "\n fit = " + method_text + ", CI =" + conf_test +
                     ", Failures = " + str(self.failures.size) +
                     ", Censored = " + str(self.censored.size) +
                     "\n Est:  Shape = " + str(round(self.shape, 2)) +
                     " ; Scale= " + str(round(self.scale, 2)) +
                     " ; Location = " + str(round(self.loc, 2)))
        plt.legend(loc='upper left')
        plt.show()
Esempio n. 4
0
File: sim.py Progetto: GenosW/NSSC2
 def enforceMI(self):
     """Enforce the Minimum Image convention on all positions in the instance"""
     return self.positions - self.L * np.around(self.positions / self.L,
                                                decimals=0)
Esempio n. 5
0
File: sim.py Progetto: GenosW/NSSC2
 def sanity_check(self):
     """Sanity check performed after minimization... conservation of momentum"""
     return np.around(grad_Epot(self.positions.ravel(), self.L,
                                self.M).reshape(self.M, 3).sum(axis=0),
                      decimals=6)  # [sum(fx_i), sum(fy_i), sum(fz_i)]
Esempio n. 6
0
 def round(self, decimals=0):
     """ Rounds the entries of a tensor up to a number of decimals. """
     return Tensor(self.dom, self.cod,
                   np.around(self.array, decimals=decimals))
Esempio n. 7
0
        np.std(input_tensor, _astuple(axis), keepdims=keepdims)))

reduce_sum = utils.copy_docstring(
    tf.math.reduce_sum,
    lambda input_tensor, axis=None, keepdims=False, name=None: (  # pylint: disable=g-long-lambda
        np.sum(input_tensor, _astuple(axis), keepdims=keepdims)))

reduce_variance = utils.copy_docstring(
    tf.math.reduce_variance,
    lambda input_tensor, axis=None, keepdims=False, name=None: (  # pylint: disable=g-long-lambda
        np.var(input_tensor, _astuple(axis), keepdims=keepdims)))

rint = utils.copy_docstring(
    tf.math.rint,
    # JAX doesn't have rint, but round/around are ~the same with decimals=0.
    lambda x, name=None: np.around(x))

round = utils.copy_docstring(  # pylint: disable=redefined-builtin
    tf.math.round,
    lambda x, name=None: np.round(x))

rsqrt = utils.copy_docstring(tf.math.rsqrt,
                             lambda x, name=None: 1. / np.sqrt(x))

# scalar_mul = utils.copy_docstring(
#     tf.math.scalar_mul,
#     lambda data, segment_ids, name=None: np.scalar_mul)

# segment_max = utils.copy_docstring(
#     tf.math.segment_max,
#     lambda data, segment_ids, name=None: np.segment_max)
Esempio n. 8
0
def test_finite_DMRG_init(N, config, D):

    backend = 'jax'
    dtype = 'float64'

    a = buildMPO()
    mpo = FiniteMPO(a, backend=backend)

    mps = FiniteMPS.random([4] * N, config, dtype=dtype, backend=backend)

    ans1 = 500
    ans2 = 100
    sumtime = 0
    while abs(2 * (ans1 - ans2) / (ans1 + ans2)) > 0.1 / 100:

        print("Bond dim = {D}, Configuration = {c}".format(D=D, c=config))
        bondarray.append(D)
        start_time = time.time()
        dmrg = FiniteDMRG(mps, mpo)
        [mps, energy] = run_one_site(dmrg,
                                     num_sweeps=1000,
                                     num_krylov_vecs=15,
                                     precision=prec,
                                     delta=prec,
                                     tol=prec,
                                     verbose=0,
                                     ndiag=1)
        timearray.append(
            jnp.around(float(time.time() - start_time) / 60, decimals=2))
        print("{x} minutes".format(x=timearray[-1]))
        sumtime += timearray[-1]
        energy += 2
        minarray.append(energy)
        print("Minimum: {x}".format(x=minarray[-1]))
        ans1 = ans2
        ans2 = energy
        precisionarray.append(
            jnp.around(2 * (ans1 - ans2) / (ans1 + ans2) * 100, decimals=2))
        print("Precision (%): {x}".format(x=precisionarray[-1]))
        print("Number of iterations: {x}\n".format(x=numofitarray[-1]))

        D *= 2
        for i in range(N - 1):
            config[i] *= 2

        A = mps.tensors
        B = jnp.zeros((1, 4, config[0]), dtype='float64')
        B = jax.ops.index_update(B, jax.ops.index[:, :, :A[0].shape[2]], A[0])
        A[0] = B
        for i in range(1, N - 1):
            B = jnp.zeros((config[i - 1], 4, config[i]), dtype='float64')
            B = jax.ops.index_update(
                B, jax.ops.index[:A[i].shape[0], :, :A[i].shape[2]], A[i])
            A[i] = B
        B = jnp.zeros((config[N - 2], 4, 1), dtype='float64')
        B = jax.ops.index_update(B, jax.ops.index[:A[N - 1].shape[0], :, :],
                                 A[N - 1])
        A[N - 1] = B
        mps.tensors = A

    print("")
Esempio n. 9
0
Narray = [10]

prec = 1E-4

Dinit = 8

for N in Narray:
    print('Length of the chain = {N}\n'.format(N=N))
    configarray = constructconfigarray(Dinit)
    for config in configarray:
        numofitarray = []
        minarray = []
        precisionarray = []
        timearray = []
        bondarray = []

        t1 = time.time()
        test_finite_DMRG_init(N, config, Dinit)
        print("{x} minutes".format(
            x=jnp.around(float(time.time() - t1) / 60, decimals=2)))
        print("Bond array: {x}".format(x=bondarray))
        print("Minimum array: {x}".format(x=jnp.float64(minarray)))
        print("Precision array (%): {x}".format(x=jnp.float(precisionarray)))
        print("Time array (minutes): {x}".format(x=jnp.float(timearray)))
        print("Number of iterations (at every bond): {x}".format(
            x=jnp.int(numofitarray)))
        print(
            "*********************************************************************************\n"
        )