コード例 #1
0
ファイル: __init__.py プロジェクト: is44c/pyrobot
 def loadBrain(self,file):
    """Finds and loads the brain file."""
    if self.robot is 0:
       raise Except('No robot loaded when loading brain')
    if file[-3:] != '.py':
       file = file + '.py'
    if system.file_exists(file):
       try:
          self.brain.window.destroy()
       except:
          pass
       try:
          self.brain.destroy()
       except:
          pass
       self.brain = system.loadINIT(file, self)
       self.brainfile = file
    elif (pyrobotdir() != None and
          system.file_exists(pyrobotdir() + \
                             '/plugins/brains/' + file)): 
       try:
          self.brain.window.destroy()
       except:
          pass
       try:
          self.brain.destroy()
       except:
          pass
       self.brain = system.loadINIT(pyrobotdir() + \
                                    '/plugins/brains/' + file, self)
       self.brainfile = pyrobotdir() + '/plugins/brains/' + file
    else:
       raise Exception("Pyrobot File not found: '%s'" % file)
コード例 #2
0
ファイル: TK.py プロジェクト: Zinebl/Pyro-Robotics-OSX
 def fileloaddialog(self, filetype, skel, startdir = ''):
    from string import replace
    import pyrobot
    from os import getcwd, getenv, chdir
    retval = ""
    cwd = getcwd()
    if startdir == '':
       chdir(pyrobot.pyrobotdir() + "/plugins/" + filetype)
    else:
       chdir(startdir)
    d = TKwidgets.LoadFileDialog(self, "Load " + filetype, skel, \
                                 pyrobot.pyrobotdir() + "/plugins/" + filetype)
    try:
       retval = d.Show()
       if retval == 1:
          doc = d.GetFileName()
          d.DialogCleanup()
          retval = doc
       else:
          d.DialogCleanup()
    except:
       print "failed!"
       # double-click bug. What should we do?
       doc = d.GetFileName()
       d.DialogCleanup()
       retval = doc
    chdir(cwd)
    return retval
コード例 #3
0
 def fileloaddialog(self, filetype, skel, startdir=''):
     from string import replace
     import pyrobot
     from os import getcwd, getenv, chdir
     retval = ""
     cwd = getcwd()
     if startdir == '':
         chdir(pyrobot.pyrobotdir() + "/plugins/" + filetype)
     else:
         chdir(startdir)
     d = TKwidgets.LoadFileDialog(self, "Load " + filetype, skel, \
                                  pyrobot.pyrobotdir() + "/plugins/" + filetype)
     try:
         retval = d.Show()
         if retval == 1:
             doc = d.GetFileName()
             d.DialogCleanup()
             retval = doc
         else:
             d.DialogCleanup()
     except:
         print "failed!"
         # double-click bug. What should we do?
         doc = d.GetFileName()
         d.DialogCleanup()
         retval = doc
     chdir(cwd)
     return retval
コード例 #4
0
 def __init__(self, root, width, height):
     Tkinter.Toplevel.__init__(self, root)
     self.done = 0
     self.quit = 0
     self.root = root
     self.width = width
     self.height = height
     self.title("PyrobotSimulator: VacuumCleanerWorld")
     self.canvas = Tkinter.Canvas(self,
                                  width=self.width,
                                  height=self.height,
                                  bg="white")
     self.canvas.pack()
     self.winfo_toplevel().protocol('WM_DELETE_WINDOW', self.destroy)
     self.dirtFilename = pyrobotdir() + "/images/dirt.gif"
     self.vacFilename = pyrobotdir() + "/images/vac.gif"
     self.dirtImage = Image.open(self.dirtFilename)
     self.vacImage = Image.open(self.vacFilename)
     self.vacImageTk = ImageTk.PhotoImage(self.vacImage)
     self.dirtImageTk = ImageTk.PhotoImage(self.dirtImage)
     self.properties = ["location", "status"]
     for i in self.properties:
         self.__dict__[i] = None
     self.movements = ["left", "right", "suck", "dump"]
     self.ports = [60000]
     self.initWorld()
     self.redraw()
コード例 #5
0
ファイル: __init__.py プロジェクト: emilydolson/forestcat
 def loadBrain(self, file):
     """Finds and loads the brain file."""
     if self.robot is 0:
         raise Except('No robot loaded when loading brain')
     if file[-3:] != '.py':
         file = file + '.py'
     if system.file_exists(file):
         try:
             self.brain.window.destroy()
         except:
             pass
         try:
             self.brain.destroy()
         except:
             pass
         self.brain = system.loadINIT(file, self)
         self.brainfile = file
     elif (pyrobotdir() != None and
           system.file_exists(pyrobotdir() + \
                              '/plugins/brains/' + file)):
         try:
             self.brain.window.destroy()
         except:
             pass
         try:
             self.brain.destroy()
         except:
             pass
         self.brain = system.loadINIT(pyrobotdir() + \
                                      '/plugins/brains/' + file, self)
         self.brainfile = pyrobotdir() + '/plugins/brains/' + file
     else:
         raise Exception("Pyrobot File not found: '%s'" % file)
コード例 #6
0
 def setCurrentConfig(self, config):
    cwd = os.getcwd()
    if self.engine.simfile:
       file = self.engine.simfile
       if pyrobotdir() + "/plugins/" in file or \
              cwd in file:
          file = file.split(os.path.sep)[-1]
       config.put("simulator", "file", file)
    if self.engine.worldfile:
       file = self.engine.worldfile
       if pyrobotdir() + "/plugins/" in file or \
              cwd in file:
          file = file.split(os.path.sep)[-1]
       config.put("world", "file", file)
    if self.engine.robotfile:
       file = self.engine.robotfile
       if pyrobotdir() + "/plugins/" in file or \
              cwd in file:
          file = file.split(os.path.sep)[-1]
       config.put("robot", "file", file)
    if self.engine.brainfile:
       file = self.engine.brainfile
       if pyrobotdir() + "/plugins/" in file or \
              cwd in file:
          file = file.split(os.path.sep)[-1]
       config.put("brain", "file", file)
    print "Ok"
コード例 #7
0
ファイル: tkmap.py プロジェクト: pfcoperez/tecnicasiarobotica
    def loadMapFile(self, file):
        import os

        if file[-3:] != ".py":
            file = file + ".py"
        if system.file_exists(file):
            grid = system.loadINIT(file)
        elif system.file_exists(pyrobotdir() + "/plugins/maps/" + file):
            grid = system.loadINIT(pyrobotdir() + "/plugins/plots/" + file)
        else:
            raise "Map file not found: " + file
        self.setGrid(grid)
コード例 #8
0
ファイル: tkmap.py プロジェクト: agigom2233/pyrobot
 def loadMapFile(self, file):
     import os
     if file[-3:] != '.py':
         file = file + '.py'
     if system.file_exists(file):
         grid = system.loadINIT(file)
     elif system.file_exists(pyrobotdir() + \
                             '/plugins/maps/' + file): 
         grid = system.loadINIT(pyrobotdir() + \
                                '/plugins/plots/' + file)
     else:
         raise 'Map file not found: ' + file
     self.setGrid(grid)
