Exemplo n.º 1
0
def generate_sdf_files(upper_left_loc: GeographicPoint, field_length):  # downloading and creating sdf(terrain)
    if not os.path.exists(SDF_DIR):
        os.makedirs(SDF_DIR)
    tmp_dir = SDF_DIR + '/tmp'
    if not os.path.exists(tmp_dir):
        os.makedirs(tmp_dir)

    lat_set = set(list(range(int(upper_left_loc.lat),
                             int(to_geographic(upper_left_loc, Point((0, field_length))).lat)+1)))
    lon_set = set(list(range(int(upper_left_loc.lon),
                             int(to_geographic(upper_left_loc, Point((field_length, 0))).lon)+1)))

    for lat in lat_set:
        for lon in lon_set:
            lat_str, lon_str = str(lat), str(lon + 1)
            if len(lon_str) < 3:
                lon_str = '0' + lon_str
            sdf_file = "N" + lat_str + "W" + lon_str + ".hgt.zip"
            print("Downloading Terrain file: ", sdf_file)
            terrain_file_url = "https://dds.cr.usgs.gov/srtm/version2_1/SRTM3/North_America/" + sdf_file
            try:
                with urllib.request.urlopen(terrain_file_url) as response, open(
                        tmp_dir + '/' + str(sdf_file), 'wb') as f:
                    shutil.copyfileobj(response, f)
            except IOError as e:
                raise ("Error: terrain file " + sdf_file + " NOT found!", e)
            print('Unzipping SDF file', sdf_file)
            try:
                # ---uncompress the zip file-----------------#
                zip_ref = zipfile.ZipFile(tmp_dir + "/" + str(sdf_file), 'r')
                zip_ref.extractall(tmp_dir)
                zip_ref.close()
            except (zipfile.BadZipFile, zipfile.LargeZipFile) as e:
                raise ("Error: Unzipping for", sdf_file, ' was NOT successful!', e)
    print("Downloading and unzipping was successful.")

    # convert zip file to hgt_file using strm2sdf command line
    owd = os.getcwd()
    os.chdir(SDF_DIR)
    pp = os.getcwd()
    try:
        for hgt_file in glob.glob('./tmp/*.hgt'):
            subprocess.call(["srtm2sdf", hgt_file])
            # subprocess.call(["srtm2sdf-hd", hgt_file])
    except (ValueError, subprocess.CalledProcessError, OSError) as e:
        # e = sys.exc_info()[0]
        raise ("Error: converting .hgt file\n", e, "was NOT successful!")
    finally:
        os.chdir(owd)
        shutil.rmtree(tmp_dir)  # remove the temporary directory created at the beginning
Exemplo n.º 2
0
 def points(self, n: int) -> List[Point]:
     if n > self.length * self.width:
         warnings.warn(
             "Number of Points requested is more than all the points. Duplicates exist."
         )
     return [
         Point((randint(0, self.width - 1), randint(0, self.length - 1)))
         for _ in range(n)
     ]
Exemplo n.º 3
0
 def create_purs(pu_id: str, pur_number: int, pur_min_dist: float, pur_max_dist: float, pur_threshold: float,
                 pur_beta: float, pur_height: float) -> List[PUR]:
     purs = []
     angle = float(360/pur_number)
     for i in range(pur_number):
         purs.append(PUR(pu_id=pu_id, pur_id=i,
                         rx=RX(element=Element(location=Point(PolarPoint(uniform(pur_min_dist, pur_max_dist),
                                                                         i * math.radians(angle))),
                                               height=pur_height)),
                         threshold=pur_threshold, beta=pur_beta))
     return purs
