Example #1
0
def main():
    freq = 5
    init_temp =  22
    init_hum = 65
    init_pres = 1010
    init_wind = 12

    temp = init_temp
    hum = init_hum
    pres = init_pres
    wind = init_wind

    cur = db.cursor()

    x = 0.0
    while True:
        x += 0.01
        temp += pnoise1(x, 1, 0.5, 2.0, 1024, 0)/10
        hum += pnoise1(x, 1, 0.5, 2.0, 1024, 256)/5
        pres += pnoise1(x, 1, 0.5, 2.0, 1024, 512)*10
        wind += pnoise1(x, 1, 0.5, 2.0, 1024, 768)*10
        print 'temp:', '%.2f'%temp, 'hum:', floor(hum), 'pres:', floor(pres), 'wind:', floor(wind), 'freq:', freq
        cur.execute("INSERT INTO samples(temp, hum, pres, wind, freq) VALUES(%s, %s, %s, %s, %s)", ('%.2f'%temp, floor(hum), floor(pres), floor(wind), freq))
        db.commit()
        sleep(freq)

    cur.close()
Example #2
0
def make_gif():
    if (os.path.exists('latent_best.h5')):
        generator = load_model('latent_best.h5')

    imgs = []
    location = [0, 0]
    velocity = [0, 0]
    acceleration = [0, 0]
    noise = np.random.rand(2) * 10
    # print(acceleration.shape)
    for i in range(150):
        noise[0] = noise[0] + 0.05
        noise[1] = noise[1] + 0.05
        acceleration[0] = pnoise1(noise[0])
        acceleration[1] = pnoise1(noise[1])
        velocity[0] = velocity[0] + acceleration[0]
        velocity[1] = velocity[1] + acceleration[1]
        velocity = np.clip(velocity, -50, 50)
        location[0] = location[0] + velocity[0]
        location[1] = location[1] + velocity[1]

        if (location[0] < -100 or location[0] > 100):
            velocity[0] = velocity[0] * -1
        if (location[1] < -100 or location[1] > 100):
            velocity[1] = velocity[1] * -1

        print(location[0], location[1])
        # location = np.add(velocity, location)
        z_sample = np.array([[location[0], location[1]]])
        x_decoded = generator.predict(z_sample)
        img = x_decoded[0].reshape(100, 100, 3)
        imgs.append(img)

    gif.build_gif(imgs, saveto='clout.gif')
    def get_action(self, timestep_i, current_orientation, actions_checked=[]):

        perlin_noise = noise.pnoise1(
            (float(timestep_i * self.action_repeat) + self.offset0) /
            self.scale0)
        perlin_noise += noise.pnoise1(
            (float(timestep_i * self.action_repeat) + self.offset1) /
            self.scale1)

        action = int(perlin_noise * self.max_scaler)
        if action > self.max_scaler:
            action = self.max_scaler
        elif action < -self.max_scaler:
            action = -self.max_scaler

        action_samples = 0
        while action in actions_checked and action_samples < 50:
            action_samples += 1
            self.reset_action()
            perlin_noise = noise.pnoise1(
                (float(timestep_i * self.action_repeat) + self.offset0) /
                self.scale0)
            perlin_noise += noise.pnoise1(
                (float(timestep_i * self.action_repeat) + self.offset1) /
                self.scale1)

            action = int(perlin_noise * self.max_scaler)
            if action > self.max_scaler:
                action = self.max_scaler
            elif action < -self.max_scaler:
                action = -self.max_scaler

        steering_force = vector(action * self.wander_range +
                                current_orientation)
        return action, steering_force
Example #4
0
    def forces(self, time):

        # 风荷载,使用perlins noise来模拟风荷载
        time /= 100
        elem_wind_force = np.zeros((self.n, 3))
        wind_force = np.zeros((self.n, 3))
        angle = noise.pnoise1(time) * math.pi * 0.5
        elem_wind_force[:, 0] = 0.6 * math.cos(angle)
        elem_wind_force[:, 1] = -math.sin(angle)
        elem_wind_force[:, 2] = 0.3 * math.sin(angle)
        wind_force[:, :] = elem_wind_force * self.wind_magnitude * (
            noise.pnoise1(time) +
            0.2) * (noise.pnoise1(noise.pnoise1(time)) * 0.5 + 0.5)

        # 集中力,暂时先作用在布料的中心上,以后再改
        concentrated_force = np.zeros((self.n, 3))
        if np.sqrt(self.n) % 2 == 0:
            concentrated_force[int(
                (self.n) / 2) - 1 + int(np.sqrt(self.n) / 2),
                               2] = -self.concentrated_force_magnitude
            concentrated_force *= self.concentrated_force_is_on
        else:
            concentrated_force[int((self.n) / 2),
                               2] = -self.concentrated_force_magnitude
            concentrated_force *= self.concentrated_force_is_on

        # 重力荷载
        gravity_force = np.zeros((self.n, 3))
        gravity_force[:, 1] += -self.gravity_magnitude / 3

        return wind_force + concentrated_force + gravity_force
Example #5
0
 def move(self):
     ''' move according to Perlin noise'''
     self.currentx += 1
     self.currenty += 1
     n = pnoise1(self.currentx * self.delta, 1) 
     m = pnoise1(self.currenty * self.delta, 1) 
     self.x = int(n/2 * self.maxx + self.maxx/2)
     self.y = int(m/2 * self.maxy + self.maxy/2)
Example #6
0
 def gencolor(self, n):
     '''Returns (R, G, B) for the chosen iteration'''
     n /= self.scale
     return (
     int(abs(pnoise1(((n + self.rand1) % 1) ** 2, octaves=3, repeat=8192)) * 255),
     int(abs(pnoise1(((n + self.rand2) % 1) ** 2, octaves=3, repeat=8192)) * 255),
     int(abs(pnoise1(((n + self.rand3) % 1) ** 2, octaves=3, repeat=8192)) * 255)
     )
