示例#1
0
def main():
    imgpath = "lena.png"
    m = "s&p"
    cv2.imshow("Image", noise.noise(imgpath, "0"))
    cv2.imshow("Image" + m, noise.noise(imgpath, m))
    cv2.waitKey(0)
    cv2.destroyAllWindows()
示例#2
0
	def fly(self):

		s = self
		s.t += 1

		s.w1[1] = -1+u.trapwave(s.t*s.aspd)*3
		s.w2[1] = -2+u.trapwave(s.t*s.aspd)*8
		s.w3[1] = -1+u.trapwave(s.t*s.aspd+math.pi*0.2)*12

		s.w2[0] = -3+math.sin(s.t*s.aspd-math.pi*0.5)*2
		s.w3[0] = -5+math.sin(s.t*s.aspd-math.pi*0.5)*3


		s.wingCoordToRL(5,s.w1)
		s.wingCoordToRL(6,s.w2,s.w1,s.skel[5][0])
		s.wingCoordToRL(7,s.w3,s.w2,s.skel[6][0],s.skel[5][0])

		s.wingCoordToRL(8,s.w1)
		s.wingCoordToRL(9,s.w2,s.w1,s.skel[5][0])
		s.wingCoordToRL(10,s.w3,s.w2,s.skel[6][0],s.skel[5][0])


		s.to(4,0,-0+math.sin(s.t*s.aspd+math.pi)*10)
		s.to(1,0,-5+math.sin(s.t*s.aspd)*1)

		s.to(12,0,-40)
		s.to(14,0,-40)

		s.to(13,0,10+math.sin(s.t*s.aspd)*5 + 10*noise.noise(s.t*s.aspd*0.01,1)-5)
		s.to(15,0,10+math.sin(s.t*s.aspd)*5 + 10*noise.noise(s.t*s.aspd*0.01,2)-5)

		#s.x += s.v[0]*s.dir
		s.y += 0.2*self.s*math.sin(s.t*s.aspd+math.pi)#30.5*s.v[1]+0.5*s.v[1]*(0.5*(math.sin(s.t*s.aspd)+1))
示例#3
0
	def rest(self):
		s = self
		s.t +=1
		for i in range(0,len(s.skel)):
			if i != 6 and i != 1:
				s.to(i,0,s.ssk[i][0]+noise.noise(i*0.05,s.t*0.05),5)
		s.to(6,0,30+math.cos(s.t*s.aspd*0.5)*10)

		noi = max(min((noise.noise(s.t*s.aspd*0.05)-0.4)*40,1),-1)
		s.to(1,0,-5+noi*50,5)
		s.to(0,0,-40-noi*40,5)
示例#4
0
	def walk(self):
		s = self
		s.t += 1
		s.f1 = 6 + math.cos(s.t*s.aspd*2)*2 +noise.noise(s.t*s.aspd)*2
		s.f2 = 8 + math.cos(s.t*s.aspd*2)*2
		#print self.animations
		if self.status[1] == "":
			for i in range(0,len(s.skel)):
				for j in range(0,max(0,len(self.animations))):
					for a in self.animations[j]:
						if i == a[0][0]:
						#print "y"
							return
				s.to(i,0,s.ssk[i][0]+10*(noise.noise(i*0.05,s.t*0.05)-0.5),2)
示例#5
0
	def rest(self):

		s = self
		#s.t = -1 #math.pi
		s.t2 += 1
		s.to(5,0,20+180*2*((s.skel[5][0]>0)-0.5),10)
		s.to(6,0,-20+180*2*((s.skel[6][0]>0)-0.5),10)
		s.to(7,0,20-180*2*((s.skel[10][0]<0)-0.5),10)

		s.to(8,0,20+180*2*((s.skel[8][0]>0)-0.5),10)
		s.to(9,0,-20+180*2*((s.skel[9][0]>0)-0.5),10)
		s.to(10,0,20-180*2*((s.skel[10][0]<0)-0.5),10)

		s.to(12,0,30,10)
		s.to(14,0,30,10)
		s.to(13,0,100,10)
		s.to(15,0,100,10)

		noi = max(min((noise.noise(s.t2*s.aspd*0.5)-0.3)*50,1),-1)
		s.to(1,0,-10+noi*20,5)
		s.to(1,1,5-noi*2,5)
		s.to(4,0,-10+noi*10,5)

		s.x += s.v[0]*s.dir
		s.y += s.v[1]
		if s.y>=0:
			s.v[1] = 0
			s.v[0] = 0
			s.y = 0
		else:
			s.v[1] += 0.2*s.s
		if random.random() < 0.02 and s.v[1] == 0:
			s.v[1]=-1*s.s
			r = random.choice([1,1])
			s.v[0]+=0.5*r*s.s
示例#6
0
	def rest(self):
		s = self
		s.t+=1
		noi = noise.noise(s.t*s.aspd*0.5)
		s.f1 += (6+(noi*5)-s.f1)/2
		s.s1 += (1-(noi*4)-s.s1)/2
		s.s2 += (1-(noi*4)-s.s2)/2
