def test_cbsdInsideDpaInMoveList(self):
    dpa = dpa_mgr.BuildDpa('Alameda',
                           protection_points_method='default(10,2,0,0)')
    dpa.ResetFreqRange([(3540, 3650)])
    alameda_geom = zones.GetCoastalDpaZones()['Alameda'].geometry
    # Assign grants inside the DPA and inband + OOB in mix of CatA and CatB
    np.random.seed(1234)
    cbsds_a = entities.GenerateCbsdsInPolygon(
        3, entities.CBSD_TEMPLATE_CAT_A_OUTDOOR, alameda_geom)
    cbsds_b = entities.GenerateCbsdsInPolygon(
        2, entities.CBSD_TEMPLATE_CAT_B, alameda_geom)
    cbsds_a[1] = cbsds_a[1]._replace(eirp_dbm_mhz=-100)
    cbsds_b[1] = cbsds_b[1]._replace(eirp_dbm_mhz=-100)
    grants = []
    grants.extend(entities.ConvertToCbsdGrantInfo(cbsds_a[0:2], 3550, 3560))
    grants.extend(entities.ConvertToCbsdGrantInfo(cbsds_a[2:3], 3660, 3670))
    grants.extend(entities.ConvertToCbsdGrantInfo(cbsds_b[0:1], 3550, 3570))
    grants.extend(entities.ConvertToCbsdGrantInfo(cbsds_b[1:2], 3630, 3670))
    dpa.SetGrantsFromList(grants)

    dpa.ComputeMoveLists()

    self.assertSetEqual(dpa.GetMoveList((3550, 3560)),
                        set([grants[0], grants[1], grants[3]]))
    self.assertSetEqual(dpa.GetMoveList((3640, 3650)),
                        set([grants[4]]))
    self.assertSetEqual(dpa.GetMoveList((3540, 3550)),
                        set(grants))
def FindOrBuildDpa(dpas, options, grants):
    """Find or build DPA for simulation purpose.

  If several DPA, select the one with most grants around (but DPA simulation
  options always override the logic).
  """
    if options.dpa:
        dpa_kml_file = options.dpa_kml or None
        dpa = dpa_mgr.BuildDpa(options.dpa,
                               None,
                               portal_dpa_filename=dpa_kml_file)
    else:
        if not dpas:
            raise ValueError(
                'Config file not defining a DPA and no --dpa option used.')
        if len(dpas) == 1:
            dpa = dpas[0]
        else:
            # Roughly find the DPA wth most CBSD within 200km
            all_cbsds = sgeo.MultiPoint([(g.longitude, g.latitude)
                                         for g in grants])
            num_cbsds_inside = [
                len(dpa.geometry.buffer(2.5).intersection(all_cbsds))
                for dpa in dpas
            ]
            dpa = dpas[np.argmax(num_cbsds_inside)]

    try:
        dpa.margin_db
    except AttributeError:
        dpa.margin_db = 'linear(1.5)'
    try:
        dpa.geometry
    except AttributeError:
        try:
            dpa_geometry = zones.GetCoastalDpaZones()[dpa.name]
        except KeyError:
            dpa_geometry = zones.GetPortalDpaZones(
                kml_path=dpa_kml_file)[dpa.name]
        dpa.geometry = dpa_geometry.geometry
    if options.dpa_builder:
        dpa.protected_points = dpa_builder.DpaProtectionPoints(
            dpa.name, dpa.geometry, options.dpa_builder)
    if options.margin_db:  # Override `movelistMargin` directive.
        try:
            dpa.margin_db = float(options.margin_db)
        except ValueError:
            dpa.margin_db = options.margin_db

    return dpa
  dpa_suut = dpa_mgr.Dpa(protection_points,
                         name='alt(East1)',
                         threshold=-144,
                         beamwidth=3,
                         radar_height=50,
                         freq_ranges_mhz=[channel])
  check = dpa_suut.CheckInterference(active_uut_grants,
                                     margin_db=margin_db,
                                     do_abs_check_single_uut=True)
  print 'Move list output: ' + str(dpa_uut.GetMoveListMask(channel))
  print 'Check Interference @%.2fdB margin: %s' % (margin_db, 'OK' if check else 'FAIL')


  # Simulate the BuildDpa feature for various types
  print '\n-- Test Build DPAs --'
  dpa_pt = dpa_mgr.BuildDpa('Pensacola')
  print '**Pensacola: %dpts' % len(dpa_pt.protected_points)
  print dpa_pt

  dpa_zone = dpa_mgr.BuildDpa('East3',
                              protection_points_method='default(4,2,1,1)')
  print '**East3: %dpts' % len(dpa_zone.protected_points)
  print dpa_zone

  dpa_portal = dpa_mgr.BuildDpa('BATH')
  print '**BATH: %dpts' % len(dpa_portal.protected_points)
  print dpa_portal

  dpa_inland = dpa_mgr.BuildDpa('Alameda',
                                protection_points_method='default(1000,2000,1,1,40,0.5,2)')
  print '**Alameda: %dpts' % len(dpa_inland.protected_points)
