code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
logger_excel.info("enter place_tables_section") try: logger_excel.info("excel: place_tables_section: placing table: {}".format(sheet["new_name"])) new_name = sheet["new_name"] logger_excel.info("placing_tables_section: {}".format(new_name)) # get all the sheet metadata neede...
def _place_tables_section(skeleton_section, sheet, keys_section)
Place data into skeleton for either a paleo or chron section. :param dict skeleton_section: Empty or current progress of skeleton w/ data :param dict sheet: Sheet metadata :param list keys_section: Paleo or Chron specific keys :return dict: Skeleton section full of data
3.55993
3.318993
1.072593
logger_excel.info("enter place_tables_main") for sheet in sheets: pc = sheet["paleo_chron"] if pc == "paleo": skeleton_paleo = _place_tables_section(skeleton_paleo, sheet, ["paleoMeasurementTable", "paleoModel"]) elif pc == "chron": skeleton_chron = _place_t...
def _place_tables_main(sheets, skeleton_paleo, skeleton_chron)
All the data has been parsed, skeletons have been created, now put the data into the skeletons. :param list sheets: All metadata needed to place sheet data into the LiPD structure :param list skeleton_paleo: The empty skeleton where we will place data :param list skeleton_chron: The empty skeleton where we ...
3.974432
4.025132
0.987404
tt = sheet["table_type"] idx_pc = sheet["idx_pc"] idx_table = sheet["idx_table"] idx_model = sheet["idx_model"] # Have we started counters for this idx model yet?? if idx_pc not in num_section: # No, create the counters and start tracking table counts num_section[idx_pc] = ...
def _get_table_counts(sheet, num_section)
Loop through sheet metadata and count how many of each table type is needed at each index. Example: 'paleo 1' needs {'2 measurement tables', '1 model table, with 1 summary, 1 ensemble, and 3 distributions'} :param dict sheet: Sheet metadata :param dict num_section: Rolling number counts of table types for e...
3.469317
3.19483
1.085916
logger_excel.info("enter create_skeleton_inner_2") # Table Template: Model template_model = {"summaryTable": {}, "ensembleTable": {}, "distributionTable": []} # Build string appropriate for paleo/chron mode pc_meas = "{}MeasurementTable".format(pc) pc_mod = "{}Model".format(pc) # Loo...
def _create_skeleton_3(pc, l, num_section)
Bottom level: {"measurement": [], "model": [{summary, distributions, ensemble}]} Fill in measurement and model tables with N number of EMPTY meas, summary, ensemble, and distributions. :param str pc: Paleo or Chron "mode" :param list l: :param dict num_section: :return dict:
5.981791
4.698796
1.273048
logger_excel.info("enter create_skeleton_inner_1") try: # Create N number of paleoData/chronData tables. l = [copy.deepcopy(template)] * len(num_section) # Create the necessary tables inside of "model" l = _create_skeleton_3(pc, l, num_section) except Exception as e: ...
def _create_skeleton_2(l, pc, num_section, template)
Mid level: {"measurement", "model"} Fill in paleoData tables with N number of EMPTY measurement and models. :param list l: paleoData or chronData list of tables :param dict num_section: Number of tables needed for each table type :param dict template: The empty template for the measurement and model to...
11.037683
7.954309
1.387636
logger_excel.info("enter create_skeleton_main") # Table template: paleoData template_paleo = {"paleoMeasurementTable": [], "paleoModel": []} template_chron = {"chronMeasurementTable": [], "chronModel": []} num_chron = {} num_paleo = {} paleo = [] chron = [] # Get table counts...
def _create_skeleton_1(sheets)
Top level: {"chronData", "paleoData"} Fill in paleoData/chronData tables with N number of EMPTY measurement and models. :return list: Blank list of N indices
4.28028
3.811202
1.123079
# Get row of data row = temp_sheet.row(num_row) # In case our row holds more cells than the amount of columns we have, slice the row # We don't want to have extra empty cells in our output. row = row[:col_total] # Replace missing values where necessary row = _replace_mvs(row, mv) ...
def _parse_sheet_data_row(temp_sheet, num_row, col_total, table_data, filename, mv)
Parse a row from the data section of the sheet. Add the cleaned row data to the overall table data. :param obj temp_sheet: Excel sheet :param int num_row: Current sheet row :param int col_total: Number of column variables in this sheet :param dict table_data: Running record of table data :param str ...
6.195095
5.989942
1.03425
for idx, v in enumerate(row): try: if v.value.lower() in EMPTY or v.value.lower() == mv: row[idx] = "nan" else: row[idx] = v.value except AttributeError: if v.value == mv: row[idx] = "nan" else: ...
def _replace_mvs(row, mv)
Replace Missing Values in the data rows where applicable :param list row: Row :return list: Modified row
2.776772
2.857121
0.971878
# Swap out NOAA keys for LiPD keys for idx, key in enumerate(row): key_low = key.value.lower() # Simple case: Nothing fancy here, just map to the LiPD key counterpart. if key_low in EXCEL_LIPD_MAP_FLAT: row[idx] = EXCEL_LIPD_MAP_FLAT[key_low] # Nested data case...
def _get_header_keys(row)
Get the variable header keys from this special row :return list: Header keys
8.113619
8.394531
0.966536
# Use the regex to match the cell m = re.match(re_var_w_units, var) # Should always get a match, but be careful anyways. if m: # m.group(1): variableName # m.group(2): units in parenthesis (may not exist). try: var = m.group(1).strip().lower() # var =...
def _rm_units_from_var_name_single(var)
NOTE: USE THIS FOR SINGLE CELLS ONLY When parsing sheets, all variable names be exact matches when cross-referenceing the metadata and data sections However, sometimes people like to put "age (years BP)" in one section, and "age" in the other. This causes problems. We're using this regex to match all variab...
8.221725
6.814897
1.206434
l2 = [] # Check each var in the row for idx, var in enumerate(row): l2.append(_rm_units_from_var_name_single(row[idx].value)) return l2
def _rm_units_from_var_names_multi(row)
Wrapper around "_rm_units_from_var_name_single" for doing a list instead of a single cell. :param list row: Variable names :return list: Variable names
4.975809
4.503524
1.10487
# KEY FORMAT : "interpretation1_somekey" _count = 0 # Determine how many entries we are going to need, by checking the interpretation index in the string for _key in data.keys(): _key_low = _key.lower() # Get regex match m = re.match(re_interpretation, _key_low) # I...
def _compile_interpretation(data)
Compile the interpretation data into a list of multiples, based on the keys provided. Disassemble the key to figure out how to place the data :param dict data: Interpretation data (unsorted) :return dict: Interpretation data (sorted)
5.586008
5.413815
1.031806
# Store the variable keys by index in a dictionary _column = {} _interpretation = {} _calibration = {} _physical = {} # Use the header keys to place the column data in the dictionary if keys: for idx, key in enumerate(keys): _key_low = key.lower() # Spe...
def _compile_column_metadata(row, keys, number)
Compile column metadata from one excel row ("9 part data") :param list row: Row of cells :param list keys: Variable header keys :return dict: Column metadata
3.474669
3.415925
1.017197
rm = [] # Iter the list in reverse, and get rid of empty and template cells for idx, key in reversed(list(enumerate(l))): if key.lower() in EXCEL_TEMPLATE: rm.append(idx) elif key in EMPTY: rm.append(idx) else: break for idx in rm: ...
def _rm_cells_reverse(l)
Remove the cells that are empty or template in reverse order. Stop when you hit data. :param list l: One row from the spreadsheet :return list: Modified row
4.714375
4.46159
1.056658
logger_excel.info("enter write_data_csv") # Loop for each file and data that is stored for file in csv_data: for filename, data in file.items(): # Make sure we're working with the right data types before trying to open and write a file if isinstance(filename, str) and is...
def _write_data_csv(csv_data)
CSV data has been parsed by this point, so take it and write it file by file. :return:
3.6775
3.658592
1.005168
logger_excel.info("enter geometry_linestring") d = OrderedDict() coordinates = [] temp = ["", ""] # Point type, Matching pairs. if lat[0] == lat[1] and lon[0] == lon[1]: logger_excel.info("matching geo coordinate") lat.pop() lon.pop() d = geometry_point(lat,...
def geometry_linestring(lat, lon, elev)
GeoJSON Linestring. Latitude and Longitude have 2 values each. :param list lat: Latitude values :param list lon: Longitude values :return dict:
4.389218
4.35222
1.008501
d = OrderedDict() coordinates = [[] for i in range(len(crd_range))] # latitude if crd_type == "lat": for idx, i in enumerate(crd_range): coordinates[idx] = [crd_range[idx], "nan"] if elev: coordinates[idx].append(elev) # longitude elif crd_...
def geometry_range(crd_range, elev, crd_type)
Range of coordinates. (e.g. 2 latitude coordinates, and 0 longitude coordinates) :param crd_range: Latitude or Longitude values :param elev: Elevation value :param crd_type: Coordinate type, lat or lon :return dict:
2.398063
2.224639
1.077956
logger_excel.info("enter geometry_point") coordinates = [] point_dict = OrderedDict() for idx, val in enumerate(lat): try: coordinates.append(lon[idx]) coordinates.append(lat[idx]) except IndexError as e: print("Error: Invalid geo coordinates") ...
def geometry_point(lat, lon, elev)
GeoJSON point. Latitude and Longitude only have one value each :param list lat: Latitude values :param list lon: Longitude values :param float elev: Elevation value :return dict:
3.67874
3.622817
1.015436
logger_excel.info("enter compile_geometry") lat = _remove_geo_placeholders(lat) lon = _remove_geo_placeholders(lon) # 4 coordinate values if len(lat) == 2 and len(lon) == 2: logger_excel.info("found 4 coordinates") geo_dict = geometry_linestring(lat, lon, elev) # # 4 c...
def compile_geometry(lat, lon, elev)
Take in lists of lat and lon coordinates, and determine what geometry to create :param list lat: Latitude values :param list lon: Longitude values :param float elev: Elevation value :return dict:
2.892881
2.88783
1.001749
logger_excel.info("enter compile_geo") d2 = OrderedDict() # get max number of sites, or number of coordinate points given. num_loc = _get_num_locations(d) # if there's one more than one location put it in a collection if num_loc > 1: d2["type"] = "FeatureCollection" featur...
def compile_geo(d)
Compile top-level Geography dictionary. :param d: :return:
4.802529
4.804667
0.999555
lengths = [] for key in EXCEL_GEO: try: if key != "siteName": lengths.append(len(d[key])) except Exception: lengths.append(1) try: num = max(lengths) except ValueError: num = 0 return num
def _get_num_locations(d)
Find out how many locations are being parsed. Compare lengths of each coordinate list and return the max :param dict d: Geo metadata :return int: Max number of locations
4.835405
4.453823
1.085675
d2 = OrderedDict() filt = {} d2['type'] = 'Feature' # If the necessary keys are missing, put in placeholders so there's no KeyErrors. for key in EXCEL_GEO: if key not in d: d[key] = "" # Compile the geometry based on the info available. d2['geometry'] = compile_geom...
def _parse_geo_location(d)
Parse one geo location :param d: :return:
6.765552
6.672112
1.014004
d2 = OrderedDict() filt = {} d2['type'] = 'Feature' # If the necessary keys are missing, put in placeholders so there's no KeyErrors. for key in EXCEL_GEO: if key not in d: d[key] = "" for key in EXCEL_GEO: try: if key == "siteName" and isinstance(d[...
def _parse_geo_locations(d, idx)
Parse one geo location :param d: :return:
4.135637
4.161019
0.9939
logger_excel.info("enter compile_authors") author_lst = [] s = cell.split(';') for w in s: author_lst.append(w.lstrip()) logger_excel.info("exit compile_authors") return author_lst
def compile_authors(cell)
Split the string of author names into the BibJSON format. :param str cell: Data from author cell :return: (list of dicts) Author names
4.462519
4.539865
0.982963
if not value: d[key] = None elif len(value) == 1: d[key] = value[0] else: d[key] = value return d
def compile_temp(d, key, value)
Compiles temporary dictionaries for metadata. Adds a new entry to an existing dictionary. :param dict d: :param str key: :param any value: :return dict:
2.235231
2.505396
0.892167
logger_excel.info("enter compile_fund") l = [] temp_sheet = workbook.sheet_by_name(sheet) while col < temp_sheet.ncols: col += 1 try: # Make a dictionary for this funding entry. _curr = { 'agency': temp_sheet.cell_value(row, col), ...
def compile_fund(workbook, sheet, row, col)
Compile funding entries. Iter both rows at the same time. Keep adding entries until both cells are empty. :param obj workbook: :param str sheet: :param int row: :param int col: :return list of dict: l
3.514439
3.20092
1.097947
try: a1 = [i for i in a1 if i] a2 = [i for i in a2 if i] a3 = set(a1).symmetric_difference(set(a2)) if a3: print("- Error: Variables are not entered correctly in sheet: {}\n\tUnmatched variables: {}".format(name, a3)) except Exception as e: logger_excel.e...
def __compare_vars(a1, a2, name)
Check that the metadata variable names are the same as the data header variable names :param list a1: Variable names :param list a2: Variable names :param str name: Sheet name :return bool: Truth
4.003655
3.88895
1.029495
try: filename = d["dataSetName"] except KeyError: logger_excel.info("get_datasetname: KeyError: No dataSetName found. Reverting to: {}".format(filename)) return filename
def __get_datasetname(d, filename)
Get the filename based on the dataset name in the metadata :param str filename: Filename.lpd :return str: Filename
9.550574
9.8482
0.969779
try: for idx, sheet in enumerate(sheets): try: sheets[idx]["filename"] = "{}.{}".format(n, sheet["filename"]) except Exception as e: logger_excel.error("set_sheet_filenames: inner: {}".format(e), exc_info=True) except Exception as q: l...
def __set_sheet_filenames(sheets, n)
Use the dataset name to build the filenames in the sheets metadata :param list sheets: Sheet metadata :param str n: Dataset Name :return list: Sheet metadata
2.94462
2.913478
1.010689
title_out = '' try: title_in = title_in.lower() title_out = EXCEL_LIPD_MAP_FLAT[title_in] except (KeyError, AttributeError) as e: if "(" in title_in: title_in = title_in.split("(")[0].strip() # try to find an exact match first. try: v = EX...
def name_to_jsonld(title_in)
Convert formal titles to camelcase json_ld text that matches our context file Keep a growing list of all titles that are being used in the json_ld context :param str title_in: :return str:
3.328732
3.479846
0.956574
if isinstance(cell, str): return 'str' elif isinstance(cell, int): return 'int' elif isinstance(cell, float): return 'float' else: return 'unknown'
def instance_str(cell)
Match data type and return string :param any cell: :return str:
1.974024
2.088645
0.945122
start = '(' stop = ')' return string_in[string_in.index(start) + 1:string_in.index(stop)]
def extract_units(string_in)
Extract units from parenthesis in a string. i.e. "elevation (meters)" :param str string_in: :return str:
3.660755
3.671986
0.996941
logger_excel.info("enter cells_rt_meta_pub") col_loop = 0 cell_data = [] temp_sheet = workbook.sheet_by_name(sheet) while col_loop < pub_qty: col += 1 col_loop += 1 cell_data.append(temp_sheet.cell_value(row, col)) logger_excel.info("exit cells_rt_meta_pub") retu...
def cells_rt_meta_pub(workbook, sheet, row, col, pub_qty)
Publication section is special. It's possible there's more than one publication. :param obj workbook: :param str sheet: :param int row: :param int col: :param int pub_qty: Number of distinct publication sections in this file :return list: Cell data for a specific row
2.742929
2.587041
1.060257
logger_excel.info("enter cells_rt_meta") col_loop = 0 cell_data = [] temp_sheet = workbook.sheet_by_name(sheet) while col_loop < temp_sheet.ncols: col += 1 col_loop += 1 try: if temp_sheet.cell_value(row, col) != xlrd.empty_cell and temp_sheet.cell_value(row,...
def cells_rt_meta(workbook, sheet, row, col)
Traverse all cells in a row. If you find new data in a cell, add it to the list. :param obj workbook: :param str sheet: :param int row: :param int col: :return list: Cell data for a specific row
2.624099
2.543063
1.031865
logger_excel.info("enter cells_dn_meta") row_loop = 0 pub_cases = ['id', 'year', 'author', 'journal', 'issue', 'volume', 'title', 'pages', 'reportNumber', 'abstract', 'alternateCitation'] geo_cases = ['latMin', 'lonMin', 'lonMax', 'latMax', 'elevation', 'siteName', 'location'] ...
def cells_dn_meta(workbook, sheet, row, col, final_dict)
Traverse all cells in a column moving downward. Primarily created for the metadata sheet, but may use elsewhere. Check the cell title, and switch it to. :param obj workbook: :param str sheet: :param int row: :param int col: :param dict final_dict: :return: none
3.805092
3.744347
1.016223
total_count = 0 start_row = traverse_to_chron_var(temp_sheet) while temp_sheet.cell_value(start_row, 0) != '': total_count += 1 start_row += 1 return total_count
def count_chron_variables(temp_sheet)
Count the number of chron variables :param obj temp_sheet: :return int: variable count
3.300497
3.459885
0.953933
col_dict = OrderedDict() out_list = [] column = 1 while (temp_sheet.cell_value(start_row, 0) != '') and (start_row < temp_sheet.nrows): short_cell = temp_sheet.cell_value(start_row, 0) units_cell = temp_sheet.cell_value(start_row, 1) long_cell = temp_sheet.cell_value(start_...
def get_chron_var(temp_sheet, start_row)
Capture all the vars in the chron sheet (for json-ld output) :param obj temp_sheet: :param int start_row: :return: (list of dict) column data
2.405435
2.455227
0.97972
traverse_row = traverse_to_chron_var(temp_sheet) reference_var = temp_sheet.cell_value(traverse_row, 0) # Traverse past all the short_names, until you hit a blank cell (the barrier) while temp_sheet.cell_value(traverse_row, 0) != '': traverse_row += 1 # Traverse past the empty cells un...
def traverse_to_chron_data(temp_sheet)
Traverse down to the first row that has chron data :param obj temp_sheet: :return int: traverse_row
3.858104
3.744681
1.030289
row = 0 while row < temp_sheet.nrows - 1: if 'Parameter' in temp_sheet.cell_value(row, 0): row += 1 break row += 1 logger_excel.info("traverse_to_chron_var: row:{}".format(row)) return row
def traverse_to_chron_var(temp_sheet)
Traverse down to the row that has the first variable :param obj temp_sheet: :return int:
3.479979
3.659892
0.950842
data_row = [] missing_val_list = ['none', 'na', '', '-'] for i in range(0, total_vars): cell = temp_sheet.cell_value(row, i) if isinstance(cell, str): cell = cell.lower() if cell in missing_val_list: cell = 'nan' data_row.append(cell) return d...
def get_chron_data(temp_sheet, row, total_vars)
Capture all data in for a specific chron data row (for csv output) :param obj temp_sheet: :param int row: :param int total_vars: :return list: data_row
2.703444
2.690227
1.004913
vals = [] for i in l: if isinstance(i, list): for k in i: if isinstance(k, float) or isinstance(k, int): vals.append(k) elif isinstance(i, float) or isinstance(i, int): vals.append(i) vals.sort() return vals
def _remove_geo_placeholders(l)
Remove placeholders from coordinate lists and sort :param list l: Lat or long list :return list: Modified list
2.128416
2.114138
1.006754
_d = {} try: # Find a jsonld file in cwd. If none, fallback for a json file. If neither found, return empty. _filename = [file for file in os.listdir() if file.endswith(".jsonld")][0] if not _filename: _filename = [file for file in os.listdir() if file.endswith(".json")...
def read_jsonld()
Find jsonld file in the cwd (or within a 2 levels below cwd), and load it in. :return dict: Jsonld data
3.229826
3.226975
1.000884
logger_jsons.info("enter read_json_from_file") d = OrderedDict() try: # Load and decode d = demjson.decode_file(filename, decode_float=float) logger_jsons.info("successful read from json file") except FileNotFoundError: # Didn't find a jsonld file. Maybe it's a json ...
def read_json_from_file(filename)
Import the JSON data from target file. :param str filename: Target File :return dict: JSON data
4.097269
4.213871
0.972329
logger_jsons.info("enter idx_num_to_name") try: if "paleoData" in L: L["paleoData"] = _import_data(L["paleoData"], "paleo") if "chronData" in L: L["chronData"] = _import_data(L["chronData"], "chron") except Exception as e: logger_jsons.error("idx_num_to_...
def idx_num_to_name(L)
Switch from index-by-number to index-by-name. :param dict L: Metadata :return dict L: Metadata
2.859273
2.899829
0.986014
logger_jsons.info("enter import_data: {}".format(crumbs)) _sections = OrderedDict() try: for _idx, section in enumerate(sections): _tmp = OrderedDict() # Process the paleo measurement table if "measurementTable" in section: _tmp["measurementT...
def _import_data(sections, crumbs)
Import the section metadata and change it to index-by-name. :param list sections: Metadata :param str pc: paleo or chron :return dict _sections: Metadata
4.078297
3.798489
1.073663
logger_jsons.info("enter import_model".format(crumbs)) _models = OrderedDict() try: for _idx, model in enumerate(models): # Keep the original dictionary, but replace the three main entries below # Do a direct replacement of chronModelTable columns. No table name, no tab...
def _import_model(models, crumbs)
Change the nested items of the paleoModel data. Overwrite the data in-place. :param list models: Metadata :param str crumbs: Crumbs :return dict _models: Metadata
3.63338
3.498755
1.038478
_tables = OrderedDict() try: for _idx, _table in enumerate(tables): # Use "name" as tableName _name = "{}{}".format(crumbs, _idx) # Call idx_table_by_name _tmp = _idx_col_by_name(_table) if _name in _tables: _name = "{}_{}"...
def _idx_table_by_name(tables, crumbs)
Import summary, ensemble, or distribution data. :param list tables: Metadata :return dict _tables: Metadata
3.669111
3.739883
0.981076
_columns = OrderedDict() # Iter for each column in the list try: for _column in table["columns"]: try: _name = _column["variableName"] if _name in _columns: _name = get_appended_name(_name, _columns) _columns[_name...
def _idx_col_by_name(table)
Iter over columns list. Turn indexed-by-num list into an indexed-by-name dict. Keys are the variable names. :param dict table: Metadata :return dict _table: Metadata
3.336089
3.186064
1.047088
logger_jsons.info("enter get_csv_from_json") csv_data = OrderedDict() if "paleoData" in d: csv_data = _get_csv_from_section(d, "paleoData", csv_data) if "chronData" in d: csv_data = _get_csv_from_section(d, "chronData", csv_data) logger_jsons.info("exit get_csv_from_json") ...
def get_csv_from_json(d)
Get CSV values when mixed into json data. Pull out the CSV data and put it into a dictionary. :param dict d: JSON with CSV values :return dict: CSV values. (i.e. { CSVFilename1: { Column1: [Values], Column2: [Values] }, CSVFilename2: ... }
3.018535
3.068722
0.983646
logger_jsons.info("enter get_csv_from_section: {}".format(pc)) for table, table_content in d[pc].items(): # Create entry for this table/CSV file (i.e. Asia-1.measTable.PaleoData.csv) # Note: Each table has a respective CSV file. csv_data[table_content['filename']] = OrderedDict() ...
def _get_csv_from_section(d, pc, csv_data)
Get csv from paleo and chron sections :param dict d: Metadata :param str pc: Paleo or chron :return dict: running csv data
6.130168
6.007996
1.020335
logger_jsons.info("enter remove_csv_from_json") # Check both sections if "paleoData" in d: d = _remove_csv_from_section(d, "paleoData") if "chronData" in d: d = _remove_csv_from_section(d, "chronData") logger_jsons.info("exit remove_csv_from_json") return d
def remove_csv_from_json(d)
Remove all CSV data 'values' entries from paleoData table in the JSON structure. :param dict d: JSON data - old structure :return dict: Metadata dictionary without CSV values
3.637516
3.214048
1.131755
logger_jsons.info("enter remove_csv_from_json: {}".format(pc)) for table, table_content in d[pc].items(): for column, column_content in table_content['columns'].items(): try: # try to delete the values key entry del column_content['values'] e...
def _remove_csv_from_section(d, pc)
Remove CSV from metadata in this section :param dict d: Metadata :param str pc: Paleo or chron :return dict: Modified metadata
3.847528
3.976275
0.967621
logger_jsons.info("enter write_json_to_file") json_data = rm_empty_fields(json_data) # Use demjson to maintain unicode characters in output json_bin = demjson.encode(json_data, encoding='utf-8', compactly=False) # Write json to file try: open("{}.jsonld".format(filename), "wb").writ...
def write_json_to_file(json_data, filename="metadata")
Write all JSON in python dictionary to a new json file. :param dict json_data: JSON data :param str filename: Target filename (defaults to 'metadata.jsonld') :return None:
4.122045
4.002508
1.029865
logger_jsons.info("enter idx_name_to_num") # Process the paleoData section if "paleoData" in L: L["paleoData"] = _export_section(L["paleoData"], "paleo") # Process the chronData section if "chronData" in L: L["chronData"] = _export_section(L["chronData"], "chron") logger_...
def idx_name_to_num(L)
Switch from index-by-name to index-by-number. :param dict L: Metadata :return dict: Modified metadata
3.51774
3.430354
1.025474
logger_jsons.info("enter export_data: {}".format(pc)) _sections = [] for name, section in sections.items(): # Process chron models if "model" in section: section["model"] = _export_model(section["model"]) # Process the chron measurement table if "measureme...
def _export_section(sections, pc)
Switch chron data to index-by-number :param dict sections: Metadata :return list _sections: Metadata
5.242587
4.390971
1.193947
logger_jsons.info("enter export_model") _models = [] try: for name, model in models.items(): if "summaryTable" in model: model["summaryTable"] = _idx_table_by_num(model["summaryTable"]) # Process ensemble table (special two columns) if "ense...
def _export_model(models)
Switch model tables to index-by-number :param dict models: Metadata :return dict _models: Metadata
3.365196
3.088372
1.089634
logger_jsons.info("enter idx_table_by_num") _tables = [] for name, table in tables.items(): try: # Get the modified table data tmp = _idx_col_by_num(table) # Append it to the growing calibrated age list of tables _tables.append(tmp) except...
def _idx_table_by_num(tables)
Switch tables to index-by-number :param dict tables: Metadata :return list _tables: Metadata
4.697398
4.494465
1.045152
_columns = [] try: # Create an empty list that matches the length of the column dictionary _columns = [None for i in range(0, len(table["columns"]))] # Loop and start placing data in the output list based on its "number" entry for _name, _dat in table["columns"].items(): ...
def _idx_col_by_num(table)
Index columns by number instead of by name. Use "number" key in column to maintain order :param dict table: Metadata :return list _table: Metadata
3.807177
3.675797
1.035742
bag_dir = os.path.abspath(bag_dir) logger.info("creating bag for directory %s", bag_dir) # assume md5 checksum if not specified if not checksum: checksum = ['md5'] if not os.path.isdir(bag_dir): logger.error("no such bag directory %s", bag_dir) raise RuntimeError("no su...
def make_bag(bag_dir, bag_info=None, processes=1, checksum=None)
Convert a given directory into a bag. You can pass in arbitrary key/value pairs to put into the bag-info.txt metadata file as the bag_info dictionary.
2.675972
2.705396
0.989124
if not os.path.exists(full_path): raise BagValidationError("%s does not exist" % full_path) try: with open(full_path, 'rb') as f: while True: block = f.read(1048576) if not block: break for i in list(f_hashers....
def _calculate_file_hashes(full_path, f_hashers)
Returns a dictionary of (algorithm, hexdigest) values for the provided filename
1.889629
1.859534
1.016184
tag_name = None tag_value = None # Line folding is handled by yielding values only after we encounter # the start of a new tag, or if we pass the EOF. for num, line in enumerate(tag_file): # If byte-order mark ignore it for now. if num == 0: if line.startswith(BOM)...
def _parse_tags(tag_file)
Parses a tag file, according to RFC 2822. This includes line folding, permitting extra-long field values. See http://www.faqs.org/rfcs/rfc2822.html for more information.
3.908992
3.783868
1.033068
unwriteable = [] for inode in os.listdir(test_dir): if not os.access(os.path.join(test_dir, inode), os.W_OK): unwriteable.append(os.path.join(os.path.abspath(test_dir), inode)) return tuple(unwriteable)
def _can_bag(test_dir)
returns (unwriteable files/folders)
2.547072
2.055845
1.238941
unreadable_dirs = [] unreadable_files = [] for dirpath, dirnames, filenames in os.walk(test_dir): for dn in dirnames: if not os.access(os.path.join(dirpath, dn), os.R_OK): unreadable_dirs.append(os.path.join(dirpath, dn)) for fn in filenames: if n...
def _can_read(test_dir)
returns ((unreadable_dirs), (unreadable_files))
1.456208
1.29075
1.128188
files_on_fs = set(self.payload_files()) files_in_fetch = set(self.files_to_be_fetched()) return list(files_in_fetch - files_on_fs)
def compare_fetch_with_fs(self)
Compares the fetch entries with the files actually in the payload, and returns a list of all the files that still need to be fetched.
4.556543
3.50613
1.299593
# Error checking if not self.path: raise BagError("Bag does not have a path.") # Change working directory to bag directory so helper functions work old_dir = os.path.abspath(os.path.curdir) os.chdir(self.path) # Generate new manifest files i...
def save(self, processes=1, manifests=False)
save will persist any changes that have been made to the bag metadata (self.info). If you have modified the payload of the bag (added, modified, removed files in the data directory) and want to regenerate manifests set the manifests parameter to True. The default is False since you ...
3.883687
3.822269
1.016068
for tagfilepath in list(self.tagfile_entries().keys()): if not os.path.isfile(os.path.join(self.path, tagfilepath)): yield tagfilepath
def missing_optional_tagfiles(self)
From v0.97 we need to validate any tagfiles listed in the optional tagmanifest(s). As there is no mandatory directory structure for additional tagfiles we can only check for entries with missing files (not missing entries for existing files).
4.073109
3.927099
1.03718
self._validate_structure() self._validate_bagittxt() self._validate_contents(processes=processes, fast=fast) return True
def validate(self, processes=1, fast=False)
Checks the structure and contents are valid. If you supply the parameter fast=True the Payload-Oxum (if present) will be used to check that the payload files are present and accounted for, instead of re-calculating fixities and comparing them against the manifest. By default validate() ...
8.441672
5.587577
1.510793
try: self.validate(fast=fast) except BagError: return False return True
def is_valid(self, fast=False)
Returns validation success or failure as boolean. Optional fast parameter passed directly to validate().
6.33923
4.933321
1.284982
errors = list() # First we'll make sure there's no mismatch between the filesystem # and the list of files in the manifest(s) only_in_manifests, only_on_fs = self.compare_manifests_with_fs() for path in only_in_manifests: e = FileMissing(path) lo...
def _validate_entries(self, processes)
Verify that the actual file contents match the recorded hashes stored in the manifest files
3.806263
3.682212
1.033689
bagit_file_path = os.path.join(self.path, "bagit.txt") with open(bagit_file_path, 'r') as bagit_file: first_line = bagit_file.readline() if first_line.startswith(BOM): raise BagValidationError("bagit.txt must not contain a byte-order mark")
def _validate_bagittxt(self)
Verify that bagit.txt conforms to specification
2.650122
2.423241
1.093627
try: for var, data in c.items(): for k, v in data.items(): if k in ["hasMeanValue", "hasMaxValue", "hasMinValue", "hasMedianValue"]: if math.isnan(v): c[var][k] = "nan" elif not isinstance(v, (int, float)): ...
def _fix_numeric_types(c)
Fix any numpy data types that didn't map back to python data types properly :param dict c: Columns of data :return dict c: Columns of data
2.29677
2.306905
0.995607
# Need to check multiple places for age, year, or yrbp # 1. Check the column variable name # 2. Check for an "inferredVariableType age = [] try: # Step 1: # Check for age first (exact match) if "age" in columns: # Save the values age = columns["...
def _get_age(columns)
Sift through table column data and find the "age" or "year" column. Return its "values" data. :param dict columns: Column data :return list age: Age values
3.347239
3.137004
1.067018
res = [] try: # Get the nan index from the values and remove from age # age2 = age[np.where(~np.isnan(values))[0]] # res = np.diff(age2) # Make sure that age and values are numpy arrays # age = np.array(age, dtype=float) # values = np.array(values, dtype=flo...
def _get_resolution(age, values)
Calculates the resolution (res) Thanks Deborah!
3.173603
3.063638
1.035894
# Base: If something goes wrong, or if there are no values, then use "NaN" placeholders. d = { "hasMinValue": "nan", "hasMaxValue": "nan", "hasMeanValue": "nan", "hasMedianValue": "nan", } try: if calc: _min = np.nanmin(v) _max = np.nanmax(v) ...
def __get_inferred_data_res_2(v=None, calc=True)
Use a list of values to calculate m/m/m/m. Resolution values or otherwise. :param numpy array v: Values :param bool calc: If false, we don't need calculations :return dict: Results of calculation
2.234204
2.247582
0.994048
try: with warnings.catch_warnings(): warnings.simplefilter("ignore") # Get the values for this column values = column["values"] # Make sure that age and values are numpy arrays _values = np.array(copy.copy(values), dtype=float) # _...
def _get_inferred_data_res(column, age)
Calculate Resolution and m/m/m/m for column values. :param dict column: Column data :param list age: Age values :return dict column: Column data - modified
3.384574
3.208382
1.054916
try: with warnings.catch_warnings(): warnings.simplefilter("ignore") # Get the values for this column values = column["values"] # Make sure that age and values are numpy arrays _values = np.array(copy.copy(values), dtype=float) # I...
def _get_inferred_data_column(column)
Calculate the m/m/m/m for column values. :param dict column: Column data :return dict column: Column data - modified
5.005216
4.715941
1.06134
age = None if pc == "paleo": # Get the age values data first, since it's needed to calculate the other column data. age = _get_age(table["columns"]) try: # If age values were not found, then skip resolution. if age: # Loop for all the columns in the table ...
def get_inferred_data_table(table, pc)
Table level: Dive down, calculate data, then return the new table with the inferred data. :param str pc: paleo or chron :param dict table: Metadata :return dict table: Metadata
3.650094
3.474827
1.050439
if not hasattr(env, 'needs_functions'): env.needs_functions = {} func_name = need_function.__name__ if func_name in env.needs_functions.keys(): raise SphinxError('sphinx-needs: Function name {} already registered.'.format(func_name)) env.needs_functions[func_name] = { 'n...
def register_func(env, need_function)
Registers a new sphinx-needs function for the given sphinx environment. :param env: Sphinx environment :param need_function: Python method :return: None
3.009461
2.254871
1.334649
func_name, func_args, func_kwargs = _analyze_func_string(func_string) if func_name not in env.needs_functions.keys(): raise SphinxError('Unknown dynamic sphinx-needs function: {}. Found in need: {}'.format(func_name, need['id'])) func = env.needs_functions[func_name]['function'] func_retu...
def execute_func(env, need, func_string)
Executes a given function string. :param env: Sphinx environment :param need: Actual need, which contains the found function string :param func_string: string of the found function. Without [[ ]] :return: return value of executed function
2.727278
2.668952
1.021854
new_children = [] if not node.children: if isinstance(node, nodes.Text): func_match = func_pattern.findall(node) new_text = node for func_string in func_match: if not is_python3: func_string = func_string.encode('utf-8') ...
def find_and_replace_node_content(node, env, need)
Search inside a given node and its children for nodes of type Text, if found check if it contains a function string and run/replace it. :param node: Node to analyse :return: None
3.074004
3.009188
1.021539
# Only perform calculation if not already done yet if env.needs_workflow['dynamic_values_resolved']: return needs = env.needs_all_needs for key, need in needs.items(): for need_option in need: if need_option in ['docname', 'lineno', 'target_node', 'content']: ...
def resolve_dynamic_values(env)
Resolve dynamic values inside need data. Rough workflow: #. Parse all needs and their data for a string like [[ my_func(a,b,c) ]] #. Extract function name and call parameters #. Execute registered function name with extracted call parameters #. Replace original string with return value :param...
2.848756
2.619762
1.08741
func = ast.parse(func_string) try: func_call = func.body[0].value func_name = func_call.func.id except AttributeError: raise SphinxError("Given dynamic function string is not a valid python call. Got: {}".format(func_string)) func_args = [] for arg in func_call.args: ...
def _analyze_func_string(func_string)
Analyze given functiion string an extract: * function name * function arguments * function keyword arguments All given arguments must by of type string, int/float or list. :param func_string: string of the function :return: function name, arguments, keyword arguments
1.817692
1.805927
1.006514
# GLOBALS global cwd, files, logger_start, logger_benchmark, settings, _timeseries_data _timeseries_data = {} # files = {".lpd": [ {"full_path", "filename_ext", "filename_no_ext", "dir"} ], ".xls": [...], ".txt": [...]} settings = {"note_update": True, "note_validate": True, "verbose": True} ...
def run()
Initialize and start objects. This is called automatically when importing the package. :return none:
9.903922
9.896643
1.000736
global cwd, settings, files if settings["verbose"]: __disclaimer(opt="update") start = clock() files[".lpd"] = [] __read(usr_path, ".lpd") _d = __read_lipd_contents() end = clock() logger_benchmark.info(log_benchmark("readLipd", start, end)) return _d
def readLipd(usr_path="")
Read LiPD file(s). Enter a file path, directory path, or leave args blank to trigger gui. :param str usr_path: Path to file / directory (optional) :return dict _d: Metadata
13.729895
12.453644
1.10248
global cwd, files start = clock() files[".xls"] = [] __read(usr_path, ".xls") end = clock() logger_benchmark.info(log_benchmark("readExcel", start, end)) return cwd
def readExcel(usr_path="")
Read Excel file(s) Enter a file path, directory path, or leave args blank to trigger gui. :param str usr_path: Path to file / directory (optional) :return str cwd: Current working directory
10.966354
11.666418
0.939993
global files, cwd, settings _d = {} # Turn off verbose. We don't want to clutter the console with extra reading/writing output statements settings["verbose"] = False # Find excel files print("Found " + str(len(files[".xls"])) + " Excel files") logger_start.info("found excel files: {}".f...
def excel()
Convert Excel files to LiPD files. LiPD data is returned directly from this function. | Example | 1: lipd.readExcel() | 2: D = lipd.excel() :return dict _d: Metadata
6.883429
6.423576
1.071588
global files, cwd # When going from NOAA to LPD, use the global "files" variable. # When going from LPD to NOAA, use the data from the LiPD Library. # Choose the mode _mode = noaa_prompt() start = clock() # LiPD mode: Convert LiPD files to NOAA files if _mode == "1": # _pro...
def noaa(D="", path="", wds_url="", lpd_url="", version="")
Convert between NOAA and LiPD files | Example: LiPD to NOAA converter | 1: L = lipd.readLipd() | 2: lipd.noaa(L, "/Users/someuser/Desktop", "https://www1.ncdc.noaa.gov/pub/data/paleo/pages2k/NAm2kHydro-2017/noaa-templates/data-version-1.0.0", "https://www1.ncdc.noaa.gov/pub/data/paleo/pages2k/NAm2kHydro-20...
5.49286
5.230573
1.050145
start = clock() print("\n") # Fetch new results by calling lipd.net/api/validator (costly, may take a while) print("Fetching results from validator at lipd.net/validator... this may take a few moments.\n") try: results = [] # Get the validator-formatted data for each dataset. ...
def validate(D, detailed=True)
Use the Validator API for lipd.net to validate all LiPD files in the LiPD Library. Display the PASS/FAIL results. Display detailed results if the option is chosen. :param dict D: Metadata (single or multiple datasets) :param bool detailed: Show or hide the detailed results of each LiPD file. Shows warnings...
6.639862
5.824186
1.14005
dfs = {} try: dfs = ts_to_df(tso) except Exception as e: print("Error: Unable to create data frame") logger_start.warn("ts_to_df: tso malformed: {}".format(e)) return dfs
def tsToDf(tso)
Create Pandas DataFrame from TimeSeries object. Use: Must first extractTs to get a time series. Then pick one item from time series and pass it through :param dict tso: Time series entry :return dict dfs: Pandas dataframes
6.630913
7.033922
0.942705
# instead of storing each raw dataset per tso, store it once in the global scope. saves memory global _timeseries_data _l = [] start = clock() try: if not d: print("Error: LiPD data not provided. Pass LiPD data into the function.") else: print(mode_ts("ex...
def extractTs(d, whichtables="meas", mode="paleo")
Create a time series using LiPD data (uses paleoData by default) | Example : (default) paleoData and meas tables | 1. D = lipd.readLipd() | 2. ts = lipd.extractTs(D) | Example : chronData and all tables | 1. D = lipd.readLipd() | 2. ts = lipd.extractTs(D, "all", "chron") :param dict d: Me...
4.415318
4.217257
1.046964
# Retrieve the associated raw data according to the "time_id" found in each object. Match it in _timeseries_data global _timeseries_data _d = {} if not ts: print("Error: Time series data not provided. Pass time series into the function.") else: # Send time series list through to...
def collapseTs(ts=None)
Collapse a time series back into LiPD record form. | Example | 1. D = lipd.readLipd() | 2. ts = lipd.extractTs(D) | 3. New_D = lipd.collapseTs(ts) _timeseries_data is sorted by time_id, and then by dataSetName _timeseries_data[10103341]["ODP1098B"] = {data} :param list ts: Time series ...
7.94315
7.036273
1.128886
# Make a copy of the ts. We're going to work directly on it. new_ts = ts[:] # User provided a single query string if isinstance(expressions, str): # Use some magic to turn the given string expression into a machine-usable comparative expression. expr_lst = translate_expression(expr...
def filterTs(ts, expressions)
Create a new time series that only contains entries that match the given expression. | Example: | D = lipd.loadLipd() | ts = lipd.extractTs(D) | new_ts = filterTs(ts, "archiveType == marine sediment") | new_ts = filterTs(ts, ["paleoData_variableName == sst", "archiveType == marine sediment"]) |...
3.753535
3.834746
0.978822
# Make a copy of the ts. We're going to work directly on it. _idx = [] # User provided a single query string if isinstance(expressions, str): # Use some magic to turn the given string expression into a machine-usable comparative expression. expr_lst = translate_expression(expressio...
def queryTs(ts, expression)
Find the indices of the time series entries that match the given expression. | Example: | D = lipd.loadLipd() | ts = lipd.extractTs(D) | matches = queryTs(ts, "archiveType == marine sediment") | matches = queryTs(ts, "geo_meanElev <= 2000") :param str expression: Expression :param list ts:...
4.411253
4.205849
1.048838
_ts = ts if isinstance(ts, list): _ts = ts[0] print("It looks like you input a full time series. It's best to view one entry at a time.\n" "I'll show you the first entry...") _tmp_sort = OrderedDict() _tmp_sort["ROOT"] = {} _tmp_sort["PUBLICATION"] = {} _tmp_so...
def viewTs(ts)
View the contents of one time series entry in a nicely formatted way | Example | 1. D = lipd.readLipd() | 2. ts = lipd.extractTs(D) | 3. viewTs(ts[0]) :param dict ts: One time series entry :return none:
3.39242
3.284532
1.032847
if not D: print("Error: LiPD data not provided. Pass LiPD data into the function.") else: print(json.dumps(D.keys(), indent=2)) return
def showLipds(D=None)
Display the dataset names of a given LiPD data | Example | lipd.showLipds(D) :pararm dict D: LiPD data :return none:
7.428592
6.20451
1.197289
_tmp = rm_values_fields(copy.deepcopy(dat)) print(json.dumps(_tmp, indent=2)) return
def showMetadata(dat)
Display the metadata specified LiPD in pretty print | Example | showMetadata(D["Africa-ColdAirCave.Sundqvist.2013"]) :param dict dat: Metadata :return none:
11.566975
15.038678
0.769148
if "metadata" in d: print("metadata") if "paleoData" in d: try: for k, v in d["paleoData"].items(): print(k) except KeyError: pass except AttributeError: pass if "chronData" in d: try: for k, v in d[...
def showDfs(d)
Display the available data frame names in a given data frame collection :param dict d: Dataframe collection :return none:
3.077492
3.257772
0.944661
_names = [] try: if not D: print("Error: LiPD data not provided. Pass LiPD data into the function.") else: _names = D.keys() except Exception: pass return _names
def getLipdNames(D=None)
Get a list of all LiPD names in the library | Example | names = lipd.getLipdNames(D) :return list f_list: File list
5.873209
6.726255
0.873177
_l = {} try: # Create a copy. Do not affect the original data. _l = copy.deepcopy(L) # Remove values fields _l = rm_values_fields(_l) except Exception as e: # Input likely not formatted correctly, though other problems can occur. print("Error: Unable to g...
def getMetadata(L)
Get metadata from a LiPD data in memory | Example | m = lipd.getMetadata(D["Africa-ColdAirCave.Sundqvist.2013"]) :param dict L: One LiPD record :return dict d: LiPD record (metadata only)
11.753661
10.073321
1.166811
_c = {} try: if not L: print("Error: LiPD data not provided. Pass LiPD data into the function.") else: _j, _c = get_csv_from_metadata(L["dataSetName"], L) except KeyError as ke: print("Error: Unable to get data. Please check that input is one LiPD dataset...
def getCsv(L=None)
Get CSV from LiPD metadata | Example | c = lipd.getCsv(D["Africa-ColdAirCave.Sundqvist.2013"]) :param dict L: One LiPD record :return dict d: CSV data
7.534801
6.333295
1.189713