def generate_noise(width, height):
    noise_map = []

    points = 256
    span = 5.0
    speed = 1.0

    botom_range = 0
    top_range = 0

    xoff = BASE_XOFF
    for _x in range(width):
        new_row = []
        xoff = float(_x) * span / points - 0.5 * span
        for _y in range(height):
            noise_value = noise(xoff + BASE_XOFF)
            new_row.append(noise_value)
            xoff += random.random()

            if noise_value < botom_range:
                botom_range = noise_value
            elif noise_value > top_range:
                top_range = noise_value
        noise_map.append(new_row)

    difference = float(top_range - botom_range)
    for x in range(width):
        for y in range(height):
            noise_map[x][y] = (noise_map[x][y] - botom_range) / difference

    return noise_map
def gen_recover_period(prange, ntimes, npers, randtimes = 0.0, rantnormp = 0.0, snrnoise = 0.0, normpropnoise = 0.0, samples = 100):
    """Generate some periodic data and then try to recover the maximum period under various conditions.

    prange = period to analyse (kicking off with a single period) with lower bound and upper bound for search
    ntimes number of times to generate signal for
    npers number of periods (possibly fractional) to scan for
    randtimes whether we vary the sample times 0.0 none, 1 probably max
    rantnormp variation in times proortion between uniform (0.0) and gaussian (1.0)
    snr signal to noise ration of noise to add 0 for None
    normpropnoise proportion of noise uniform (0.0) or gaussian (1.0)
    samples is the number of samples for the periodogram

    Return fractional error"""

    lbound, period, ubound = prange

    timelist, amps = siggen.siggen(period, ntimes=ntimes, npers=npers, randv=randtimes, unorm=rantnormp, randphase=True)

    if snrnoise > 0.0:
        amps = noise.noise(amps, snrnoise, normpropnoise)

    # OK now lets do our stuff

    model = LombScargle().fit(timelist, amps, 0.001)
    periods = np.linspace(lbound, ubound, samples)
    pgram = model.periodogram(periods)

    # Find maximum

    maxes = argmaxmin.maxmaxes(periods, pgram)
    if len(maxes) == 0:
        return  1.0

    maxp = periods[maxes[0]]
    return abs(maxp - period) / period
    def __init__(self,
                 seed,
                 n_state,
                 n_action,
                 batch_size=64,
                 buffer=1e5,
                 gamma=0.99,
                 lr_actor=1e-4,
                 lr_critic=1e-3,
                 weight_decay=0,
                 tau=1e-3):
        self.batch_size = batch_size

        #init actor
        self.local_actor = Actor(n_state, n_action, seed).to(device)
        self.target_actor = Actor(n_state, n_action, seed).to(device)
        self.optim_actor = torch.optim.Adam(self.local_actor.parameters(),
                                            lr=lr_actor)
        #init critic
        self.local_critic = Critic(n_state, n_action, seed).to(device)
        self.target_critic = Critic(n_state, n_action, seed).to(device)
        self.optim_critic = torch.optim.Adam(self.local_critic.parameters(),
                                             lr=lr_critic,
                                             weight_decay=weight_decay)

        #init memory
        self.memory = memory(int(buffer), device, seed)
        self.tau = tau
        self.gamma = gamma
        self.noise = noise(n_action, seed=seed)
示例#10
0
文件: sl.py 项目: puzzlet/cgkit
def float_noise(*args):
    """Returns a float value which is a (pseudo) random function of its arguments.

    This function is imported from the noise module.
    """
    
    la = len(args)
    if la==1:
        return noise.noise(args[0])
    elif la==2:
        return noise.noise(args[0],args[1])
    elif la==3:
        return noise.noise(args[0],args[1],args[2])
    elif la==4:
        return noise.noise(args[0],args[1],args[2],args[3])
    else:
        raise TypeError("the function takes between 1 and 4 arguments (%s given)"%(la))
示例#11
0
def test_noise(img):
    print('\t[Loading...] Calculating..')
    start = perf_counter()
    result = noise(img, -9, 20)
    finish = perf_counter()
    cv2.imshow('Add noise', result)
    print('\tTime: ' + str(finish - start))
    return result
示例#12
0
 def fill(self):
     for y in range(0, Chunk.size):
         for x in range(0, Chunk.size):
             rand = noise((x + self.x) / 8, (y + self.y) / 8, .1, octaves=2)
             if rand < .35 and rand > -.35:
                 value = 1
             else:
                 value = 0
             self.grid[Chunk.size - 1 - y][x] = value
示例#13
0
def fill(zone):
    noise_f = noise(6)
    bg = generate(zone.y, zone.x, noise_f)

    for y, row in enumerate(bg):
        for x, col in enumerate(row):
            val = FILTERS['mountains'](col)
            if val > 0.25:
                zone.set_field(y, x, '=')
