Ejemplo n.º 1
0
def main():

    # The Wiener process parameter.
    delta = 2
    # Total time.
    T = 10.0
    # Number of steps.
    N = 500
    # Time step size
    dt = T/N
    # Number of realizations to generate.
    m = 20
    # Create an empty array to store the realizations.
    x = numpy.empty((m,N+1))
    # Initial values of x.
    x[:, 0] = 50

    brownian(x[:,0], N, dt, delta, out=x[:,1:])

    t = numpy.linspace(0.0, N*dt, N+1)
    for k in range(m):
        plot(t, x[k])
    xlabel('t', fontsize=16)
    ylabel('x', fontsize=16)
    grid(True)
    show()
Ejemplo n.º 2
0
def main():

    # The Wiener process parameter.
    delta = 0.25
    # Total time.
    T = 10.0
    # Number of steps.
    N = 500
    # Time step size
    dt = T/N
    # Initial values of x.
    x = numpy.empty((2,N+1))
    x[:, 0] = 0.0

    brownian(x[:,0], N, dt, delta, out=x[:,1:])

    # Plot the 2D trajectory.
    plot(x[0],x[1])
    
    # Mark the start and end points.
    plot(x[0,0],x[1,0], 'go')
    plot(x[0,-1], x[1,-1], 'ro')

    # More plot decorations.
    title('2D Brownian Motion')
    xlabel('x', fontsize=16)
    ylabel('y', fontsize=16)
    axis('equal')
    grid(True)
    show()
def main():
    #Weiner process parameter
    delta = 0.25
    #Total time
    T = 10.0
    #Number of steps
    N = 500
    #Time step size
    dt = T/N
    #Initial values of x
    x = numpy.empty((2, N+1))
    x[:,0] = 0.0

    brownian(x[:,0], N, dt, delta, out=x[:,1:])    
    
    #Plot 2D trajectory
    plot(x[0], x[1])
    
    #Mark start and end points
    plot(x[0,0], x[1,0], 'go')
    plot(x[0,-1], x[1,-1], 'ro')
    
    #Decorate plot
    title("2D Brownian Motion")
    xlabel('x', fontsize = 16)
    ylabel('y', fontsize = 16)
    axis('equal')
    grid('TRUE')
    show()
Ejemplo n.º 4
0
    def setup_samples_from_equation(self):
        try:
            # throws an exception if not found
            if (self.driving_function.index('Bt') + 1):
                x0 = 0.0
                n = self.sample_count - 1
                dt = self.time_upper_bound / n
                delta = 1

                Bt = brownian(x0, n, dt, delta)[::-1]
                Bt = np.resize(Bt, n + 1)
                Bt[-1] = x0
                self.Bt = Bt
        except:
            pass

        t = self.time_domain
        t = t
        # "+(0*t)" to ensure the correct number of samples (for constant functions)
        eq = '(' + self.driving_function + ')+(0*t)'
        self.samples = numexpr.evaluate(eq)
    def integrate(self):
        # If noise is Ito, first generate brownian motion.
        if self.noise_implementation == NOISE.ARATO_LINEAR:
            self.xt = np.zeros_like(self.params['initial_condition'])
            self.bm = brownian(np.zeros(len(self.params['initial_condition'])),
                               int(self.T / self.dt),
                               self.dt,
                               1,
                               out=None)

        x_ts = np.zeros(
            [int(self.T / (self.dt * (self.tskip + 1))), self.Nspecies])

        # set initial condition
        x_ts[0] = self.x.flatten()

        # Integrate ODEs according to model and noise
        for i in range(1, int(self.T / (self.dt * (self.tskip + 1)))):
            for j in range(self.tskip + 1):
                self.add_step(self, i * (self.tskip + 1) + j)

            # Save abundances
            if self.f != 0:
                self.write_abundances_to_file(i * (self.tskip + 1) + j)

            x_ts[i] = self.x.flatten()

            if np.all(np.isnan(self.x)):
                break

        # dataframe to save timeseries
        self.x_ts = pd.DataFrame(
            x_ts,
            columns=['species_%d' % i for i in range(1, self.Nspecies + 1)])
        self.x_ts['time'] = (
            self.dt * (self.tskip + 1) *
            np.arange(0, int(self.T / (self.dt * (self.tskip + 1)))))

        return