def _McpConfigRead(config):
    """Extracts DPA and grants from MCP config JSON.

  Note: returns all grants involved in the test irrespective of iteration
  process.

  Args:
    config: A JSON dictionary.

  Returns:
    A tuple (dpas, grants) where:
      dpas:  a list of objects of type |dpa_mgr.Dpa|.
      grants: a list of |data.CbsdGrantInfo|.
  """
    if ('iterationData' not in config or 'dpas' not in config
            or 'initialCbsdRequestsWithDomainProxies' not in config):
        raise ValueError(
            'Unsupported config file. Please use a MCP1 config file')

    # Build the DPAs.
    dpas = []
    for dpa_id, dpa_data in config['dpas'].items():
        dpa = dpa_mgr.BuildDpa(
            dpa_id, protection_points_method=dpa_data['points_builder'])
        # - add extra properties for the geometry and margin.
        dpa.margin_db = dpa_data['movelistMargin']
        try:
            dpa_zone = zones.GetCoastalDpaZones()[dpa_id]
        except KeyError:
            dpa_zone = zones.GetPortalDpaZones(kml_path=dpa_kml_file)[dpa_id]
        dpa.geometry = dpa_zone.geometry

        # - read also the activation list and freq range.
        dpa.activation = None
        for iter_data in config['iterationData']:
            for activation in iter_data['dpaActivationList']:
                if activation['dpaId'] == dpa_id:
                    dpa.activation = activation['frequencyRange']
                    break

        dpas.append(dpa)

    # Read the CBSDs, assuming all granted, into list of |CbsdGrantInfo|.
    # - initial stuff into SAS UUT
    grants = []
    for records in config['initialCbsdRequestsWithDomainProxies']:
        grant_requests = records['grantRequests']
        reg_requests = MergeConditionalData(
            records['registrationRequests'],
            records['conditionalRegistrationData'])
        grants.extend(
            data.getGrantsFromRequests(reg_requests,
                                       grant_requests,
                                       is_managing_sas=True))
    for record in config['initialCbsdRecords']:
        grant_request = [record['grantRequest']]
        reg_request = MergeConditionalData(
            [record['registrationRequest']],
            [record['conditionalRegistrationData']])
        grants.append(
            data.getGrantsFromRequests(reg_requests,
                                       grant_requests,
                                       is_managing_sas=True))

    # - then iterations for TH and UUT
    for iter_data in config['iterationData']:
        for th_data in iter_data['sasTestHarnessData']:
            th_grants = data.getAllGrantInfoFromCbsdDataDump(
                th_data['cbsdRecords'], is_managing_sas=False)
            grants.extend([g for g in th_grants])

        for records in iter_data['cbsdRequestsWithDomainProxies']:
            grant_requests = records['grantRequests']
            reg_requests = MergeConditionalData(
                records['registrationRequests'],
                records['conditionalRegistrationData'])
            uut_grants = data.getGrantsFromRequests(reg_requests,
                                                    grant_requests,
                                                    is_managing_sas=True)
            grants.extend([g for g in uut_grants])

        for record in iter_data['cbsdRecords']:
            grant_request = [record['grantRequest']]
            reg_request = MergeConditionalData(
                [record['registrationRequest']],
                [record['conditionalRegistrationData']])
            uut_grant = data.getGrantsFromRequests(reg_requests,
                                                   grant_requests,
                                                   is_managing_sas=True)
            grants.append(uut_grant)

    return grants, dpas
