|
17 | 17 | __all__ = ["inputToString"] |
18 | 18 |
|
19 | 19 | import os.path |
| 20 | +from pathlib import Path |
20 | 21 |
|
21 | 22 |
|
22 | 23 | def inputToString(input): |
@@ -51,4 +52,65 @@ def inputToString(input): |
51 | 52 | return inptstr |
52 | 53 |
|
53 | 54 |
|
| 55 | +def get_dict_from_results_file( |
| 56 | + results_filepath: Path | str, |
| 57 | +) -> dict[str, float]: |
| 58 | + """Get a dictionary of parameter names and values from a results |
| 59 | + file. |
| 60 | +
|
| 61 | + The file should have lines in the format: |
| 62 | + "parameter_name value +/- uncertainty". Lines that do not match this |
| 63 | + format will be ignored. |
| 64 | +
|
| 65 | + Parameters |
| 66 | + ---------- |
| 67 | + results_filepath : pathlib.Path or str |
| 68 | + The path to the results file. |
| 69 | +
|
| 70 | + Returns |
| 71 | + ------- |
| 72 | + parsed_results_dict : dict |
| 73 | + The dictionary where keys are parameter names and values are the |
| 74 | + corresponding parameter values as floats. |
| 75 | + """ |
| 76 | + with open(results_filepath, "r") as f: |
| 77 | + results_string = f.read() |
| 78 | + parsed_results_dict = {} |
| 79 | + for raw_line in results_string.splitlines(): |
| 80 | + line = raw_line.strip() |
| 81 | + # skip blank lines and lines that are just dashes |
| 82 | + if not line or set(line) == {"-"}: |
| 83 | + continue |
| 84 | + line_items = line.split() |
| 85 | + if len(line_items) < 2: |
| 86 | + continue |
| 87 | + if len(line_items) >= 4 and line_items[2] == "+/-": |
| 88 | + try: |
| 89 | + parsed_results_dict[line_items[0]] = float(line_items[1]) |
| 90 | + except ValueError: |
| 91 | + pass |
| 92 | + return parsed_results_dict |
| 93 | + |
| 94 | + |
| 95 | +def get_dict_from_results_object(results_object) -> dict[str, float]: |
| 96 | + """Get a dictionary of parameter names and values from a FitResults |
| 97 | + object. |
| 98 | +
|
| 99 | + Parameters |
| 100 | + ---------- |
| 101 | + results_object : FitResults |
| 102 | + The FitResults object containing the parameter names and values. |
| 103 | +
|
| 104 | + Returns |
| 105 | + ------- |
| 106 | + params_dict : dict |
| 107 | + The dictionary where keys are parameter names and values are the |
| 108 | + corresponding parameter values as floats. |
| 109 | + """ |
| 110 | + param_names = results_object.varnames |
| 111 | + param_vals = results_object.varvals |
| 112 | + params_dict = dict(zip(param_names, param_vals)) |
| 113 | + return params_dict |
| 114 | + |
| 115 | + |
54 | 116 | # End of file |
0 commit comments