hicrafter 0.2.11__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pauline Gorbatchev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.4
2
+ Name: hicrafter
3
+ Version: 0.2.11
4
+ Summary: HI Intensity Mapping generator with LHS sampling & multi-CPU batching
5
+ Author: HI Crafter
6
+ Author-email: your.email@example.com
7
+ License: MIT License
8
+
9
+ Copyright (c) 2026 Pauline Gorbatchev
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
28
+
29
+ Classifier: Development Status :: 4 - Beta
30
+ Classifier: Intended Audience :: Science/Research
31
+ Classifier: Topic :: Scientific/Engineering :: Astronomy
32
+ Classifier: License :: OSI Approved :: MIT License
33
+ Requires-Python: >=3.9
34
+ Description-Content-Type: text/markdown
35
+ License-File: LICENSE
36
+ Requires-Dist: numpy<2.0,>=1.21
37
+ Requires-Dist: healpy>=1.15
38
+ Requires-Dist: camb>=1.5
39
+ Requires-Dist: glass>=0.5
40
+ Requires-Dist: scipy>=1.8
41
+ Requires-Dist: cosmology>=0.7
42
+ Provides-Extra: dev
43
+ Requires-Dist: black; extra == "dev"
44
+ Requires-Dist: pytest; extra == "dev"
45
+ Requires-Dist: matplotlib; extra == "dev"
46
+ Requires-Dist: isort; extra == "dev"
47
+ Dynamic: author-email
48
+ Dynamic: license-file
49
+ Dynamic: requires-python
50
+ Dynamic: summary
51
+
52
+ # HIcrafter
53
+ HIcrafter generates realistic HI intensity maps across redshift ranges. Features: Gaussian beam/noise/masks/zebras, single maps or Latin Hypercube parameter suites for ML/SBI training, multi-CPU parallel batching. Seeds logged 1→N. Perfect for cosmological simulations.
@@ -0,0 +1,2 @@
1
+ # HIcrafter
2
+ HIcrafter generates realistic HI intensity maps across redshift ranges. Features: Gaussian beam/noise/masks/zebras, single maps or Latin Hypercube parameter suites for ML/SBI training, multi-CPU parallel batching. Seeds logged 1→N. Perfect for cosmological simulations.
@@ -0,0 +1,4 @@
1
+ from .generator import HIGenerator
2
+
3
+ __version__ = "0.2.0"
4
+ __all__ = ["HIGenerator"]
@@ -0,0 +1,246 @@
1
+ import numpy as np
2
+ import healpy as hp
3
+ import camb
4
+ import glass.shells
5
+ import glass.fields
6
+ import glass.observations
7
+ import glass.ext.camb
8
+
9
+ from cosmology import Cosmology
10
+ from multiprocessing import Pool
11
+ from functools import partial
12
+ import os
13
+ from scipy.stats import qmc # For Latin Hypercube
14
+
15
+ class HIGenerator:
16
+ def __init__(self, h=0.7, As=2e-9, Oc=0.25, Ob=0.05,
17
+ nside=1024, z_min=0.4, z_max=0.45, nbins=1, sigmaz0=0.0001,
18
+ beam_deg=None, noise=True, noise_level=1.0, mask_file=None,
19
+ zebras=False, zebra_amplitude=0.1, zebra_width_deg=5.0,
20
+ zebra_angle_deg=45.0, seed=1, n_jobs=4, batch_size=100):
21
+
22
+ self.h = h
23
+ self.As = As
24
+ self.Oc = Oc
25
+ self.Ob = Ob
26
+ self.nside = nside
27
+ self.z_min = z_min
28
+ self.z_max = z_max
29
+ self.nbins = nbins
30
+ self.sigmaz0 = sigmaz0
31
+ self.beam_deg = beam_deg
32
+ self.noise = noise
33
+ self.noise_level = noise_level
34
+ self.mask_file = mask_file
35
+ self.zebras = zebras
36
+ self.zebra_amplitude = zebra_amplitude
37
+ self.zebra_width_deg = zebra_width_deg
38
+ self.zebra_angle_deg = zebra_angle_deg
39
+ self.seed = seed # Base seed (1 for LHS)
40
+ self.n_jobs = n_jobs
41
+ self.batch_size = batch_size
42
+
43
+ self.rng = np.random.default_rng(seed)
44
+ self.cosmo = self._setup_cosmology()
45
+ self._preload_data()
46
+
47
+ # ... _setup_cosmology, Tbar, b_HI unchanged ...
48
+
49
+ def generate_single(self, custom_params=None):
50
+ """SINGLE MAP at specific cosmology (your original mode)."""
51
+ if custom_params:
52
+ temp_params = self._copy_params()
53
+ temp_params.update(custom_params)
54
+ temp_gen = HIGenerator(**temp_params)
55
+ return temp_gen._generate_single_map(0)
56
+ return self._generate_single_map(0)
57
+
58
+ def generate_lhs_suite(self, priors, n_samples=100, output_dir="lhs_maps",
59
+ prefix="lhs_map", seed_base=1, log_seeds=True):
60
+ """
61
+ LHS SUITE: Vary priors across CPUs, seeds 1→N.
62
+
63
+ priors = {
64
+ 'h': [0.65, 0.70],
65
+ 'As': [1.8e-9, 2.2e-9],
66
+ 'Oc': [0.24, 0.26]
67
+ }
68
+ """
69
+ print(f"Generating {n_samples} LHS maps (seeds {seed_base}→{seed_base+n_samples-1})")
70
+
71
+ # Generate Latin Hypercube
72
+ sampler = qmc.LatinHypercube(d=len(priors))
73
+ sample = sampler.random(n=n_samples)
74
+ lhs_params = {}
75
+
76
+ param_names = list(priors.keys())
77
+ for i, name in enumerate(param_names):
78
+ lhs_params[name] = (priors[name][0] +
79
+ sample[:, i] * (priors[name][1] - priors[name][0]))
80
+
81
+ # Save LHS hypercube
82
+ np.savetxt(f"{output_dir}/{prefix}_hypercube.txt",
83
+ np.column_stack([range(n_samples)] +
84
+ [lhs_params[name] for name in param_names]),
85
+ header="idx " + " ".join(param_names),
86
+ comments='')
87
+
88
+ os.makedirs(output_dir, exist_ok=True)
89
+
90
+ def single_lhs_map(args):
91
+ idx, row = args
92
+ params = self._copy_fixed_params()
93
+ for name in param_names:
94
+ params[name] = row[name]
95
+ params['seed'] = seed_base + idx # Seeds 1→N!
96
+ gen = HIGenerator(**params)
97
+ return gen._generate_single_map(0), row # Returns map + params
98
+
99
+ # Parallel generation
100
+ with Pool(self.n_jobs) as pool:
101
+
102
+ results = pool.map(single_lhs_map,
103
+ [(i, dict(zip(param_names, (lhs_params[name][i] for name in param_names))))
104
+ for i in range(n_samples)])
105
+
106
+ # Save maps + log seeds (like your code)
107
+
108
+ results = pool.map(single_lhs_map, [
109
+ (i, dict(zip(param_names, (lhs_params[name][i] for name in param_names))))
110
+ for i in range(n_samples)
111
+ ])
112
+ # Save maps + log seeds
113
+ if log_seeds:
114
+ self._log_seeds(n_samples, seed_base, output_dir)
115
+
116
+ maps = [r[0] for r in results]
117
+ for i, hi_map in enumerate(maps):
118
+ np.save(f"{output_dir}/{prefix}_{i:06d}.npy", hi_map)
119
+
120
+ print(f"Saved {n_samples} LHS maps + hypercube.txt to {output_dir}/")
121
+ return maps, lhs_params
122
+
123
+ def _copy_params(self):
124
+ """Copy current parameters."""
125
+ return {k: v for k, v in self.__dict__.items() if not k.startswith('_')}
126
+
127
+ def _copy_fixed_params(self):
128
+ """Copy non-varying parameters."""
129
+ fixed = {k: v for k, v in self._copy_params().items()
130
+ if k not in ['h', 'As', 'Oc', 'Ob']}
131
+ return fixed
132
+
133
+ def _log_seeds(self, n_samples, seed_base, output_dir):
134
+ """Log seeds like your usedseedsnew.txt."""
135
+ import datetime
136
+ with open(f"{output_dir}/used_seeds.txt", 'a') as f:
137
+ timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
138
+ for i in range(n_samples):
139
+ f.write(f"{seed_base+i} {timestamp} lhs_suite\n")
140
+
141
+
142
+ def update_params(self, **kwargs):
143
+ for key, value in kwargs.items():
144
+ if hasattr(self, key):
145
+ setattr(self, key, value)
146
+ self.rng = np.random.default_rng(self.seed)
147
+ self.cosmo = self._setup_cosmology()
148
+ self._preload_data()
149
+
150
+ def _setup_cosmology(self):
151
+ pars.set_params(H0=100*self.h, omch2=self.Oc*self.h**2, ombh2=self.Ob*self.h**2)
152
+ pars.InitPower.set_params(ns=0.96, As=self.As)
153
+ pars.NonLinear = camb.model.NonLinear.both
154
+ return Cosmology.from_camb(pars)
155
+
156
+
157
+ def _preload_data(self):
158
+ """Precompute expensive static data."""
159
+ self.z = np.linspace(0, self.z_max, 1000)
160
+ self.zb = glass.shells.distance_grid(self.cosmo, self.z[0], self.z[-1], dx=50.)
161
+ self.ws = glass.shells.linear_windows(self.zb)
162
+ self.cls = glass.ext.camb.matter_cls(pars=None, lmax=3*self.nside-1, ws=self.ws)
163
+ self.gls = glass.fields.lognormal_gls(self.cls)
164
+ self.z_edges = glass.observations.equal_dens_z_bins(self.z, self.Tbar(self.z), nbins=self.nbins)
165
+ self.tomo_THI = glass.observations.to_mon_z_gauss_err(self.z, self.Tbar(self.z), self.sigmaz0, self.z_edges)
166
+
167
+ def Tbar(self, redshift):
168
+ OHI = 4e-4 * (1 + redshift)**0.6
169
+ return 189 * OHI * self.cosmo.h * (1 + redshift)**2 / self.cosmo.hf(redshift)
170
+
171
+ def b_HI(self, redshift):
172
+ return 0.6 + 0.3 * (1 + redshift)
173
+
174
+ def _generate_single_map(self, seed_offset):
175
+ """Single map generation (for multiprocessing)."""
176
+ local_rng = np.random.default_rng(self.seed + seed_offset)
177
+ matter = glass.fields.generate_lognormal(self.gls, self.nside, ncorr=5, rng=local_rng)
178
+
179
+ HImap = np.stack([np.zeros(hp.nside2npix(self.nside)) for _ in range(self.nbins)], axis=0)
180
+ for i, delta_i in enumerate(matter):
181
+ for j in range(self.nbins):
182
+ tomo_z_i, tomo_THI_i = glass.shells.restrict_z(self.tomo_THI[:,j], self.ws[i])
183
+ HImap[j] += np.mean(tomo_THI_i) * self.b_HI(np.mean(tomo_z_i)) * delta_i
184
+
185
+ fullskymap = HImap[0]
186
+
187
+ if self.beam_deg:
188
+ fullskymap = self._apply_beam(fullskymap)
189
+ if self.mask_file:
190
+ fullskymap = self._apply_mask(fullskymap)
191
+ if self.zebras:
192
+ fullskymap = self._add_zebras(fullskymap)
193
+ if self.noise:
194
+ fullskymap += self._add_noise(hp.nside2npix(self.nside), local_rng)
195
+
196
+ return fullskymap
197
+
198
+ def generate_map(self):
199
+ """Generate single map."""
200
+ return self._generate_single_map(0)
201
+
202
+ def generate_batch(self, n_maps=100, output_dir="maps", prefix="hi_map"):
203
+ """Generate batch of maps using all CPUs."""
204
+ print(f"Generating {n_maps} maps on {self.n_jobs} CPUs...")
205
+
206
+ os.makedirs(output_dir, exist_ok=True)
207
+ gen_func = partial(self._generate_single_map)
208
+
209
+ with Pool(self.n_jobs) as pool:
210
+ maps = pool.map(gen_func, range(n_maps))
211
+
212
+ # Save maps
213
+ for i, hi_map in enumerate(maps):
214
+ np.save(f"{output_dir}/{prefix}_{i:06d}.npy", hi_map)
215
+
216
+ print(f"Saved {n_maps} maps to {output_dir}/")
217
+ return maps
218
+
219
+ def _apply_beam(self, map_data):
220
+ fwhm_rad = np.radians(self.beam_deg)
221
+ alm = hp.map2alm(map_data, lmax=2*self.nside-1)
222
+ bl = hp.gauss_beam(fwhm=fwhm_rad, lmax=2*self.nside-1)
223
+ alm *= bl
224
+ return hp.alm2map(alm, self.nside)
225
+
226
+ def _apply_mask(self, map_data):
227
+ if self.mask_file.endswith('.npy'):
228
+ mask = np.load(self.mask_file)
229
+ else:
230
+ mask = hp.read_map(self.mask_file, verbose=False)
231
+ mask = np.logical_not(mask)
232
+ return map_data * mask.astype(float)
233
+
234
+ def _add_noise(self, npix, rng):
235
+ return rng.normal(0.0, self.noise_level, size=npix)
236
+
237
+ def _add_zebras(self, map_data):
238
+ npix = len(map_data)
239
+ theta, phi = hp.pix2ang(self.nside, np.arange(npix))
240
+ x = np.sin(theta) * np.cos(phi)
241
+ y = np.sin(theta) * np.sin(phi)
242
+ angle_rad = np.radians(self.zebra_angle_deg)
243
+ stripe_dir = x * np.cos(angle_rad) + y * np.sin(angle_rad)
244
+ stripe_pattern = np.sin(2 * np.pi * stripe_dir / np.radians(self.zebra_width_deg))
245
+ zebra_map = self.zebra_amplitude * stripe_pattern
246
+ return map_data + zebra_map
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.4
2
+ Name: hicrafter
3
+ Version: 0.2.11
4
+ Summary: HI Intensity Mapping generator with LHS sampling & multi-CPU batching
5
+ Author: HI Crafter
6
+ Author-email: your.email@example.com
7
+ License: MIT License
8
+
9
+ Copyright (c) 2026 Pauline Gorbatchev
10
+
11
+ Permission is hereby granted, free of charge, to any person obtaining a copy
12
+ of this software and associated documentation files (the "Software"), to deal
13
+ in the Software without restriction, including without limitation the rights
14
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15
+ copies of the Software, and to permit persons to whom the Software is
16
+ furnished to do so, subject to the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be included in all
19
+ copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27
+ SOFTWARE.
28
+
29
+ Classifier: Development Status :: 4 - Beta
30
+ Classifier: Intended Audience :: Science/Research
31
+ Classifier: Topic :: Scientific/Engineering :: Astronomy
32
+ Classifier: License :: OSI Approved :: MIT License
33
+ Requires-Python: >=3.9
34
+ Description-Content-Type: text/markdown
35
+ License-File: LICENSE
36
+ Requires-Dist: numpy<2.0,>=1.21
37
+ Requires-Dist: healpy>=1.15
38
+ Requires-Dist: camb>=1.5
39
+ Requires-Dist: glass>=0.5
40
+ Requires-Dist: scipy>=1.8
41
+ Requires-Dist: cosmology>=0.7
42
+ Provides-Extra: dev
43
+ Requires-Dist: black; extra == "dev"
44
+ Requires-Dist: pytest; extra == "dev"
45
+ Requires-Dist: matplotlib; extra == "dev"
46
+ Requires-Dist: isort; extra == "dev"
47
+ Dynamic: author-email
48
+ Dynamic: license-file
49
+ Dynamic: requires-python
50
+ Dynamic: summary
51
+
52
+ # HIcrafter
53
+ HIcrafter generates realistic HI intensity maps across redshift ranges. Features: Gaussian beam/noise/masks/zebras, single maps or Latin Hypercube parameter suites for ML/SBI training, multi-CPU parallel batching. Seeds logged 1→N. Perfect for cosmological simulations.
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ setup.py
5
+ hicrafter/__init__.py
6
+ hicrafter/generator.py
7
+ hicrafter.egg-info/PKG-INFO
8
+ hicrafter.egg-info/SOURCES.txt
9
+ hicrafter.egg-info/dependency_links.txt
10
+ hicrafter.egg-info/requires.txt
11
+ hicrafter.egg-info/top_level.txt
@@ -0,0 +1,12 @@
1
+ numpy<2.0,>=1.21
2
+ healpy>=1.15
3
+ camb>=1.5
4
+ glass>=0.5
5
+ scipy>=1.8
6
+ cosmology>=0.7
7
+
8
+ [dev]
9
+ black
10
+ pytest
11
+ matplotlib
12
+ isort
@@ -0,0 +1 @@
1
+ hicrafter
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "hicrafter"
7
+ dynamic = ["version", "description"]
8
+ readme = "README.md"
9
+ authors = [{name = "HI Crafter"}]
10
+ license = {file = "LICENSE"}
11
+ requires-python = ">=3.9"
12
+ classifiers = [
13
+ "Development Status :: 4 - Beta",
14
+ "Intended Audience :: Science/Research",
15
+ "Topic :: Scientific/Engineering :: Astronomy",
16
+ "License :: OSI Approved :: MIT License"
17
+ ]
18
+
19
+ dependencies = [
20
+ "numpy>=1.21,<2.0",
21
+ "healpy>=1.15",
22
+ "camb>=1.5",
23
+ "glass>=0.5",
24
+ "scipy>=1.8",
25
+ "cosmology>=0.7",
26
+ ]
27
+
28
+ [project.optional-dependencies]
29
+ dev = [
30
+ "black",
31
+ "pytest",
32
+ "matplotlib",
33
+ "isort",
34
+
35
+ ]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,28 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name="hicrafter",
5
+ version="0.2.11",
6
+ description="HI Intensity Mapping generator with LHS sampling & multi-CPU batching",
7
+ long_description=open("README.md").read(),
8
+ long_description_content_type="text/markdown",
9
+ author="Your Name",
10
+ author_email="your.email@example.com",
11
+ packages=find_packages(),
12
+ install_requires=[
13
+ "numpy>=1.21",
14
+ "healpy>=1.15",
15
+ "camb>=0.5",
16
+ "glass>=0.5",
17
+ "scipy>=1.8",
18
+ ],
19
+ classifiers=[
20
+ "Development Status :: 4 - Beta",
21
+ "Intended Audience :: Science/Research",
22
+ "License :: OSI Approved :: MIT License",
23
+ "Programming Language :: Python :: 3",
24
+ "Programming Language :: Python :: 3.9",
25
+ "Topic :: Scientific/Engineering :: Astronomy",
26
+ ],
27
+ python_requires=">=3.9",
28
+ )