Exemple #1
0
    def loadSpecFile(self, spec_file):
        # Figure out where we should be looking for files, based on the spec file name & location
        self.project_root = os.path.abspath(os.path.dirname(spec_file))
        self.project_basename, ext = os.path.splitext(os.path.basename(spec_file))

        ### Load in the specification file
        if not self.silent:
            print "Loading specification file %s..." % spec_file
        spec_data = fileMethods.readFromFile(spec_file)

        if spec_data is None:
            if not self.silent:
                print "WARNING: Failed to load specification file"
            return None

        try:
            self.specText = "\n".join(spec_data["SPECIFICATION"]["Spec"])
        except KeyError:
            if not self.silent:
                print "WARNING: Specification text undefined"

        if "CompileOptions" in spec_data["SETTINGS"]:
            for l in spec_data["SETTINGS"]["CompileOptions"]:
                if ":" not in l:
                    continue

                k, v = l.split(":", 1)
                if k.strip().lower() == "parser":
                    self.compile_options[k.strip().lower()] = v.strip().lower()
                else:
                    # convert to boolean if not a parser type
                    self.compile_options[k.strip().lower()] = v.strip().lower() in ["true", "t", "1"]

        return spec_data
Exemple #2
0
    def loadSpecFile(self, spec_file):
        # Figure out where we should be looking for files, based on the spec file name & location
        self.project_root = os.path.abspath(os.path.dirname(spec_file))
        self.project_basename, ext = os.path.splitext(os.path.basename(spec_file))


        ### Load in the specification file
        if not self.silent: print "Loading specification file %s..." % spec_file
        spec_data = fileMethods.readFromFile(spec_file)

        if spec_data is None:
            if not self.silent: print "WARNING: Failed to load specification file"
            return None

        try:
            self.specText = '\n'.join(spec_data['SPECIFICATION']['Spec'])
        except KeyError:
            if not self.silent: print "WARNING: Specification text undefined"

        if 'CompileOptions' in spec_data['SETTINGS']:
            for l in spec_data['SETTINGS']['CompileOptions']:
                if ":" not in l:
                    continue

                k,v = l.split(":", 1)
                self.compile_options[k.strip().lower()] = (v.strip().lower() in ['true', 't', '1'])

        return spec_data
Exemple #3
0
    def loadSpecFile(self, spec_file):
        # Figure out where we should be looking for files, based on the spec file name & location
        self.project_root = os.path.abspath(os.path.dirname(spec_file))
        self.project_basename, ext = os.path.splitext(
            os.path.basename(spec_file))

        ### Load in the specification file
        if not self.silent:
            print "Loading specification file %s..." % spec_file
        spec_data = fileMethods.readFromFile(spec_file)

        if spec_data is None:
            if not self.silent:
                print "WARNING: Failed to load specification file"
            return None

        try:
            self.specText = '\n'.join(spec_data['SPECIFICATION']['Spec'])
        except KeyError:
            if not self.silent: print "WARNING: Specification text undefined"

        if 'CompileOptions' in spec_data['SETTINGS']:
            for l in spec_data['SETTINGS']['CompileOptions']:
                if ":" not in l:
                    continue

                k, v = l.split(":", 1)
                self.compile_options[k.strip().lower()] = (v.strip().lower()
                                                           in [
                                                               'true', 't', '1'
                                                           ])

        return spec_data
Exemple #4
0
    def loadSpecFile(self, spec_file):
        # Figure out where we should be looking for files, based on the spec file name & location
        self.project_root = os.path.abspath(os.path.dirname(spec_file))
        self.project_basename, ext = os.path.splitext(os.path.basename(spec_file))


        ### Load in the specification file
        logging.info("Loading specification file %s..." % spec_file)
        spec_data = fileMethods.readFromFile(spec_file)

        if spec_data is None:
            logging.warning("Failed to load specification file")
            return None

        try:
            self.specText = '\n'.join(spec_data['SPECIFICATION']['Spec'])
        except KeyError:
            logging.warning("Specification text undefined")

        if 'CompileOptions' in spec_data['SETTINGS']:
            for l in spec_data['SETTINGS']['CompileOptions']:
                if ":" not in l:
                    continue

                k,v = l.split(":", 1)
                if k.strip().lower() == "parser":
                    self.compile_options[k.strip().lower()] = v.strip().lower()
                else:
                    # convert to boolean if not a parser type
                    self.compile_options[k.strip().lower()] = (v.strip().lower() in ['true', 't', '1'])

        return spec_data
