def load_click(self): filename = QtGui.QFileDialog.getOpenFileName(self, "Select a file with parameters", "supervisors", "XML files (*.xml)") if filename is not None: reader = XMLReader(filename, 'parameters') cache = self.contents.get_xmlstruct() try: self.contents.use_xmlstruct(reader.read()) except Exception as e: QtGui.QMessageBox.critical(self,"Loading parameters failed",str(e)) self.contents.use_xmlstruct(cache)
def get_obstacles(file): """ get obstacle's coordinates from world file file: the world file """ xml = XMLReader(file, 'parameters') vertexs_list = [] for item in xml.read(): points = [] temp = [] if item[0] == 'obstacle': pose = item[1][0] geometry = item[1][1] y, x, theta = pose[1][0][1], pose[1][1][1], pose[1][2][1] for point in geometry[1]: point_y, point_x = point[1][0][1], point[1][1][1] points.append([point_x, point_y]) origin = array([x,y]) origin = origin.reshape(2, 1) A = array([[cos(theta), -sin(theta)], # rotation matrix [sin(theta), cos(theta)]]) #print A.shape, 'A' for x0 in points: x0 = array(x0) #print x0.shape x0 = x0.reshape(2,1) #print origin vertexs = (dot(A, x0) + origin) #print vertexs, round(vertexs[0],1),'\n' temp.append((round(vertexs[0],1), round(vertexs[1],1))) #print temp, 'temp' vertexs_list.append(temp) return vertexs_list # pose is the bottom left corner # origin = origin.reshape(2, 1) # x0 = x0.reshape(2, 1) # x0 = x0 - origin # assingment operator (-=) would modify original x0 # A = array([[cos(theta), -sin(theta)], # rotation matrix # [sin(theta), cos(theta)]]) # return (dot(A, x0) + origin).ravel() # return (dot(A, x0) + origin).ravel()
def get_obstacles(file): xml = XMLReader(file, 'parameters') vertexs_list = [] for item in xml.read(): points = [] temp = [] if item[0] == 'obstacle': pose = item[1][0] geometry = item[1][1] y, x, theta = pose[1][0][1], pose[1][1][1], pose[1][2][1] for point in geometry[1]: point_y, point_x = point[1][0][1], point[1][1][1] points.append([point_x, point_y]) origin = array([x, y]) origin = origin.reshape(2, 1) A = array([ [cos(theta), -sin(theta)], # rotation matrix [sin(theta), cos(theta)] ]) #print A.shape, 'A' for x0 in points: x0 = array(x0) #print x0.shape x0 = x0.reshape(2, 1) #print origin vertexs = (dot(A, x0) + origin) #print vertexs, round(vertexs[0],1),'\n' temp.append((round(vertexs[0], 1), round(vertexs[1], 1))) #print temp, 'temp' vertexs_list.append(temp) return vertexs_list # pose is the bottom left corner # origin = origin.reshape(2, 1) # x0 = x0.reshape(2, 1) # x0 = x0 - origin # assingment operator (-=) would modify original x0 # A = array([[cos(theta), -sin(theta)], # rotation matrix # [sin(theta), cos(theta)]]) # return (dot(A, x0) + origin).ravel() # return (dot(A, x0) + origin).ravel()
def test_parse_parameters_legal(self): parameters = XMLReader("../testfiles/parameters.xml", "parameters").read() assert parameters == { 'pid': { 'goal': { 'y': 10.0, 'x': 11.0 }, 'angle': { 'theta': 0.7854 }, 'velocity': { 'v': 0.1 }, ('gains', 'soft'): { 'ki': 0.1, 'kp': 5.0, 'kd': 0.01 }, ('gains', 'hard'): { 'ki': 0.1, 'kp': 5.0, 'kd': 0.01 } } }
def start_test(self, challenge): vals = self.parseChallenge(challenge, {'dir': str}) if 'v' not in vals or 'dir' not in vals or 'theta' not in vals: raise CourseraException( "Unknown challenge format. Please contact developers for assistance." ) self.new_lap = True self.lap_count = 1 self.testsuite.gui.start_testing() self.testsuite.gui.register_event_handler(self) from xmlreader import XMLReader world = XMLReader("worlds/week6_test_{}.xml".format(vals['dir']), 'simulation').read() i = 0 while world[i].type != 'robot': i += 1 world[i].robot.pose.theta = vals['theta'] world[ i].supervisor.options = '{{"velocity":{}, "direction":"{}"}}'.format( vals['v'], vals['dir']) self.testsuite.gui.dockmanager.clear() self.testsuite.gui.run_simulator_command('load_world', world) self.testsuite.gui.run_simulator_command('add_plotable', self.dst20x) self.testsuite.gui.run_simulator_command('add_plotable', self.dst20y) self.testsuite.gui.run_simulation()
def load_click(self): filename = QtGui.QFileDialog.getOpenFileName( self, "Select a file with parameters", "supervisors", "XML files (*.xml)") if filename is not None: reader = XMLReader(filename, 'parameters') cache = self.contents.get_xmlstruct() try: self.contents.use_xmlstruct(reader.read()) except Exception as e: #QtGui.QMessageBox.critical(self,"Loading parameters failed",str(e)) QtGui.QMessageBox.critical( self, "Loading parameters failed", "\n".join(format_exception(*sys.exc_info()))) self.contents.use_xmlstruct(cache)
def run(self): """ Its a thread main function. Mainly, compares XML provided files. Execution is synchronised using two semaphores. """ result = False try: logging.debug("Comparing => %s" %(self.name)) with Dispatcher.__semaphore: result = XMLReader.compare(self.expectfile, self.resultfile) except: logging.debug("Unknown exception occured") finally: status = "[Pass]" if (result == True) else "[Fail]" output = "{0:80} {1}".format(self.relfilename, status) logging.info("%s" %(output)) # synchronisation locking with Dispatcher.__lock: if (result == True): Dispatcher.__pass = Dispatcher.__pass + 1 Dispatcher.__total = Dispatcher.__total + 1
def test_validate_parameters_saved(self): try: import lxml except ImportError: return True assert XMLReader("../testfiles/parameters_saved.xml", "parameters").validate("../schemas/pid.rng") == True
def load(cls, filename, format): """ It loads and validates user settings. Moreover, initialises file logger. """ try: reader = XMLReader(filename) #regression loglevel = reader.find(r'loglevel') cls.expecteddir = reader.find(r'expected') cls.sourcedir = reader.find(r'source') cls.resultdir = reader.find(r'result') cls.logdir = reader.find(r'log') # directories must exist cls.path_exists(cls.expecteddir) cls.path_exists(cls.sourcedir) cls.path_exists(cls.logdir) #cls.path_exists(cls.resultdir) #sybase cls.semaphore = int(reader.find(r'semaphore')) cls.isql = reader.find(r'dbisql') cls.uid = reader.find(r'uid') cls.pwd = reader.find(r'pwd') cls.dbf = reader.find(r'dbf') cls.file_exists(cls.isql) cls.file_exists(cls.dbf) cls.exe = cls.isql + str(r' -c "UID=') + cls.uid \ + str(r';PWD=') + cls.pwd + str(r';DBF=') + cls.dbf + str(r'" ') cls.level = getattr(logging, loglevel.upper()) if not isinstance(cls.level, int): raise Exception("Invalid log value") fh = logging.FileHandler(str(r"{0}\regression.log".format(cls.logdir)), mode='w') fh.setLevel(cls.level) formatter = logging.Formatter(fmt=format[0], datefmt=format[1]) fh.setFormatter(formatter) logging.getLogger('').addHandler(fh) except Exception:# as e: logging.debug("Exception occured while reading configuration") raise
def test_baseline(): # TNG_set = fetch_20newsgroups(subset='all', remove=('headers', 'footers', 'quotes'), shuffle=True, # random_state=42) # ba = BaselineApproach(TNG_set['data'][:144]) # my_file = read_file('..\\data\\sample_texts', 'sample_text.txt') # keyphrases = ba.returnSolutionforDoc(my_file) # keyphrases = ba.returnSolution() # print('Keyphrases selected from sample text: ', keyphrases) xmlReader = XMLReader('../data/SemEval-2010', True) dswa = xmlReader.readXML() un_xml = BaselineApproach(dswa) solution_xml = un_xml.returnSolution() stats = evaluate_dataset(readJSONSolution(False), solution_xml) print(solution_xml)
def test_validate_parameters_no_pid_goal(self): try: import lxml except ImportError: return True assert XMLReader("../testfiles/no_pid_goal.xml", "parameters").validate("../schemas/pid.rng") == False
def test_validate_simulation_too_few_obstacle_points(self): try: import lxml except ImportError: return True assert XMLReader( "../testfiles/too_few_points.xml", "simulation").validate("../schemas/simulation.rng") == False
def test_validate_simulation_missing_obstacle_coordinate(self): try: import lxml except ImportError: return True assert XMLReader( "../testfiles/missing_obstacle_coord.xml", "simulation").validate("../schemas/simulation.rng") == False
def test_validate_simulation_no_obstacle_geometry(self): try: import lxml except ImportError: return True assert XMLReader( "../testfiles/no_obstacle_geometry.xml", "simulation").validate("../schemas/simulation.rng") == False
def test_validate_simulation_no_robot_supervisor(self): try: import lxml except ImportError: return True assert XMLReader( "../testfiles/no_robot_supervisor.xml", "simulation").validate("../schemas/simulation.rng") == False
def test_validate_simulation_default(self): try: import lxml except ImportError: return True assert XMLReader( "../testfiles/settings.xml", "simulation").validate("../schemas/simulation.rng") == True
def read_config(self, filename): '''Load in the objects from the world XML file ''' self.log('Loading new world') try: world = XMLReader(filename, 'simulation').read() except Exception as e: raise Exception('[Simulator.read_config] Failed to parse ' + filename \ + ': ' + str(e)) else: self.load_world(world)
def test_parse_simulation_legal(self): objects = XMLReader("../testfiles/settings.xml", "simulation").read() assert objects[0] == \ ('robot', 'Khepera3', 'khepera3.K3Supervisor', (1.0, 1.0, 1.5708), 0xFFAACC) assert objects[1] == \ ('obstacle', (1.0, 1.2, 0.0), [(0.0, 0.0), (0.3, 0.0), (0.3, 0.3), (0.0, 0.3)], None) assert objects[2] == \ ('obstacle', (-0.5, 0.0, 0.7854), [(0.0, 0.0), (0.3, 0.0), (0.3, 0.3), (0.0, 0.3)], None) assert objects[3] == \ ('obstacle', (0.65, 0.0, 0.7854), [(0.0, 0.0), (0.3, 0.0), (0.3, 0.3), (0.0, 0.3)], None) assert objects[4] == \ ('obstacle', (0.2, 0.8, 0.0), [(0.0, 0.0), (0.3, 0.0), (0.3, 0.3), (0.0, 0.3)], None) assert objects[5] == \ ('obstacle', (-1.0, -1.0, 0.0), [(0.0, 0.0), (1.5, 0.0), (1.5, 0.3), (0.0, 0.3)], None) assert objects[6] == \ ('obstacle', (-1.6, -1.5, 0.0), [(0.0, 0.0), (3.0, 0.0), (3.0, 0.1), (0.0, 0.1)], None) assert objects[7] == \ ('obstacle', (-1.5, -1.4, 1.5708), [(0.0, 0.0), (3.0, 0.0), (3.0, 0.1), (0.0, 0.1)], None) assert objects[8] == \ ('obstacle', (1.5, -1.5, 1.5708), [(0.0, 0.0), (3.0, 0.0), (3.0, 0.1), (0.0, 0.1)], None) assert objects[9] == \ ('obstacle', (-1.5, 1.5, 0.0), [(0.0, 0.0), (3.0, 0.0), (3.0, 0.1), (0.0, 0.1)], None)
def read_config(self, filename): '''Load in the objects from the world XML file ''' self.log('reading initial configuration') try: self.__world = XMLReader(filename, 'simulation').read() except Exception as e: raise Exception('[Simulator.read_config] Failed to parse ' + filename \ + ': ' + str(e)) else: self.__supervisor_param_cache = None self.__center_on_robot = False self.__construct_world()
def read_config(self, filename): '''Load in the objects from the world XML file ''' self.log('reading initial configuration') try: self.__world = XMLReader(filename, 'simulation').read() except Exception as e: raise Exception('[PCLoop.read_config] Failed to parse ' + filename \ + ': ' + str(e)) else: self.__supervisor_param_cache = None self.__center_on_robot = False if self.__robot is not None: r = self.__robot self.__robot = None del r del self.__supervisor self.__supervisor = None gc.collect(r) print(gc.get_referrers(r)) self.__construct_world()
def test_write_parameters_legal(self): parameters = {'pid': { 'goal': {'y': 10.0, 'x': 11.0}, 'angle': {'theta': 0.7854}, 'velocity': {'v': 0.1}, ('gains', 'soft'): {'ki': 0.1, 'kp': 5.0, 'kd': 0.01}, ('gains', 'hard'): {'ki': 0.1, 'kp': 5.0, 'kd': 0.01} } } file_ = "tmp_removeme.xml" try: XMLWriter(file_, "parameters", parameters).write() result = XMLReader(file_, "parameters").read() assert result == parameters finally: # If the file was created (it exists), delete it try: with open(file_) as f: f.close() unlink(file_) except IOError: pass
def test_parse_simulation_no_robot_pose(self): parser = XMLReader("../testfiles/no_robot_pose.xml", "simulation") self.assertRaises(Exception, parser.read)
def test_parse_simulation_bad_robot_coordinate(self): parser = XMLReader("../testfiles/bad_robot_coord.xml", "simulation") self.assertRaises(Exception, parser.read)
def test_parse_simulation_missing_obstacle_coordinate(self): parser = XMLReader("../testfiles/missing_obstacle_coord.xml", "simulation") self.assertRaises(Exception, parser.read)
def __init__(self, parent = None): """Creates a filter instance, allowing applications to set the parent on instantiation.""" XMLReader.__init__(self) self._parent = parent
def test_parse_simulation_too_few_obstacle_points(self): parser = XMLReader("../testfiles/too_few_points.xml", "simulation") self.assertRaises(Exception, parser.read)
def test_normal(self): self.assertTrue(XMLReader.compare(r'Expected/foo.xml', r'Expected/foo.xml')) self.assertFalse(XMLReader.compare(r'Expected/foo.xml', r'Expected/bar.xml')) self.assertFalse(XMLReader.compare(r'Expected/foo.xml', r'Expected/foo_rowdel.xml')) self.assertFalse(XMLReader.compare(r'Expected/bar.xml', r'Expected/bar_casechanged.xml'))
def test_invalid_file(self): self.assertRaises(IOError,XMLReader,'ABCTEMP.xml') self.assertRaises(AssertionError,XMLReader,'') self.assertFalse(XMLReader.compare('/C/.xml','')) self.assertFalse(XMLReader.compare('', '/C/.xml'))
def test_parse_simulation_no_obstacle_geometry(self): parser = XMLReader("../testfiles/no_obstacle_geometry.xml", "simulation") self.assertRaises(Exception, parser.read)