示例#14
0
def fill(zone):
    noise_f = noise(6)
    bg = generate(zone.y, zone.x, noise_f)

    for y, row in enumerate(bg):
        for x, col in enumerate(row):
            val = FILTERS['mountains'](col)
            if val > 0.25:
                zone.set_field(y, x, '=')
示例#15
0
文件: julia.py 项目: crossjam/peyote
def draw():
    global noisy, WIDTH, HEIGHT
    set_line_width(1.0)

    set_source_rgba(1.0,1.0,1.0,0.2)
    rectangle(0,0,WIDTH,HEIGHT)
    fill()
    
    for i in range(num):
        x, y = pos[i]

        # print "Drawing circle at: %s, %s" % (x, y)
        
        set_source_rgba(R1,G1,B1)
        arc(x, y, 4, 0, 2 * pi)
        stroke()
        
        set_source_rgba(R2,G2,B2,100/255.0)
        arc(x, y, 4.5, 0, 2 * pi)
        stroke()

        set_source_rgba(100/255.0,100/255.0,100/255.0,1.0)
        vel[i][0] = 10 * noise(200+x*0.007, 200+y*0.007, noisy*2)*cos(4*pi*noise(x*0.003,y*0.003, noisy))
        vel[i][1] = 10 * noise(200+x*0.007, 200+y*0.007, noisy*2)*sin(4*pi*noise(x*0.003,y*0.003, noisy))

        '''
        # If you want to adjust the acceleration of the circles
        for j in range(num):
            if j != i:
                jx, jy = pos[j]
                den1, den2 = dist(x, y, jx, jy), (5+dist(x, y, jx, jy)) ** 2

                acc[i][0] += (x-jy)/den1/den2
                acc[i][1] += (y-jy)/den1/den2
        '''
        
        pos[i] += vel[i]
        if not (0 < pos[i][0] < WIDTH) or not (0 < pos[i][1] < HEIGHT):
            pos[i][0], pos[i][1] = randrange(0, WIDTH), randrange(0, HEIGHT)
            vel[i] = 0

        # acc[i] = 0
        
    noisy += 0.007
示例#16
0
def hatch(IM, sc=16):
    print("hatching...")
    PX = IM.load()
    w, h = IM.size
    lg1 = []
    lg2 = []
    for x0 in range(w):
        for y0 in range(h):
            x = x0 * sc
            y = y0 * sc
            if PX[x0, y0] > 144:
                pass

            elif PX[x0, y0] > 64:
                lg1.append([(x, y + sc / 4), (x + sc, y + sc / 4)])
            elif PX[x0, y0] > 16:
                lg1.append([(x, y + sc / 4), (x + sc, y + sc / 4)])
                lg2.append([(x + sc, y), (x, y + sc)])

            else:
                lg1.append([(x, y + sc / 4), (x + sc, y + sc / 4)])
                lg1.append([(x, y + sc / 2 + sc / 4),
                            (x + sc, y + sc / 2 + sc / 4)])
                lg2.append([(x + sc, y), (x, y + sc)])

    lines = [lg1, lg2]
    for k in range(0, len(lines)):
        for i in range(0, len(lines[k])):
            for j in range(0, len(lines[k])):
                if lines[k][i] != [] and lines[k][j] != []:
                    if lines[k][i][-1] == lines[k][j][0]:
                        lines[k][i] = lines[k][i] + lines[k][j][1:]
                        lines[k][j] = []
        lines[k] = [l for l in lines[k] if len(l) > 0]
    lines = lines[0] + lines[1]

    for i in range(0, len(lines)):
        for j in range(0, len(lines[i])):
            lines[i][j] = int(lines[i][j][0] +
                              sc * noise.noise(i * 0.5, j * 0.1, 1)
                              ), int(lines[i][j][1] +
                                     sc * noise.noise(i * 0.5, j * 0.1, 2)) - j
    return lines
示例#17
0
def getcontours(IM, sc=2):
    print("generating contours...")
    IM = find_edges(IM)
    IM1 = IM.copy()
    IM2 = IM.rotate(-90, expand=True).transpose(Image.FLIP_LEFT_RIGHT)
    dots1 = getdots(IM1)
    contours1 = connectdots(dots1)
    dots2 = getdots(IM2)
    contours2 = connectdots(dots2)

    for i in range(len(contours2)):
        contours2[i] = [(c[1], c[0]) for c in contours2[i]]
    contours = contours1 + contours2

    for i in range(len(contours)):
        for j in range(len(contours)):
            if len(contours[i]) > 0 and len(contours[j]) > 0:
                if sum_distance(contours[j][0], contours[i][-1]) < 8:
                    contours[i] = contours[i] + contours[j]
                    contours[j] = []

    for i in range(len(contours)):
        contours[i] = [contours[i][j] for j in range(0, len(contours[i]), 8)]

    contours = [c for c in contours if len(c) > 1]

    for i in range(0, len(contours)):
        contours[i] = [(v[0] * sc, v[1] * sc) for v in contours[i]]

    for i in range(0, len(contours)):
        for j in range(0, len(contours[i])):
            contours[i][j] = int(contours[i][j][0] +
                                 10 * noise.noise(i * 0.5, j * 0.1, 1)), int(
                                     contours[i][j][1] +
                                     10 * noise.noise(i * 0.5, j * 0.1, 2))

    return contours
