コード例 #1
0
  def ToXML(self):
    '''! Return a XML version of the simulator
    '''
    # House keeping data
    doc = sandboXML('scenario')
    doc.root.setAttribute('simulator','sandbox')
    doc.root.setAttribute('version', self.version)

    # Identifiers
    doc.AddField('name',self.OS['gametag'],doc.root)
    
    # Map
    doc.AddField('map',self.map.mapenv, doc.root)
    
    # Clock
    doc.AddNode(doc.DateTime('clock',self.clock))
    
    # Infrastructure
    if hasattr(self, 'serializeinfrastructure'):
      infra = doc.NewNode('infrastructures')
      imprt = doc.NewNode('network')
      doc.SetAttribute('import', 'infrastructure.xml',imprt)
      doc.AddNode(imprt, infra)
      doc.AddNode(infra, doc.root)
    
    # sides
    for side_name in self.sides.keys():
      # Create side node and add a few pieces of information
      side = doc.NewNode('side')
      doc.AddField('name',side_name,side)
      doc.AddField('color',self.sides[side_name],side,type='RGB')
      # Write the OOB
      oob = doc.NewNode('OOB')
      for unit in self.GetOOB(color=side_name):
        # Create a link in the Scenario definition
        unode = doc.NewNode('unit')
        doc.SetAttribute('import', unit.GetName(),unode)
        doc.AddNode(unode,oob)
        # Triggers the writing of the unit's state
        path = os.path.join(unit.FolderName(),'current.xml')
        unitdoc = sandboXML('sandbox')
        unitdoc.AddNode(unit.toXML(unitdoc),unitdoc.root)
        with open(path,'w') as fout:
          fout.write(str(unitdoc))
        
        
      doc.AddNode(oob, side)
      
      # Add to the main document
      doc.AddNode(side, doc.root)
      
    
    
    return str(doc)
コード例 #2
0
    def testReadWriteContact(self):
        # Read in
        x = self.GetTest('test unit')

        # Write out
        from sandbox_XML import sandboXML
        xml = sandboXML('tests')
        xml.AddNode(x.toXML(xml), xml.root)

        # Read again
        y = xml.Get(xml.root, 'contact')

        out = []

        # Compare fields
        out.append(
            set(x.fields.keys()).difference(set(y.fields.keys())) == set())
        out.append(
            set(y.fields.keys()).difference(set(x.fields.keys())) == set())
        for k in x.fields.keys():
            out.append(x.GetField(k) == y.GetField(k))

        # unit
        out.append(x.unit == y.unit)
        out.append(x.timestamp == y.timestamp)
        out.append(x.rating == y.rating)

        self.assertEqual(out.count('False'), 0)
コード例 #3
0
ファイル: sandbox_graphics.py プロジェクト: hsoula/opcon
    def testWriteOverlaytoKML(self):
        # file to load
        import os
        filename = os.path.join(os.environ['OPCONhome'],'tests','overlay.xml')
        from sandbox_XML import sandboXML
        doc = sandboXML(read=filename)
        ovnode = doc.Get(doc.root, 'OVERLAY')

        # Write to KML
        from Renderer_kml import KML_renderer
        kml = KML_renderer('kandahar_small')
        
        # Blank overlay
        ov = operational_overlay()
        ov.fromXML(doc, ovnode)
        ov.InternalCoordinates(kml.map.MGRS)
        
        
        out = kml.WriteOverlay(ov)
        
        # Write to a KML file
        from pysmirk import KMLDocument
        x = KMLDocument('test_overlay.kml')
        x.AddItem(out)
        x.WriteXML()
        
        self.assertTrue(out)
コード例 #4
0
ファイル: sandbox_map.py プロジェクト: hsoula/opcon
  def Initialize(self):
    '''! \brief Read in the XML definition and take appropriate action
    '''
    if not os.access(os.path.join(self.path,'main.xml'),os.F_OK):
      raise 'InvalidMapDefinition'
    
    # Obtain XML
    doc = sandboXML(read=os.path.join(self.path,'main.xml'))
    
    # Load Graphics
    f = doc.Get(doc.root,'filename')
    if f:
      self.graphics = Image.open(os.path.join(self.path,f))
      self.graphicfile = os.path.join(self.path,f)
    
    # Load Terrain
    self.ParseXMLterrain( doc, doc.Get(doc.root,'terrain') )
        
    # Load friction data
    self.frictions = {'':{}}
    self.ParseXMLfrictions( doc, doc.Get(doc.root, 'friction') )

    # Metadata and linear parameters
    self.ParseXMLData(doc, doc.root)
    
    # Setup Flatland
    self.MGRS = sandbox_FlatLand()
    self.MGRS.Bind( self.data['ref XY'],self.data['ref coord'],)
    
    # Do we need to keep this?
    #self.copy = self.terrain.copy()
    #self.TerrainDraw = ImageDraw.Draw(self.copy)
    self.copy = self.TerrainDraw = None