def _IprConfigRead(config):
    """Extracts DPA and grants from IPR config JSON.

  Note: All IPT suppprted except IPR1.

  Args:
    config: A JSON dictionary.

  Returns:
    A tuple (dpas, grants) where:
      dpas:  a list of objects of type |dpa_mgr.Dpa|.
      grants: a list of |data.CbsdGrantInfo|.
  """
    dpa_cfgs = None
    if 'portalDpa' in config:
        dpa_cfgs = [config['portalDpa']]
    elif 'escDpa' in config:
        dpa_cfgs = [config['escDpa']]
    if dpa_cfgs is None:
        if 'dpas' in config:
            dpa_cfgs = config['dpas']
        elif 'dpa' in config:
            dpa_cfgs = [config['dpa']]
    if dpa_cfgs is None or ('domainProxies' not in config
                            and 'registrationRequest' not in config):
        raise ValueError(
            'Unsupported config file. Please use a IPR config file')

    # Build the DPAs
    dpas = []
    for dpa_cfg in dpa_cfgs:
        dpa_id = dpa_cfg['dpaId']
        try:
            dpa_kml_file = config['dpaDatabaseConfig']['filePath']
        except KeyError:
            dpa_kml_file = None
        try:
            points_builder = dpa_cfg['points_builder']
        except KeyError:
            points_builder = None
        try:
            dpa = dpa_mgr.BuildDpa(dpa_id,
                                   protection_points_method=points_builder,
                                   portal_dpa_filename=dpa_kml_file)
        except IOError:
            print('Portal KML File not found: %s ' % dpa_kml_file)
            raise
        try:
            freq_range_mhz = (dpa_cfg['frequencyRange']['lowFrequency'] / 1.e6,
                              dpa_cfg['frequencyRange']['highFrequency'] /
                              1.e6)
            dpa.ResetFreqRange([freq_range_mhz])
        except KeyError:
            pass
        # - add extra properties for the geometry and margin
        try:
            dpa.margin_db = dpa_cfg['movelistMargin']
        except KeyError:
            dpa_margin_db = 'linear(1.5)'
        try:
            dpa_zone = zones.GetCoastalDpaZones()[dpa_id]
        except KeyError:
            dpa_zone = zones.GetPortalDpaZones(kml_path=dpa_kml_file)[dpa_id]
        dpa.geometry = dpa_zone.geometry
        dpas.append(dpa)

    # Read the CBSDs, assuming all granted, into list of |CbsdGrantInfo|.
    grants = []
    if 'domainProxies' in config:
        #  - first the SAS UUT
        for domain_proxy_config in config['domainProxies']:
            grant_requests = domain_proxy_config['grantRequests']
            reg_requests = MergeConditionalData(
                domain_proxy_config['registrationRequests'],
                domain_proxy_config['conditionalRegistrationData'])
            grants.extend(
                data.getGrantsFromRequests(reg_requests,
                                           grant_requests,
                                           is_managing_sas=True))

        #  - now the peer SASes.
        if 'sasTestHarnessConfigs' in config:
            for th_config in config['sasTestHarnessConfigs']:
                dump_records = th_config['fullActivityDumpRecords'][0]
                grants.extend(
                    data.getAllGrantInfoFromCbsdDataDump(
                        dump_records, is_managing_sas=False))

    elif 'registrationRequest' in config:
        grants.extend(
            data.getGrantsFromRequests(
                MergeConditionalData([config['registrationRequest']],
                                     [config['conditionalRegistrationData']]),
                [config['grantRequest']],
                is_managing_sas=True))

    return grants, dpas
    # reset the random seed
    np.random.seed(12345)

    # Configure the global pool of processes
    mpool.Configure(num_processes)
    num_workers = mpool.GetNumWorkerProcesses()

    (all_cbsds, reg_requests, grant_requests, protection_zone,
     (n_a_indoor, n_a_outdoor, n_b), ax) = PrepareSimulation()

    # Build the grants
    grants = data.getGrantsFromRequests(reg_requests, grant_requests)

    # Build the DPA manager
    dpa = dpa_mgr.BuildDpa(
        dpa_name, 'default (%d,%d,%d,%d,%d)' %
        (npts_front_dpa_contour, npts_back_dpa_contour, npts_within_dpa_front,
         npts_within_dpa_back, front_usborder_buffer_km))
    dpa.ResetFreqRange([(fmin, fmax)])

    # Plot the protection points
    ax.scatter([pt.longitude for pt in dpa.protected_points],
               [pt.latitude for pt in dpa.protected_points],
               color='k',
               marker='*')
    plt.show(block=False)

    # Run the move list algorithm a first time to fill up geo cache
    print 'Running Move List algorithm (%d workers)' % num_workers
    print '  + once to populate the terrain cache (small run)'
    dpa.SetGrantsFromList(grants[0:50])
    dpa.ComputeMoveLists()