Beispiel #1
0
    def writeFile(self, filename):
        """
        File format is described inside the comments variable. 
        """

        comments = {"FILE_HEADER":"This is a region definition file for the LTLMoP toolkit.\n" +
                                  "Format details are described at the beginning of each section below.\n" +
                                  "Note that all values are separated by *tabs*.",
                    "Background": "Relative path of background image file",
                    "Regions": "Stored as JSON string",
                    "Transitions": "Region 1 Name, Region 2 Name, Bidirectional transition faces (face1_x1, face1_y1, face1_x2, face1_y2, face2_x1, ...)",
                    "CalibrationPoints": "Vertices to use for map calibration: (vertex_region_name, vertex_index)",
                    "Obstacles": "Names of regions to treat as obstacles"}    
    
        regionData = []
        for r in self.regions:
            d = r.getData()
            # We don't want to store the following two attributes inside the regions
            del d['alignmentPoints']
            del d['isObstacle']
            regionData.append(d)
        je = prettierJSONEncoder(indent=4)
        regionData = [je.encode(regionData)]
       
        transitionData = []
        for region1, destinations in enumerate(self.transitions):
            # Note: We are assuming all transitions are bidirectional so we only have to include
            # the parts of the adjacency matrix above the diagonal
            for region2, faces in enumerate(destinations[region1+1:]):
                if faces == []: continue    # No transition between these regions, so skip

                faceData = []
                for face in faces:
                    faceData.extend([face[0][0], face[0][1], face[1][0], face[1][1]])

                transitionData.append("\t".join([self.regions[region1].name,
                                                 self.regions[region1 + 1 + region2].name] +
                                                 map(str, faceData)))

        calibPoints = []
        for region in self.regions:
            for index, isAP in enumerate(region.alignmentPoints):
                if isAP:
                    calibPoints.append("\t".join([region.name, str(index)]))

        calibPointsStr = "\t".join(calibPoints)

        obstacleRegions = [r.name for r in self.regions if r.isObstacle]

        data = {"Background": self.background,
                "Regions": regionData,
                "Transitions": transitionData,
                "CalibrationPoints": calibPoints,
                "Obstacles": obstacleRegions}

        fileMethods.writeToFile(filename, data, comments)
        self.filename = filename

        return True
Beispiel #2
0
    def writeFile(self, filename):
        """
        File format is described inside the comments variable. 
        """

        comments = {"FILE_HEADER":"This is a region definition file for the LTLMoP toolkit.\n" +
                                  "Format details are described at the beginning of each section below.\n" +
                                  "Note that all values are separated by *tabs*.",
                    "Background": "Relative path of background image file",
                    "Regions": "Stored as JSON string",
                    "Transitions": "Region 1 Name, Region 2 Name, Bidirectional transition faces (face1_x1, face1_y1, face1_x2, face1_y2, face2_x1, ...)",
                    "CalibrationPoints": "Vertices to use for map calibration: (vertex_region_name, vertex_index)",
                    "Obstacles": "Names of regions to treat as obstacles"}    
    
        regionData = []
        for r in self.regions:
            d = r.getData()
            # We don't want to store the following two attributes inside the regions
            del d['alignmentPoints']
            del d['isObstacle']
            regionData.append(d)
        je = prettierJSONEncoder(indent=4)
        regionData = [je.encode(regionData)]
       
        transitionData = []
        for region1, destinations in enumerate(self.transitions):
            # Note: We are assuming all transitions are bidirectional so we only have to include
            # the parts of the adjacency matrix above the diagonal
            for region2, faces in enumerate(destinations[region1+1:]):
                if faces == []: continue    # No transition between these regions, so skip

                faceData = [coord for face in faces for pt in face for coord in pt]

                transitionData.append("\t".join([self.regions[region1].name,
                                                 self.regions[region1 + 1 + region2].name] +
                                                 map(str, faceData)))

        calibPoints = []
        for region in self.regions:
            for index, isAP in enumerate(region.alignmentPoints):
                if isAP:
                    calibPoints.append("\t".join([region.name, str(index)]))

        calibPointsStr = "\t".join(calibPoints)

        obstacleRegions = [r.name for r in self.regions if r.isObstacle]

        data = {"Background": self.background,
                "Regions": regionData,
                "Transitions": transitionData,
                "CalibrationPoints": calibPoints,
                "Obstacles": obstacleRegions}

        fileMethods.writeToFile(filename, data, comments)
        self.filename = filename

        return True
