Esempio n. 1
0
    def module1(self,img):
        '''
            処理の概要
            args :      -> 
            dst  :      -> 
            param:      -> 
        '''

        # 図の準備
        nrow = 2
        ncol = 2
        plt.subplots(nrow, ncol, figsize=(16,7))
        gs = gridspec.GridSpec(nrow,ncol)
        axs = [plt.subplot(gs[i]) for i in range(4) ]

        # 一つ目の図の描画 
        rd.seed(0)
        n = 141
        x = np.linspace(0,140,n) # float64でつくる
        y = rd.exponential(1.5, n) * 300 # 乱数じゃない
        col = ["#2F79B0" for _ in range(n)] # colorの生成
        for i in range(5):    
            y[60+i] = rd.exponential(1.5, 1) * 300 + 2000
            col[60+i] = "r"
        axs[0].scatter(x,y, c=col) #散布図の描画
        axs[0].set_xlim(-5,145)
        axs[0].set_xlabel('time',size=12)

        plt.pause(3)
        plt.show()
Esempio n. 2
0
def homogeneous_process(t, rate):
    r"""Generate a realisation of a Possion process.

    Parameters
    ----------
    t : scalar
        The time length to realise. The events generated are between time 0 and `t`.
    rate : scalar
        The average rate of events.

    Returns
    -------
    events : ndarry
        An array containing the times of the events.
    """

    # Generates the intervals between events from an exponential
    # distribution (until total is time is greater than t) and then
    # perform cumulative sum to find event times. Generates in blocks
    # for efficiency.
    n = int(1.2*rate*t + 1)

    iv = rnd.exponential(1.0/rate, n)

    n = int(0.4*rate*t + 1)
    while (iv.sum() < t):
        ivt = rnd.exponential(1.0/rate, n)
        iv = np.concatenate((iv,ivt))

    ts = np.cumsum(iv)
    maxi = np.searchsorted(ts, [t])
    return ts[:maxi]
Esempio n. 3
0
def update():
    global Occup    
    global t    
    t1=T
    I,J=0,0
    for i in range(0,2):
        for j in range(0,2):
            if Occup[i][j]!=0:
                if i==j:
                    t2=rand.exponential(Lambda[i][j])    
                else:
                    t2=rand.exponential(Lambda[i][j]/Occup[i][j])
                if t2<t1:
                    I,J=i,j
                    t1=t2
#    print t1
    if I==0 and J==0:
        Occup[0][0]=Occup[0][0]-1
        Occup[0][1]=Occup[0][1]+1
    if I==1 and J==1:
        Occup[1][1]=Occup[1][1]-1
        Occup[1][0]=Occup[1][0]+1
    if I==1 and J==0:
        Occup[1][0]=Occup[1][0]-1
        Occup[0][0]=Occup[0][0]+1
    if I==0 and J==1:
        Occup[0][1]=Occup[0][1]-1
        Occup[1][1]=Occup[1][1]+1
    t=t+t1
 def __call__( self, w ) :
     shuffle(self.values)
     move= exponential(self.k) * self.values
     neww = w + move
     while not self.validrange( neww ) :
         shuffle(self.values)
         move= exponential(self.k) * self.values
         neww = w + move
     return neww
Esempio n. 5
0
def rprior(size, hyperparameters):
    """ returns untransformed parameters """
    nu = random.exponential(scale = 1 / hyperparameters["nu_rate"], size = size)
    xi = random.exponential(scale = 1 / hyperparameters["xi_rate"], size = size)
    sigma = random.exponential(scale = 1 / hyperparameters["sigma_rate"], size = size)
    parameters = zeros((3, size))
    parameters[0, :] = nu
    parameters[1, :] = xi
    parameters[2, :] = sigma
    return parameters
def rprior(size, hyperparameters):
    """ returns untransformed parameters """
    xi = random.exponential(scale = 1 / hyperparameters["xi_rate"], size = size)
    omega2 = random.exponential(scale = 1 / hyperparameters["omega2_rate"], size = size)
    lamb = random.exponential(scale = 1 / hyperparameters["lambda_rate"], size = size)
    parameters = zeros((3, size))
    parameters[0, :] = xi
    parameters[1, :] = omega2
    parameters[2, :] = lamb
    return parameters
def rInitDistribution(size):
    """ returns untransformed parameters """
    xi = random.exponential(scale = 1, size = size)
    omega2 = random.exponential(scale = 1, size = size)
    lamb = random.exponential(scale = 1, size = size)
    parameters = zeros((3, size))
    parameters[0, :] = xi
    parameters[1, :] = omega2
    parameters[2, :] = lamb
    return parameters
Esempio n. 8
0
def rprior(size, hyperparameters):
    """ returns untransformed parameters """
    mu = norm.rvs(size = size, loc = hyperparameters["mu_mean"], scale = hyperparameters["mu_sd"])
    beta = norm.rvs(size = size, loc = hyperparameters["beta_mean"], scale = hyperparameters["beta_sd"])
    xi = random.exponential(scale = 1 / hyperparameters["xi_rate"], size = size)
    omega2 = random.exponential(scale = 1 / hyperparameters["omega2_rate"], size = size)
    lamb = random.exponential(scale = 1 / hyperparameters["lambda_rate"], size = size)
    parameters = zeros((5, size))
    parameters[0, :] = mu
    parameters[1, :] = beta
    parameters[2, :] = xi
    parameters[3, :] = omega2
    parameters[4, :] = lamb
    return parameters