コード例 #9
0
ファイル: config.py プロジェクト: Zinebl/Pyro-Robotics-OSX
 def load(self, file = None):
     cp = ConfigParser.ConfigParser()
     if file_exists( pyrobotdir() + "/.pyrobot"): 
         self.processFile( pyrobotdir() + "/.pyrobot", cp)
     if file_exists( pyrobotdir() + "/pyrobot.ini"): # $PYRO?
         self.processFile( pyrobotdir() + "/pyrobot.ini", cp)
     if file_exists( pyrobotdir() +
                     "/.pyrobot-" + environ['HOSTNAME']):
         # $PYRO-HOSTNAME?
         self.processFile( pyrobotdir() +
                           "/.pyrobot-" + environ['HOSTNAME'], cp)
     if file_exists( pyrobotdir() +
                     "/pyrobot-" + environ['HOSTNAME'] + ".ini"):
         # $PYRO-HOSTNAME?
         self.processFile( pyrobotdir() +
                           "/pyrobot-" + environ['HOSTNAME'] + ".ini", cp)
     if file_exists( environ['HOME'] + "/.pyrobot"): # home dir?
         self.processFile( environ['HOME'] + "/.pyrobot", cp)
     if file_exists( environ['HOME'] + "/pyrobot.ini"): # home dir?
         self.processFile( environ['HOME'] + "/pyrobot.ini", cp)
     if file_exists(".pyrobot"): # current dir?
         self.processFile( ".pyrobot", cp)
     if file_exists("pyrobot.ini"): # current dir?
         self.processFile( "pyrobot.ini", cp)
     if file and file_exists(file):
         self.processFile( file, cp)
コード例 #10
0
 def load(self, file=None):
     cp = ConfigParser.ConfigParser()
     if file_exists(pyrobotdir() + "/.pyrobot"):
         self.processFile(pyrobotdir() + "/.pyrobot", cp)
     if file_exists(pyrobotdir() + "/pyrobot.ini"):  # $PYRO?
         self.processFile(pyrobotdir() + "/pyrobot.ini", cp)
     if file_exists(pyrobotdir() + "/.pyrobot-" + environ['HOSTNAME']):
         # $PYRO-HOSTNAME?
         self.processFile(pyrobotdir() + "/.pyrobot-" + environ['HOSTNAME'],
                          cp)
     if file_exists(pyrobotdir() + "/pyrobot-" + environ['HOSTNAME'] +
                    ".ini"):
         # $PYRO-HOSTNAME?
         self.processFile(
             pyrobotdir() + "/pyrobot-" + environ['HOSTNAME'] + ".ini", cp)
     if file_exists(environ['HOME'] + "/.pyrobot"):  # home dir?
         self.processFile(environ['HOME'] + "/.pyrobot", cp)
     if file_exists(environ['HOME'] + "/pyrobot.ini"):  # home dir?
         self.processFile(environ['HOME'] + "/pyrobot.ini", cp)
     if file_exists(".pyrobot"):  # current dir?
         self.processFile(".pyrobot", cp)
     if file_exists("pyrobot.ini"):  # current dir?
         self.processFile("pyrobot.ini", cp)
     if file and file_exists(file):
         self.processFile(file, cp)
コード例 #11
0
ファイル: __init__.py プロジェクト: is44c/pyrobot
 def loadRobot(self,file):
    """Finds and loads the robot."""
    if file[-3:] != '.py':
       file = file + '.py'
    if system.file_exists(file):
       self.robot = system.loadINIT(file)
       self.robotfile = file
    elif (pyrobotdir() != None and
          system.file_exists(pyrobotdir() + \
                             '/plugins/robots/' + file)): 
       self.robot = system.loadINIT(pyrobotdir() + \
                                    '/plugins/robots/' + file)
       self.robotfile = pyrobotdir() + '/plugins/robots/' + file
    else:
       raise Exception("Pyrobot Robot file not found: '%s'" % file)
コード例 #12
0
ファイル: __init__.py プロジェクト: emilydolson/forestcat
 def loadRobot(self, file):
     """Finds and loads the robot."""
     if file[-3:] != '.py':
         file = file + '.py'
     if system.file_exists(file):
         self.robot = system.loadINIT(file)
         self.robotfile = file
     elif (pyrobotdir() != None and
           system.file_exists(pyrobotdir() + \
                              '/plugins/robots/' + file)):
         self.robot = system.loadINIT(pyrobotdir() + \
                                      '/plugins/robots/' + file)
         self.robotfile = pyrobotdir() + '/plugins/robots/' + file
     else:
         raise Exception("Pyrobot Robot file not found: '%s'" % file)
コード例 #13
0
 def filesavedialog(self, filetype, skel, startdir='', default=None):
     # FIXED: from string import replace
     print("pyrobot/gui/TK.py filesaveddialog")  #DEBUG
     import string
     import pyrobot
     from os import getcwd, getenv, chdir
     retval = ""
     cwd = getcwd()
     if startdir == '':
         chdir(pyrobot.pyrobotdir() + "/plugins/" + filetype)
     else:
         chdir(startdir)
     d = TKwidgets.SaveFileDialog(self,
                                  "Save " + filetype,
                                  skel,
                                  defaultFilename=default)
     try:
         if d.Show() == 1:
             doc = d.GetFileName()
             d.DialogCleanup()
             retval = doc
         else:
             d.DialogCleanup()
     except:
         # double-click bug. What should we do?
         doc = d.GetFileName()
         d.DialogCleanup()
         retval = doc
     chdir(cwd)
     return retval
コード例 #14
0
ファイル: trace.py プロジェクト: agigom2233/pyrobot
 def __init__(self,
              pathDataFilename="",
              worldImageFilename="",
              resolution=0.01):
     self.worldImageFilename = worldImageFilename
     self.pathDataFilename = pathDataFilename
     self.outfile = ""
     self.app = 0
     path = pyrobotdir()
     self.fontFilename = path + "/tools/pilfonts/courR08.pil"
     self.symbols = 1  # activates/deactivates symbol mode
     self.color = "0"  # activates/deactivates color
     self.length = 10  # the length of lines in non-symbol mode
     # the resolution given for the bitmap in the world file
     self.resolution = resolution
     self.interval = 2  # frequency datapoints should be displayed
     self.robotPathData = self.readDataFile()
     im = Image.open(self.worldImageFilename)
     if self.color == "0":
         self.imageData = ImageChops.invert(im)
     self.imageData = im.convert("RGB")
     self.convertXPositionData(self.imageData, self.robotPathData)
     self.drawObj = ImageDraw.Draw(self.imageData)
     self.textDict = {}
     self.symbolDict = {}
     self.symbolSet = SymbolSet()
     self.colorSet = ColorSet()
     self.quitWhenDone = 1
コード例 #15
0
ファイル: trace.py プロジェクト: Zinebl/Pyro-Robotics-OSX
 def __init__(self, pathDataFilename = "", worldImageFilename = "", resolution = 0.01):
     self.worldImageFilename = worldImageFilename
     self.pathDataFilename = pathDataFilename
     self.outfile = ""
     self.app = 0
     path = pyrobotdir()
     self.fontFilename = path + "/tools/pilfonts/courR08.pil"
     self.symbols = 1        # activates/deactivates symbol mode
     self.color = "0"          # activates/deactivates color
     self.length = 10     # the length of lines in non-symbol mode
     # the resolution given for the bitmap in the world file
     self.resolution = resolution
     self.interval = 2       # frequency datapoints should be displayed
     self.robotPathData = self.readDataFile()
     im = Image.open(self.worldImageFilename)
     if self.color == "0":
         self.imageData = ImageChops.invert(im)
     self.imageData = im.convert("RGB")
     self.convertXPositionData(self.imageData, self.robotPathData)
     self.drawObj = ImageDraw.Draw(self.imageData)
     self.textDict = {}
     self.symbolDict = {}
     self.symbolSet = SymbolSet()
     self.colorSet = ColorSet()
     self.quitWhenDone = 1
