Skip to content

Commit 2b8412a

Browse files
authored
Merge pull request #89 from GeoscienceAustralia/NPI-3470-misc-clarity-and-hint-improvements
Npi 3470 misc clarity and hint improvements
2 parents 7a579cd + 2713e07 commit 2b8412a

2 files changed

Lines changed: 41 additions & 27 deletions

File tree

gnssanalysis/gn_download.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -432,7 +432,7 @@ def generate_product_filename(
432432
)
433433
else:
434434
if file_ext.lower() == "snx":
435-
product_filename = f"igs{gps_date.yr[2:]}P{gps_date.gpswk}.snx.Z"
435+
product_filename = f"igs{gps_date.year[2:]}P{gps_date.gps_week}.snx.Z"
436436
else:
437437
hour = f"{reference_start.hour:02}"
438438
prefix = "igs" if solution_type == "FIN" else "igr" if solution_type == "RAP" else "igu"
@@ -498,7 +498,7 @@ def attempt_ftps_download(
498498
download_dir: _Path,
499499
ftps: _ftplib.FTP_TLS,
500500
filename: str,
501-
type_of_file: str = None,
501+
type_of_file: Optional[str] = None,
502502
if_file_present: str = "prompt_user",
503503
) -> Union[_Path, None]:
504504
"""Attempt download of file (filename) given the ftps client object (ftps) to chosen location (download_dir)
@@ -742,7 +742,7 @@ def download_file_from_cddis(
742742
max_retries: int = 3,
743743
decompress: bool = True,
744744
if_file_present: str = "prompt_user",
745-
note_filetype: str = None,
745+
note_filetype: Optional[str] = None,
746746
) -> Union[_Path, None]:
747747
"""Downloads a single file from the CDDIS ftp server
748748
@@ -755,7 +755,7 @@ def download_file_from_cddis(
755755
:param str note_filetype: How to label the file for STDOUT messages, defaults to None
756756
:raises e: Raise any error that is run into by ftplib
757757
:return _Path or None: The pathlib.Path of the downloaded file (or decompressed output of it). Returns None if the
758-
file already existed and was skipped.
758+
file already existed and was skipped, or if the download failed.
759759
"""
760760
with ftp_tls(CDDIS_FTP) as ftps:
761761
ftps.cwd(ftp_folder)
@@ -796,7 +796,7 @@ def download_file_from_cddis(
796796
raise Exception("Failed to download file or raise exception. Some logic is broken.")
797797

798798

799-
def download_multiple_files_from_cddis(files: List[str], ftp_folder: str, output_folder: _Path) -> None:
799+
def download_multiple_files_from_cddis(files: list[str], ftp_folder: str, output_folder: _Path) -> None:
800800
"""Downloads multiple files in a single folder from cddis in a thread pool.
801801
802802
:param files: List of str filenames
@@ -846,7 +846,7 @@ def download_product_from_cddis(
846846
# We do this because the weekly files are released/dated as Sunday of each GPS week.
847847
start_epoch_as_gps_date = GPSDate(start_epoch)
848848
# Get GPS week number *without* DayOfWeek suffix (therefore start of the GPS Week), then convert back to datetime
849-
start_epoch = gps_week_day_to_datetime(f"{start_epoch_as_gps_date.gpswk}")
849+
start_epoch = gps_week_day_to_datetime(f"{start_epoch_as_gps_date.gps_week}")
850850
timespan = _datetime.timedelta(days=7)
851851

852852
logging.info("Attempting CDDIS Product download/s")
@@ -875,7 +875,7 @@ def download_product_from_cddis(
875875
download_filepaths = []
876876
with ftp_tls(CDDIS_FTP) as ftps:
877877
try:
878-
ftps.cwd(f"gnss/products/{gps_date.gpswk}")
878+
ftps.cwd(f"gnss/products/{gps_date.gps_week}")
879879
except _ftplib.all_errors as e:
880880
logging.warning(f"{reference_start} too recent")
881881
logging.warning(f"ftp_lib error: {e}")
@@ -891,11 +891,11 @@ def download_product_from_cddis(
891891
version=version,
892892
project=project_type,
893893
)
894-
ftps.cwd(f"gnss/products/{gps_date.gpswk}")
894+
ftps.cwd(f"gnss/products/{gps_date.gps_week}")
895895

896896
all_files = ftps.nlst()
897897
if not (product_filename in all_files):
898-
logging.warning(f"{product_filename} not in gnss/products/{gps_date.gpswk} - too recent")
898+
logging.warning(f"{product_filename} not in gnss/products/{gps_date.gps_week} - too recent")
899899
raise FileNotFoundError
900900

901901
# reference_start will be changed in the first run through while loop below
@@ -926,7 +926,7 @@ def download_product_from_cddis(
926926
download_filepaths.append(
927927
download_file_from_cddis(
928928
filename=product_filename,
929-
ftp_folder=f"gnss/products/{gps_date.gpswk}",
929+
ftp_folder=f"gnss/products/{gps_date.gps_week}",
930930
output_folder=download_dir,
931931
if_file_present=if_file_present,
932932
note_filetype=file_ext,

gnssanalysis/gn_io/nanu.py

Lines changed: 31 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,17 @@
22
import logging as _logging
33
import os as _os
44
from typing import Union as _Union
5+
from datetime import datetime
56

67
import numpy as _np
78
import pandas as _pd
89

910
from .. import gn_io as _gn_io
1011

1112

12-
def nanu_path_to_id(nanu_path):
13+
def nanu_path_to_id(nanu_path: str) -> str:
14+
# TODO some examples would be good here.
15+
1316
dir, _, filename = nanu_path.rpartition(_os.sep)
1417
nanu_id, _, extension = filename.partition(".") # get filename without extension
1518
if nanu_id == "nanu": # celestrak naming convention
@@ -45,17 +48,17 @@ def parse_nanu(nanu_bytes: bytes) -> dict:
4548
return output_dict
4649

4750

48-
def read_nanu(path_or_bytes: _Union[str, bytes]) -> dict:
51+
def read_nanu(path: str) -> dict:
4952
"""A parser for Notice Advisory to Navstar Users (NANU) files.
5053
Assumes there is only one message per file, that starts with '1.'
5154
5255
:param _Union[str, bytes] path_or_bytes: path to nanu file or a bytes object
5356
:return dict: nanu values with parameter names as keys
5457
"""
55-
nanu_bytes = _gn_io.common.path2bytes(path_or_bytes)
58+
nanu_bytes = _gn_io.common.path2bytes(path)
5659
output_dict = {}
57-
output_dict["FILEPATH"] = path_or_bytes # TODO change to pathlib
58-
output_dict["NANU ID"] = nanu_path_to_id(path_or_bytes)
60+
output_dict["FILEPATH"] = path # TODO change to pathlib
61+
output_dict["NANU ID"] = nanu_path_to_id(path)
5962
output_dict["CONTENT"] = nanu_bytes
6063
output_dict.update(parse_nanu(nanu_bytes))
6164
return output_dict
@@ -71,15 +74,22 @@ def collect_nanus_to_df(glob_expr: str) -> _pd.DataFrame:
7174
return _pd.DataFrame(read_nanu(n) for n in nanus_list if n is not None)
7275

7376

74-
def get_bad_sv_from_nanu_df(nanu_df: _pd.DataFrame, datetime: _Union[_np.datetime64, str], offset_days: int) -> list:
75-
"""A simple function that analyses an input dataframe NANU collection and outputs a list of SVs that should be excluded for the entered epoch+offset
77+
def get_bad_sv_from_nanu_df(
78+
nanu_df: _pd.DataFrame, up_to_epoch: _Union[_np.datetime64, datetime, str], offset_days: int
79+
) -> list:
80+
"""A simple function that analyses an input dataframe NANU collection and outputs a list of SVs that should be
81+
excluded for the entered epoch+offset
7682
77-
:param _pd.DataFrame nanu_df: a dataframe returned by the collect_nanus_to_df, effectively a _pd.DataFrame call on a list of parsed dicts or a parsed dict
78-
:param _Union[_np.datetime64, str] datetime: epoch to analyse NANUs up to
83+
:param _pd.DataFrame nanu_df: a dataframe returned by the collect_nanus_to_df, effectively a _pd.DataFrame call on
84+
a list of parsed dicts or a parsed dict
85+
:param _Union[_np.datetime64, datetime, str] up_to_epoch: epoch to analyse NANUs up to
7986
:param int offset_days: an offset or a length of a planned processing session in days
80-
:return list: a list of SVs that should not be used for the specified timeperiod. FIXME Potentially needs to be int?
87+
:return list[str]: a list of SVs that should not be used for the specified timeperiod. FIXME Potentially needs to
88+
be int?
8189
"""
82-
datetime = datetime if isinstance(datetime, _np.datetime64) else _np.datetime64(datetime)
90+
up_to_epoch_datetime64: _np.datetime64 = (
91+
up_to_epoch if isinstance(up_to_epoch, _np.datetime64) else _np.datetime64(up_to_epoch)
92+
)
8393

8494
columns_new = [
8595
"FILEPATH",
@@ -129,25 +139,29 @@ def get_bad_sv_from_nanu_df(nanu_df: _pd.DataFrame, datetime: _Union[_np.datetim
129139
dt_df = _pd.concat([df.drop(labels=columns_date, axis=1), dates], axis=1)
130140

131141
events_already_started = (
132-
(dt_df["START CALENDAR DATE"] <= (datetime + offset_days))
133-
| (dt_df["UNUSABLE START CALENDAR DATE"] <= (datetime + offset_days))
134-
| (dt_df["LAUNCH START CALENDAR DATE"] <= (datetime + offset_days))
142+
(dt_df["START CALENDAR DATE"] <= (up_to_epoch_datetime64 + offset_days))
143+
| (dt_df["UNUSABLE START CALENDAR DATE"] <= (up_to_epoch_datetime64 + offset_days))
144+
| (dt_df["LAUNCH START CALENDAR DATE"] <= (up_to_epoch_datetime64 + offset_days))
135145
)
136146
dt_valid_df = dt_df[events_already_started]
137147

138148
prns_last_nanu_to_date = dt_valid_df.PRN.astype(float).drop_duplicates(keep="last").index
139149

140150
all_the_last_msgs = dt_df.loc[prns_last_nanu_to_date]
141151

152+
# Filter maneuver related NANU messages down to those with an end date in the future, or no end date at all:
142153
last_selected = all_the_last_msgs[
143-
((all_the_last_msgs["STOP CALENDAR DATE"] >= datetime) | all_the_last_msgs["STOP CALENDAR DATE"].isna())
154+
(
155+
(all_the_last_msgs["STOP CALENDAR DATE"] >= up_to_epoch_datetime64)
156+
| all_the_last_msgs["STOP CALENDAR DATE"].isna()
157+
)
144158
& (all_the_last_msgs["NANU TYPE"] != "USABINIT")
145159
]
146160

147161
if last_selected.empty:
148-
return []
162+
return [] # No NANUs currently in effect
149163

150-
_logging.info(msg="NANUs in affect are:\n" + "\n".join(last_selected.FILEPATH.to_list()))
164+
_logging.info(msg="NANUs in effect are:\n" + "\n".join(last_selected.FILEPATH.to_list()))
151165

152166
sel_idx = last_selected.index.values
153167
msg_gaps = dt_df.loc[sel_idx.min() : sel_idx.max()]

0 commit comments

Comments
 (0)