dodo.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. """
  2. Define the tasks for UNFCCC data repository
  3. The setup with the function that calls datalad.api.run is necessary because doit doesn't
  4. like the return values of datalad.api.run
  5. TODO: could add try-except blocks and return proper values so doit knows if the task
  6. was run successfully
  7. """
  8. import os
  9. import sys
  10. import datalad.api
  11. from doit import get_var
  12. root_path = "."
  13. os.environ["UNFCCC_GHG_ROOT_PATH"] = root_path
  14. from unfccc_ghg_data.helper.functions import ( # noqa: E402
  15. get_country_datasets,
  16. get_country_submissions,
  17. )
  18. from unfccc_ghg_data.unfccc_crf_reader.unfccc_crf_reader_devel import ( # noqa: E402
  19. read_year_to_test_specs,
  20. )
  21. from unfccc_ghg_data.unfccc_crf_reader.unfccc_crf_reader_prod import ( # noqa: E402
  22. read_crf_for_country_datalad,
  23. read_new_crf_for_year_datalad,
  24. )
  25. from unfccc_ghg_data.unfccc_di_reader import ( # noqa: E402
  26. process_DI_for_country_datalad,
  27. process_DI_for_country_group_datalad,
  28. read_DI_for_country_datalad,
  29. read_DI_for_country_group_datalad,
  30. )
  31. def set_root_path():
  32. """Set the root folder for the repository"""
  33. os.environ["UNFCCC_GHG_ROOT_PATH"] = root_path
  34. def map_folders(parent_folder):
  35. """
  36. Create or update the folder mapping in the given folder
  37. Internal function
  38. """
  39. datalad.api.run(
  40. cmd="python3 src/unfccc_ghg_data/helper/folder_mapping.py "
  41. f"--folder={parent_folder}",
  42. dataset=root_path,
  43. message=f"Update folder mapping for {parent_folder}",
  44. outputs=f"{parent_folder}/folder_mapping.json",
  45. dry_run=None,
  46. explicit=True,
  47. )
  48. def task_in_venv():
  49. """
  50. Check if code run from virtual environment and throw an error is not.
  51. Returns
  52. -------
  53. Nothing
  54. """
  55. def in_venv():
  56. if sys.prefix == sys.base_prefix:
  57. raise ValueError( # noqa: TRY003
  58. "You need to run the code from the virtual environment."
  59. )
  60. return {
  61. "actions": [in_venv],
  62. }
  63. # Task to create the mapping files which map folder names to ISO 3-letter country codes
  64. read_config_folder = {
  65. "folder": get_var("folder", None),
  66. }
  67. def task_map_folders():
  68. """
  69. Create or update the folder mapping in the given folder
  70. """
  71. return {
  72. "actions": [(map_folders, [read_config_folder["folder"]])],
  73. "verbosity": 2,
  74. "setup": ["in_venv"],
  75. }
  76. # Tasks for getting submissions and downloading them
  77. def task_update_bur():
  78. """Update list of BUR submissions"""
  79. def fetch_bur():
  80. datalad.api.run(
  81. cmd="python3 src/unfccc_ghg_data/unfccc_downloader/"
  82. "fetch_submissions_bur.py",
  83. dataset=root_path,
  84. message="Fetch BUR submissions",
  85. outputs="downloaded_data/UNFCCC/submissions-bur.csv",
  86. dry_run=None,
  87. explicit=True,
  88. )
  89. return {
  90. "targets": ["downloaded_data/UNFCCC/submissions-bur.csv"],
  91. "actions": [
  92. (fetch_bur,),
  93. ],
  94. "verbosity": 2,
  95. "setup": ["in_venv"],
  96. }
  97. def task_download_bur():
  98. """Download BUR submissions"""
  99. def download_bur():
  100. (
  101. datalad.api.run(
  102. cmd="python3 src/unfccc_ghg_data/unfccc_downloader/"
  103. "download_nonannexI.py --category=BUR",
  104. dataset=root_path,
  105. message="Download BUR submissions",
  106. inputs="downloaded_data/UNFCCC/submissions-bur.csv",
  107. dry_run=None,
  108. explicit=False,
  109. ),
  110. )
  111. return {
  112. #'file_dep': ['downloaded_data/UNFCCC/submissions-bur.csv'],
  113. # deactivate file_dep fow now as it will always run fetch submissions
  114. # before download
  115. "actions": [
  116. (download_bur,),
  117. (map_folders, ["downloaded_data/UNFCCC"]),
  118. ],
  119. "verbosity": 2,
  120. "setup": ["in_venv"],
  121. }
  122. def task_update_nc():
  123. """Update list of NC submissions"""
  124. def fetch_nc():
  125. datalad.api.run(
  126. cmd="python3 src/unfccc_ghg_data/unfccc_downloader/"
  127. "fetch_submissions_nc.py",
  128. dataset=root_path,
  129. message="Fetch NC submissions",
  130. outputs="downloaded_data/UNFCCC/submissions-nc.csv",
  131. dry_run=None,
  132. explicit=True,
  133. )
  134. return {
  135. "targets": ["downloaded_data/UNFCCC/submissions-nc.csv"],
  136. "actions": [
  137. (fetch_nc,),
  138. ],
  139. "verbosity": 2,
  140. "setup": ["in_venv"],
  141. }
  142. def task_download_nc():
  143. """Download BUR submissions"""
  144. def download_nc():
  145. (
  146. datalad.api.run(
  147. cmd="python3 src/unfccc_ghg_data/unfccc_downloader/"
  148. "download_nonannexI.py --category=NC",
  149. dataset=root_path,
  150. message="Download NC submissions",
  151. inputs="downloaded_data/UNFCCC/submissions-nc.csv",
  152. dry_run=None,
  153. explicit=False,
  154. ),
  155. )
  156. return {
  157. #'file_dep': ['downloaded_data/UNFCCC/submissions-bur.csv'],
  158. # deactivate file_dep fow now as it will always run fetch submissions
  159. # before download
  160. "actions": [
  161. (download_nc,),
  162. (map_folders, ["downloaded_data/UNFCCC"]),
  163. ],
  164. "verbosity": 2,
  165. "setup": ["in_venv"],
  166. }
  167. # annexI data: one update call for all data types (as they are on one page)
  168. # but for each year separately.
  169. # downloading is per year and
  170. update_aI_config = {
  171. "year": get_var("year", None),
  172. "category": get_var("category", None),
  173. }
  174. def task_update_annexi():
  175. """Update list of AnnexI submissions"""
  176. def fetch_annexi():
  177. (
  178. datalad.api.run(
  179. cmd="python src/unfccc_ghg_data/unfccc_downloader/"
  180. "fetch_submissions_annexI.py "
  181. f"--year={update_aI_config['year']}",
  182. dataset=root_path,
  183. message=f"Fetch AnnexI submissions for {update_aI_config['year']}",
  184. outputs=f"downloaded_data/UNFCCC/submissions-annexI_"
  185. f"{update_aI_config['year']}.csv",
  186. dry_run=None,
  187. explicit=True,
  188. ),
  189. )
  190. return {
  191. "targets": [
  192. f"downloaded_data/UNFCCC/submissions-annexI_{update_aI_config['year']}.csv"
  193. ],
  194. "actions": [
  195. (fetch_annexi,),
  196. ],
  197. "verbosity": 2,
  198. "setup": ["in_venv"],
  199. }
  200. def task_download_annexi():
  201. """Download AnnexI submissions"""
  202. def download_annexi():
  203. (
  204. datalad.api.run(
  205. cmd="python src/unfccc_ghg_data/unfccc_downloader/download_annexI.py "
  206. f"--category={update_aI_config['category']} "
  207. f"--year={update_aI_config['year']}",
  208. dataset=root_path,
  209. message=f"Download AnnexI submissions for "
  210. f"{update_aI_config['category']}"
  211. f"{update_aI_config['year']}",
  212. inputs=f"downloaded_data/UNFCCC/submissions-annexI_"
  213. f"{update_aI_config['year']}.csv",
  214. dry_run=None,
  215. explicit=False,
  216. ),
  217. )
  218. return {
  219. # 'file_dep': [f"downloaded_data/UNFCCC/submissions-annex1_"
  220. # f"{update_aI_config['year']}.csv"],
  221. # deactivate file_dep fow now as it will always run fetch submissions
  222. # before download
  223. "actions": [
  224. (download_annexi,),
  225. (map_folders, ["downloaded_data/UNFCCC"]),
  226. ],
  227. "verbosity": 2,
  228. "setup": ["in_venv"],
  229. }
  230. # BTR data: one update call for all data types (as they are on one page)
  231. # but for each submission round separately.
  232. # downloading is per submission round
  233. update_btr_config = {
  234. "round": get_var("round", None),
  235. }
  236. def task_update_btr():
  237. """Update list of BTR submissions"""
  238. def fetch_btr():
  239. (
  240. datalad.api.run(
  241. cmd="python src/unfccc_ghg_data/unfccc_downloader/"
  242. "fetch_submissions_btr.py "
  243. f"--round={update_btr_config['round']}",
  244. dataset=root_path,
  245. message=f"Fetch Biannial Transparency Report submissions for "
  246. f"BTR{update_btr_config['round']}",
  247. outputs=f"downloaded_data/UNFCCC/submissions-BTR"
  248. f"{update_btr_config['round']}.csv",
  249. dry_run=None,
  250. explicit=True,
  251. ),
  252. )
  253. return {
  254. "targets": [
  255. f"downloaded_data/UNFCCC/submissions-BTR{update_btr_config['round']}.csv"
  256. ],
  257. "actions": [
  258. (fetch_btr,),
  259. ],
  260. "verbosity": 2,
  261. "setup": ["in_venv"],
  262. }
  263. def task_download_btr():
  264. """Download BTR submissions"""
  265. def download_btr():
  266. (
  267. datalad.api.run(
  268. cmd="python src/unfccc_ghg_data/unfccc_downloader/download_btr.py "
  269. f"--round={update_btr_config['round']}",
  270. dataset=root_path,
  271. message="Download BTR submissions for "
  272. f"BTR{update_btr_config['round']}",
  273. inputs=f"downloaded_data/UNFCCC/submissions-BTR"
  274. f"{update_btr_config['round']}.csv",
  275. dry_run=None,
  276. explicit=False,
  277. ),
  278. )
  279. return {
  280. # 'file_dep': [f"downloaded_data/UNFCCC/submissions-btr.csv "
  281. # f"{update_btr_config['round']}.csv"],
  282. # deactivate file_dep fow now as it will always run fetch submissions
  283. # before download
  284. "actions": [
  285. (download_btr,),
  286. (map_folders, ["downloaded_data/UNFCCC"]),
  287. ],
  288. "verbosity": 2,
  289. "setup": ["in_venv"],
  290. }
  291. def task_download_ndc():
  292. """Download NDC submissions"""
  293. def download_ndc():
  294. (
  295. datalad.api.run(
  296. cmd="src/unfccc_ghg_data/unfccc_downloader/download_ndc.py",
  297. dataset=root_path,
  298. message="Download NDC submissions",
  299. inputs=None,
  300. dry_run=None,
  301. explicit=False,
  302. ),
  303. )
  304. return {
  305. "actions": [
  306. (download_ndc,),
  307. (map_folders, ["downloaded_data/UNFCCC"]),
  308. ],
  309. "verbosity": 2,
  310. "setup": ["in_venv"],
  311. }
  312. # read UNFCCC submissions.
  313. # datalad run is called from within the read_UNFCCC_submission.py script
  314. read_config = {
  315. "country": get_var("country", None),
  316. "submission": get_var("submission", None),
  317. }
  318. # TODO: make individual task for non-UNFCCC submissions
  319. def task_read_unfccc_submission():
  320. """Read submission for a country (if code exists) (not for CRF)
  321. Datalad is called from `read_UNFCCC_submission`, so we can just call this script
  322. here.
  323. TODO: check if it makes sense to convert script to function
  324. """
  325. return {
  326. "actions": [
  327. f"python src/unfccc_ghg_data/unfccc_reader/read_UNFCCC_submission.py "
  328. f"--country={read_config['country']} "
  329. f"--submission={read_config['submission']}",
  330. (map_folders, ["extracted_data/UNFCCC"]),
  331. ],
  332. "verbosity": 2,
  333. "setup": ["in_venv"],
  334. }
  335. # read UNFCCC CRF submissions.
  336. # datalad run is called from within the read_UNFCCC_submission.py script
  337. read_config_crf = {
  338. "country": get_var("country", None),
  339. "submission_year": get_var("submission_year", None),
  340. "submission_date": get_var("submission_date", None),
  341. "re_read": get_var("re_read", False),
  342. "countries": get_var("countries", None),
  343. "data_year": get_var("data_year", None),
  344. "totest": get_var("totest", None),
  345. "type": get_var("type", "CRF"),
  346. }
  347. def task_read_unfccc_crf_submission():
  348. """Read CRF submission for a country"""
  349. def read_CRF():
  350. if read_config_crf["re_read"] == "True":
  351. re_read = True
  352. else:
  353. re_read = False
  354. read_crf_for_country_datalad(
  355. read_config_crf["country"],
  356. submission_year=int(read_config_crf["submission_year"]),
  357. submission_date=read_config_crf["submission_date"],
  358. re_read=re_read,
  359. type=read_config_crf["type"],
  360. )
  361. return {
  362. "actions": [
  363. (read_CRF,),
  364. (map_folders, ["extracted_data/UNFCCC"]),
  365. ],
  366. "verbosity": 2,
  367. "setup": ["in_venv"],
  368. }
  369. def task_read_new_unfccc_crf_for_year():
  370. """
  371. Read CRF/CRT submission for all countries for given submission year.
  372. By default only reads data not present yet. Only reads the latest updated
  373. submission for each country.
  374. """
  375. def read_new_CRF():
  376. if read_config_crf["re_read"] == "True":
  377. re_read = True
  378. else:
  379. re_read = False
  380. read_new_crf_for_year_datalad(
  381. submission_year=int(read_config_crf["submission_year"]),
  382. # countries=read_config_crf["countries"],
  383. re_read=re_read,
  384. type=read_config_crf["type"],
  385. )
  386. return {
  387. "actions": [
  388. (read_new_CRF,),
  389. (map_folders, ["extracted_data/UNFCCC"]),
  390. ],
  391. "verbosity": 2,
  392. "setup": ["in_venv"],
  393. }
  394. def task_test_read_unfccc_crf_for_year():
  395. """
  396. Test CRF/CRT reading.
  397. Test CRF/CRT with a single year only for speed and logging to extend specifications
  398. if necessary.
  399. """
  400. def read_CRF():
  401. if read_config_crf["totest"] == "True":
  402. totest = True
  403. else:
  404. totest = False
  405. if read_config_crf["data_year"] is not None:
  406. data_year = int(read_config_crf["data_year"])
  407. else:
  408. data_year = None
  409. read_year_to_test_specs(
  410. submission_year=int(read_config_crf["submission_year"]),
  411. data_year=data_year,
  412. totest=totest,
  413. country_code=read_config_crf["country"],
  414. type=read_config_crf["type"],
  415. )
  416. return {
  417. "actions": [
  418. (read_CRF,),
  419. (map_folders, ["extracted_data/UNFCCC"]),
  420. ],
  421. "verbosity": 2,
  422. "setup": ["in_venv"],
  423. }
  424. def task_compile_raw_unfccc_crf_for_year():
  425. """
  426. Collect all latest CRF/CRT submissions for a given year / submission round
  427. Reads the latest data from the extracted data folder for each country.
  428. Notifies the user if new data are available in the downloaded_data folder
  429. which have not yet been read.
  430. Data are saved in the datasets/UNFCCC/[CRFYYYY|CRTX] folder.
  431. TODO: could make a function from the script
  432. """
  433. actions = [
  434. f"python "
  435. f"src/unfccc_ghg_data/unfccc_crf_reader/crf_raw_for_year.py "
  436. f"--submission_year={read_config_crf['submission_year']} "
  437. f"--type={read_config_crf['type']} "
  438. ]
  439. return {
  440. "actions": actions,
  441. "verbosity": 2,
  442. "setup": ["in_venv"],
  443. }
  444. # tasks for DI reader
  445. # TODO DI tasks need testing
  446. # datalad run is called from within the read_unfccc_di_for_country.py script
  447. read_config_di = {
  448. "country": get_var("country", None),
  449. "date": get_var("date", None),
  450. "annexI": get_var("annexI", False),
  451. # "countries": get_var('countries', None),
  452. }
  453. def task_read_unfccc_di_for_country():
  454. """Read DI data for a country"""
  455. return {
  456. "actions": [
  457. (read_DI_for_country_datalad, [read_config_di["country"]]),
  458. (map_folders, ["extracted_data/UNFCCC"]),
  459. ],
  460. "verbosity": 2,
  461. "setup": ["in_venv"],
  462. }
  463. def task_process_unfccc_di_for_country():
  464. """Process DI data for a country"""
  465. return {
  466. "actions": [
  467. (
  468. process_DI_for_country_datalad,
  469. [],
  470. {
  471. "country": read_config_di["country"],
  472. "date_str": read_config_di["date"],
  473. },
  474. ),
  475. (map_folders, ["extracted_data/UNFCCC"]),
  476. ],
  477. "verbosity": 2,
  478. "setup": ["in_venv"],
  479. }
  480. def task_read_unfccc_di_for_country_group():
  481. """Read DI data for a country group"""
  482. def read_DI():
  483. if read_config_di["annexI"] == "True":
  484. annexI = True
  485. else:
  486. annexI = False
  487. read_DI_for_country_group_datalad(annexI=annexI)
  488. return {
  489. "actions": [(read_DI,), (map_folders, ["extracted_data/UNFCCC"])],
  490. "verbosity": 2,
  491. "setup": ["in_venv"],
  492. }
  493. def task_process_unfccc_di_for_country_group():
  494. """Process DI data for a country group"""
  495. def proc_DI():
  496. if read_config_di["annexI"] == "True":
  497. annexI = True
  498. else:
  499. annexI = False
  500. process_DI_for_country_group_datalad(
  501. annexI=annexI,
  502. date_str=read_config_di["date"],
  503. )
  504. return {
  505. "actions": [(proc_DI,), (map_folders, ["extracted_data/UNFCCC"])],
  506. "verbosity": 2,
  507. "setup": ["in_venv"],
  508. }
  509. # general tasks
  510. def task_country_info():
  511. """
  512. Print information on submissions and datasets available for given country
  513. """
  514. def country_info(country):
  515. # print available submissions
  516. print("=" * 15 + " Available submissions " + "=" * 15)
  517. get_country_submissions(country, True)
  518. print("")
  519. # print available datasets
  520. print("=" * 15 + " Available datasets " + "=" * 15)
  521. get_country_datasets(country, True)
  522. return {
  523. "actions": [(country_info, [read_config["country"]])],
  524. "verbosity": 2,
  525. "setup": ["in_venv"],
  526. }