Esempio n. 9
0
def sample(n):
  T = DiGraph()
  alive = dict()
  heights = list()
  total = 0.0
  for i in range(n):
    alive[i] = 0.0

  k = n
  while k > 1:
    event = exponential(1.0/binom(k, 2))
    total += event
    heights.append(total)
    for c in alive.keys():
      alive[c] += event

    [a, b] = subset(alive.keys(), 2)
    c = new_node(k)
    alive[a]
    alive[b]
    T.add_edge(a, c, length = alive[a])
    T.add_edge(b, c, length = alive[b])

    del alive[a]
    del alive[b]
    alive[c] = 0.0

    k -= 1

  T.below = collapse(T)
  T.heights = heights

  return T
Esempio n. 10
0
    def _sample_next_reaction(self):
        """
        Use random sampling to select the next reaction and firing time.

        Returns a tuple of (reaction, wait time). The wait time is the duration
        from the current simulation time to the time the next reaction fires.
        It is sampled from an exponential distribution.

        Handles delayed reactions by looking back in the history and using the
        state as it was (delay) time units ago.

        """
        propensities = np.empty((len(self.reactions)))
        for ridx, rxn in enumerate(self.reactions):
            if rxn.delay == 0.0:
                state = self.state
            else:
                state = self.sample_state(
                    self.time - rxn.delay, use_init_state=True)
            propensities[ridx] = rxn.calc_propensity(state)
        prop_csum = np.cumsum(propensities)
        total_prop = prop_csum[-1]
        wait_time = exponential(1.0 / total_prop)
        rxn_selector = random() * total_prop
        for ridx, rxn in enumerate(self.reactions):
            if prop_csum[ridx] >= rxn_selector:
                next_rxn = rxn
                break
        return (next_rxn, wait_time)
Esempio n. 11
0
def MiExponential(rate):
    """Exponential Distribution Function
        rate: Gamma of exp distribution"""
    global manflag
    if not manflag:
        setManual()
    return np.exponential(rate,1) 
Esempio n. 12
0
def simulator_alpha(theta, N=100):
    """
    function that samples form the alpha stable distribution
    theta is np.array([alpha, beta, gamma, delta])
    """
    # unpack values
    #	theta = theta.astype(object)
    alpha = theta[0,:]
    beta =  theta[1,:]
    gamma =  theta[2,:]
    delta =  theta[3,:]
    # add random seed
    random_seed = random.randrange(10**9)
    np.random.seed(seed=random_seed)
    # generate w and u for simulating
    #	pdb.set_trace()
    w = nr.exponential(size=N)
    u = nr.uniform(low=-np.pi/2., high=np.pi/2., size=N)
    #	w = w.astype(float)
    #	u = u.astype(float)
    S_a_b = (1.+ beta**2. * np.tan(np.pi*alpha/2.)**2. )**(1/(2.*alpha))
    B_a_b = 1./alpha * np.arctan(beta*np.tan(np.pi*alpha*0.5))
    if alpha == 1.:
        y_bar = 2./np.pi * ((np.pi/2. + beta*u)*np.tan(u)-beta*np.log(np.pi/2. * w *np.cos(u ) / (np.pi/2. + beta*u)   ) )
    else:
        y_bar = S_a_b * ((np.sin(alpha)*(u + B_a_b ) ) / np.cos(u)**(1./alpha)  ) * (np.cos(u-alpha*(u+ B_a_b ))/w) **((1-alpha)/alpha )

    return S1_summary_statistic_alpha(y_bar*gamma+delta, theta)
Esempio n. 13
0
 def generate_newpath(self, known_first=False):
     t_start = self.t_start
     t_end = self.t_end
     t = t_start
     z = 0
     rate_matrix = copy.deepcopy(self.rate_matrix)
     if not known_first:
         pi0 = self.initial_pi
         s0 = sample_from_Multi(pi0)
         self.s0 = s0
     rate_list = abs(rate_matrix.diagonal())
     S = []
     T = []
     temp_state = self.s0
     while (t + z) < t_end:
         t += z
         current_state = temp_state
         S.append(current_state)
         if t > t_start:
             T.append(t)
         rate = rate_list[current_state]
         z = random.exponential(1.0 / rate)
         beta = rate_matrix[current_state]
         beta[beta < 0] = 0
         temp_state = sample_from_Multi(beta)
     self.S = S
     self.T = T
Esempio n. 14
0
    def sample(self, density, deviation, add_source_point=True, seed=None):

        try: seed = int(seed)
        except: seed = None
        np_random.seed(seed)
        self.sample_seed = seed
        points = set()
        for k, node in self.K.items():
            if node.parent is None: continue
            parent = self.K[node.parent]
            avg_radius = (node.radius + parent.radius) / 2
            axis = node.pos - parent.pos
            surf = 2 * pi * avg_radius * linalg.norm(axis)
            n = int(round(density * surf))
            p1 = parent.pos
            p2 = node.pos
            p = np_random.randn(3)
            r = cross(p-p1, p2-p1)
            r /= linalg.norm(r)
            s = cross(r, p2-p1)
            s /= linalg.norm(s)
            for i in range(n):
                theta = np_random.uniform(0, radians(360))
                d = np_random.uniform() # relative distance of the point, on line between p1 and p2
                t = p1 + d * axis
                interp_radius = (node.radius - parent.radius) * d + parent.radius
                if deviation:
                    interp_radius += np_random.exponential(deviation)
                q = harray([t[0] + interp_radius * cos(theta) * r[0] + interp_radius * sin(theta) * s[0],
                           t[1] + interp_radius * cos(theta) * r[1] + interp_radius * sin(theta) * s[1],
                           t[2] + interp_radius * cos(theta) * r[2] + interp_radius * sin(theta) * s[2]])
                points.add(q)
        if add_source_point:
            points.add((0,-0.01,0))
        self.P = vstack(points)