Exemplo n.º 4
0
    def compute_field_power(
        self
    ) -> List[List[
            float]]:  # calculate received power at specific locations all over the
        # field to create a heatmap
        # TODO fix this part before using
        received_power = []

        [min_x, min_y] = [0, 0]  # self.corners[0].get_cartesian
        [max_x, max_y] = [1, 2]  # self.corners[-1].get_cartesian
        for y in range(min_y, max_y, min(1, max(1, (max_y - min_y) // 400))):
            tmp = []
            for x in range(min_x, max_x, min(1, max(1,
                                                    (max_x - min_x) // 400))):
                pwr_tmp = -float('inf')
                for pu in self.pus:
                    pwr_tmp = self.power_with_path_loss(
                        tx=pu.tx, rx=RX(Element(Point((x, y)), 15)))
                tmp.append(pwr_tmp)
            received_power.append(tmp)
        return received_power
Exemplo n.º 5
0
def create_sensors(path: str, sensor_height) -> List[Sensor]:
    sss = []
    try:
        with open(path, 'r') as f:
            # max_gain = 0.5 * num_intruders  # len(self.transmitters)
            # index = 0
            lines = f.readlines()
            for line_idx, line in enumerate(lines):
                inputs = line.split(' ')
                x, y, std, cost = float(inputs[0]), float(inputs[1]), float(
                    inputs[2]), float(inputs[3])
                sss.append(
                    Sensor(ss_id=line_idx,
                           rx=RX(
                               Element(location=Point(CartesianPoint(x, y)),
                                       height=sensor_height)),
                           cost=cost,
                           std=std))
    except FileNotFoundError:
        raise ValueError('Sensor file does not exist')
    except IndexError as e:
        raise ValueError(
            'The file given is not in correct format of x y std cost')
    return sss
Exemplo n.º 6
0
    @property
    def cost(self):
        return self.__cost

    @cost.setter
    def cost(self, cost: float):
        self.__cost = cost

    @property
    def std(self):
        return self.__std

    @std.setter
    def std(self, std: float):
        self.__std = std

    def __str__(self):
        return "id= {0}\n".format(self.id) + \
               "{0}\n".format(self.rx) + \
               "cost= {0}\n".format(self.cost) + \
               "std= {0}\n".format(self.std)


if __name__ == "__main__":
    ss = Sensor(ss_id=15,
                rx=RX(Element(location=Point((1, 5)), height=15)),
                cost=15,
                std=1)
    print(ss)
Exemplo n.º 7
0
    def path_loss(self, tx: Element, rx: Element, iteration: int = 0):
        if iteration == 20:
            raise Exception("Sample skipped")
        tmp_fetch_time = time.time()
        approx_tx = (int(tx.location.cartesian.x // SPLAT.APPROX) *
                     SPLAT.APPROX,
                     int(tx.location.cartesian.y // SPLAT.APPROX) *
                     SPLAT.APPROX)
        approx_rx = (int(rx.location.cartesian.x // SPLAT.APPROX) *
                     SPLAT.APPROX,
                     int(rx.location.cartesian.y // SPLAT.APPROX) *
                     SPLAT.APPROX)
        tx_dict_key = '{:04d}{:04d}'.format(approx_tx[0], approx_tx[1])
        rx_dict_key = '{:04d}{:04d}'.format(approx_rx[0], approx_rx[1])
        if tx_dict_key in self.pl_dict:
            if rx_dict_key in self.pl_dict[tx_dict_key]:
                # free, itm = self.pl_dict[tx_dict_key][rx_dict_key]  # old format which the map has both values
                pl_value = self.pl_dict[tx_dict_key][rx_dict_key]
                self.__FETCH_TIME += time.time() - tmp_fetch_time
                self.__FETCH_NUM += 1
                # return itm if itm != 0.0 else free  # old version
                return pl_value
        tmp_exec_time = time.time()
        pwd = os.getcwd()
        file_dir = os.path.dirname(__file__)
        os.chdir(file_dir + "/" + SPLAT.SDF_DIR)
        # terr_dir = os.getcwd()
        # os.chdir('out')

        tx_loc = to_geographic(self.upper_left_ref, tx.location)
        rx_loc = to_geographic(self.upper_left_ref, rx.location)
        # print(haversine_distance(tx_loc, rx_loc)*1000)
        tx_site = Site('tx', tx_loc.lat, tx_loc.lon, tx.height)
        rx_site = Site('rx', rx_loc.lat, rx_loc.lon, rx.height)
        tx_name = SPLAT.create_qth_files(tx_site)
        rx_name = SPLAT.create_qth_files(rx_site)

        # running splat command
        path_loss_command = [
            SPLAT.SPLAT_COMMAND, '-t', tx_name + '.qth', '-r', rx_name + '.qth'
        ]

        count = 1
        # subprocess.call(path_loss_command, stdout=open(os.devnull, 'wb'))
        try:
            p = subprocess.Popen(path_loss_command,
                                 stdout=open(os.devnull, 'wb'))
        except (OSError or ValueError or TimeoutError) as e:
            print("Error happened executing SPLAT! command.\n" + e)
            count += 1
            pass
        start_time = time.time()
        while True:
            if p.poll() is not None:
                # count = 1
                break
            else:
                if time.time() - start_time > SPLAT.TIMEOUT:
                    if count > 50:
                        # print('Error: Too many repetition for a location')
                        raise Exception(
                            "Error: Too many SPLAT! repetition for a location")
                    # print('SPLAT! does not produce result for', ' '.join(path_loss_command), 'for ', count, 'times.')
                    count += 1
                    p.kill()
                    # splat! does not respond
                    # os.remove(tx_name + '.qth')
                    # os.remove(rx_name + '.qth')
                    offset = count
                    # tx_loc = SPLAT.get_loc(upper_left_ref, tx[0] + uniform(-(SPLAT.APPROX/2)**2 - offset,
                    # (SPLAT.APPROX/2)**2),
                    #                        tx[1] + uniform(-(SPLAT.APPROX / 2) ** 2 - offset,
                    # (SPLAT.APPROX / 2) ** 2 +
                    #                                        offset))
                    tx_loc = to_geographic(
                        self.upper_left_ref, tx.location + Point((uniform(
                            -offset, offset), uniform(-offset, offset))))
                    rx_loc = to_geographic(
                        self.upper_left_ref, rx.location + Point((uniform(
                            -offset, offset), uniform(-offset, offset))))

                    tx_site = Site('tx', tx_loc.lat, tx_loc.lon, tx.height,
                                   tx_name)
                    rx_site = Site('rx', rx_loc.lat, rx_loc.lon, rx.height,
                                   rx_name)
                    tx_name = SPLAT.create_qth_files(tx_site)
                    rx_name = SPLAT.create_qth_files(rx_site)

                    try:
                        path_loss_command = [
                            SPLAT.SPLAT_COMMAND, '-t', tx_name + '.qth', '-r',
                            rx_name + '.qth'
                        ]
                        p = subprocess.Popen(path_loss_command,
                                             stdout=open(os.devnull, 'wb'))
                    except (OSError or ValueError or TimeoutError) as e:
                        print("Error happened executing SPLAT! command.\n" + e)
                        # pass
                    start_time = time.time()  # reset time
                else:
                    time.sleep(SPLAT.TIMEOUT / 5)

        output_name = "{tx_name}-to-{rx_name}.txt".format(tx_name=tx_name,
                                                          rx_name=rx_name)
        # output_name = tx_name + '-to-' + rx_name + '.txt'  # the file where the result will be created
        try:
            free_pl, itm_pl = self.process_output(output_name)
        except FileNotFoundError:
            print('Warning: Recalling is happening')
            os.chdir(pwd)
            return self.path_loss(tx, rx, iteration + 1)

        # removing created files
        try:
            os.remove(output_name)
            os.remove(tx_name + '.qth')
            os.remove(rx_name + '.qth')
            os.remove(tx_name + '-site_report.txt')
        except (FileNotFoundError, Exception) as e:
            pass

        os.chdir(pwd)
        pl_value = float(itm_pl) if float(itm_pl) != 0.0 else float(free_pl)
        if tx_dict_key not in self.pl_dict:
            # self.__pl_dict[tx_dict_key] = {rx_dict_key: (float(free_pl), float(itm_pl))}  # old version
            self.__pl_dict[tx_dict_key] = {rx_dict_key: pl_value}
        else:
            # self.__pl_dict[tx_dict_key][rx_dict_key] = (float(free_pl), float(itm_pl))  # old version
            self.__pl_dict[tx_dict_key][rx_dict_key] = pl_value
        self.__EXEC_TIME += time.time() - tmp_exec_time
        self.__EXEC_NUM += 1
        # return float(itm_pl) if float(itm_pl) != 0.0 else float(free_pl)  # old version
        return pl_value
Exemplo n.º 8
0
        # return float(itm_pl) if float(itm_pl) != 0.0 else float(free_pl)  # old version
        return pl_value

    @staticmethod
    def process_output(file_name):
        positive_float = r'(\d+\.\d+)'
        free_space_pattern = r'Free space.*\D{}.*'.format(positive_float)
        itm_pattern = r'ITWOM Version 3.0.*\D{}.*'.format(positive_float)
        free_p = re.compile(free_space_pattern)
        itm_p = re.compile(itm_pattern)
        with open(file_name, encoding="ISO-8859-1", mode='r') as f:
            content = f.read()
            free_m = free_p.search(content)
            free_pl = free_m.group(1) if free_m else 0

            itm_m = itm_p.search(content)
            itm_pl = itm_m.group(1) if itm_m else 0
        return free_pl, itm_pl

    def __str__(self):
        "SPLAT! PM:\nUpper-left corner:{}".format(self.upper_left_ref)


if __name__ == "__main__":
    # 40.800595, -73.107507
    top_left_ref = GeographicPoint(40.800595, 73.107507)
    splat = SPLAT(top_left_ref)
    # splat.generate_sdf_files()
    free_pl, itm_pl = splat.path_loss(Element(Point((180, 170)), 300),
                                      Element(Point((100, 100)), 15))
    print('free path loss:', free_pl, ', itm path loss:', itm_pl)
Exemplo n.º 9
0
            thr_decimal = get_decimal(self.threshold)
            return get_db(thr_decimal - irp_decimal)

    def __str__(self):
        r, theta = self.rx.element.location.polar.r, self.rx.element.location.polar.theta
        return "id= {pur_id}\n".format(pur_id=self.__id) + \
               "relative location= ({r},{theta})\n".format(r=round(r, 3), theta=round(theta, 3)) +\
               "height= {height}\n".format(height=self.rx.element.height) +\
               "threshold= {thr}\n".format(thr=self.__thr) +\
               "beta= {beta}\n".format(beta=self.__beta) +\
               "received power= {rp}\n".format(rp=self.rx.received_power) +\
               "received interference= {irp}".format(irp=self.__irp)


if __name__ == "__main__":
    pur = PUR('PU10',
              1,
              RX(Element(location=Point(PolarPoint(5, 0)), height=15)),
              beta=1)
    print(pur)
    pur.received_power = -25
    pur.add_interference('PU110', -30)
    print(pur)
    pur.add_interference('PU110', -35)
    pur.update_interference('PU110', -35)
    print(pur)
    pur.update_interference('PU10', -30)
    pur.add_interference('PU10', -30)
    pur.delete_interference_power_from('PU110')
    print(pur)
Exemplo n.º 10
0
    @staticmethod
    def create_purs(pu_id: str, pur_number: int, pur_min_dist: float, pur_max_dist: float, pur_threshold: float,
                    pur_beta: float, pur_height: float) -> List[PUR]:
        purs = []
        angle = float(360/pur_number)
        for i in range(pur_number):
            purs.append(PUR(pu_id=pu_id, pur_id=i,
                            rx=RX(element=Element(location=Point(PolarPoint(uniform(pur_min_dist, pur_max_dist),
                                                                            i * math.radians(angle))),
                                                  height=pur_height)),
                            threshold=pur_threshold, beta=pur_beta))
        return purs

    def __str__(self):
        return "{loc},{power}".format(loc=str(self.tx.element.location), power=round(self.tx.power, 3))


if __name__ == "__main__":
<<<<<<< HEAD
    pu1 = PU(Point(5,5), 10, 13, 2, 10)
    for i in range(pu1.n):
        print(str(i+1), "(", pu1.purs[i].loc.get_cartesian[0], ",", pu1.purs[i].loc.get_cartesian[1],")", pu1.loc.distance(pu1.purs[i].loc))
=======
    pu1 = PU(pu_id=10, tx=TX(element=Element(location=Point(CartesianPoint(5, 5)), height=15), power=-5),
             pur_num=16, pur_beta=1.0, pur_dist=[1, 3], pur_height=15)
    print(pu1)
    for idx, pur in enumerate(pu1.purs):
        pur_location = pu1.tx.element.location + pur.rx.element.location
        print("{0}. ({1}), {2}".format(idx+1, str(pur_location), pu1.tx.element.location.distance(pur_location)))
>>>>>>> 2f6fbc9e82c377be81183e276e9e45d79365b964
Exemplo n.º 11
0
    @element.setter
    def element(self, element: float):
        self.__elm = element

    @property
    def received_power(self):
        return self.__rp

    @received_power.setter
    def received_power(self, received_power: float):
        self.__rp = received_power

    def __str__(self):
        return "{elm}\nreceived power={power}".format(elm=self.element,
                                                      power=round(
                                                          self.received_power,
                                                          3))


if __name__ == "__main__":
    elm = Element(Point(CartesianPoint(5, 5)), 10)
    print(elm)
    print(elm.location)
    tx = TX(elm, -5)
    print(tx)
    print(tx.element.location)
    rx = RX(elm)
    print(rx)
    rx.received_power = -25.0
    print(rx)
Exemplo n.º 12
0
 def all_points(self):
     return [
         Point((x, y)) for x in range(self.width)
         for y in range(self.length)
     ]
        # loss += 0 if distance == 0 else self.__shadow_amp * sin(
        #     2 * pi * distance / self.__dist_period)  # add shadowing
        if self.is_noisy:  # add multipath
            loss += gauss(0, self.std)
        return loss

    def __str__(self):
        return "Log-Distance(Normal):\n" +\
               "Path-Loss Coeff.= {0}\n".format(self.alpha) +\
               "Path-Loss reference {0} in distance reference {1}\n".format(self.pl_ref, self.dist_ref) +\
               ("std= {0}" if self.is_noisy else "").format(self.std if self.is_noisy else None)


if __name__ == "__main__":
    log_pm = LogDistancePM(2.0, True, 1)
    print(log_pm)
    print(
        log_pm.path_loss(Element(Point((0, 0)), 15),
                         Element(Point((10, 10)), 15)))
    # log_pm.is_noisy = False
    print(log_pm)
    print(hasattr(log_pm, 'alpha'))
    x = [i / 10 for i in range(10, 1000)]
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(x, [
        log_pm.path_loss(Element(Point(
            (1, 1)), 15), Element(Point((1, 1)) * i, 15)) for i in x
    ])
    ax.set_xscale('log')
    plt.show()