コード例 #16
0
ファイル: TK.py プロジェクト: Zinebl/Pyro-Robotics-OSX
 def filesavedialog(self, filetype, skel, startdir = '', default=None):
    from string import replace
    import pyrobot
    from os import getcwd, getenv, chdir
    retval = ""
    cwd = getcwd()
    if startdir == '':
       chdir(pyrobot.pyrobotdir() + "/plugins/" + filetype)
    else:
       chdir(startdir)
    d = TKwidgets.SaveFileDialog(self, "Save " + filetype, skel, defaultFilename=default)
    try:
       if d.Show() == 1:
          doc = d.GetFileName()
          d.DialogCleanup()
          retval = doc
       else:
          d.DialogCleanup()
    except:
       # double-click bug. What should we do?
       doc = d.GetFileName()
       d.DialogCleanup()
       retval = doc
    chdir(cwd)
    return retval
コード例 #17
0
 def __init__(self, root, width, height):
     Tkinter.Toplevel.__init__(self, root)
     self.done = 0
     self.quit = 0
     self.root = root
     self.width = width
     self.height = height
     self.visible = 1
     self.title("PyrobotSimulator: WumpusWorld")
     self.canvas = Tkinter.Canvas(self,
                                  width=self.width,
                                  height=self.height,
                                  bg="white")
     self.canvas.pack()
     self.winfo_toplevel().protocol('WM_DELETE_WINDOW', self.destroy)
     # sensors: stench, breeze, glitter, bump, scream
     self.goldFilename = pyrobotdir() + "/images/gold.gif"
     self.wumpusFilename = pyrobotdir() + "/images/wumpus.gif"
     self.pitFilename = pyrobotdir() + "/images/pit.gif"
     self.agentFilename = pyrobotdir() + "/images/agent.gif"
     # --------------------------------------------------------
     self.goldImage = Image.open(self.goldFilename)
     self.goldImage = self.goldImage.resize((100, 25), Image.BILINEAR)
     self.wumpusImage = Image.open(self.wumpusFilename)
     self.wumpusImage = self.wumpusImage.resize((100, 100), Image.BILINEAR)
     self.pitImage = Image.open(self.pitFilename)
     self.pitImage = self.pitImage.resize((100, 100), Image.BILINEAR)
     self.agentImage = Image.open(self.agentFilename)
     self.agentImage = self.agentImage.resize((100, 100), Image.BILINEAR)
     # --------------------------------------------------------
     self.goldImageTk = ImageTk.PhotoImage(self.goldImage)
     self.wumpusImageTk = ImageTk.PhotoImage(self.wumpusImage)
     self.pitImageTk = ImageTk.PhotoImage(self.pitImage)
     self.agentImageTk = ImageTk.PhotoImage(self.agentImage)
     # --------------------------------------------------------
     self.properties = [
         "percept", "location", "x", "y", "direction", "arrow", "score",
         "alive"
     ]
     for i in self.properties:
         self.__dict__[i] = None
     self.initWorld()
     self.count = 0
     self.tag = "data-%d" % self.count
     self.movements = ["left", "right", "forward", "shoot", "grab"]
     self.ports = [60000]
     self.redraw()
コード例 #18
0
 def fileloaddialog(self, filetype, skel, startdir=''):
     # FIXED: string import replace
     import string
     import pyrobot
     from os import getcwd, getenv, chdir
     retval = ""
     cwd = getcwd()
     if startdir == '':
         chdir(pyrobot.pyrobotdir() + "/plugins/" + filetype)
     else:
         print("startdir")  #DEBUG
         chdir(pyrobot.pyrobotdir() + "/plugins/" + filetype)  #DEBUG
         print(startdir)  #DEBUG
         #chdir(startdir)
     print(
         "gui/TK.py - fileloaddialog : File Load dialog mean server.. Robot.. Brain"
     )  #DEBUG
     d = TKwidgets.LoadFileDialog(self, "Load " + filetype, skel, \
                                  pyrobot.pyrobotdir() + "/plugins/" + filetype)
     print("gui/TK.py - fileloaddialog")  #DEBUG
     print("gui/TK.py - d values")  #DEBUG
     print(d)  #DEBUG
     try:
         retval = d.Show()
         print("d.show()")  #DEBUG
         print(retval)  #DEBUG
         if retval == 1:
             print("gui/TK.py")  #DEBUG
             print("gui/TK.py, print d")  #DEBUG
             print(d)  #DEBUG
             print("    retval == 1")  #DEBUG
             doc = d.GetFileName()
             print("    print doc")  #DEBUG
             print(doc)  #DEBUG
             d.DialogCleanup()
             retval = doc
         else:
             d.DialogCleanup()
     except:
         print("    fail occured")  #DEBUG
         # double-click bug. What should we do?
         doc = d.GetFileName()
         d.DialogCleanup()
         retval = doc
     chdir(cwd)
     return retval
コード例 #19
0
ファイル: __init__.py プロジェクト: agigom2233/pyrobot
 def startDevices(self, item, override=False, **args):
     """Load devices can take a dict, list, builtin name, or filename """
     # Item can be: dict, list, or string. string can be name or filename
     if type(item) == type({}):
         # this is the only one that does anything
         retval = []
         for dev in item.keys():
             deviceNumber = self._getNextDeviceNumber(dev)
             print "Loading device %s[%d]..." % (dev, deviceNumber)
             self.__dict__[dev][deviceNumber] = item[dev]
             item[dev].setTitle(dev + "[" + str(deviceNumber) + "]")
             item[dev].index = deviceNumber
             retval.append(item[dev])  # return object
         return retval
     elif item in self.builtinDevices:  # built-in name
         # deviceBuiltin returns dictionary
         deviceList = self.startDeviceBuiltin(item)
         if type(deviceList) == type(
                 "device"):  # loaded it here, from the robot
             return [deviceList]
         else:
             return self.startDevices(deviceList, **args)  # dict of objs
     elif isinstance(item, (type((1, )), type([
             1,
     ]))):
         retval = []
         for i in item:
             retval.append(self.startDevice(i, **args))
         return retval
     else:  # from a file
         file = item
         if file == None:
             return []
         if len(file) > 3 and file[-3:] != '.py':
             file = file + '.py'
         if system.file_exists(file):
             return self.startDevices(system.loadINIT(file, self), **args)
         elif system.file_exists(pyrobotdir() + \
                                 '/plugins/devices/' + file):
             return self.startDevices( system.loadINIT(pyrobotdir() + \
                                                '/plugins/devices/'+ \
                                                file, self), **args)
         else:
             print 'Device file not found: ' + file
             return []