示例#18
0
 def init(self):
     self.field = []
     xoff = 0
     xrand = Prandom(0, 1)
     yrand = Prandom(0, 1)
     for i in range(self.cols):
         yoff = 0
         tmp = []
         for j in range(self.rows):
             theta = Pmap(noise(xoff + xrand, yoff + yrand), 0, 1, 0,
                          2 * pi)
             assert theta < 2 * pi
             # Polar to cartesian coordinate transformation to get x and y components of the vector
             tmp.append(PVector(cos(theta), sin(theta)))
             yoff += 0.01
         self.field.append(tmp)
         xoff += 0.01
示例#19
0
 def _generate(self, x: int):
     l = []
     y = 0
     for _ in range(round((noise(x * 0.01) + 1) * 50) + 50):
         l.append(blocks.Stone((x, y)))
         y += 1
     for _ in range(3):
         l.append(blocks.Dirt((x, y)))
         y += 1
     l.append(blocks.Grass((x, y)))
     y += 1
     for _ in range(5):
         l.append(blocks.Air((x, y)))
         y += 1
     for _ in range(255 - len(l)):
         l.append(blocks.Air((x, y)))
         y += 1
     self._generated[x] = l
示例#20
0
    for y, row in enumerate(bg):
        for x, col in enumerate(row):
            val = FILTERS['mountains'](col)
            if val > 0.25:
                zone.set_field(y, x, '=')


if __name__ == '__main__':
    from bmp import Bitmap
    size = 500

    def rgb(x):
        return (x, x, x)

    f = Bitmap('output.bmp', size, size)

    perlin = Perlin()
    pnoise_harmonic = noise(6)
    pnoise = perlin.noise

    n = generate(size, size, pnoise_harmonic)

    for y, row in enumerate(n):
        for x, col in enumerate(row):
            val = FILTERS['mountains'](col)
            f.set_pixel(y, x, rgb(val))

    f.flush()
    f.close()
示例#21
0
saveTime = time.time()
totalTime = saveTime - start_time
print("Totaly data prework time " + str(totalTime) + " seconds")

print(user_venc_in_plane)

#os.system("python /home/condauser/Documents/ao_seg/aorta_seg.py --path=/home/condauser/Documents/ao_seg/MK")

ppp = "/home/condauser/Documents/ao_seg/MK"
image, mrStruct, netflow = eddy(ppp)
eddyTime = time.time()
totalEddyTime = eddyTime - saveTime
print("Totaly eddy time " + str(totalEddyTime) + " seconds")
#gc.collect()

image, mrStruct = noise(image, mrStruct, netflow)
noiseTime = time.time()
totalNoiseTime = noiseTime - eddyTime
print("Totaly Noise time " + str(totalNoiseTime) + " seconds")
#gc.collect()

cc = TFrecord(mrStruct, user_venc_in_plane)
print("TFrecord finish")
io.savemat('MK/vel_struct.mat', {'mrStruct': mrStruct})
del mrStruct
jjj = Unet_test()
#del jj
aliasTime = time.time()
totalAliasTime = aliasTime - noiseTime
print("Totaly Aliasing time " + str(totalAliasTime) + " seconds")
#jjj = io.loadmat("/home/condauser/Documents/ao_seg/new_vel.mat")
示例#22
0
    print "Unable to open", ewfile, "error was", e.args[1]
    sys.exit(11)
except ValueError as e:
    print "Conversion error in", ewfile, "error was", e.args[0]
    sys.exit(12)

signals = []
for sig in siglist:
    nsig = sigdets()
    nsig.parse(sig)
    signals.append(nsig)

col2 = np.zeros_like(ewf[1])
col4 = col2 + 1.0
col6 = col2 + 1.0

for sig in signals:
    col2 += sig.apply(ewf[1], 0)
    col4 += sig.apply(ewf[1], 1)
    col6 += sig.apply(ewf[1], 2)

if snr != 0:
    col2 = noise.noise(col2, snr, gauss)
    col4 = noise.noise(col4, snr, gauss)
    col6 = noise.noise(col6, snr, gauss)
ewf[2] = col2
ewf[4] = col4
ewf[6] = col6

np.savetxt(outfile, ewf.transpose())
            if dp[pointer + 1][1] > dp[pointer + 1][3]:
                text += "0"
                index = 3
            else:
                text += "0"
                index = 1
        elif index == 3:
            if dp[pointer + 1][1] > dp[pointer + 1][3]:
                text += "1"
                index = 3
            else:
                text += "1"
                index = 1
        pointer += 1
    return text[::-1]