Example #7
0
 def __init__(self, beats):
     self.beat = list()
     for i in range(64):
         # generate beat
         play_sound = pnoise1(0, 1)
         amplitude = pnoise1(1, 100)
         duration = random.uniform(0.01, 1)
         self.beat.append((play_sound, amplitude, duration))
Example #8
0
 def wind_forces(self, time):
     time /= 500
     forces = np.zeros(((self.n, 3)))
     angle = noise.pnoise1(time) * math.pi * 0.5
     forces[:, 0] = math.cos(angle)
     forces[:, 2] = math.sin(angle)
     # Forces * max magnitude * perlins random * randomness influence between 0.5 and 1
     return forces * self.wind_magnitude * (noise.pnoise1(time)  + 0.2) * (noise.pnoise1(noise.pnoise1(time)) * 0.5 + 0.5)
Example #9
0
 def draw(self):
     if self.vel < 0 :
         self.beans.remove(self)
     self.x_off += 0.0007
     self.y_off += 0.0007
     self.vel += self.accel
     self.x += abs(noise.pnoise1(self.x_off) * self.vel) - self.vel / 2
     self.y += abs(noise.pnoise1(self.y_off) * self.vel) - self.vel / 2
     self.surface.set_at((int(self.x), int(self.y)), self.get_color())
Example #10
0
 def draw(self):
     if self.vel < 0:
         self.beans.remove(self)
     self.x_off += 0.0007
     self.y_off += 0.0007
     self.vel += self.accel
     self.x += abs(noise.pnoise1(self.x_off) * self.vel) - self.vel / 2
     self.y += abs(noise.pnoise1(self.y_off) * self.vel) - self.vel / 2
     self.surface.set_at((int(self.x), int(self.y)), self.get_color())
Example #11
0
    def def_noise(self, typeofnoice, stdlongpv, stdshortpv, stdlonglast, stdshortlast, logdata):

        # Langer Fehler muss größer sein als kurzer
        #
        # Setze Perlin Noise mit übergebenen Fehler
        if typeofnoice == "perlin":
            base = random.randrange(1, 10000, 100)
            octaves = 5
            points = len(logdata)
            span = 15
            df = pd.DataFrame({'A': [np.nan]})

            logdata['errorpvlong'] = 0
            logdata['errorpvshort'] = 0

            for i in range(len(logdata)):
                x = float(i) * span / (points) - 0.5 * span
                y = noise.pnoise1(x + base, octaves) / 20 * stdlongpv * 100
                df = df.append({'A': y}, ignore_index=True)
            logdata['errorpvlong'] = df['A']
            logdata['errorpvshort'] = df['A'] / stdlongpv * stdshortpv
            base = random.randrange(1, 10000, 100)
            logdata['errorlastlong'] = 0
            logdata['errorlastshort'] = 0

            df = pd.DataFrame({'B': [np.nan]})

            for i in range(len(logdata)):
                x = float(i) * span / (points) - 0.5 * span
                y = noise.pnoise1(x + base, octaves) / 20 * stdlonglast * 100
                df = df.append({'B': y}, ignore_index=True)
            logdata['errorlastlong'] = df['B']
            logdata['errorlastshort'] = df['B'] / stdlonglast * stdshortlast
            logdata.loc[0, 'errorpvlong'] = 0
            logdata.loc[0, 'errorlastlong'] = 0
            logdata.loc[0, 'errorpvshort'] = 0
            logdata.loc[0, 'errorlastshort'] = 0

        # setze Gaussian Noise
        if typeofnoice == "gaussian":
            df = pd.DataFrame(np.random.normal(0, stdlongpv, len(logdata)))
            logdata['errorpvlong'] = df[0]
            logdata['errorpvshort'] = df[0] / stdlongpv * stdshortpv

            df = pd.DataFrame(np.random.normal(0, stdlonglast, len(logdata)))
            logdata['errorlastlong'] = df[0]
            logdata['errorlastshort'] = df[0] / stdlonglast * stdshortlast

        if stdlonglast == 0:
            logdata['errorlastlong'] = 0
        if stdlongpv == 0:
            logdata['errorpvlong'] = 0
        if stdshortlast == 0:
            logdata['errorlastshort'] = 0
        if stdshortpv == 0:
            logdata['errorpvshort'] = 0
 def addNoise(self, pasadas, potencia):
     for j in  range( len(self.points) ):
       self.points[j].dx = self.points[j].ix
       self.points[j].dy = self.points[j].iy
       for i in range( pasadas ):
         rx = pnoise1(random.random() + self.points[j].ix) * potencia
         ry = pnoise1(random.random() + self.points[j].iy) * potencia
         # print(str(rx))
         self.points[j].dx = self.points[j].dx + rx
         self.points[j].dy = self.points[j].dy + ry
 def addNoise(self, pasadas, potencia):
     for j in range(len(self.points)):
         self.points[j].dx = self.points[j].ix
         self.points[j].dy = self.points[j].iy
         for i in range(pasadas):
             rx = pnoise1(random.random() + self.points[j].ix) * potencia
             ry = pnoise1(random.random() + self.points[j].iy) * potencia
             # print(str(rx))
             self.points[j].dx = self.points[j].dx + rx
             self.points[j].dy = self.points[j].dy + ry
Example #14
0
 def generate(self):
     # self.fill(BLACK)
     x = noise.pnoise1(self.t) + 1
     y = noise.pnoise1(self.t + self.y_offset) + 1
     x = translate(x, 0, 2., 10, self.width - 10)
     y = translate(y, 0, 2., 10, self.height - 10)
     # self.draw_circle(x, y, 10, GREEN)
     color = [int(0xff * c) for c in colorsys.hsv_to_rgb(self.t, 1, 1)]
     self.draw_pixel(x, y, color)
     self.t += 0.001
Example #15
0
 def generate(self):
     # self.fill(BLACK)
     x = noise.pnoise1(self.t) + 1
     y = noise.pnoise1(self.t + self.y_offset) + 1
     x = translate(x, 0, 2., 10, self.width - 10)
     y = translate(y, 0, 2., 10, self.height - 10)
     # self.draw_circle(x, y, 10, GREEN)
     color = [int(0xff * c) for c in colorsys.hsv_to_rgb(self.t, 1, 1)]
     self.draw_pixel(x, y, color)
     self.t += 0.001
