|
1 | 1 | """Benchmarks to check computation time and memory usage for batsim.""" |
2 | 2 | import batsim.stamp as batstamp |
3 | 3 | import batsim.transforms as batforms |
| 4 | +import batsim |
| 5 | +import contextlib |
4 | 6 | import galsim |
| 7 | +import io |
| 8 | +import numpy as np |
5 | 9 | import time |
6 | 10 |
|
7 | 11 | def time_shear_speed(nn=64, scale=0.2): |
@@ -74,7 +78,131 @@ def time_ia_speed(nn=128, scale=0.1): |
74 | 78 | aff_time = aff_end - aff_start |
75 | 79 |
|
76 | 80 | return {'IA time' : ia_time, 'Lens time' : aff_time} |
77 | | - |
| 81 | + |
| 82 | + |
| 83 | +def _parse_simulate_profile_logs(log_lines): |
| 84 | + stats = {} |
| 85 | + timings = {} |
| 86 | + for line in log_lines: |
| 87 | + msg = line.split("] ", 1)[-1] |
| 88 | + if msg.startswith("stats "): |
| 89 | + for token in msg[6:].split(): |
| 90 | + if "=" not in token: |
| 91 | + continue |
| 92 | + key, value = token.split("=", 1) |
| 93 | + try: |
| 94 | + stats[key] = int(value) |
| 95 | + except ValueError: |
| 96 | + try: |
| 97 | + stats[key] = float(value) |
| 98 | + except ValueError: |
| 99 | + stats[key] = value |
| 100 | + elif "=" in msg: |
| 101 | + key, value = msg.split("=", 1) |
| 102 | + value = value[:-1] if value.endswith("s") else value |
| 103 | + try: |
| 104 | + timings[key] = float(value) |
| 105 | + except ValueError: |
| 106 | + timings[key] = value |
| 107 | + return {"timings": timings, "stats": stats} |
| 108 | + |
| 109 | + |
| 110 | +def _extract_parametric_profile_info(cosmos_catalog, catalog_index, gal_obj): |
| 111 | + info = { |
| 112 | + "catalog_index": int(catalog_index), |
| 113 | + "gsobject_type": type(gal_obj).__name__, |
| 114 | + } |
| 115 | + for attr in ("flux", "nyquist_scale"): |
| 116 | + if hasattr(gal_obj, attr): |
| 117 | + try: |
| 118 | + info[attr] = float(getattr(gal_obj, attr)) |
| 119 | + except Exception: |
| 120 | + pass |
| 121 | + param_cat = getattr(cosmos_catalog, "param_cat", None) |
| 122 | + if param_cat is None: |
| 123 | + return info |
| 124 | + keys = [] |
| 125 | + if hasattr(param_cat, "colnames"): |
| 126 | + keys = ["mag_auto", "flux_radius", "zphot"] + [k for k in ("use_bulgefit", "viable_sersic") if k in param_cat.colnames] |
| 127 | + elif hasattr(param_cat, "dtype") and param_cat.dtype.names: |
| 128 | + keys = [k for k in ("mag_auto", "flux_radius", "zphot", "use_bulgefit", "viable_sersic") if k in param_cat.dtype.names] |
| 129 | + if not keys: |
| 130 | + return info |
| 131 | + row = param_cat[int(catalog_index)] |
| 132 | + for key in keys: |
| 133 | + try: |
| 134 | + value = row[key] |
| 135 | + if hasattr(value, "item"): |
| 136 | + value = value.item() |
| 137 | + info[key] = value |
| 138 | + except Exception: |
| 139 | + pass |
| 140 | + return info |
| 141 | + |
| 142 | + |
| 143 | +def benchmark_parametric_cosmos_profiles( |
| 144 | + n_galaxies=5, |
| 145 | + ngrid=128, |
| 146 | + pix_scale=0.2, |
| 147 | + psf_obj=None, |
| 148 | + draw_method="auto", |
| 149 | + truncate_ratio=1.0, |
| 150 | + maximum_num_grids=4096, |
| 151 | + force_ngrid=False, |
| 152 | + seed=1234, |
| 153 | + cosmos_catalog=None, |
| 154 | +): |
| 155 | + """Run a lightweight per-galaxy benchmark using parametric COSMOS profiles. |
| 156 | +
|
| 157 | + Returns a list of dictionaries containing profile metadata, parsed |
| 158 | + `simulate_galaxy(profile=True)` logs, and end-to-end elapsed time. |
| 159 | + """ |
| 160 | + cosmos_catalog = cosmos_catalog or galsim.COSMOSCatalog() |
| 161 | + rng = np.random.RandomState(seed) |
| 162 | + indices = rng.choice(len(cosmos_catalog), size=n_galaxies, replace=(n_galaxies > len(cosmos_catalog))) |
| 163 | + |
| 164 | + records = [] |
| 165 | + for i, idx in enumerate(indices): |
| 166 | + gal = cosmos_catalog.makeGalaxy(index=int(idx), gal_type="parametric") |
| 167 | + profile_info = _extract_parametric_profile_info(cosmos_catalog, idx, gal) |
| 168 | + |
| 169 | + log_buf = io.StringIO() |
| 170 | + t0 = time.perf_counter() |
| 171 | + with contextlib.redirect_stdout(log_buf): |
| 172 | + image = batsim.simulate_galaxy( |
| 173 | + ngrid=ngrid, |
| 174 | + pix_scale=pix_scale, |
| 175 | + gal_obj=gal, |
| 176 | + psf_obj=psf_obj, |
| 177 | + truncate_ratio=truncate_ratio, |
| 178 | + maximum_num_grids=maximum_num_grids, |
| 179 | + draw_method=draw_method, |
| 180 | + force_ngrid=force_ngrid, |
| 181 | + profile=True, |
| 182 | + ) |
| 183 | + elapsed_s = time.perf_counter() - t0 |
| 184 | + |
| 185 | + profile_logs = [line for line in log_buf.getvalue().splitlines() if line.startswith("[simulate_galaxy]")] |
| 186 | + parsed_logs = _parse_simulate_profile_logs(profile_logs) |
| 187 | + record = { |
| 188 | + "galaxy_number": i, |
| 189 | + "profile": profile_info, |
| 190 | + "logger": parsed_logs, |
| 191 | + "elapsed_s": elapsed_s, |
| 192 | + "image_shape": tuple(image.shape), |
| 193 | + "image_sum": float(np.sum(image)), |
| 194 | + } |
| 195 | + records.append(record) |
| 196 | + |
| 197 | + print( |
| 198 | + f"[benchmark_parametric_cosmos_profiles] i={i} idx={int(idx)} " |
| 199 | + f"nn={parsed_logs['stats'].get('nn')} downsample_ratio={parsed_logs['stats'].get('downsample_ratio')} " |
| 200 | + f"elapsed_s={elapsed_s:.4e}" |
| 201 | + ) |
| 202 | + print(f"[benchmark_parametric_cosmos_profiles] profile={profile_info}") |
| 203 | + for line in profile_logs: |
| 204 | + print(line) |
| 205 | + return records |
78 | 206 |
|
79 | 207 | if __name__ == "__main__": |
80 | 208 | time_shear_speed() |
|
0 commit comments