Exemple #5
0
    def loadSpecFile(self, spec_file):
        # Figure out where we should be looking for files, based on the spec file name & location
        self.project_root = os.path.abspath(os.path.dirname(spec_file))
        self.project_basename, ext = os.path.splitext(
            os.path.basename(spec_file))

        ### Load in the specification file
        logging.info("Loading specification file %s..." % spec_file)
        spec_data = fileMethods.readFromFile(spec_file)

        if spec_data is None:
            logging.warning("Failed to load specification file")
            return None

        try:
            self.specText = '\n'.join(spec_data['SPECIFICATION']['Spec'])
        except KeyError:
            logging.warning("Specification text undefined")

        if 'CompileOptions' in spec_data['SETTINGS']:
            for l in spec_data['SETTINGS']['CompileOptions']:
                if ":" not in l:
                    continue

                k, v = l.split(":", 1)
                if k.strip().lower() in ("parser", "synthesizer"):
                    self.compile_options[k.strip().lower()] = v.strip().lower()
                else:
                    # convert to boolean if not a parser type
                    self.compile_options[k.strip().lower()] = (
                        v.strip().lower() in ['true', 't', '1'])

        return spec_data
Exemple #6
0
    def loadSpecFile(self, spec_file):
        # Figure out where we should be looking for files, based on the spec file name & location
        self.project_root = os.path.abspath(os.path.dirname(spec_file))
        self.project_basename, ext = os.path.splitext(os.path.basename(spec_file)) 
        self.ltlmop_root = os.path.abspath(os.path.dirname(sys.argv[0]))

        ### Load in the specification file
        print "Loading specification file %s..." % spec_file
        spec_data = fileMethods.readFromFile(spec_file)   
        
        return spec_data
Exemple #7
0
    def readFile(self, filename):
        """
        For file format information, refer to writeFile() above.
        """

        if not os.path.exists(filename):
            return False

        data = fileMethods.readFromFile(filename)

        if data is None:
            return False

        try:
            self.background = data["Background"][0]
        except KeyError:
            self.background = "None"

        self.thumb = os.path.join(os.path.split(filename)[0],data["Thumbnail"][0])

        self.regions = []
        for region in data["Regions"]:
            regionData = region.split("\t");
            newRegion = Region()
            newRegion.setData(regionData, withAlignment=False)    
            newRegion.alignmentPoints = [False] * len([x for x in newRegion.getPoints()])
            self.regions.append(newRegion)

        # Make an empty adjacency matrix of size (# of regions) x (# of regions)
        self.transitions = [[[] for j in range(len(self.regions))] for i in range(len(self.regions))]
        for transition in data["Transitions"]:
            transData = transition.split("\t");
            region1 = self.indexOfRegionWithName(transData[0])
            region2 = self.indexOfRegionWithName(transData[1])
            faces = []
            for i in range(2, len(transData), 4):
                p1 = wx.Point(int(transData[i]), int(transData[i+1]))
                p2 = wx.Point(int(transData[i+2]), int(transData[i+3]))
                faces.append(tuple(sorted((p1, p2))))
                
            # During adjacency matrix reconstruction, we'll mirror over the diagonal
            self.transitions[region1][region2] = faces
            self.transitions[region2][region1] = faces

        if "CalibrationPoints" in data:
            for point in data["CalibrationPoints"]:
                [name, index] = point.split("\t")
                self.regions[self.indexOfRegionWithName(name)].alignmentPoints[int(index)] = True
            
        return True
