示例#1
0
def train(net_params, optimizer, pool):
    noise_seed = rng().integers(0, 2**32 - 1, size=POP_SIZE // 2).repeat(2)
    jobs = [
        pool.apply_async(get_reward,
                         (net_params, env, [noise_seed[k_id], k_id]))
        for k_id in range(POP_SIZE)
    ]
    rewards = np.array([j.get() for j in jobs])
    gradients = optimizer.gradients(rewards, noise_seed)

    return net_params + LR * gradients, rewards
    def __init__(self, update_port, update_rate=0.01, sync_port, num_params):
        # Init TCP server
        self.upd_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sync_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        self.update_port = update_port
        self.sync_port = sync_port

        self.update_rate = update_rate

        self.params = rng(size=num_params) * 1e-2
示例#3
0
def evolve(env, genotype, opt, pool):
    seeds = rng().integers(0, 2 ** 32 - 1, size=POP_SIZE//2).repeat(2)

    jobs = [
        pool.apply_async(eval_mutant, (env, genotype, m_id, seeds[m_id]))
        for m_id in range(POP_SIZE)
    ]
    rewards = np.array([j.get() for j in jobs])

    grad = opt.get_gradient(seeds, rewards)
    genotype += LR * grad
示例#4
0
def randNS(detector,redshiftSampler):
    cosTh=rng()*2 -1
    Theta=np.arccos(cosTh)
    Phi=2*np.pi*rng()
    cosIo=rng()*2 -1
    Iota=np.arccos(cosIo)
    Psi=2*np.pi*rng()
    M=randMass()
    randomZ=redshiftSampler()
    Dl=D_L(randomZ)  
    if(detector=='AdLigoDesign'):
        A=AdLigoDesign(M*(1+randomZ))
    elif(detector=='AdLigoH1'):
        A=AdLigoH1(M*(1+randomZ))
    elif(detector=='ET'):
        A=ET(M*(1+randomZ))
    else:
        print('zly detector:', detector)
        return 0
    return (SNR(Dl,Theta,Phi,Psi,Iota,A) ,Dl,M,randomZ,Theta,Phi,Psi,Iota)
def Random_Walk(number_steps):  # our function that does all the work
    # you could say this is the workhorse of the program
    # it takes the random walks for us so we don't have to and can stay inside, never to walk again
    # our random walk generates arrays of positions, not arrays of steps
    # this is important and means that we do not need to sum over slices of an array later to generate paths
    x = np.zeros(number_steps)  # create a null array for x positions
    y = np.zeros(number_steps)  # create a null array for y positions
    x_samples = rng(
        number_steps)  # generate 1000 random floats between 0 and 1
    y_samples = rng(
        number_steps)  # generate 1000 random floats between 0 and 1

    x_sum = 0  # set the final x position to zero
    # x_sum will be the sum of all movements in the x direction so that the end result is the final x value
    y_sum = 0  # set the final y position to zero
    # y_sum will be the sum of all movements in the y direction so that the end result is the final y value

    for i in range(
            1, number_steps
    ):  # we use a parameter for the range so we can change it easier
        if x_samples[
                i] < 0.5:  # if x_samples[i] is heads, move +1 in x direction
            x[i] = x[i - 1] + 1  # move +1 in the x direction
            x_sum += 1  # I add one to the sum of x movements
        else:  # if x_samples[i] is tails, move -1 in the x direction
            x[i] = x[i - 1] - 1  # move -1 in the x direction
            x_sum -= 1  # I subtract one from the sum of the x movements

        if y_samples[
                i] < 0.5:  # if y_samples[i] is heads move +1 in the y direction
            y[i] = y[i - 1] + 1  # move +1 in the y direction
            y_sum += 1  # I add one to the sum of the y movements
        else:  # if y_samples[i] is tails move -1 in the y direction
            y[i] = y[i - 1] - 1  # move -1 in the y direction
            y_sum -= 1  # I subtract one from the sum of the y movements

    distance = np.sqrt(
        x_sum**2 +
        y_sum**2)  # find the displacement from the origin for the walk

    return x, y, distance  # return the x positions, y positions, and displacement
示例#6
0
def write_fox(qs=qNom, name=None, directory=FOX_DIR, fox_file='SEC_neutrons_WF_14m_v1.fox'):
    # how many magnets to set
    input_len = len(qs)
    # if less than qNom, use qNom values (0) for remainder
    if (len(qNom)-input_len>0):
        for i in range(len(qNom)-input_len):
            qs = append(qs,qNom[i+input_len])
    # get rand number for the temporary file
    if name==None:
        rand = rng()
    else:
        rand = name
    # get the fox file for the simulation and change the qvalues
    cosy_input = FOX_DIR + fox_file
    text = None
    with open(cosy_input, 'r') as f:
        text = f.readlines()

    start_line = 0 
    # find where in the file to change
    for i in range(len(text)):
        # dummy text line in the fox file that the code searches for to find the qvalue setting
        if "SET MAGNETS" in text[i]:
            start_line = i+1
#            print(text[i], text[start_line])
    # change the q setttings
    for i in range(len(qs)):
        text[i+start_line] = "Q{0}_SC:= {1};\n".format(i+1,qs[i])

    # temporary output file
    cosyFilename = directory + 'pygmoCosy'+str(rand)+'.fox'
    # if by some ridiculous chance we pick the same number as another iteration, find new number
    while os.path.exists(cosyFilename):
        rand = rng()
        cosyFilename = directory + 'pygmoCosy'+str(rand)+'.fox'
    lisFilename = directory + 'pygmoCosy'+str(rand)+'.lis'
    # write out the fox file
    with open(cosyFilename, 'w') as f:
        f.writelines(text)
    # return filenames for cosy to find
    return cosyFilename, lisFilename
示例#7
0
  def generate_patch_info(self, shape_type, sizx, sizy, ori):
    max_s   = int(2*max(sizx, sizy))
    patch   = np.zeros((max_s, max_s))
    patch_0 = None

    if shape_type == 'ellipse':
      center = (patch.shape[0]//2, patch.shape[1]//2)
      radius = (sizy/2, sizx/2) 
      rr, cc = ellipse(center[0], center[1], radius[0], radius[1], shape=patch.shape)
      patch[rr, cc] = 255
    elif shape_type == 'rectangle':
      start  = (int(max_s - sizy//2, int(max_s - sizx)//2))
      extent = (int(sizy), int(sizx))
      rr, cc = rectangle(start=start, extent=extent, shape=patch.shape)
      patch[rr, cc] = 255
    if shape_type == 'vernier':
      patch_0 = np.zeros((max_s, max_s))  # patch with zero offset
      
      v_siz_w = rng().uniform(1 + sizx//6, 1 + sizx//2)
      v_siz_h = rng().uniform(1 + sizy//4, 1 + sizy//2)
      v_off_w = rng().uniform(1,              1 + (sizx - v_siz_w)//2)*2
      v_off_h = rng().uniform(1 + v_siz_h//2, 1 + (sizy - v_siz_h)//2)*2

      start1     = (int((max_s - v_off_h - v_siz_h)//2), int((max_s - v_off_w - v_siz_w)//2))
      start2     = (int((max_s + v_off_h - v_siz_h)//2), int((max_s + v_off_w - v_siz_w)//2))
      start01    = (int((max_s - v_off_h - v_siz_h)//2), int((max_s - 0       - v_siz_w)//2))
      start02    = (int((max_s + v_off_h - v_siz_h)//2), int((max_s + 0       - v_siz_w)//2))
      extent     = (int(v_siz_h), int(v_siz_w))
      rr1,  cc1  = rectangle(start=start1,  extent=extent, shape=patch.shape)
      rr2,  cc2  = rectangle(start=start2,  extent=extent, shape=patch.shape)
      rr01, cc01 = rectangle(start=start01, extent=extent, shape=patch.shape)
      rr02, cc02 = rectangle(start=start02, extent=extent, shape=patch.shape)
      patch[  rr1,  cc1 ] = 255
      patch[  rr2,  cc2 ] = 255
      patch_0[rr01, cc01] = 255
      patch_0[rr02, cc02] = 255

    patch  = rotate(patch, ori).astype(int)
    patch_info = [patch, np.fliplr(patch), patch_0]

    return patch_info
示例#8
0
def Initialize():
    x0 = [XPOS0, VX0]
    y0 = [YPOS0, VY0]
    
    PvCB = rand.choice([0,1])          #0 = paper, 1 = cardboard
    theta = ((rng(1)[0]+0.001)*3.14)/9 #theta varies between approximately 
                                       #0 degrees and 10 degrees
    
    if PvCB == 0:                #If paper
        i = (rng(1)[0]+0.1)*.594 #i ranges between 0.0594m and 0.594m
        j = (rng(1)[0]+0.1)*.841 #j ranges between 0.0841m and 0.841m
        area = i*j               #Area of the paper
        s= np.sqrt(i*i+j*j)      #Diagonal of the paper
        height = .000005         #Height of paper is 0.05mm
        mass = DENSITY_PAPER * height * area
        #Numerically integrate XAccel and YAccel to find x(t) and y_p(t)
        x = odeint(XAccel, x0, t, args=(mass, area, PvCB, theta))    
        y_p = odeint(YAccel_p, y0, t, args=(mass, area, s, PvCB, theta))
        return [x, y_p, PvCB]
    
    else:                           #If cardboard
        i = (rng(1)[0]+0.001)*1.219 #i ranges between 0.1219m and 1.219m
        j = (rng(1)[0]+0.001)*.457  #j ranges between 0.0457m and 0.457m
        area = i*j                  #Area of the cardboard
        s= np.sqrt(i*i+j*j)         #Diagonal of the cardboard
        height = ((rng(1)[0]* 0.0045) + 0.0015) #Height of cardboard ranges 
                                                #between 0.0015m and 0.006m
        mass = DENSITY_CB * height * area
        #Numerically integrate XAccle and YAccel to find x(t) and y_c(t)
        x = odeint(XAccel, x0, t, args=(mass, area, PvCB, theta))
        y_c = odeint(YAccel_c, y0, t, args=(mass, area, s, PvCB, theta))
        return [x, y_c, PvCB]
示例#9
0
def diffusion_confined_space(num_steps, num_walkers):
    """
    Generating the random walk data, for statistically
    independent random variables. This for a 2D random walk.

    The two arrays, x_coord and y_coord,
    contain only the particles in the
    specified coordinates: contrained to -100 to 100 for both axes
    (i.e 200X200 coordinate system--square lattice).

    """
    # to store x position for all the walkers
    x_coord = np.zeros((num_walkers, num_steps))

    # to store y position for all the walkers
    y_coord = np.zeros((num_walkers, num_steps))

    for j in range(num_walkers):

        # generate random steps +/- 1
        x = (2 * (rng(num_steps) > 0.5) - 1).cumsum()
        # generate random steps +/- 1
        y = (2 * (rng(num_steps) > 0.5) - 1).cumsum()

        #store data
        x_coord[j, :] = x

        #store data
        y_coord[j, :] = y

    #fills all values outside boundary with np.nan
    for i in range(num_walkers):
        for j in range(num_steps):
            if 100<x_coord[i,j] or x_coord[i,j]<-100 or\
            100<y_coord[i,j] or y_coord[i,j]<-100:
                x_coord[i, j] = np.nan
                y_coord[i, j] = np.nan

    #return variables for plotting
    return x_coord, y_coord, num_steps, num_walkers
示例#10
0
        def move_random(self):
            """Literaly move in a random formation"""
            from numpy.random import randint as rng
            direction = ["up", "down", "left", "right"]
            direction_choice = direction[int(rng(low = 0, high = len(direction)))]

            if direction_choice == "up":
                self.move_up()
            elif direction_choice == "down":
                self.move_down()
            elif direction_choice == "right":
                self.move_right()
            else:
                self.move_left()
示例#11
0
文件: 5.2.py 项目: wmh001/learning
def get_trajectory(num_steps):
    x_steps = np.ones(num_steps)
    y_steps = np.ones(num_steps)
    for i in range(0, num_steps):
        if (rng() < 0.5):
            x_steps[i] = -1
        else:
            x_steps[i] = 1
        if (rng() < 0.5):
            y_steps[i] = -1
        else:
            y_steps[i] = 1
    # 累加前k项
    X_steps = np.cumsum(x_steps)
    Y_steps = np.cumsum(y_steps)
    plt.figure()
    ax = plt.gca()
    ax.set_title("bulangyundong", size=24, weight='bold')
    ax.set_xlabel("X")
    ax.set_ylabel("Y")
    plt.axis('equal')
    plt.plot(X_steps, Y_steps)
    plt.show()
示例#12
0
  def __init__(self, set_type, objects, batch_s, scl, n_frames, c, wn_w, wn_h, grav, pop_t=0, random_start_pos=False, random_start_speed=False, random_size=False):
    super().__init__(objects, batch_s, scl, n_frames, wn_w, wn_h, grav, random_start_pos, random_start_speed, random_size)

    # Select object static and dynamic properties
    choices    = ['vernier'] # type of object that appears in frames
    self.ori   = np.ones((1, batch_s))*0.0 # orientation (rotation)
    self.colr  = np.ones((c, batch_s), dtype=int)*255 # color
    self.pop_t = np.ones((1, batch_s), dtype=int)*pop_t # frame where object appears and seed offset takes place

    self.shape  = rng().choice(choices, (1, batch_s))
    self.side   = rng().randint(0, 2, (1, batch_s)) if len(objects) == 0 else objects[0].side
    self.side_  = 1*self.side                   # evolving value for sqm (deep copy)
    self.popped = np.array([[False]*batch_s])   # display stimulus or not
    self.sizx[self.shape == 'vernier'] /= 1.5   # verniers look better if not too wide
    self.sizy[self.shape == 'vernier'] *= 2.0   # verniers appear smaller than other shapes
    self.pos    = np.vstack((self.x,   self.y))
    self.vel    = np.vstack((self.vx, self.vy))
    self.acc    = np.array([[0.00]*batch_s, [grav]*batch_s])

    # Generate patches to draw the shapes efficiently
    self.patches = []
    for b in range(batch_s):
      patch_info = self.generate_patch_info(self.sizx[0, b], self.sizy[0, b], self.ori[0, b])
      self.patches.append(patch_info)
示例#13
0
  def __init__(self, set_type, objects, batch_s, scl, n_frames, c, wn_w, wn_h, grav, random_start_pos=False, random_start_speed=False, random_size=False):
    super().__init__(objects, batch_s, scl, n_frames, wn_w, wn_h, grav, random_start_pos, random_start_speed, random_size)

    # Select object static and dynamic properties
    choices    = ['rectangle', 'ellipse', 'vernier']
    self.ori   = rng().uniform(0, 2*np.pi,      (1, batch_s))
    self.colr  = rng().randint(100, 255,        (c, batch_s))
    self.pop_t = rng().randint(0, n_frames//2,  (1, batch_s))

    self.shape  = rng().choice(choices, (1, batch_s))
    self.side   = rng().randint(0, 2, (1, batch_s)) if len(objects) == 0 else objects[0].side
    self.side_  = 1*self.side                   # evolving value for sqm (deep copy)
    self.popped = np.array([[False]*batch_s])   # display stimulus or not
    self.sizx[self.shape == 'vernier'] /= 1.5   # verniers look better if not too wide
    self.sizy[self.shape == 'vernier'] *= 2.0   # verniers appear smaller than other shapes
    self.pos    = np.vstack((self.x,   self.y))
    self.vel    = np.vstack((self.vx, self.vy))
    self.acc    = np.array([[0.00]*batch_s, [grav]*batch_s])

    # Generate patches to draw the shapes efficiently
    self.patches = []
    for b in range(batch_s):
      patch_info = self.generate_patch_info(self.shape[0, b], self.sizx[0, b], self.sizy[0, b], self.ori[0, b])
      self.patches.append(patch_info)
示例#14
0
    def init_batch(self):

        # Background window and objects inside it
        self.batch = []
        self.objects = []
        self.window = 127 * np.ones(
            (self.batch_s, self.wn_h, self.wn_w, self.n_chans), dtype=int)
        for _ in range(self.n_objects):
            self.objects.append(
                self.Object(self.set_type, self.objects, self.batch_s,
                            self.scale, self.n_frames, self.n_chans, self.wn_h,
                            self.wn_w, self.gravity))
        self.bg_color = rng().randint(
            0, 80, (self.batch_s, self.n_chans)
        )  # if set_type == 'recons' else 40*np.ones((self.batch_s, self.n_chans))
        for b in range(self.batch_s):
            for c in range(self.n_chans):
                self.window[b, :, :, c] = self.bg_color[b, c]

        # Occluding walls in the frontground
        n_occl = rng().randint(0, self.n_max_occl + 1, (
            self.batch_s)) if self.set_type == 'recons' else [0] * self.batch_s
        self.frnt_grd = np.zeros(self.window.shape, dtype=bool)
        for b in range(self.batch_s):
            for _ in range(n_occl[b]):
                if rng().rand() > 0.5:
                    pos = rng().randint(0, self.wn_h)
                    height = rng().randint(2, self.wn_h // 10)
                    self.frnt_grd[b,
                                  max(0, pos -
                                      height):min(self.wn_h, pos +
                                                  height), :, :] = True
                else:
                    pos = rng().randint(0, self.wn_w)
                    height = rng().randint(2, self.wn_w // 10)
                    self.frnt_grd[b, :,
                                  max(0, pos -
                                      height):min(self.wn_w, pos +
                                                  height), :] = True
示例#15
0
  def __init__(self, objects, batch_s, scl, n_frames, wn_w, wn_h, grav, random_start_pos, random_start_speed, random_size):
    """
    Parameters
    ----------
    objects: int
    batch_s: int
    scl: float
    n_frames: int
    wn_w: int
    wn_h: int
    """
    self.batch_s = batch_s

    # vx and vy denote the starting velocity of the vernier
    if random_start_speed:
      self.vx         = rng().uniform(-3*scl, 3*scl,   (1, self.batch_s))
      self.vy         = rng().uniform(-3*scl, 3*scl,   (1, batch_s))
    else:
      flow       = (len(objects)%2 - 0.5)*4*scl**2
      self.vx         = np.ones((1, self.batch_s))*flow
      self.vy         = np.ones((1, self.batch_s))*0.0

    # sizx and sizy denote the size of half a vernier
    if random_size:
      self.sizx  = rng().uniform(wn_w/10, wn_w/2, (1, self.batch_s))  # max: /4
      self.sizy  = rng().uniform(wn_h/10, wn_h/2, (1, self.batch_s))  # max: /4
    else:
      self.sizx  = np.ones((1, self.batch_s))*wn_w/5
      self.sizy  = np.ones((1, self.batch_s))*wn_w/4

    # x and y denote the starting position of the center of the vernier
    if random_start_pos:
      x_margin = n_frames * abs(self.vx) + self.sizx
      y_margin = self.sizy + 4
      self.x = rng().uniform(x_margin, wn_w - x_margin, (1, self.batch_s))
      self.y = rng().uniform(y_margin, wn_h - y_margin, (1, self.batch_s))
    else:
      self.x = np.ones((1, self.batch_s)) * wn_w//2
      self.y = np.ones((1, self.batch_s)) * wn_h//2
示例#16
0
def triangle_lattice_random_walk(num_steps, num_walkers):
    """
    Generating the random walk data, for statistically
    independent random variables. This is for a 2D random walk
    on a triangular lattice.

    The two arrays, x_arrray and y_array,
    contain the coordinates of the random walker and the r_sqaured_normal array
    contains the averge displacement of all the walker
    at each time (step number).

    """
    #store distance squared for each walker
    r_squared = np.zeros(num_steps)

    #array to store analytical solutions for the diffusion constant
    diffusion_constant = np.zeros(num_steps)

    # specify all step numbers-- for consistent plotting purposes
    step_num = np.arange(1, num_steps + 1)

    #becuase triangular lattice has locations it can move
    #(non-binary arguments).
    #So, creating arrays to store coordinates of the walks
    x_array = np.zeros(num_steps)
    y_array = np.zeros(num_steps)

    plt.figure()
    ax = plt.gca()
    plt.xlabel("x")
    plt.ylabel("y")
    plt.axis('equal')
    ax.set_title('2D Triangular Lattice: Random Walk\n\
    %s Steps For Each Walker'                              %(num_steps),\
    family='monospace',size=12, weight='bold')
    ax.legend("", title='# of Walks= %s' % (num_walkers), loc=1, fontsize=9)
    for j in range(num_walkers):

        #evenly distributed values from (0,1]
        theta_step = (rng(num_steps))

        # generate random steps
        #6 possible movement locations for each step
        #So, each condition (excluding the error condition)
        #represents the movement possiblites.
        #AAND the probability that the walk moves in a direction
        #is the same for all six possibilites
        for i in range(num_steps):
            if 0 <= theta_step[i] < 1 / 6:
                x_array[i] = 1
                y_array[i] = 0

            elif 1 / 6 <= theta_step[i] < 2 / 6:
                x_array[i] = 0.5
                y_array[i] = 1

            elif 2 / 6 <= theta_step[i] < 3 / 6:
                x_array[i] = -0.5
                y_array[i] = 1

            elif 3 / 6 <= theta_step[i] < 4 / 6:
                x_array[i] = -1
                y_array[i] = 0

            elif 4 / 6 <= theta_step[i] < 5 / 6:
                x_array[i] = -0.5
                y_array[i] = -1

            elif 5 / 6 <= theta_step[i] < 1:
                x_array[i] = 0.5
                y_array[i] = -1

            else:
                print("Something went wrong")

        cum_x = np.cumsum(x_array)
        cum_y = np.cumsum(y_array)

        #to get distance_sqaured for each walker
        r_squared_temp = np.add(cum_x**2, cum_y**2)

        # add the distance squared of current walker to last walker
        #this is done for the collection of 2d walks.
        r_squared = r_squared + r_squared_temp

        plt.plot(cum_x, cum_y)

    #normalizes the r_squared data
    normal_r_sqaured = r_squared / num_walkers

    #analytically solve for the diffuion
    #all solutions are output in the interactive kernel.
    for i in range(num_steps):
        diffusion_constant[i] = normal_r_sqaured[i] / (2 * (i + 1))
        print("At Step Number", i + 1, ":")
        print("Diffusion Constant =", diffusion_constant[i], "\n")

    plt.show()

    plt.figure()
    ax = plt.gca()
    plt.plot(step_num, normal_r_sqaured, '.')
    plt.xlabel("step number = (time)")
    plt.ylabel("<r$^2$>")
    ax.set_title('2D Triangular Lattice:\n\
    The Average of The Sqaure of the Displacement:\n\
    %s Steps For Each Walker'                              %(num_steps),\
    family='monospace',size=12, weight='bold')
    ax.legend("",
              title='# of Walks Averaged= %s' % (num_walkers),
              loc=2,
              fontsize=9)
    plt.show()

    return diffusion_constant, normal_r_sqaured
示例#17
0
def random_walk(num_steps, num_walkers):
    """
    Generating the random walk data, for statistically
    independent random variables. This for a 2D random walk.

    The two arrays, x and y,
    contain the coordinates of the random walker and the r_sqaured_normal array
    contains the averge displacement of all the walker
    at each time (step number).

    """

    #store distance squared for each walker
    r_squared = np.zeros(num_steps)

    #array to store analytical solutions for the diffusion constant
    diffusion_constant = np.zeros(num_steps)

    # specify all step numbers-- for consistent plotting purposes
    step_num = np.arange(1, num_steps + 1)

    plt.figure()
    ax = plt.gca()
    plt.xlabel("x")
    plt.ylabel("y")
    plt.axis('equal')
    ax.set_title('2D Random Walk:\n\
    %s Steps For Each Walker'                              %(num_steps),\
    family='monospace',size=12, weight='bold')
    ax.legend("", title='# of Walks= %s' % (num_walkers), loc=1, fontsize=9)

    for j in range(num_walkers):

        # generate random steps +/- 1
        x = (2 * (rng(num_steps) > 0.5) - 1).cumsum()
        # generate random steps +/- 1
        y = (2 * (rng(num_steps) > 0.5) -
             1).cumsum()  # generate random steps +/- 1

        #to get distance_sqaured for each walker
        r_squared_temp = np.add(x**2, y**2)

        # add the distance squared of current walker to last walker
        #this is done for the collection of 2d walks.
        r_squared = r_squared + r_squared_temp

        #plot the coodinates of the random walker after each
        #is generated
        plt.plot(x, y)

    #normalizes the r_squared data
    normal_r_sqaured = r_squared / num_walkers

    #analytically solve for the diffuion
    #all solutions are output in the interactive kernel.
    for i in range(num_steps):
        diffusion_constant[i] = normal_r_sqaured[i] / (2 * (i + 1))
        print("At Step Number", i + 1, ":")
        print("Diffusion Constant =", diffusion_constant[i], "\n")

    plt.show()

    plt.figure()
    ax = plt.gca()
    plt.plot(step_num, normal_r_sqaured, '.')
    plt.xlabel("step number = (time)")
    plt.ylabel("<r$^2$>")
    ax.set_title('2D Random Walk:\n\
    The Average of The Sqaure of the Displacement\n\
    and %s Steps For Each Walker'                                  %(num_steps),\
    family='monospace',size=12, weight='bold')
    ax.legend("",
              title='# of Walks Averaged= %s' % (num_walkers),
              loc=2,
              fontsize=9)
    plt.show()

    return diffusion_constant, normal_r_sqaured
示例#18
0
pickup= int(input("\nHow many pickup locations do you want? (26 and under): "))

os.system("rm TempDat* -f")

##############################################################################
################          Creating Rider File              ###################
##############################################################################


riders_file = 'TempDatRiders.csv'


riders_name = []
for i in range(riders):
	riders_name.append(chr(i+97))
riders_x = 10*rng(riders)
riders_y = 10*rng(riders)


for i in range(riders):

	newline = 'echo '+str(riders_name[i])+','+str(riders_x[i])+','+str(riders_y[i])+' >> '+riders_file
	os.system(newline)

##############################################################################
################         Creating Pickup File              ###################
##############################################################################

pickup_file = 'TempDatPickup.csv' 

pickup_name = []
示例#19
0
def flat_linear(n_in, n_out):
    w = rng().standard_normal(n_in * n_out) * 0.1
    b = rng().standard_normal(n_out) * 0.1
    return np.concatenate([w, b])
示例#20
0
文件: 5.2.py 项目: wmh001/learning
"""
Created on Tue Oct  6 00:19:34 2020

@author: w'm'h
"""
import numpy as np
import matplotlib.pyplot as plt

# 随机数和模拟

# 模拟抛硬币
from numpy.random import random as rng

samples = np.zeros(100)
for i in range(0, 100):
    samples[i] = rng()
flips = (samples < 0.5)
print(np.sum(flips))


# 布朗运动轨迹线
def get_trajectory(num_steps):
    x_steps = np.ones(num_steps)
    y_steps = np.ones(num_steps)
    for i in range(0, num_steps):
        if (rng() < 0.5):
            x_steps[i] = -1
        else:
            x_steps[i] = 1
        if (rng() < 0.5):
            y_steps[i] = -1
 def reset(self):
     self._random = rng(self._seed)
     self._data_index = 0
     self._epochs_completed = 0
示例#22
0
        #%% Initialized given code
        n = np.zeros((lattice_size, lattice_size))
        b = np.zeros((lattice_size, lattice_size))
        prob = (1 + p) / sizer
        occupancy = int(prob * (lattice_size - 2) * (lattice_size - 2))

        clust = np.zeros(lattice_size * lattice_size)
        d = np.zeros((lattice_size, lattice_size))

        #%% Given Code
        # cluster count
        x = 0
        counter = 0
        for count in range(occupancy):
            counter = counter + 1
            i = int((lattice_size - 2) * rng()) + 1
            j = int((lattice_size - 2) * rng()) + 1
            while n[i, j] > 0:
                i = int((lattice_size - 2) * rng()) + 1
                j = int((lattice_size - 2) * rng()) + 1

            x = x + 1
            n[i, j] = 1
            d[i, j] = x
            clust[x] = x

            if (n[i - 1, j] != 0):
                ind = d[i - 1, j]
                ind = clust[int(ind)]
                while ind < 0:
                    ind = clust[int(-1 * ind)]
示例#23
0
from numpy.random import random as rng
import matplotlib.pyplot as plt
import numpy as np

########  Makes sure input is an integer between a certain range[]  ############


#########################################################################

# Following Creates User Specified N number of Uniformly Dist. Points #

N = (1, 100, 250, 500, 1000, 10000,100000)
approx = np.zeros(len(N))
for j in range(len(N)):

	x_arr = rng(N[j])*2
	y_arr = rng(N[j])*2
	
	hyp = np.square(x_arr-1) + np.square(y_arr-1)
	usr_num = N
	count = 0
	for i in range(1,usr_num[j]):
	
		if hyp[i] <= 1:
			count+=1
	piapprox = (4*count)/ usr_num[j]
	approx[j] = piapprox
	
array_approx = (abs(approx-np.pi)/np.pi) * 100

示例#24
0
def get_epsilon(seed, m_id):
    sign = -1.0 if m_id % 2 == 0 else 1.0
    return sign * rng(seed).standard_normal(PARAM_SIZE)
示例#25
0
    def __init__(self, set_type, objects, batch_s, scl, n_frames, c, wn_h,
                 wn_w, grav):

        # Select object static and dynamic properties
        if set_type in ['recons', 'decode']:
            choices = ['rectangle', 'ellipse', 'vernier'
                       ] if set_type == 'recons' else ['vernier']
            x = rng().uniform(0, wn_w, (1, batch_s))
            y = rng().uniform(0, wn_h, (1, batch_s))
            vx = rng().uniform(-5 * scl, 5 * scl, (1, batch_s))
            vy = rng().uniform(-5 * scl, 5 * scl, (1, batch_s))
            self.ori = rng().uniform(0, 2 * np.pi, (1, batch_s))
            self.sizx = rng().uniform(wn_w / 10, wn_w / 2,
                                      (1, batch_s))  # max: /4
            self.sizy = rng().uniform(wn_w / 10, wn_w / 2,
                                      (1, batch_s))  # max: /4
            self.colr = rng().randint(100, 255, (c, batch_s))
            self.pop_t = rng().randint(0, n_frames // 2, (1, batch_s))
        if set_type == 'sqm':
            choices = ['vernier']
            flow = (len(objects) % 2 - 0.5) * 8 * scl**2
            x = np.ones((1, batch_s)) * wn_w // 2
            y = np.ones((1, batch_s)) * wn_h // 2
            vx = np.ones((1, batch_s)) * flow
            vy = np.ones((1, batch_s)) * 0.0
            self.ori = np.ones((1, batch_s)) * 0.0
            self.sizx = np.ones((1, batch_s)) * wn_w / 5
            self.sizy = np.ones((1, batch_s)) * wn_w / 4
            self.colr = np.ones((c, batch_s), dtype=int) * 255
            self.pop_t = np.ones((1, batch_s), dtype=int) * 3
        self.shape = rng().choice(choices, (1, batch_s))
        self.side = rng().randint(
            0, 2, (1, batch_s)) if len(objects) == 0 else objects[0].side
        self.side_ = 1 * self.side  # evolving value for sqm (deep copy)
        self.popped = np.array([[False] * batch_s])  # display stimulus or not
        self.sizx[self.shape ==
                  'vernier'] /= 1.5  # verniers look better if not too wide
        self.sizy[
            self.shape ==
            'vernier'] *= 2.0  # verniers appear smaller than other shapes
        self.pos = np.vstack((x, y))
        self.vel = np.vstack((vx, vy))
        self.acc = np.array([[0.00] * batch_s, [grav] * batch_s])

        # Generate patches to draw the shapes efficiently
        self.patches = []
        for b in range(batch_s):
            max_s = int(2 * max(self.sizx[0, b], self.sizy[0, b]))
            patch = np.zeros((max_s, max_s))
            patch_0 = None
            if self.shape[0, b] == 'ellipse':
                center = (patch.shape[0] // 2, patch.shape[1] // 2)
                radius = (self.sizy[0, b] / 2, self.sizx[0, b] / 2)
                rr, cc = ellipse(center[0],
                                 center[1],
                                 radius[0],
                                 radius[1],
                                 shape=patch.shape)
                patch[rr, cc] = 255
            elif self.shape[0, b] == 'rectangle':
                start = (int(max_s - self.sizy[0, b]) // 2,
                         int(max_s - self.sizx[0, b]) // 2)
                extent = (int(self.sizy[0, b]), int(self.sizx[0, b]))
                rr, cc = rectangle(start=start,
                                   extent=extent,
                                   shape=patch.shape)
                patch[rr, cc] = 255
            if self.shape[0, b] == 'vernier':
                patch_0 = np.zeros((max_s, max_s))  # patch with zero offset
                if set_type == 'sqm':
                    side = self.side[0, b]
                    v_siz_w = 1 + self.sizx[0, b] // 4
                    v_siz_h = 1 + self.sizy[0, b] // 3
                    v_off_w = (1 + (self.sizx[0, b] - v_siz_w) // 3) * 2
                    v_off_h = (
                        1 +
                        (self.sizy[0, b] - v_siz_h) // 6) * 2 + v_siz_h // 2
                else:
                    side = rng().randint(
                        0, 2) if set_type == 'recons' else self.side[0, b]
                    v_siz_w = rng().uniform(1 + self.sizx[0, b] // 6,
                                            1 + self.sizx[0, b] // 2)
                    v_siz_h = rng().uniform(1 + self.sizy[0, b] // 4,
                                            1 + self.sizy[0, b] // 2)
                    v_off_w = rng().uniform(
                        1, 1 + (self.sizx[0, b] - v_siz_w) // 2) * 2
                    v_off_h = rng().uniform(
                        1 + v_siz_h // 2, 1 +
                        (self.sizy[0, b] - v_siz_h) // 2) * 2
                    if len(objects) > 0 and set_type == 'decode':
                        v_off_w = 0.0  # only one vernier (the first in the list) has an offset in decode mode
                start1 = (int((max_s - v_off_h - v_siz_h) // 2),
                          int((max_s - v_off_w - v_siz_w) // 2))
                start2 = (int((max_s + v_off_h - v_siz_h) // 2),
                          int((max_s + v_off_w - v_siz_w) // 2))
                start01 = (int((max_s - v_off_h - v_siz_h) // 2),
                           int((max_s - 0 - v_siz_w) // 2))
                start02 = (int((max_s + v_off_h - v_siz_h) // 2),
                           int((max_s + 0 - v_siz_w) // 2))
                extent = (int(v_siz_h), int(v_siz_w))
                rr1, cc1 = rectangle(start=start1,
                                     extent=extent,
                                     shape=patch.shape)
                rr2, cc2 = rectangle(start=start2,
                                     extent=extent,
                                     shape=patch.shape)
                rr01, cc01 = rectangle(start=start01,
                                       extent=extent,
                                       shape=patch.shape)
                rr02, cc02 = rectangle(start=start02,
                                       extent=extent,
                                       shape=patch.shape)
                patch[rr1, cc1] = 255
                patch[rr2, cc2] = 255
                patch_0[rr01, cc01] = 255
                patch_0[rr02, cc02] = 255
            patch = rotate(patch, self.ori[0, b]).astype(int)
            to_add = [patch, np.fliplr(patch), patch_0]
            self.patches.append(to_add)
示例#26
0
    try:
        usr_num = int(usr_num)
        if usr_num < 0:
            raise ValueError()
    except ValueError:
        print("Your input was not an integer or between 4 and 10 Try Again.\n", file= sys.stderr)
    else:
        break


#########################################################################

# Following Creates User Specified N number of Uniformly Dist. Points #

arr_x = (rng(usr_num)*2)
arr_y = (rng(usr_num)*2)

hyp =(np.square(arr_x-1) + np.square(arr_y-1))  


count = 0
for i in range(0,usr_num):
	
	if hyp[i] <= 1:
		count +=1

 


print("The approximation of pi with %d points is:" % usr_num)
示例#27
0
#%%

plt.figure()
plt.title("Random Walk")
plt.xlabel("x")
plt.ylabel("y")

r2ave=np.zeros(num_steps)

x=np.zeros(num_steps)
y=np.zeros(num_steps)

for j in range(num_walkers):
    i=0
    while(i<num_steps-1):
        x_step=rng()
        y_step=rng()
        x_step=2*(x_step>0.5)-1
        y_step=2*(y_step>0.5)-1
        
        x1=x[i]+x_step
        y1=y[i]+y_step
        
        print(x1,y1)
        
    plt.plot(x,y)

plt.figure()
plt.title("Random Walk in Two Dimensions")
plt.xlabel("step number")
plt.ylabel("<r.r>")
示例#28
0
# random_walk.py
# -------------------------------------------------------------------------
# Monte Carlo simulation of a two-dimensional random walk.
# -------------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
from numpy.random import random as rng

num_steps = 500
x_step = rng(num_steps) > 0.5
y_step = rng(num_steps) > 0.5
x_step = 2 * x_step - 1
y_step = 2 * y_step - 1
x_position = np.cumsum(x_step)
y_position = np.cumsum(y_step)

plt.figure()
plt.plot(x_position, y_position)
plt.axis('equal')

# A more succinct alternative:
x = (2 * (rng(num_steps) > 0.5) - 1).cumsum()
y = (2 * (rng(num_steps) > 0.5) - 1).cumsum()

plt.figure()
plt.plot(x, y)
plt.axis('equal')

plt.show()
示例#29
0
#%%Declaring constants
num_steps = 500
num_walkers = 1000
endpoints = np.zeros(num_walkers)
temp = np.zeros(num_walkers)

#%%Plotting
def plot2d():
    plt.figure(title)
    plt.xlabel('Distance in the x - direction')
    plt.ylabel('Distance in the y - direction')
    
#%%Code for 1D
for j in range(num_walkers):
    #initialization for number of elements in each step
    x_step = rng(num_walkers); y_step = rng(num_walkers)
    
    #Initialize the steps to be either zero or one
    x_step = 2 * (x_step > 0.5) - 1
    y_step = 2 * (y_step > 0.5) - 1
    
    #Sum of each step
    x = np.cumsum(x_step)
    y = np.cumsum(y_step)
    
    #Plotting of all steps in all direction 
    plot = x; title = "Ramdom walks in 1D"
    plot2d(); plt.plot(plot, y)
    
    #Calculations to plot the average
    r2 = x**2 + y**2
示例#30
0
Author: %(username)s (Python 3.4)

Created: 2018
Author: Stephan Goldberg

Description:
Random walk with step_size number of steps in x- and y-direction with the numpy random-function.

"""
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import random as rng

num_steps = 10000

x_step = rng((num_steps, ))  # array with num_steps elements between 0 and 1
y_step = rng((num_steps, ))

x_step[
    x_step >= 0.5] = 1  # assigning the value 1 for numbers between 0.5 and 1
x_step[
    x_step < 0.5] = -1  # assigning the value -1 for numbers between 0 and 0.5

y_step[y_step >= 0.5] = 1
y_step[y_step < 0.5] = -1

plt.plot(np.cumsum(x_step), np.cumsum(y_step))

ax = plt.gca()
ax.set_title(str(num_steps) + " random steps in x- and y-direction ", size=16)