コード例 #20
0
ファイル: tkmap.py プロジェクト: agigom2233/pyrobot
 def fileloaddialog(self, filetype, skel, startdir = ''):
     from string import replace
     from os import getcwd, getenv, chdir
     retval = ""
     cwd = getcwd()
     if startdir == '':
         chdir(pyrobotdir() + "/plugins/" + filetype)
     else:
         chdir(startdir)
     d = TKwidgets.LoadFileDialog(self, "Load " + filetype, skel,
                                  pyrobotdir() + "/plugins/" + filetype)
     if d.Show() == 1:
         doc = d.GetFileName()
         d.DialogCleanup()
         retval = doc
     else:
         d.DialogCleanup()
     chdir(cwd)
     return retval
コード例 #21
0
ファイル: tkmap.py プロジェクト: pfcoperez/tecnicasiarobotica
    def fileloaddialog(self, filetype, skel, startdir=""):
        from string import replace
        from os import getcwd, getenv, chdir

        retval = ""
        cwd = getcwd()
        if startdir == "":
            chdir(pyrobotdir() + "/plugins/" + filetype)
        else:
            chdir(startdir)
        d = TKwidgets.LoadFileDialog(self, "Load " + filetype, skel, pyrobotdir() + "/plugins/" + filetype)
        if d.Show() == 1:
            doc = d.GetFileName()
            d.DialogCleanup()
            retval = doc
        else:
            d.DialogCleanup()
        chdir(cwd)
        return retval
コード例 #22
0
ファイル: __init__.py プロジェクト: Zinebl/Pyro-Robotics-OSX
 def startDevices(self, item, override = False, **args):
     """Load devices can take a dict, list, builtin name, or filename """
     # Item can be: dict, list, or string. string can be name or filename
     if type(item) == type({}):
         # this is the only one that does anything
         retval = []
         for dev in item.keys():
             deviceNumber = self._getNextDeviceNumber(dev)
             print "Loading device %s[%d]..." % (dev, deviceNumber)
             self.__dict__[dev][deviceNumber] = item[dev]
             item[dev].setTitle( dev + "[" + str(deviceNumber) + "]" )
             item[dev].index = deviceNumber
             retval.append(item[dev]) # return object
         return retval
     elif item in self.builtinDevices: # built-in name
         # deviceBuiltin returns dictionary
         deviceList = self.startDeviceBuiltin(item)
         if type(deviceList) == type("device"): # loaded it here, from the robot
             return [ deviceList ]
         else:
             return self.startDevices( deviceList, **args ) # dict of objs
     elif isinstance(item, (type((1,)), type([1,]))):
         retval = []
         for i in item:
             retval.append( self.startDevice(i, **args) )
         return retval
     else: # from a file
         file = item
         if file == None:
             return []
         if len(file) > 3 and file[-3:] != '.py':
             file = file + '.py'
         if system.file_exists(file):
             return self.startDevices( system.loadINIT(file, self), **args )
         elif system.file_exists(pyrobotdir() + \
                                 '/plugins/devices/' + file): 
             return self.startDevices( system.loadINIT(pyrobotdir() + \
                                                '/plugins/devices/'+ \
                                                file, self), **args)
         else:
             print 'Device file not found: ' + file
             return []
コード例 #23
0
ファイル: TK.py プロジェクト: Zinebl/Pyro-Robotics-OSX
 def newBrain(self):
    import os
    for i in range(1, 100):
       myfile = "~/MyBrain%d.py" % i
       if not exists(myfile):
          break
    os.system( "cp " + pyrobotdir() + ("/build/brainTemplate.py %s" % myfile))
    if os.getenv("EDITOR"):
       os.system(os.getenv("EDITOR") + " %s &" % myfile)
    else:
       os.system("emacs %s &"  % myfile)
コード例 #24
0
 def __init__(self, root, width, height):
     Tkinter.Toplevel.__init__(self, root)
     self.done = 0
     self.quit = 0
     self.root = root
     self.width = width
     self.height = height
     self.visible = 1
     self.title("PyrobotSimulator: WumpusWorld")
     self.canvas = Tkinter.Canvas(self,width=self.width,height=self.height,bg="white")
     self.canvas.pack()
     self.winfo_toplevel().protocol('WM_DELETE_WINDOW',self.destroy)
     # sensors: stench, breeze, glitter, bump, scream
     self.goldFilename = pyrobotdir() + "/images/gold.gif" 
     self.wumpusFilename = pyrobotdir() + "/images/wumpus.gif" 
     self.pitFilename = pyrobotdir() + "/images/pit.gif"
     self.agentFilename = pyrobotdir() + "/images/agent.gif" 
     # --------------------------------------------------------
     self.goldImage = Image.open(self.goldFilename)
     self.goldImage = self.goldImage.resize( (100, 25), Image.BILINEAR )
     self.wumpusImage = Image.open(self.wumpusFilename)
     self.wumpusImage = self.wumpusImage.resize( (100, 100), Image.BILINEAR )
     self.pitImage = Image.open(self.pitFilename)
     self.pitImage = self.pitImage.resize( (100, 100), Image.BILINEAR )
     self.agentImage = Image.open(self.agentFilename)
     self.agentImage = self.agentImage.resize( (100, 100), Image.BILINEAR )
     # --------------------------------------------------------
     self.goldImageTk = ImageTk.PhotoImage(self.goldImage)
     self.wumpusImageTk = ImageTk.PhotoImage(self.wumpusImage)
     self.pitImageTk = ImageTk.PhotoImage(self.pitImage)
     self.agentImageTk = ImageTk.PhotoImage(self.agentImage)
     # --------------------------------------------------------
     self.properties = ["percept", "location", "x", "y", "direction", "arrow", "score", "alive"]
     for i in self.properties:
         self.__dict__[i] = None
     self.initWorld()
     self.count = 0
     self.tag = "data-%d" % self.count
     self.movements = ["left", "right", "forward", "shoot", "grab"]
     self.ports = [60000]
     self.redraw()
コード例 #25
0
 def newBrain(self):
     import os
     for i in range(1, 100):
         myfile = "~/MyBrain%d.py" % i
         if not exists(myfile):
             break
     os.system("cp " + pyrobotdir() +
               ("/build/brainTemplate.py %s" % myfile))
     if os.getenv("EDITOR"):
         os.system(os.getenv("EDITOR") + " %s &" % myfile)
     else:
         os.system("emacs %s &" % myfile)