コード例 #5
0
ファイル: intelligence.py プロジェクト: hsoula/opcon
 def testReadWriteContact(self):
   # Read in
   x = self.GetTest('test unit')
   
   # Write out
   from sandbox_XML import sandboXML
   xml = sandboXML('tests')
   xml.AddNode(x.toXML(xml), xml.root)
   
   # Read again
   y = xml.Get(xml.root, 'contact')
   
   out = []
   
   # Compare fields
   out.append(set(x.fields.keys()).difference(set(y.fields.keys())) == set())
   out.append(set(y.fields.keys()).difference(set(x.fields.keys())) == set())
   for k in x.fields.keys():
     out.append(x.GetField(k) == y.GetField(k))
     
   # unit
   out.append(x.unit == y.unit)
   out.append(x.timestamp == y.timestamp)
   out.append(x.rating == y.rating)
   
   self.assertEqual(out.count('False'),0)
コード例 #6
0
    def testWriteOverlaytoKML(self):
        # file to load
        import os
        filename = os.path.join(os.environ['OPCONhome'], 'tests',
                                'overlay.xml')
        from sandbox_XML import sandboXML
        doc = sandboXML(read=filename)
        ovnode = doc.Get(doc.root, 'OVERLAY')

        # Write to KML
        from Renderer_kml import KML_renderer
        kml = KML_renderer('kandahar_small')

        # Blank overlay
        ov = operational_overlay()
        ov.fromXML(doc, ovnode)
        ov.InternalCoordinates(kml.map.MGRS)

        out = kml.WriteOverlay(ov)

        # Write to a KML file
        from pysmirk import KMLDocument
        x = KMLDocument('test_overlay.kml')
        x.AddItem(out)
        x.WriteXML()

        self.assertTrue(out)
コード例 #7
0
 def testLoadfromXML(self):
   # Test files
   filename = os.path.join(os.environ['OPCONhome'], 'tests', 'opord.xml')
   
   # Get the XML data
   from sandbox_XML import sandboXML
   doc = sandboXML(read=filename)
   opord = doc.Get(doc.root, 'COMM')
   opord.SetMSR('ROUTE BLUE')
   
   # Write the node info
   newopordnode = opord.toXML(doc)
   outxml = sandboXML('COMMS')
   outxml.AddNode(newopordnode, outxml.root)
   with open(os.path.join(os.environ['OPCONhome'], 'tests', 'testOPORD.xml'),'w') as fout:
     fout.write(str(outxml))
   
   # Test for the structure of the OPORD
   self.assertTrue(opord)
コード例 #8
0
 def testWriteOPORDtoXML(self):
   # Test files
   filename = os.path.join(os.environ['OPCONhome'], 'tests', 'opord.xml')
   
   # Get the XML data
   from sandbox_XML import sandboXML
   doc = sandboXML(read=filename)
   opord = doc.Get(doc.root, 'COMM')
   
   # Write to an XML node
   doc.AddNode(opord.toXML(doc))
コード例 #9
0
 def LoadNetwork(self, fname):
   '''! \brief Load network infrastructure from the map XML file.
   '''
   if self.network == None:
     self.network = sandbox_network()
   try:
     doc = sandboXML(read=fname)
     self.network.LoadFromXML(doc)
   except:
     pass
     
   return self.network
コード例 #10
0
  def LoadFromFile(self, filename):
    ''' Load a scenario and execute the command in the XML, if any. 
    '''
    # Determine whether it is a scenario or a savegame.
    if filename.endswith('.xml'):
      # This should be read from the scenario folder
      fname = os.path.join('.','scenarios',filename)
      if not os.path.exists(fname):
        raise SandboxException('ScenarioNotFound', filename)
      
      # Read from XML
      # Load the Scenario definition
      xml = sandboXML(read=fname)
      self.fromXML(xml, xml.root)

      # Create a folder structure
      pass
    
      return True
    
    else:
      # Opens and existing scenario for which there should be a folder.
      fname = os.path.join('.','Simulations', filename.replace(' ', '_'))
      if not os.path.exists(fname):
        raise SandboxException('SaveGameNotFound', filename)
      
      # Find the most recent savegame
      fname = os.path.join('.',fname, 'current.xml')
      if not os.path.exists(fname):
        raise SandboxException('SaveGameFileNotFound', fname)
      
      # Load the file
      xml = sandboXML(read=fname)
      self.fromXML(xml, xml.root)
      
      # Ensure that all COC pointers are valid
      pass
    
      return True
