functions.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  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. if cat_name_present:
  137. cat_name = subtract_cats_current[cat_to_generate]['name']
  138. data_agg = data_agg.assign_coords(
  139. coords={f'category ({cat_terminology_in})':
  140. (f'category ({cat_terminology_in})',
  141. [cat_to_generate])})
  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. data_country[basket] = xr.full_like(data_country["CO2"],
  247. np.nan).pr.quantify(
  248. units="Gg CO2 / year")
  249. data_country[basket].attrs = {"entity": basket.split(' ')[0],
  250. "gwp_context": basket.split(' ')[1][
  251. 1:-1]}
  252. data_country[basket] = data_country.pr.gas_basket_contents_sum(
  253. basket=basket, basket_contents=basket_contents_present,
  254. min_count=1)
  255. except Exception as ex:
  256. print(f"No gas basket created for {country_code}, {source}, "
  257. f"{scenario}: {ex}")
  258. # amend title and comment
  259. data_country.attrs["comment"] = data_country.attrs["comment"] + f" Processed on " \
  260. f"{date.today()}"
  261. data_country.attrs["title"] = data_country.attrs["title"] + f" Processed on " \
  262. f"{date.today()}"
  263. return data_country
  264. def convert_categories(
  265. ds_input: xr.Dataset,
  266. conversion: Dict[str, Dict[str, str]],
  267. #terminology_from: str,
  268. terminology_to: str,
  269. debug: bool=False,
  270. tolerance: float=0.01,
  271. )->xr.Dataset:
  272. """
  273. convert data from one category terminology to another
  274. """
  275. print(f"converting categories to {terminology_to}")
  276. if 'orig_cat_name' in ds_input.coords:
  277. cat_name_present = True
  278. else:
  279. cat_name_present = False
  280. ds_converted = ds_input.copy(deep=True)
  281. ds_converted.attrs = deepcopy(ds_input.attrs)
  282. # change category terminology
  283. cat_dim = ds_converted.attrs["cat"]
  284. ds_converted.attrs["cat"] = f"category ({terminology_to})"
  285. ds_converted = ds_converted.rename({cat_dim: ds_converted.attrs["cat"]})
  286. # find categories present in dataset
  287. cats_present = list(ds_converted.coords[f'category ({terminology_to})'])
  288. # restrict categories and map category names
  289. if 'mapping' in conversion.keys():
  290. mapping_cats_present = [cat for cat in list(conversion['mapping'].keys()) if
  291. cat in cats_present]
  292. ds_converted = ds_converted.pr.loc[
  293. {'category': mapping_cats_present}]
  294. from_cats = ds_converted.coords[f'category ({terminology_to})'].values
  295. to_cats = pd.Series(from_cats).replace(conversion['mapping'])
  296. ds_converted = ds_converted.assign_coords({f'category ({terminology_to})':
  297. (f'category ({terminology_to})',
  298. to_cats)})
  299. # redo the list of present cats after mapping, as we have new categories in the
  300. # target terminology now
  301. cats_present_mapped = list(ds_converted.coords[f'category ({terminology_to})'])
  302. # aggregate categories
  303. if 'aggregate' in conversion:
  304. aggregate_cats = conversion['aggregate']
  305. for cat_to_agg in aggregate_cats:
  306. if debug:
  307. print(f"Category: {cat_to_agg}")
  308. source_cats = [cat for cat in aggregate_cats[cat_to_agg]['sources'] if
  309. cat in cats_present_mapped]
  310. if debug:
  311. print(source_cats)
  312. data_agg = ds_converted.pr.loc[{'category': source_cats}].pr.sum(
  313. dim='category', skipna=True, min_count=1)
  314. nan_vars = [var for var in data_agg.data_vars if
  315. data_agg[var].isnull().all().data == True]
  316. data_agg = data_agg.drop(nan_vars)
  317. if len(data_agg.data_vars) > 0:
  318. data_agg = data_agg.expand_dims([f'category ({terminology_to})'])
  319. data_agg = data_agg.assign_coords(
  320. coords={f'category ({terminology_to})':
  321. (f'category ({terminology_to})', [cat_to_agg])})
  322. if cat_name_present:
  323. data_agg = data_agg.assign_coords(
  324. coords={'orig_cat_name':
  325. (f'category ({terminology_to})',
  326. [aggregate_cats[cat_to_agg]['name']])})
  327. ds_converted = ds_converted.pr.merge(data_agg, tolerance=tolerance)
  328. cats_present_mapped.append(cat_to_agg)
  329. else:
  330. print(f"no data to aggregate category {cat_to_agg}")
  331. return ds_converted
  332. def get_country_name(
  333. country_code: str,
  334. ) -> str:
  335. """get country name from code """
  336. if country_code in custom_country_mapping:
  337. country_name = custom_country_mapping[country_code]
  338. else:
  339. try:
  340. country = pycountry.countries.get(alpha_3=country_code)
  341. country_name = country.name
  342. except:
  343. raise ValueError(f"Country code {country_code} can not be mapped to "
  344. f"any country")
  345. return country_name
  346. def get_country_code(
  347. country_name: str,
  348. )->str:
  349. """
  350. obtain country code. If the input is a code it will be returned,
  351. if the input
  352. is not a three letter code a search will be performed
  353. Parameters
  354. __________
  355. country_name: str
  356. Country code or name to get the three-letter code for.
  357. Returns
  358. -------
  359. country_code: str
  360. """
  361. # First check if it's in the list of custom codes
  362. if country_name in custom_country_mapping:
  363. country_code = country_name
  364. else:
  365. try:
  366. # check if it's a 3 letter UNFCCC_GHG_data
  367. country = pycountry.countries.get(alpha_3=country_name)
  368. country_code = country.alpha_3
  369. except:
  370. try:
  371. country = pycountry.countries.search_fuzzy(country_name.replace("_", " "))
  372. except:
  373. raise ValueError(f"Country name {country_name} can not be mapped to "
  374. f"any country UNFCCC_GHG_data. Try using the ISO3 UNFCCC_GHG_data directly.")
  375. if len(country) > 1:
  376. country_code = None
  377. for current_country in country:
  378. if current_country.name == country_name:
  379. country_code = current_country.alpha_3
  380. if country_code is None:
  381. raise ValueError(f"Country name {country_name} has {len(country)} "
  382. f"possible results for country codes.")
  383. country_code = country[0].alpha_3
  384. return country_code
  385. def create_folder_mapping(
  386. folder: str,
  387. extracted: bool = False
  388. ) -> None:
  389. """
  390. Create a mapping from 3 letter ISO country codes to folders
  391. based on the subfolders of the given folder. The mapping is
  392. stored in 'folder_mapping.json' in the given folder. Folder
  393. must be given relative to the repository root
  394. Parameters
  395. ----------
  396. folder: str
  397. folder to create the mapping for
  398. extracted: bool = False
  399. If true treat the folder as extracted data, where we
  400. only have one folder per country and no typos in the
  401. names
  402. Returns
  403. -------
  404. Nothing
  405. """
  406. folder = root_path / folder
  407. folder_mapping = {}
  408. #if not extracted:
  409. known_folders = custom_folders
  410. #else:
  411. # known_folders = {}
  412. for item in folder.iterdir():
  413. if item.is_dir() and not item.match("__pycache__"):
  414. if item.name in known_folders:
  415. ISO3 = known_folders[item.name]
  416. else:
  417. try:
  418. country = pycountry.countries.search_fuzzy(item.name.replace("_", " "))
  419. if len(country) > 1:
  420. ISO3 = None
  421. for current_country in country:
  422. if current_country.name == item.name.replace("_", " "):
  423. ISO3 = current_country.alpha_3
  424. else:
  425. ISO3 = country[0].alpha_3
  426. except:
  427. ISO3 = None
  428. if ISO3 is None:
  429. print(f"No match for {item.name}")
  430. else:
  431. if ISO3 in folder_mapping.keys():
  432. folder_mapping[ISO3] = [folder_mapping[ISO3], item.name]
  433. else:
  434. folder_mapping[ISO3] = item.name
  435. with open(folder / "folder_mapping.json", "w") as mapping_file:
  436. json.dump(folder_mapping, mapping_file, indent=4)
  437. # TODO add crf
  438. def get_country_submissions(
  439. country_name: str,
  440. print_sub: bool = True,
  441. ) -> Dict[str, List[str]]:
  442. """
  443. Input is a three letter ISO UNFCCC_GHG_data for a country, or the countries name.
  444. The function tries to map the country name to an ISO UNFCCC_GHG_data and then
  445. queries the folder mapping files for folders.
  446. Parameters
  447. ----------
  448. country_name: str
  449. String containing the country name or ISO 3 letter UNFCCC_GHG_data
  450. print_sub: bool
  451. If True information on submissions will be written to stdout
  452. Returns
  453. -------
  454. returns a dict with keys for the dataset classes (e.g. UNFCCC, non-UNFCCC)
  455. Each value is a list of folders
  456. """
  457. data_folder = downloaded_data_path
  458. country_code = get_country_code(country_name)
  459. if print_sub:
  460. print(f"Country name {country_name} maps to ISO code {country_code}")
  461. country_submissions = {}
  462. if print_sub:
  463. print(f"#" * 80)
  464. print(f"The following submissions are available for {country_name}")
  465. for item in data_folder.iterdir():
  466. if item.is_dir():
  467. if print_sub:
  468. print("")
  469. print("-" * 80)
  470. print(f"Data folder {item.name}")
  471. print("-" * 80)
  472. with open(item / "folder_mapping.json", "r") as mapping_file:
  473. folder_mapping = json.load(mapping_file)
  474. if country_code in folder_mapping:
  475. country_folders = folder_mapping[country_code]
  476. if isinstance(country_folders, str):
  477. # only one folder
  478. country_folders = [country_folders]
  479. submission_folders = []
  480. for country_folder in country_folders:
  481. current_folder = item / country_folder
  482. if print_sub:
  483. print(f"Submissions in folder {country_folder}:")
  484. for submission_folder in current_folder.iterdir():
  485. if submission_folder.is_dir():
  486. if print_sub:
  487. print(submission_folder.name)
  488. submission_folders.append(submission_folder.name)
  489. country_submissions[item.name] = submission_folders
  490. else:
  491. print(f"No submissions available for {country_name}.")
  492. return country_submissions
  493. def get_country_datasets(
  494. country_name: str,
  495. print_ds: bool = True,
  496. ) -> Dict[str, List[str]]:
  497. """
  498. Input is a three letter ISO code for a country, or the country's name.
  499. The function tries to map the country name to an ISO UNFCCC_GHG_data and then
  500. checks the UNFCCC_GHG_data and data folders for content on the country.
  501. Parameters
  502. ----------
  503. country_name: str
  504. String containing the country name or ISO 3 letter code
  505. print_ds: bool
  506. If True information on submissions will be written to stdout
  507. Returns
  508. -------
  509. returns a dict with keys for the dataset classes (e.g. UNFCCC, non-UNFCCC)
  510. Each value is a list of folders
  511. """
  512. data_folder = extracted_data_path
  513. data_folder_legacy = legacy_data_path
  514. # obtain country UNFCCC_GHG_data
  515. country_code = get_country_code(country_name)
  516. if print_ds:
  517. print(f"Country name {country_name} maps to ISO code {country_code}")
  518. rep_data = {}
  519. # data
  520. if print_ds:
  521. print(f"#" * 80)
  522. print(f"The following datasets are available for {country_name}")
  523. for item in data_folder.iterdir():
  524. if item.is_dir():
  525. cleaned_datasets_current_folder = {}
  526. if print_ds:
  527. print("-" * 80)
  528. print(f"Data folder {item.name}")
  529. print("-" * 80)
  530. with open(item / "folder_mapping.json", "r") as mapping_file:
  531. folder_mapping = json.load(mapping_file)
  532. if country_code not in folder_mapping:
  533. if print_ds:
  534. print("No data available")
  535. print("")
  536. else:
  537. country_folder = folder_mapping[country_code]
  538. if not isinstance(country_folder, str):
  539. raise ValueError("Wrong data type in folder mapping json file. Should be str.")
  540. datasets_current_folder = {}
  541. current_folder = item / country_folder
  542. for data_file in current_folder.iterdir():
  543. if data_file.suffix in ['.nc', '.yaml', '.csv']:
  544. if data_file.stem in datasets_current_folder:
  545. datasets_current_folder[data_file.stem].append(data_file.suffix)
  546. else:
  547. datasets_current_folder[data_file.stem] = [data_file.suffix]
  548. for dataset in datasets_current_folder:
  549. # process filename to get submission
  550. parts = dataset.split('_')
  551. if parts[0] != country_code:
  552. cleaned_datasets_current_folder[f'Wrong code: {parts[0]}'] =\
  553. dataset
  554. else:
  555. terminology = "_".join(parts[3 : ])
  556. key = f"{parts[1]} ({parts[2]}, {terminology})"
  557. data_info = ""
  558. if '.nc' in datasets_current_folder[dataset]:
  559. data_info = data_info + "NF (.nc), "
  560. if ('.csv' in datasets_current_folder[dataset]) and ('.yaml' in datasets_current_folder[dataset]):
  561. data_info = data_info + "IF (.yaml + .csv), "
  562. elif '.csv' in datasets_current_folder[dataset]:
  563. data_info = data_info + "incomplete IF? (.csv), "
  564. elif '.yaml' in datasets_current_folder[dataset]:
  565. data_info = data_info + "incomplete IF (.yaml), "
  566. code_file = get_code_file(country_code, parts[1])
  567. if code_file:
  568. data_info = data_info + f"code: {code_file.name}"
  569. else:
  570. data_info = data_info + f"code: not found"
  571. cleaned_datasets_current_folder[key] = data_info
  572. if print_ds:
  573. if cleaned_datasets_current_folder:
  574. for country_ds in cleaned_datasets_current_folder:
  575. print(f"{country_ds}: {cleaned_datasets_current_folder[country_ds]}")
  576. else:
  577. print("No data available")
  578. print("")
  579. rep_data[item.name] = cleaned_datasets_current_folder
  580. # legacy data
  581. if print_ds:
  582. print(f"#" * 80)
  583. print(f"The following legacy datasets are available for {country_name}")
  584. legacy_data = {}
  585. for item in data_folder_legacy.iterdir():
  586. if item.is_dir():
  587. cleaned_datasets_current_folder = {}
  588. if print_ds:
  589. print("-" * 80)
  590. print(f"Data folder {item.name}")
  591. print("-" * 80)
  592. with open(item / "folder_mapping.json", "r") as mapping_file:
  593. folder_mapping = json.load(mapping_file)
  594. if country_code not in folder_mapping:
  595. if print_ds:
  596. print("No data available")
  597. print("")
  598. else:
  599. country_folder = folder_mapping[country_code]
  600. if not isinstance(country_folder, str):
  601. raise ValueError("Wrong data type in folder mapping json file. Should be str.")
  602. datasets_current_folder = {}
  603. current_folder = item / country_folder
  604. for data_file in current_folder.iterdir():
  605. if data_file.suffix in ['.nc', '.yaml', '.csv']:
  606. if data_file.stem in datasets_current_folder:
  607. datasets_current_folder[data_file.stem].append(data_file.suffix)
  608. else:
  609. datasets_current_folder[data_file.stem] = [data_file.suffix]
  610. for dataset in datasets_current_folder:
  611. # process filename to get submission
  612. parts = dataset.split('_')
  613. if parts[0] != country_code:
  614. cleaned_datasets_current_folder[f'Wrong UNFCCC_GHG_data: {parts[0]}'] = dataset
  615. else:
  616. terminology = "_".join(parts[3 : ])
  617. key = f"{parts[1]} ({parts[2]}, {terminology}, legacy)"
  618. data_info = ""
  619. if '.nc' in datasets_current_folder[dataset]:
  620. data_info = data_info + "NF (.nc), "
  621. if ('.csv' in datasets_current_folder[dataset]) and ('.yaml' in datasets_current_folder[dataset]):
  622. data_info = data_info + "IF (.yaml + .csv), "
  623. elif '.csv' in datasets_current_folder[dataset]:
  624. data_info = data_info + "incomplete IF? (.csv), "
  625. elif '.yaml' in datasets_current_folder[dataset]:
  626. data_info = data_info + "incomplete IF (.yaml), "
  627. cleaned_datasets_current_folder[key] = data_info
  628. if print_ds:
  629. if cleaned_datasets_current_folder:
  630. for country_ds in cleaned_datasets_current_folder:
  631. print(f"{country_ds}: {cleaned_datasets_current_folder[country_ds]}")
  632. else:
  633. print("No data available")
  634. print("")
  635. legacy_data[item.name] = cleaned_datasets_current_folder
  636. all_data = {
  637. "rep_data": rep_data,
  638. "legacy_data": legacy_data,
  639. }
  640. return all_data
  641. def get_code_file(
  642. country_name: str,
  643. submission: str,
  644. print_info: bool = False,
  645. ) -> Path:
  646. """
  647. For given country name and submission find the script that creates the data
  648. Parameters
  649. ----------
  650. country_name: str
  651. String containing the country name or ISO 3 letter UNFCCC_GHG_data
  652. submission: str
  653. String of the submission
  654. print_info: bool = False
  655. If True print information on UNFCCC_GHG_data found
  656. Returns
  657. -------
  658. returns a pathlib Path object for the UNFCCC_GHG_data file
  659. """
  660. code_file_path = None
  661. UNFCCC_reader_path = code_path / "UNFCCC_reader"
  662. # CRF is an exception as it's read using the UNFCCC_CRF_reader module
  663. # so we return the path to that.
  664. if submission[0:3] == "CRF":
  665. return root_path / "UNFCCC_CRF_reader"
  666. if submission[0:2] == "DI":
  667. return root_path / "UNFCCC_DI_reader"
  668. # obtain country UNFCCC_GHG_data
  669. country_code = get_country_code(country_name)
  670. if print_info:
  671. print(f"Country name {country_name} maps to ISO UNFCCC_GHG_data {country_code}")
  672. with open(UNFCCC_reader_path / "folder_mapping.json", "r") as mapping_file:
  673. folder_mapping = json.load(mapping_file)
  674. if country_code not in folder_mapping:
  675. if print_info:
  676. print("No UNFCCC_GHG_data available")
  677. print("")
  678. else:
  679. country_folder = UNFCCC_reader_path / folder_mapping[country_code]
  680. code_file_name_candidate = "read_" + country_code + "_" + submission + "*"
  681. for file in country_folder.iterdir():
  682. if file.match(code_file_name_candidate):
  683. if code_file_path is not None:
  684. raise ValueError(f"Found multiple UNFCCC_GHG_data candidates: "
  685. f"{code_file_path} and file.name. "
  686. f"Please use only one file with name "
  687. f"'read_ISO3_submission_XXX.YYY'.")
  688. else:
  689. if print_info:
  690. print(f"Found UNFCCC_GHG_data file {file.relative_to(root_path)}")
  691. code_file_path = file
  692. if code_file_path is not None:
  693. return code_file_path.relative_to(root_path)
  694. else:
  695. return None