text = "amirhosseinahmadi"
print("Plain Text:", text)
huffman_encoded = huffman_encoder(text)
print("Huffman Encoding:", huffman_encoded)
conv_encoded = convolutional_enccoder(huffman_encoded)
print("Convolutional Encoding:", conv_encoded)
conv_encoded = [int(item) for item in conv_encoded]
noised_data = noise(conv_encoded)
noised_data = list(map(str, noised_data))
noised_data = "".join(noised_data)
viterbi_decoded = viterbi_decoder(noised_data)
print("Viterbi Decoding:", viterbi_decoded)
huffman_decoded = huffman_decoder(viterbi_decoded)
print("Huffman Decoding:", huffman_decoded)
示例#24
0
 def get_price_at_minutes(self, minutes):
     noise_seed(self.cost_seed)
     cost = self.cost_min + self.cost_range * noise(self.cost_offset +
                                                    minutes / 2000)
     return max(1, int(cost))
示例#25
0
    for y, row in enumerate(bg):
        for x, col in enumerate(row):
            val = FILTERS['mountains'](col)
            if val > 0.25:
                zone.set_field(y, x, '=')


if __name__ == '__main__':
    from bmp import Bitmap
    size = 500
    
    def rgb(x):
        return (x, x, x)

    f = Bitmap('output.bmp', size, size)

    perlin = Perlin()
    pnoise_harmonic = noise(6)
    pnoise = perlin.noise

    n = generate(size, size, pnoise_harmonic)

    for y, row in enumerate(n):
        for x, col in enumerate(row):
            val = FILTERS['mountains'](col)
            f.set_pixel(y, x, rgb(val))

    f.flush()
    f.close()
phasesr = np.arange(0.0, 1.0, res['pstep'])
phases = phasesr  * TWOPI
errs = np.zeros_like(times) + err

lo = []
mid = []
hi = []

s1 = []
s2 = []
s3 = []

for p in phases:
    sig = a1 * np.sin(f1 * times) + a2 * np.sin(f2 * times + p)
    if snr != 0:
        sig = noise.noise(sig, snr, gauss)
    if usegatspy:
        model = LombScargle().fit(times, sig, err)
        pgram = model.periodogram(periods)
    else:
        pgram = lsas(times, sig, errs, freqs)
    maxima = argmaxmin.maxmaxes(periods, pgram)
    if len(maxima) > 3:
        maxima = maxima[0:3]
    maxp = list(periods[maxima])
    h, m, l = maxp
    s1.append(h)
    s2.append(m)
    s3.append(l)
    maxp.sort()
    l, m, h = maxp
示例#27
0
suff = resargs['suff']

if suff is None:
    suff = '.' + string.replace("n%#.3g" % snr, ".", "_")
elif len(suff) == 0:
    print "Invalid suffix should be at least 1 char"
    sys.exit(11)
elif suff[0] != '.':
    suff = '.' + suff

errors = 0
ok = 0
for spec in specs:
    try:
        indata = np.loadtxt(spec, unpack=True)
        indata[ycolumn] = noise.noise(indata[ycolumn], snr, gauss)
        np.savetxt(spec + suff, indata.transpose())
    except IndexError:
        print "Invalid y column", ycolumn, "in", spec
        errors += 1
        continue
    except ValueError:
        print "Invalid values in", spec
        errors += 1
        continue
    except IOError as e:
        print "IO Error in", spec, "was", e.args[1]
        errors += 1
    ok += 1

if errors > 0:
示例#28
0
import encrypt
import parse_mat
import network_encoding
import noise
import viterbi_decoding
import decrypt

string = 'saharrajabi'
probs = parse_mat.parse('data\\freq.mat').get('freq')
codes = {}
print 'name: ' + string
source_encrypted = encrypt.encrypt(probs, string, codes)
print 'source encoder output: ' + source_encrypted
network_encrypted = network_encoding.encode(source_encrypted)
print 'network encoder output: ' + network_encrypted
network_encrypted = map(lambda x: int(x), list(network_encrypted))
noisy_data = noise.noise(network_encrypted)
noisy_data = ''.join(map(lambda x: str(x), noisy_data))
print 'noisy data: ' + noisy_data
err, network_decoded = viterbi_decoding.decode(noisy_data)
print 'network decoder output: ' + network_decoded
decoded = decrypt.decrypt(network_decoded, codes)
print 'source decoder output: ' + decoded
示例#29
0
r = deriv.sin(x)
print "r", deriv.v(r)
print "dr/dx", deriv.v(deriv.d(r, x))
print "dr/dy", deriv.v(deriv.d(r, y))
print "d2r/dx2", deriv.v(deriv.d(r, x, x))
print "d2r/dy2", deriv.v(deriv.d(r, y, y))
print "d2r/dx/dy", deriv.v(deriv.d(r, x, y))
print "d2r/dy/dx", deriv.v(deriv.d(r, y, x))

