def step(self): ''' Function called every unit of time to generate events, process changes in resource quantities, and simulate everything else that happens. :return: ''' step()
def loadDebugData(input): global steps steps = [] # Clear the container tree = ET.parse(input) root = tree.getroot() stepNum = 1 for child in root: tempStep = step.step(stepNum, float(child.attrib.get('ambTemp')), [float(child.attrib.get('lat')), float(child.attrib.get('lon'))], float(child.attrib.get('dist')), float(child.attrib.get('trip')), float(child.attrib.get('speedLimit')), float(child.attrib.get('inclination')), float(child.attrib.get('heading')), float(child.attrib.get('cloud')), [float(child.attrib.get('windSpd')), float(child.attrib.get('windDir'))], int(child.attrib.get('stepType')), float(child.attrib.get('timezone'))) if config.EN_WIND == False: tempStep.wind = [0., 0.] steps.append(tempStep) stepNum = stepNum + 1 return
def compound_smooth_impulse_response(Neff_pos, Neff_neg, Nwindow): "a compound smoothing impulse response" h_step = step(Nwindow) h_macd = macd(Neff_pos, Neff_neg, Nwindow) gauge = 1.0 / (Neff_neg - Neff_pos) candidate = np.convolve(gauge * h_macd, h_step) return candidate[:Nwindow]
def train(iteration): LookupTable = Q.Qtable() for x in range(1, iteration): playersum = np.zeros(30) actionstaken = np.zeros(30) playerstate = randint(1, 11) dealerstate = randint(1, 11) x = 0 action = LookupTable.getaction(playerstate, dealerstate) state = play.step(dealerstate, playerstate, action) playersum[0] = playerstate actionstaken[0] = action # print "state action space first", playerstate, dealerstate, action if state[3] == 1: LookupTable.Qupdate(playerstate, dealerstate, action, state[2]) # print "state action space", state[1], state[0], action # print "reward", state[2] while state[3] == 0: x = x + 1 playersum[x] = state[1] action = LookupTable.getaction(state[1], state[0]) actionstaken[x] = action state = play.step(state[0], state[1], action) while x > 0: LookupTable.Qupdate(int(playersum[x]), dealerstate, int(actionstaken[x]), state[2]) # print "state action space", int(playersum[x]), dealerstate, int(actionstaken[x]) # print "reward", state[2] x = x - 1 ''' LookupTable.Qupdate(playerstate, dealerstate, action, state[2]) playerstate=20 dealerstate=randint(1,11) action=LookupTable.getaction(playerstate,dealerstate) state=play.step() LookupTable.Qupdate(playerstate,dealerstate,action,state[2]) ''' return LookupTable.Q
def New(self, playersum, dealersum, lamda): self.E = np.zeros([22, 11, 2]) terminal = 0 action = self.getaction(playersum, dealersum) while terminal == 0: #print "action:", action state = play.step(dealersum, playersum, action) #print state self.Naction[playersum, dealersum, action] = self.Naction[playersum, dealersum, action] + 1 if state[3] == 0: action1 = self.getaction(state[1], state[0]) #print "action1:", action1 gamma = state[2] + self.Q[state[1], state[0], action1] - self.Q[playersum, dealersum, action] self.E[playersum, dealersum, action] += 1 for x in range(0, 21): for y in range(0, 10): for z in range(0, 1): #if self.Naction[x, y, z] != 0: if self.E[x, y, z] != 0: self.Q[x, y, z] += (gamma * self.E[x, y, z]) / \ (self.Naction[x, y, z]) self.E[x, y, z] = lamda * self.E[x, y, z] #print "Q0",x,y,z, self.Q[x,y,z] playersum = state[1] dealersum = state[0] action = action1 terminal = state[3] if state[3] == 1: terminal = 1 self.E = np.zeros([22, 11, 2]) if state[3] == 1: #print "terminating calc" gamma = state[2] - self.Q[playersum, dealersum, action] self.E[playersum, dealersum, action] += 1 for x in range(1, 21): for y in range(1, 11): for z in range(0, 2): #if self.Naction[x,y,z]!=0: if self.E[x, y, z] != 0: self.Q[x, y, z] += (gamma * self.E[x, y, z]) / ( self.Naction[x, y, z]) self.E[x, y, z] = lamda * self.E[x, y, z] #print "Q1",x,y,z, self.Q[x,y,z] self.E = np.zeros([22, 11, 2]) terminal = 1
def execute(e, n, method, f): if method == '(p-1)-метод': p, q = pollard_p_1(n) f.write("The result of the algorithm is: {}*{}".format(p, q)) elif method == 'ро-Поллард': p, q = po_pollard_brent(n) f.write("The result of the algorithm is: {}*{}".format(p, q)) elif method == 'малый-модуль-шифрования': m_1 = random.randint(2, n - 2) a = random.randint(2, n - 2) b = random.randint(2, n - 2) m_2 = (a * m_1 + b) % n c_1 = pow(m_1, e, n) c_2 = pow(m_2, e, n) l = [b, a] f.write("Selected parameters:\n") f.write("First cipher-text: {}\n".format(c_1)) f.write("Second cipher-text: {}\n".format(c_2)) f.write("message relations: m_1 = {} * m_2 + {} mod {}\n".format( a, b, n)) try: m_1, m_2 = small_exp(c_1, c_2, l, e, n) except CustomException as e: f.write( "Found factor during the algorithm performance: {}*{}".format( e.message, n // e.message)) else: f.write("The result of the algorithm is: {} and {}".format( m_1, m_2)) elif method == 'атака-Винера': p, q = wiener(e, n) if p: f.write("The result of the algorithm is: {}*{}".format(p, q)) else: f.write( "Unable to achieve the result among the successive convergents." ) elif method == 'итерация': m = random.randint(2, n - 2) c = pow(m, e, n) p, q = step(c, e, n) f.write("Used the cipher-text: {}\n".format(c)) if q: f.write("The result of the algorithm is: {}*{}".format(p, q)) else: f.write("The result is {}".format(p)) else: exit("Unknown method") return 0
def breed(solutions, n_offspring, n_videos): all_offspring = [] # assuming all solutions have the same number of caches: for _ in range(n_offspring): offspring = [] for i in range(len(solutions[0])): s = random.choice(solutions) offspring.append(s[i]) # Randomly introduce a mutation? if random.choice([True, False]): offspring = step(offspring, n_videos) all_offspring.append(offspring) return all_offspring
def hill_climb(description, endpoints, requests, video_sizes, search_duration): derv = (description, endpoints, requests, video_sizes) steps = 0 start_time = time() s = generate_solution(description, video_sizes) while time() - start_time < search_duration: next_s = step(s, description['n_videos']) steps += 1 if score_solution(next_s, *derv) > score_solution(s, *derv): s = next_s best_score, best_solution = score_solution(s, *derv), s return steps, best_score, best_solution
def simulated_annealing(description, endpoints, requests, video_sizes, time_to_run): derv = description, endpoints, requests, video_sizes temperature = 1.0 cold = 0.1 best_score, best_solution = -1, None s_count = 0 start_time = time() s = generate_solution(description, video_sizes) while (temperature > cold) and (time() - start_time <= time_to_run): s_count += 1 s_score = score_solution(s, *derv) if s_score > best_score: best_score, best_solution = s_score, s # we 1/score because we need to convert scores to values between 1 and 0 # to produce coparible probabilities # NB: this inverts things. The better the solution, the lower the # number!! s_score = 1 / s_score s_new = step(s, description['n_videos']) s_new_score = 1 / score_solution(s_new, *derv) if s_new_score < s_score: s = s_new continue p = step_probability(s_score, s_new_score, temperature) if (p * 100) > random.randint(0, 100): s = s_new return s_count, best_score, best_solution
screen.blit(start, start.get_rect()) pygame.display.flip() waiting = True while waiting: for event in pygame.event.get(): if event.type == pygame.KEYUP: if event.key == pygame.K_SPACE: waiting = False screen.fill((0, 0, 0)) pygame.display.flip() state = 0 while state == 0: state = step(screen) pygame.time.delay(50) pygame.time.delay(1000) winImage = None if state == 1: winImage = pygame.image.load("assets/welldone.png") if state > 1 and state < 4: winImage = pygame.image.load("assets/tryharder.png") if state >= 4: winImage = pygame.image.load("assets/toodirty.png") screen.blit(winImage, winImage.get_rect())
def compound_smooth_impulse_response(Neff_pos, Neff_neg, Nwindow): "a compound smoothing impulse response" h_step = step(Nwindow) h_macd = macd(Neff_pos, Neff_neg, Nwindow) gauge = 1.0 / (Neff_neg - Neff_pos) candidate = np.convolve(gauge * h_macd, h_step) return candidate[:Nwindow] if __name__ == "__main__": f, axarr = plt.subplots(1, 1) Nwindow = 500 Neff_pos = 7 Neff_neg = 14 h_step = step(Nwindow) h_macd = macd(Neff_pos, Neff_neg, Nwindow) h_csir = compound_smooth_impulse_response(Neff_pos, Neff_neg, Nwindow) axarr.plot(h_step) axarr.plot(h_macd) axarr.plot(h_csir) axarr.set_title('Unit step, macd, and compound impulse responses') plt.tight_layout() plt.show()
def dispcal(data, samprate, fcs, hs, gap, volts, displ, bfc=0.0, bm=0): dt = 1.0 / samprate npts = len(data) npol = 3 perc1 = 50 perc2 = 95 fac = volts / displ * 0.001 # remove offset using the first 6 seconds that have to be quiet! z = np.ones(npts) offset = np.sum(data[0:int(6.0*samprate)]) data = data - offset # apply butterworth low pass filter if required if bfc > 0.0 and bm > 0: bt0 = 1.0 / bfc mm = int(bm / 2.0) # if odd order apply first order low pass if bm > 2 * mm: f0_lp1, f1_lp1, f2_lp1, g1_lp1, g2_lp1 = lp1(bt0*samprate) data = rekfl(data, npts, f0_lp1, f1_lp1, f2_lp1, g1_lp1, g2_lp1) # now apply second order low pass for i in range(mm): h = np.sin(np.pi / 2.0 * (2.0 * i - 1.0) / bm) f0_lp2, f1_lp2, f2_lp2, g1_lp2, g2_lp2 = lp2(bt0*samprate, h) data = rekfl(data, npts, f0_lp2, f1_lp2, f2_lp2, g1_lp2, g2_lp2) # report filtering print 'Input data filtered with low pass Butterworth filter:' print ' corner frequency: ' + str(bfc) + 'Hz' print ' order: ' + str(bm) + '.' raw = data.copy() # deconvolution to velocity step # done by appling an exact invers second order high pass filter (infinit period) t0 = 1.0e12 h = 1.0 t0s = 1.0 / fcs f0_he2, f1_he2, f2_he2, g1_he2, g2_he2 = he2(t0/dt, t0s/dt, h, hs) data = rekfl(data, npts, f0_he2, f1_he2, f2_he2, g1_he2, g2_he2) data = politrend(npol, data, npts, z) x = data.copy() deconv = data.copy() # store deconvolves data np.savetxt('dispcal_vel.txt', deconv) # loop over fife trial values if no gap is given if gap > 0.0: onegap = True ngap = 1 else: #gap = 0.125 #onegap = False #ngap = 5 print 'parameter "gap" not specified!' sys.exit(1) for k in range(ngap): avglen = 6.0 * gap iab = int(gap / dt) iavg = int(avglen / dt) data = x z = np.ones(npts) P0 = np.zeros(npts) y = np.zeros(npts) ja = np.ones(99) # search for quiet section of minimum length 2*iab+1 samples P = krum(data, npts, 2*iab+1, P0) for j in range(npts): P[j] = np.log10(max(P[j], 1.0e-6)) P1 = P.copy() # import ipdb; ipdb.set_trace() z = heapsort(npts, P1) n50 = int(perc1 * npts / 100.0) n95 = int(perc2 * npts / 100.0) zlim = 0.5 * (z[n50] + z[n95]) P = P - zlim z = z - zlim # create trigger z = 0 if quiet, z = 1 if pulse for j in range(npts): if P[j] < 0: z[j] = 1.0 else: z[j] = 0.0 #zn1 = z[npts-1] #zn = z[n] #z[n-1] = -0.4 #z[n] = 1.4 #z[n-1] = zn1 #z[n] = zn data = politrend(npol, data, npts, z) data_c = data.copy() # cut out pulses quiet = data * z # identifiy pulses number = 0 i = 0 while i < npts and z[i] < 0.5: i = i + 1 n1 = i while i < npts and z[i] > 0.5: i = i + 1 n2 = i - 1 if i == npts: print 'No pulses found! Check dispcal.??? for pulses!' sys.exit(1) # continue if interval is too small (< gap) while n2 < n1 + iab: while i < npts and z[i] < 0.5: i = i + 1 n1 = i while i < npts and z[i] > 0.5: i = i + 1 n2 = i - 1 # now we have the first (n1) and the last (n2) sample of the first quiet interval if i == n: print 'No pulses found! Check dispcal.??? for pulses!' sys.exit(1) # now continue with the next pulses steps = [] marks = [] while i < npts: while i < npts and z[i] < 0.5: i = i + 1 if i == npts: break n3 = i while i < npts and z[i] > 0.5: i = i + 1 if i == npts: break n4 = i - 1 # continue if interval is too small (< gap) while n4 < n3 + iab: while i < npts and z[i] < 0.5: i = i + 1 if i == npts: break n3 = i while i < npts and z[i] > 0.5: i = i + 1 if i == npts: break n4 = i - 1 # now we have the first (n1) and the last (n2) sample of the next quiet interval number = number + 1 if number == 1: data_c = zspline('zsp', 1, n2, n3, npts, data_c, npts) n2null = n2 elif n4 >= n3+iab: data_c = zspline('zsp', n1, n2, n3, npts, data_c, npts) n3null = n3 marks.append((n2,n3-1)) print 'found pulse # ' + str(number) + ': from sample ' + str(n2) + ' to sample ' + str(n3 - 1) n1a = 0 n2a = n2 - n1 n3a = n3 - n1 n4a = n4 - n1 n1a = max(n1a, n2a-iavg) n4a = min(n4a, n3a+iavg) for ii in range(n4a): y[ii] = data[n1-1+ii] y_z = zspline('zsp', n1a, n2a, n3a, n4a, y, n4a) y_int = integrate(y_z, npts, dt) stp = step(y_int, n1a, n2a, n3a, n4a, n4a) n1 = n3 n2 = n4 steps.append(stp) dtr = trend('tre', 0, n2-n1+1, 0, 0, data_c[n1:], npts-n1) data2 = data_c.copy() for i in np.arange(n1, npts, 1): data2[i] = dtr[i-n1] y = data_c * z ymin = 0.0 ymax = 0.0 for i in np.arange(n2null+1, n3null-1,1): ymin = min(ymin,y[i]) ymax = max(ymax,y[i]) for i in range(n2null): y[i] = min(ymax, max(ymin, y[i])) for i in np.arange(n3null, npts, 1): y[i] = min(ymax, max(ymin, y[i])) np.savetxt('dispcal_res.txt', y) y_dis = integrate(data2, npts, dt) # remove offset from displacement offset = np.mean(y_dis) y_dis = y_dis - offset displ = y_dis.copy() np.savetxt('dispcal_dis.txt', displ) ############################################################## # Statistics total = sum(np.abs(steps)) avgs = total / number sigma = np.std(np.abs(steps)) print '' print '-------------------------------------------------------------' print 'Raw average step: ' + str(np.round(avgs,3)) + ' +/- ' + str(np.round(sigma, 3)) print 'Raw generator constant: ' + str(np.round((avgs * fac) * 1e6,3)) + ' +/- ' + str(np.round((sigma * fac) *1e6, 3)) + 'Vs/m' print '-------------------------------------------------------------' if number <= 2: return raw, deconv, displ, marks # import ipdb; ipdb.set_trace() ja = np.ones(len(steps)) for nrest in np.arange(number-1,int(float(number+1.0)/2.0),-1): siga = sigma kmax = np.argmax(steps) ja[kmax] = 0 total = 0 #for k in range(number): # total = total + ja[k] * steps[k] stepsa = ja * steps total = sum(np.abs(stepsa)) #print total avgs = total / nrest #print avgs total = 0 for k in range(number): total = total + ja[k] * (abs(steps[k]) - avgs)**2 sigma = np.sqrt(total / nrest) print 'Pulse ' + str(kmax) + ' eliminated; ' + str(nrest) + ' pulses remaning: ' + str(np.round((avgs * fac) * 1e6,3)) + ' +/- ' + str(np.round((sigma * fac) *1e6, 3)) + 'Vs/m' # if sigma < 0.05*avgs and siga-sigma < siga/ nrest: break steps[kmax] = 0.0 print '------------------------------------------------------------' print '' return raw, deconv, displ, marks
from step import step state, r = step([20, 20], 0) print("New State", state, r)
def test_step(self): # mock_class.func.set_return_value(1) #.func = 1 step(_dummy_func)() self.assertTrue("start at" in _log_mem[0]) self.assertTrue("stop at" in _log_mem[1])
episodes = 1000 for i in range(episodes): sum_p = rd.randint(1,10) sum_d = rd.randint(1,10) s = [sum_p,sum_d] sp = [sum_p,sum_d] terminal = False G = 0 while terminal == False: a = pi[s[0]-1,s[1]-1] ns[s[0]-1,s[1]-1] += 1 s, sp, r, terminal = step(s,a,sp) if a == 'hit': nsa[s[0]-1,s[1]-1,0]+=1 G += r alpha = 1/nsa[s[0]-1,s[1]-1,0] Q[s[0]-1,s[1]-1,0] += alpha*(G - Q[s[0]-1,s[1]-1,0]) else: nsa[s[0]-1,s[1]-1,1]+=1 G += r alpha = 1/nsa[s[0]-1,s[1]-1,1] Q[s[0]-1,s[1]-1,1] += alpha*(G - Q[s[0]-1,s[1]-1,1]) s = sp[:]
import numpy as np import matplotlib.pyplot as plt from ema import ema from step import step from macd import macd from compound_smooth_impulse_response import compound_smooth_impulse_response f, axarr = plt.subplots(3, 1) Nwindow = 500 Neff = 21 Neff_pos = 7 Neff_neg = 14 h_ema = ema(Neff, Nwindow) h_step = step(Nwindow) h_macd = macd(Neff_pos, Neff_neg, Nwindow) with open('jpm_trades.csv', 'r') as trades_csv: trades = np.array(list(csv.reader(trades_csv))[1:]).astype('double') volumes = trades[:,4] #ema print("Problem 10 (a): Ema on trade volume series") candidate1 = np.convolve(volumes-volumes[0], h_ema) + volumes[0] truncated1 = candidate1[:len(volumes)] axarr[0].plot(truncated1) axarr[0].plot(volumes) axarr[0].set_title('Ema applied to volume series with Neff = 21') print("Problem 10 (b): Compound smoothing on volume series with Neff+ = 7, Neff- = 14")
def tiltcal(data, samprate, fcs, hs, gap, volts, tilt, bfc=0.0, bm=0): dt = 1.0 / samprate npts = len(data) npol = 3 perc1 = 50 perc2 = 95 fac = volts / tilt * 0.001 # remove offset using the first 6 seconds that have to be quiet! z = np.ones(npts) offset = np.sum(data[0:int(6.0 * samprate)]) data = data - offset # apply butterworth low pass filter if required if bfc > 0.0 and bm > 0: bt0 = 1.0 / bfc mm = int(bm / 2.0) # if odd order apply first order low pass if bm > 2 * mm: f0_lp1, f1_lp1, f2_lp1, g1_lp1, g2_lp1 = lp1(bt0 * samprate) data = rekfl(data, npts, f0_lp1, f1_lp1, f2_lp1, g1_lp1, g2_lp1) # now apply second order low pass for i in range(mm): h = np.sin(np.pi / 2.0 * (2.0 * i - 1.0) / bm) f0_lp2, f1_lp2, f2_lp2, g1_lp2, g2_lp2 = lp2(bt0 * samprate, h) data = rekfl(data, npts, f0_lp2, f1_lp2, f2_lp2, g1_lp2, g2_lp2) # report filtering print 'Input data filtered with low pass Butterworth filter:' print ' corner frequency: ' + str(bfc) + 'Hz' print ' order: ' + str(bm) + '.' raw = data.copy() # deconvolution to ground acceleration # done by appling an exact invers second order high pass filter (infinit period) t0 = 1.0e12 h = 1.0 t0s = 1.0 / fcs f0_he2, f1_he2, f2_he2, g1_he2, g2_he2 = he2(t0 / dt, t0s / dt, h, hs) data = rekfl(data, npts, f0_he2, f1_he2, f2_he2, g1_he2, g2_he2) data = politrend(npol, data, npts, z) x = data.copy() deconv_vel = data.copy() np.savetxt('tiltcal_vel.txt', deconv_vel) # differentiate to get ground acceleration data_diff = differentiate(data, npts, dt, 1) #np.savetxt('diff_test', data_diff) # loop over fife trial values if no gap is given if gap > 0.0: onegap = True ngap = 1 else: gap = 0.125 onegap = False ngap = 5 for k in range(ngap): avglen = 6.0 * gap iab = int(gap / dt) iavg = int(avglen / dt) data = x z = np.ones(npts) P0 = np.zeros(npts) y = np.zeros(npts) ja = np.ones(99) # search for quiet section of minimum length 2*iab+1 samples P = krum(data, npts, 2 * iab + 1, P0) for j in range(npts): P[j] = np.log10(max(P[j], 1.0e-6)) P1 = P.copy() # import ipdb; ipdb.set_trace() z = heapsort(npts, P1) n50 = int(perc1 * npts / 100.0) n95 = int(perc2 * npts / 100.0) zlim = 0.5 * (z[n50] + z[n95]) P = P - zlim z = z - zlim # create trigger z = 0 if quiet, z = 1 if pulse for j in range(npts): if P[j] < 0: z[j] = 1.0 else: z[j] = 0.0 #zn1 = z[npts-1] #zn = z[n] #z[n-1] = -0.4 #z[n] = 1.4 #z[n-1] = zn1 #z[n] = zn mpol = npol - 2 if mpol < 1: print 'npol too small!' sys.exit(1) # compute residual signal data2 = data_diff.copy() quiet = differentiate(data2, npts, dt, 0) quiet = quiet * z res, a = politrendTilt(npol, quiet, npts, z) res = res * z res_int = integrate(res, npts, dt) np.savetxt('tiltcal_res.txt', res_int) # final trend removal on acceleration signal xpolint = 0.0 xavg = 0.0 for i in range(npts): xpol = a[mpol] for j in np.arange(mpol - 1, 0, -1): xpol = xpol * (float(i + 1) / fnh - 1.0) + a[j] xpolint = xpolint + xpol * dt data_diff[i] = data_diff[i] - xpolint xavg = xavg + data_diff[i] xavg = xavg / npts for i in range(npts): data_diff[i] = data_diff[i] - xavg acc = data_diff.copy() np.savetxt('tiltcal_acc.txt', acc) data_c = data_diff.copy() # identifiy pulses number = 0 i = 0 while i < npts and z[i] < 0.5: i = i + 1 n1 = i while i < npts and z[i] > 0.5: i = i + 1 n2 = i - 1 if i == npts: print 'No pulses found! Check dispcal.??? for pulses!' sys.exit(1) # continue if interval is too small (< gap) while n2 < n1 + iab: while i < npts and z[i] < 0.5: i = i + 1 n1 = i while i < npts and z[i] > 0.5: i = i + 1 n2 = i - 1 # now we have the first (n1) and the last (n2) sample of the first quiet interval if i == n: print 'No pulses found! Check dispcal.??? for pulses!' sys.exit(1) # now continue with the next pulses steps = [] marks = [] while i < npts: while i < npts and z[i] < 0.5: i = i + 1 if i == npts: break n3 = i while i < npts and z[i] > 0.5: i = i + 1 if i == npts: break n4 = i - 1 # continue if interval is too small (< gap) while n4 < n3 + iab: while i < npts and z[i] < 0.5: i = i + 1 if i == npts: break n3 = i while i < npts and z[i] > 0.5: i = i + 1 if i == npts: break n4 = i - 1 # now we have the first (n1) and the last (n2) sample of the next quiet interval number = number + 1 #if number == 1: # data_c = zspline('zsp', 1, n2, n3, npts, data_c, npts) # n2null = n2 #elif n4 >= n3+iab: # #print 'bin da!' # data_c = zspline('zsp', n1, n2, n3, npts, data_c, npts) #n3null = n3 marks.append((n2, n3 - 1)) print 'found pulse # ' + str(number) + ': from sample ' + str( n2) + ' to sample ' + str(n3 - 1) n1a = 0 n2a = n2 - n1 n3a = n3 - n1 n4a = n4 - n1 n1a = max(n1a, n2a - iavg) n4a = min(n4a, n3a + iavg) for ii in range(n4a): y[ii] = data_diff[n1 - 1 + ii] #print n1a, n2a, n3a, n4a y_m = mspline('msp', n1a, n2a, n3a, n4a, y, n4a) #y_int = integrate(y_z, npts, dt) #y_int = cumtrapz(y_z) * dt stp = step(y_m, n1a, n2a, n3a, n4a, n4a) n1 = n3 n2 = n4 steps.append(stp) #np.savetxt('y_z'+str(number), y_z) #np.savetxt('y_int'+str(number), y_int) #print steps #dtr = trend('tre', 0, n2-n1+1, 0, 0, data_c[n1:], npts-n1) #for i in np.arange(n1, npts, 1): # data_c[i] = dtr[i-n1] # #y = data_c * z #ymin = 0.0 #ymax = 0.0 #for i in np.arange(n2null+1, n3null-1,1): # ymin = min(ymin,y[i]) # ymax = max(ymax,y[i]) #for i in range(n2null): # y[i] = min(ymax, max(ymin, y[i])) #for i in np.arange(n3null, npts, 1): # y[i] = min(ymax, max(ymin, y[i])) # # #y_dis = integrate(data_c, npts, dt) # remove offset from displacement #offset = np.mean(y_dis) #y_dis = y_dis - offset #displ = y_dis.copy() ############################################################## # Statistics total = sum(np.abs(steps)) avgs = total / number sigma = np.std(np.abs(steps)) print '' print '-------------------------------------------------------------' print 'Raw average step: ' + str(np.round(avgs, 3)) + ' +/- ' + str( np.round(sigma, 3)) print 'Raw generator constant: ' + str(np.round( (avgs * fac) * 1e6, 3)) + ' +/- ' + str( np.round((sigma * fac) * 1e6, 3)) + 'Vs/m' print '-------------------------------------------------------------' if number <= 2: return raw, deconv, displ, marks # import ipdb; ipdb.set_trace() ja = np.ones(len(steps)) for nrest in np.arange(number - 1, int(float(number + 1.0) / 2.0), -1): siga = sigma kmax = np.argmax(steps) ja[kmax] = 0 total = 0 #for k in range(number): # total = total + ja[k] * steps[k] stepsa = ja * steps total = sum(np.abs(stepsa)) #print total avgs = total / nrest #print avgs total = 0 for k in range(number): total = total + ja[k] * (abs(steps[k]) - avgs)**2 sigma = np.sqrt(total / nrest) print 'Pulse ' + str(kmax) + ' eliminated; ' + str( nrest) + ' pulses remaning: ' + str( np.round((avgs * fac) * 1e6, 3)) + ' +/- ' + str( np.round((sigma * fac) * 1e6, 3)) + 'Vs/m' # if sigma < 0.05*avgs and siga-sigma < siga/ nrest: break steps[kmax] = 0.0 print '------------------------------------------------------------' print '' gap = gap * 2.0 return raw, deconv_vel, acc, marks
# generator, discriminator, # generator.generate_6, discriminator.discriminate_6, # generator_optimizer, discriminator_optimizer, # dataroot, device # ) # step( # 24, 20, # generator, discriminator, # generator.generate_7, discriminator.discriminate_7, # generator_optimizer, discriminator_optimizer, # dataroot, device # ) # torch.save(generator.state_dict(), f'./generator') # torch.save(discriminator.state_dict(), f'./discriminator') generator.load_state_dict(torch.load('./generator')) discriminator.load_state_dict(torch.load('./discriminator')) # interpolation_step( # 48, 40, # generator, discriminator, # generator.generate_8, discriminator.discriminate_8, # generator_optimizer, discriminator_optimizer, # dataroot, device # ) step(48, 40, generator, discriminator, generator.generate_9, discriminator.discriminate_9, generator_optimizer, discriminator_optimizer, dataroot, device) # torch.save(generator.state_dict(), f'./generator_final') # torch.save(discriminator.state_dict(), f'./discriminator_final')
accumulate(inference_generator, generator, 0.) discriminator_optimizer = torch.optim.Adam(discriminator.parameters(), lr=.01, betas=(.0, .99)) generator_optimizer = torch.optim.Adam(generator.parameters(), lr=.01, betas=(.0, .99)) with torch.no_grad(): test_noise = torch.Tensor( # np.random.normal(size = (256, 256)) np.random.uniform(-5., 5., size=(256, 256))).to(device) step(4, 400, test_noise, generator, inference_generator, discriminator, accumulate, generator.generate_1, inference_generator.generate_1, discriminator.discriminate_1, generator_optimizer, discriminator_optimizer, dataroot, device) interpolation_step(8, 400, test_noise, generator, inference_generator, discriminator, accumulate, generator.generate_2, inference_generator.generate_2, discriminator.discriminate_2, generator_optimizer, discriminator_optimizer, dataroot, device) step(8, 400, test_noise, generator, inference_generator, discriminator, accumulate, generator.generate_3, inference_generator.generate_3, discriminator.discriminate_3, generator_optimizer, discriminator_optimizer, dataroot, device) # torch.save(generator.state_dict(), f'./split_generator') # torch.save(discriminator.state_dict(), f'./split_discriminator') # torch.save(inference_generator.state_dict(), f'./split_inference_generator')
import time import step import motor import tempControl import param steps = [] for i in range(5): steps.append(step.step(0, 0, 0)) currentStep = 0 currentTime = 0 startTime = 0 isRunning = False def start(): global startTime startTime = time.time() _initStep(steps[currentStep]) def update(): global currentStep currentTime = time.time() - startTime print("Zeit:", currentTime, "von", steps[currentStep].time, "Sekunden") if (currentTime >= steps[currentStep].time): if (currentStep > 4): param.isOn = False
def addStep(self, stepString): self.steps.append(step(stepString, self.stepIndex)) self.stepIndex = self.stepIndex + 1
z[:] = [x * 4 for x in z] plt.step(t, z) plt.xlabel('time') plt.ylabel('function value') plt.title('x(t)*4*d(t)') plt.show() t = np.arange(-10, 10, 0.01) x = [] comb_step_ramp4(t, x) t = np.arange(-10, 10, 0.01) u = [] step(t, u) z = [] for j in range(len(t)): z.append(u[j] * x[j]) plt.step(t, z) plt.axhline(0, color='black') plt.axvline(0, color='black') plt.xlabel('time') plt.ylabel('function value') plt.title('x(t)*u(t)') plt.show() t = np.arange(-10, 10, 0.01) u = []