Skip to content

Commit 51bbc17

Browse files
beckermrsidneymau
andauthored
ENH add DES gal cat (#30)
* ENH add DES gal cat * REF add cuts and start in on script for catalogs * add use_all_gals option * ENH add cli to make catalogs * BUG need cli file at top-level * BUG fix typo in import * TST install ruff * BUG make sure to use larger area * BUG wrong field name * ENH add code for v2 cosmos catalogs * ENH v3 cats * ENH v4 cats * DOC add doc strings * BUG this import is gone * ENH v6 model * Update tests.yml * ENH v7 * TST added tests for new utils --------- Co-authored-by: Sidney Mau <sidneymau@gmail.com>
1 parent 5f019d5 commit 51bbc17

File tree

8 files changed

+984
-25
lines changed

8 files changed

+984
-25
lines changed

.github/workflows/tests.yml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,8 @@ jobs:
3232
- name: configure conda and install code
3333
shell: bash -l {0}
3434
run: |
35-
mamba install pytest flake8
36-
python -m pip install -e .
35+
conda install pytest ruff --yes --quiet
36+
python -m pip install --no-deps --no-build-isolation -e .
3737
3838
- name: test
3939
shell: bash -l {0}
@@ -43,4 +43,4 @@ jobs:
4343
- name: lint
4444
shell: bash -l {0}
4545
run: |
46-
flake8 montara
46+
ruff check montara

environment.yaml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,17 @@ channels:
22
- conda-forge
33
dependencies:
44
# run
5+
- click
56
- galsim
67
- fitsio
78
- numpy
89
- astropy
10+
- hpgeom
11+
- scipy
12+
- esutil
913
- pandas
1014
- des-eastlake
15+
- des-y6utils
1116
- galsim_extra
1217
- importlib_metadata
1318
- cfitsio # for fpack

montara/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,5 @@
2020
from . import badpixfromfits # noqa
2121
from . import eastlake_step # noqa
2222
from . import eval_gsobject # noqa
23+
from . import input_desgal # noqa
24+
from . import make_input_desgal # noqa

montara/des_tile.py

Lines changed: 34 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -539,27 +539,41 @@ def setup(self, config, base, file_num, logger):
539539
if isinstance(nobjects, dict):
540540
# ^ this should return True for both dict and OrderedDict
541541
if base['image']['nobjects']['type'] == "MixedNObjects":
542-
# First get the number of galaxies. Either this will be an int, in
543-
# which case
544-
# ParseValue will work straightaway, or a random variable, in which
545-
# case we'll
546-
# need to initalize the rng and then try ParseValue again.
547-
try:
548-
ngalaxies = galsim.config.ParseValue(
549-
nobjects, 'ngalaxies', base, int)[0]
550-
except TypeError:
551-
seed = galsim.config.ParseValue(
552-
base['image'], 'random_seed', base, int)[0]
542+
if nobjects.get("use_all_gals", False):
543+
# if we use all of the galaxies, then we look at the input desgals
544+
# object to get the number of galaxies
545+
galsim.config.input.SetupInput(base, logger=logger)
546+
key = 'desgal'
547+
field = base['input'][key]
548+
loader = galsim.config.input.valid_input_types[key]
549+
gal_input = galsim.config.GetInputObj("desgal", config, base, "desgal")
550+
if gal_input is None:
551+
kwargs, safe = loader.getKwargs(field, base, logger)
552+
kwargs['_nobjects_only'] = True
553+
gal_input = loader.init_func(**kwargs)
554+
ngalaxies = gal_input.getNObjects()
555+
else:
556+
# First get the number of galaxies. Either this will be an int, in
557+
# which case
558+
# ParseValue will work straightaway, or a random variable, in which
559+
# case we'll
560+
# need to initalize the rng and then try ParseValue again.
553561
try:
554-
assert (isinstance(seed, int) and (seed != 0))
555-
except AssertionError as e:
556-
logger.critical(
557-
"image.random_seed must be set to a non-zero integer for "
558-
"output type DES_Tile")
559-
raise e
560-
base['rng'] = galsim.BaseDeviate(seed)
561-
ngalaxies = galsim.config.ParseValue(nobjects, 'ngalaxies',
562-
base, int)[0]
562+
ngalaxies = galsim.config.ParseValue(
563+
nobjects, 'ngalaxies', base, int)[0]
564+
except TypeError:
565+
seed = galsim.config.ParseValue(
566+
base['image'], 'random_seed', base, int)[0]
567+
try:
568+
assert (isinstance(seed, int) and (seed != 0))
569+
except AssertionError as e:
570+
logger.critical(
571+
"image.random_seed must be set to a non-zero integer for "
572+
"output type DES_Tile")
573+
raise e
574+
base['rng'] = galsim.BaseDeviate(seed)
575+
ngalaxies = galsim.config.ParseValue(nobjects, 'ngalaxies',
576+
base, int)[0]
563577
logger.log(logging.CRITICAL, "simulating %d galaxies" % ngalaxies)
564578

565579
if nobjects.get("use_all_stars", True):

montara/input_desgal.py

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import logging
2+
3+
import fitsio
4+
import galsim
5+
import numpy as np
6+
from galsim.config.input import InputLoader, RegisterInputType, GetInputObj
7+
from galsim.config.value import RegisterValueType
8+
9+
from .utils import add_field
10+
11+
logger = logging.getLogger("pipeline")
12+
13+
14+
class DESGalCatalog(object):
15+
_req_params = {'file_name': str}
16+
_opt_params = {'cuts': dict, 'verbose': bool}
17+
_single_params = []
18+
_takes_rng = False
19+
20+
def __init__(self, file_name, cuts=None, _nobjects_only=False, verbose=False):
21+
self.gal_data = fitsio.read(file_name)
22+
self.gal_data = add_field(
23+
self.gal_data,
24+
[("catalog_row", int)],
25+
[np.arange(len(self.gal_data))],
26+
)
27+
self.cuts = cuts
28+
if cuts is not None:
29+
self.apply_cuts(cuts, verbose=verbose)
30+
self.nobjects = len(self.gal_data)
31+
32+
def apply_cuts(self, cuts, verbose=False):
33+
"""Apply some cuts.
34+
35+
- `cuts` is a dictionary
36+
- A key should be the same as a column in
37+
the catalog.
38+
- The value corresponding to that cut can either be
39+
a single integer, in which case that value will be retained
40+
e.g. "flags":0 would just keep objects with flags==0.
41+
Or it can be a range e.g. "hlr":[a,b] in which case only
42+
objects with a<=hlr<b will be retained.
43+
"""
44+
45+
use = np.ones(len(self.gal_data), dtype=bool)
46+
47+
for key, val in cuts.items():
48+
col_data = self.gal_data[key]
49+
50+
if len(val) == 1:
51+
mask = col_data == int(val[0])
52+
cut_string = "{0} == {1}".format(key, val[0])
53+
elif len(val) == 2:
54+
mask = (col_data >= val[0]) * (col_data < val[1])
55+
cut_string = "{0} <= {1} < {2}".format(val[0], key, val[1])
56+
else:
57+
raise ValueError("cut value should be length 1 or 2")
58+
59+
use[~mask] = False
60+
61+
if verbose:
62+
print('applying {0} leaves fraction {1}'.format(
63+
cut_string, float(mask.sum())/len(mask))
64+
)
65+
66+
if verbose:
67+
print("%d/%d objects remaining after cuts" % (use.sum(), len(use)))
68+
69+
self.gal_data = self.gal_data[use]
70+
71+
def get(self, index, col):
72+
return self.gal_data[index][col]
73+
74+
def getNObjects(self):
75+
return self.nobjects
76+
77+
78+
def _GenerateFromDESGalCatalog(config, base, value_type):
79+
"""@brief Return a value read from an input catalog
80+
"""
81+
gal_input = GetInputObj('desgal', config, base, 'DESGalValue')
82+
83+
# Setup the indexing sequence if it hasn't been specified.
84+
# The normal thing with a Catalog is to just use each object in order,
85+
# so we don't require the user to specify that by hand. We can do it for them.
86+
galsim.config.SetDefaultIndex(config, gal_input.getNObjects())
87+
88+
req = {'col': str, 'index': int}
89+
opt = {'num': int}
90+
kwargs, safe = galsim.config.GetAllParams(config, base, req=req, opt=opt)
91+
col = kwargs['col']
92+
index = kwargs['index']
93+
94+
logger.log(
95+
logging.DEBUG,
96+
"sampling fixed gal catalog band|index|col: %s %s %s" % (
97+
base["eval_variables"]["sband"],
98+
index,
99+
col,
100+
),
101+
)
102+
103+
val = gal_input.get(index, col)
104+
return val, safe
105+
106+
107+
RegisterInputType('desgal', InputLoader(DESGalCatalog, has_nobj=True))
108+
RegisterValueType(
109+
'DESGalValue',
110+
_GenerateFromDESGalCatalog,
111+
[float],
112+
input_type='desgal',
113+
)

0 commit comments

Comments
 (0)