Exemple #8
0
    def loadRobotFile(self,fileName):

        # Add extension to the name if there isn't one.
        if not fileName.endswith('.robot'):
            fileName = fileName+'.robot'

        if not self.silent: print "Loading robot file %s..." % fileName
        try:
            # try to load the robot file
            robot_data = fileMethods.readFromFile(fileName)
        except IOError:
            if not self.silent: print "ERROR: Cannot find robot file %s" % fileName
            return

        return self.loadRobotData(robot_data)
Exemple #9
0
    def fromFile(self, file_path, hsub = None):
        """
        Given a robot file, load the robot info in it
        The file_path needs to be the path starting from lib/
        """

        logging.debug("Loading robot file {!r}".format(os.path.basename(file_path).split('.')[0]))
        try:
            # try to load the robot file
            robot_data = fileMethods.readFromFile(file_path)
        except IOError:
            ht.LoadingError("Cannot load the information")
            self._setLoadFailureFlag()
        else:
            # now load the robot config from the dictionary data
            self.fromData(robot_data, hsub)
Exemple #10
0
    def extractJSONFromRegions(self, filename):
        """
        Turns a regions file into a straight JSON file
        """
        if not os.path.exists(filename):
            raise IOError("path does not exist")

        data = fileMethods.readFromFile(filename)

        if data is None:
            raise IOError("read from file failed")

        rdata = data["Regions"]

        try:
            rdata = json.loads("\n".join(rdata))
        except ValueError:
            raise ValueError("json failed to load")

        return rdata
Exemple #11
0
    def extractJSONFromRegions(self, filename):
        """
        Turns a regions file into a straight JSON file
        """
        if not os.path.exists(filename):
            raise IOError("path does not exist")

        data = fileMethods.readFromFile(filename)

        if data is None:
            raise IOError("read from file failed")

        rdata = data["Regions"]

        try:
            rdata = json.loads("\n".join(rdata))
        except ValueError:
            raise ValueError("json failed to load")

        return rdata
Exemple #12
0
    def fromFile(self, file_path, hsub = None):
        """
        Given an experiment config file, load the info
        """

        # Add extension to the name if there isn't one.
        if not file_path.endswith('.config'):
            file_path = file_path + '.config'

        logging.debug("Loading config file: {!r}".format(os.path.basename(file_path).split('.')[0]))
        try:
            # try to load the config file
            config_data = fileMethods.readFromFile(file_path)
        except IOError:
            ht.LoadingError("Cannot load the information")
        else:
            # now load the robot config from the dictionary data
            self.fromData(config_data, hsub)
            # update the file_path
            self.file_name = file_path
Exemple #13
0
    def loadSpecFile(self, spec_file):
        # Figure out where we should be looking for files, based on the spec file name & location
        self.project_root = os.path.abspath(os.path.dirname(spec_file))
        self.project_basename, ext = os.path.splitext(os.path.basename(spec_file)) 
        
        # Climb the tree to find out where we are
        p = os.path.abspath(sys.argv[0])
        t = ""
        while t != "src":
            (p, t) = os.path.split(p)
            if p == "":
                print "I have no idea where I am; this is ridiculous"
                sys.exit(1)

        self.ltlmop_root = os.path.join(p,"src")

        ### Load in the specification file
        if not self.silent: print "Loading specification file %s..." % spec_file
        spec_data = fileMethods.readFromFile(spec_file)   
        
        return spec_data