Example #16
0
File: river.py Project: eykd/orphan
 def draw(self, row, col, noise_base, fill):
     mod_up = int(round(5 * pnoise1(col * 0.01, base=noise_base)))
     mod_down = int(round(5 * pnoise1(col * 0.01, base=-noise_base)))
     width_2 = 20
     top_row = row - (width_2 + mod_up)
     bot_row = row + (width_2 + mod_down)
     try:
         self.block[top_row : bot_row + 1, col : col + 1] = fill
     except IndexError:
         logger.exception('Bad terrain index (shape %s): %s : %s, %s : %s', self.block.terrain.shape, top_row, bot_row, col, col)
         raise
Example #17
0
 def filmjitter(self,
                doneness,
                base=0,
                speed=(10, 20),
                scale=(2, 3),
                octaves=16):
     """
     An easy way to make something move in a way reminiscent of misregistered film
     """
     nx = pnoise1(doneness * speed[0], base=base, octaves=octaves)
     ny = pnoise1(doneness * speed[1], base=base + 10, octaves=octaves)
     return self.translate(nx * scale[0], ny * scale[1])
Example #18
0
def drawSurface(nPoints):

    xp = 0.1
    yp = 1000.0
    zp = 10000.0

    verts = []

    for inx in range(nPoints):

        x = noise.pnoise1(xp)*10
        y = noise.pnoise1(yp)*10
        z = noise.pnoise1(zp)*10

        verts.append([x,y,z])

        xp +=0.05
        yp +=0.05
        zp +=0.05


    edges = [[i, i+1] for i in range(len(verts)-1)]


    ####### mesh #######

    mesh = bpy.data.meshes.new("mesh_name")
    mesh.from_pydata(verts, edges, faces=[])

    obj = bpy.data.objects.new("curva", mesh)

    scene = bpy.context.scene
    scene.objects.link(obj)

    bpy.context.scene.objects.active = obj

    bpy.ops.object.modifier_apply(modifier="SMOOTH")
    bpy.ops.object.modifier_add(type='SMOOTH')
    bpy.context.object.modifiers["Smooth"].iterations=100

    bpy.data.objects['curva'].select = True

    bpy.ops.object.convert(target='CURVE')

    bpy.context.object.data.fill_mode = 'FRONT'

    bpy.context.object.data.bevel_depth = 0.50

    bpy.context.object.data.bevel_resolution = 100

    bpy.context.object.data.twist_smooth = 100

    bpy.ops.object.convert(target='MESH')
Example #19
0
def make_vary(index, length, freq):
    def i(index, offset):
        return ((index + offset) % nump) / float(nump) 

    pulsewidth = int(pnoise1(i(index, 100), 2) * (length / 2))
    
    snd = dsp.tone(pulsewidth, freq, amp=pnoise1(i(index, 99), 3) * 0.5)
    snd = dsp.env(snd, 'sine')

    snd = dsp.pad(snd, 0, length - pulsewidth)

    return snd
Example #20
0
def generate_perlin_noise():

    arg = config.pattern_num / config.sample_num
    x_list = [
        (1 + noise.pnoise1(arg * i, octaves=1, base=0)) / 2 * config.x_max
        for i in range(config.sample_num)
    ]
    y_list = [
        (1 + noise.pnoise1(arg * i, octaves=1, persistence=0.5, base=1)) / 2 *
        config.y_max for i in range(config.sample_num)
    ]

    return x_list, y_list
Example #21
0
def on_draw(x):
    win.clear()
    global xoff, yoff, particle
    for wall in Walls:
        wall.show()

    newX = np.interp(noise.pnoise1(x=xoff, octaves=2), [-1, 1], [0, size[0]])
    newY = np.interp(noise.pnoise1(x=yoff, octaves=2), [-1, 1], [0, size[1]])
    particle.update(newX, newY)
    particle.show()
    particle.look(Walls)
    xoff += 0.01
    yoff += 0.01
def noise_drawing():
    noise_step = 1.0
    while True:
        bar = ""
        length_of_string = map(noise.pnoise1(noise_step, 2), -0.5, 0.5, 0,
                               width)
        range_of_color = map(noise.pnoise1(noise_step, 2), -0.5, 0.5, 0, 15)
        for x in range(0, int(length_of_string)):
            bar += "-"

        print(term.color(int(range_of_color)) + bar)

        noise_step += 0.001
        sleep(0.001)
Example #23
0
 def draw(self):
     """draw line"""
     if self.vel < 0 :
         # remove self
         self.beans.remove(self)
     # original 0.0007
     self.x_off += 0.0007
     self.y_off += 0.0007
     self.vel += self.accel
     self.x += noise.pnoise1(self.x_off, octaves=8) * self.vel - self.vel / 2
     self.y += noise.pnoise1(self.y_off, octaves=8) * self.vel - self.vel / 2
     # set color
     h = abs(noise.pnoise1((self.x_off + self.y_off) / 2)) * 360
     self.color.hsva = (h, 100, 100, 4)
     pygame.gfxdraw.pixel(self.surface, int(self.x) % self.width, int(self.y) % self.height, self.color)
Example #24
0
def generate_points(step, mag, step_offset, num, x_scale, x_offset):
    points = []
    for x in range(0, num):
        yy = mag * (noise.pnoise1(x * step + step_offset, octaves=2))
        xx = x * x_scale - x_offset
        points.append([xx, yy])
    return points