Beispiel #3
0
    def writeFile(self, filename):
        """
        File format is described inside the comments variable. 
        """

        comments = {
            "FILE_HEADER": "This is a region definition file for the LTLMoP toolkit.\n"
            + "Format details are described at the beginning of each section below.\n"
            + "Note that all values are separated by *tabs*.",
            "Background": "Relative path of background image file",
            "Regions": "Name, Type, Pos X, Pos Y, Width, Height, Color R, Color G, Color B, Vertices (x1, y1, x2, y2, ...)",
            "Transitions": "Region 1 Name, Region 2 Name, Bidirectional transition faces (face1_x1, face1_y1, face1_x2, face1_y2, face2_x1, ...)",
            "Thumbnail": "Relative path of image file that has region shapes overlayed on background image",
            "CalibrationPoints": "Vertices to use for map calibration: (vertex_region_name, vertex_index)",
        }

        regionData = []
        for i, region in enumerate(self.regions):
            regionData.append("\t".join(map(str, region.getData(withAlignment=False))))

        transitionData = []
        for region1, destinations in enumerate(self.transitions):
            # Note: We are assuming all transitions are bidirectional so we only have to include
            # the parts of the adjacency matrix above the diagonal
            for region2, faces in enumerate(destinations[region1 + 1 :]):
                if faces == []:
                    continue  # No transition between these regions, so skip

                faceData = []
                for face in faces:
                    faceData.extend([face[0][0], face[0][1], face[1][0], face[1][1]])

                transitionData.append(
                    "\t".join(
                        [self.regions[region1].name, self.regions[region1 + 1 + region2].name] + map(str, faceData)
                    )
                )

        calibPoints = []
        for region in self.regions:
            for index, bool in enumerate(region.alignmentPoints):
                if bool:
                    calibPoints.append("\t".join([region.name, str(index)]))

        calibPointsStr = "\t".join(calibPoints)

        data = {
            "Background": self.background,
            "Regions": regionData,
            "Transitions": transitionData,
            "Thumbnail": os.path.basename(self.thumb),
            "CalibrationPoints": calibPoints,
        }

        fileMethods.writeToFile(filename, data, comments)

        return True
Beispiel #4
0
    def writeSpecFile(self, filename=None):
        if filename is None:
            # Default to same filename as we loaded from
            filename = os.path.join(self.project_root, self.project_basename + ".spec")
        else:
            # Update our project paths based on the new filename
            self.project_root = os.path.dirname(os.path.abspath(filename))
            self.project_basename, ext = os.path.splitext(os.path.basename(filename))

        data = {}

        data["SPECIFICATION"] = {"Spec": self.specText}

        if self.regionMapping is not None:
            data["SPECIFICATION"]["RegionMapping"] = [
                rname + " = " + ", ".join(rlist) for rname, rlist in self.regionMapping.iteritems()
            ]

        data["SETTINGS"] = {
            "Sensors": [p + ", " + str(int(p in self.enabled_sensors)) for p in self.all_sensors],
            "Actions": [p + ", " + str(int(p in self.enabled_actuators)) for p in self.all_actuators],
            "Customs": self.all_customs,
        }

        if self.currentConfig is not None:
            data["SETTINGS"]["CurrentConfigName"] = self.currentConfig.name

        data["SETTINGS"]["CompileOptions"] = "\n".join(
            ["%s: %s" % (k, str(v)) for k, v in self.compile_options.iteritems()]
        )

        if self.rfi is not None:
            # Save the path to the region file as relative to the spec file
            # FIXME: relpath has case sensitivity problems on OS X
            data["SETTINGS"]["RegionFile"] = os.path.normpath(os.path.relpath(self.rfi.filename, self.project_root))

        comments = {
            "FILE_HEADER": "This is a specification definition file for the LTLMoP toolkit.\n"
            + "Format details are described at the beginning of each section below.",
            "RegionFile": "Relative path of region description file",
            "Sensors": "List of sensor propositions and their state (enabled = 1, disabled = 0)",
            "Actions": "List of action propositions and their state (enabled = 1, disabled = 0)",
            "Customs": "List of custom propositions",
            "Spec": "Specification in structured English",
            "RegionMapping": "Mapping between region names and their decomposed counterparts",
        }

        fileMethods.writeToFile(filename, data, comments)
