Ejemplo n.º 1
0
    def fromXML(self, doc, node):
        '''! \brief Populate instance from XML node.
         Effect:
               - signature under a series of stances.
               - sensors listing.
    '''
        # Signatures
        for sig in doc.Get(node, 'signature', True):
            tp = doc.Get(sig, 'type')
            level = doc.Get(sig, 'level')

            # Sameas attribute
            sameas = doc.Get(sig, 'sameas')
            if sameas:
                if sameas in self.signature:
                    self.signature[tp] = self.signature[sameas]
                else:
                    raise SandboxException('XMLParseSameAsInvalid',
                                           ['intelligence', tp, sameas])
                continue

            # Basal level has an empty label
            self.SetSignature(tp, level)

            # Read labels exeptions
            for pr in [
                    'very_likely', 'likely', 'neutral', 'unlikely',
                    'very_unlikely'
            ]:
                x = doc.Get(sig, pr)
                if x != '':
                    for label in x.split(','):
                        label = label.strip()
                        self.SetSignature(tp, pr.replace('_', ' '), label)
Ejemplo n.º 2
0
 def SetBaseProb(self, x):
     ''' The first thing to do when setting up.
     '''
     # from a concept
     if x in self.concept:
         self.base_prob = self.concept[x]
     else:
         raise SandboxException('TOEM: Invalid concept.', x)
Ejemplo n.º 3
0
 def GetLocation(self, name):
   '''! \brief Return the location as a vector designated by name in the format specified by output.
   '''
   node = self.network.GetNode(name)
   if node:
     if node.Coordinates():
       name = node.Coordinates()
     else:
       raise SandboxException('InfrastructureNodeLookupError', name)
   
   # Is it a coordinate?
   v = self.map.MGRS.AsVect(name)
   
   if v:
     return v
   
   raise SandboxException('LocationLookupError', name)
Ejemplo n.º 4
0
 def GetTemplate(self, tname=''):
   ''' Opens the template and returns it as a string, use tname if provided instead of hthe self.template
   '''
   if not tname:
     tname = self.template
   try:
     self.report = open(os.path.join(os.environ['OPCONhome'],'COMM',tname)).read()
   except:
     raise SandboxException('COMMTemplateNotFound',tname)
Ejemplo n.º 5
0
 def GetArea(self, name, infrastructure = ''):
   '''! \brief Retrieve the area covered by the name. If infrastructure is provided, will limit area to infrastructure named as such.
         If the infrastructure exists, but has no footprint, return the node's area instead to avoid errors.
   '''
   node = self.network.GetNode(name)
   if not node:
     raise SandboxException('InfrastructureNodeLookupError', name)
   # return the area of the node.
   if not infrastructure:
     return node.AsArea()
   else:
     for i in node.Infrastructures():
       if i.name == infrastructure:
         if i.footprint:
           return i.footprint
         else:
           raise SandboxException('InfrastructureAreaLookupError', (name, infrastructure))
         
     return node.AsArea()
Ejemplo n.º 6
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
Ejemplo n.º 7
0
    def UpdateFieldsFromList(self, E, cnt, fields):
        ''' Fetch the correct information from the target unit for each field
    '''
        # tgt unit
        tgt = cnt.unit

        # Cycle
        for fd in fields:
            methodname = 'ExtractField' + fd
            if hasattr(self, methodname):
                # Call the method
                cnt.UpdateField(fd,
                                getattr(self, methodname)(E, tgt),
                                mytime=E.sim.clock)
            else:
                raise SandboxException('ExtractFieldError', fd)

        pass
Ejemplo n.º 8
0
    def ReadFile(self, fname):
        # Read in the file and index the instances into the data dictionary
        # Test for the file's existance
        x = os.path.join(self.datafolder, fname)
        if not os.path.exists(x):
            raise SandboxException('DataFileNotFound', x)

        # Create a XML document
        x = sandboXML(read=x)
        if not x.root.tagName == 'templates':
            raise

        # Nodes
        for node in x.ElementAsList(x.root):
            # Imported file
            if node.tagName == 'import':
                self.ReadFile(x.Get(node, 'name'))
            for cnode in x.ElementAsList(node):
                # Data node
                if not cnode.tagName in self.data:
                    self.data[cnode.tagName] = {}
                self.data[cnode.tagName][x.Get(cnode, 'name')] = (cnode, x)