コード例 #26
0
 def loadSim(self, worldfile = ''):
    pyropath = pyrobotdir()
    f = self.fileloaddialog("simulators","*",self.lastDir.get("sim", ''))
    if f != '' and f != 0:
       self.lastDir["sim"] = string.join(f.split('/')[:-1],'/')
       if worldfile == '':
          simulatorName = f.split('/')[-1]
          if simulatorName[-6:] == "Server":
             configDirName = simulatorName[:-6]
             worldfile = self.fileloaddialog("configs","*.cfg",
                                             self.lastDir.get("%s-config" % simulatorName,
                                                              "%s/plugins/configs/%s/" %
                                                              (pyropath, configDirName)))
             if worldfile == "":
                return
             self.lastDir["%s-config" % simulatorName] = string.join(worldfile.split('/')[:-1],'/')
          else:
             # ends with "Simulator"
             simDirName = simulatorName[:-9]
             if simulatorName == "PyrobotSimulator":
                worldfile = self.fileloaddialog("worlds","*.py",
                                                self.lastDir.get("%s-world" % simulatorName,
                                                                 "%s/plugins/worlds/%s/" %
                                                                 (pyropath, simDirName)))
             elif simulatorName == "StageSimulator":
                worldfile = self.fileloaddialog("worlds","*.cfg",
                                                self.lastDir.get("%s-world" % simulatorName,
                                                                 "%s/plugins/worlds/%s/" %
                                                                 (pyropath, simDirName)))
             else:
                worldfile = self.fileloaddialog("worlds","*.world",
                                                self.lastDir.get("%s-world" % simulatorName,
                                                                 "%s/plugins/worlds/%s/" %
                                                                 (pyropath, simDirName)))
             if worldfile == "" or worldfile == 0:
                return
             self.lastDir["%s-world" % simulatorName] = string.join(worldfile.split('/')[:-1],'/')
       else:
          simulatorName = worldfile
          self.lastDir["%s-world" % simulatorName] = string.join(worldfile.split('/')[:-1],'/')
       self.engine.worldfile = worldfile
       self.engine.simfile = f
       pyroPID = os.getpid()
       if os.name in ['nt', 'dos', 'os2'] :
          # FIXME: this assumes program to run is a python program; how will we know?
          # could leave out "python" and windows will ask
          print "start python %s %d %s" % (f, pyroPID, worldfile)
          os.system("start python \"%s\" \"%d\" \"%s\"" % (f, pyroPID, worldfile))
       elif os.name in ['posix']:
          os.system(f + (" %d " % pyroPID) + worldfile + " &")
       else:
          raise AttributeError, "your OS (%s) is not supported" % os.name
コード例 #27
0
 def printCommandLine(self):
    commandLine = sys.argv[0] + " "
    if self.engine.simfile:
       file = self.engine.simfile
       if pyrobotdir() + "/plugins/" in file:
          file = file.split(os.path.sep)[-1]
       commandLine += "-s %s " % file
    if self.engine.worldfile:
       file = self.engine.worldfile
       if pyrobotdir() + "/plugins/" in file:
          file = file.split(os.path.sep)[-1]
       commandLine += "-w %s " % file
    if self.engine.robotfile:
       file = self.engine.robotfile
       if pyrobotdir() + "/plugins/" in file:
          file = file.split(os.path.sep)[-1]
       commandLine += "-r %s " % file
    if self.engine.brainfile:
       file = self.engine.brainfile
       if pyrobotdir() + "/plugins/" in file:
          file = file.split(os.path.sep)[-1]
       commandLine += "-b %s " % file
    print commandLine
コード例 #28
0
 def __init__(self, root, width, height):
     Tkinter.Toplevel.__init__(self, root)
     self.done = 0
     self.quit = 0
     self.root = root
     self.width = width
     self.height = height
     self.title("PyrobotSimulator: VacuumCleanerWorld")
     self.canvas = Tkinter.Canvas(self,width=self.width,height=self.height,bg="white")
     self.canvas.pack()
     self.winfo_toplevel().protocol('WM_DELETE_WINDOW',self.destroy)
     self.dirtFilename = pyrobotdir() + "/images/dirt.gif" 
     self.vacFilename = pyrobotdir() + "/images/vac.gif" 
     self.dirtImage = Image.open(self.dirtFilename)
     self.vacImage = Image.open(self.vacFilename)
     self.vacImageTk = ImageTk.PhotoImage(self.vacImage)
     self.dirtImageTk = ImageTk.PhotoImage(self.dirtImage)
     self.properties = ["location", "status"]
     for i in self.properties:
         self.__dict__[i] = None
     self.movements = ["left", "right", "suck", "dump"]
     self.ports = [60000]
     self.initWorld()
     self.redraw()
コード例 #29
0
ファイル: RLWorld.py プロジェクト: abitrolly/pyrorobotics
    def __init__(self, root, width, height):
        Tkinter.Toplevel.__init__(self, root)

        self.inaccessible = [(-1,-1),\
                             ( 4, 2),( 5, 2),( 6, 2),( 4, 3),( 5, 3),( 6, 3),\
                             ( 9, 2),(10, 2),(11, 2),( 9, 3),(10, 3),(11, 3),( 9, 4),(10, 4),(11, 4),\
                             (13, 1),(14, 1),(13, 2),(14, 2),(13, 3),(14, 3),(13, 4),(14, 4),\
                             (3,6),(4,6),(5,6),(3,7),(4,7),(5,7),(3,8),(4,8),(5,8),(3,9),(4,9),(5,9),\
                             (7,6),(8,6),     (7,7),(8,7),     (7,8),(8,8),    \
                             (6,9),(7,9),(8,9),     (6,10),(7,10),(8,10),(9,10),(10,10),(6,11),(7,11),\
                             (8,11),(9,11),(10,11),(6,12),(7,12),(8,12),(9,12),(6,13),(7,13),(8,13),\
                             (11,6),(12,6),(13,6),(11,7),(12,7),(13,7),(11,8),(12,8),(13,8),\
                             (0,11),(1,11),(2,11),(0,12),(1,12),(2,12),(0,13),(1,13),(2,13),(0,14),(1,14),(2,14)]

        self.path_color = "#5ee563"
        self.visited_color = "#c5c5c5"
        self.current_pos_color = "#00AF32"
        self.inaccessible_color = "black"
        self.gridline_color = "black"
        self.background_color = "white"

        self.path = []
        self.visited = []
        self.pits = []
        self.goal = []

        self.goal_id = -1
        self.pit_ids = []

        # how many states ?
        self.num_squares_x = 15
        self.num_squares_y = 15

        self.squares = resize(0, (self.num_squares_x, self.num_squares_y))

        # various object members
        self.done = 0
        self.quit = 0
        self.root = root
        self.width = width
        self.height = height
        self.complete = 0

        # various tk objects
        self.title("SymbolicSimulator: RLWorld")
        self.canvas = Tkinter.Canvas(self,
                                     width=self.width,
                                     height=self.height,
                                     bg="black")
        self.canvas.pack()
        self.winfo_toplevel().protocol('WM_DELETE_WINDOW', self.destroy)

        # set height and width of images
        self.square_height = self.width / self.num_squares_x
        self.square_width = self.height / self.num_squares_y

        # goal image
        goldFilename = pyrobotdir() + "/images/rlgoal.gif"
        goldImage = Image.open(goldFilename)
        goldImage = goldImage.resize(
            [self.square_height - 2, self.square_width - 2])
        self.goldImageTk = ImageTk.PhotoImage(goldImage)

        # pit image
        pitFilename = pyrobotdir() + "/images/rlpit.gif"
        pitImage = Image.open(pitFilename)
        pitImage = pitImage.resize(
            [self.square_height - 2, self.square_width - 2])
        self.pitImageTk = ImageTk.PhotoImage(pitImage,
                                             height=self.square_height,
                                             width=self.square_width)

        for i in range(0, self.num_squares_x):
            for j in range(0, self.num_squares_y):
                self.squares[i][j] = self.canvas.create_rectangle(
                    i * self.square_width,
                    j * self.square_height, (i + 1) * self.square_width - 1,
                    (j + 1) * self.square_height - 1,
                    fill=self.background_color,
                    tag="square-%d-%d" % (i, j))

        # initialize the world
        self.initWorld()
        self.resetStates()

        # used by simulator
        self.properties = ["location", "obstacles", "goal", "home", \
                           "final", "visited", "complete", \
                           "pits", "path"]

        self.movements = ["up", "right", "down", "left"]
        self.ports = [60000]

        # start things off
        self.redraw()
        self.drawInaccessible()
