functions.py 33 KB

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