Esempio n. 15
0
def mixture_process(nu, P, tauc, t):
    '''
    Generate correlated spike trains from a mixture process.
    nu = rates of source spike trains
    P = mixture matrix
    tauc = correlation time constant
    t = duration
    Returns a list of (neuron_number,spike_time) to be passed to SpikeGeneratorGroup.
    '''
    n = array(poisson(nu * t)) # number of spikes for each source spike train
    if n.ndim == 0:
        n = array([n])
    # Only non-zero entries:
    nonzero = n.nonzero()[0]
    n = n[nonzero]
    P = array(P.take(nonzero, axis=1))
    nik = binomial(n, P) # number of spikes from k in i
    result = []
    for k in xrange(P.shape[1]):
        spikes = rand(n[k]) * t
        for i in xrange(P.shape[0]):
            m = nik[i, k]
            if m > 0:
                if tauc > 0:
                    selection = sample(spikes, m) + array(exponential(tauc, m))
                else:
                    selection = sample(spikes, m)
                result.extend(zip([i] * m, selection))
    result = [(i,t*second) for i,t in result]
    return result
Esempio n. 16
0
 def test_exp_1db(self):
     """
     e^-x for x = 0..1 with g(x) = e^-x : alternate dist formulation
     """
     npoints = 2000
     self.run_all(lambda x:x<1.0,npoints,lambda size: exponential(size=(size,1)),
             self.exp_integral(1),self.exp_variance(1))
Esempio n. 17
0
 def interarr(self,s,d,avgtraff,time):
   if float(avgtraff) == 0:
     return self.simdur + 1
   rate = float(avgtraff)/self.flowsize 
   scale = 1.0/rate
   nextarr = rv.exponential(scale,1)
   return nextarr[0] + time
Esempio n. 18
0
def testDrawVarying ():
    #data = np.array ([8,5,4,2])
    data0 = rnd.exponential (10, 30)
    data1 = rnd.triangular (4, 5, 5, 20)
    data2 = rnd.triangular (10,11,11, 10)
    data3 = rnd.triangular (14,14,15, 5)
    data4 = rnd.triangular (0,1,1, 10)
    data = np.concatenate ((data0,data1,data2,data3,data4), axis=0)
    #data = data0

    data = rnd.beta (5,2,1000)
    data = [10 * x for x in data]

    #data0 = rnd.triangular (5, 5, 10, 100)
    #data1 = rnd.triangular (10, 20, 20, 100)
    #data2 = rnd.triangular (20, 21, 21, 0)
    #data = np.concatenate ((data0, data1, data2), axis=0)

    #data = rnd.triangular (0, 10, 15, 200)
    
    data = np.sort (data)
    #data = np.ceil (data, None)
    
    blocks = bucket (data, limit=0.1, depth=3, individualSigma = 2.0, maxExtremas=0, minHeight=0.0)
    draw (data, blocks=blocks)
def make_notes_and_sounds(model, T=SAMPLE_RATE * 1):
    """ generate notes (t samples) from a generative music model

    notes : T x N : |samples| x |notes|
    default |samples| is 10sec

    prototype models
    which notes "n"
    how loud "x"
    what time "t"
    
    doesn't need to sound like music
    but should locally look like music

    note
    note := periodic modes + aperiodic attack
    note : R | {0 1}
    periodic note := sum-of-sines + phase|amplitude noise + decay
    aperiodic note := correlated gaussian noise process
    
    Genarative Model #1
    each time, random chord
    sample next time from gaussian
    sample |notes| from exponential
    TODO sample note duration

    Genarative Model #2
    noise
     add gaussian noise = blur
     swap samples
     if hmm, then observation noise + transition noise variance
    distort pitch
    
    """
    print 'making notes and sounds...'
    X = zeros(T)
    Y = zeros((T, nNOTES))
    T = X.size - AUDIO_SIZE - 1
    over_notes = 0 if A.shape[0]==nNOTES else 1
        
    t = max(0, int(sample.normal(1, 1)*SAMPLE_RATE))
    while t<T:
        Y[t,:] = sample.exponential(0.2, nNOTES)
        Y[t,:][Y[t,:] < 0.5] = 0
        #  randomly zero or real

        X[t:t+AUDIO_SIZE] = sum( Y[t,:] * A , axis=over_notes )
        #  Y weights A along Time
        #  broadcast (1,N) to (AUDIO_SIZE, N)
        #  sum over Notes

        sigma = sample.randint(1,20)
        #  1 sounds the same
        #  100 sounds like nothing
        X[t:t+AUDIO_SIZE] = gaussian_filter(X[t:t+AUDIO_SIZE], sigma)
        
        t += max(1, int(sample.normal(1, 1)*SAMPLE_RATE))
            
    return X,Y
Esempio n. 20
0
 def next(self):
     p = None
     if self.next_tick == self.cur_tick:
         p = Packet(self.cur_tick)
         num = ceil(random.exponential(1/self.lamb, None) * self.multiplier)
         self.next_tick = self.cur_tick + num
     self.cur_tick += 1
     return p
Esempio n. 21
0
 def random(self, point=None, size=None, repeat=None):
     mu, sigma, nu = draw_values([self.mu, self.sigma, self.nu],
                                 point=point)
     return generate_samples(lambda mu, sigma, nu, size=None: nr.normal(mu, sigma, size=size) +
                                 nr.exponential(scale=nu, size=size),
                             mu, sigma, nu,
                             dist_shape=self.shape,
                             size=size)
Esempio n. 22
0
 def test_exp_6d(self):
     """
     e^-(sum(x)) for x = 0..1 with g(x) = e^-(sum(x)) for d=6.
     """
     npoints = 10000
     self.run_all(lambda x:np.all(x<1.0),npoints,
             lambda size:(exponential(size=(size,6))),
             self.exp_integral(6),self.exp_variance(6))
