|
| 1 | +"""TREECORR_AUX. |
| 2 | +
|
| 3 | +:Name: treecorr_aux.py |
| 4 | +
|
| 5 | +:Description: This file contains methods for working with TreeCorr output files. |
| 6 | +
|
| 7 | +:Author: Martin Kilbinger <martin.kilbinger@cea.fr> |
| 8 | +
|
| 9 | +""" |
| 10 | + |
| 11 | +import ast |
| 12 | +import numpy as np |
| 13 | +import treecorr |
| 14 | + |
| 15 | + |
| 16 | +def read_ascii_to_ngcorrelation(file_path): |
| 17 | + """Read ASCII to NGCorrelation. |
| 18 | +
|
| 19 | + Read TreeCorr ASCII output file and create a NGCorrelation instance |
| 20 | + without needing a config file. All configuration parameters are |
| 21 | + extracted from the ASCII file metadata. |
| 22 | +
|
| 23 | + Parameters |
| 24 | + ---------- |
| 25 | + file_path : str |
| 26 | + path to TreeCorr ASCII output file |
| 27 | +
|
| 28 | + Returns |
| 29 | + ------- |
| 30 | + treecorr.NGCorrelation |
| 31 | + TreeCorr NGCorrelation object with data loaded from ASCII file |
| 32 | +
|
| 33 | + Raises |
| 34 | + ------ |
| 35 | + IOError |
| 36 | + if input file is not found or cannot be read |
| 37 | + ValueError |
| 38 | + if file format is not recognized as TreeCorr ASCII output |
| 39 | + """ |
| 40 | + try: |
| 41 | + with open(file_path, 'r') as f: |
| 42 | + lines = f.readlines() |
| 43 | + except IOError as e: |
| 44 | + raise IOError(f"Cannot read file '{file_path}': {e}") |
| 45 | + |
| 46 | + if not lines: |
| 47 | + raise ValueError(f"File '{file_path}' is empty") |
| 48 | + |
| 49 | + # Parse the config from first line |
| 50 | + if not lines[0].startswith('##'): |
| 51 | + raise ValueError(f"File '{file_path}' does not appear to be TreeCorr ASCII output") |
| 52 | + |
| 53 | + # Extract config dictionary from first line |
| 54 | + config_str = lines[0][2:].strip() # Remove '##' and whitespace |
| 55 | + try: |
| 56 | + config = ast.literal_eval(config_str) |
| 57 | + except (ValueError, SyntaxError) as e: |
| 58 | + raise ValueError(f"Cannot parse config from first line: {e}") |
| 59 | + |
| 60 | + # Verify this is an NG (gamma-gamma) correlation |
| 61 | + if config.get('corr') != 'NG': |
| 62 | + raise ValueError(f"Expected 'NG' correlation type, got '{config.get('corr')}'") |
| 63 | + |
| 64 | + # Create NGCorrelation object with config parameters |
| 65 | + ng = treecorr.NGCorrelation( |
| 66 | + min_sep=config['min_sep'], |
| 67 | + max_sep=config['max_sep'], |
| 68 | + sep_units=config['sep_units'], |
| 69 | + nbins=config['nbins'], |
| 70 | + var_method=config.get('var_method', 'shot'), |
| 71 | + metric=config.get('metric', 'Euclidean'), |
| 72 | + ) |
| 73 | + |
| 74 | + # Use TreeCorr's built-in read method to load the data |
| 75 | + ng.read(file_path) |
| 76 | + |
| 77 | + return ng |
0 commit comments