Beispiel #5
0
    def writeSpecFile(self, filename=None):
        if filename is None:
            # Default to same filename as we loaded from
            filename = os.path.join(self.project_root, self.project_basename + ".spec")
        else:
            # Update our project paths based on the new filename
            self.project_root = os.path.dirname(os.path.abspath(filename))
            self.project_basename, ext = os.path.splitext(os.path.basename(filename))

        data = {}

        data['SPECIFICATION'] = {"Spec": self.specText}

        if self.regionMapping is not None:
            data['SPECIFICATION']['RegionMapping'] = [rname + " = " + ', '.join(rlist) for
                                                      rname, rlist in self.regionMapping.iteritems()]

        data['SETTINGS'] = {"Sensors": [p + ", " + str(int(p in self.enabled_sensors)) for p in self.all_sensors],
                            "Actions": [p + ", " + str(int(p in self.enabled_actuators)) for p in self.all_actuators],
                            "Customs": self.all_customs}

        if self.currentConfig is not None:
            data['SETTINGS']['CurrentConfigName'] = self.currentConfig.name

        data['SETTINGS']['CompileOptions'] = "\n".join(["%s: %s" % (k, str(v)) for k,v in self.compile_options.iteritems()])
    
        if self.rfi is not None:
            # Save the path to the region file as relative to the spec file
            # FIXME: relpath has case sensitivity problems on OS X
            data['SETTINGS']['RegionFile'] = os.path.normpath(os.path.relpath(self.rfi.filename, self.project_root))

        comments = {"FILE_HEADER": "This is a specification definition file for the LTLMoP toolkit.\n" +
                                   "Format details are described at the beginning of each section below.",
                    "RegionFile": "Relative path of region description file",
                    "Sensors": "List of sensor propositions and their state (enabled = 1, disabled = 0)",
                    "Actions": "List of action propositions and their state (enabled = 1, disabled = 0)",
                    "Customs": "List of custom propositions",
                    "Spec": "Specification in structured English",
                    "RegionMapping": "Mapping between region names and their decomposed counterparts"}

        fileMethods.writeToFile(filename, data, comments)
Beispiel #6
0
    def saveConfig(self):
        """
        Save the config object.
        Return True for successfully saved, False for not
        """
        # TODO: check if the config is complete

        # the file name is default to be the config name with underscore
        if self.name == "":
            self.name = 'Untitled configuration'
        file_name = self.name.replace(' ', '_')

        # Add extension to the name
        file_name = file_name+'.config'

        # Add the path to the file name
        file_name = os.path.join(os.path.dirname(self.file_name), file_name)
        self.file_name = file_name

        data = {'General Config':{'Name':self.name}}

        # proposition mapping
        sensorMappingList = []
        actuatorMappingList = []
        for prop, fun in self.prop_mapping.iteritems():
            if 'sensor' in fun.lower():
                sensorMapping = prop + ' = ' + fun
                sensorMappingList.append(sensorMapping)
            elif 'actuator' in fun.lower():
                actuatorMapping = prop + ' = ' + fun
                actuatorMappingList.append(actuatorMapping)
            else:
                logging.warning("Cannot recognize prop mapping: {}".format(prop+" = "+fun))

        data['General Config']['Sensor_Proposition_Mapping'] = sensorMappingList
        data['General Config']['Actuator_Proposition_Mapping'] = actuatorMappingList
        data['General Config']['Main_Robot'] = self.main_robot
        data['General Config']['Initial_Truths'] = self.initial_truths
        data['General Config']['Region_Tags'] = json.dumps(self.region_tags)

        for i, robot in enumerate(self.robots):
            header = 'Robot'+str(i+1)+' Config'
            data[header] = {}
            data[header]['RobotName'] = robot.name
            data[header]['Type'] = robot.r_type

            data[header]['CalibrationMatrix'] = repr(robot.calibration_matrix)
            # TODO: change to string function
            try:
                for handler_type_name in  ht.getAllHandlerTypeName(short_name = False):
                    handler_type_class = ht.getHandlerTypeClass(handler_type_name)
                    if handler_type_class in robot.handlers.keys():
                        data[header][handler_type_name] = robot.handlers[handler_type_class].toString()
            except AttributeError:
                logging.warning("Cannot save handlers for robot {}({}). Please make sure they are all successfully loaded. Aborting saving."\
                        .format(robot.name, robot.r_type))
                return False


        comments = {"FILE_HEADER": "This is a configuration definition file in folder \"%s\".\n" % os.path.dirname(self.file_name)+
                    "Format details are described at the beginning of each section below.\n",
                    "PoseHandler": "Input value for robot pose handler, refer to file inside the handlers/pose folder",
                    "DriveHandler": "Input value for robot drive handler, refer to file inside the handlers/drive folder",
                    "MotionControlHandler": "Input value for robot motion control handler, refer to file inside the handlers/motionControl folder",
                    "LocomotionCommandHandler": "Input value for robot locomotion command handler, refer to file inside the handlers/robots/Type folder",
                    "InitHandler": "Input value for robot init handler, refer to the init file inside the handlers/robots/Type folder",
                    "SensorHandler": "Sensor handler file in robots/Type folder",
                    "ActuatorHandler": "Actuator handler file in robots/Type folder",
                    "RobotName": "Robot Name",
                    "Type": "Robot type",
                    "CalibrationMatrix": "3x3 matrix for converting coordinates, stored as lab->map",
                    "Actuator_Proposition_Mapping": 'Mapping between actuator propositions and actuator handler functions',
                    "Sensor_Proposition_Mapping": "Mapping between sensor propositions and sensor handler functions",
                    "Name": 'Configuration name',
                    "Main_Robot":'The name of the robot used for moving in this config',
                    "Initial_Truths": "Initially true propositions",
                    "Region_Tags": "Mapping from tag names to region groups, for quantification"}

        fileMethods.writeToFile(file_name, data, comments)
        return True