Esempio n. 23
0
 def test_exp_2d(self):
     """
     e^-(x+y) for x,y = 0..1 with g(x) = e^-(x+y)
     """
     npoints = 2000
     self.run_all(lambda xs:xs[0]<1.0 and xs[1]<1.0,npoints,
             lambda size:(exponential(size=(size,2))),
             self.exp_integral(2),self.exp_variance(2))
Esempio n. 24
0
 def next(self):
     p = None
     if self.nextPacket == self.curTime:
         p = Packet(self.curTime)
         num = ceil(random.exponential(1 / self.lamb, None) * self.multiplier)
         self.nextPacket = self.curTime + num
     self.curTime += 1
     return p
Esempio n. 25
0
    def generate_poisson(self, tstart, tend, cadence):
        n=int((tend-tstart)/cadence*2 + 20)

        dts=cadence*nr.exponential(size=n)

        ts=tstart + np.cumsum(dts)

        return ts[ts<tend]
Esempio n. 26
0
 def execute(self, simulator):
     """Generates new customer at given time"""
     print 'new customer at t= ' + str(self.time)
     customer = Customer(simulator.time)
     self.queue.insert(simulator, customer)
     self.time += exponential(4)
     if self.time < self.maxtime:
         simulator.insert(self)
Esempio n. 27
0
    def generate_check_time(self,num_of_bags):
        bag_time = 0

        if num_of_bags == 0:
            return 0
        else:
            for bag in xrange(1,num_of_bags):
                bag_time += npr.exponential(scale=1,size=1)
            return bag_time
Esempio n. 28
0
def defineGroupSizes(n_groups, beta):
	sizes = []
	#sample = pl.randht(n_groups,'cutoff',3,2,1.0/(beta));
	sample = rd.exponential(beta,n_groups)
	for i in sample:
		sizes = sizes + [int(i)]

	print(sizes)
	return sizes
    def Sample(self, count=1):
        return self.DependentSample(count=count)

        samples = random.exponential(np.exp(-self.LogLambda()), count * self.dimension)
        samples = samples * np.sign(random.random(count * self.dimension) - 0.5)
        
        samples = (samples.reshape(count, self.dimension)
                   + self._state[0:self.dimension])
        return samples
def main():
    
    (options, args) = get_parser().parse_args()

    assert int(options.dim) > 0

    seed(int(options.seed) if options.seed else None)
    
    for i in range(int(options.num)):
        print (options.delim.join(["%s" % exponential(float(options.scale)) for x in range(int(options.dim))]))
Esempio n. 31
0
    def sample_hold_time(self, n=1):
        """
        Samples the time to the n^th event

        Homogenous Poisson Process
        -> time to first event is exponential
        -> time to kth event is Erlang (Gamma) distribution 
           -> sum of k exponentials
        """
        if n > 1:
            raise ValueError("I've not done this yet...")
        if self.stationary:
            scale = 1 / self.lambda0
            return npr.exponential(scale=scale, size=1)
        else:
            return self.sample_hold_time_ns(n=1)
Esempio n. 32
0
def person_generator(env, toilet, lam, mu, person_Num=None):
    print('time: %6.2f, start' % env.now)
    i = 0
    if person_Num is None:
        def flag(i):
            return True  # Noneのときは無限母集団として扱う。
    else:
        def flag(i):
            return i < person_Num  # 有限母集団。

    while flag(i):
        # 登場する時間間隔は指数分布
        yield env.timeout(npr.exponential(1.0 / lam, size=1))
        person = Person(env, 'person_%00d' % i, mu)
        i += 1
        env.process(person.behave(toilet))  # シミュレーション環境に実行するプロセスを追加
Esempio n. 33
0
 def _update_business_3__(self, pop, g_best):
     pr = [i / self.pop_size for i in range(1, self.pop_size + 1)]
     for i in range(self.pop_size):
         X_new = deepcopy(pop[i][self.ID_POS])
         for j in range(self.problem_size):
             if random() > pr[i]:
                 i1, i2 = choice(self.pop_size, 2, replace=False)
                 e = exponential(0.5)
                 X1 = pop[i1][self.ID_POS]
                 X2 = pop[i2][self.ID_POS]
                 X_new[j] = X1[j] + e * (X2[j] - pop[i][self.ID_POS][j])
         fit = self.get_fitness_position(position=X_new,
                                         minmax=self.ID_MIN_PROB)
         if fit < pop[i][self.ID_FIT]:
             pop[i] = [X_new, fit]
     return pop
    def __init__(self, sourceId, targetId):
        self.__type = 'Transaction'
        self.id = uuid4()
        self.source = sourceId
        self.target = targetId
        self.date = self._datetime.date(start=2015, end=2019)
        self.time = self._datetime.time()

        if random() < 0.05:
            self.amount = self._numbers.between(100000, 1000000)
        self.amount = npr.exponential(10)

        if random() < 0.15:
            self.currency = self._business.currency_iso_code()
        else:
            self.currency = None