print
print
print

import noise

x = -1 + noise.noise(3)
y = 2 + noise.noise(7)

r = x, y, x + y, x - y, x / y, x * x, x * y, y * y

print ' '.join("%7.03f" % noise.E(x) for x in r), "E"
print ' '.join("%7.03f" % noise.var(x) for x in r), "variance"
print
print "covariance matrix:"

for row in noise.cov_matrix(r):
    for col in row:
        print "%7.03f" % col,
    print
示例#30
0
 def mk_noise(self):
     self.StatusLabel.hide()
     noise.noise(im)
     self.StatusLabel.show()
     im.last_op = 'noise'
示例#31
0
def main():
    startTime = time.time()
    args = _getparser().parse_args()
    _dispParser(args)
    tf._stats(args.fname.name)

    header, _, offset, obs, dates = tf._read(args.fname.name)
    A, cycle = dm(args.fname.name, args.periods, args.fs)._coefficients()
    L = obs[:, 0].reshape(len(obs[:, 0]), 1)
    dof = len(A[:, 0]) - len(A[0, :])
    unkOLS, sUnkOLS, s0OLS, resid = ls._lse(A, L)
    WRMS = np.sqrt((resid.T @ resid) / len(A[:, 0]))[0][0]
    #print("WRMS: " + str(WRMS))

    for line in header:
        if 'UNIT' in line:
            unit = line.split(": ")[1].split("\n")[0]
            break

    unitLabel = [unit] * len(unkOLS)
    unitLabel[1] = unitLabel[1] + "/year"
    unkLabel = ['intercept', 'trend']
    offsetLabel = [
        "{}{}".format(a, b)
        for a, b in zip(["offset at "] * len(offset), offset)
    ]
    unkLabel = np.append(unkLabel, offsetLabel)
    seasLabel = []
    for s1 in range(len(cycle)):
        seasLabel = np.append(seasLabel, [
            'sin ' + "{:10.4f}".format(cycle[s1]),
            'cos ' + "{:10.4f}".format(cycle[s1])
        ])
    unkLabel = np.append(unkLabel, seasLabel)

    if args.ols:
        print("\n Ordinary Least-squares estimation\n")
        for o in range(len(unkOLS)):
            print("%20s: %10.4f  +- %9.4f %s" % \
                (unkLabel[o], \
                 unkOLS[o], \
                 sUnkOLS[o], \
                 unitLabel[o]))
        print("\n")
        print("%20s: %14.8f %8s\n" % ('s0', s0OLS, unit))
        print("\nElapsed time : %.1f sec\n" % (time.time() - startTime))
        return

    for line in header:
        if 'DATE FORMAT' in line:
            dateFormat = line.split(": ")[1].split("\n")[0]
            break

    _, J = noise(dates, dateFormat, args.kappa, args.fs).mat()

    resultTemp = np.zeros((args.nRND**2, 3))
    wnaLast = np.zeros((args.repeat, 1), dtype=float)
    fnaLast = np.zeros((args.repeat, 1), dtype=float)
    for i in range(args.repeat):
        printProgressBar(i + 1,
                         args.repeat,
                         prefix=' Progress',
                         suffix='Complete')
        _, yWNA, _, yFNA = ss(args.alpha, WRMS, dof, args.nRND)._randomPoints()

        idx = 0
        for j in range(args.nRND):
            cWN = (yWNA[j]**2 * np.eye(len(A[:, 0]), dtype=float))
            for k in range(args.nRND):
                C = cWN + (yFNA[k]**2 * J)
                _, _, s0, _ = ls._lse(A, L, la.cholesky(la.inv(C)).T)
                resultTemp[idx, :] = [yWNA[j], yFNA[k], s0]
                idx += 1
        #np.savetxt('15-s0s.dat', resultTemp, fmt="%10.10f")
        xx = np.arange(min(resultTemp[:, 0]), max(resultTemp[:, 0]), args.incr)
        yy = np.arange(min(resultTemp[:, 1]), max(resultTemp[:, 1]), args.incr)
        XX, YY = np.meshgrid(xx, yy)
        ZZ = griddata((resultTemp[:, 0], resultTemp[:, 1]),
                      resultTemp[:, 2], (XX, YY),
                      method='cubic')
        #np.savetxt('1-XX.dat', XX, fmt="%10.4f")
        #np.savetxt('2-YY.dat', YY, fmt="%10.4f")
        #np.savetxt('3-ZZ.dat', ZZ, fmt="%10.4f")
        if (np.min(np.ma.masked_invalid(ZZ)) < 1) and (np.max(
                np.ma.masked_invalid(ZZ)) > 1):
            cs = plt.contour(xx, yy, np.ma.masked_invalid(ZZ), [1])
            L1 = cs.collections[0].get_paths()[0]
            coorL1 = L1.vertices
        else:
            index = np.where(
                abs(np.ma.masked_invalid(ZZ) -
                    1) == np.amin(abs(np.ma.masked_invalid(ZZ) - 1)))
            coorL1 = np.array([[XX[index[0][0],index[1][0]], \
                                YY[index[0][0],index[1][0]]]])
        #np.savetxt('4-coorL1.dat', coorL1, fmt="%10.4f")
        s0 = np.zeros((len(coorL1[:, 0]), 1), dtype=float)
        for d in range(len(coorL1[:, 0])):
            C2 = (coorL1[d,0]**2 * np.eye(len(A[:,0]), dtype=float)) + \
                 (coorL1[d,1]**2 * J)
            _, _, s0[d], _ = ls._lse(A, L, la.cholesky(la.inv(C2)).T)

        diffIDX = np.where(abs(s0 - 1) == np.amin(abs(s0 - 1)))[0][0]
        wnaLast[i] = coorL1[diffIDX, 0]
        fnaLast[i] = coorL1[diffIDX, 1]

    #np.savetxt('5-noiseAmp.dat', np.concatenate((wnaLast, fnaLast), axis=1), fmt="%10.4f")
    Cfin = (statistics.median(wnaLast)**2 * np.eye(len(A[:,0]), dtype=float)) + \
           (statistics.median(fnaLast)**2 * J)

    unk_fin, sUnk_fin, s0_fin, _ = ls._lse(A, L, la.cholesky(la.inv(Cfin)).T)
    print("\n")
    for o in range(len(unk_fin)):
        print("%20s: %10.4f +- %9.4f %s" % \
            (unkLabel[o], \
            unk_fin[o], \
            sUnk_fin[o], \
            unitLabel[o]))
    print("\n")
    print("%20s: %10.4f %s" % ('wna', statistics.median(wnaLast), unit))
    print("%20s: %10.4f %s" %
          ('fna', statistics.median(fnaLast), unit + "/year^0.25"))
    print("%20s: %14.8f %s\n" % ('s0', s0_fin, unit))

    if args.writeModel:
        for ii in range(len(header)):
            if 'COMMENT' and 'outliers' in header[ii]:
                header[ii] = "* COMMENT      : Model values" + "\n"
                break
        modelFilename = (args.fname.name.split(".")[0] + "_model.tse")
        tf._write(modelFilename, \
                 header, \
                 np.concatenate(((A @ unk_fin), np.zeros((len(A[:,0]),1), dtype=float)), axis=1), \
                 dates)

    print("\nElapsed time : %.1f sec\n" % (time.time() - startTime))