Ejemplo n.º 9
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)
Ejemplo n.º 10
0
  def RelativePositionTo(self, name, bearing, distance):
    '''! \brief Provide the ability to specify position in the simulation that are relative to named positions.
          INPUT:
            name      [string] the name of a node in the network.
            bearing   [*] either a bearing string (see list b below) or an angle in radians
            distance  [float] The distance in km from the node
          OUTPUT:
            A vector instance for the requested position
    '''
    # Get the reference point in the simulator in flat coordinates.
    v = self.GetLocation(name)
    
    if type(bearing) == type(''):
      # Textual bearing are acceptable
      b = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW']

      if bearing in b:
        bearing = b.index(bearing) * (2*pi / 16.0)
      else:
        raise SandboxException('InvalidTextualBearing',[name,bearing,distance])
    
    # Solve vector with such bearing
    return v.ToBearing([bearing, distance])
Ejemplo n.º 11
0
  def fromXML(self, doc, node):
    # Read templates and data from XML to populate the data fields.
    # Identity, size and echelon
    self['name'] = doc.SafeGet(node, 'identity', self.GetName())
    self['side'] = doc.SafeGet(node, 'side', self['side'])
    self['size'] = doc.SafeGet(node, 'size', self['size'])
    self['command_echelon'] = doc.SafeGet(node, 'command_echelon', self['command_echelon'])
    
    # Deploment Status
    self['stance'] = doc.SafeGet(node, 'stance', self['stance'])
    self['dismounted'] = bool(doc.SafeGet(node, 'dismounted', self['dismounted']))
    self['readiness'] = doc.SafeGet(node, 'readiness', self['readiness'])
    
    # Position descriptor ###################################
    # Fetch the node, either a pos_desc or location
    ploc = doc.Get(node, 'location')
    if ploc != '':
      # Check for type of location
      loctype = doc.Get(ploc, 'type')
      if loctype == '':
        raise SandboxException('NoTypedLocation',self.GetName())
      if loctype == 'coordinates':
        # Get the content of the node
        coord = doc.Get(ploc)
      elif loctype == 'named_location':
        # Get the coordinate from the network
        nd = self.sim.network.GetNode(doc.Get(ploc))
        # Get the coordinate from the node
        coord = nd.Coordinates()
      else:
        raise SandboxException('UnsupportedLocationType',[loctype,self.GetName()])
      # convert to a position vector
      self.SetPosition(self.sim.map.MGRS.AsVect(coord))
    
    # Systems #####################################################
    models = doc.Get(node,'models')
    if models != '':
      for i in ['C4I','combat','intelligence','movement','logistics']:
        # Get the model node
        x = doc.Get(models,i)
        
        # No model specified
        if x == '':
          self.sim.data.FetchData(self[i],i,'base')
        elif doc.Get(x,'template') in ['', 'base']:
          # Load base model
          self.sim.data.FetchData(self[i],i,'base')
        else:
          # Load correct template
          self.sim.data.FetchData(self[i],i,doc.Get(x,'template'))
          
        # Read the node itself
        if x:
          self[i].fromXML(doc,x)
      
    # Systems and components #######################################
    x = doc.Get(node, 'TOE')
    if x:
      z = doc.Get(x,'category')
      if z:
        self['TOE'] = z

      # Personel
      z = doc.Get(x,'personel', True)
      for it in z:
        kit = doc.Get(it,'template')
        auth = doc.Get(it,'authorized')
        count = doc.Get(it,'count')
        if count == '':
          count = auth
        self.personel[kit] = sandbox_component_state('personel', self.sim.data.Get('personel',kit), count, auth)
        
      # vehicle
      z = doc.Get(x,'vehicle', True)
      for it in z:
        kit = doc.Get(it,'template')
        auth = doc.Get(it,'authorized')
        count = doc.Get(it,'count')
        if count == '':
          count = auth
        self.vehicle[kit] = sandbox_component_state('vehicle', self.sim.data.Get('vehicle',kit), count, auth)     
      self['movement'].SetVehicles(self.vehicle.values())
      
      # Sensors TODO
      
    # Human Factors ################################################
    x = doc.Get(node, 'human_factors')
    if x:
      temp = doc.AttributesAsDict(x)
      for i in temp.keys():
        self[i] = temp[i]
        
    # Operational Orders ###########################################
    x = doc.SafeGet(node, 'OPORD', self['OPORD'])
      
        
    # Chain of command #############################################
    coc = doc.Get(node, 'chain_of_command')
    if coc:
      # HIGHER (the TOE HQ)
      hq = doc.Get(coc, 'HIGHER')
      opcon = doc.Get(coc, 'OPCON')
      subs = doc.Get(coc, 'subordinate', True)
      if self.sim:
        # The HIGHER unit
        x = self.sim.GetEntity(self['side'],hq)
        if x:
          self['HQ'] = x
        elif hq:
          self['HQ'] = hq
        
        # The OPCON unit
        x = self.sim.GetEntity(self['side'],opcon)
        if x:
          self['OPCON'] = x
        elif hq:
          self['OPCON'] = opcon
          
        # Subordinates
        for u in subs:
          # The subordinates unit
          x = self.sim.GetEntity(self['side'],u)
          if x:
            self.AddSubordinate(x)
          else:
            # Will need to be connected to the right pointer after loading the file
            self['subordinates'] = u
        
        # INTEL picture
        intel = doc.Get(node, 'intel_picture')
        if intel:
          # Read in the contacts
          for nd in doc.ElementAsList(intel):
            key = doc.Get(nd,'key')
            cnt = sandbox_contact()
            cnt.fromXML(doc, nd)
            self['contacts'][key] = cnt