Esempio n. 35
0
def rndFindBlockTime(lamb):
    global adjustCountUnder10
    global adjustCountOver20
    time = nprnd.exponential(1 / lamb)
    mult = 1 + 1 / 2048 * max(1 - time // 10, -99)  # difficult
    if (np.absolute(1 / 2048 * max(1 - time // 10, -99)) > 0.01):
        print(mult)
        tm.sleep(0.1)
    # mult = 1 + 1 / 2048 * max(2 - time // 9, -99) # difficulty
    if (time < 10):
        adjustCountUnder10 += 1
        # print("up"
    elif (time >= 20):
        adjustCountOver20 += 1
    # mult > 1: consensus時間を長くする, mult < 1: consensus時間を短くする
    return lamb / mult
Esempio n. 36
0
def generate_covariates(n, d, n_binary=0, p=0.5):
    """
    n: the number of instances, integer
    d: the dimension of the covarites, integer
    binary: a float between 0 and d the represents the binary covariates
    p: in binary, the probability of 1

    returns (n, d+1)
    """
    # pylint: disable=chained-comparison
    assert n_binary >= 0 and n_binary <= d, "binary must be between 0 and d"
    covariates = np.zeros((n, d + 1))
    covariates[:, : d - n_binary] = random.exponential(1, size=(n, d - n_binary))
    covariates[:, d - n_binary : -1] = random.binomial(1, p, size=(n, n_binary))
    covariates[:, -1] = np.ones(n)
    return covariates
Esempio n. 37
0
    def simulate():
        runtimes = npr.choice(task_times, size=remaining_tasks)
        runtimes = np.concatenate(
            (current_predictions, npr.exponential(runtimes)))

        schedules = []
        for t in runtimes[:parallelism]:
            heapq.heappush(schedules, t)

        clock = 0.0

        for t in runtimes[parallelism:]:
            clock = heapq.heappop(schedules)
            heapq.heappush(schedules, t + clock)

        return max(schedules)
Esempio n. 38
0
    def sampleDiffShare(self, t, tau):
        while(True):
            sum_u = self.intensity(
                t, skip_last_share=False) - self.intensity(t, skip_last_share=True)
            # If the intensity is zero return a large time.
            if sum_u < np.finfo(float).eps:
                return self.T + np.finfo(float).eps
            t_ = random.exponential(1.0 / sum_u)
            t = t_ + t
            if t > tau:
                return tau
            new_u = self.intensity(
                t, skip_last_share=False) - self.intensity(t, skip_last_share=True)

            if random.uniform() * sum_u < new_u:
                return t
Esempio n. 39
0
def sample_edges(z, out_strength, in_strength):
    s_tot = max(np.sum(out_strength.value), np.sum(in_strength.value))
    sample = []
    for i in np.arange(len(out_strength)):
        ind_out = out_strength[i].id
        s_out = out_strength[i].value
        for j in np.arange(len(in_strength)):
            ind_in = in_strength[j].id
            s_in = in_strength[j].value
            if ind_out != ind_in:
                p = p_fit(z, s_out, s_in)
                if rng.random() < p:
                    w = np.float64(rng.exponential(s_out * s_in / (s_tot * p)))
                    sample.append((ind_out, ind_in, w))

    return sample
Esempio n. 40
0
    def sample(self, skip_last_share=False):
        while (True):
            sum_u = self.intensity(self.t, skip_last_share=skip_last_share)

            # If the intensity is zero return a large time.
            if sum_u < np.finfo(float).eps:
                self.t = self.T
                return self.T + np.finfo(float).eps
            t_ = random.exponential(1.0 / sum_u)
            self.t = t_ + self.t
            if self.t > self.T:
                self.t = self.T
                return self.T
            new_u = self.intensity(self.t, skip_last_share=skip_last_share)
            if random.uniform() * sum_u < new_u:
                return self.t
Esempio n. 41
0
    def _SSA_single_simulation(self, final_time, time_stamp, model_dimension,
                               trans_number):
        """
        A single SSA simulation run, returns the value of observables

        :param final_time: final simulation time
        :param time_stamp: time array containing time points to save
        :param model_dimension: dimension of the model
        :param trans_number: transitions' number
        :return: the observables computed along the trajectory
        """
        # tracks simulation time and state
        time = 0
        state = self.x0
        # tracks index of the time stamp vector, to save the array
        print_index = 1
        x = np.zeros((len(time_stamp), model_dimension))
        # save initial state
        x[0, :] = self.x0
        # main SSA loop
        trans_code = range(trans_number)
        while time < final_time:
            # compute rates and total rate
            rates = self.model.evaluate_rates(state)
            # sanity check, to avoid negative numbers close to zero
            rates[rates < 1e-14] = 0.0
            total_rate = sum(rates)
            # check if total rate is non zero.
            if total_rate > 1e-14:
                # if so, sample next time and next state and update state and time
                trans_index = rnd.choice(trans_number, p=rates / total_rate)
                delta_time = rnd.exponential(
                    1 / (self.model.system_size * total_rate))
                time += delta_time
                state = state + self.model.transitions[
                    trans_index].update.flatten() / self.model.system_size
            else:
                # If not, stop simulation by skipping to final time
                time = final_time
            # store values in the output array
            while print_index < len(
                    time_stamp) and time_stamp[print_index] <= time:
                x[print_index, :] = state
                print_index += 1
        # computes observables
        y = self._compute_observables(x)
        return y
Esempio n. 42
0
    def __init__(self, tempdir):
        np.random.seed(42)
        self.tmp_dir = tempdir
        p = Path(self.tmp_dir)
        self.ns = 100
        self.nc = 10
        self.nt = 5
        self.ncd = 1000
        np.save(p / 'spike_times.npy',
                .01 * np.cumsum(nr.exponential(size=self.ns)))
        np.save(p / 'spike_clusters.npy',
                nr.randint(low=0, high=self.nt, size=self.ns))
        shutil.copy(p / 'spike_clusters.npy', p / 'spike_templates.npy')
        np.save(p / 'amplitudes.npy',
                nr.uniform(low=0.5, high=1.5, size=self.ns))
        np.save(p / 'channel_positions.npy', np.c_[np.arange(self.nc),
                                                   np.zeros(self.nc)])
        np.save(p / 'templates.npy',
                np.random.normal(size=(self.nt, 50, self.nc)))
        np.save(p / 'similar_templates.npy',
                np.tile(np.arange(self.nt), (self.nt, 1)))
        np.save(p / 'channel_map.npy', np.c_[np.arange(self.nc)])
        np.save(p / 'channel_probe.npy', np.zeros(self.nc))
        _write_tsv_simple(p / 'cluster_group.tsv', 'group', {
            2: 'good',
            3: 'mua',
            5: 'noise'
        })
        _write_tsv_simple(
            p / 'cluster_Amplitude.tsv',
            field_name='Amplitude',
            data={str(n): np.random.rand() * 120
                  for n in np.arange(self.nt)})
        with open(p / 'probes.description.txt', 'w+') as fid:
            fid.writelines(['label\n'])

        # Raw data
        self.dat_path = p / 'rawdata.npy'
        np.save(self.dat_path, np.random.normal(size=(self.ncd, self.nc)))

        # LFP data.
        lfdata = (100 * np.random.normal(size=(1000, self.nc))).astype(
            np.int16)
        with (p / 'mydata.lf.bin').open('wb') as f:
            lfdata.tofile(f)

        self.files = os.listdir(self.tmp_dir)
def simulateHawkesProcess(params):
    """  
		Input :  params = (T,lambda0,alpha,beta)
				 
							T      : Time Horizon of simulation.
							lambda0: Base intensity.
							alpha  : the stretch parameter of function g.
							beta   : the decaying parameter of function g

							"g(x) = alpha*exp(-beta*x)"
	

		Output:  jumpTimes: an array containing the jump times of Hawkes process
    """
    
    T,lambda0,alpha,beta = params
    currentInstant = 0            # the current generated instant.
    numberOfInstants = 0          # the current number of jumps.
    lambdaUpperBound = lambda0    # the current upper bound for lambda_t for thining algorithm
    jumpTimes = []                # a list of accepted instants (jumpTimes)
    
    
    

    while(currentInstant<T):

        jumpGapWidth = npr.exponential(1/lambdaUpperBound)
        currentInstant += jumpGapWidth
        D = npr.uniform(0,1)
        intensityOfNewPoint = lambda0 + np.exp(-beta*jumpGapWidth)*(lambdaUpperBound-lambda0)

        if(lambdaUpperBound*D<=intensityOfNewPoint):
           
            
            lambdaUpperBound = intensityOfNewPoint + alpha    
            numberOfInstants+=1
            jumpTimes.append(currentInstant)

        else:
            
            lambdaUpperBound = intensityOfNewPoint
  
    if(jumpTimes[-1]>T):
    	jumpTimes.pop()

    	
    return np.array(jumpTimes)
Esempio n. 44
0
    def reset_board(self):

        # Create Snakes
        self.master_snake = Snake(self.BOARD_SIZE, self.M)
        self.enemy_snake = Snake(self.BOARD_SIZE, self.M)
        self.COUNTER = 0
        self.ENEMY_COUNTER = 0

        # Create Board
        self._state = [([[0, 0, 0, 0, 0]] * self.BOARD_SIZE)
                       for i in range(self.BOARD_SIZE)]
        self._enemy_state = [([[0, 0, 0, 0, 0]] * self.BOARD_SIZE)
                             for i in range(self.BOARD_SIZE)]
        self._episode_ended = False
        master_init_x_coord, master_init_y_coord = self.master_snake.get_path_coords(
        )
        enemy_init_x_coord, enemy_init_y_coord = self.enemy_snake.get_path_coords(
        )

        self._state[master_init_y_coord[0]][master_init_x_coord[0]] = [
            self.M, 0, self.M, 0, 0
        ]
        self._state[enemy_init_y_coord[0]][enemy_init_x_coord[0]] = [
            0, 0, 0, 0, self.M
        ]
        self._enemy_state[master_init_y_coord[0]][master_init_x_coord[0]] = [
            0, 0, 0, 0, self.M
        ]
        self._enemy_state[enemy_init_y_coord[0]][enemy_init_x_coord[0]] = [
            self.M, 0, self.M, 0, 0
        ]

        # Special case for food spawn 0
        if (self.FOOD_SPAWN_MODE == 0):
            self.food_spawn_arr = np.ceil(exponential(5, size=100))
            self.current_food_spawn = 0  #current index of above array
            self.food_timer = 0
        # Special case for food spawn 1
        elif (self.FOOD_SPAWN_MODE == 1):
            self.foodspawn_assist()

        # Set if snake ate during previous turn, which is true for first spawn
        self.master_snake.set_just_eaten(True)
        self.enemy_snake.set_just_eaten(True)

        self.__dict__.pop('ENEMY_POLICY', None)
        self.ENEMY_POLICY = self.MASTER_ENEMY_POLICY
Esempio n. 45
0
def cindep(n, d):
    beta = 10
    p = 0.5
    exp_dist = rnd.exponential(scale=beta, size=n)
    pois_dist = list()
    binom_dist = list()
    for itr in exp_dist:
        pois = rnd.poisson(itr, size=1)[0]
        pois_dist.append(pois)
        binom_dist.append(rnd.binomial(pois, p, size=1)[0])
    dat = {'exp': exp_dist, 'binom': binom_dist, 'pois': pois_dist}
    for itr in range(d - 1):
        dat[str(itr)] = rnd.normal(0, 1, n)
    df = pd.DataFrame(data=dat)
    info = 0
    name = 'Variables Mixed and Conditionally Independent'
    return df, info, name
Esempio n. 46
0
def eulerMascheroni():
    gamma = 0
    gamma1 = 0
    beta = uniform(5, 100)
    A = []
    while True:
        k = int(exponential(beta)) + 1
        print(k, gamma, gamma1, len(A))
        if k in A: pass
        else:
            gamma = gamma + 1 / k
            A.append(k)
            if len(A) >= 250: break
        gamma1 = gamma
    n = max(A)
    gamma = gamma - log(n)
    return (n, gamma)
Esempio n. 47
0
 def getoneimg(self):
     self.img[:, :] = 20.0
     # get points
     Np = rd.poisson(self.nnp)
     pti = rd.randint(0, 1000, Np)
     #xp = self.xps[pti]
     #yp = self.yps[pti]
     xp = self.xcntr
     yp = self.ycntr
     zp = self.zps[pti]
     #Ip = rd.poisson(self.iip,Np) #[self.iip]
     Ip = rd.exponential(self.iip, Np)
     # create psfs
     for m in range(Np):
         self.addpsf(xp, yp, zp[m], Ip[m])
     # noise
     self.img = rd.poisson(self.img)
Esempio n. 48
0
def confirm(block_id, chunk_ids):
    print("Confirming block", block_id, "with chunks:", chunk_ids)
    if BETA:
        time.sleep(random.exponential(BETA))
    url = "{}/api/block/{}".format(config.BASE_URL, block_id)
    owner = config.OWNER
    r = requests.post(url,
                      json={
                          'block_id': block_id,
                          'chunks': chunk_ids,
                          'owner': owner
                      })
    if r.status_code == 200:
        print("Confirmed:", block_id)
    else:
        print("Rejected:", block_id, r.status_code, r.text)
    return r.status_code
Esempio n. 49
0
    def createPackets(self, cs):
        '''You must complete this method. This method generates and creates packets as per the
            arrival rate distribution defined'''
        i = 0
        while True:

            ##
            if args.type == 'MM1' or args.type == 'MM2':
                yield hold, self, exponential(Parameters.arrivals_poisson)
            ##
            else:
                yield hold, self, uniform(Parameters.interarrivalTimeMin,
                                          Parameters.interarrivalTimeMax)
            packet_name = "Packet " + str(i)
            p = Packet(name=packet_name)
            activate(p, p.behavior_of_single_packet(cs))
            i = i + 1
Esempio n. 50
0
def build_chunglu_graph(N,
                        exp_val,
                        fn_edges=[
                            lambda G, x, y: npr.exponential(2),
                            lambda G, x, y: np.abs(npr.normal(0, 1))
                        ],
                        directed=True,
                        self=False):
    A = nx.expected_degree_graph(
        [np.round(v) for v in truncated_power_law(N, exp_val)], selfloops=self)
    A.remove_nodes_from(list(nx.isolates(A)))
    A = nx.relabel_nodes(A,
                         {k: v
                          for k, v in zip(A.nodes, range(len(A.nodes)))})
    A = nx.DiGraph(A)

    return networkx_wrapper(A, self=self, directed=directed, fn_edges=fn_edges)
Esempio n. 51
0
def generate_usage_log_data(Model, n=100):
    _names = ['andy', 'betty', 'bobby', 'timmy', 'sue']
    _imagetypes = ['Python', 'Python+R']
    _numgpus = [0, 1, 2, 3, 4]
    containers = []

    for i in range(n):
        td_start = timedelta(days=i % 30, hours=random.randint(0, 23))
        start = datetime.utcnow() - td_start
        instance = Model(id=secrets.token_hex(32),
                         username=random.choice(_names),
                         image_type=random.choice(_imagetypes),
                         num_gpus=random.choice(_numgpus),
                         start_time=start,
                         stop_time=start + timedelta(hours=exponential(8)))
        containers.append(instance)

    return containers
Esempio n. 52
0
def play(n, hist, lw, lc, y):

    # Needed to access the global variables
    global sumlw, games
    games += 1

    # On the first game, we can't calculate a mean of previous wins, so just
    # guess zero
    if (games == 0):
        sumlw = lw
        return 1

    # On subsequent games, calculate the mean of the previous wins, rounded to
    # the nearest integer
    sumlw += lw
    mean_lw = sumlw / games
    #return the nearest int from an exponential distribution sample with mean of all winners in previous rounds
    return int(nprnd.exponential(mean_lw) + 0.5)
Esempio n. 53
0
def fit_sample(p_f, param, out_strength, in_strength):
    """ Sample from the fitness model ensemble.
    """
    s_tot = np.sum(out_strength)
    msg = 'Sum of in/out strengths not the same.'
    assert np.abs(1 - np.sum(in_strength)/s_tot) < 1e-6, msg
    sample = []
    for i in np.arange(len(out_strength)):
        s_out = out_strength[i]
        for j in np.arange(len(in_strength)):
            s_in = in_strength[j]
            if i != j:
                p = p_f(param, s_out, s_in)
                if rng.random() < p:
                    w = np.float64(rng.exponential(s_out*s_in/(s_tot*p)))
                    sample.append((i, j, w))

    return sample
    def put_arrival(self, router_idx, packet_idx):
        """
        Put a MType.ARRIVAL event into router event queue
        :param router_idx: index of a router in which event should be put
        :param packet_idx: index of a packet
        """
        if router_idx == 0:  # if it is the first router we have to make a new packet
            t = self.time + exponential(1/self.lambd)
            packet = MopsPacket(len(self.packet_list), len(self.routers))
            packet.times[router_idx][MType.ARRIVAL] = t
            self.packet_list.append(packet)
            e = MopsEvent(t, event_type=MType.ARRIVAL, packet_idx=packet.packet_idx, router_idx=router_idx)
        else:  # otherwise just send existing packet to the next router
            t = self.packet_list[packet_idx].times[router_idx - 1][MType.END_SERVICE]
            e = MopsEvent(t, event_type=MType.ARRIVAL, packet_idx=packet_idx, router_idx=router_idx)
            self.packet_list[packet_idx].times[router_idx][MType.ARRIVAL] = t

        self.event_queue.put((t, e))
Esempio n. 55
0
def sim_occurrences(tree, r):
    occurrences = {}
    for i in tree.iternodes():
        if i.istip:
            cur_length = i.length
            occurrences[i.label] = []
            i.old_length = i.length
            while (cur_length > 0):
                cur_length -= exponential(r)
                cur_time = i.height + cur_length
                if cur_length > 0:
                    occurrences[i.label].append(cur_time)
            if len(occurrences[i.label]) == 0:
                occurrences[i.label].append(i.height)
            elif i.height == 0.:
                occurrences[i.label].append(i.height)
            i.length = i.old_length
    return occurrences
Esempio n. 56
0
def gen_rnd_sequence(N_sekv, N_realiz, tip, mean=0, std=1):
    if tip == 'uniform':
        return rnd.uniform(mean - std * sqrt(3), mean + std * sqrt(3),
                           (N_realiz, N_sekv))
    elif tip == 'exponential':
        return rnd.exponential(std, (N_realiz, N_sekv))
    elif tip == 'normal':
        return rnd.normal(mean, std, (N_realiz, N_sekv))
    elif tip == 'normal_converging_var':
        X_n = empty((N_realiz, N_sekv))
        for j in range(N_sekv):
            X_n[:, j] = rnd.normal(mean, std * (1 - exp(-(j + 1))), N_realiz)
        return X_n
    elif tip == 'normal_diverging_var':
        X_n = empty((N_realiz, N_sekv))
        for j in range(N_sekv):
            X_n[:, j] = rnd.normal(mean, std * (j + 1), N_realiz)
        return X_n
Esempio n. 57
0
def gen_samples(data, s, samples, num):

    y = np.zeros(samples)

    a = np.random.randint(4, samples - (s + 4))
    x = data

    signal_std = x.std()
    noize_std = signal_std / np.power(10, d / 20)
    a = (noize_std * np.sqrt(12)) / 2

    if num == 1:
        n = (r.uniform(-a, a, size=s) + r.normal(0, noize_std, size=s) +
             r.exponential(noize_std, size=s))
        x[a:a + s] = x[a] + n
        y[a:a + s] = 1

    return x, y
def arrival():
    """
    Simulates the arrival of a car. 
    Cars arrive according to a Poisson process wite rate r.  
    The time between subsequent arrivals are i.i.d. exponential random variables with mean 1.0 / r
    """
    global arrival_count, env, light, queue
    while True:
        arrival_count += 1
        if light == 'red' or len(queue): # new car joins queue
            queue.append((arrival_count, env.now))
            print("Car #%d arrived and joined the queue at position %d at time "
               "%.3f." % (arrival_count, len(queue), env.now))
        else:
            print("Car #%d arrived to a green light with no cars waiting at time "
           "%.3f." % (arrival_count, env.now))
            W_stats.count+= 1
        yield env.timeout( random.exponential(1.0 / ARRIVAL_RATE)) # schedule next arrival
Esempio n. 59
0
 def setUp(self):
     self.tmp_dir = tempfile.TemporaryDirectory()
     p = Path(self.tmp_dir.name)
     self.ns = 100
     self.nc = 10
     self.nt = 5
     np.save(p / 'spike_times.npy', np.cumsum(nr.exponential(size=self.ns)))
     np.save(p / 'spike_clusters.npy',
             nr.randint(low=0, high=10, size=self.ns))
     np.save(p / 'amplitudes.npy',
             nr.uniform(low=0.5, high=1.5, size=self.ns))
     np.save(p / 'channel_positions.npy', np.c_[np.arange(self.nc),
                                                np.zeros(self.nc)])
     np.save(p / 'templates.npy',
             np.random.normal(size=(self.nt, 50, self.nc)))
     np.save(p / 'channel_map.npy', np.c_[np.arange(self.nc)])
     np.save(p / 'rawdata.npy', np.random.normal(size=(1000, self.nc)))
     self.files = os.listdir(self.tmp_dir.name)
Esempio n. 60
0
def simulate_time_rescaling(runtime,
                            kernel=functions.kernel_zhao,
                            p=functions.infectious_rate_tweets,
                            dt=0.01,
                            follower_pool=None,
                            int_fol_cnt=10000,
                            follower_mean=200,
                            split=0.015):
    """
    Simulates time dependent Hawkes process using time rescaling.

    Follower counts can be taken from a pool passed to the function or generated.

    :param runtime: time to simulate (in hours)
    :param kernel: kernel function
    :param p: infectious rate function
    :param dt: integral evaluation interval size
    :param follower_pool: follower counts used for simulation, makes last 3 parameters void
    :param int_fol_cnt: initial follower value
    :param follower_mean: mean of generated followers
    :param split: percentage for when the follower should be generated very big
    :return: list of event tuples
    """
    events = [(0, int_fol_cnt)]
    ti = 0
    print_cnt = 0

    while 0 <= ti < runtime and len(events) < 4500:
        X = rand.exponential()
        tj = solve_integral(ti, X, kernel, p, events, dt, runtime)
        if follower_pool is not None:
            fol = rand.choice(follower_pool)
        else:
            fol = rand_followers_extended(int_fol_cnt, follower_mean, split)
        if tj > 0:
            events.append((tj, fol))
        ti = tj
        if print_cnt % 100 == 0:
            print("Simulating [%f%%]..." % (ti / runtime * 100), flush=True)
        print_cnt += 1

    print("\nOver %d events generated" % len(events))

    return events