コード例 #30
0
ファイル: __init__.py プロジェクト: emilydolson/forestcat
 def loadSimulator(self, file, worldfile):
     """Finds and loads the simulator."""
     import string
     options = string.split(file)
     guiflag = ''
     simulatorName = file.split('/')[-1]
     pyroPID = os.getpid()
     if simulatorName[-6:] == "Server":
         configDirName = simulatorName[:-6]
         if system.file_exists(worldfile):
             pass  # leave it alone
         elif (pyrobotdir() != None and
               system.file_exists( pyrobotdir() + \
                                   '/plugins/configs/%s/%s' %
                                   (configDirName, worldfile))):
             worldfile = pyrobotdir() + \
                         '/plugins/configs/%s/%s' % (configDirName, worldfile)
         if self.config.get("pyrobot", "gui").lower() == 'tty':
             guiflag = '-g'
         if system.file_exists(options[0]):
             os.system(file + (" %d " % pyroPID) + guiflag + " " +
                       worldfile + " &")
         elif (pyrobotdir() != None and
               system.file_exists(pyrobotdir() + \
                                  '/plugins/simulators/' + options[0])):
             os.system(pyrobotdir() + '/plugins/simulators/' + file + \
                       (" %d " % pyroPID) + guiflag + " " + worldfile + " &")
         else:
             raise Exception("Pyrobot Server file not found: '%s'" % file)
     else:
         # Ends with "Simulator"
         simDirName = simulatorName[:-9]
         if system.file_exists(worldfile):
             pass  # leave it alone
         elif (pyrobotdir() != None and
               system.file_exists( pyrobotdir() + \
                                   '/plugins/worlds/%s/%s' %
                                   (simDirName, worldfile))):
             worldfile = pyrobotdir() + \
                         '/plugins/worlds/%s/%s' % (simDirName, worldfile)
         if self.config.get("pyrobot", "gui").lower() == 'tty':
             guiflag = '-g'
         if system.file_exists(options[0]):
             os.system(file + (" %d " % pyroPID) + guiflag + " " +
                       worldfile + " &")
         elif (pyrobotdir() != None and
               system.file_exists(pyrobotdir() + \
                                  '/plugins/simulators/' + options[0])):
             os.system(pyrobotdir() + '/plugins/simulators/' + file + \
                       (" %d " % pyroPID) + guiflag + " " + worldfile + " &")
         else:
             raise Exception("Pyrobot Simulator file not found: '%s'" %
                             file)
     print "Loading.",
     sys.stdout.flush()
     wait = None
     if type(share.config) != type(0):
         wait = share.config.get("gui", "sim_start_delay")
     if wait == None:
         time.sleep(1)  # default
     elif wait:
         time.sleep(float(wait))
     print ".",
     sys.stdout.flush()
コード例 #31
0
ファイル: vis.py プロジェクト: Zinebl/Pyro-Robotics-OSX
      self.canvas.tag_lower('label', 'cell')
      self.canvas.update()

   def show_labels(self):
      self.canvas.tag_raise('label', 'cell')
      self.canvas.tag_lower('traincount', 'cell')
      self.canvas.tag_lower('mapcount', 'cell')
      self.canvas.update()

   
if __name__ == "__main__":
   def pause():
      print "Press [Enter] to continue...",
      raw_input();
   #mysom = VisPsom(file='ex.cod', vis_vectortype="Hinton")
   mysom = VisPsom(file=pyrobotdir() + '/brain/psom/ex.cod')
   mydataset = dataset(file=pyrobotdir() + '/brain/psom/ex.dat')
   mysom.init_training(0.02,4.0,5005)
   print "---> Begin training from dataset..."
   mysom.timing_start()
   mysom.train_from_dataset(mydataset)
   mysom.timing_stop()
   ttime = mysom.get_training_time()
   print "---> 5000 Training steps complete: %s seconds" % ttime
   pause()
   print "---> Training..."
   mysom.train(vector([30.0, 20.0, -.3, -.8, 400.0]))
   pause()
   print "---> Training..."
   mysom.train(vector([14.0, 10.0, .3, -.8, 400.0]))
   pause()
コード例 #32
0
    )
    print "Do you want to run test 1: create bitmap, blobify, and display results? ",
    if sys.stdin.readline().lower()[0] == "y":
        print "Running..."
        bitmap.display()
        myblobdata = Blobdata(bitmap)
        myblobdata.sort("area")
        myblobdata.display()
        print "Done!"
    else:
        print "skipping..."
    print "Do you want to run test 2: create image from file, save it back out? ",
    if sys.stdin.readline().lower()[0] == "y":
        print "Running..."
        image = PyrobotImage(0, 0)
        image.loadFromFile(pyrobotdir() + "/vision/snaps/som-1.ppm")
        image.saveToFile("test2.ppm")
        print "Done! To see output, use 'xv test2.ppm'"
    else:
        print "skipping..."
    print "Do you want to run test 2.25: image shrinking? ",
    if sys.stdin.readline().lower()[0] == "y":
        print "Running..."
        from time import clock

        tavg = clock()
        newimage = image.getShrunkenImage(mode="average")
        tavg = clock() - tavg
        newimage.saveToFile("test2.25_avg.ppm")
        tsmp = clock()
        newimage = image.getShrunkenImage(mode="sample")
コード例 #33
0
ファイル: RLWorld.py プロジェクト: Zinebl/Pyro-Robotics-OSX
    def __init__(self, root, width, height):
        Tkinter.Toplevel.__init__(self, root)

        self.inaccessible = [(-1,-1),\
                             ( 4, 2),( 5, 2),( 6, 2),( 4, 3),( 5, 3),( 6, 3),\
                             ( 9, 2),(10, 2),(11, 2),( 9, 3),(10, 3),(11, 3),( 9, 4),(10, 4),(11, 4),\
                             (13, 1),(14, 1),(13, 2),(14, 2),(13, 3),(14, 3),(13, 4),(14, 4),\
                             (3,6),(4,6),(5,6),(3,7),(4,7),(5,7),(3,8),(4,8),(5,8),(3,9),(4,9),(5,9),\
                             (7,6),(8,6),     (7,7),(8,7),     (7,8),(8,8),    \
                             (6,9),(7,9),(8,9),     (6,10),(7,10),(8,10),(9,10),(10,10),(6,11),(7,11),\
                             (8,11),(9,11),(10,11),(6,12),(7,12),(8,12),(9,12),(6,13),(7,13),(8,13),\
                             (11,6),(12,6),(13,6),(11,7),(12,7),(13,7),(11,8),(12,8),(13,8),\
                             (0,11),(1,11),(2,11),(0,12),(1,12),(2,12),(0,13),(1,13),(2,13),(0,14),(1,14),(2,14)];
    
	self.path_color        = "#5ee563"
	self.visited_color     = "#c5c5c5"
        self.current_pos_color = "#00AF32"
	self.inaccessible_color= "black"
	self.gridline_color    = "black"
	self.background_color  = "white"

        self.path    = []
        self.visited = []
	self.pits    = []
	self.goal    = []

	self.goal_id = -1
	self.pit_ids = []

        # how many states ?
        self.num_squares_x = 15
        self.num_squares_y = 15

        self.squares     = resize(   0,(self.num_squares_x,self.num_squares_y)); 

        # various object members
        self.done    = 0
        self.quit    = 0
        self.root    = root
        self.width   = width
        self.height  = height
        self.complete = 0

        # various tk objects
        self.title("SymbolicSimulator: RLWorld")
        self.canvas = Tkinter.Canvas(self,width=self.width,height=self.height,bg="black")
        self.canvas.pack()
        self.winfo_toplevel().protocol('WM_DELETE_WINDOW',self.destroy)

        # set height and width of images
        self.square_height = self.width  / self.num_squares_x;
        self.square_width  = self.height / self.num_squares_y;

        # goal image
        goldFilename = pyrobotdir() + "/images/rlgoal.gif" 
        goldImage = Image.open(goldFilename)
        goldImage = goldImage.resize( [self.square_height-2, self.square_width-2] )
        self.goldImageTk = ImageTk.PhotoImage(goldImage)

        # pit image
        pitFilename = pyrobotdir() + "/images/rlpit.gif" 
        pitImage = Image.open(pitFilename)
        pitImage = pitImage.resize( [self.square_height-2, self.square_width-2] )
        self.pitImageTk = ImageTk.PhotoImage(pitImage, height=self.square_height, width=self.square_width)

	for i in range(0, self.num_squares_x):
	  for j in range(0, self.num_squares_y):
            self.squares[i][j] = self.canvas.create_rectangle( i*self.square_width, j*self.square_height,
                            	        (i+1)*self.square_width - 1, (j+1)*self.square_height - 1,
                                	fill= self.background_color, tag = "square-%d-%d" % (i,j));

        # initialize the world
        self.initWorld()
        self.resetStates()
        
        # used by simulator
        self.properties = ["location", "obstacles", "goal", "home", \
                           "final", "visited", "complete", \
                           "pits", "path"]

        self.movements = ["up", "right", "down", "left"]
        self.ports = [60000]

        # start things off
        self.redraw()
        self.drawInaccessible()
