def main(): # We'll open the visualizer by spawning it as a subprocess. See # testDrakeVisualizer.py for an example of how to spawn it within Python # instead. vis_binary = os.path.join(os.path.dirname(sys.executable), "drake-visualizer") print("vis_binary:", vis_binary) vis_process = subprocess.Popen([vis_binary, '--testing', '--interactive']) # The viewer will take some time to load before it is ready to receive # messages, so we'll wait until it sends its first status message. print("waiting for viewer to initialize") lc = lcm.LCM() lc.subscribe("DRAKE_VIEWER_STATUS", lambda c, d: None) # Wait for one LCM message to be received. lc.handle() # Load and animate the robot publish_robot_data() # Shut down the viewer. vis_process.terminate()
def __init__(self, title, aircraft): wx.Frame.__init__(self, None, title=title, pos=(150, 150), size=(850, 550)) self.aircraft = aircraft # set up lcm self.lc = lcm.LCM("udpm://239.255.76.67:7667?ttl=0") self.lc_event = threading.Event() self.reset() # start the lcm listener thread self.lcm_listener_thread = LcmListener(self.lc, self.lc_event) self.lcm_listener_thread.daemon = True # so that it dies when the program stops self.lcm_listener_thread.start() self.Show()
def main(): lc = lcm.LCM() true_graph = Grid(True) Graph_data = "1GraphData" subscription = lc.subscribe(Graph_data, true_graph.graph_data_handler) test_case = 50 L2_error_collection = [] ave_cell_error = [] try: if True: lc.handle() true_graph.graph_vis("Origin") true_graph.graph_vis() for tc in range(test_case): # Generate the training data training_idx = [] while len( training_idx) < grid_rows * grid_cols * training_ratio: t_idx = random.randint(0, grid_cols * grid_rows) if t_idx not in training_idx and t_idx in nz_ig: training_idx.append(t_idx) unknown_graph = Grid(False) unknown_graph.gp(true_graph, training_idx) true_graph.calculate_L2_error() L2_error_collection.append(true_graph.L2_error_total_) ave_cell_error.append(true_graph.L2_error_total_ / (grid_cols * grid_rows)) print(L2_error_collection) print(ave_cell_error) print("The L2 norm for cases is {}".format( sum(L2_error_collection) / test_case)) print("The average cell L2 error is {}".format( sum(ave_cell_error) / test_case)) except KeyboardInterrupt: pass lc.unsubscribe(subscription)
def wait_for_lcm_message_on_channel(channel): """Wait for a single message to arrive on the specified LCM channel. """ m = lcm.LCM() def receive(channel, data): _ = (channel, data) raise StopIteration() sub = m.subscribe(channel, receive) start_time = time.time() try: while True: if time.time() - start_time > 10.: raise RuntimeError("Timeout waiting for channel %s" % channel) rlist, _, _ = select.select([m], [], [], 0.1) if m in rlist: m.handle() except StopIteration: pass finally: m.unsubscribe(sub)
def main(): joysticks = [Joystick(0, LED_BLUE), Joystick(1, LED_GOLD), Joystick(2, LED_BONUS)] lc = lcm.LCM(settings.LCM_URI) if len(sys.argv) > 1: node_name = sys.argv[1] else: node_name = "default" seqs = [make_seq(lc, node_name, joystick.joystick) for joystick in joysticks] current_state_ids = [0 for _ in range(3)] while True: time.sleep(SLEEP_TIME) for i in range(3): if joysticks[i].state_id != current_state_ids[i]: current_state_ids[i] = joysticks[i].state_id seqs[i].publish(axes=joysticks[i].axis_states, buttons=joysticks[i].button_states)
def __init__(self, scenario, traces, shiftX, shiftY): ############################################################# if not scenario: print "Error: Missing scenario file" print scenario exit(1) print "Reading scenario from ", scenario self.configureScenario(scenario) #self.x_shift = rospy.get_param("~x_shift", 0.0) #self.y_shift = rospy.get_param("~y_shift", 0.0) self.x_shift = float(shiftX) self.y_shift = float(shiftY) self.ticks_since_start = 0 self.rate = 1 self.wait_to_initial_wp = 1 #traces = rospy.get_param("~bm_traces", None) if not traces: print "Error: Missing trace file" exit(1) print "reading traces from", traces self.readTraces(traces) self.lc = lcm.LCM("udpm://239.255.76.67:7667?ttl=1")
def __init__(self, comPort="", baudRate=57600, backChannel="Klima", withCrc=cnet_crc_constants_t.noCRC, timeout=1000): if comPort != "": self.interface = serial.Serial(comPort, 57600, timeout=3) else: self.interface = backChannel self.lc = lcm.LCM("udpm://239.255.76.67:7667?ttl=1") self.subscription = self.lc.subscribe(backChannel, self.answer_handler) if withCrc == True: self.crc = cnet_crc_constants_t.CRC_xmodem else: self.crc = cnet_crc_constants_t.noCRC self.crc = withCrc self.backChannel = backChannel self.timeout = timeout self.gotAnswer = False self.subscription = None
def publisher(side): """Main loop which requests new commands and publish them on the SModelRobotOutput topic.""" command_topic = "ROBOTIQ_" + side.upper() + "_COMMAND" lc = lcm.LCM() try: while True: command = genCommand(askForCommand()) if command: command.utime = (time() * 1000000) lc.publish(command_topic, command.encode()) else: print "ERROR: bad command" sleep(0.1) except KeyboardInterrupt: pass
def main(): keyboard = KeyboardManager() lc = lcm.LCM() cassie_blue = (6, 61, 128) white = (255, 255, 255) pygame.display.set_caption('Cassie Virtual Radio Controller') keyboard.screen.fill(cassie_blue) fnt = pygame.font.Font('freesansbold.ttf', 32) while True: # Get any keypresses keyboard.event_callback() # Update display screen display_text1 = 'Sagittal vel: ' + '%.2f'%(keyboard.vel[0]) display_text2 = 'Coronal Vel: ' + '%.2f'%(keyboard.vel[1]) text1 = fnt.render(display_text1, True, white, cassie_blue) text2 = fnt.render(display_text2, True, white, cassie_blue) text_rect1 = text1.get_rect() text_rect2 = text2.get_rect() text_rect1.center = (200, 150) text_rect2.center = (200, 250) keyboard.screen.fill(cassie_blue) keyboard.screen.blit(text1, text_rect1) keyboard.screen.blit(text2, text_rect2) # Send LCM message cassie_out_msg = dairlib.lcmt_cassie_out() cassie_out_msg.pelvis.radio.channel[0] = keyboard.vel[0] + keyboard.trim_x cassie_out_msg.pelvis.radio.channel[1] = keyboard.vel[1] + keyboard.trim_y cassie_out_msg.pelvis.radio.channel[3] = 0 lc.publish("CASSIE_OUTPUT_ECHO", cassie_out_msg.encode()) time.sleep(0.05) pygame.display.update()
def __init__(self, rexarm, planner): self.rexarm = rexarm self.tp = planner self.tags = [] self.status_message = "State: Idle" self.current_state = "idle" self.image = None self.lc = lcm.LCM() lcmSLAMPoseSub = self.lc.subscribe("SLAM_POSE", self.slampose_feedback_handler) lcmSLAMPoseSub.set_queue_capacity(1) lcmMbotStatusSub = self.lc.subscribe("MBOT_STATUS", self.mbotstatus_feedback_handler) # TODO: Add more variables here, such as RBG/HSV image here. self.current_step = 0 self.path = [] self.start_time = 0 self.duration = 0 self.slam_pose = None rotation_matrix = [[ 0.99995118, 0.00709628, -0.00687564], [-0.00444373, -0.29853831, -0.95438731], [-0.00882524, 0.95437127, -0.2984922 ]] tvec = [[-0.00106227],[ 0.08470473],[-0.02910629]] # extrinsic_mtx translates from points in camera frame to world frame self.extrinsic_mtx = np.linalg.inv(rot_tran_to_homo(rotation_matrix, tvec)) self.intrinsic_mtx = cameraMatrix = np.array([[596.13380911, 0, 322.69869837], [0, 598.59497209, 232.09155051], [0, 0, 1 ]]) self.recent_color = None self.mbot_status = mbot_status_t.STATUS_COMPLETE self.pickup_1x1_block = pickup_1x1_block(self) self.pickup_corner_block = pickup_corner_block(self) self.travel_square = travel_square(self) self.spin_state = spin_state(self) self.pickup_3x1_block = pickup_3x1_block(self, travel_square) self.go_to_garbage = go_to_garbage(self, travel_square)
def Main(): channel = 'WAMV.RELAY_CONTROL' print('ACFR USYD dS2824 Relay TESTER started for driver LCM channel: {}'.format(channel)) if len(sys.argv) < 4: print('Usage: python relay_tester.py <R/O> <relay number> <0/1>') print(' e.g. python relay_tester.py R 8 1 (to turn relay 8 on)') print(' python relay_tester.py O 5 0 (to turn i/o 5 off)') print(' python relay_tester.py D 12 1000 (to turn relay 12 on for 1000 ms))\n') sys.exit() # Setup LCM lc = lcm.LCM() msg = relay_command_t() if str(sys.argv[1]) == 'R': msg.relay_number = int(sys.argv[2]) msg.relay_request = int(sys.argv[3]) msg.relay_off_delay = 0 msg.io_number = 0 msg.io_request = 0 elif str(sys.argv[1]) == 'O': msg.io_number = int(sys.argv[2]) msg.io_request = int(sys.argv[3]) msg.relay_off_delay = 0 msg.relay_number = 0 msg.relay_request = 0 elif str(sys.argv[1]) == 'D': msg.relay_number = int(sys.argv[2]) msg.relay_request = 1 msg.relay_off_delay = int(sys.argv[3]) msg.io_number = 0 msg.io_request = 0 msg.utime = long(time.time())*1000000 lc.publish(channel, msg.encode())
def send_robots(ids, coordinates, ori, channel, timestamp): for i in range(len(ids)): robotid = ids[i] x, y = coordinates[i] """ --- no z --- """ o = ori[i] channel = options.channel lc = lcm.LCM("udpm://239.255.76.67:7667?ttl=1") msg = waypoint_list() msg.timestamp = float(timestamp) * 1e3 msg.robotid = robotid msg.n = 1 wp = waypoint() wp.timestamp = float(timestamp) * 1e3 """ in mm """ wp.position = [x * 1000, y * 1000, -1] wp.orientation = [o, 0, 0, 0] wps = [wp] msg.waypoints = wps lc.publish(channel, msg.encode())
def main(): lc = lcm.LCM('udpm://239.255.76.67:7667?ttl=1') parser = argparse.ArgumentParser() parser.add_argument('--local-port', type=int, action='store') parser.add_argument('--remote-port', type=int, action='store') parser.add_argument('--remote-address', type=str, action='store') parser.add_argument('--number', type=int, action='store') args = parser.parse_args() vals = [args.remote_address, args.remote_port, args.local_port] if any(vals) and not all(vals): print('Missing an argument') print('Should have remote-address, local-address, and local-port') print('Alternatively, only pass number') return if args.number is not None: args.local_port = local_base_port + args.number args.remote_port = remote_base_port + args.number args.remote_address = remote_base_address.format(args.number) bridge = PiEMOSBridge((args.remote_address, args.remote_port), args.number, lc) bridge.start() piemos_receiver = PiEMOSReceiver(lc, ('', args.local_port), args.number).serve_forever()
def handle_thread(self): self.channel = "NETWORK_CASSIE_STATE_DISPATCHER" self.lcm = lcm.LCM() subscription = self.lcm.subscribe(self.channel, self.state_handler) subscription.set_queue_capacity(1) # Create the plant (TODO: URDF name a JSON option) builder = pydrake.systems.framework.DiagramBuilder() self.plant, scene_graph = \ pydrake.multibody.plant.AddMultibodyPlantSceneGraph(builder, 0) pydrake.multibody.parsing.Parser(self.plant).AddModelFromFile( FindResourceOrThrow("examples/Cassie/urdf/cassie_v2.urdf")) # Fixed-base model (weld-body, or null, a JSON option) self.plant.WeldFrames(self.plant.world_frame(), self.plant.GetFrameByName("pelvis"), RigidTransform.Identity()) self.plant.Finalize() self.context = self.plant.CreateDefaultContext() print('Starting to handle LCM messages') while True: self.lcm.handle_timeout(100)
def main(): lc = lcm.LCM() sample_vis = SamplingVis() subscription = lc.subscribe("WORKSPACE", sample_vis.workspace_size_handler) subscription = lc.subscribe("REGION", sample_vis.region_handler) subscription = lc.subscribe("OBSTACLE", sample_vis.obstacle_handler) # subscription = lc.subscribe("SAMPLE", sample_vis.sampling_node_handler) subscription = lc.subscribe("PATH", sample_vis.path_handler) subscription = lc.subscribe("DRAW_SAMPLE", sample_vis.samples_draw) try: while True: lc.handle() except KeyboardInterrupt: # print 'Resuming...' pass # continue # print("######") lc.unsubscribe(subscription)
def __init__(self, input_method, lcm_tag, joy_name): print 'Initializing...' pygame.init() self.screen = pygame.display.set_mode((300, 70)) pygame.display.set_caption(lcm_tag) self.font = pygame.font.SysFont('Courier', 20) if input_method == 'keyboard': self.event_processor = KeyboardEventProcessor() print bcolors.OKBLUE + '--- Keyboard Control Instruction --- '\ + bcolors.ENDC print 'To increase the throttle/brake: press and hold the Up/Down'\ + ' Arrow' print 'To decrease the throttle/brake: release the Up/Down Arrow' print 'To keep the the current throttle/brake: press the Space Bar' print 'To increase left/right steering: press the Left/Right Arrow' print bcolors.OKBLUE + '------------------------------------ ' \ + bcolors.ENDC else: self.event_processor = JoystickEventProcessor(joy_name) self.last_value = SteeringThrottleBrake(0, 0, 0) self.lc = lcm.LCM() self.lcm_tag = lcm_tag print 'Ready'
def init_globals(): global lc, name, pub, lcm_sub, lcm_channel, TYPE, module_type, id lc = lcm.LCM("udpm://224.1.1.1:5007?ttl=2") name = gethostname() # lcm_sub = lc.subscribe(name, udp_callback) # if 'tb' in name: topic = rospy.get_param('~topic') lcm_channel = rospy.get_param('~lcm_channel', topic) msg_package = rospy.get_param('~msg_package') msg_name = rospy.get_param('~msg_name') module_type = rospy.get_param('~module_type') module = importlib.import_module(msg_package) TYPE = getattr(module, msg_name) id = rospy.get_param('~id', 'robot_id') if module_type in ['receiver', 'transceiver']: lcm_sub = lc.subscribe(lcm_channel, udp_callback) pub = rospy.Publisher(topic, TYPE, queue_size=1) if module_type in ['sender', 'transceiver']: rospy.Subscriber(topic, TYPE, handle_msg)
def __init__(self, master): # 目前仅用到rospy的time rospy.init_node('my_monitor', anonymous=True, log_level=rospy.INFO, disable_signals=True) self.root = master textLabel = Tkinter.Label(master, text='Topological Map') textLabel.pack() imageFrame = Tkinter.Frame(master, relief=Tkinter.RAISED, borderwidth=1) imageFrame.pack(side=Tkinter.TOP) self.mapImage = Image.open(mapImage_filename) mapPhoto = ImageTk.PhotoImage(self.mapImage) self.imageLabel = Tkinter.Label(imageFrame, image=mapPhoto) self.imageLabel.image = mapPhoto # keep a reference! self.imageLabel.pack() buttonFrame = Tkinter.Frame(master) buttonFrame.pack(side=Tkinter.BOTTOM) self.startButton = Tkinter.Button(buttonFrame, text="Start", command=self.send_start) self.startButton.pack(side=Tkinter.LEFT, padx=10, pady=10) self.stopButton = Tkinter.Button(buttonFrame, text="Stop", command=self.send_stop) self.stopButton.pack(side=Tkinter.RIGHT, padx=10, pady=10) self.lc = lcm.LCM() self.update_image() # 更新机器人的位置信息,并在界面上显示
def __init__(self): self.rate = rospy.Rate(125) self.robot_state = JointState() self.pub_joint_state = rospy.Publisher('/joint_states', JointState, queue_size=1) self.joint_names = [] self.joint_positions = [] self.joint_velocities = [] self.joint_efforts = [] self.joint_idx = {} self.lc = lcm.LCM() self.lc.subscribe("IIWA_STATUS", self.onIiwaStatus) #gripper_sub = self.lc.subscribe("command_topic", self.gripper_sub) # self.base_names = ['base_x', 'base_y', 'base_theta'] self.iiwa_joint_names = [ 'iiwa_joint_1', 'iiwa_joint_2', 'iiwa_joint_3', 'iiwa_joint_4', 'iiwa_joint_5', 'iiwa_joint_6', 'iiwa_joint_7' ] #self.gripper_names = ['robotiq_hand'] # !! Jay, maybe want the "actual" name...not that it matters... self.joints = [] # self.joints.extend(self.base_names) self.joints.extend(self.iiwa_joint_names) #self.joints.extend(self.gripper_names) idx = 0 for j in xrange(0, len(self.joints)): self.joint_names.append(str(self.joints[j])) self.joint_positions.append(0.0) self.joint_velocities.append(0.0) self.joint_efforts.append(0.0) self.joint_idx[str(self.joints[j])] = idx idx = idx + 1
def __init__(self, lcm_obj=None): """Initialize a new Sheriff object. \param lcm_obj the LCM object to use for communication. If None, then the sheriff creates a new lcm.LCM() instance and spawns a thread that endlessly calls LCM.handle(). If this is passed in by the user, then the user is expected to call LCM.handle(). """ self._lcm = lcm_obj self._lcm_thread = None self._lcm_thread_obj = None if self._lcm is None: self._lcm = lcm.LCM() self._lcm_thread_obj = threading.Thread(target=self._lcm_thread) self._lcm.subscribe("PM_INFO", self._on_pmd_info) self._lcm.subscribe("PM_ORDERS", self._on_pmd_orders) self._deputies = {} self._is_observer = False self._id = platform.node() + ":" + str(os.getpid()) + \ ":" + str(_now_utime()) # publish a discovery message to query for existing deputies discover_msg = discovery_t() discover_msg.utime = _now_utime() discover_msg.transmitter_id = self._id discover_msg.nonce = 0 self._lcm.publish("PM_DISCOVER", discover_msg.encode()) # Create a worker thread for periodically publishing orders self._worker_thread_obj = threading.Thread(target=self._worker_thread) self._exiting = False self._lock = threading.Lock() self._condvar = threading.Condition(self._lock) self._worker_thread_obj.start() self._listeners = [] self._queued_events = []
def test_handle_and_publish(self): """Worker thread calls LCM.handle(), while main thread calls LCM.publish() """ lcm_obj = lcm.LCM("memq://") def on_msg(channel, data): on_msg.msg_handled = True on_msg.msg_handled = False lcm_obj.subscribe("channel", on_msg) def thread_func(): lcm_obj.handle() worker = threading.Thread(target=thread_func) worker.start() time.sleep(0.1) lcm_obj.publish("channel", "") worker.join() self.assertTrue(on_msg.msg_handled)
def __init__(self): self.lcm = lcm.LCM("udpm://?ttl=1") self.lcm.subscribe("PHONE_THUMB0", self.on_phone_thumb0) self.lcm.subscribe("PHONE_THUMB1", self.on_phone_thumb1) self.lcm.subscribe("PHONE_THUMB2", self.on_phone_thumb2) self.lcm.subscribe("PHONE_THUMB3", self.on_phone_thumb3) self.lcm.subscribe("PHONE_PRINT", self.on_phone_print) self.lcm.subscribe("TABLET_SCRSHOT_REQUEST", self.on_scrshot_request) self.lcm.subscribe("CLASS_STATE", self.on_class_state) self.lcm.subscribe("SYSTEM_INFO", self.on_system_info) self.lcm.subscribe("UI_MAP", self.on_ui_map) self.lcm.subscribe("LOGGER_INFO", self.on_logger_info) self.lcm.subscribe("IMAGE_ANNOUNCE", self.on_announce) self.lcm.subscribe("FEATURES_ANNOUNCE", self.on_announce) self.lcm.subscribe("MAP_LIST", self.on_map_list) self.lcm.subscribe("FUTURE_DIRECTION", self.on_map_list) print "starting phoned..." self.server = bluetooth.BluetoothSocket() self.server.bind(("", 17)) self.server.listen(1) self.client = None self.client_ios = 0 self.verbose = True self.thumb_to_send = [None, None, None, None] self.thumb_dirty = [False, False, False, False] # bluetooth message handling variables self._data_buf = None self._data_channel = "" self._recv_mode = "channel" self._datalen_buf = "" self._datalen = 0 self._data_received = 0
def __init__(self, rndf_fname=None): threading.Thread.__init__(self) self.lc = lcm.LCM() #load the model if rndf_fname != None: self.set_rndf(rndf_fname) else: self.rndf = None self.trans_xyz = (0, 0, 0) self.trans_theta = 0 self.curr_location = None self.curr_orientation = None self.lc.subscribe("PALLET_LIST", self.on_pallet_msg) self.lc.subscribe("POSE", self.on_pose_msg) self.lc.subscribe("GPS_TO_LOCAL", self.on_transform_msg) self.lc.subscribe("OBJECT_LIST", self.on_objects_msg) self.reset() self.lock = threading.Lock()
import select import lcm from exlcm import example_t def my_handler(channel, data): msg = example_t.decode(data) print("Received message on channel \"%s\"" % channel) print(" timestamp = %s" % str(msg.timestamp)) print(" position = %s" % str(msg.position)) print(" orientation = %s" % str(msg.orientation)) print(" ranges: %s" % str(msg.ranges)) print(" name = '%s'" % msg.name) print(" enabled = %s" % str(msg.enabled)) print("") lc = lcm.LCM() lc.subscribe("EXAMPLE", my_handler) try: timeout = 1.5 # amount of time to wait, in seconds while True: rfds, wfds, efds = select.select([lc.fileno()], [], [], timeout) if rfds: lc.handle() else: print("Waiting for message...") except KeyboardInterrupt: pass
def publish_driving_command(lcm_tag, throttle, steering_angle): lc = lcm.LCM() last_msg = make_driving_command(throttle, steering_angle) lc.publish(lcm_tag, last_msg.encode())
def publish_driving_command(lcm_tag, throttle, steering_angle): lc = lcm.LCM() last_msg = lcm_msg() last_msg.throttle = throttle last_msg.steering_angle = steering_angle lc.publish(lcm_tag, last_msg.encode())
def main(): lc = lcm.LCM() num_cases = 100 case_idx = 0 true_graph = Grid(True, ROIs, nz_ig) for i in range(num_cases + 1): Graph_data = str(i) + "GraphData" subscription = lc.subscribe(Graph_data, true_graph.graph_data_handler) msg_flag = prediction_data() bayes_data_ = [] ave_opt = 0 ave_relative_err = 0 ave_iteration = 0 ave_samples = 0 correct_case = 0 try: while True: lc.handle() data = [] pred_graph = Grid(False, ROIs, nz_ig) pred_graph.duplicate_true_graph(true_graph) pred_graph.adjacent_prob(true_graph) pred_graph.training_samples(samples_idx, true_graph) pred_graph.complexity_prob() bayes_iter = 0 while bayes_iter < BayesianMaxIter: bayes_iter = bayes_iter + 1 gpr = pred_graph.gp(true_graph, samples_idx) true_graph.calculate_ave_L2_norm() if true_graph.ave_L2_norm_ < TOL_AVE_L2: print( "==============REACH THE L2 TOLLERANCE===============") break next_sample_x = pred_graph.propose_location( pred_graph.expected_improvement) next_sample_x = [round(i[0], 2) for i in next_sample_x] print( "======================================================================" ) print( "The next X sample selected by Bayesian Opt is {}".format( next_sample_x)) next_sample_y = pred_graph.locate_vertex( next_sample_x, true_graph) print("The corresponding ig for the next sample is {}".format( next_sample_y)) pred_graph.training_x_.append(next_sample_x) pred_graph.training_y_.append(next_sample_y) true_graph.maximum_IG() pred_graph.maximum_IG() pred_graph.bayesian_iter_ = bayes_iter pred_graph.bayesian_samples_ = bayes_iter + len(samples_idx) pred_graph.bayesian_opt_ = round(pred_graph.max_ig_, 3) / round( true_graph.max_ig_, 3) pred_graph.bayesian_relative_err_ = abs( true_graph.max_ig_ - pred_graph.max_ig_) / true_graph.max_ig_ print( "===========================================================================" ) print( "===========================================================================" ) print( "===========================================================================" ) print("Bayesian Opt terminates at T = {}".format( pred_graph.bayesian_iter_)) print("Required samples number is {}".format( pred_graph.bayesian_samples_)) print( "The maximum IG for true graph is {}, the maximum IG for predicted graph is {}" .format(true_graph.max_ig_, pred_graph.max_ig_)) print("The maximum IG vertex for true graph is {}".format( true_graph.max_ig_vertex_)) print("The maximum IG vertex for predicted graph is {}".format( pred_graph.max_ig_vertex_)) print("The optimality for the Bayesian optimization is {}".format( pred_graph.bayesian_opt_)) print( "============================================================================" ) print( "============================================================================" ) print( "============================================================================" ) msg_flag.bayesian_opt_flag = True lc.publish("BayesianChannel", msg_flag.encode()) print("Publish the msg") data.append(case_idx) data.append(true_graph.max_ig_) data.append(pred_graph.max_ig_) data.append(pred_graph.bayesian_opt_) ave_opt = ave_opt + pred_graph.bayesian_opt_ ave_relative_err = ave_relative_err + pred_graph.bayesian_relative_err_ ave_iteration = ave_iteration + pred_graph.bayesian_iter_ ave_samples = ave_samples + pred_graph.bayesian_samples_ data.append(pred_graph.bayesian_iter_) data.append(pred_graph.bayesian_samples_) data.append(true_graph.max_ig_vertex_) data.append(pred_graph.max_ig_vertex_) data.append(pred_graph.bayesian_relative_err_) bayes_data_.append(data) true_vt = true_graph.max_ig_vertex_ if true_vt == pred_graph.max_ig_vertex_ or abs( pred_graph.vertex_[true_vt].ig_ - true_graph.max_ig_) <= 10e-2: correct_case = correct_case + 1 case_idx = case_idx + 1 if case_idx >= num_cases: break print("The average optimality is {}".format(ave_opt / num_cases)) print("The average relative error is {}".format(ave_relative_err / num_cases)) print("The average iteration is {}".format(ave_iteration / num_cases)) print("The average samples is {}".format(ave_samples / num_cases)) print("Correct cases are {}".format(correct_case)) print("Start to write into cvs") with open('bayes_opt_data.cvs', mode='w') as csv_file: fieldnames = [ '#Case', 'TrueMAXIG', 'PredictedMAXIG', 'Optimality', 'Iteration', '#samples', 'TrueMAXVert', 'PredictMAXVert', 'RelativeError' ] writer = csv.DictWriter(csv_file, fieldnames=fieldnames) writer.writeheader() for case in bayes_data_: writer.writerow({ '#Case': case[0], 'TrueMAXIG': case[1], 'PredictedMAXIG': case[2], 'Optimality': case[3], 'Iteration': case[4], '#samples': case[5], 'TrueMAXVert': case[6], 'PredictMAXVert': case[7], 'RelativeError': case[8] }) except KeyboardInterrupt: pass lc.unsubscribe(subscription)
args = sys.argv if len(args) < 1+4 or len(args) > 1+5: print(USAGE) sys.exit(1) elif len(args) == 1+5: exec 'import ' + sys.argv[5] out_filename = sys.argv[1] listen_channel = sys.argv[2] lcmtype_str = sys.argv[3] field_expr_str = sys.argv[4] lc = lcm.LCM('udpm://239.255.76.67:7667?ttl=1') out_file = open(out_filename,'w') print 'LCM Writer Setup Success. Writing to file ' + out_filename + '...' PRINT_LIMIT_SECONDS = 0.1 last_time = time.time() try: def handler(channel, data): global last_time cur_time = time.time() if cur_time - last_time > PRINT_LIMIT_SECONDS: print('Received..')
def create_lcm(): return lcm.LCM("udpm://239.255.76.67:62237?ttl=0")
""" import tornado.ioloop import tornado.web import tornado.websocket import tornado.httpserver import json import lcm import threading import LCMNode ### SETTINGS import settings import forseti2 LCM_URI = settings.LCM_URI TYPES_ROOT = forseti2 ### END SETTINGS lc = lcm.LCM(LCM_URI) class BridgeNode(LCMNode.LCMNode): def __init__(self, lc): self.lc = lc self.start_thread() class WSHandler(tornado.websocket.WebSocketHandler): def check_origin(self, origin): return True def open(self): """ Called when a client opens the websocket