示例#32
0
# set env
env = ArmEnv([0., 0., 0.], [0., 0., 0.], [0., 0., 0.], [0., 0., 0.])
s_dim = env.state_dim
a_dim = env.action_dim
a_bound = env.action_bound

# set RL method (continuous)
a_scale = [1000, 3000]
#a_scale = [0, 10]
rl = DDPG(a_dim, s_dim, a_scale)

noise_mean = 0
noise_std_dev = 0.2
noise_theta = 0.15
noise_dt = env.dt
noise = noise(a_dim, noise_mean, noise_std_dev, noise_theta, noise_dt)
steps = []


def train():
    # start training
    for i in range(MAX_EPISODES):
        s = env.reset()
        noise.reset()
        ep_r = 0.

        for j in range(MAX_EP_STEPS):
            #j = 0
            #while not (s[0] > 400 or s[1] > 400 or s[0] < 0 or s[1] < 0):

            #env.render()
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import random
import array
import cv2

from noise import noise
from loader import MNIST
from save import save

__all__ = [MNIST, ]
absPath = os.path.dirname(__file__)

mnist = MNIST(absPath)
noise = noise()
filesave = save()



def serialize(image):
    im_array = np.zeros(784, np.int32)
    #im_array = array.array('i', (0 for k in range(784)))
    k = 0
    for i in xrange(image.__len__()):
        for j in xrange(image[i].__len__()):
            im_array[k] = int(round(image[i, j]))
            if im_array[k] < 0:
                im_array[k] = 0
            k = k + 1
    return im_array
示例#34
0
        hs = hr = 1.0
        results.append([obst, obst, ew, 0.0, hs, 0.0, hr, 0,0])
        continue
    
    ewleft, ewright = prof.ewinds
    if ewleft == ewright:
        print "Error, cannot find EW in", sf
        errors += 1
        nohorns += 1
        ew = 0.0
        hs = hr = 1.0
        results.append([obst, obst, ew, 0.0, hs, 0.0, hr, 0.0])
        continue

    if snr > -1000.0:
        amps = noise.noise(amps, snr, gauss)
    ewsz = si.simps(amps[ewleft:ewright+1]-1.0, wavelengths[ewleft:ewright+1])
    ew = ewsz - (wavelengths[ewright] - wavelengths[ewleft])

    if prof.twinpeaks:
                
        lhmax, rhmax = prof.maxima
        minind = prof.minima[0]
        minamp = amps[minind]
        below_minamp = np.where(amps < minamp)[0]
        lwhere = below_minamp[below_minamp < lhmax][-1] + 1
        rwhere = below_minamp[below_minamp > rhmax][0] - 1
        lhornsz = si.simps(amps[lwhere:minind+1] - 1.0, wavelengths[lwhere:minind+1])
        rhornsz = si.simps(amps[minind:rwhere+1]- 1.0, wavelengths[minind:rwhere+1])
        lwl = wavelengths[minind] - wavelengths[lwhere]
        rwl = wavelengths[rwhere] - wavelengths[minind]