コード例 #11
0
    def Duplicate(self, encode=None):
        '''
       Make a copy of self into a new instance, used when a contact is reported to more than 1 recipient.
       encode : make the instance pickle-safe.
    '''
        # Write out
        from sandbox_XML import sandboXML
        xml = sandboXML('tests')
        xml.AddNode(self.toXML(xml), xml.root)

        # Read again
        out = xml.Get(xml.root, 'contact')

        # Preserve the pointer type if no encoding is required.
        if not encode:
            out.unit = self.unit

        return out
コード例 #12
0
ファイル: intelligence.py プロジェクト: hsoula/opcon
 def Duplicate(self, encode = None):
   '''
      Make a copy of self into a new instance, used when a contact is reported to more than 1 recipient.
      encode : make the instance pickle-safe.
   '''
   # Write out
   from sandbox_XML import sandboXML
   xml = sandboXML('tests')
   xml.AddNode(self.toXML(xml), xml.root)
   
   # Read again
   out = xml.Get(xml.root, 'contact')
   
   # Preserve the pointer type if no encoding is required.
   if not encode:
     out.unit = self.unit
     
   return out
コード例 #13
0
ファイル: sandbox_graphics.py プロジェクト: hsoula/opcon
 def testOverlayfromXML(self):
     # Create a flatland instance and bind it to EPW control measure as 0,0
     from FlatLand import FlatLand
     flatland = FlatLand()
     flatland.Bind(vect_3D(), '41 R 763672 3502932')
     
     # file to load
     import os
     filename = os.path.join(os.environ['OPCONhome'],'tests','overlay.xml')
     from sandbox_XML import sandboXML
     doc = sandboXML(read=filename)
     ovnode = doc.Get(doc.root, 'OVERLAY')
     
     # Blank overlay
     ov = operational_overlay()
     ov.fromXML(doc, ovnode)
     ov.InternalCoordinates(flatland)
     
     # Test
     self.assertEqual(type(vect_3D()),type(ov.GetElement('EPW RED').GetShape()))
コード例 #14
0
    def testOverlayfromXML(self):
        # Create a flatland instance and bind it to EPW control measure as 0,0
        from FlatLand import FlatLand
        flatland = FlatLand()
        flatland.Bind(vect_3D(), '41 R 763672 3502932')

        # file to load
        import os
        filename = os.path.join(os.environ['OPCONhome'], 'tests',
                                'overlay.xml')
        from sandbox_XML import sandboXML
        doc = sandboXML(read=filename)
        ovnode = doc.Get(doc.root, 'OVERLAY')

        # Blank overlay
        ov = operational_overlay()
        ov.fromXML(doc, ovnode)
        ov.InternalCoordinates(flatland)

        # Test
        self.assertEqual(type(vect_3D()),
                         type(ov.GetElement('EPW RED').GetShape()))
コード例 #15
0
 def LoadSide(self, doc, node):
   '''! \brief Load a side and all associated information into the simulator.
   '''
   # Color name
   self.sides[doc.Get(node,'name').upper()] = doc.Get(node,'color')
   
   # OOB 
   oob = doc.Get(node,'OOB')
   # Make sure that there is a OOB node in the side node
   if oob != '':
     for unit in doc.Get(oob,'unit', True):
       # CASE 1: The unit must be imported
       if doc.Get(unit, 'import'):
         name = doc.Get(unit, 'import').replace('/','.')
         # Form a correct path
         path = os.path.join(self.OS['savepath'], doc.Get(node,'name'), name, 'current.xml')
         # Read in the unit's description
         if os.path.exists(path):
           udoc = sandboXML(read=path)
           x = udoc.Get(udoc.root, 'unit')
           # Look for a template definition
           x = sandbox_entity(sim=self,template=udoc.Get(x,'template'))
           del udoc
         else:
           raise SandboxException('UnitDescriptionNotFound',path)
       
       # CASE 2: The units must be loaded from this file
       else:
         # Add Side information
         doc.AddField('side', doc.Get(node,'name').upper(), unit)
         # Build unit from template
         x = sandbox_entity(sim=self,template=doc.Get(unit,'template'))
   
       # Read in the state data
       x.fromXML(doc, unit)
 
       # Add to world
       self.AddEntity(x)