Exemple #14
0
    def readFile(self, filename):
        """
        For file format information, refer to writeFile() above.
        """

        if not os.path.exists(filename):
            return False

        data = fileMethods.readFromFile(filename)

        if data is None:
            return False

        try:
            self.background = data["Background"][0]
        except KeyError:
            self.background = "None"

        self.regions = []
        rdata = data["Regions"]

        try:
            rdata = json.loads("\n".join(rdata))
            compatMode = False
        except ValueError:
            compatMode = True

        for rd in rdata:
            newRegion = Region()
            if compatMode:
                regionData = rd.split("\t");
                newRegion.setDataOld(regionData)    
            else:
                newRegion.setData(rd)    

            self.regions.append(newRegion)

        # Make an empty adjacency matrix of size (# of regions) x (# of regions)
        self.transitions = [[[] for j in range(len(self.regions))] for i in range(len(self.regions))]
        for transition in data["Transitions"]:
            transData = transition.split("\t");
            region1 = self.indexOfRegionWithName(transData[0])
            region2 = self.indexOfRegionWithName(transData[1])
            faces = []
            for i in range(2, len(transData), 4):
                p1 = Point(float(transData[i]), float(transData[i+1]))
                p2 = Point(float(transData[i+2]), float(transData[i+3]))
                faces.append(frozenset((p1, p2)))
                
            # During adjacency matrix reconstruction, we'll mirror over the diagonal
            self.transitions[region1][region2] = faces
            self.transitions[region2][region1] = faces

        if "CalibrationPoints" in data:
            for point in data["CalibrationPoints"]:
                [name, index] = point.split("\t")
                self.regions[self.indexOfRegionWithName(name)].alignmentPoints[int(index)] = True

        if "Obstacles" in data:
            for rname in data["Obstacles"]:
                self.regions[self.indexOfRegionWithName(rname)].isObstacle = True
            
        self.filename = filename

        return True
Exemple #15
0
    def loadConfigFile(self,fileName):
        # If only filename offered, assume it is in the config path
        if len(os.path.split(fileName)[0]) == 0:
            fileName = os.path.join(self.config_path,fileName)

        # Add extension to the name if there isn't one.
        if not fileName.endswith('.config'):
            fileName = fileName+'.config'

        if not self.silent: print "Loading config file %s..." % fileName
        try:
            # First try path relative to project path
            config_data = fileMethods.readFromFile(fileName)
        except IOError:
            if not self.silent: print "ERROR: Cannot find config file %s" % fileName
            return

        configObj = ConfigObject()
        try:
            configObj.name = config_data['General Config']['Name'][0]
        except IOError:
            if not self.silent: print "ERROR: Missing general config information in config file %s" % fileName

        # parse the string for sensor prop mapping
        for sensorMapping in config_data['General Config']['Sensor_Proposition_Mapping']:
            try:
                sensorProp,sensorFun = [s.strip() for s in sensorMapping.split('=',1)]
            except IOError:
                if not self.silent: print "ERROR: Wrong sensor mapping -- %s" % sensorMapping

            configObj.prop_mapping[sensorProp]=sensorFun

        # parse the string for actuator prop mapping
        for actuatorMapping in config_data['General Config']['Actuator_Proposition_Mapping']:
            try:
                actuatorProp,actuatorFun = [s.strip() for s in actuatorMapping.split('=',1)]
            except IOError:
                if not self.silent: print "ERROR: Wrong actuator mapping -- %s" % actuatorMapping
            configObj.prop_mapping[actuatorProp]=actuatorFun

        if 'Initial_Truths' in config_data['General Config']:
            # parse the initially true propositions
            for propName in config_data['General Config']['Initial_Truths']:
                try:
                    configObj.initial_truths.append(propName)
                except IOError:
                    if not self.silent: print "ERROR: Wrong initially true propositions -- %s"


        try:
            configObj.main_robot = config_data['General Config']['Main_Robot'][0]
        except (IndexError, KeyError):
            if not self.silent: print "ERROR: Cannot find main robot for this config"

        # load robot configs
        robot_data = []
        for configKey,configValue in config_data.iteritems():
            if configKey.startswith('Robot'):
                robot_data.append(configValue)

        if robot_data == []:
            if not self.silent: print "ERROR: Missing Robot data in config file %s" % fileName

        else:
            # using the parsing function in RobotFileParser to parse the data
            robot_parser = RobotFileParser(self.handler_path,self.handler_dic)
            for data in robot_data:
                try:
                    robotObj = robot_parser.loadRobotData(data)
                    if robotObj is not None:
                        configObj.robots.append(robotObj)
                except IOError:
                    if not self.silent: print "ERROR: Cannot parse robot data in %s" % fileName

        # if the main robot for this config cannot be loaded, return no config object
        noRobot = True
        if configObj.main_robot == '' and len(configObj.robots)>0:
            noRobot = False
        if configObj.main_robot != '':
            for robotObj in configObj.robots:
                if configObj.main_robot == robotObj.name:
                    noRobot = False
                    break
        if noRobot:
            if not self.silent: print "WARNING: Cannot load configuration %s, missing main robot object" %fileName
            return None
        return configObj
