def stream(unused_addr, *raws): raw_list = np.array([float(r) * 10.0 for r in raws]).astype(np.int64) config.is_calibration = cb.start_calibration(config.is_calibration, raw_list) xyz = raw_list - config.calibration_numbers #print(len(raws), xyz[0], len(xyz), len(config.calibration_numbers), len(config.fitted_data)) #print(fitted_data, raw_list) dist = [] aves = np.array([0 for n in range(132)]).astype(np.int64) for label, f in enumerate(config.fitted_data): dist.append(np.linalg.norm(f - xyz)) #print(label, f - xyz) ''' for f in fitted_data: count = 0 for label, a in enumerate(raws): aves += a count += 1 aves = aves/count dist.append(np.linalg.norm(f - aves)) ''' predict_label = np.argmin(dist) print("predict_label", predict_label, config.face_expression[predict_label])
def serial_loop(): with serial.Serial('COM5', 9600, timeout=0.1) as ser: between_a_and_a = False want_predict_num_array_raw = [] arranged_sensor_date_list = [] count_label = 0 learner = None #このスコープのみで有効な学習器 if config.learner == "svm": learner = svm else: learner = na machine = learner.setup() try: while True: s = ser.readline() m = None try: de = s.decode('utf-8') m = re.match("\-*[\w]+", str(de)) except Exception as e: pass if (m != None): num = m.group() #print(want_predict_num_array) if num == "a": between_a_and_a = True count_label = 0 want_predict_num_array_raw = [] elif between_a_and_a: want_predict_num_array_raw.append(int(num)) if len(want_predict_num_array_raw) == config.sensor_nums: count_label = 0 if config.calibration_numbers is not None: want_predict_num_array = want_predict_num_array_raw - config.calibration_numbers else: want_predict_num_array = want_predict_num_array_raw config.is_calibration = Calibrate.start_calibration( config.is_calibration, want_predict_num_array) while len(arranged_sensor_date_list) > 1: arranged_sensor_date_list.pop(0) arranged_sensor_date_list.append( want_predict_num_array) want_predict_num_array = [] between_a_and_a = False ser.flushInput() #print(xyz_array) learner.stream( machine, np.array(arranged_sensor_date_list).astype( np.int64)) else: pass #print(type(m)) except: print("Unexpected error:", sys.exc_info()[0]) raise ser.close()
def fetch_numbers(self, matched_group): is_calibration = config.is_calibration console_input_number = config.console_input_number self.calibration_numbers = config.calibration_numbers make_serial_flush = False if self.pre_console_input_number != console_input_number: self.pre_console_input_number = console_input_number self.count = 0 self.count2 = 0 #???? fn = os.path.join(os.getcwd(), self.mode, console_input_number) if not os.path.exists(fn): if console_input_number != "1025": os.makedirs(fn) else: nums_past_all_fn = os.listdir(fn) nums_past_all = [] for nums in nums_past_all_fn: num, ext = os.path.splitext(os.path.splitext(nums)[0]) nums_past_all.append(int(num)) if len(nums_past_all) != 0: self.count = max(nums_past_all) + 1 if matched_group == "a": #strat byte == a self.between_a_and_a = True self.result_list_nums = [] elif self.between_a_and_a: self.result_list_nums.append(int(matched_group)) if len(self.result_list_nums) == self.sensor_nums: self.between_a_and_a = False make_serial_flush = True if is_calibration: is_calibration = Calibrate.start_calibration( is_calibration, np.array(self.result_list_nums).astype(np.int64)) if self.count < self.pattern[ self.mode] and console_input_number.isdigit(): if self.count2 < 5: result_list = np.array(self.result_list_nums).astype( np.int64) - self.calibration_numbers if console_input_number != "1025": self.write_ceps(result_list, console_input_number) print("Calibration Mode is ", is_calibration, ":input array = ", result_list, ":MODE = ", self.mode) return is_calibration, make_serial_flush
def main(): global awayFromHome awayFromHome = False print("Top Level running") threads = [] calibrated = False # Calibration Loop while calibrated == False: Readings = Calibrate.Calibrate() calibrated = Calibrate.Check(Readings) # Once calibrated, a thread is generated for each component threadComp = Thread(target=RunCompass.Run, args=(Readings["comp"],)) threadAcc = Thread(target=RunAcc.Run) threadTemp = Thread(target=RunTemp.Run, args=(Readings["temp"],)) threadComp.daemon = True # Setting daemon flag to True forces the threads threadAcc.daemon = True # to terminate once the main program does threadTemp.daemon = True threads.append(threadComp) threads.append(threadAcc) threads.append(threadTemp) # Run the threads threadComp.start() threadAcc.start() threadTemp.start() # Keep the program running as to not terminate the daemonic threads while True: pass
def calibrate(self): np.set_printoptions(precision=2, suppress=True, linewidth=200) self.matchImages = [] # for each image pair... for i in range(int(len(self.images)/2)): # Find it's circular points (and output details) self.matchImages.append(Calibrate.getCircularPoints(self.images[i*2][0], self.images[i*2+1][0])) self.setMatchImage(0) # Prepare a matrix for linear fitting of conic parameters DLT = [] for matchImage in self.matchImages: DLT += matchImage[0] try: # Find the focal lengths if self.focalOnly.get() == 1: # Linear fit of IAC parameters A = np.array(Calibrate.getFocalLengthConic(DLT)) print("A: ", A) # Decompose the conic to a calibration matrix K = Calibrate.getFocalLength(A) # Same with full calibration matrix else: A = np.array(Calibrate.getConic(DLT)) print("A: ", A) K = Calibrate.getCameraParameters(A) self.calibrationMatrixLabel.config(text=self.matrixDisplayString(K, "K")) except np.linalg.linalg.LinAlgError: self.calibrationMatrixLabel.config(text="DIAC not positive definite")
def getRainValue(B0, B1): ########################## INPUT VALUES ######################################## AttenSampleData = np.genfromtxt('AttenGenerator/Sample.txt', delimiter=';') AttenSampleYear = AttenSampleData[0] AttenSampleMonth = AttenSampleData[1] AttenSampleDay = AttenSampleData[2] AttenSampleHour = AttenSampleData[3] AttenSampleValue = AttenSampleData[4] ############################ HYPOTHESIS RESULT CALC ############################ x = AttenSampleValue Xmean, Xmax, Xmin, Ymean, Ymax, Ymin = Calibrate.GetImpValues() Xnorm = (x - Xmean) / (Xmax - Xmin) Ynorm = B0 + B1 * (Xnorm) y = ((Ymax - Ymin) * (Ynorm)) + Ymean return y, x, AttenSampleYear, AttenSampleMonth, AttenSampleDay, AttenSampleHour
def do_GET(self): if(self.path.startswith(apiPrefix)): # All API request calls are handled and parsed within this function. # They are then passed onto the appropriate handler function. args = {} function = self.path.replace(apiPrefix, "").split(apiArgStringSep)[0] page = "self" if(apiClassFuncSep in function): page = function.split(apiClassFuncSep)[0] function = function.split(apiClassFuncSep)[1] if(apiArgStringSep in self.path): argString = self.path.split("?")[1] for kvp in argString.split("&"): key = kvp.split("=")[0] value = kvp.split("=")[1] args[key] = value print(key+":\t"+value) print("Page: \t"+page) print("Function:\t"+function) if(function == "saveLatestFrame"): result = cam.save_latest() if(result): print("Updated latest frame!") self.send_response(200) else: self.send_response(500) elif(function == "getLatestFrame"): result = cam.capture() if(result != None): print("Captured latest frame!") self.send_response(200) self.send_header("Content-type", "image/jpeg") self.end_headers() self.wfile.write(result) else: self.send_response(500) elif(page == "Calibration"): if(function=="newBlank"): newFile = Calibrate.newBlankFile() print("Created new calibration file: "+newFile) self.send_response(200) self.send_header("Content-type", "text/text") self.end_headers() self.wfile.write(bytes(newFile)) elif(function == "getAll"): print("Fetching list of available config files...") self.send_response(200) self.send_header("Content-type", "text/text") self.end_headers() files = Calibrate.listCalibrationFiles() for f in files: self.wfile.write(bytes(f+","+files[f]+"\n")) elif(function == "LoadEl"): print("Loading element from file...") result = Calibrate.getElement(args["file"], args["el"]) self.send_response(200) self.send_header("Content-type", "text/text") self.end_headers() self.wfile.write(bytes(result)) elif(function == "delete"): print("Deleting calibration file: "+args["file"]) Calibrate.deleteFile(args["file"]) self.send_response(200) self.send_header("Content-type", "text/text") self.end_headers() else: super(APIHandler, self).do_GET()
def combined(inputfile, debug=False): start_file = inputfile img = cv2.imread(start_file) full_img = cv2.imread(start_file) original_img = deepcopy(img) fullheight, fullwidth, fullchannels = full_img.shape print "fullwidth %s" % fullwidth print "fullheight %s" % fullheight img, scale = ScaleImage.scale(full_img,1000) height, width, channels = img.shape scaled_img = deepcopy(img) ##First blur image in order to reduce noise blurred_img = deepcopy(img) print "Blurring image for filtering" blurred_img = cv2.GaussianBlur(blurred_img,(9,9),0) blurred_img = cv2.GaussianBlur(blurred_img,(9,9),0) blurred_img = cv2.GaussianBlur(blurred_img,(9,9),0) print "Blurring done" cv2.imwrite("Test_Images/Output_Images/blurred_img.jpg", blurred_img) ##Then find the average background color print "Calibrating color filtration" red,green,blue = Calibrate.findRed(blurred_img) ##Filter the image based on that average color print "Filtering blurred image" blurred_img = FilterImage.filter(blurred_img,red,green,blue) if (debug): showImage.showImage(blurred_img) ##Mask the original image based on the the blurred filter print "Masking original image based on blurred image" for y in range(0,height): for x in range(0,width): pxR = blurred_img[y,x,2] pxB = blurred_img[y,x,1] pxG = blurred_img[y,x,0] if ( (pxR == 0) and (pxG == 0) and (pxB == 0) ): img[y,x] = 0 cv2.imwrite("Test_Images/Output_Images/justFiltered.jpg", img) if (debug): showImage.showImage(img, "Just filtered") morpher = ImageMorpher() openimg = deepcopy(img) ## Use morphology to get rid of erratic blobs and specs print "Doing morphology to fix blobbies" openimg = morpher.openWithSquare(openimg,7) openimg = morpher.closeWithSquare(openimg,7) openimg = cv2.cvtColor(openimg,cv2.COLOR_BGR2GRAY) for x in range(0,height): for y in range(0,width): px = openimg[x,y] if ( (px == 0) ): openimg[x,y] = 0 else: openimg[x,y] = 255 ##Get contours for remaining blobs print "Contouring blobbies" contoured_img, contours, hierarchy = cv2.findContours(openimg,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) ##Get rid of the tiny remaining specs print "Removing small blobs" for i in range(0, len(contours)): cnt = contours[i] if (cv2.contourArea(cnt) < 2000): cv2.drawContours(contoured_img,cnt,-1,0,thickness=cv2.FILLED) ##Create a new mask to remove contours print "Masking image based on removed contours" for x in range(0,height): for y in range(0,width): px = contoured_img[x,y] if ( (px == 0) ): img[x,y] = [0,0,0] else: continue if (debug): showImage.showImage(img, "Filtered and corrected") color_filtered_img = deepcopy(img) cv2.imwrite("Test_Images/Output_Images/1_Template_Color_Filtered.jpg",img) temp = deepcopy(color_filtered_img) ##Watershed works best with blurred image print "Blurring image for watershed algorithm" img = cv2.GaussianBlur(img,(9,9),0) img = cv2.GaussianBlur(img,(9,9),0) ##### #Watershed segmentation b,g,r = cv2.split(img) rgb_img = cv2.merge([r,g,b]) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) # noise removal kernel = np.ones((2,2),np.uint8) closing = cv2.morphologyEx(thresh,cv2.MORPH_CLOSE,kernel, iterations = 2) # sure background area sure_bg = cv2.dilate(closing,kernel,iterations=1) # Finding sure foreground area dist_transform = cv2.distanceTransform(sure_bg,cv2.DIST_L2,3) # Threshold ret, sure_fg = cv2.threshold(dist_transform,0.1*dist_transform.max(),255,0) # Finding unknown region sure_fg = np.uint8(sure_fg) unknown = cv2.subtract(sure_bg,sure_fg) # Marker labelling ret, markers = cv2.connectedComponents(sure_fg) # Add one to all labels so that sure background is not 0, but 1 markers = markers+1 # Now, mark the region of unknown with zero markers[unknown==255] = 0 markers = cv2.watershed(img,markers) img[markers == -1] = [255,0,0] cv2.imwrite('Test_Images/Output_Images/2_Template_Watershedded.jpg',img) if (debug): showImage.showImage(img,"Template_Watershedded") water_img = deepcopy(img) new_img = img for x in range(1,height-1): for y in range(1,width-1): if markers[x,y] == -1: new_img[x,y] = [255,255,255] else: new_img[x,y] = [0,0,0] cv2.imwrite('Test_Images/Output_Images/3_Template_Just_Watershed_Edges.jpg',new_img) ##### #Hough Circles print "Doing Hough cirlces on watershedded edges" scimg = cv2.imread('Test_Images/Output_Images/3_Template_Just_Watershed_Edges.jpg',0) #scimg = cv2.medianBlur(scimg,5) sccimg = cv2.cvtColor(scimg,cv2.COLOR_GRAY2BGR) circles = cv2.HoughCircles(scimg,cv2.HOUGH_GRADIENT,1,100, param1=50,param2=20,minRadius=30,maxRadius=100) ##circles = cv2.HoughCircles(scimg,cv2.HOUGH_GRADIENT,1,50, ## param1=50,param2=15,minRadius=15,maxRadius=50) counter = 0 radsum = 0 try: print circles.shape except Exception, e: print e
def calibrate(): print ('Calibrate') w.Calibration.configure(state=DISABLED,cursor='arrow') Calibrate.create_Calibration_Mode (root,w)
window.resizable(0, 0) window.config(bg="white") ##################### IMPORT THE CALIBRATION AND ALERT ######################### import Calibrate import RainValueCalc ############################# DEFINITIONS ###################################### TimerFlag = True sTime = 5000 graphDataY = np.zeros(9) graphDataX = np.ones(9) * (-47) counterG = 0 B0, B1 = Calibrate.RunCalibrate() PromR = np.ones(9) PromVal = 0 xList = [" ", " ", " ", " ", " ", " ", " ", " ", " "] clr = "#b5c3cb" ############################# FRAMES CONFIG #################################### linkDetail = Frame() linkDetail.pack() def linkDetailTimer(): linkDetail.config(bg=clr) linkDetail.config(width="1300", height="100") linkDetail.config(bd=5) linkDetail.config(relief="ridge")
def InitializeStepEngine(order_list, image_list, options, parameters, timedata): ## Connect to the step engine and turn off the joystick ConnectSimple(1, "COM4", 9600, 0) SetJoystickOff() # ## We find any potential difference between the speed we set, and the speed we get SetVelocityToFactor(0.1,0.1,0,0) # This is noise vel_fac = GetVelocityFactor() x_vel_fac, y_vel_fac = vel_fac[0], vel_fac[1] speed_error = CalcSpeedError(0.3) print "speed error is ", speed_error ## We callibrate our positions, so that the inlets are where we wants them to be left_inlet, right_inlet = Calibrate(options.needs_calibrate) # We don't actually do anything with them atm :D ## We find the appropriate starting position if options.starting_left: start_x = 0 else: start_x = -35 MoveToAbsolutePosition(start_x,0,0,0,1) ## We assume that we are at the left inlet ## If we do not have a good average image, we fix that. if options.needs_average: dirt_arr = GetAverageImage(options) else: dirt_im = Image.open("Images/Averaging/average_image.jpg") dirt_arr = np.array(dirt_im) dirt_arr= dirt_arr.astype(np.float32) ## Remove old image files if we intend to save new ones if options.printing_output: # nothing = raw_input("Press enter to remove old image files") contour_folder = "Images/Contours" positions_folder = "Images/Positions" clear_folder(contour_folder) # Makes sure we only store the images from this particular run. clear_folder(positions_folder) remove_old_images() ## We let the user find a particle SetJoystickOn(True, True) print "Press the star tracking button to initiate tracking of the particle closes to the middle" state = DetectorState(parameters, options) state.speed_error = speed_error state.vel_fac = [x_vel_fac, y_vel_fac] while True: if not order_list.empty(): if order_list.get() == "start_tracking": break im = ImageGrab.grab(parameters.box) contours, pix = GetContours(im, dirt_arr, 210, printing_output=False, iteration=0) best_contour_nr, positions = DetectParticle(state,contours,0, timedata,pix, parameters, options, initialize=True) # i is the current nr of runs if best_contour_nr < 0: continue cv2.drawContours(pix,[contours[best_contour_nr]],-1,(0,255,0),3) im = Image.fromarray(pix) image_list.put(im) sleep(1.5/parameters.fps_max) ## We find the velocity we were going at vel_approx = CalcVelocity(0.1) print "vel approx is ", vel_approx state.step_vel = np.array([vel_approx[0],vel_approx[1]]) state.going_right = vel_approx[0]<0 state.flowing_right = vel_approx[0]<0 print " We think we are going right: ", state.going_right print " We think we are going right: ", state.flowing_right ## We set the step engine to move at this speed SetJoystickOff() ##### MAYBE WE SHOULD INCLUDE THE SPEED ERROR HERE? I THINK SO BUT LET'S TEST THAT IT'S REASONABLE FIRST SetSpeed(vel_approx[0]/x_vel_fac, vel_approx[1]/y_vel_fac, 0, 0, max_speed = 3.0/(min(x_vel_fac, y_vel_fac))) # return np.array([vel_approx[0],vel_approx[1]]), dirt_arr, speed_error, [x_vel_fac, y_vel_fac], going_right return dirt_arr, state
def calibrate(): print ('Calibrate') Calibrate.create_Calibration_Mode (root)
def process_calibration_parameters(): ''' -------------------------------------------------------------------- This function defines parameters that are used for calibration of the chi_n_vec -------------------------------------------------------------------- INPUTS: S = integer in [3, 80], number of periods an individual lives hours_worked_file_name = string, name of the hours worked STATA file hours_worked_file_years = string, years included in the names of the STATA files with hours worked data file_extensions = string, STATA data file extension consumption_file_name = string, name of the STATA file that contains data on average monthly consumption expenditure and income hours_worked_file_parameter_name = string, header of the dataset for hours worked in the STATA file hours_worked_file_parameter_name2 = string, header of the dataset for number of persons in the STATA file time_endowment = integer, numer of total weekly hours that can be used for work files_path = string, path where the source STATA files are saved OBJECTS CREATED WITHIN FUNCTION: hours_worked_file_complete_name = string, complete name of the hours worked STATA file that includes year and file extension consumption_file_complete_name = string, complete name of the consumption and income STATA file that includes file extension hours_worked_file_parameter = string, header of the dataset for hours worked in the STATA file hours_worked_file_parameter2 = string, header of the dataset for number of individuals in the STATA file consumption_file_parameter = string, header of the dataset for average monthly consumption expenditure in the STATA file consumption_file_parameter2 = string, head of the dataset for income in the STATA file consumption_file_year = year of the data for average income by age of an individual years = string, elements of the years_list years_list = list, years of hours worked data FILES CREATED BY THIS FUNCTION: None RETURNS: calibration_params -------------------------------------------------------------------- ''' with open("parameters.json") as json_data_file: data = json.load(json_data_file) calibration_data = data['calibration'] print(calibration_data) S = calibration_data['S'] hours_worked_file_name = calibration_data['hours_worked_file_name'] hours_worked_file_years = calibration_data['hours_worked_file_years'] file_extensions = calibration_data['file_extensions'] consumption_file_name = calibration_data['consumption_file_name'] hours_worked_file_parameter_name = calibration_data[ 'hours_worked_file_parameter'] hours_worked_file_parameter_name2 = calibration_data[ 'hours_worked_file_parameter2'] population_by_age_file_name = calibration_data[ 'population_by_age_file_name'] population_by_age_file_parameter = calibration_data[ 'population_by_age_file_parameter'] population_by_age_sheet_name = calibration_data[ 'population_by_age_sheet_name'] time_endowment = calibration_data['time_endowment'] files_path = calibration_data['files_path'] years = hours_worked_file_years.split(" ") hours_worked_file_complete_name = [] hours_worked_file_parameter = [] hours_worked_file_parameter2 = [] consumption_file_parameter = [] consumption_file_parameter2 = [] years_list = [] for year in years: file_name = hours_worked_file_name + "_" + year + "." + file_extensions hours_worked_file_complete_name.append(file_name) parameter_name = hours_worked_file_parameter_name + "_" + year parameter_name2 = hours_worked_file_parameter_name2 + "_" + year hours_worked_file_parameter.append(parameter_name) hours_worked_file_parameter2.append(parameter_name2) years_list.append(year) consumption_file_parameter = calibration_data['consumption_file_parameter'] consumption_file_parameter2 = calibration_data[ 'consumption_file_parameter2'] consumption_file_year = calibration_data['consumption_file_year'] print(years_list) print(hours_worked_file_complete_name) print(hours_worked_file_parameter) print(hours_worked_file_parameter2) consumption_file_complete_name = consumption_file_name + "." + file_extensions print(consumption_file_complete_name) calibration_params = Calibrate.Calibrate( S, hours_worked_file_complete_name, consumption_file_complete_name, hours_worked_file_parameter, hours_worked_file_parameter2, consumption_file_parameter, consumption_file_parameter2, consumption_file_year, population_by_age_file_name, population_by_age_file_parameter, population_by_age_sheet_name, files_path, years_list, time_endowment) print(calibration_params) return calibration_params
import os import sys import threading sys.path.append('../') from Prologix import Prologix from Configuration import * import CollectDAC import Calibrate import CollectBias import CollectCurrent import CollectScan import CollectScan_Drift2 import CollectBiasScan if data == 'calibrate': Calibrate.calibrate() elif data == 'bias': CollectBias.bias() elif data == 'dac': CollectDAC.dac() elif data == 'current': print('Collecting current.') CollectCurrent.current() elif data == 'scan': CollectScan.scan() elif data == 'bias_scan': CollectBiasScan.scan() elif data == 'scan_drift2': CollectScan_Drift2.scan()
def serial_loop(): with serial.Serial('COM5', 9600, timeout=0.1) as ser: setPortCount = 0 between_a_and_a = False want_predict_num_array_raw = [] arranged_sensor_date_list = [] count_label = 0 machine = svm.setup() try: while True: s = ser.readline() m = None if setPortCount < 100: print("waiting port now" + str(setPortCount)) ser.write(bytes(str(2), 'UTF-8')) try: de = s.decode('utf-8') m = re.match("\-*[\w]+", str(de)) except Exception as e: pass if not m is None: num = m.group() setPortCount = setPortCount + 1 if num == "a": between_a_and_a = True count_label = 0 want_predict_num_array_raw = [] elif between_a_and_a: if int(num) == 0: print("重篤なエラーがあります") want_predict_num_array_raw.append(int(num)) if len(want_predict_num_array_raw) == config.sensor_nums: count_label = 0 if config.calibration_numbers is not None: want_predict_num_array = want_predict_num_array_raw - config.calibration_numbers else: want_predict_num_array = want_predict_num_array_raw config.is_calibration = Calibrate.start_calibration( config.is_calibration, want_predict_num_array) while len(arranged_sensor_date_list) > 1: arranged_sensor_date_list.pop(0) arranged_sensor_date_list.append( want_predict_num_array) want_predict_num_array = [] between_a_and_a = False ser.flushInput() svm.stream_w_face( machine, np.array(arranged_sensor_date_list).astype( np.int64)) else: pass except: print("Unexpected error:", sys.exc_info()[0]) raise ser.close()
def serial_loop(): ''' OSC ''' parser = argparse.ArgumentParser() parser.add_argument("--ip", default="127.0.0.1", help="The ip of the OSC server") parser.add_argument("--port", type=int, default=12345, help="The port the OSC server is listening on") args = parser.parse_args() client = udp_client.UDPClient(args.ip, args.port) ''' Serial ''' with serial.Serial('COM5', 9600, timeout=0.1) as ser: setPortCount = 0 between_a_and_a = False want_predict_num_array_raw = [] arranged_sensor_date_list = [] count_label = 0 learner = None #このスコープのみで有効な学習器 if config.learner == "svm": learner = svm else: learner = na machine = learner.setup() try: while True: s = ser.readline() m = None if setPortCount < 100: print("waiting port now" + str(setPortCount)) ser.write(bytes(str(2), 'UTF-8')) try: de = s.decode('utf-8') m = re.match("\-*[\w]+", str(de)) except Exception as e: pass if (m != None): setPortCount = setPortCount + 1 num = m.group() #print(want_predict_num_array) if num == "a": between_a_and_a = True count_label = 0 want_predict_num_array_raw = [] elif between_a_and_a: want_predict_num_array_raw.append(int(num)) if len(want_predict_num_array_raw) == config.sensor_nums: count_label = 0 if config.calibration_numbers is not None: want_predict_num_array = want_predict_num_array_raw - config.calibration_numbers else: want_predict_num_array = want_predict_num_array_raw config.is_calibration = Calibrate.start_calibration( config.is_calibration, want_predict_num_array) while len(arranged_sensor_date_list) > 1: arranged_sensor_date_list.pop(0) arranged_sensor_date_list.append( want_predict_num_array) want_predict_num_array = [] between_a_and_a = False ser.flushInput() #print(arranged_sensor_date_list[0]) p_label = learner.stream( machine, np.array(arranged_sensor_date_list).astype( np.int64)) #print(type(p_label)) msg = osc_message_builder.OscMessageBuilder( address="/emotion") msg.add_arg(int(p_label)) #msg = osc_message_builder.OscMessageBuilder(address = "/raw") for a in arranged_sensor_date_list[0]: msg.add_arg(int(a)) msg = msg.build() client.send(msg) else: pass #print(type(m)) except: print("Unexpected error:", sys.exc_info()[0]) raise ser.close()
job_states[jobs[i]] = state print "Current states: " + str(result_map) time.sleep(5) if finish_counter == NUMBER_JOBS_PER_STAGE: break runtime.append(time.time() - starttime[stage]) print "#################################################" print "Runtime for Stage " + str(stage) + " is: " + str( runtime[stage]) + " s; Runtime per Job: " + str( runtime[stage] / NUMBER_JOBS_PER_STAGE) print "finished with Stage number: " + str(stage) print "#################################################" print "Performing checking" print "Running Calibrate.py" if (Calibrate.Calibrate() == 1): print "Calibration successful" else: print "Calibration failed, proceed with caution" print "#################################################" print "Checking the actual output files" RERUN_LIST = FileTest.FileTest(WORK_DIR, SIMULATION_DIR_PREFIX, OUTPUT_FILE_EXTENSION, NUMBER_JOBS_PER_STAGE) if len(RERUN_LIST) != 0: print "THE FOLLOWING JOBS FAILED: " + str(out) print "Attempting to re-submit" rerun_jobs = [] rerun_job_start_times = {} rerun_job_states = {}