def test(): print 'here we go' # while s.read(100000): # print 'flush serial' uc = uControl() # junk = s.read(1000) print 'here' try: print 'uc.cuff_pressure', uc.cuff_pressure print 'maintain()' uc.maintain(200, 230, 3) uc.record(True) print 'len(uc.hirate)', len(uc.hirate) while uc.pump_state: print 'uc.cuff_pressure', uc.cuff_pressure serial_interact() print 'deflate' uc.deflate(40) uc.record(False) print 'len(uc.hirate)', len(uc.hirate) hirate = array(uc.hirate) if len(uc.hirate) > 0: dt = 0.004 n_tap = 100 lp_taps = util.get_lowpass_taps(5, dt, n_tap) llp_taps = util.get_lowpass_taps(.25, dt, n_tap) lpd = util.filter(hirate[:, 1] - hirate[0, 1], lp_taps)[::10] + hirate[0, 1] llpd = util.filter(hirate[:, 1] - hirate[0, 1], llp_taps)[::10] + hirate[0, 1] print len(lpd) times = hirate[::10, 0] ax = pylab.subplot(211) pylab.plot(times, lpd) pylab.plot(times, llpd) pylab.subplot(212, sharex=ax) pylab.plot(times, lpd - llpd) pfn = 'hirate.pkl' pickle.dump(hirate, open(pfn, 'w')) print 'write', pfn # pylab.figure(2); pylab.plot(uc.lpf.out) # pylab.figure(3); pylab.plot(hirate[:,1]) print 'done' finally: uc.deflate(50) send_cmd(pump_rate=False, valve=getValveByte(valve0=True)) time.sleep(2) send_cmd(pump_rate=False, valve=getValveByte(valve0=False), interval=0) pylab.show()
def main(filename): minn_score = "NA" directory, fn = os.path.split(filename) notes_fn = os.path.join(directory, "Notes.txt") if os.path.exists(notes_fn): minn_notes = open(notes_fn).readlines() for line in minn_notes: keyval = line.upper().split() if len(keyval) != 2: continue key, val = line.upper().split() if key == "SCORE": minn_score = "%s.0%%" % (val) break figure(7) clf() title("Arterial compliance vs transmural pressure\n%s" % directory) ucontrol = unpickle(open(filename)) norm = ucontrol.normal amb_temp_n = ucontrol.normal_temp amb_temp_n = 21 amb_pressure_n = ucontrol.normal_pressure amb_pressure_n = 728.0 hype = ucontrol.hyper amb_temp_h = ucontrol.hyper_temp amb_temp_h = amb_temp_h amb_pressure_h = ucontrol.hyper_pressure amb_pressure_h = amb_pressure_n n_skip = 750 gage_n = array([l[1] for l in norm]) ## pressure in mmhg lpg_n = util.filter(gage_n - gage_n[0], LP_TAPS) + gage_n[0] llpg_n = util.filter(gage_n - gage_n[0], LLP_TAPS) + gage_n[0] gage_h = array([l[1] for l in hype]) ## pressure in mmhg lpg_h = util.filter(gage_h - gage_h[0], LP_TAPS) + gage_h[0] llpg_h = util.filter(gage_h - gage_h[0], LLP_TAPS) + gage_h[0] flow_n = util.filter(array([l[2] for l in norm]), DELAY_TAPS) flow_h = util.filter(array([l[2] for l in hype]), DELAY_TAPS) gage_n = util.filter(gage_n, DELAY_TAPS) gage_h = util.filter(gage_h, DELAY_TAPS) gage_n = gage_n[n_skip:] gage_h = gage_h[n_skip:] lpg_n = lpg_n[n_skip:] lpg_h = lpg_h[n_skip:] llpg_n = llpg_n[n_skip:] llpg_h = llpg_h[n_skip:] flow_n = flow_n[n_skip:] flow_h = flow_h[n_skip:] ac1, tp1, SBP, DBP, MAP, HR, cba = get_arterial_compliance( flow_n, llpg_n, lpg_n, amb_temp_n, amb_pressure_n, cba=None ) print os.path.split(filename)[0], "\t%.0f\t%.0f" % (SBP, DBP)
def test(): print 'here we go' # while s.read(100000): # print 'flush serial' uc = uControl() # junk = s.read(1000) print 'here' try: print 'uc.cuff_pressure', uc.cuff_pressure print 'maintain()' uc.maintain(200, 230, 3) uc.record(True) print 'len(uc.hirate)', len(uc.hirate) while uc.pump_state: print 'uc.cuff_pressure', uc.cuff_pressure serial_interact() print 'deflate' uc.deflate(40) uc.record(False) print 'len(uc.hirate)', len(uc.hirate) hirate = array(uc.hirate) if len(uc.hirate) > 0: dt = 0.004 n_tap = 100 lp_taps = util.get_lowpass_taps(5, dt, n_tap) llp_taps = util.get_lowpass_taps(.25, dt, n_tap) lpd = util.filter(hirate[:,1] - hirate[0, 1], lp_taps)[::10] + hirate[0, 1] llpd = util.filter(hirate[:,1] - hirate[0, 1], llp_taps)[::10] + hirate[0, 1] print len(lpd) times = hirate[::10,0] ax = pylab.subplot(211) pylab.plot(times, lpd) pylab.plot(times, llpd) pylab.subplot(212, sharex=ax) pylab.plot(times, lpd - llpd) pfn = 'hirate.pkl' pickle.dump(hirate, open(pfn, 'w')) print 'write', pfn # pylab.figure(2); pylab.plot(uc.lpf.out) # pylab.figure(3); pylab.plot(hirate[:,1]) print 'done' finally: uc.deflate(50) send_cmd(pump_rate=False, valve=getValveByte(valve0=True)) time.sleep(2) send_cmd(pump_rate=False, valve=getValveByte(valve0=False), interval=0) pylab.show()
def restaurants(): if request.method == "POST": form = request.form details = form['details'] session['details'] = details details = [c.strip() for c in details.strip().strip(',').split(';')] #address radius ratings categories address = details[0] radius = int(details[1]) * 1609 rating = details[2] types = [d.strip() for d in details[3].split(',')] session['setrad'] = details[1] session['setrating'] = rating session['addr'] = address if 'types' in session: session['types'] += types else: session['types'] = types results = util.filter(address, radius, types, rating) cats = util.getTypes(address, radius) i = 0 while i < len(cats): if cats[i] in session['types']: cats.pop(i) else: i += 1 for result in results: result['category'] = catformat(result['category']) return render_template( 'restaurants.html', results=results, categories=cats) return redirect('/index')
def history(location="", restaurant="", category="", rating=0): if location == "": return redirect('/index') # if request.method == "POST": # form = request.form # rating = form['rating'] # session['rating'] = rating # util.setrating(session['user'], rating, location, restaurant, category) #rating = util.getrating(location) session['rating'] = rating # if len(rating) > 0: # rating = reduce(lambda x, y: x+y, rating)/len(rating) # rating = int(rating * 10) / 10. #else: damn = util.filter(session['addr'], 10000) damn = damn[random.randrange(len(damn))] print damn damn = '/history/%s,%s/%s/%s/%s' % ( damn['location'][0], damn['location'][1], damn['name'], catformat(damn['category']), damn['rating']) return render_template('rating.html', restaurant=restaurant, location=location.split(','), category=category.split(','), randomurl=damn)
def restaurants(): if request.method == "POST": form = request.form details = form['details'] session['details'] = details details = [c.strip() for c in details.strip().strip(',').split(';')] #address radius ratings categories address = details[0] radius = int(details[1]) * 1609 rating = details[2] types = [d.strip() for d in details[3].split(',')] session['setrad'] = details[1] session['setrating'] = rating session['addr'] = address if 'types' in session: session['types'] += types else: session['types'] = types results = util.filter(address, radius, types, rating) cats = util.getTypes(address, radius) i = 0 while i < len(cats): if cats[i] in session['types']: cats.pop(i) else: i += 1 for result in results: result['category'] = catformat(result['category']) return render_template('restaurants.html', results=results, categories=cats) return redirect('/index')
def complete_paths(): line = util.get_line()[0:util.get_cursor_col_num() - 1] m = re.search("res://(((\w|-)+/)*)$", line) if m: project_dir = util.get_project_dir() if not project_dir: return # Directories and files are grouped and sorted separately. dirs = [] files = [] base_dir = "{}/{}".format(project_dir, m.group(1)) if not os.path.isdir(base_dir): return for entry in os.listdir(base_dir): if not entry.startswith("."): if not util.filter(entry): continue if os.path.isdir("{}/{}".format(base_dir, entry)): dirs.append("{}/".format(entry)) else: files.append(entry) for d in sorted(dirs): append_completion(d) for f in sorted(files): append_completion(f)
def restaurants(): if request.method == "POST": form = request.form details = form["details"] session["details"] = details details = [c.strip() for c in details.strip().strip(",").split(";")] # address radius ratings categories address = details[0] radius = int(details[1]) * 1609 rating = details[2] types = [d.strip() for d in details[3].split(",")] session["setrad"] = details[1] session["setrating"] = rating session["addr"] = address if "types" in session: session["types"] += types else: session["types"] = types results = util.filter(address, radius, types, rating) cats = util.getTypes(address, radius) i = 0 while i < len(cats): if cats[i] in session["types"]: cats.pop(i) else: i += 1 for result in results: result["category"] = catformat(result["category"]) return render_template("restaurants.html", results=results, categories=cats) return redirect("/index")
def history(location="", restaurant="", category="", rating=0): if location == "": return redirect("/index") # if request.method == "POST": # form = request.form # rating = form['rating'] # session['rating'] = rating # util.setrating(session['user'], rating, location, restaurant, category) # rating = util.getrating(location) session["rating"] = rating # if len(rating) > 0: # rating = reduce(lambda x, y: x+y, rating)/len(rating) # rating = int(rating * 10) / 10. # else: damn = util.filter(session["addr"], 10000) damn = damn[random.randrange(len(damn))] print damn damn = "/history/%s,%s/%s/%s/%s" % ( damn["location"][0], damn["location"][1], damn["name"], catformat(damn["category"]), damn["rating"], ) return render_template( "rating.html", restaurant=restaurant, location=location.split(","), category=category.split(","), randomurl=damn )
def run(self): # download model-pkg from http or s3 from sys import version_info if version_info.major == 2: from urlparse import urlparse parsed_result = urlparse(self.source["url"]) else: from urllib import parse parsed_result = parse.urlparse(self.source["url"]) print("%s" % str(parsed_result)) self.pkg_name = parsed_result.path.split('/')[-1] getter.getterFactory(self.type)(self.source, self.model_path, self.pkg_name) # uncompress model-pkg to model_path util.uncompress(os.path.join(self.model_path, self.pkg_name), self.model_path) # filter hidden files or MAC special dirs util.filter(self.model_path) # check dir structure checker.dirCheckerFactory(self.model_type)(self.model_path)
def plot_hirate(hirate): times = hirate[:,0] gage = hirate[:,1] flow = hirate[:,2] figure(1) ax = pylab.subplot(211) ylabel('Gage mmHG') pylab.plot(times, gage) pylab.subplot(212) xlabel('Time sec.') ylabel('Flow') pylab.plot(times, flow) figure(2) ## plot high pass data lp_taps = util.get_lowpass_taps(.5, dt=.004, n=100) hpd = util.filter(gage - gage[0], lp_taps) + gage[0] plot(gage, gage - hpd)
def run_bot(replied_to): reddit = authenticate() legislators = get_legislators() names = [leg['name']['official_full'] for leg in legislators] start = '"' end = '"' while True: for mention in reddit.inbox.mentions(limit=25): if mention.id not in replied_to: mark_applied(mention.id) name = mention.body.split(start)[1].split(end)[0] person = process.extractOne(name, names, scorer=fuzz.partial_ratio)[0] matching_leg = filter( lambda x: person == x['name']['official_full'], legislators) if matching_leg: mention.reply(get_legislator_info(matching_leg)) time.sleep(10)
def do_update(bot, update): global fid global cookies global data global update_mode global update_progress global update_list logging.info('update') if update_mode: bot.send_message( chat_id=update.message.chat_id, text="Already in update mode, use /next to show next thread, or use /add `OEM` to add to certain OEM data." ) return update_mode = True bot.send_message( chat_id=update.message.chat_id, text="Update Mode - On\nPreparing data..." ) result = crawler.crawl(fid, cookies, data['lastUpdateTime'], data['lastUpdateThread']) update_progress = 0 update_list = util.filter(result, regex) next_thread(bot, update)
def thread_save(): while runing: moveon, bufferData = first_buffer() if not moveon: continue current_time = pygame.time.get_ticks() # how long to show or hide move_delay = 7000 # time of next change change_time = current_time + move_delay while current_time < change_time: chunk = read_data() if len(chunk) > 0: chunk = np.array(chunk).transpose() bufferData = np.concatenate((bufferData, chunk), axis=1) current_time = pygame.time.get_ticks() try: data = ul.filter(bufferData, Fs) target = ul.generate_target(data, Fs) index = ul.cca(data, target) player = maze.player if player is None: raise Exception('Fail find player') maze.move_right() # if index == 0: # maze.move_up() # elif index == 1: # maze.move_bottom() # elif index == 2: # maze.move_left() # else: # maze.move_right() except Exception as error: print(error)
def plot_hirate(hirate, color): dt = 0.004 n_tap = 100 fmax = 10 ## Hz lp_taps = util.get_lowpass_taps(fmax, dt, n_tap) delay_taps = zeros(defaults['n_tap']) delay_taps[defaults['n_tap'] // 2] = 1 lpd = util.filter(hirate[:,1] - hirate[0, 1], lp_taps) + hirate[0, 1] ax = pylab.subplot(211) times = hirate[:,0] pylab.plot(times, lpd) peaks, troughs = util.find_peaks_and_troughs(lpd, eps=.1, edit=False) if peaks[0] < troughs[0]: peaks = peaks[1:] if peaks[-1] < troughs[-1]: troughs = troughs[:-1] pylab.plot(times[peaks], lpd[peaks], 'ro') pylab.plot(times[troughs], lpd[troughs], 'bo') deltas = lpd[peaks] - lpd[troughs] print std(deltas) pylab.subplot(212) pylab.plot(lpd[troughs], deltas)
def chan_data(self, eeg, chan): """returns data for channel @chan from the signal matrix @eeg which is arranged as an (electrode x time sample) ndarray, parameterized by the polarities""" return util.filter(self.pols @ self.chanMatrix @ eeg)
return {k: v for k, v in [x.split(":") for x in raw_passport]} def passports(data): return [ build_passport(" ".join(block).split(" ")) for block in split_by(lambda x: x is "")(data) ] def validate_with(validators): def validator(entry): key, value = entry return validators.get(key, lambda x: True)(value) return validator def is_valid(passport): return (contained_in(required_fields, passport.keys()) and all( validate_with(validators)(entry) for entry in passport.items())) result = [[is_valid(passport), passport] for passport in passports(real_data)] assert not any(is_valid(passport) for passport in passports(test_invalids)) assert all(is_valid(passport) for passport in passports(test_valids)) print(len(list(filter(passports(real_data), is_valid))))
def dP_dt(t, r0, p0, a, b): ''' eqn (1a)''' _r = -smooth_dP_dt(t, r0, p0) xx = P0 -smooth_P(t, r0, p0) return -_r + (P0 + Pamb - xx) / (V0) * dVa_dt(t, r0, p0, a, b) t = arange(0, Tmax, DT) def P(t, r0, p0, a, b): return P0 + cumsum(dP_dt(t, r0, p0, a, b)) * DT IDX = slice(None, None, OVERSAMPLE) Pt1 = P(t, R0, P0, A, B)[IDX] Pt2 = P(t + .5/HR, R0, P0, A, .75 * B)[IDX] lp1 = util.filter(Pt1 - Pt1[0], LP_TAPS) + Pt1[0] llp1 = util.filter(Pt1 - Pt1[0], LLP_TAPS) + Pt1[0] lp2 = util.filter(Pt2 - Pt2[0], LP_TAPS) + Pt2[0] llp2 = util.filter(Pt2 - Pt2[0], LLP_TAPS) + Pt2[0] XX = (smooth_P(t[IDX], R0, P0) - P0) fixup = -util.filter(XX, LP_TAPS - LLP_TAPS) bpf1 = lp1 - llp1 + fixup bpf2 = lp2 - llp2 + fixup if False: figure(1) subplot(212) plot(t, smooth_P(t, R0, P0))
def build_completion(item, c_name=None): t = type(item) d = {} if t is str: if util.filter(item): d["word"] = item elif item.name: if not util.filter(item.name): return # Built-in if t is classes.GodotMember: d["word"] = item.name if c_name: d["abbr"] = "{}.{}".format(c_name, item.name) d["kind"] = item.type elif t is classes.GodotConstant: d["word"] = item.name if c_name: d["abbr"] = "{}.{} = {}".format(c_name, item.name, item.value) else: d["abbr"] = "{} = {}".format(item.name, item.value) if item.type: d["kind"] = item.type elif t is classes.GodotMethod: if len(item.args) > 0: d["word"] = "{}(".format(item.name) else: d["word"] = "{}()".format(item.name) args = list(map(lambda a: "{} {}".format(a.type, a.name), item.args)) qualifiers = " {}".format(item.qualifiers) if item.qualifiers else "" if "vararg" in qualifiers: args.append("...") joined_args = ", ".join(args) if c_name: d["abbr"] = "{}.{}({}){}".format(c_name, item.name, joined_args, qualifiers) else: d["abbr"] = "{}({}){}".format(item.name, joined_args, qualifiers) d["kind"] = item.returns # User decls elif t is script.VarDecl: d["word"] = item.name if item.type: d["kind"] = item.type elif t is script.ConstDecl: d["word"] = item.name if item.value: d["abbr"] = "{} = {}".format(item.name, item.value) elif t is script.FuncDecl: if len(item.args) > 0: d["word"] = "{}(".format(item.name) else: d["word"] = "{}()".format(item.name) d["abbr"] = "{}({})".format(item.name, ", ".join(item.args)) elif t is script.EnumDecl: d["word"] = item.name d["kind"] = "enum" elif t is script.ClassDecl: d["word"] = item.name d["kind"] = "class" if not d: return d["dup"] = 1 if util.get_ignore_case(): d["icase"] = 1 return d
size = 0 df_from_each_file = [] for file in all_files: size += os.path.getsize(file) df = pd.read_csv(file, sep=',', header=None, names=None) df.columns = HEADER_LONG if (df.shape[1] == len(HEADER_LONG)) else HEADER_SHORT df_from_each_file.append(df) df = pd.concat(df_from_each_file, ignore_index=True, sort=False) print(" Reading {0} files {1:.2f} kB".format(len(all_files), size / (1024))) total_rows = df.shape[0] df = util.filter(df) conf_file = os.path.join(path_to_measurement, 'conf.json') CENTER = config[measurement]["center"] util.addDistanceTo(df, CENTER) df = df[df['distance'] < 100 * 1000] util.addPathLossTo(df) current_rows = df.shape[0] current_rows_data = df[df.isPacket > 0].shape[0] print(" Processed {0}/{1} {2:.1f}% rows".format( current_rows, total_rows, (current_rows / total_rows) * 100)) print(" Processed {0}/{1} {2:.1f}% and {3:.1f}% of total".format( current_rows_data, current_rows, (current_rows_data / current_rows) * 100,
# @Software: PyCharm import numpy as np import cv2 as cv import copy import util # 读取图像 origin_img = cv.imread("../img/mission1/car.jpg") origin_img = copy.copy(origin_img) origin_gray = cv.cvtColor(origin_img, cv.COLOR_BGR2GRAY) origin_gray = origin_gray.astype(np.float) / 256 cv.imshow("Raw Gray", origin_gray) kernel_size = (3, 3) gauss_img = util.filter(origin_gray, util.Gauss_kernel) cv.imshow("Gauss Gradient", gauss_img) center_8_img = util.filter(origin_gray, util.Center_8_kernel) cv.imshow("Center_8 Gradient", center_8_img) center_4_img = util.filter(origin_gray, util.Center_4_kernel) cv.imshow("Center_4 Gradient", center_4_img) dignoal_img = util.filter(origin_gray, util.Diagonal_opposite_kernel) cv.imshow("Dignoal Gradient", dignoal_img) center_peek_img = util.filter(origin_gray, util.Center_peek_kernel) cv.imshow("Center Peek Gradient", center_peek_img) origin_kernel_img = util.filter(origin_gray, util.Origin_kernel)