for letter in letternames:
    letterpath = path_original_letters + '/' + letter
    newletterpath = path_new_letters + '/' + letter + '/'
    if not os.path.exists(newletterpath):
        os.mkdir(newletterpath)

            
    imagenames = os.listdir(letterpath)
    for imagename in imagenames[0:5]:
        imagepath = letterpath + '/' + imagename
        image = cv2.imread(imagepath,0)           #read as grayscale image
        #print(newletterpath)
        #Now we will do the follow with all images: 
        rotation(image, newletterpath + imagename[0:-4], [5,10,15,20,25,30])
        noise(image, newletterpath + imagename[0:-4], [1.2,1.4,1.6,1.8,2])
        translation(image, newletterpath + imagename[0:-4],[3,5])
        shearing(image, newletterpath + imagename[0:-4],[0,0.5,0.8,1.2])
        
        
        
        
        
        

        
        
        

        
         
import Image
import math

size = 256
inv = 1.0 / size

im = Image.new("RGB", (size, size))

redOffs = (1.3579, 0.25672, 0.4567)
greenOffs = (2.4786, 1.54567, 2.654)
blueOffs = (3.5795, 2.16713, 1.0912)

# now build the texture
for x in range(size):
    for y in range(size):
        x1 = inv * x
        y1 = inv * y

        # get func value based on noise
        n = (1 + noise.noise(redOffs[0] + 35 * x1, redOffs[1] + 4 * y1,
                             redOffs[2])) * 0.15
        v = (y1 + n) * 0.5

        if v < 0:
            v = 1.0

        im.putpixel((x, y), (255 * v, 0, 0))

im.show()
im.save("ThirdSpace.bmp", "bmp")
示例#37
0
from noise import pnoise2 as noise

parts = []

rings = []

height = 40
segs = 30

h_freq_scale = .1
a_freq_scale = 1

for i in range( height ):
	ring = []
	for a in range( segs ):
		ring.append( (noise( i*h_freq_scale, math.sin((float(a)/segs)*math.pi)*a_freq_scale, 5 )+1)*.7 )
	rings.append( ring )
	
h_scale = lambda h: (height+1 - h)*.25 + 5
a_to_p = lambda a, v, h: [math.cos(a)*h_scale(h)*v,math.sin(a)*h_scale(h)*v,h]
		
for h in range( len( rings ) -1 ):
	ringa = rings[h]
	ringb = rings[h+1]
	points = []
	print h
	for i in range( len( ringa ) ):
		print ringa[i]
		points.append( a_to_p( i * ((math.pi*2)/segs), ringa[i], h ) )
	for i in range( len( ringb ) ):
		points.append( a_to_p( i * ((math.pi*2)/segs), ringb[i], h+1 ) )
def n2D(x, y, offs):
    return 127 * noise.noise(offs[0] + x, offs[1] + y, offs[2]) + 128
示例#39
0
 def __init__(self,size=1000):
     self.size=size
     self.grid=[noise.noise(i) in range(size)]
     self.gravity=[0,5]
示例#40
0
        # nearest neighbor algorithm
        from upscale import upscale
        p1 = args["factor"]  # pixel
        p2 = args["factor2"]
        new_size = (p1, p2)
        output = upscale(input_image, new_size)
        save(option, output)
    elif option == "crop" or option2 == "crop":
        # cropping
        from crop import crop
        p1 = args["factor"]  # pos
        p2 = args["factor2"]
        pos = (p1, p2)  #origin
        #end defined in crop.py
        output = crop(input_image, pos)
        save(option, output)
    elif option == "contrast" or option2 == "contrast":
        from contrast import change_contrast
        factor = args["factor"]  # factor
        output = change_contrast(input_image, factor)
        save(option, output)
    elif option == "noise" or option2 == "noise":
        from noise import noise
        factor = args["factor"]  # factor
        output = noise(input_image, factor)
        save(option, output)
else:
    print(
        "Usage: python pmake.py o -i<input_img>.<extention> -o <option1> or -oo<option2> -f1<factor 1> -f2 <factor2>"
    )
示例#41
0
def reverb(samples):
    n = noise(0.8, 0.6, 0.01, 0.0)

    n[0] = 1

    return list(np.convolve(samples, n))
示例#42
0
def f():
    a = noise(3)
    b = 8 + noise(2)
    return a, b, a + b, a /b, a*a, a*b, b*b