コード例 #16
0
  def fromXML(self, doc, scenario):
    '''! \brief Either parse a XML scenario document at the scenario node level.
    '''
    # Name and file system
    self.OS['gametag'] = doc.Get(scenario,'name')
    self.OS['savepath'] = os.path.join(os.getcwd(),'Simulations',self.OS['gametag'].replace(' ','_'))
    if doc.Get(scenario,'reset'):
      self.fileStructure(self.OS['gametag'])
    
    # Set clock
    self.clock = doc.Get(scenario, 'clock')
    self.lastpulse = doc.Get(scenario, 'clock')
    
    # Map
    x = doc.Get(scenario,'map')
    self.map = sandbox_map(x)
    
    # Infrastructure to load
    inf = doc.Get(scenario,'infrastructures')
    if inf:
      self.serializeinfrastructure = True
      # Make a Copy of this node to the savegame
      if not os.path.exists(self.OS['savegame'],'infrastructure.xml'):
        fout = open(os.path.exists(self.OS['savegame'],'infrastructure.xml'),'w')
        fout.write('<?xml version="1.0"?>\n')
        fout.write(doc.WriteNode(inf))
        fout.close()
      
      # Read the data
      if doc.Get(inf,'default') == 1:
        # Load the map definition infrastructure
        if os.access(self.map.infrastructurefile,os.F_OK):
          self.network.LoadFromXML(sandboXML(read=self.map.infrastructurefile))
        else:
          raise 'DefaultInfrastructureNotFound'
        
      for n in doc.Get(inf, 'network', True):
        # Case of import network nodes
        if doc.Get(n,'import'):
          fname = os.path.join(os.getcwd(),'scenario',doc.Get(n,'import'))
          if not fname.endswith('.xml'):
            fname += '.xml'
          if os.access(fname,os.F_OK):
            self.network.LoadFromXML(sandboXML(fname))
        else:
          # Directly load node into infrastructure
          self.network.LoadFromXML(doc, n)
          
    else:
      # Load the map definition infrastructure
      if os.access(self.map.infrastructurefile,os.F_OK):
        self.network.LoadFromXML(sandboXML(read=self.map.infrastructurefile))
      else:
        raise 'DefaultInfrastructureNotFound'
      
    # Load sides and OOB
    for side in doc.Get(scenario, 'side', True):
      self.LoadSide(doc, side)

    # Check for an execute node
    exe = doc.Get(scenario, 'execute')
    if exe:
      for cmd in doc.Get(exe, 'cmd', True):
        # A list of command
        methodname = doc.Get(cmd, 'method')
        # If the method exists, call it right away.
        if hasattr(self, methodname):
          getattr(self, methodname)()
        else:
          raise SandboxException('ExecuteScenarioError',methodname)
コード例 #17
0
ファイル: intelligence.py プロジェクト: hsoula/opcon
 def setUp(self):
   from sandbox_XML import sandboXML
   # Get the XML test file
   os.chdir(os.environ['OPCONhome'])
   self.doc = sandboXML(read="./tests/contacts.xml")
コード例 #18
0
ファイル: sandbox_map.py プロジェクト: hsoula/opcon
 def AsXML(self):
   '''! \brief A XML render of the map data.
   '''
   doc = sandboXML('map')
   root = doc.root
   
   # Name
   doc.AddField('name',self.mapenv, root)
   # filename
   fn = os.path.split(self.graphicfile)[-1]
   doc.AddField('filename',fn, root)
   # width
   doc.AddField('width',self.data['width'],root)
   # Climate
   doc.AddField('climate', self.data['climate'], root)
   # ref coord
   doc.AddField('ref_coord', self.data['ref coord'],root)
   # ref XY
   doc.AddNode(doc.write_vector_5D('ref_XY',self.data['ref XY']), root)
   
   # Terrain definition
   F = doc.NewNode('terrain')
   doc.SetAttribute('filename',os.path.split(self.terrainfile)[-1],F)
   for i in self.code_terrain:
     nn = doc.NewNode('class')
     doc.SetAttribute('name', i,nn)
     a = self.code_terrain[i]
     doc.AddField('color', '%d,%d,%d'%tuple(a), nn, 'RGB')
     doc.AddNode(nn,F)
   
   doc.AddNode(F,root)
   
   # Frictions
   ref = self.frictions['']
   fr = doc.NewNode('friction')
   for i in self.frictions:
     if i == 'sameas':
       continue
     if i == '':
       # base case
       nn = doc.NewNode('mode')
       doc.SetAttribute('name', 'base', nn)
       for j in self.frictions[i]:
         doc.AddField('terrain', str(self.frictions[i][j]),nn,name= j)
       doc.AddNode(nn, fr)
     else:
       nn = doc.NewNode('mode')
       doc.SetAttribute('name', i, nn)
       if i in self.frictions['sameas']:
         doc.SetAttribute('sameas', self.frictions['sameas'][i], nn)
         ref = self.frictions[ self.frictions['sameas'][i] ]
       else:
         ref = self.frictions['']
       for j in self.frictions[i]:
         if self.frictions[i][j] != ref[j]:
           doc.AddField('terrain', str(self.frictions[i][j]),nn,name= j)
       doc.AddNode(nn, fr)
       
   doc.AddNode(fr, root)
         
   
   return doc
コード例 #19
0
 def setUp(self):
     from sandbox_XML import sandboXML
     # Get the XML test file
     os.chdir(os.environ['OPCONhome'])
     self.doc = sandboXML(read="./tests/contacts.xml")