functions.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. import pycountry
  2. import json
  3. import re
  4. import xarray as xr
  5. import pandas as pd
  6. import numpy as np
  7. from datetime import date
  8. from copy import deepcopy
  9. from typing import Dict, List, Optional
  10. from pathlib import Path
  11. from .definitions import custom_country_mapping, custom_folders
  12. from .definitions import root_path, downloaded_data_path, extracted_data_path
  13. from .definitions import legacy_data_path, code_path
  14. def process_data_for_country(
  15. data_country: xr.Dataset,
  16. entities_to_ignore: List[str],
  17. gas_baskets: Dict[str, List[str]],
  18. filter_dims: Optional[Dict[str, List[str]]] = None,
  19. cat_terminology_out: Optional[str] = None,
  20. category_conversion: Dict[str, Dict] = None,
  21. sectors_out: List[str] = None,
  22. processing_info_country: Dict = None,
  23. ) -> xr.Dataset:
  24. """
  25. Process data from DI interface (where necessary).
  26. * Downscaling including subtraction of time series
  27. * country specific sector aggregation
  28. * Conversion to IPCC2006 categories
  29. * general sector and gas basket aggregation (in new categories)
  30. """
  31. # 0: gather information
  32. countries = list(data_country.coords[data_country.attrs['area']].values)
  33. if len(countries) > 1:
  34. raise ValueError(
  35. f"Found {len(countries)} countries. Only single country data "
  36. f"can be processed by this function. countries: {countries}")
  37. else:
  38. country_code = countries[0]
  39. # get category terminology
  40. cat_col = data_country.attrs['cat']
  41. temp = re.findall(r'\((.*)\)', cat_col)
  42. cat_terminology_in = temp[0]
  43. # get scenario
  44. scenarios = list(data_country.coords[data_country.attrs['scen']].values)
  45. if len(scenarios) > 1:
  46. raise ValueError(
  47. f"Found {len(scenarios)} scenarios. Only single scenario data "
  48. f"can be processed by this function. Scenarios: {scenarios}")
  49. scenario = scenarios[0]
  50. # get source
  51. sources = list(data_country.coords['source'].values)
  52. if len(sources) > 1:
  53. raise ValueError(
  54. f"Found {len(sources)} sources. Only single source data "
  55. f"can be processed by this function. Sources: {sources}")
  56. source = sources[0]
  57. # check if category name column present
  58. # TODO: replace 'name' in config by 'additional_cols' dict that defines the cols
  59. # and the values
  60. if 'orig_cat_name' in data_country.coords:
  61. cat_name_present = True
  62. else:
  63. cat_name_present = False
  64. # 1: general processing
  65. # remove unused cats
  66. data_country = data_country.dropna(f'category ({cat_terminology_in})', how='all')
  67. # remove unused years
  68. data_country = data_country.dropna(f'time', how='all')
  69. # remove variables only containing nan
  70. nan_vars_country = [var for var in data_country.data_vars if
  71. data_country[var].isnull().all().data is True]
  72. print(f"removing all-nan variables: {nan_vars_country}")
  73. data_country = data_country.drop_vars(nan_vars_country)
  74. # remove unnecessary variables
  75. entities_ignore_present = [entity for entity in entities_to_ignore if
  76. entity in data_country.data_vars]
  77. data_country = data_country.drop_vars(entities_ignore_present)
  78. # filter ()
  79. if filter_dims is not None:
  80. data_country = data_country.pr.loc[filter_dims]
  81. # 2: country specific processing
  82. if processing_info_country is not None:
  83. if 'tolerance' in processing_info_country:
  84. tolerance = processing_info_country["tolerance"]
  85. else:
  86. tolerance = 0.01
  87. # remove entities if needed
  88. if 'ignore_entities' in processing_info_country:
  89. entities_to_ignore_country = processing_info_country[
  90. 'ignore_entities']
  91. entities_ignore_present = \
  92. [entity for entity in entities_to_ignore_country if
  93. entity in data_country.data_vars]
  94. data_country = data_country.drop_vars(entities_ignore_present)
  95. # take only desired years
  96. if 'years' in processing_info_country:
  97. data_country = data_country.pr.loc[
  98. {'time': processing_info_country['years']}]
  99. # remove timeseries if desired
  100. if 'remove_ts' in processing_info_country:
  101. for case in processing_info_country['remove_ts']:
  102. remove_info = processing_info_country['remove_ts'][case]
  103. entities = remove_info.pop("entities")
  104. for entity in entities:
  105. data_country[entity].pr.loc[remove_info] = \
  106. data_country[entity].pr.loc[remove_info] * np.nan
  107. # remove all data for given years if necessary
  108. if 'remove_years' in processing_info_country:
  109. data_country = data_country.drop_sel(
  110. time=processing_info_country['remove_years'])
  111. # subtract categories
  112. if 'subtract_cats' in processing_info_country:
  113. subtract_cats_current = processing_info_country['subtract_cats']
  114. if 'entities' in subtract_cats_current.keys():
  115. entities_current = subtract_cats_current['entities']
  116. else:
  117. entities_current = list(data_country.data_vars)
  118. print(f"Subtracting categories for country {country_code}, entities "
  119. f"{entities_current}")
  120. for cat_to_generate in subtract_cats_current:
  121. cats_to_subtract = \
  122. subtract_cats_current[cat_to_generate]['subtract']
  123. data_sub = \
  124. data_country.pr.loc[{'category': cats_to_subtract}].pr.sum(
  125. dim='category', skipna=True, min_count=1)
  126. data_parent = data_country.pr.loc[
  127. {'category': subtract_cats_current[cat_to_generate]['parent']}]
  128. data_agg = data_parent - data_sub
  129. nan_vars = [var for var in data_agg.data_vars if
  130. data_agg[var].isnull().all().data is True]
  131. data_agg = data_agg.drop(nan_vars)
  132. if len(data_agg.data_vars) > 0:
  133. print(f"Generating {cat_to_generate} through subtraction")
  134. data_agg = data_agg.expand_dims([f'category ('
  135. f'{cat_terminology_in})'])
  136. data_agg = data_agg.assign_coords(
  137. coords={f'category ({cat_terminology_in})':
  138. (f'category ({cat_terminology_in})',
  139. [cat_to_generate])})
  140. if cat_name_present:
  141. cat_name = subtract_cats_current[cat_to_generate]['name']
  142. data_agg = data_agg.assign_coords(
  143. coords={'orig_cat_name':
  144. (f'category ({cat_terminology_in})',
  145. [cat_name])})
  146. data_country = data_country.pr.merge(data_agg,
  147. tolerance=tolerance)
  148. else:
  149. print(f"no data to generate category {cat_to_generate}")
  150. # downscaling
  151. if 'downscale' in processing_info_country:
  152. if 'sectors' in processing_info_country['downscale']:
  153. sector_downscaling = \
  154. processing_info_country['downscale']['sectors']
  155. for case in sector_downscaling.keys():
  156. print(f"Downscaling for {case}.")
  157. sector_downscaling_current = sector_downscaling[case]
  158. entities = sector_downscaling_current.pop('entities')
  159. for entity in entities:
  160. data_country[entity] = data_country[
  161. entity].pr.downscale_timeseries(
  162. **sector_downscaling_current)
  163. # , skipna_evaluation_dims=None)
  164. if 'entities' in processing_info_country['downscale']:
  165. entity_downscaling = \
  166. processing_info_country['downscale']['entities']
  167. for case in entity_downscaling.keys():
  168. print(f"Downscaling for {case}.")
  169. # print(data_country.coords[f'category ('
  170. # f'{cat_terminology_in})'].values)
  171. data_country = data_country.pr.downscale_gas_timeseries(
  172. **entity_downscaling[case], skipna=True,
  173. skipna_evaluation_dims=None)
  174. # aggregate categories
  175. if 'aggregate_cats' in processing_info_country:
  176. if 'agg_tolerance' in processing_info_country:
  177. agg_tolerance = processing_info_country['agg_tolerance']
  178. else:
  179. agg_tolerance = tolerance
  180. aggregate_cats_current = processing_info_country['aggregate_cats']
  181. print(
  182. f"Aggregating categories for country {country_code}, source {source}, "
  183. f"scenario {scenario}")
  184. for cat_to_agg in aggregate_cats_current:
  185. print(f"Category: {cat_to_agg}")
  186. source_cats = aggregate_cats_current[cat_to_agg]['sources']
  187. data_agg = data_country.pr.loc[{'category': source_cats}].pr.sum(
  188. dim='category', skipna=True, min_count=1)
  189. nan_vars = [var for var in data_agg.data_vars if
  190. data_agg[var].isnull().all().data is True]
  191. data_agg = data_agg.drop(nan_vars)
  192. if len(data_agg.data_vars) > 0:
  193. data_agg = data_agg.expand_dims([f'category ('
  194. f'{cat_terminology_in})'])
  195. data_agg = data_agg.assign_coords(
  196. coords={f'category ({cat_terminology_in})':
  197. (f'category ({cat_terminology_in})',
  198. [cat_to_agg])})
  199. if cat_name_present:
  200. cat_name = aggregate_cats_current[cat_to_agg]['name']
  201. data_agg = data_agg.assign_coords(
  202. coords={'orig_cat_name':
  203. (f'category ({cat_terminology_in})',
  204. [cat_name])})
  205. data_country = data_country.pr.merge(data_agg,
  206. tolerance=agg_tolerance)
  207. else:
  208. print(f"no data to aggregate category {cat_to_agg}")
  209. # aggregate gases if desired
  210. if 'aggregate_gases' in processing_info_country:
  211. for case in processing_info_country['aggregate_gases'].keys():
  212. case_info = processing_info_country['aggregate_gases'][case]
  213. data_country[case_info['basket']] = \
  214. data_country.pr.fill_na_gas_basket_from_contents(
  215. **case_info)
  216. # 3: map categories
  217. if category_conversion is not None:
  218. data_country = convert_categories(
  219. data_country,
  220. category_conversion,
  221. cat_terminology_out,
  222. debug=False,
  223. tolerance=0.01,
  224. )
  225. else:
  226. cat_terminology_out = cat_terminology_in
  227. # more general processing
  228. # reduce categories to output cats
  229. if sectors_out is not None:
  230. cats_to_keep = [cat for cat in
  231. data_country.coords[f'category ({cat_terminology_out})'].values
  232. if cat in sectors_out]
  233. data_country = data_country.pr.loc[{'category': cats_to_keep}]
  234. # create gas baskets
  235. entities_present = set(data_country.data_vars)
  236. for basket in gas_baskets.keys():
  237. basket_contents_present = [gas for gas in gas_baskets[basket] if
  238. gas in entities_present]
  239. if len(basket_contents_present) > 0:
  240. if basket in list(data_country.data_vars):
  241. data_country[basket] = data_country.pr.fill_na_gas_basket_from_contents(
  242. basket=basket, basket_contents=basket_contents_present,
  243. skipna=True, min_count=1)
  244. else:
  245. try:
  246. #print(data_country.data_vars)
  247. data_country[basket] = xr.full_like(data_country["CO2"],
  248. np.nan).pr.quantify(
  249. units="Gg CO2 / year")
  250. data_country[basket].attrs = {"entity": basket.split(' ')[0],
  251. "gwp_context": basket.split(' ')[1][
  252. 1:-1]}
  253. data_country[basket] = data_country.pr.gas_basket_contents_sum(
  254. basket=basket, basket_contents=basket_contents_present,
  255. min_count=1)
  256. except Exception as ex:
  257. print(f"No gas basket created for {country_code}, {source}, "
  258. f"{scenario}: {ex}")
  259. # amend title and comment
  260. data_country.attrs["comment"] = data_country.attrs["comment"] + f" Processed on " \
  261. f"{date.today()}"
  262. data_country.attrs["title"] = data_country.attrs["title"] + f" Processed on " \
  263. f"{date.today()}"
  264. return data_country
  265. def convert_categories(
  266. ds_input: xr.Dataset,
  267. conversion: Dict[str, Dict[str, str]],
  268. #terminology_from: str,
  269. terminology_to: str,
  270. debug: bool=False,
  271. tolerance: float=0.01,
  272. )->xr.Dataset:
  273. """
  274. convert data from one category terminology to another
  275. """
  276. print(f"converting categories to {terminology_to}")
  277. if 'orig_cat_name' in ds_input.coords:
  278. cat_name_present = True
  279. else:
  280. cat_name_present = False
  281. ds_converted = ds_input.copy(deep=True)
  282. ds_converted.attrs = deepcopy(ds_input.attrs)
  283. # change category terminology
  284. cat_dim = ds_converted.attrs["cat"]
  285. ds_converted.attrs["cat"] = f"category ({terminology_to})"
  286. ds_converted = ds_converted.rename({cat_dim: ds_converted.attrs["cat"]})
  287. # find categories present in dataset
  288. cats_present = list(ds_converted.coords[f'category ({terminology_to})'])
  289. # restrict categories and map category names
  290. if 'mapping' in conversion.keys():
  291. mapping_cats_present = [cat for cat in list(conversion['mapping'].keys()) if
  292. cat in cats_present]
  293. ds_converted = ds_converted.pr.loc[
  294. {'category': mapping_cats_present}]
  295. from_cats = ds_converted.coords[f'category ({terminology_to})'].values
  296. to_cats = pd.Series(from_cats).replace(conversion['mapping'])
  297. ds_converted = ds_converted.assign_coords({f'category ({terminology_to})':
  298. (f'category ({terminology_to})',
  299. to_cats)})
  300. # redo the list of present cats after mapping, as we have new categories in the
  301. # target terminology now
  302. cats_present_mapped = list(ds_converted.coords[f'category ({terminology_to})'])
  303. # aggregate categories
  304. if 'aggregate' in conversion:
  305. aggregate_cats = conversion['aggregate']
  306. for cat_to_agg in aggregate_cats:
  307. if debug:
  308. print(f"Category: {cat_to_agg}")
  309. source_cats = [cat for cat in aggregate_cats[cat_to_agg]['sources'] if
  310. cat in cats_present_mapped]
  311. if debug:
  312. print(source_cats)
  313. data_agg = ds_converted.pr.loc[{'category': source_cats}].pr.sum(
  314. dim='category', skipna=True, min_count=1)
  315. nan_vars = [var for var in data_agg.data_vars if
  316. data_agg[var].isnull().all().data == True]
  317. data_agg = data_agg.drop(nan_vars)
  318. if len(data_agg.data_vars) > 0:
  319. data_agg = data_agg.expand_dims([f'category ({terminology_to})'])
  320. data_agg = data_agg.assign_coords(
  321. coords={f'category ({terminology_to})':
  322. (f'category ({terminology_to})', [cat_to_agg])})
  323. if cat_name_present:
  324. data_agg = data_agg.assign_coords(
  325. coords={'orig_cat_name':
  326. (f'category ({terminology_to})',
  327. [aggregate_cats[cat_to_agg]['name']])})
  328. ds_converted = ds_converted.pr.merge(data_agg, tolerance=tolerance)
  329. cats_present_mapped.append(cat_to_agg)
  330. else:
  331. print(f"no data to aggregate category {cat_to_agg}")
  332. return ds_converted
  333. def get_country_name(
  334. country_code: str,
  335. ) -> str:
  336. """get country name from code """
  337. if country_code in custom_country_mapping:
  338. country_name = custom_country_mapping[country_code]
  339. else:
  340. try:
  341. country = pycountry.countries.get(alpha_3=country_code)
  342. country_name = country.name
  343. except:
  344. raise ValueError(f"Country code {country_code} can not be mapped to "
  345. f"any country")
  346. return country_name
  347. def get_country_code(
  348. country_name: str,
  349. )->str:
  350. """
  351. obtain country code. If the input is a code it will be returned,
  352. if the input
  353. is not a three letter code a search will be performed
  354. Parameters
  355. __________
  356. country_name: str
  357. Country code or name to get the three-letter code for.
  358. Returns
  359. -------
  360. country_code: str
  361. """
  362. # First check if it's in the list of custom codes
  363. if country_name in custom_country_mapping:
  364. country_code = country_name
  365. else:
  366. try:
  367. # check if it's a 3 letter UNFCCC_GHG_data
  368. country = pycountry.countries.get(alpha_3=country_name)
  369. country_code = country.alpha_3
  370. except:
  371. try:
  372. country = pycountry.countries.search_fuzzy(country_name.replace("_", " "))
  373. except:
  374. raise ValueError(f"Country name {country_name} can not be mapped to "
  375. f"any country UNFCCC_GHG_data. Try using the ISO3 UNFCCC_GHG_data directly.")
  376. if len(country) > 1:
  377. country_code = None
  378. for current_country in country:
  379. if current_country.name == country_name:
  380. country_code = current_country.alpha_3
  381. if country_code is None:
  382. raise ValueError(f"Country name {country_name} has {len(country)} "
  383. f"possible results for country codes.")
  384. country_code = country[0].alpha_3
  385. return country_code
  386. def create_folder_mapping(
  387. folder: str,
  388. extracted: bool = False
  389. ) -> None:
  390. """
  391. Create a mapping from 3 letter ISO country codes to folders
  392. based on the subfolders of the given folder. The mapping is
  393. stored in 'folder_mapping.json' in the given folder. Folder
  394. must be given relative to the repository root
  395. Parameters
  396. ----------
  397. folder: str
  398. folder to create the mapping for
  399. extracted: bool = False
  400. If true treat the folder as extracted data, where we
  401. only have one folder per country and no typos in the
  402. names
  403. Returns
  404. -------
  405. Nothing
  406. """
  407. folder = root_path / folder
  408. folder_mapping = {}
  409. #if not extracted:
  410. known_folders = custom_folders
  411. #else:
  412. # known_folders = {}
  413. for item in folder.iterdir():
  414. if item.is_dir() and not item.match("__pycache__"):
  415. if item.name in known_folders:
  416. ISO3 = known_folders[item.name]
  417. else:
  418. try:
  419. country = pycountry.countries.search_fuzzy(item.name.replace("_", " "))
  420. if len(country) > 1:
  421. ISO3 = None
  422. for current_country in country:
  423. if current_country.name == item.name.replace("_", " "):
  424. ISO3 = current_country.alpha_3
  425. else:
  426. ISO3 = country[0].alpha_3
  427. except:
  428. ISO3 = None
  429. if ISO3 is None:
  430. print(f"No match for {item.name}")
  431. else:
  432. if ISO3 in folder_mapping.keys():
  433. folder_mapping[ISO3] = [folder_mapping[ISO3], item.name]
  434. else:
  435. folder_mapping[ISO3] = item.name
  436. with open(folder / "folder_mapping.json", "w") as mapping_file:
  437. json.dump(folder_mapping, mapping_file, indent=4)
  438. # TODO add crf
  439. def get_country_submissions(
  440. country_name: str,
  441. print_sub: bool = True,
  442. ) -> Dict[str, List[str]]:
  443. """
  444. Input is a three letter ISO UNFCCC_GHG_data for a country, or the countries name.
  445. The function tries to map the country name to an ISO UNFCCC_GHG_data and then
  446. queries the folder mapping files for folders.
  447. Parameters
  448. ----------
  449. country_name: str
  450. String containing the country name or ISO 3 letter UNFCCC_GHG_data
  451. print_sub: bool
  452. If True information on submissions will be written to stdout
  453. Returns
  454. -------
  455. returns a dict with keys for the dataset classes (e.g. UNFCCC, non-UNFCCC)
  456. Each value is a list of folders
  457. """
  458. data_folder = downloaded_data_path
  459. country_code = get_country_code(country_name)
  460. if print_sub:
  461. print(f"Country name {country_name} maps to ISO code {country_code}")
  462. country_submissions = {}
  463. if print_sub:
  464. print(f"#" * 80)
  465. print(f"The following submissions are available for {country_name}")
  466. for item in data_folder.iterdir():
  467. if item.is_dir():
  468. if print_sub:
  469. print("")
  470. print("-" * 80)
  471. print(f"Data folder {item.name}")
  472. print("-" * 80)
  473. with open(item / "folder_mapping.json", "r") as mapping_file:
  474. folder_mapping = json.load(mapping_file)
  475. if country_code in folder_mapping:
  476. country_folders = folder_mapping[country_code]
  477. if isinstance(country_folders, str):
  478. # only one folder
  479. country_folders = [country_folders]
  480. submission_folders = []
  481. for country_folder in country_folders:
  482. current_folder = item / country_folder
  483. if print_sub:
  484. print(f"Submissions in folder {country_folder}:")
  485. for submission_folder in current_folder.iterdir():
  486. if submission_folder.is_dir():
  487. if print_sub:
  488. print(submission_folder.name)
  489. submission_folders.append(submission_folder.name)
  490. country_submissions[item.name] = submission_folders
  491. else:
  492. print(f"No submissions available for {country_name}.")
  493. return country_submissions
  494. def get_country_datasets(
  495. country_name: str,
  496. print_ds: bool = True,
  497. ) -> Dict[str, List[str]]:
  498. """
  499. Input is a three letter ISO code for a country, or the country's name.
  500. The function tries to map the country name to an ISO UNFCCC_GHG_data and then
  501. checks the UNFCCC_GHG_data and data folders for content on the country.
  502. Parameters
  503. ----------
  504. country_name: str
  505. String containing the country name or ISO 3 letter code
  506. print_ds: bool
  507. If True information on submissions will be written to stdout
  508. Returns
  509. -------
  510. returns a dict with keys for the dataset classes (e.g. UNFCCC, non-UNFCCC)
  511. Each value is a list of folders
  512. """
  513. data_folder = extracted_data_path
  514. data_folder_legacy = legacy_data_path
  515. # obtain country UNFCCC_GHG_data
  516. country_code = get_country_code(country_name)
  517. if print_ds:
  518. print(f"Country name {country_name} maps to ISO code {country_code}")
  519. rep_data = {}
  520. # data
  521. if print_ds:
  522. print(f"#" * 80)
  523. print(f"The following datasets are available for {country_name}")
  524. for item in data_folder.iterdir():
  525. if item.is_dir():
  526. cleaned_datasets_current_folder = {}
  527. if print_ds:
  528. print("-" * 80)
  529. print(f"Data folder {item.name}")
  530. print("-" * 80)
  531. with open(item / "folder_mapping.json", "r") as mapping_file:
  532. folder_mapping = json.load(mapping_file)
  533. if country_code not in folder_mapping:
  534. if print_ds:
  535. print("No data available")
  536. print("")
  537. else:
  538. country_folder = folder_mapping[country_code]
  539. if not isinstance(country_folder, str):
  540. raise ValueError("Wrong data type in folder mapping json file. Should be str.")
  541. datasets_current_folder = {}
  542. current_folder = item / country_folder
  543. for data_file in current_folder.iterdir():
  544. if data_file.suffix in ['.nc', '.yaml', '.csv']:
  545. if data_file.stem in datasets_current_folder:
  546. datasets_current_folder[data_file.stem].append(data_file.suffix)
  547. else:
  548. datasets_current_folder[data_file.stem] = [data_file.suffix]
  549. for dataset in datasets_current_folder:
  550. # process filename to get submission
  551. parts = dataset.split('_')
  552. if parts[0] != country_code:
  553. cleaned_datasets_current_folder[f'Wrong code: {parts[0]}'] =\
  554. dataset
  555. else:
  556. terminology = "_".join(parts[3 : ])
  557. key = f"{parts[1]} ({parts[2]}, {terminology})"
  558. data_info = ""
  559. if '.nc' in datasets_current_folder[dataset]:
  560. data_info = data_info + "NF (.nc), "
  561. if ('.csv' in datasets_current_folder[dataset]) and ('.yaml' in datasets_current_folder[dataset]):
  562. data_info = data_info + "IF (.yaml + .csv), "
  563. elif '.csv' in datasets_current_folder[dataset]:
  564. data_info = data_info + "incomplete IF? (.csv), "
  565. elif '.yaml' in datasets_current_folder[dataset]:
  566. data_info = data_info + "incomplete IF (.yaml), "
  567. code_file = get_code_file(country_code, parts[1])
  568. if code_file:
  569. data_info = data_info + f"code: {code_file.name}"
  570. else:
  571. data_info = data_info + f"code: not found"
  572. cleaned_datasets_current_folder[key] = data_info
  573. if print_ds:
  574. if cleaned_datasets_current_folder:
  575. for country_ds in cleaned_datasets_current_folder:
  576. print(f"{country_ds}: {cleaned_datasets_current_folder[country_ds]}")
  577. else:
  578. print("No data available")
  579. print("")
  580. rep_data[item.name] = cleaned_datasets_current_folder
  581. # legacy data
  582. if print_ds:
  583. print(f"#" * 80)
  584. print(f"The following legacy datasets are available for {country_name}")
  585. legacy_data = {}
  586. for item in data_folder_legacy.iterdir():
  587. if item.is_dir():
  588. cleaned_datasets_current_folder = {}
  589. if print_ds:
  590. print("-" * 80)
  591. print(f"Data folder {item.name}")
  592. print("-" * 80)
  593. with open(item / "folder_mapping.json", "r") as mapping_file:
  594. folder_mapping = json.load(mapping_file)
  595. if country_code not in folder_mapping:
  596. if print_ds:
  597. print("No data available")
  598. print("")
  599. else:
  600. country_folder = folder_mapping[country_code]
  601. if not isinstance(country_folder, str):
  602. raise ValueError("Wrong data type in folder mapping json file. Should be str.")
  603. datasets_current_folder = {}
  604. current_folder = item / country_folder
  605. for data_file in current_folder.iterdir():
  606. if data_file.suffix in ['.nc', '.yaml', '.csv']:
  607. if data_file.stem in datasets_current_folder:
  608. datasets_current_folder[data_file.stem].append(data_file.suffix)
  609. else:
  610. datasets_current_folder[data_file.stem] = [data_file.suffix]
  611. for dataset in datasets_current_folder:
  612. # process filename to get submission
  613. parts = dataset.split('_')
  614. if parts[0] != country_code:
  615. cleaned_datasets_current_folder[f'Wrong UNFCCC_GHG_data: {parts[0]}'] = dataset
  616. else:
  617. terminology = "_".join(parts[3 : ])
  618. key = f"{parts[1]} ({parts[2]}, {terminology}, legacy)"
  619. data_info = ""
  620. if '.nc' in datasets_current_folder[dataset]:
  621. data_info = data_info + "NF (.nc), "
  622. if ('.csv' in datasets_current_folder[dataset]) and ('.yaml' in datasets_current_folder[dataset]):
  623. data_info = data_info + "IF (.yaml + .csv), "
  624. elif '.csv' in datasets_current_folder[dataset]:
  625. data_info = data_info + "incomplete IF? (.csv), "
  626. elif '.yaml' in datasets_current_folder[dataset]:
  627. data_info = data_info + "incomplete IF (.yaml), "
  628. cleaned_datasets_current_folder[key] = data_info
  629. if print_ds:
  630. if cleaned_datasets_current_folder:
  631. for country_ds in cleaned_datasets_current_folder:
  632. print(f"{country_ds}: {cleaned_datasets_current_folder[country_ds]}")
  633. else:
  634. print("No data available")
  635. print("")
  636. legacy_data[item.name] = cleaned_datasets_current_folder
  637. all_data = {
  638. "rep_data": rep_data,
  639. "legacy_data": legacy_data,
  640. }
  641. return all_data
  642. def get_code_file(
  643. country_name: str,
  644. submission: str,
  645. print_info: bool = False,
  646. ) -> Path:
  647. """
  648. For given country name and submission find the script that creates the data
  649. Parameters
  650. ----------
  651. country_name: str
  652. String containing the country name or ISO 3 letter UNFCCC_GHG_data
  653. submission: str
  654. String of the submission
  655. print_info: bool = False
  656. If True print information on UNFCCC_GHG_data found
  657. Returns
  658. -------
  659. returns a pathlib Path object for the UNFCCC_GHG_data file
  660. """
  661. code_file_path = None
  662. UNFCCC_reader_path = code_path / "UNFCCC_reader"
  663. # CRF is an exception as it's read using the UNFCCC_CRF_reader module
  664. # so we return the path to that.
  665. if submission[0:3] == "CRF":
  666. return root_path / "UNFCCC_CRF_reader"
  667. if submission[0:2] == "DI":
  668. return root_path / "UNFCCC_DI_reader"
  669. # obtain country UNFCCC_GHG_data
  670. country_code = get_country_code(country_name)
  671. if print_info:
  672. print(f"Country name {country_name} maps to ISO UNFCCC_GHG_data {country_code}")
  673. with open(UNFCCC_reader_path / "folder_mapping.json", "r") as mapping_file:
  674. folder_mapping = json.load(mapping_file)
  675. if country_code not in folder_mapping:
  676. if print_info:
  677. print("No UNFCCC_GHG_data available")
  678. print("")
  679. else:
  680. country_folder = UNFCCC_reader_path / folder_mapping[country_code]
  681. code_file_name_candidate = "read_" + country_code + "_" + submission + "*"
  682. for file in country_folder.iterdir():
  683. if file.match(code_file_name_candidate):
  684. if code_file_path is not None:
  685. raise ValueError(f"Found multiple UNFCCC_GHG_data candidates: "
  686. f"{code_file_path} and file.name. "
  687. f"Please use only one file with name "
  688. f"'read_ISO3_submission_XXX.YYY'.")
  689. else:
  690. if print_info:
  691. print(f"Found UNFCCC_GHG_data file {file.relative_to(root_path)}")
  692. code_file_path = file
  693. if code_file_path is not None:
  694. return code_file_path.relative_to(root_path)
  695. else:
  696. return None