Exemple #16
0
        #### Load in the robot file
        
        try:
            rdf_name = exp_cfg_data['RobotFile'][0]
        except IndexError, KeyError:
            if not self.silent: print "WARNING: Robot description file undefined"        
            return

        # Add extension to the name if there isn't one. 
        if not rdf_name.endswith('.robot'):
            rdf_name = rdf_name+'.robot'  
     
        if not self.silent: print "Loading robot description file %s..." % rdf_name
        try:
            # First try path relative to project path
            rdf_data = fileMethods.readFromFile(os.path.join(self.project_root, rdf_name))   
        except IOError: 
            try:
                # If that doesn't work, try looking in $self.ltlmop_root/robots/ directory
                rdf_data = fileMethods.readFromFile(os.path.join(self.ltlmop_root, "robots", rdf_name))   
            except IOError:
                if not self.silent: print "ERROR: Couldn't find robot description file in project directory or robots folder."
                return
        if not self.silent: print "  -> %s looks excited for this run." % rdf_data["Name"][0]
        
        return rdf_data

    def loadRegionFile(self, decomposed=False):
        """
        Returns a Region File Interface object corresponding to the regions file referenced in the spec file
        """
Exemple #17
0
def region2json(region_file, json_file):
    data = fileMethods.readFromFile(region_file)

    with open(json_file, 'w+') as json_file_obj:
        json_file_obj.write("\n".join(data["Regions"]))
    json_file_obj.closed
Exemple #18
0
    def readFile(self, filename):
        """
        For file format information, refer to writeFile() above.
        """

        if not os.path.exists(filename):
            return False

        data = fileMethods.readFromFile(filename)

        if data is None:
            return False

        try:
            self.background = data["Background"][0]
        except KeyError:
            self.background = "None"

        self.regions = []
        rdata = data["Regions"]

        try:
            rdata = json.loads("\n".join(rdata))
            compatMode = False
        except ValueError:
            compatMode = True

        for rd in rdata:
            newRegion = Region()
            if compatMode:
                regionData = rd.split("\t");
                newRegion.setDataOld(regionData)    
            else:
                newRegion.setData(rd)    

            self.regions.append(newRegion)

        # Make an empty adjacency matrix of size (# of regions) x (# of regions)
        self.transitions = [[[] for j in range(len(self.regions))] for i in range(len(self.regions))]
        for transition in data["Transitions"]:
            transData = transition.split("\t");
            region1 = self.indexOfRegionWithName(transData[0])
            region2 = self.indexOfRegionWithName(transData[1])
            faces = []
            for i in range(2, len(transData), 4):
                p1 = Point(float(transData[i]), float(transData[i+1]))
                p2 = Point(float(transData[i+2]), float(transData[i+3]))
                faces.append(tuple(sorted((p1, p2))))
                
            # During adjacency matrix reconstruction, we'll mirror over the diagonal
            self.transitions[region1][region2] = faces
            self.transitions[region2][region1] = faces

        if "CalibrationPoints" in data:
            for point in data["CalibrationPoints"]:
                [name, index] = point.split("\t")
                self.regions[self.indexOfRegionWithName(name)].alignmentPoints[int(index)] = True

        if "Obstacles" in data:
            for rname in data["Obstacles"]:
                self.regions[self.indexOfRegionWithName(rname)].isObstacle = True
            
        self.filename = filename

        return True