def addNoise():
    global points, gp
    # Add noise
    counter = -1

    # Noise params
    base = random.randint( 0, 100)
    octaves = random.randint( 9, 12 )
    persistence = random.uniform( 1.2, 5.8 )
    lacunarity = random.uniform( 2.1, 2.9 )

    print('b:'+str(base)+' o:'+str(octaves)+' p:'+str(persistence)+' l:'+str(lacunarity) )

    gp['params']['b'] = base
    gp['params']['o'] = octaves
    gp['params']['p'] = persistence
    gp['params']['l'] = lacunarity

    for line in points:
        for j in range(len(line)):
            counter += 1
            pn1 = pnoise1(
                counter / segments_total * 0.25,
                octaves,     # octaves 9 - 12
                persistence, # persistence 1.2 - 6.2
                lacunarity,  # lacunarity 2.1 - 3.15
                64,          # repeat 1024
                base         # base 0.0
            )
            line_inc[j][1] += pn1 * 8
            line[j][1] += line_inc[j][1]

            line_inc[j][0] += pn1 * 3
            line[j][0] += line_inc[j][0]
Example #26
0
 def test_perlin_1d_octaves_range(self):
     from noise import pnoise1
     for i in range(-1000, 1000):
         for o in range(10):
             x = i * 0.49
             n = pnoise1(x, octaves=o + 1)
             self.assertTrue(-1.0 <= n <= 1.0, (x, n))
Example #27
0
    def _run(self):
        while True:
            current_commitment_service = random.choice(self.commitment_services)
            self.make_offer(self.market_price, current_commitment_service)
            # propagate perlin noise generator and set new market price target, always positive
            # TODO Fixme, optimize
            self.market_price = abs(self.market_price + self.max_price_movement * pnoise1(self.time))
            self.time += 0.01
            magic_number = random.randint(1, self.message_volume)
            # 20% of offers get taken, others should time out
            if magic_number <= int(round(self.message_volume * 0.2)):
                type_ = random.choice([OfferType.BUY, OfferType.SELL])
                offers = None
                if type_ == OfferType.SELL:
                    # FIXME, ugly
                    # FIXME Can be empty!!
                    offers = list(reversed(list(self.offer_book.buys.values())))

                elif type_ == OfferType.BUY:
                    offers = list(self.offer_book.sells.values())

                # threshold_index = int(self.message_volume * 0.2)
                threshold_index = int(len(offers) * 0.2)
                try:
                    # FIXME will most likely not succeed because of a lot of index errors
                    offer_to_take = random.choice(offers[0:threshold_index])
                    self.take_and_swap_offer(offer_to_take, current_commitment_service)
                except IndexError or TypeError:
                    pass
            # new activity every 1-5 seconds
            ttl = random.randint(1, 5)
            gevent.sleep(ttl)
Example #28
0
    def generate_chunk(self, x, y, CHUNK_SIZE):

        chunk_data = []
        for y_pos in range(CHUNK_SIZE):
            for x_pos in range(CHUNK_SIZE):
                target_x = x * CHUNK_SIZE + x_pos
                target_y = y * CHUNK_SIZE + y_pos
                tile_type = 0

                height = int(noise.pnoise1(target_x * 0.1, repeat=100000)*5)
                if target_y > 5 - height:
                    tile_type  = 2
                if target_y == 5 - height:
                    tile_type  = 1
                #for grass tile
                if target_y == 4 - height:
                    tile_type = 4
                    if random.randint(1,5) >= 2:
                        tile_type = 3
                #for plant tile
                if tile_type != 0:
                    chunk_data.append([[target_x,target_y], tile_type])

        return chunk_data

# map = Map('Assets/Sprites/tiles/tile.txt')
# arr_map = map.load_map()
#
# air = 0
# for row in arr_map:
#     for col in row:
#         if col == " ":
#             air += 1
#         print(col, end='')
# print(air)
Example #29
0
def play(player, balls):
    global _step

    _step += 0.001
    _step %= 1
    left = False
    right = False
    ball_to_follow = balls.sprites()[0]
    trigger_range_offset = numpy.interp(ball_to_follow.rect.y,
                                        [0, config.PLAYER_Y - 10], [400, 0])
    trigger_range = (player.rect.centerx - trigger_range_offset / 2,
                     player.rect.centerx + trigger_range_offset / 2)

    for ball in balls:
        if ball.sticky and random.randint(0, 50) == 11:
            ball.sticky = False

    if not trigger_range[0] < ball_to_follow.rect.centerx < trigger_range[1]:
        offset = numpy.interp(
            noise.pnoise1(_step), [0, 1],
            [-player.rect.width * inaccuracy, player.rect.width * inaccuracy])
        # print(offset)
        if player.rect.centerx > ball_to_follow.rect.centerx + offset:
            left = True
        else:
            right = True

    return left, right
Example #30
0
def gen_env_fn(choice="planar"):
    """
    choice (str): 'planar', 'perlin', 'step'
    """
    if choice == "planar":
        ma = np.tan(np.random.rand() * 90)
        c = np.random.rand() * 10 - 5
        variation = np.random.rand() * 2
        root_logger.debug("Planar parameters: {ma} {c} {variation}")
        func = lambda x: ma * x + c + np.random.normal(0, np.sqrt(variation))
    elif choice == "perlin":
        # Old params 3, 1.5, 5
        octaves = int(np.random.rand() * 10) + 1  # Affects terrain roughness
        speed = np.random.rand() * 10  # affects rate of variation
        offset = np.random.rand() * 500  # A randomness based on shift
        scale = np.random.rand() * 5 + 1  # A randomness based on shift
        root_logger.debug(
            "Perlin parameters: {octaves} {speed} {offset} {scale}")
        func = lambda x: scale * pnoise1(speed * x + offset, octaves
                                         )  # Perlin noise
    elif choice == "step":
        # Step
        c = np.random.random_sample()
        root_logger.debug("Step parameter: {c}")
        func = lambda x: 0 if x < c else 1  # Step
    else:
        raise ValueError("Invalid choice of environment.")

    f = np.vectorize(func)

    return f