コード例 #34
0
ファイル: __init__.py プロジェクト: is44c/pyrobot
 def loadSimulator(self, file, worldfile):
    """Finds and loads the simulator."""
    import string
    options = string.split(file)
    guiflag = ''
    simulatorName = file.split('/')[-1]
    pyroPID = os.getpid()
    if simulatorName[-6:] == "Server":
       configDirName = simulatorName[:-6]
       if system.file_exists(worldfile):
          pass # leave it alone
       elif (pyrobotdir() != None and
             system.file_exists( pyrobotdir() + \
                                 '/plugins/configs/%s/%s' %
                                 (configDirName, worldfile))):
          worldfile = pyrobotdir() + \
                      '/plugins/configs/%s/%s' % (configDirName, worldfile)
       if self.config.get("pyrobot", "gui") .lower() == 'tty':
          guiflag = '-g'
       if system.file_exists(options[0]):
          os.system(file + (" %d " % pyroPID) + guiflag + " " + worldfile + " &")
       elif (pyrobotdir() != None and
             system.file_exists(pyrobotdir() + \
                                '/plugins/simulators/' + options[0])):
          os.system(pyrobotdir() + '/plugins/simulators/' + file + \
                    (" %d " % pyroPID) + guiflag + " " + worldfile + " &")
       else:
          raise Exception("Pyrobot Server file not found: '%s'" % file)
    else:
       # Ends with "Simulator"
       simDirName = simulatorName[:-9]
       if system.file_exists(worldfile):
          pass # leave it alone
       elif (pyrobotdir() != None and
             system.file_exists( pyrobotdir() + \
                                 '/plugins/worlds/%s/%s' %
                                 (simDirName, worldfile))):
          worldfile = pyrobotdir() + \
                      '/plugins/worlds/%s/%s' % (simDirName, worldfile)
       if self.config.get("pyrobot", "gui") .lower() == 'tty':
          guiflag = '-g'
       if system.file_exists(options[0]):
          os.system(file + (" %d " % pyroPID)+ guiflag + " " + worldfile + " &")
       elif (pyrobotdir() != None and
             system.file_exists(pyrobotdir() + \
                                '/plugins/simulators/' + options[0])):
          os.system(pyrobotdir() + '/plugins/simulators/' + file + \
                    (" %d " % pyroPID) + guiflag + " " + worldfile + " &")
       else:
          raise Exception("Pyrobot Simulator file not found: '%s'" % file)
    print "Loading.",
    sys.stdout.flush()
    wait = None
    if type(share.config) != type(0):
       wait = share.config.get("gui", "sim_start_delay")
    if wait == None:
       time.sleep(1) # default
    elif wait:
       time.sleep(float(wait)) 
    print ".",
    sys.stdout.flush()
コード例 #35
0
    def show_labels(self):
        self.canvas.tag_raise('label', 'cell')
        self.canvas.tag_lower('traincount', 'cell')
        self.canvas.tag_lower('mapcount', 'cell')
        self.canvas.update()


if __name__ == "__main__":

    def pause():
        print "Press [Enter] to continue...",
        raw_input()

    #mysom = VisPsom(file='ex.cod', vis_vectortype="Hinton")
    mysom = VisPsom(file=pyrobotdir() + '/brain/psom/ex.cod')
    mydataset = dataset(file=pyrobotdir() + '/brain/psom/ex.dat')
    mysom.init_training(0.02, 4.0, 5005)
    print "---> Begin training from dataset..."
    mysom.timing_start()
    mysom.train_from_dataset(mydataset)
    mysom.timing_stop()
    ttime = mysom.get_training_time()
    print "---> 5000 Training steps complete: %s seconds" % ttime
    pause()
    print "---> Training..."
    mysom.train(vector([30.0, 20.0, -.3, -.8, 400.0]))
    pause()
    print "---> Training..."
    mysom.train(vector([14.0, 10.0, .3, -.8, 400.0]))
    pause()
コード例 #36
0
ファイル: __init__.py プロジェクト: agigom2233/pyrobot
 ])
 print "Do you want to run test 1: create bitmap, blobify, and display results? ",
 if sys.stdin.readline().lower()[0] == 'y':
     print "Running..."
     bitmap.display()
     myblobdata = Blobdata(bitmap)
     myblobdata.sort("area")
     myblobdata.display()
     print "Done!"
 else:
     print "skipping..."
 print "Do you want to run test 2: create image from file, save it back out? ",
 if sys.stdin.readline().lower()[0] == 'y':
     print "Running..."
     image = PyrobotImage(0, 0)
     image.loadFromFile(pyrobotdir() + "/vision/snaps/som-1.ppm")
     image.saveToFile("test2.ppm")
     print "Done! To see output, use 'xv test2.ppm'"
 else:
     print "skipping..."
 print "Do you want to run test 2.25: image shrinking? ",
 if sys.stdin.readline().lower()[0] == 'y':
     print "Running..."
     from time import clock
     tavg = clock()
     newimage = image.getShrunkenImage(mode='average')
     tavg = clock() - tavg
     newimage.saveToFile("test2.25_avg.ppm")
     tsmp = clock()
     newimage = image.getShrunkenImage(mode='sample')
     tsmp = clock() - tsmp
