|
| 1 | +# %% |
| 2 | +import json |
| 3 | +import multiprocessing as mp |
| 4 | +import os |
| 5 | +from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed |
| 6 | +from datetime import datetime, timedelta, timezone |
| 7 | +from threading import Lock, Thread |
| 8 | + |
| 9 | +import fsspec |
| 10 | +import numpy as np |
| 11 | +import pandas as pd |
| 12 | +import pyproj |
| 13 | +from obspy import read_inventory |
| 14 | +from obspy.clients.fdsn import Client |
| 15 | +from sklearn.cluster import DBSCAN |
| 16 | +from tqdm import tqdm |
| 17 | +from args import parse_args |
| 18 | +from glob import glob |
| 19 | + |
| 20 | + |
| 21 | +def scan_csv(year, root_path, fs=None, bucket=None, protocol="file"): |
| 22 | + # %% |
| 23 | + csv_list = [] |
| 24 | + if protocol != "file": |
| 25 | + jdays = fs.ls(f"{bucket}/{region}/{folder}/{year}") |
| 26 | + else: |
| 27 | + jdays = os.listdir(f"{root_path}/{region}/phasenet/picks/{year}/") |
| 28 | + |
| 29 | + for jday in jdays: |
| 30 | + if protocol != "file": |
| 31 | + csvs = fs.glob(f"{jday}/??/*.csv") |
| 32 | + else: |
| 33 | + csvs = glob(f"{root_path}/{region}/phasenet/picks/{year}/{jday}/??/*.csv") |
| 34 | + |
| 35 | + csv_list.extend([[year, jday, csv] for csv in csvs]) |
| 36 | + |
| 37 | + csvs = pd.DataFrame(csv_list, columns=["year", "jday", "csv"]) |
| 38 | + csv_file = f"{root_path}/{region}/phasenet/csv_list_{year}.csv" |
| 39 | + csvs.to_csv(csv_file, index=False) |
| 40 | + |
| 41 | + return csv_file |
| 42 | + |
| 43 | + |
| 44 | +# %% |
| 45 | +def read_csv(rows, region, year, jday, root_path, fs=None, bucket=None): |
| 46 | + |
| 47 | + picks = [] |
| 48 | + for i, row in rows.iterrows(): |
| 49 | + # if fs.info(row["csv"])["size"] == 0: |
| 50 | + # continue |
| 51 | + # with fs.open(row["csv"], "r") as f: |
| 52 | + # picks_ = pd.read_csv(f, dtype=str) |
| 53 | + if os.path.getsize(row["csv"]) == 0: |
| 54 | + continue |
| 55 | + with open(row["csv"], "r") as f: |
| 56 | + picks_ = pd.read_csv(f, dtype=str) |
| 57 | + picks.append(picks_) |
| 58 | + |
| 59 | + if len(picks) > 0: |
| 60 | + picks = pd.concat(picks, ignore_index=True) |
| 61 | + if not os.path.exists(f"{root_path}/{region}/phasenet/{year}"): |
| 62 | + os.makedirs(f"{root_path}/{region}/phasenet/{year}", exist_ok=True) |
| 63 | + picks.to_csv(f"{root_path}/{region}/phasenet/{year}/{year}.{jday}.csv", index=False) |
| 64 | + # fs.put( |
| 65 | + # f"{root_path}/{region}/phasenet/{year}/{jday}/{year}.{jday}.csv", |
| 66 | + # f"{bucket}/{region}/phasenet_merged/{year}/{year}.{jday}.csv", |
| 67 | + # ) |
| 68 | + else: |
| 69 | + with open(f"{root_path}/{region}/phasenet/{year}/{year}.{jday}.csv", "w") as f: |
| 70 | + f.write("") |
| 71 | + |
| 72 | + |
| 73 | +# %% |
| 74 | +if __name__ == "__main__": |
| 75 | + |
| 76 | + args = parse_args() |
| 77 | + root_path = args.root_path |
| 78 | + region = args.region |
| 79 | + |
| 80 | + data_path = f"{region}/phasenet/picks" |
| 81 | + result_path = f"{region}/phasenet" |
| 82 | + |
| 83 | + # %% |
| 84 | + # protocol = "gs" |
| 85 | + # token_json = f"{os.environ['HOME']}/.config/gcloud/application_default_credentials.json" |
| 86 | + # with open(token_json, "r") as fp: |
| 87 | + # token = json.load(fp) |
| 88 | + # fs = fsspec.filesystem(protocol, token=token) |
| 89 | + |
| 90 | + # %% |
| 91 | + years = os.listdir(f"{root_path}/{region}/phasenet/picks") |
| 92 | + |
| 93 | + for year in years: |
| 94 | + |
| 95 | + csv_list = scan_csv(year, root_path) |
| 96 | + |
| 97 | + # %% |
| 98 | + csv_list = pd.read_csv(csv_list, dtype=str) |
| 99 | + |
| 100 | + # for jday, csvs in csv_list.groupby("jday"): |
| 101 | + # read_csv(csvs, region, year, jday, root_path) |
| 102 | + # raise |
| 103 | + |
| 104 | + # ncpu = os.cpu_count() |
| 105 | + ncpu = 64 |
| 106 | + print(f"Number of processors: {ncpu}") |
| 107 | + csv_by_jday = csv_list.groupby("jday") |
| 108 | + pbar = tqdm(total=len(csv_by_jday), desc=f"Loading csv files (year {year})") |
| 109 | + |
| 110 | + # with mp.Pool(ncpu) as pool: |
| 111 | + ctx = mp.get_context("spawn") |
| 112 | + with ctx.Pool(ncpu) as pool: |
| 113 | + jobs = [] |
| 114 | + for jday, csvs in csv_by_jday: |
| 115 | + job = pool.apply_async( |
| 116 | + read_csv, (csvs, region, year, jday, root_path), callback=lambda _: pbar.update() |
| 117 | + ) |
| 118 | + jobs.append(job) |
| 119 | + pool.close() |
| 120 | + pool.join() |
| 121 | + for job in jobs: |
| 122 | + output = job.get() |
| 123 | + if output: |
| 124 | + print(output) |
| 125 | + |
| 126 | + pbar.close() |
| 127 | + |
| 128 | + # %% |
| 129 | + csvs = glob(f"{root_path}/{region}/phasenet/????/????.???.csv") |
| 130 | + picks = [] |
| 131 | + for csv in tqdm(csvs, desc="Merge csv files"): |
| 132 | + picks.append(pd.read_csv(csv, dtype=str)) |
| 133 | + picks = pd.concat(picks, ignore_index=True) |
| 134 | + picks.to_csv(f"{root_path}/{region}/phasenet/phasenet_picks.csv", index=False) |
| 135 | + |
| 136 | +# %% |
0 commit comments