Example #31
0
 def __init__(self, path, size):
     self.width, self.height = size
     self.x, self.y = self.width // 8, self.height // 8
     try:
         with open(path, 'r') as file:
             self._map_data = file.read().split('\n')
             self._map_data = [
                 list(map(int, list(i))) for i in self._map_data
             ]
     except FileNotFoundError:
         self._map_data = [([0] * self.x) for _ in range(self.y)]
         for x in range(self.y):
             f = noise.pnoise1(x / 1000,
                               octaves=3,
                               lacunarity=10,
                               persistence=0.6,
                               base=1200)
             y = round((f * self.x) + (self.x // 2))
             for index, _ in enumerate(self._map_data[x]):
                 if index > y:
                     self._map_data[x][index] = 1
             # TODO: Repeat for trees/sand
         with open(path, 'w+') as file:
             final = ''
             for i in self._map_data:
                 final += ''.join([str(j) for j in i]) + '\n'
             file.write(final[:-1])
Example #32
0
    def _draw(self, frame):
        """
        Draws one animation frame
        :param frame: Frame number
        :return:
        """
        center_cell = int(.5 * self.size)
        n = self.size

        # add density
        for x in range(-1, 2):
            for y in range(-1, 2):
                self.densities[index(center_cell + x, center_cell + y, n)] += randint(50, 150)

        # add velocity
        for i in range(0, 2):
            angle = 2 * np.pi * noise.pnoise1(self.t)
            v = np.array([np.cos(angle), np.sin(angle)])
            v *= .2
            self.t += .1
            self.x_velocities[index(center_cell, center_cell, n)] += v[0]
            self.y_velocities[index(center_cell, center_cell, n)] += v[1]

        self._step()
        self._render_densities()
Example #33
0
def gen_env_fn_2d(choice="planar", path=None):
    """
    choice (str): 'planar', 'perlin', 'step'
    """
    if choice == "planar":
        ma = np.tan(np.random.rand() * 90)
        c = np.random.rand() * 10 - 5
        variation = np.random.rand() * 2
        print("Planar parameter:", ma, c, variation)
        func = lambda x: ma * x + c + np.random.normal(0, np.sqrt(variation))
    elif choice == "perlin":
        # Old params 3, 1.5, 5
        octaves = int(np.random.rand() * 10) + 1  # Affects terrain roughness
        speed = np.random.rand() * 10  # affects rate of variation
        offset = np.random.rand() * 500  # A randomness based on shift
        scale = np.random.rand() * 5 + 1  # A randomness based on shift
        print("Perlin parameters:", octaves, speed, offset, scale)
        func = lambda x: scale * pnoise1(speed * x + offset, octaves
                                         )  # Perlin noise
    elif choice == "step":
        # Step
        c = np.random.random_sample()
        func = lambda x: 0 if x < c else 2  # Step
    elif choice == "simonsberg":
        if path is None:
            path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                "simonsberg.svg")
        func, _, _ = extract_surface_from_svg(path)
    else:
        raise ValueError("Invalid choice of environment.")

    f = np.vectorize(func)

    return f
Example #34
0
def generate_chunk(x, y):
    chunk_data = []
    for y_pos in range(CHUNK_SIZE):
        chunk_data.append([])
        for x_pos in range(CHUNK_SIZE):
            target_x = x * CHUNK_SIZE + x_pos
            target_y = y * CHUNK_SIZE + y_pos
            tile_type = 0  # nothing

            height = int(noise.pnoise1(target_x * 0.1, repeat=9999999) * 5)

            if target_y > 8 - height:
                tile_type = 2  # dirt

            elif target_y == 8 - height:
                tile_type = 1  # grass

            elif target_y == 8 - height - 1:
                if random.randint(1, 5) == 1:
                    tile_type = 3  # plant

            if target_y == 3 - height - 1:
                if random.randint(1, 10) == 1:
                    tile_type = 11  # tree

            chunk_data[y_pos].append([[target_x, target_y], tile_type,
                                      [x_pos, y_pos]])

    chunk_data = load_map(chunk_data)

    return chunk_data
Example #35
0
def get_random_signal(signal_size):
    random_type = random.choice(['flat', 'gaussian', 'multi_gaussian', 'perlin'])
    signal = []

    if random_type == 'flat':
        signal = [random.randint(0, 1000)] * signal_size

    elif random_type == 'gaussian':
        mean = random.uniform(300, 600)
        stdev = random.uniform(10, 500)
        signal = [int(random.gauss(mean, stdev)) for _ in range(signal_size)]

    elif random_type == 'multi_gaussian':
        while len(signal) < signal_size:
            length = random.randint(100, 500)
            mean = random.uniform(300, 600)
            stdev = random.uniform(10, 500)
            signal += [int(random.gauss(mean, stdev)) for _ in range(length)]

    elif random_type == 'perlin':
        octaves = random.randint(1, 4)
        step = random.uniform(0.001, 0.04)
        start = random.uniform(0.0, 1.0)
        factor = random.uniform(10, 300)
        mean = random.uniform(300, 600)
        signal = [int(mean + factor * noise.pnoise1(start + (i * step), octaves))
                  for i in range(signal_size)]

    signal = signal[:signal_size]
    return ','.join(str(x) for x in signal)
Example #36
0
 def update(self):
     self.framecount += 1
     x_off = self.framecount * 0.0003
     y_off = x_off + 20
     x = noise.pnoise1(x_off) * self.surface.get_width()
     y = noise.pnoise1(y_off) * self.surface.get_height()
     # every 8th frame a new bean
     print len(self.beans)
     if self.framecount % 8 == 0:
         self.beans.append(Bean(self.surface, self.beans, { 
             "x" : x, 
             "y" : y, 
             "x_off" : x_off, 
             "y_off" : y_off}))
     for bean in self.beans:
         bean.draw()
Example #37
0
def addNoise():
    global points, gp
    # Add noise
    counter = -1

    # Noise params
    base = random.randint(0, 100)
    octaves = random.randint(9, 12)
    persistence = random.uniform(1.2, 5.8)
    lacunarity = random.uniform(2.1, 2.9)

    print('b:' + str(base) + ' o:' + str(octaves) + ' p:' + str(persistence) +
          ' l:' + str(lacunarity))

    gp['params']['b'] = base
    gp['params']['o'] = octaves
    gp['params']['p'] = persistence
    gp['params']['l'] = lacunarity

    for line in points:
        for j in range(len(line)):
            counter += 1
            pn1 = pnoise1(
                counter / segments_total * 0.25,
                octaves,  # octaves 9 - 12
                persistence,  # persistence 1.2 - 6.2
                lacunarity,  # lacunarity 2.1 - 3.15
                64,  # repeat 1024
                base  # base 0.0
            )
            line_inc[j][1] += pn1 * 8
            line[j][1] += line_inc[j][1]

            line_inc[j][0] += pn1 * 3
            line[j][0] += line_inc[j][0]
Example #38
0
def colour_for_pixel(pixel, sequence_number):
    modifier = pixel.modifier
    colours = pixel.colours
    duration = pixel.duration
    offset = pixel.offset
    proportion = ((sequence_number /
                   (FRAMES_PER_SECOND * duration)) + offset) % 1
    start_of_period = int((sequence_number + (FRAMES_PER_SECOND * duration) -
                           (offset * FRAMES_PER_SECOND * duration)) %
                          (FRAMES_PER_SECOND * duration)) == 0
    if modifier == 'noise':
        noise_factor = (sequence_number /
                        (FRAMES_PER_SECOND * duration)) + offset
        return lerp_colours(colours, (pnoise1(noise_factor) + 1) / 2)
    elif modifier == 'smooth':
        return lerp_colours(colours, proportion, back_to_start=True)
    elif modifier == 'random':
        if start_of_period:
            return choice(colours)
        else:
            return None  # Use previous colour
    elif modifier == 'blink':
        if start_of_period:
            return choice(colours[1:] or [(255, 255, 255)])
        else:
            return colours[0]
    elif modifier == 'sparkle':
        if random() < offset:
            return choice(colours[1:] or [(255, 255, 255)])
        else:
            return colours[0]
    else:
        colour_index = int(len(colours) * proportion)
        return colours[colour_index]
Example #39
0
    def alive_trigger(self, count_seed):
        """
        This is triggered frequently, when the aliveness is turned on.

        :param float count_seed:   seed value for randomization

        :return:    True if the module updated something
        :rtype:     bool
        """
        currentTime = int(round(time.time() * 1000))
        updated = False
        if Preferences.get('behaviour', 'blink', False):
            if (currentTime -
                    self.dofs['lid'].last_set_time) > self.blink_delay:
                updated = self.blink(self.blink_speed / 1000.0)

        if Preferences.get('behaviour', 'gaze', False):
            if (currentTime -
                    self.dofs['horizontal'].last_set_time) > self.look_delay:
                # Update random looking position
                # if Robot.look_at_position == self.last_look_position:
                for i in range(len(self.last_look_position)):
                    # Add i to the seed for different x, y, z values
                    self.last_look_position[i] = pnoise1(count_seed + i, 1)
                updated = self.look()

        return updated
Example #40
0
 def test_perlin_1d_octaves_range(self):
     from noise import pnoise1
     for i in range(-1000, 1000):
         for o in range(10):
             x = i * 0.49
             n = pnoise1(x, octaves=o + 1)
             self.assertTrue(-1.0 <= n <= 1.0, (x, n))
Example #41
0
def perlin_noise1(x,
                  octaves=1,
                  gain=0.5,
                  lacunarity=2,
                  amp=1,
                  repeat=1024,
                  base=0):
    if type(x) not in [np.ndarray, list]:
        return amp * fit_11_to_01(
            pnoise1(x, octaves, gain, lacunarity, repeat, base))
    else:
        r = np.empty((len(x), ), dtype=np.float64)
        for i, d in enumerate(x):
            r[i] = amp * fit_11_to_01(
                pnoise1(d, octaves, gain, lacunarity, repeat, base))
        return r
Example #42
0
def p(x):
    return noise.pnoise1(x+base,
                         octaves=octaves,
                         lacunarity=lacunarity,
                         base=0,
                         repeat=repeat,
                         persistence=persistence
                        )
Example #43
0
 def value(self,t):
     p = noise.pnoise1(t*self.frequency,
                       octaves=self.octaves,
                       lacunarity=self.lacunarity,
                       persistence = self.persistence,
                       repeat = self.repeat,
                       base=self.base)
     return self.mean + self.amplitude*p
Example #44
0
def test_noise(base, step, viz=False):
    global pdist, qdist
    for i in range(ITERATIONSIZE):
        p = noise.pnoise1(base + step * i)
        q = generators._noise1(base + step * i)
        if viz:
            print '%+0.4f | %s | %s | %+0.4f'%(p, _fmt(p), _fmt(q), q)
        pdist[_rmap(p, -1.0, 1.0, DISTRIBUTION_BUCKETS)] += 1
        qdist[_rmap(q, -1.0, 1.0, DISTRIBUTION_BUCKETS)] += 1
Example #45
0
def on_draw():
    global min,max
    window.clear()
    glLoadIdentity()
    glTranslatef(0, 0, -1)
    r = range(256)
    glBegin(GL_LINE_STRIP)
    for i in r:
        x = float(i) * span / points - 0.5 * span
        y = pnoise1(x + base, octaves)
        glVertex3f(x * 2.0 / span, y, 0)
    glEnd()
Example #46
0
def noise_color(illuminators, color, step, amplitude):
    base_color = Color(color.r, color.g, color.b)
    temp_color = colorsys.rgb_to_hls(remap(base_color.r, 0, 255, 0, 1), remap(base_color.g, 0, 255, 0, 1), remap(base_color.b, 0, 255, 0, 1))

    while True:
        lightness = min(0.1+temp_color[1]*pnoise1(time.clock()*step)*amplitude*0.1, 1)

        final_color_rgb = colorsys.hls_to_rgb(temp_color[0], lightness, temp_color[2])

        final_color = Color(int(remap(final_color_rgb[0], 0, 1, 0, 255)), int(remap(final_color_rgb[1], 0, 1, 0, 255)), int(remap(final_color_rgb[2], 0, 1, 0, 255)))

        for illuminator in illuminators:
            illuminator.set(final_color)

        time.sleep(0.001)
    def render(self, ctx):
        self.current_x = cx
        self.current_y = cy
        self.prev_x = cx
        self.prev_y = cy
        self.angle = 0 # random.random() * math.pi*2

        for i in range(self.segments):

            pn1 = pnoise1 (
                self.noise_seed + ( (i / self.segments) * self.noise_speed ),
                2,
                0.2,  # persintence 0.2
                4.0,  # Lacunarity 2.0
                1024,   # repeat 1024
                self.noise_base
            )
            # print(str(pn1))

            _cos = math.cos(self.angle)
            _sin = math.sin(self.angle)
            self.current_x = self.current_x + self.dis * _cos
            self.current_y = self.current_y + self.dis * _sin

            self.angle += pn1 / 60.0

            self.segment_w_current = self.segment_w * pn1 * 2

            col.a = ( 0.5 + ( pn1 * 0.5 ) ) * self.alpha_correction
            col.rotateHue( pn1 / self.rotate_hue )
            # col.setSat( 0.0 )
            ctx.set_source_rgba( *col.rgba)
            # draw.plot( ctx, self.current_x, self.current_y, 1)

            ABx =  self.current_x - self.prev_x
            ABy =  self.current_y - self.prev_y
            NABx = ABx / self.dis
            NABy = ABy / self.dis
            PNABx = -NABy
            PNABy =  NABx
            Dx1 = self.current_x + self.segment_w_current * PNABx
            Dy1 = self.current_y + self.segment_w_current * PNABy
            Dx2 = self.current_x - self.segment_w_current * PNABx
            Dy2 = self.current_y - self.segment_w_current * PNABy
            draw.line( ctx, Dx1, Dy1, Dx2, Dy2)

            self.prev_x = self.current_x
            self.prev_y = self.current_y
Example #48
0
    def horizon(self):
        print "Parsing map_template for horizon gen"
        '''This method divides ground and sky. It opens and parses the xml
        file generated previously.'''

        ###Begin column height noise, generates hills and valleys at horizon###
        self.hpoints = 256
        self.hspan = 15.0
        self.hoctaves = 8 #Determines variation in peaks and valleys. Lower numbers produce better results.
        self.hbase = 0 #Not sure what this does but it still changes stuff.

        for i in xrange(self.columns):
            x = float(i) * self.hspan / self.hpoints - 0.5 * self.hspan
            y = pnoise1(x + self.hbase, self.hoctaves)
            self.column_height_offset.append(y*3)
        ###End column height noise###

        #Open and parse the xml file to change cells according to noise#
        tree = ET.parse("map_template.xml")
        root = tree.getroot()

        print "Finished root parsing"

        #The counters that iterate for every column and cell.
        self.col_counter = 0
        self.cell_counter = 0

        for column in root.iter('column'):
            self.col_height = self.col_height + self.column_height_offset[self.col_counter]
            self.column_height_values.append(self.col_height-1)
            self.col_counter += 1
            self.cell_counter = 0

            for cell in column:
                self.cell_counter += 1
                if self.cell_counter > self.col_height:
                    cell.set('tile', 'air')

        tree.write("terrain.xml")
        root.clear()
        self.ground_layers()
Example #49
0
def on_draw():
    global x

    window.clear()
    #glLoadIdentity()

    scale = pnoise1(time,octaves=1) # pnoise1(time,octaves)  range: -1 -> 1
    scale = (scale + 1) * 0.5 # range: 0 -> 1
    #print scale
    scale *= window.height
    y = scale;
    size = 2

    # DRAW LITTLE SQUARE
    glColor4f(1,0,0,1.0)
    glBegin(GL_QUADS)

    glVertex2f(x,y)
    glVertex2f(x + size,y)
    glVertex2f(x + size, y + size)
    glVertex2f(x,y + size)

    glEnd()

    # DRAW BLACK RECTANGLE TO CLEAR THE WAY
    glColor4f(0,0,0,1.0)
    glBegin(GL_QUADS)

    glVertex2f(x+size,0)
    glVertex2f(x + 30,0)
    glVertex2f(x + 30,window.height)
    glVertex2f(x+size,window.height)

    glEnd()

    #glColor4f(1,1,1,1.0)
    #pyglet.text.Label(str(scale),x=100,y=100)

    x+= 1
    if x>window.width:
        x = 0
Example #50
0
 def test_perlin_1d_base(self):
     from noise import pnoise1
     self.assertEqual(pnoise1(0.5), pnoise1(0.5, base=0))
     self.assertNotEqual(pnoise1(0.5), pnoise1(0.5, base=5))
     self.assertNotEqual(pnoise1(0.5, base=5), pnoise1(0.5, base=1))
Example #51
0
 def test_perlin_1d_range(self):
     from noise import pnoise1
     for i in range(-10000, 10000):
         x = i * 0.49
         n = pnoise1(x)
         self.assertTrue(-1.0 <= n <= 1.0, (x, n))
Example #52
0
def noise1D(val, seed):
	seed = parse_seed(seed)
	return pnoise1((val/100.) + seed)
Example #53
0
"""generated 2D terrain"""
import noise


def get_terrain(top_margin, width_margin, (screen_width, screen_height),
                itter_width, distance):
    """gets random terrainNN"""
    pos_wght = 0.01/2.0
    dist_wght = 0.01/2.0
    height_amp = 70.0
    width_margin = int(width_margin)
    gen_terrain = lambda x: (x, top_margin +
                             noise.pnoise1(x*pos_wght+distance*dist_wght)
                             * height_amp)
    terrain = [gen_terrain(x) for x in xrange
               (-width_margin, screen_width+width_margin, itter_width)]
    # round of bottom
    terrain.append((screen_width+width_margin, screen_height))
    terrain.append((-width_margin, screen_height))
    return [terrain]
Example #54
0
 def get_color(self):
     h = abs(noise.pnoise1((self.x_off + self.y_off) / 2)) * 360
     color = pygame.Color(0, 255, 0, 100)
     print color
     # color.hsva = (h, 100, 100, 4)
     return(color)
Example #55
0
def noise1D(val, seed, sharp=100.):
	seed = parse_seed(seed)
	return pnoise1((val/sharp) + seed)
def render():

    req = requests.get(url=CONFIG['palett_esAPI']['url'])
    palette = req.json()
    print(palette)
    print(('http://palett.es/' + '-'.join(palette)).replace('#', ''))
    # palette = ['#2b2c27', '#ff5279', '#fdaad0', '#e4def8', '#f8faff']

    w = 600
    h = 600
    cx = w / 2
    cy = h / 2
    r = w / 2 - 40
    num_stains = 6
    points = []

    ims = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h) # Simple Surface
    ctx = cairo.Context(ims)

    # Clear
    ctx.rectangle(0, 0, w, h) # Rectangle(x0, y0, x1, y1)
    ctx.set_source_rgb(0.1, 0.1, 0.1)
    ctx.fill ()

    for j in range(num_stains):

        ctx.set_line_width(random.random() + 0.5)

        r = w / 2 - random.randint(0, w / 4)

        c1 = Colz()
        c1.setHex(random.choice(palette))
        c2 = Colz()
        c2.setHex(random.choice(palette))

        cx, cy = random.randint(0, w), random.randint(0, h)

        ctx.set_operator(cairo.OPERATOR_SOURCE)
        effect = random.randint(1, 10)
        global_alpha = 1.0
        if effect == 1:
            ctx.set_operator(cairo.OPERATOR_OVERLAY)
            points.append([cx, cy])
        if effect == 2:
            global_alpha = 0.5
            ctx.set_operator(cairo.OPERATOR_ADD)
            points.append([cx, cy])

        ctx.save()
        ctx.translate(cx, cy)
        ctx.rotate(random.random() * math.pi * 2)
        ctx.translate(-cx, -cy)
        ctx.restore()

        num_lines = 512
        noise_offset = random.randint(0, num_lines)

        for i in range(num_lines):
            percent = i / num_lines

            pn1 = pnoise1(
                percent,
                2,    # octaves
                1.1,  # persistence, amplitude of each succesive octave
                8.0,  # lacunarity, frecuency
                1,    # repeat
                noise_offset # initial offset
            )
            # print(str(pn1))

            cmix = Colz.interpolate(c1, c2, percent)
            if percent < 0.5:
                cmix = Colz.interpolate(c1, c2, percent * 2)
            else:
                cmix = Colz.interpolate(c2, c1, (percent - 0.5) * 2)

            ctx.set_source_rgba(*cmix.rgb, global_alpha)

            temp_r = r + (pn1 * random.randint(1, 250))

            a = math.pi * 2
            dx = cx + temp_r * math.cos(a * percent)
            dy = cy + temp_r * math.sin(a * percent)
            draw.line(ctx, cx, cy, dx, dy)

    gp = collections.OrderedDict()
    gp['name'] = 'flowight'
    gp['params'] = collections.OrderedDict()
    gp['params']['flowers'] = num_stains
    gp['params']['lines'] = num_lines

    footline = name.footline(gp)
    draw.footline(ctx, footline, 8, h - 10)
    filename = name.filename(gp)

    return ims, filename, footline