Ejemplo n.º 6
0
                col = index.column()
                return QtCore.QVariant("%.3f" % self._array[row, col])
        return QtCore.QVariant()


def update_data(model, home_sim, away_sim):
    h = max([0, next(home_sim)])
    a = max([0, next(away_sim)])
    model.updateData(correct_score_grid(h, a))


if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    widget = QtWidgets.QTableView()

    home_simulator = brownian(1, 0.1, 2.2)
    away_simulator = brownian(1, 0.1, 3.2)
    data = correct_score_grid(2.2, 3.2, 13)  # Hardcoded for now.
    model = NumpyModel(data)

    widget.setItemDelegate(HMDelegate(model))
    widget.setModel(model)
    widget.resizeColumnsToContents()
    widget.resizeRowsToContents()
    widget.show()

    timer = Qt.QTimer()
    cb = functools.partial(update_data, model, home_simulator, away_simulator)

    timer.timeout.connect(cb)
    timer.start(50)
Ejemplo n.º 7
0
# The Wiener process parameter.
sigma = 1
# Total time.
T = 10000
# Number of steps.
N = 10000
# Time step size
dt = T/N
# Number of realizations to generate.
n = 20
# Create an empty array to store the realizations.
X = np.empty((n, N+1))
# Initial values of x.
X[:, 0] = 50
brownian(X[:, 0], N, dt, sigma, out=X[:, 1:])
Z = np.roll(X,-1)[:, :-1]
X = X[:, :-1]

#%%
'''======================= SETUP/DEFINITIONS ======================='''
import observables
from sympy import symbols
from sympy.polys.monomials import itermonomials, monomial_count
from sympy.polys.orderings import monomial_key

d = X.shape[0]
m = X.shape[1]
s = int(d*(d+1)/2) # number of second order poly terms
rtoler=1e-02
atoler=1e-02
Ejemplo n.º 8
0
from volatility_gen import generate_volatility

print('Lesssgooo...')

# init daily demand = 2000 pcs
initial_demand = 1100
# stdeviation
stdev = 50
# run for certain amount of years
period = 365
max_time_point = 5 * period

delta = 2

for i in range(1):
    brownian_sample = brownian(initial_demand, max_time_point, 1, delta)
    volitility_sample = generate_volatility(initial_demand, max_time_point,
                                            0.01)
    x = np.arange(max_time_point)
    plt.plot(x, brownian_sample, label="brownian motion")
    plt.plot(x, volitility_sample, label="volatility algorithm")

plt.legend()
plt.show()

# write values to csv
# distr = np.random.normal(initial_demand, stdev, max_time_point)
# with open("out.csv", "w") as f:
#     f.write("timestep, value\n")
#     for (i, val) in enumerate(distr):
#         # val = "---"
Ejemplo n.º 9
0
# to note that the calculation is the cumulative sum of samples from the
# normal distribution. A fast version can be implemented by first
# generating all the samples from the normal distribution with one call to
# scipy.stats.norm.rvs(), and then using the numpy *cumsum* function to
# form the cumulative sum.
# 
# The following function uses this idea to implement the function
# *brownian()*. The function allows the initial condition to be an array
# (or anything that can be converted to an array). Each element of *x0* is
# treated as an initial condition for a Brownian motion.
# 
# <codecell>


#!python
"""
brownian() implements one dimensional Brownian motion (i.e. the Wiener process).
"""

# File: brownian.py

from math import sqrt
from scipy.stats import norm
import numpy as np