Beispiel #7
0
    def saveConfigFile(self,configObj,fileName=''):
        """
        Write all data out to a file.
        """

        if fileName is '':
            fileName = configObj.name.replace(' ','_')


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

        data = {'General Config':{'Name':configObj.name}}

        # proposition mapping
        sensorMappingList = []
        actuatorMappingList = []
        for prop, fun in configObj.prop_mapping.iteritems():
            if 'sensor' in fun.lower():
                sensorMapping = prop + ' = ' + fun
                sensorMappingList.append(sensorMapping)
            elif 'actuator' in fun.lower():
                actuatorMapping = prop + ' = ' + fun
                actuatorMappingList.append(actuatorMapping)

        data['General Config']['Sensor_Proposition_Mapping'] = sensorMappingList
        data['General Config']['Actuator_Proposition_Mapping'] = actuatorMappingList
        data['General Config']['Main_Robot'] = configObj.main_robot
        data['General Config']['Initial_Truths'] = configObj.initial_truths

        for i,robot in enumerate(configObj.robots):
            header = 'Robot'+str(i+1)+' Config'
            data[header]={}
            data[header]['RobotName'] = robot.name
            data[header]['Type'] = robot.type

            if robot.calibrationMatrix is not None:
                data[header]['CalibrationMatrix'] = repr(robot.calibrationMatrix)

            data[header]['InitHandler'] = robot.handlers['init'].toString()
            data[header]['PoseHandler'] = robot.handlers['pose'].toString()
            data[header]['MotionControlHandler'] = robot.handlers['motionControl'].toString()
            data[header]['DriveHandler'] = robot.handlers['drive'].toString()
            data[header]['LocomotionCommandHandler'] = robot.handlers['locomotionCommand'].toString()
            data[header]['SensorHandler'] = robot.handlers['sensor'].toString()
            data[header]['ActuatorHandler'] = robot.handlers['actuator'].toString()


        comments = {"FILE_HEADER": "This is a configuration definition file for the example \"%s\".\n" % self.proj.project_basename +
                    "Format details are described at the beginning of each section below.\n",
                    "PoseHandler": "Input value for robot pose handler, refer to file inside the handlers/pose folder",
                    "DriveHandler": "Input value for robot drive handler, refer to file inside the handlers/drive folder",
                    "MotionControlHandler": "Input value for robot motion control handler, refer to file inside the handlers/motionControl folder",
                    "LocomotionCommandHandler": "Input value for robot locomotion command handler, refer to file inside the handlers/robots/Type folder",
                    "InitHandler": "Input value for robot init handler, refer to the init file inside the handlers/robots/Type folder",
                    "SensorHandler": "Sensor handler file in robots/Type folder",
                    "ActuatorHandler": "Actuator handler file in robots/Type folder",
                    "RobotName": "Robot Name",
                    "Type": "Robot type",
                    "CalibrationMatrix": "3x3 matrix for converting coordinates, stored as lab->map",
                    "Actuator_Proposition_Mapping": 'Mapping between actuator propositions and actuator handler functions',
                    "Sensor_Proposition_Mapping": "Mapping between sensor propositions and sensor handler functions",
                    "Name": 'Configuration name',
                    "Main_Robot":'The name of the robot used for moving in this config',
                    "Initial_Truths": "Initially true propositions"}

        fileMethods.writeToFile(os.path.join(self.config_path,fileName), data, comments)