Example #57
0
def wave():
    return  [int(pnoise1((i/100.0) * base, 4) * 100) for i in range(0, 128)]
Example #58
0
def noise(t):
    return pnoise1(t % 1000.0, 2)
 def random2D_vector(self):
   v = PVector(noise.pnoise1(PVector.tx), noise.pnoise1(PVector.ty))
   PVector.tx += 0.01
   PVector.ty += 0.01
   v.normalize()
   return v
Example #60
0
def main():
	parser = optparse.OptionParser()
	parser.add_option('--seed', default=create_seed(), dest='seed', help='')
	parser.add_option('--fmt', default='pdf', dest='fmt', help='')
	parser.add_option('--nx', default=100, dest='nx', type='int', help='')
	opts, args = parser.parse_args()

	print('seed = %s' % opts.seed)	
	random.seed(opts.seed)

	w, h = 16 * 72, 10 * 72

	surface = lib.create_surface(opts.fmt, os.path.basename(__file__), w, h)
	context = cairo.Context(surface)

	context.rectangle(0, 0, w, h)
	context.set_source_rgb(1, 1, 1)
	context.fill()

	pad = w/16.0
	pa = Pt(pad, pad + (h - 2*pad) * random.random())
	pb = Pt(w - pad, pad + (h - 2*pad) * random.random())

	dx = pb.x - pa.x
	dy = pb.y - pa.y
	n = math.sqrt(dx*dx + dy*dy)
	m = dy / dx

	context.move_to(pa.x, pa.y)
	context.line_to(pb.x, pb.y)
	context.set_source_rgb(*color_of(0xaa, 0xaa, 0xaa))
	context.stroke()

	di = dx / opts.nx
	context.set_line_width(1.0)
	context.set_source_rgb(*color_of(0xee, 0xee, 0xee))
	for i in range(opts.nx + 1):
		context.move_to(pa.x + di*i, pad)
		context.line_to(pa.x + di*i, h - 2*pad)
		context.stroke()

	dj = 0.0
	r = 5

	pts = []
	for i in range(opts.nx + 1):
		x = di*i
		pts.append(Pt(pa.x + x, x*m + pa.y + r*noise.pnoise1(x/10.0, 1)))
		#pts.append(Pt(pa.x + x, x*m + pa.y + dj))
		#dj = max(min(dj + random.random()*r - r/2.0, r), -r)

	context.move_to(pts[0].x, pts[0].y)
	for i in range(1, len(pts)):
		# context.line_to(pts[i].x, pts[i].y)
		a = pts[i - 1]
		b = pts[i]
		context.curve_to(
			a.x + di/2.0, a.y,
			b.x - di/2.0, b.y,
			b.x, b.y)
	context.set_source_rgb(*color_of(0xff, 0x00, 0xff))
	context.stroke()


	lib.commit(surface, os.path.basename(__file__) + '.png')