コード例 #37
0
    def __init__(self,
                 pattern=None,
                 start=0,
                 stop=19,
                 char="?",
                 interval=1.0,
                 visionSystem=None,
                 verbose=0):
        """
      pattern is a filename with indicators on where to put digits for the
      sequence.  Absolute or relative filenames can be used.

      For example, 'image???-.ppm' would start at 'image000.ppm'
      and continue up to stop.
      
      char is the character that should be replaced in the pattern.

      interval = how often do I get new image

      As an example, to load som-0.ppm through som-19.ppm, we could call
      FakeCamera('vision/snaps/som-?.ppm', 0, 19)
      """
        if pattern == None:
            pattern = "vision/snaps/som-?.ppm"
        self.pattern = pattern
        self.stop = stop
        self.start = start
        self.current = start
        self.setUpdateInterval(interval)
        self.verbose = verbose
        self.lastUpdate = 0
        #create a matchdata object that we will store
        self.match = re.search(re.escape(char) + "+", pattern)
        #create a format string that we can use to replace the
        #replace characters
        if self.match:
            self.fstring = "%%0%dd" % len(self.match.group())
            currname = self.pattern[:self.match.start()] + \
                       self.fstring % self.current + \
                       self.pattern[self.match.end():]
        else:
            currname = self.pattern
        if system.file_exists(currname):
            self.path = ''
        elif system.file_exists(pyrobotdir() + "/" + currname):
            self.path = pyrobotdir() + "/"
        else:
            raise ValueError, "file not found: '%s'" % currname
        if self.verbose:
            print "info: reading file '%s'..." % (self.path + currname)
        self._dev = Fake(self.path + currname)
        # connect vision system: --------------------------
        if visionSystem:
            self.vision = visionSystem
            self.vision.registerCameraDevice(self._dev)
            self.width = self.vision.getWidth()
            self.height = self.vision.getHeight()
            self.depth = self.vision.getDepth()
            self._cbuf = self.vision.getMMap()
        else:
            self.vision = None
            self.width = 0
            self.height = 0
            self.depth = 0
            self._cbuf = None
        # -------------------------------------------------
        self.rgb = (0, 1, 2)  # offsets to RGB
        self.format = "RGB"
        Camera.__init__(self, self.width, self.height, self.depth,
                        "Fake Camera View")
        self.subtype = "simulated"
        self.source = self.pattern
        self.data = CBuffer(self._cbuf)
        self.oldStart = None
        self.oldStop = None
コード例 #38
0
ファイル: __init__.py プロジェクト: Zinebl/Pyro-Robotics-OSX
   def __init__(self, pattern = None,
                start = 0, stop = 19, char = "?",
                interval = 1.0, visionSystem = None, verbose = 0):
      """
      pattern is a filename with indicators on where to put digits for the
      sequence.  Absolute or relative filenames can be used.

      For example, 'image???-.ppm' would start at 'image000.ppm'
      and continue up to stop.
      
      char is the character that should be replaced in the pattern.

      interval = how often do I get new image

      As an example, to load som-0.ppm through som-19.ppm, we could call
      FakeCamera('vision/snaps/som-?.ppm', 0, 19)
      """
      if pattern == None:
         pattern = "vision/snaps/som-?.ppm"
      self.pattern = pattern
      self.stop = stop
      self.start = start
      self.current = start
      self.setUpdateInterval(interval)
      self.verbose = verbose
      self.lastUpdate = 0
      #create a matchdata object that we will store
      self.match = re.search(re.escape(char) + "+", pattern)
      #create a format string that we can use to replace the
      #replace characters
      if self.match:
         self.fstring = "%%0%dd" % len(self.match.group())
         currname = self.pattern[:self.match.start()] + \
                    self.fstring % self.current + \
                    self.pattern[self.match.end():]
      else:
         currname = self.pattern
      if system.file_exists(currname):
         self.path = ''
      elif system.file_exists( pyrobotdir() + "/" + currname):
         self.path = pyrobotdir() + "/"
      else:
         raise ValueError, "file not found: '%s'" % currname
      if self.verbose:
         print "info: reading file '%s'..." % (self.path + currname)
      self._dev = Fake(self.path + currname)
      # connect vision system: --------------------------
      if visionSystem:
         self.vision = visionSystem
         self.vision.registerCameraDevice(self._dev)
         self.width = self.vision.getWidth()
         self.height = self.vision.getHeight()
         self.depth = self.vision.getDepth()
         self._cbuf = self.vision.getMMap()
      else:
         self.vision = None
         self.width = 0
         self.height = 0
         self.depth = 0
         self._cbuf = None
      # -------------------------------------------------
      self.rgb = (0, 1, 2) # offsets to RGB
      self.format = "RGB"
      Camera.__init__(self, self.width, self.height, self.depth,
                      "Fake Camera View")
      self.subtype = "simulated"
      self.source = self.pattern
      self.data = CBuffer(self._cbuf)
      self.oldStart = None
      self.oldStop = None
コード例 #39
0
 def loadSim(self, worldfile=''):
     pyropath = pyrobotdir()
     f = self.fileloaddialog("simulators", "*", self.lastDir.get("sim", ''))
     if f != '' and f != 0:
         self.lastDir["sim"] = string.join(f.split('/')[:-1], '/')
         if worldfile == '':
             simulatorName = f.split('/')[-1]
             if simulatorName[-6:] == "Server":
                 configDirName = simulatorName[:-6]
                 worldfile = self.fileloaddialog(
                     "configs", "*.cfg",
                     self.lastDir.get(
                         "%s-config" % simulatorName,
                         "%s/plugins/configs/%s/" %
                         (pyropath, configDirName)))
                 if worldfile == "":
                     return
                 self.lastDir["%s-config" % simulatorName] = string.join(
                     worldfile.split('/')[:-1], '/')
             else:
                 # ends with "Simulator"
                 simDirName = simulatorName[:-9]
                 if simulatorName == "PyrobotSimulator":
                     worldfile = self.fileloaddialog(
                         "worlds", "*.py",
                         self.lastDir.get(
                             "%s-world" % simulatorName,
                             "%s/plugins/worlds/%s/" %
                             (pyropath, simDirName)))
                 elif simulatorName == "StageSimulator":
                     worldfile = self.fileloaddialog(
                         "worlds", "*.cfg",
                         self.lastDir.get(
                             "%s-world" % simulatorName,
                             "%s/plugins/worlds/%s/" %
                             (pyropath, simDirName)))
                 else:
                     worldfile = self.fileloaddialog(
                         "worlds", "*.world",
                         self.lastDir.get(
                             "%s-world" % simulatorName,
                             "%s/plugins/worlds/%s/" %
                             (pyropath, simDirName)))
                 if worldfile == "" or worldfile == 0:
                     return
                 self.lastDir["%s-world" % simulatorName] = string.join(
                     worldfile.split('/')[:-1], '/')
         else:
             simulatorName = worldfile
             self.lastDir["%s-world" % simulatorName] = string.join(
                 worldfile.split('/')[:-1], '/')
         self.engine.worldfile = worldfile
         self.engine.simfile = f
         pyroPID = os.getpid()
         if os.name in ['nt', 'dos', 'os2']:
             # FIXME: this assumes program to run is a python program, but theres is only
             # one such simulator
             cmd = 'start "simulator" "%s" "%s" %d "%s"' % (
                 sys.executable, f, pyroPID, worldfile)
             print cmd
             os.system(cmd)
         elif os.name in ['posix']:
             os.system(f + (" %d " % pyroPID) + worldfile + " &")
         else:
             raise AttributeError, "your OS (%s) is not supported" % os.name