def brownian(x0, n, dt, delta, out=None):
    """\
    Generate an instance of Brownian motion (i.e. the Wiener process):

        X(t) = X(0) + N(0, delta**2 * t; 0, t)
Ejemplo n.º 10
0
# The Wiener process parameter.
delta = 2
# Total time.
T = 30.0
# Number of steps.
N = 500
# Time step size
dt = T / N
# Number of realizations to generate.
m = 5000
# Create an empty array to store the realizations.
x = numpy.empty((m, N + 1))
# Initial values of x.
x[:, 0] = 50

brownian(x[:, 0], N, dt, delta, out=x[:, 1:])

t = numpy.linspace(0.0, N * dt, N + 1)

for k in range(m):
    plot(t, x[k])
xlabel('t', fontsize=16)
ylabel('x', fontsize=16)
grid(True)
#show()

savefig("lineas.png")
plt.close()
half = N // 2

mu = 50
Ejemplo n.º 11
0
    #########################################

    # The Wiener process parameter.
    sigma = 2
    # Total time.
    T = 1.0
    # Number of steps.
    N = 200  # int(T/dt)
    # Time step size
    dt = T / N  # 0.005
    # Create an empty array to store the realizations.
    s = numpy.empty((N + 1))
    # Initial value of x.
    s[0] = 100

    bm.brownian(s[0], N, dt, sigma, out=s[1:])

    t = numpy.linspace(0.0, N * dt, N + 1)

    # plt.plot(t, s)
    # plt.xlabel('time', fontsize=16)
    # plt.ylabel('price', fontsize=16)
    # plt.grid(True)
    # plt.show()

    ##########################################
    #       Computational loop
    #########################################

    # Limit horizon
    limit_horizon = True
Ejemplo n.º 12
0
def test_process(index):
    nuAb = 0.
    nuBb = 0.
    nuAd = 0.
    nuBd = 0.
    # if index==0:
    #     s=1.7
    #     nuAb=1e-4
    #     nuBb=1e-3
    #     logi=1
    # if index==1:
    #     s=1.7
    #     nuAb=1e-4
    #     nuBb=1e-3
    #     logi=0
    # if index==2:
    #     s=1.51
    #     nuAb=5e-4
    #     nuBb=1e-3
    #     logi=1
    # if index==3:
    #     s=1.51
    #     nuAb=5e-4
    #     nuBb=1e-3
    #     logi=0
    # if index==4:
    #     s=1.43
    #     nuAb=1e-3
    #     nuBb=1e-3
    #     logi=1
    # if index==5:
    #     s=1.43
    #     nuAb=1e-3
    #     nuBb=1e-3
    #     logi=0
    # if index==6:
    #     s=1.
    #     nuAb=1e-3
    #     nuBb=1e-3
    #     logi=1
    # if index==7:
    #     s=1.
    #     nuAb=1e-3
    #     nuBb=1e-3
    #     logi=0
    if index == 0:
        s = 1.8
        nuAb = 0.011
        nuBb = 0.022
        nuAd = 0.001
        nuBd = 0.002
        logi = 1
    if index == 1:
        s = 1.8
        nuAb = 0.011
        nuBb = 0.022
        nuAd = 0.001
        nuBd = 0.002
        logi = 0
    if index == 2:
        s = 2.5
        nuAb = 0.011
        nuBb = 0.022
        nuAd = 0.001
        nuBd = 0.002
        logi = 1
    if index == 3:
        s = 2.5
        nuAb = 0.011
        nuBb = 0.022
        nuAd = 0.001
        nuBd = 0.002
        logi = 0
    if index == 4:
        s = 4.
        nuAb = 0.011
        nuBb = 0.022
        nuAd = 0.001
        nuBd = 0.002
        logi = 1
    if index == 5:
        s = 4.
        nuAb = 0.011
        nuBb = 0.022
        nuAd = 0.001
        nuBd = 0.002
        logi = 0
    # if index==10:
    #     s=1.35
    #     nuAb=1e-3
    #     nuBb=5e-4
    #     logi=1
    # if index==11:
    #     s=1.35
    #     nuAb=1e-3
    #     nuBb=5e-4
    #     logi=0
    # if index==12:
    #     s=1.3
    #     nuAb=1e-3
    #     nuBb=1e-4
    #     logi=1
    # if index==13:
    #     s=1.3
    #     nuAb=1e-3
    #     nuBb=1e-4
    #     logi=0

    # Parameters for the model

    KAA = 4.
    KAB = s
    KBA = s
    KBB = 1.

    nuAAc = 1.
    nuABc = 1.
    nuBAc = 1.
    nuBBc = 1.

    nuAAd = 1.
    nuABd = 1.
    nuBAd = 1.
    nuBBd = 1.

    R = 1.
    R0 = 1.
    r = 0.5

    DA = 1e-4
    DB = 1e-4

    NA = 500
    NB = 500
    mu = 1.

    b0A = nuAb * logi
    d0A = nuAd * logi
    b0B = nuBb * logi
    d0B = nuBd * logi

    thA = 0.005 * logi
    thB = 0.01 * logi

    # b0A = 0.
    # d0A = 0.
    # b0B = 0.
    # d0B = 0.
    #
    # thA = 0.
    # thB = 0.

    # Parameters for the scheme

    L = 7.5
    Nstar = (NA + NB) * np.pi * (R0**2) / (4 * L**2)

    # [x,y]=np.meshgrid(np.arange(-L+dx/2.,L,dx),np.arange(-L+dy/2.,L,dy))
    # X=np.zeros((2,M))
    # X[0,:]=np.reshape(x,(M))
    # X[1,:]=np.reshape(y,(M))

    dt = 0.1
    T = 10001
    Nt = int(T / dt)

    # Initial condition

    [XA0, XB0] = ic.ini_uniform(L, NA, NB)

    XA = XA0
    XB = XB0

    XAmem = [XA0]
    XBmem = [XB0]

    # Time scheme

    for i in range(Nt):
        print(i * dt)
        time_start = time.clock()

        # second membre
        # for A
        argsAA = (KAA, nuAAc, nuAAd, R)
        argsAB = (KAB, nuABc, nuABd, R)
        BA = bw.brownian(DA, NA)
        WA = pt.potential(NA, NB, argsAA, argsAB, XA, XB, i, mu, R, L)

        # for B
        argsBB = (KBB, nuBBc, nuBBd, R)
        argsBA = (KBA, nuBAc, nuBAd, R)
        BB = bw.brownian(DB, NB)
        WB = pt.potential(NB, NA, argsBB, argsBA, XB, XA, i, mu, R, L)

        XAnew = XA + dt * WA + np.sqrt(dt) * BA
        XBnew = XB + dt * WB + np.sqrt(dt) * BB

        # boundary conditions

        XAnew[0, XAnew[0, :] > L] = XAnew[0, XAnew[0, :] > L] - 2 * L
        XAnew[0, XAnew[0, :] < -L] = XAnew[0, XAnew[0, :] < -L] + 2 * L
        XAnew[1, XAnew[1, :] > L] = XAnew[1, XAnew[1, :] > L] - 2 * L
        XAnew[1, XAnew[1, :] < -L] = XAnew[1, XAnew[1, :] < -L] + 2 * L

        XBnew[0, XBnew[0, :] > L] = XBnew[0, XBnew[0, :] > L] - 2 * L
        XBnew[0, XBnew[0, :] < -L] = XBnew[0, XBnew[0, :] < -L] + 2 * L
        XBnew[1, XBnew[1, :] > L] = XBnew[1, XBnew[1, :] > L] - 2 * L
        XBnew[1, XBnew[1, :] < -L] = XBnew[1, XBnew[1, :] < -L] + 2 * L

        # birth and death

        [betaA, deltaA] = bd.bdrate(XAnew, XBnew, R0, b0A, d0A, thA, Nstar, L)
        [betaB, deltaB] = bd.bdrate(XBnew, XAnew, R0, b0B, d0B, thB, Nstar, L)

        betaA = dt * betaA
        deltaA = dt * deltaA
        betaB = dt * betaB
        deltaB = dt * deltaB

        XAnew = bd.birthdeath(XAnew, betaA, deltaA, r)
        XBnew = bd.birthdeath(XBnew, betaB, deltaB, r)

        # updating
        XA = XAnew
        XB = XBnew
        NA = XA.shape[1]
        NB = XB.shape[1]
        print(NA)
        print(NB)

        if i % 50000 == 0:
            # XAmem.append(XA)
            # XBmem.append(XB)
            if not os.path.exists('../data'):
                os.makedirs('../data')
            np.savez('../data/results_A_case_' + str(index) + '_' + str(i),
                     *XA)
            np.savez('../data/results_B_case_' + str(index) + '_' + str(i),
                     *XB)