Ejemplo n.º 12
0
    def fromXML(self, doc, node):
        ''' Base methods for component (personel, vehicle).
        '''
        # Kit name
        self.name = doc.Get(node, 'name')

        # Sensors
        for nd in doc.Get(node, 'sensor', True):
            template = doc.Get(nd, 'type')
            if template:
                x = self.datasource.Get('sensor', template)
            else:
                x = sandbox_sensor()
            # Read from XML
            x.fromXML(doc, nd)

            # Count
            count = doc.Get(nd, 'count')
            if not count:
                count = 1
            else:
                count = float(count)

            # Add to list
            self.sensors.append([x, count])

        # Read in logistics parameters
        temp = doc.Get(node, 'logistics')
        if temp:
            template = doc.Get(temp, 'template')
            if not template:
                template = 'base'
            self.logistics = self.datasource.Get('logistics', template)

        # Read in kit's weapons
        for x in doc.Get(node, 'weapon_system', True):
            self.weapon_systems.append(
                self.datasource.Get('weapon_system', doc.Get(x, 'template')))

        # defense
        x = doc.Get(node, 'defense_system')
        if x:
            self.defense_system = self.datasource.Get('defense_system',
                                                      doc.Get(x, 'template'))

        # Movement
        x = doc.Get(node, 'movement')
        if x:
            template = doc.Get(x, 'template')
            if not template:
                template = 'base'
        else:
            template = 'base'
        self.movement = self.datasource.Get('movement', template)

        # Criticals
        x = doc.Get(node, 'criticals')
        if x:
            for item in doc.ElementAsList(x):
                if item.tagName == 'critical':
                    # Get the data
                    pen = bool(doc.Get(item, 'penetrating'))
                    effect = doc.Get(item, 'effect')
                    wt = doc.Get(item, 'weight')
                    if not wt:
                        wt = 1.0
                    # Ensure that there is data
                    if None in [pen, effect] or '' in [pen, effect]:
                        raise SandboxException('CriticalParseError')
                    if pen:
                        pen = 'penetrating'
                    else:
                        pen = 'non-penetrating'
                    self.criticals[pen].append((effect, float(wt)))
Ejemplo n.º 13
0
 def GetInstance(self, template_name):
     if template_name in self.constructor_map:
         return self.constructor_map[template_name]()
     else:
         raise SandboxException('Data Server Instanciation Failure',
                                template_name)
Ejemplo n.º 14
0
 def SetSkillLevel(self, x):
     # Adjust with skill level
     if x in self.concept:
         self.base_prob += self.concept[x]
     else:
         raise SandboxException('TOEM: Invalid skill level.', x)
Ejemplo n.º 15
0
 def ConceptValue(self, concept):
     ''' Returns the concept's TOEM integer value. '''
     if concept in self.concept:
         return self.concept[concept]
     raise SandboxException('InvalidTOEMconcept', concept)
Ejemplo n.º 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)