Dataset Viewer
Auto-converted to Parquet Duplicate
instance_id
stringlengths
18
32
text
stringlengths
13.1k
63.9k
repo
stringclasses
11 values
base_commit
stringlengths
40
40
problem_statement
stringlengths
36
24.8k
hints_text
stringlengths
0
38.1k
created_at
stringlengths
20
20
patch
stringlengths
302
252k
test_patch
stringlengths
347
33.9k
version
stringclasses
55 values
FAIL_TO_PASS
stringlengths
12
95.7k
PASS_TO_PASS
stringlengths
2
271k
environment_setup_commit
stringlengths
40
40
astropy__astropy-12318
You will be provided with a partial code base and an issue statement explaining a problem to resolve. <issue> BlackBody bolometric flux is wrong if scale has units of dimensionless_unscaled The `astropy.modeling.models.BlackBody` class has the wrong bolometric flux if `scale` argument is passed as a Quantity with `dimensionless_unscaled` units, but the correct bolometric flux if `scale` is simply a float. ### Description <!-- Provide a general description of the bug. --> ### Expected behavior Expected output from sample code: ``` 4.823870774433646e-16 erg / (cm2 s) 4.823870774433646e-16 erg / (cm2 s) ``` ### Actual behavior Actual output from sample code: ``` 4.5930032795393893e+33 erg / (cm2 s) 4.823870774433646e-16 erg / (cm2 s) ``` ### Steps to Reproduce Sample code: ```python from astropy.modeling.models import BlackBody from astropy import units as u import numpy as np T = 3000 * u.K r = 1e14 * u.cm DL = 100 * u.Mpc scale = np.pi * (r / DL)**2 print(BlackBody(temperature=T, scale=scale).bolometric_flux) print(BlackBody(temperature=T, scale=scale.to_value(u.dimensionless_unscaled)).bolometric_flux) ``` ### System Details ```pycon >>> import numpy; print("Numpy", numpy.__version__) Numpy 1.20.2 >>> import astropy; print("astropy", astropy.__version__) astropy 4.3.dev758+g1ed1d945a >>> import scipy; print("Scipy", scipy.__version__) Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'scipy' >>> import matplotlib; print("Matplotlib", matplotlib.__version__) Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'matplotlib' ``` </issue> <code> [start of README.rst] 1 ======= 2 Astropy 3 ======= 4 5 |Actions Status| |CircleCI Status| |Azure Status| |Coverage Status| |PyPI Status| |Documentation Status| |Zenodo| 6 7 The Astropy Project (http://astropy.org/) is a community effort to develop a 8 single core package for Astronomy in Python and foster interoperability between 9 Python astronomy packages. This repository contains the core package which is 10 intended to contain much of the core functionality and some common tools needed 11 for performing astronomy and astrophysics with Python. 12 13 Releases are `registered on PyPI <https://pypi.org/project/astropy>`_, 14 and development is occurring at the 15 `project's GitHub page <http://github.com/astropy/astropy>`_. 16 17 For installation instructions, see the `online documentation <https://docs.astropy.org/>`_ 18 or `docs/install.rst <docs/install.rst>`_ in this source distribution. 19 20 Contributing Code, Documentation, or Feedback 21 --------------------------------------------- 22 23 The Astropy Project is made both by and for its users, so we welcome and 24 encourage contributions of many kinds. Our goal is to keep this a positive, 25 inclusive, successful, and growing community by abiding with the 26 `Astropy Community Code of Conduct <http://www.astropy.org/about.html#codeofconduct>`_. 27 28 More detailed information on contributing to the project or submitting feedback 29 can be found on the `contributions <http://www.astropy.org/contribute.html>`_ 30 page. A `summary of contribution guidelines <CONTRIBUTING.md>`_ can also be 31 used as a quick reference when you are ready to start writing or validating 32 code for submission. 33 34 Supporting the Project 35 ---------------------- 36 37 |NumFOCUS| |Donate| 38 39 The Astropy Project is sponsored by NumFOCUS, a 501(c)(3) nonprofit in the 40 United States. You can donate to the project by using the link above, and this 41 donation will support our mission to promote sustainable, high-level code base 42 for the astronomy community, open code development, educational materials, and 43 reproducible scientific research. 44 45 License 46 ------- 47 48 Astropy is licensed under a 3-clause BSD style license - see the 49 `LICENSE.rst <LICENSE.rst>`_ file. 50 51 .. |Actions Status| image:: https://github.com/astropy/astropy/workflows/CI/badge.svg 52 :target: https://github.com/astropy/astropy/actions 53 :alt: Astropy's GitHub Actions CI Status 54 55 .. |CircleCI Status| image:: https://img.shields.io/circleci/build/github/astropy/astropy/main?logo=circleci&label=CircleCI 56 :target: https://circleci.com/gh/astropy/astropy 57 :alt: Astropy's CircleCI Status 58 59 .. |Azure Status| image:: https://dev.azure.com/astropy-project/astropy/_apis/build/status/astropy.astropy?repoName=astropy%2Fastropy&branchName=main 60 :target: https://dev.azure.com/astropy-project/astropy 61 :alt: Astropy's Azure Pipelines Status 62 63 .. |Coverage Status| image:: https://codecov.io/gh/astropy/astropy/branch/main/graph/badge.svg 64 :target: https://codecov.io/gh/astropy/astropy 65 :alt: Astropy's Coverage Status 66 67 .. |PyPI Status| image:: https://img.shields.io/pypi/v/astropy.svg 68 :target: https://pypi.org/project/astropy 69 :alt: Astropy's PyPI Status 70 71 .. |Zenodo| image:: https://zenodo.org/badge/DOI/10.5281/zenodo.4670728.svg 72 :target: https://doi.org/10.5281/zenodo.4670728 73 :alt: Zenodo DOI 74 75 .. |Documentation Status| image:: https://img.shields.io/readthedocs/astropy/latest.svg?logo=read%20the%20docs&logoColor=white&label=Docs&version=stable 76 :target: https://docs.astropy.org/en/stable/?badge=stable 77 :alt: Documentation Status 78 79 .. |NumFOCUS| image:: https://img.shields.io/badge/powered%20by-NumFOCUS-orange.svg?style=flat&colorA=E1523D&colorB=007D8A 80 :target: http://numfocus.org 81 :alt: Powered by NumFOCUS 82 83 .. |Donate| image:: https://img.shields.io/badge/Donate-to%20Astropy-brightgreen.svg 84 :target: https://numfocus.salsalabs.org/donate-to-astropy/index.html 85 86 87 If you locally cloned this repo before 7 Apr 2021 88 ------------------------------------------------- 89 90 The primary branch for this repo has been transitioned from ``master`` to 91 ``main``. If you have a local clone of this repository and want to keep your 92 local branch in sync with this repo, you'll need to do the following in your 93 local clone from your terminal:: 94 95 git fetch --all --prune 96 # you can stop here if you don't use your local "master"/"main" branch 97 git branch -m master main 98 git branch -u origin/main main 99 100 If you are using a GUI to manage your repos you'll have to find the equivalent 101 commands as it's different for different programs. Alternatively, you can just 102 delete your local clone and re-clone! 103 [end of README.rst] [start of astropy/modeling/physical_models.py] 1 # Licensed under a 3-clause BSD style license - see LICENSE.rst 2 """ 3 Models that have physical origins. 4 """ 5 # pylint: disable=invalid-name, no-member 6 7 import warnings 8 9 import numpy as np 10 11 from astropy import constants as const 12 from astropy import units as u 13 from astropy.utils.exceptions import AstropyUserWarning 14 from .core import Fittable1DModel 15 from .parameters import Parameter, InputParameterError 16 17 __all__ = ["BlackBody", "Drude1D", "Plummer1D", "NFW"] 18 19 20 class BlackBody(Fittable1DModel): 21 """ 22 Blackbody model using the Planck function. 23 24 Parameters 25 ---------- 26 temperature : `~astropy.units.Quantity` ['temperature'] 27 Blackbody temperature. 28 29 scale : float or `~astropy.units.Quantity` ['dimensionless'] 30 Scale factor 31 32 Notes 33 ----- 34 35 Model formula: 36 37 .. math:: B_{\\nu}(T) = A \\frac{2 h \\nu^{3} / c^{2}}{exp(h \\nu / k T) - 1} 38 39 Examples 40 -------- 41 >>> from astropy.modeling import models 42 >>> from astropy import units as u 43 >>> bb = models.BlackBody(temperature=5000*u.K) 44 >>> bb(6000 * u.AA) # doctest: +FLOAT_CMP 45 <Quantity 1.53254685e-05 erg / (cm2 Hz s sr)> 46 47 .. plot:: 48 :include-source: 49 50 import numpy as np 51 import matplotlib.pyplot as plt 52 53 from astropy.modeling.models import BlackBody 54 from astropy import units as u 55 from astropy.visualization import quantity_support 56 57 bb = BlackBody(temperature=5778*u.K) 58 wav = np.arange(1000, 110000) * u.AA 59 flux = bb(wav) 60 61 with quantity_support(): 62 plt.figure() 63 plt.semilogx(wav, flux) 64 plt.axvline(bb.nu_max.to(u.AA, equivalencies=u.spectral()).value, ls='--') 65 plt.show() 66 """ 67 68 # We parametrize this model with a temperature and a scale. 69 temperature = Parameter(default=5000.0, min=0, unit=u.K, description="Blackbody temperature") 70 scale = Parameter(default=1.0, min=0, description="Scale factor") 71 72 # We allow values without units to be passed when evaluating the model, and 73 # in this case the input x values are assumed to be frequencies in Hz. 74 _input_units_allow_dimensionless = True 75 76 # We enable the spectral equivalency by default for the spectral axis 77 input_units_equivalencies = {'x': u.spectral()} 78 79 def evaluate(self, x, temperature, scale): 80 """Evaluate the model. 81 82 Parameters 83 ---------- 84 x : float, `~numpy.ndarray`, or `~astropy.units.Quantity` ['frequency'] 85 Frequency at which to compute the blackbody. If no units are given, 86 this defaults to Hz. 87 88 temperature : float, `~numpy.ndarray`, or `~astropy.units.Quantity` 89 Temperature of the blackbody. If no units are given, this defaults 90 to Kelvin. 91 92 scale : float, `~numpy.ndarray`, or `~astropy.units.Quantity` ['dimensionless'] 93 Desired scale for the blackbody. 94 95 Returns 96 ------- 97 y : number or ndarray 98 Blackbody spectrum. The units are determined from the units of 99 ``scale``. 100 101 .. note:: 102 103 Use `numpy.errstate` to suppress Numpy warnings, if desired. 104 105 .. warning:: 106 107 Output values might contain ``nan`` and ``inf``. 108 109 Raises 110 ------ 111 ValueError 112 Invalid temperature. 113 114 ZeroDivisionError 115 Wavelength is zero (when converting to frequency). 116 """ 117 if not isinstance(temperature, u.Quantity): 118 in_temp = u.Quantity(temperature, u.K) 119 else: 120 in_temp = temperature 121 122 # Convert to units for calculations, also force double precision 123 with u.add_enabled_equivalencies(u.spectral() + u.temperature()): 124 freq = u.Quantity(x, u.Hz, dtype=np.float64) 125 temp = u.Quantity(in_temp, u.K) 126 127 # check the units of scale and setup the output units 128 bb_unit = u.erg / (u.cm ** 2 * u.s * u.Hz * u.sr) # default unit 129 # use the scale that was used at initialization for determining the units to return 130 # to support returning the right units when fitting where units are stripped 131 if hasattr(self.scale, "unit") and self.scale.unit is not None: 132 # check that the units on scale are covertable to surface brightness units 133 if not self.scale.unit.is_equivalent(bb_unit, u.spectral_density(x)): 134 raise ValueError( 135 f"scale units not surface brightness: {self.scale.unit}" 136 ) 137 # use the scale passed to get the value for scaling 138 if hasattr(scale, "unit"): 139 mult_scale = scale.value 140 else: 141 mult_scale = scale 142 bb_unit = self.scale.unit 143 else: 144 mult_scale = scale 145 146 # Check if input values are physically possible 147 if np.any(temp < 0): 148 raise ValueError(f"Temperature should be positive: {temp}") 149 if not np.all(np.isfinite(freq)) or np.any(freq <= 0): 150 warnings.warn( 151 "Input contains invalid wavelength/frequency value(s)", 152 AstropyUserWarning, 153 ) 154 155 log_boltz = const.h * freq / (const.k_B * temp) 156 boltzm1 = np.expm1(log_boltz) 157 158 # Calculate blackbody flux 159 bb_nu = 2.0 * const.h * freq ** 3 / (const.c ** 2 * boltzm1) / u.sr 160 161 y = mult_scale * bb_nu.to(bb_unit, u.spectral_density(freq)) 162 163 # If the temperature parameter has no unit, we should return a unitless 164 # value. This occurs for instance during fitting, since we drop the 165 # units temporarily. 166 if hasattr(temperature, "unit"): 167 return y 168 return y.value 169 170 @property 171 def input_units(self): 172 # The input units are those of the 'x' value, which should always be 173 # Hz. Because we do this, and because input_units_allow_dimensionless 174 # is set to True, dimensionless values are assumed to be in Hz. 175 return {self.inputs[0]: u.Hz} 176 177 def _parameter_units_for_data_units(self, inputs_unit, outputs_unit): 178 return {"temperature": u.K} 179 180 @property 181 def bolometric_flux(self): 182 """Bolometric flux.""" 183 # bolometric flux in the native units of the planck function 184 native_bolflux = ( 185 self.scale.value * const.sigma_sb * self.temperature ** 4 / np.pi 186 ) 187 # return in more "astro" units 188 return native_bolflux.to(u.erg / (u.cm ** 2 * u.s)) 189 190 @property 191 def lambda_max(self): 192 """Peak wavelength when the curve is expressed as power density.""" 193 return const.b_wien / self.temperature 194 195 @property 196 def nu_max(self): 197 """Peak frequency when the curve is expressed as power density.""" 198 return 2.8214391 * const.k_B * self.temperature / const.h 199 200 201 class Drude1D(Fittable1DModel): 202 """ 203 Drude model based one the behavior of electons in materials (esp. metals). 204 205 Parameters 206 ---------- 207 amplitude : float 208 Peak value 209 x_0 : float 210 Position of the peak 211 fwhm : float 212 Full width at half maximum 213 214 Model formula: 215 216 .. math:: f(x) = A \\frac{(fwhm/x_0)^2}{((x/x_0 - x_0/x)^2 + (fwhm/x_0)^2} 217 218 Examples 219 -------- 220 221 .. plot:: 222 :include-source: 223 224 import numpy as np 225 import matplotlib.pyplot as plt 226 227 from astropy.modeling.models import Drude1D 228 229 fig, ax = plt.subplots() 230 231 # generate the curves and plot them 232 x = np.arange(7.5 , 12.5 , 0.1) 233 234 dmodel = Drude1D(amplitude=1.0, fwhm=1.0, x_0=10.0) 235 ax.plot(x, dmodel(x)) 236 237 ax.set_xlabel('x') 238 ax.set_ylabel('F(x)') 239 240 plt.show() 241 """ 242 243 amplitude = Parameter(default=1.0, description="Peak Value") 244 x_0 = Parameter(default=1.0, description="Position of the peak") 245 fwhm = Parameter(default=1.0, description="Full width at half maximum") 246 247 @staticmethod 248 def evaluate(x, amplitude, x_0, fwhm): 249 """ 250 One dimensional Drude model function 251 """ 252 return ( 253 amplitude 254 * ((fwhm / x_0) ** 2) 255 / ((x / x_0 - x_0 / x) ** 2 + (fwhm / x_0) ** 2) 256 ) 257 258 @staticmethod 259 def fit_deriv(x, amplitude, x_0, fwhm): 260 """ 261 Drude1D model function derivatives. 262 """ 263 d_amplitude = (fwhm / x_0) ** 2 / ((x / x_0 - x_0 / x) ** 2 + (fwhm / x_0) ** 2) 264 d_x_0 = ( 265 -2 266 * amplitude 267 * d_amplitude 268 * ( 269 (1 / x_0) 270 + d_amplitude 271 * (x_0 ** 2 / fwhm ** 2) 272 * ( 273 (-x / x_0 - 1 / x) * (x / x_0 - x_0 / x) 274 - (2 * fwhm ** 2 / x_0 ** 3) 275 ) 276 ) 277 ) 278 d_fwhm = (2 * amplitude * d_amplitude / fwhm) * (1 - d_amplitude) 279 return [d_amplitude, d_x_0, d_fwhm] 280 281 @property 282 def input_units(self): 283 if self.x_0.unit is None: 284 return None 285 return {self.inputs[0]: self.x_0.unit} 286 287 def _parameter_units_for_data_units(self, inputs_unit, outputs_unit): 288 return { 289 "x_0": inputs_unit[self.inputs[0]], 290 "fwhm": inputs_unit[self.inputs[0]], 291 "amplitude": outputs_unit[self.outputs[0]], 292 } 293 294 @property 295 def return_units(self): 296 if self.amplitude.unit is None: 297 return None 298 return {self.outputs[0]: self.amplitude.unit} 299 300 @x_0.validator 301 def x_0(self, val): 302 """ Ensure `x_0` is not 0.""" 303 if np.any(val == 0): 304 raise InputParameterError("0 is not an allowed value for x_0") 305 306 def bounding_box(self, factor=50): 307 """Tuple defining the default ``bounding_box`` limits, 308 ``(x_low, x_high)``. 309 310 Parameters 311 ---------- 312 factor : float 313 The multiple of FWHM used to define the limits. 314 """ 315 x0 = self.x_0 316 dx = factor * self.fwhm 317 318 return (x0 - dx, x0 + dx) 319 320 321 class Plummer1D(Fittable1DModel): 322 r"""One dimensional Plummer density profile model. 323 324 Parameters 325 ---------- 326 mass : float 327 Total mass of cluster. 328 r_plum : float 329 Scale parameter which sets the size of the cluster core. 330 331 Notes 332 ----- 333 Model formula: 334 335 .. math:: 336 337 \rho(r)=\frac{3M}{4\pi a^3}(1+\frac{r^2}{a^2})^{-5/2} 338 339 References 340 ---------- 341 .. [1] https://ui.adsabs.harvard.edu/abs/1911MNRAS..71..460P 342 """ 343 344 mass = Parameter(default=1.0, description="Total mass of cluster") 345 r_plum = Parameter(default=1.0, description="Scale parameter which sets the size of the cluster core") 346 347 @staticmethod 348 def evaluate(x, mass, r_plum): 349 """ 350 Evaluate plummer density profile model. 351 """ 352 return (3*mass)/(4 * np.pi * r_plum**3) * (1+(x/r_plum)**2)**(-5/2) 353 354 @staticmethod 355 def fit_deriv(x, mass, r_plum): 356 """ 357 Plummer1D model derivatives. 358 """ 359 d_mass = 3 / ((4*np.pi*r_plum**3) * (((x/r_plum)**2 + 1)**(5/2))) 360 d_r_plum = (6*mass*x**2-9*mass*r_plum**2) / ((4*np.pi * r_plum**6) * 361 (1+(x/r_plum)**2)**(7/2)) 362 return [d_mass, d_r_plum] 363 364 @property 365 def input_units(self): 366 if self.mass.unit is None and self.r_plum.unit is None: 367 return None 368 else: 369 return {self.inputs[0]: self.r_plum.unit} 370 371 def _parameter_units_for_data_units(self, inputs_unit, outputs_unit): 372 return {'mass': outputs_unit[self.outputs[0]] * inputs_unit[self.inputs[0]] ** 3, 373 'r_plum': inputs_unit[self.inputs[0]]} 374 375 376 class NFW(Fittable1DModel): 377 r""" 378 Navarro–Frenk–White (NFW) profile - model for radial distribution of dark matter. 379 380 Parameters 381 ---------- 382 mass : float or `~astropy.units.Quantity` ['mass'] 383 Mass of NFW peak within specified overdensity radius. 384 concentration : float 385 Concentration of the NFW profile. 386 redshift : float 387 Redshift of the NFW profile. 388 massfactor : tuple or str 389 Mass overdensity factor and type for provided profiles: 390 Tuple version: 391 ("virial",) : virial radius 392 393 ("critical", N) : radius where density is N times that of the critical density 394 395 ("mean", N) : radius where density is N times that of the mean density 396 397 String version: 398 "virial" : virial radius 399 400 "Nc" : radius where density is N times that of the critical density (e.g. "200c") 401 402 "Nm" : radius where density is N times that of the mean density (e.g. "500m") 403 cosmo : :class:`~astropy.cosmology.Cosmology` 404 Background cosmology for density calculation. If None, the default cosmology will be used. 405 406 Notes 407 ----- 408 409 Model formula: 410 411 .. math:: \rho(r)=\frac{\delta_c\rho_{c}}{r/r_s(1+r/r_s)^2} 412 413 References 414 ---------- 415 .. [1] https://arxiv.org/pdf/astro-ph/9508025 416 .. [2] https://en.wikipedia.org/wiki/Navarro%E2%80%93Frenk%E2%80%93White_profile 417 .. [3] https://en.wikipedia.org/wiki/Virial_mass 418 """ 419 420 # Model Parameters 421 422 # NFW Profile mass 423 mass = Parameter(default=1.0, min=1.0, unit=u.M_sun, 424 description="Peak mass within specified overdensity radius") 425 426 # NFW profile concentration 427 concentration = Parameter(default=1.0, min=1.0, description="Concentration") 428 429 # NFW Profile redshift 430 redshift = Parameter(default=0.0, min=0.0, description="Redshift") 431 432 # We allow values without units to be passed when evaluating the model, and 433 # in this case the input r values are assumed to be lengths / positions in kpc. 434 _input_units_allow_dimensionless = True 435 436 def __init__(self, mass=u.Quantity(mass.default, mass.unit), 437 concentration=concentration.default, redshift=redshift.default, 438 massfactor=("critical", 200), cosmo=None, **kwargs): 439 # Set default cosmology 440 if cosmo is None: 441 # LOCAL 442 from astropy.cosmology import default_cosmology 443 444 cosmo = default_cosmology.get() 445 446 # Set mass overdensity type and factor 447 self._density_delta(massfactor, cosmo, redshift) 448 449 # Establish mass units for density calculation (default solar masses) 450 if not isinstance(mass, u.Quantity): 451 in_mass = u.Quantity(mass, u.M_sun) 452 else: 453 in_mass = mass 454 455 # Obtain scale radius 456 self._radius_s(mass, concentration) 457 458 # Obtain scale density 459 self._density_s(mass, concentration) 460 461 super().__init__(mass=in_mass, concentration=concentration, redshift=redshift, **kwargs) 462 463 def evaluate(self, r, mass, concentration, redshift): 464 """ 465 One dimensional NFW profile function 466 467 Parameters 468 ---------- 469 r : float or `~astropy.units.Quantity` ['length'] 470 Radial position of density to be calculated for the NFW profile. 471 mass : float or `~astropy.units.Quantity` ['mass'] 472 Mass of NFW peak within specified overdensity radius. 473 concentration : float 474 Concentration of the NFW profile. 475 redshift : float 476 Redshift of the NFW profile. 477 478 Returns 479 ------- 480 density : float or `~astropy.units.Quantity` ['density'] 481 NFW profile mass density at location ``r``. The density units are: 482 [``mass`` / ``r`` ^3] 483 484 Notes 485 ----- 486 .. warning:: 487 488 Output values might contain ``nan`` and ``inf``. 489 """ 490 # Create radial version of input with dimension 491 if hasattr(r, "unit"): 492 in_r = r 493 else: 494 in_r = u.Quantity(r, u.kpc) 495 496 # Define reduced radius (r / r_{\\rm s}) 497 # also update scale radius 498 radius_reduced = in_r / self._radius_s(mass, concentration).to(in_r.unit) 499 500 # Density distribution 501 # \rho (r)=\frac{\rho_0}{\frac{r}{R_s}\left(1~+~\frac{r}{R_s}\right)^2} 502 # also update scale density 503 density = self._density_s(mass, concentration) / (radius_reduced * 504 (u.Quantity(1.0) + radius_reduced) ** 2) 505 506 if hasattr(mass, "unit"): 507 return density 508 else: 509 return density.value 510 511 def _density_delta(self, massfactor, cosmo, redshift): 512 """ 513 Calculate density delta. 514 """ 515 # Set mass overdensity type and factor 516 if isinstance(massfactor, tuple): 517 # Tuple options 518 # ("virial") : virial radius 519 # ("critical", N) : radius where density is N that of the critical density 520 # ("mean", N) : radius where density is N that of the mean density 521 if massfactor[0].lower() == "virial": 522 # Virial Mass 523 delta = None 524 masstype = massfactor[0].lower() 525 elif massfactor[0].lower() == "critical": 526 # Critical or Mean Overdensity Mass 527 delta = float(massfactor[1]) 528 masstype = 'c' 529 elif massfactor[0].lower() == "mean": 530 # Critical or Mean Overdensity Mass 531 delta = float(massfactor[1]) 532 masstype = 'm' 533 else: 534 raise ValueError("Massfactor '" + str(massfactor[0]) + "' not one of 'critical', " 535 "'mean', or 'virial'") 536 else: 537 try: 538 # String options 539 # virial : virial radius 540 # Nc : radius where density is N that of the critical density 541 # Nm : radius where density is N that of the mean density 542 if massfactor.lower() == "virial": 543 # Virial Mass 544 delta = None 545 masstype = massfactor.lower() 546 elif massfactor[-1].lower() == 'c' or massfactor[-1].lower() == 'm': 547 # Critical or Mean Overdensity Mass 548 delta = float(massfactor[0:-1]) 549 masstype = massfactor[-1].lower() 550 else: 551 raise ValueError("Massfactor " + str(massfactor) + " string not of the form " 552 "'#m', '#c', or 'virial'") 553 except (AttributeError, TypeError): 554 raise TypeError("Massfactor " + str( 555 massfactor) + " not a tuple or string") 556 557 # Set density from masstype specification 558 if masstype == "virial": 559 Om_c = cosmo.Om(redshift) - 1.0 560 d_c = 18.0 * np.pi ** 2 + 82.0 * Om_c - 39.0 * Om_c ** 2 561 self.density_delta = d_c * cosmo.critical_density(redshift) 562 elif masstype == 'c': 563 self.density_delta = delta * cosmo.critical_density(redshift) 564 elif masstype == 'm': 565 self.density_delta = delta * cosmo.critical_density(redshift) * cosmo.Om(redshift) 566 567 return self.density_delta 568 569 @staticmethod 570 def A_NFW(y): 571 r""" 572 Dimensionless volume integral of the NFW profile, used as an intermediate step in some 573 calculations for this model. 574 575 Notes 576 ----- 577 578 Model formula: 579 580 .. math:: A_{NFW} = [\ln(1+y) - \frac{y}{1+y}] 581 """ 582 return np.log(1.0 + y) - (y / (1.0 + y)) 583 584 def _density_s(self, mass, concentration): 585 """ 586 Calculate scale density of the NFW profile. 587 """ 588 # Enforce default units 589 if not isinstance(mass, u.Quantity): 590 in_mass = u.Quantity(mass, u.M_sun) 591 else: 592 in_mass = mass 593 594 # Calculate scale density 595 # M_{200} = 4\pi \rho_{s} R_{s}^3 \left[\ln(1+c) - \frac{c}{1+c}\right]. 596 self.density_s = in_mass / (4.0 * np.pi * self._radius_s(in_mass, concentration) ** 3 * 597 self.A_NFW(concentration)) 598 599 return self.density_s 600 601 @property 602 def rho_scale(self): 603 r""" 604 Scale density of the NFW profile. Often written in the literature as :math:`\rho_s` 605 """ 606 return self.density_s 607 608 def _radius_s(self, mass, concentration): 609 """ 610 Calculate scale radius of the NFW profile. 611 """ 612 # Enforce default units 613 if not isinstance(mass, u.Quantity): 614 in_mass = u.Quantity(mass, u.M_sun) 615 else: 616 in_mass = mass 617 618 # Delta Mass is related to delta radius by 619 # M_{200}=\frac{4}{3}\pi r_{200}^3 200 \rho_{c} 620 # And delta radius is related to the NFW scale radius by 621 # c = R / r_{\\rm s} 622 self.radius_s = (((3.0 * in_mass) / (4.0 * np.pi * self.density_delta)) ** ( 623 1.0 / 3.0)) / concentration 624 625 # Set radial units to kiloparsec by default (unit will be rescaled by units of radius 626 # in evaluate) 627 return self.radius_s.to(u.kpc) 628 629 @property 630 def r_s(self): 631 """ 632 Scale radius of the NFW profile. 633 """ 634 return self.radius_s 635 636 @property 637 def r_virial(self): 638 """ 639 Mass factor defined virial radius of the NFW profile (R200c for M200c, Rvir for Mvir, etc.). 640 """ 641 return self.r_s * self.concentration 642 643 @property 644 def r_max(self): 645 """ 646 Radius of maximum circular velocity. 647 """ 648 return self.r_s * 2.16258 649 650 @property 651 def v_max(self): 652 """ 653 Maximum circular velocity. 654 """ 655 return self.circular_velocity(self.r_max) 656 657 def circular_velocity(self, r): 658 r""" 659 Circular velocities of the NFW profile. 660 661 Parameters 662 ---------- 663 r : float or `~astropy.units.Quantity` ['length'] 664 Radial position of velocity to be calculated for the NFW profile. 665 666 Returns 667 ------- 668 velocity : float or `~astropy.units.Quantity` ['speed'] 669 NFW profile circular velocity at location ``r``. The velocity units are: 670 [km / s] 671 672 Notes 673 ----- 674 675 Model formula: 676 677 .. math:: v_{circ}(r)^2 = \frac{1}{x}\frac{\ln(1+cx)-(cx)/(1+cx)}{\ln(1+c)-c/(1+c)} 678 679 .. math:: x = r/r_s 680 681 .. warning:: 682 683 Output values might contain ``nan`` and ``inf``. 684 """ 685 # Enforce default units (if parameters are without units) 686 if hasattr(r, "unit"): 687 in_r = r 688 else: 689 in_r = u.Quantity(r, u.kpc) 690 691 # Mass factor defined velocity (i.e. V200c for M200c, Rvir for Mvir) 692 v_profile = np.sqrt(self.mass * const.G.to(in_r.unit**3 / (self.mass.unit * u.s**2)) / 693 self.r_virial) 694 695 # Define reduced radius (r / r_{\\rm s}) 696 reduced_radius = in_r / self.r_virial.to(in_r.unit) 697 698 # Circular velocity given by: 699 # v^2=\frac{1}{x}\frac{\ln(1+cx)-(cx)/(1+cx)}{\ln(1+c)-c/(1+c)} 700 # where x=r/r_{200} 701 velocity = np.sqrt((v_profile**2 * self.A_NFW(self.concentration * reduced_radius)) / 702 (reduced_radius * self.A_NFW(self.concentration))) 703 704 return velocity.to(u.km / u.s) 705 706 @property 707 def input_units(self): 708 # The units for the 'r' variable should be a length (default kpc) 709 return {self.inputs[0]: u.kpc} 710 711 @property 712 def return_units(self): 713 # The units for the 'density' variable should be a matter density (default M_sun / kpc^3) 714 715 if (self.mass.unit is None): 716 return {self.outputs[0]: u.M_sun / self.input_units[self.inputs[0]] ** 3} 717 else: 718 return {self.outputs[0]: self.mass.unit / self.input_units[self.inputs[0]] ** 3} 719 720 def _parameter_units_for_data_units(self, inputs_unit, outputs_unit): 721 return {'mass': u.M_sun, 722 "concentration": None, 723 "redshift": None} 724 [end of astropy/modeling/physical_models.py] </code> I need you to solve this issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the following format. <patch> --- a/file.py +++ b/file.py @@ -1,27 +1,35 @@ def euclidean(a, b): - while b: - a, b = b, a % b - return a + if b == 0: + return a + return euclidean(b, a % b) def bresenham(x0, y0, x1, y1): points = [] dx = abs(x1 - x0) dy = abs(y1 - y0) - sx = 1 if x0 < x1 else -1 - sy = 1 if y0 < y1 else -1 - err = dx - dy + x, y = x0, y0 + sx = -1 if x0 > x1 else 1 + sy = -1 if y0 > y1 else 1 - while True: - points.append((x0, y0)) - if x0 == x1 and y0 == y1: - break - e2 = 2 * err - if e2 > -dy: + if dx > dy: + err = dx / 2.0 + while x != x1: + points.append((x, y)) err -= dy - x0 += sx - if e2 < dx: - err += dx - y0 += sy + if err < 0: + y += sy + err += dx + x += sx + else: + err = dy / 2.0 + while y != y1: + points.append((x, y)) + err -= dx + if err < 0: + x += sx + err += dy + y += sy + points.append((x, y)) return points </patch>
astropy/astropy
43ce7895bb5b61d4fab2f9cc7d07016cf105f18e
BlackBody bolometric flux is wrong if scale has units of dimensionless_unscaled The `astropy.modeling.models.BlackBody` class has the wrong bolometric flux if `scale` argument is passed as a Quantity with `dimensionless_unscaled` units, but the correct bolometric flux if `scale` is simply a float. ### Description <!-- Provide a general description of the bug. --> ### Expected behavior Expected output from sample code: ``` 4.823870774433646e-16 erg / (cm2 s) 4.823870774433646e-16 erg / (cm2 s) ``` ### Actual behavior Actual output from sample code: ``` 4.5930032795393893e+33 erg / (cm2 s) 4.823870774433646e-16 erg / (cm2 s) ``` ### Steps to Reproduce Sample code: ```python from astropy.modeling.models import BlackBody from astropy import units as u import numpy as np T = 3000 * u.K r = 1e14 * u.cm DL = 100 * u.Mpc scale = np.pi * (r / DL)**2 print(BlackBody(temperature=T, scale=scale).bolometric_flux) print(BlackBody(temperature=T, scale=scale.to_value(u.dimensionless_unscaled)).bolometric_flux) ``` ### System Details ```pycon >>> import numpy; print("Numpy", numpy.__version__) Numpy 1.20.2 >>> import astropy; print("astropy", astropy.__version__) astropy 4.3.dev758+g1ed1d945a >>> import scipy; print("Scipy", scipy.__version__) Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'scipy' >>> import matplotlib; print("Matplotlib", matplotlib.__version__) Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'matplotlib' ```
I forgot who added that part of `BlackBody`. It was either @karllark or @astrofrog . There are several problems here: 1. In `BlackBody.evaluate()`, there is an `if` statement that handles two special cases: either scale is dimensionless, and multiplies the original blackbody surface brightness, or `scale` has units that are compatible with surface brightness, and replaces the original surface brightness. This check is broken, because it does not correctly handle the case that `scale` has a unit, but that unit is compatible with `dimensionless_unscaled`. This is easy to fix. 2. The `BlackBody.bolometric_flux` method does not handle this special case. Again, this is easy to fix. 3. In the case that `scale` has units that are compatible with surface brightness, it is impossible to unambiguously determine the correct multiplier in `BlackBody.bolometric_flux`, because the conversion may depend on the frequency or wavelength at which the scale was given. This might be a design flaw. Unless I'm missing something, there is no way for this class to give an unambiguous and correct value of the bolometric flux, unless `scale` is dimensionless. Is that correct? Here's another weird output from BlackBody. I _think_ it's a manifestation of the same bug, or at least it's related. I create three black bodies: * `bb1` with a scale=1 erg / (cm2 Hz s sr) * `bb2` with a scale=1 J / (cm2 Hz s sr) * `bb3` with a scale=1e7 erg / (cm2 Hz s sr) The spectra from `bb1` and `bb2` look the same, even though `bb2` should be (1 J / 1 erg) = 1e7 times as bright! And the spectrum from `bb3` looks different from `bb2`, even though 1e7 erg = 1 J. ```python from astropy.modeling.models import BlackBody from astropy import units as u from matplotlib import pyplot as plt import numpy as np nu = np.geomspace(0.1, 10) * u.micron bb1 = BlackBody(temperature=3000*u.K, scale=1*u.erg/(u.cm ** 2 * u.s * u.Hz * u.sr)) bb2 = BlackBody(temperature=3000*u.K, scale=1*u.J/(u.cm ** 2 * u.s * u.Hz * u.sr)) bb3 = BlackBody(temperature=3000*u.K, scale=1e7*u.erg/(u.cm ** 2 * u.s * u.Hz * u.sr)) fig, ax = plt.subplots() ax.set_xscale('log') ax.set_yscale('log') ax.plot(nu.value, bb1(nu).to_value(u.erg/(u.cm ** 2 * u.s * u.Hz * u.sr)), lw=4, label='bb1') ax.plot(nu.value, bb2(nu).to_value(u.erg/(u.cm ** 2 * u.s * u.Hz * u.sr)), label='bb2') ax.plot(nu.value, bb3(nu).to_value(u.erg/(u.cm ** 2 * u.s * u.Hz * u.sr)), label='bb3') ax.legend() fig.savefig('test.png') ``` ![test](https://user-images.githubusercontent.com/728407/115497738-3e2ef600-a23a-11eb-93b0-c9e358afd986.png) This is great testing of the code. Thanks! I think I was the one that added this capability. I don't have time at this point to investigate this issue in detail. I can look at in the near(ish) future. If someone else is motivated and has time to investigate and solve, I'm happy to cheer from the sidelines. In pseudocode, here's what the code does with `scale`: * If `scale` has no units, it simply multiplies a standard blackbody. * If `scale` has units that are compatible with flux density, it splits off the value and unit. The value multiplies the standard blackbody, and the output is converted to the given unit. So in both cases, the actual _units_ of the `scale` parameter are ignored. Only the _value_ of the `scale` parameter matters. As nice as the spectral equivalencies are, I think it was a mistake to support a dimensionful `scale` parameter. Clearly that case is completely broken. Can we simply remove that functionality? Beginning to think that the scale keyword should go away (in time, deprecated first of course) and docs updated to clearly show how to convert between units (flam to fnu for example) and remove sterradians. Astropy does have great units support and the scale functionality can all be accomplished with such. Not 100% sure yet, looking forward to seeing what others think. The blackbody function would return in default units and scale (fnu seems like the best choice, but kinda arbitrary in the end). If my memory is correct, the scale keyword was partially introduced to be able to reproduce the previous behavior of two backbody functions that were deprecated and have now been removed from astropy. No, I think @astrofrog introduced scale for fitting. The functional, uh, functions that we have removed did not have scaling. FWIW, I still have the old stuff over at https://github.com/spacetelescope/synphot_refactor/blob/master/synphot/blackbody.py . I never got around to using the new models over there. 😬 In trying to handle support for flux units outside of the `BlackBody` model, I ran into a few issues that I'll try to summarize with an example below. ``` from astropy.modeling import models import astropy.units as u import numpy as np FLAM = u.erg / (u.cm ** 2 * u.s * u.AA) SLAM = u.erg / (u.cm ** 2 * u.s * u.AA * u.sr) wavelengths = np.linspace(2000, 50000, 10001)*u.AA ``` Using `Scale` to handle the unit conversion fails in the forward model because the `Scale` model will not accept wavelength units as input (it seems `factor` **must** be provided in the same units as the input x-array, but we need output of `sr` for the units to cooperate). ``` m = models.BlackBody(temperature=5678*u.K, scale=1.0*SLAM) * models.Scale(factor=1.0*u.sr) fluxes = m(wavelengths) ``` which gives the error: `Scale: Units of input 'x', Angstrom (length), could not be converted to required input units of sr (solid angle)`. Using `Linear1D` with a slope of 0 and an intercept as the scaling factor (with appropriate units to convert from wavelength to `sr`) does work for the forward model, and yields correct units from the `Compound` model, but fails within fitting when calling `without_units_for_data`: ``` m = models.BlackBody(temperature=5678*u.K, scale=1.0*SLAM) * models.Linear1D(slope=0.0*u.sr/u.AA, intercept=1.0*u.sr) fluxes = m(wavelengths) m.without_units_for_data(x=wavelengths, y=fluxes) ``` with the error: `'sr' (solid angle) and 'erg / (Angstrom cm2 s)' (power density/spectral flux density wav) are not convertible`. It seems to me that this error _might_ be a bug (?), and if it could be fixed, then this approach would technically work for handling the scale and unit conversions externally, but its not exactly obvious or clean from the user-perspective. Is there another approach for handling the conversion externally to the model that works with fitting and `Compound` models? If not, then either the `without_units_for_data` needs to work for a case like this, or I think `scale` in `BlackBody` might need to be kept and extended to support `FLAM` and `FNU` units as input to allow fluxes as output. While I broadly like the cleanness of @karllark's approach of just saying "rescale to your hearts desire", I'm concerned that the ship has essentially sailed. In particular, I think the following are true: 1. Plenty of other models have scale parameters, so users probably took that up conceptually already 2. In situations like `specutils` where the blackbody model is used as a tool on already-existing data, it's often useful to carry around the model *with its units*. So to me that argues pretty clearly for "allow `scale` to have whatever units the user wants. But I see a way to "have our cake and eat it too": 1. Take the existing blackbody model, remove the `scale`, and call it `UnscaledBlackbodyModel` or something 2. Make a new `BlackbodyModel` which is a compound model using `Scale` (with `scale` as the keyword), assuming @kecnry's report that it failed can be fixed (since it sure seems like as a bug). That way we can let people move in the direction @karllark suggested if it seems like people actually like it by telling them to use `UnscaledBlackbodyModel`, but fixing the problem with `Scale` at the same time. (Plan B, at least if we want something fixed for Astropy 5.0, is to just fix `scale` and have the above be a longer-term plan for maybe 5.1) If someone else wants to do Plan B for ver5.0 as described by @eteq, that's fine with me. I won't have time before Friday to do such. I think that all of these proposed solutions fail to address the problem that scale units of FLAM or FNU cannot be handled unambiguously, because the reference frequency or wavelength is unspecified. I feel the way forward on this topic is to generate a list of use cases for the use of the scale keyword and then we can figure out how to modify the current code. These use cases can be coded up into tests. I have to admit I'm getting a little lost in knowing what all the uses of scale. And if all the use cases are compatible with each other. @lpsinger - agreed. The `bolometric_flux` method and adding support for flux units to `evaluate` are definitely related, but have slightly different considerations that make this quite difficult. Sorry if the latter goal somewhat hijacked this issue - but I do think the solution needs to account for both (as well as the unitless "bug" in your original post). @karllark - also agreed. After looking into this in more detail, I think `scale` really has 2 (and perhaps eventually 3) different purposes: a _unitless_ scale to the blackbody equation, determining the output units of `evaluate` and whether it should be wrt wavelength or frequency, and possibly would also be responsible for providing `sterradians` to convert to flux units. Separating this functionality into three separate arguments might be the simplest to implement and perhaps the clearest and might resolve the `bolometric_flux` concern, but also is clunky for the user and might be a little difficult for backwards compatibility. Keeping it as one argument is definitely convenient, but confusing and raises issues with ambiguity in `bolometric_flux` mentioned above. @kecnry, I'm concerned that overloading the scale to handle either a unitless value or a value with units of steradians is a footgun, because depending on the units you pass, it may or may not add a factor of pi. This is a footgun because people often think of steradians as being dimensionless. @lpsinger (and others) - how would you feel about splitting the parameters then? * `scale`: **must** be unitless (or convertible to true unitless), perhaps with backwards compatibility support for SLAM and SNU units that get stripped and interpreted as `output_units`. I think this can then be used in both `evaluate` and `bolometric_flux`. * `solid_angle` (or similar name): which is only required when wanting the `evaluate` method to output in flux units. If provided, you must also set a compatible unit for `output_units`. * `output_units` (or similar name): choose whether `evaluate` will output SNU (default as it is now), SLAM, FNU, or FLAM units (with compatibility checks for the other arguments: you can't set this to SLAM or SNU and pass `solid_angle`, for example). The downside here is that in the flux case, fitting both `scale` and `solid_angle` will be entirely degenerate, so one of the two will likely need to be held fixed. In some use-cases where you don't care about how much of the scale belongs to which units, it might be convenient to just leave one fixed at unity and let the other absorb the full scale factor. But the upside is that I _think_ this approach might get around the ambiguity cases you brought up? A delta on @kecnry's suggestion to make it a bit less confusing to the user (maybe?) would be to have *3* classes, one that's just `BaseBlackbodyModel` with only the temperature (and no units), a `BlackbodyModel` that's what @kecnry suggeted just above, and a `FluxButNotDensityReallyIMeanItBlackbodyModel` (ok, maybe a different name is needed there) which has the originally posed `scale` but not `solid_angle`. My motivation here is that I rarely actually want to think about solid angle at all if I can avoid it, but sometimes I have to. @eteq - I would be for that, but then `FluxButNotDensityReallyIMeanItBlackbodyModel` would likely have to raise an error if calling `bolometric_flux` or possibly could estimate through integration (over wavelength or frequency) instead. Yeah, I'm cool with that, as long as the exception message says something like "not sure why you're seeing this? Try using BlackbodyModel instead" If you end up with a few new classes, the user documentation needs some serious explaining, as I feel like this is going against "There should be one-- and preferably only one --obvious way to do it" ([PEP 20](https://www.python.org/dev/peps/pep-0020/)) a little... @eteq @pllim - it might be possible to achieve this same use-case (not having to worry about thinking about solid angle if you don't intend to make calls to `bolometric_flux`) in a single class by allowing `solid_angle = None` for the flux case and absorbing the steradians into the scale factor. That case would then need to raise an informative error for calls to `bolometric_flux` to avoid the ambiguity issue. The tradeoff I see is more complex argument validation logic and extended documentation in a single class rather than multiple classes for different use-cases. If no one thinks of any major drawbacks/concerns, I will take a stab at that implementation and come up with examples for each of the use-cases discussed so far and we can then reconsider if splitting into separate classes is warranted. Thanks for all the good ideas! Here are some proposed pseudo-code calls that I think could cover all the cases above with a single class including new optional `solid_angle` and `output_units` arguments. Please let me know if I've missed any cases or if any of these wouldn't act as you'd expect. As you can see, there are quite a few different scenarios, so this is likely to be a documentation and testing challenge - but I'm guessing any approach will have that same problem. Ultimately though it boils down to attempting to pull the units out of `scale` to avoid the ambiguous issues brought up here, while still allowing support for output and fitting in flux units (by supporting both separating the dimensionless scale from the solid angle to allow calling `bolometric_flux` and also by absorbing them together for the case of fitting a single scale factor and sacrificing the ability to call `bolometric_flux`). **SNU/SLAM units** `BlackBody(temperature, [scale (float or unitless)], output_units=(None, SNU, or SLAM))` * if `output_units` is not provided or `None`, defaults to `SNU` to match current behavior * unitless `scale` converted to unitless_unscaled (should address this *original* bug report) * returns in SNU/SLAM units * `bolometric_flux` uses unitless `scale` directly (matches current behavior) `BlackBody(temperature, scale (SNU or SLAM units))` * for **backwards compatibility** only * `output_units = scale.unit`, `scale = scale.value` * returns in SNU/SLAM units * `bolometric_flux`: we have two options here: (1) interpret this as a unitless `scale` with units being interpreted only for the sake of output units which matches current behavior (2) raise an error that `bolometric_flux` requires unitless `scale` to be passed (see [point 3 in the comment above](https://github.com/astropy/astropy/issues/11547#issuecomment-822667522)). `BlackBody(temperature, scale (with other units), output_units=(None, SNU, or SLAM))` * **ERROR**: `scale` cannot have units if `output_units` are SNU or SLAM (or non-SNU/SLAM units if `output_units` not provided or None) **FNU/FLAM units** `BlackBody(temperature, scale (float or unitless), solid_angle (u.sr), output_units=(FNU or FLAM))` * unitless `scale` converted to unitless_unscaled * returns in FNU/FLAM * `bolometric_flux` uses unitless `scale` directly (since separated from `solid_angle`) * fitting: either raise an error if both `scale` and `solid_angle` are left unfixed or just let it be degenerate? `BlackBody(temperature, scale (sr units), output_units=(FNU or FLAM))` * `scale = scale.value`, `solid_angle = 1.0*u.sr` and **automatically set to be kept fixed** during fitting * returns in FNU/FLAM * `bolometric_flux` => ERROR: must provide separate `scale` and `solid_angle` to call `bolometric_flux` (i.e. the previous case) `BlackBody(temperature, scale (FNU or FLAM units))` * to match **backwards compatibility** case for SNU/SLAM * `output_units = scale.unit`, `scale = scale.value`, `solid_angle = 1.0*u.sr` and **automatically set to be kept fixed** during fitting * returns in FNU/FLAM units * `bolometric_flux` => ERROR: same as above, must provide separate `scale` and `solid_angle`. `BlackBody(temperature, scale (float, unitless, or non sr units), output_units=(FNU or FLAM))` * **ERROR**: FNU/FLAM requires scale to have FNU/FLAM/sr units OR unitless with solid_angle provided (any of the cases above) Upon further reflection, I think that we are twisting ourselves into a knot by treating the black body as a special case when it comes to this pesky factor of pi. It's not. The factor of pi comes up any time that you need to convert from specific intensity (S_nu a.k.a. B_nu [erg cm^-2 s^-1 Hz^-1 sr^-1]) to flux density (F_nu [erg cm^-2 s^-1 Hz^-1]) assuming that your emitting surface element radiates isotropically. It's just the integral of cos(theta) from theta=0 to pi/2. BlackBody only looks like a special case among the astropy models because there are no other physical radiation models. If we declared a constant specific intensity source model class, then we would be having the same argument about whether we need to have a dual flux density class with an added factor of pi. What we commonly call Planck's law is B_nu. In order to avoid confusing users who are expecting the class to use the textbook definition, the Astropy model should _not_ insert the factor of pi. Instead, I propose that we go back to for `astropy.modeling.models.BlackBody`: 1. `scale` may have units of dimensionless_unscaled or solid angle, and in either case simply multiplies the output, or 2. has no scale parameter. In both cases, support for scale in FNU/FLAM/SNU/SLAM is deprecated because it cannot be implemented correctly and unambiguously. And in both cases, synphot keeps its own BlackBody1D class (perhaps renamed to BlackBodyFlux1D to mirror ConstFlux1D) and it _does_ have the factor of pi added. BTW, I found this to be a nice refresher: https://www.cv.nrao.edu/~sransom/web/Ch2.html > synphot keeps its own BlackBody1D class (perhaps renamed to BlackBodyFlux1D to mirror ConstFlux1D) `synphot` never used the new blackbody stuff here, so I think it can be safely left out of the changes here. If you feel strongly about its model names, feel free to open issue at https://github.com/spacetelescope/synphot_refactor/issues but I don't think it will affect anything at `astropy` or vice versa. 😅 @lpsinger - good points. I agree that this situation isn't fundamentally unique to BlackBody, and on further thought along those lines, can't think of any practical reason not to abstract away the `solid_angle` entirely from my use-cases above (as it should probably always either be N/A or pi - allowing it to possibly be fitted or set incorrectly just asks for problems). I have gone back and forth with myself about your point for *not* adding support for including the pi automatically, but as long as the default behavior remains the "pure" B_nu form, I think there are significant practical advantages for supporting more flexibility. The more this conversation continues, the more convinced I am that `scale` is indeed useful, but that we should move towards forcing it to be unitless to avoid a lot of these confusing scenarios. I'm worried that allowing `scale` to have steradians as units will cause more confusion (although I appreciate the simplicity of just multiplying the result). So... my (current) vote would be to still implement a separate `output_units` argument to make sure any change in units (and/or inclusion of pi) is explicitly clear and to take over the role of differentiating between specific intensity and flux density (by eventually requiring `scale` to be unitless and always handling the pi internally if requesting in flux units). Assuming we can't remove support for units in `scale` this release without warning, that leaves us with the following: * `BlackBody(temperature, [scale (float or unitless)], output_units=(None, SNU, or SLAM))` * temporary support for `BlackBody(temperature, scale (SNU or SLAM units))`: this is the current supported syntax that we want to deprecate. In the meantime, we would split the `scale` quantity into `scale` (unitless) and `output_units`. I think this still might be a bit confusing for the `bolometric_flux` case, so we may want to raise an error/warning there? * `BlackBody(temperature, [scale (float or unitless)], output_units=(FNU or FLAM))`: since scale is unitless, it is assumed *not* to include the pi, the returned value is multiplied by `scale*pi` internally and with requested units. * temporary support for `BlackBody(temperature, scale (FNU, FLAM))`: here `scale` includes units of solid angle, so internally we would set `scale = scale.value/pi` and then use the above treatment to multiply by `scale*pi`. Note that this does mean the these last two cases behave a little differently for passing the same "number" to `scale`, as without units it assumes to not include the pi, but will assume to include the pi if passed as a quantity. Definitely not ideal - I suppose we don't need to add support for this case since it wasn't supported in the past. But if we do, we may again want to raise an error/warning when calling `bolometric_flux`? If we don't like the `output_units` argument, this could be done instead with `BlackBody` vs `BlackBodyFlux` model (similar to @eteq's suggestion earlier), still deprecate passing units to scale as described above for both classes, and leave any unit conversion between *NU and *LAM to the user. Separate classes may be slightly cleaner looking and help separate the documentation, while a single class with the `output_units` argument provides a little more convenience functionality. I think we should not include the factor of pi at all in the astropy model because it assumes not only that one is integrating over a solid angle, but that the temperature is uniform over the body. In general, that does not have to be the case, does it? Would we ruffle too many feathers if we deprecated `scale` altogether? > Would we ruffle too many feathers Can't be worse than the episode when we deprecated `clobber` in `io.fits`... 😅 No, not in general. But so long as we only support a single temperature, I think it's reasonable that that would assume uniform temperature. I think getting rid of `scale` entirely was @karllark's original suggestion, but then all of this logic is left to be done externally (likely by the user). My attempts to do so with the existing `Scale` or `Linear1D` models, [showed complications](https://github.com/astropy/astropy/issues/11547#issuecomment-949734738). Perhaps I was missing something there and there's a better way... or maybe we need to work on fixing underlying bugs or lack of flexibility in `Compound` models instead. I also agree with @eteq's [arguments that users would expect a scale](https://github.com/astropy/astropy/issues/11547#issuecomment-951154117) and that it might indeed ruffle some feathers. > No, not in general. But so long as we only support a single temperature, I think it's reasonable that that would assume uniform temperature. It may be fair to assume a uniform temperature, but the factor of pi is also kind of assuming that the emitting surface is a sphere, isn't it? > I think getting rid of `scale` entirely was @karllark's original suggestion, but then all of this logic is left to be done externally (likely by the user). My attempts to do so with the existing `Scale` or `Linear1D` models, [showed complications](https://github.com/astropy/astropy/issues/11547#issuecomment-949734738). Perhaps I was missing something there and there's a better way... or maybe we need to work on fixing underlying bugs or lack of flexibility in `Compound` models instead. I also agree with @eteq's [arguments that users would expect a scale](https://github.com/astropy/astropy/issues/11547#issuecomment-951154117) and that it might indeed ruffle some feathers. I see. In that case, it seems that we are converging toward retaining the `scale` attribute but deprecating any but dimensionless units for it. Is that an accurate statement? If so, then I can whip up a PR. Yes, most likely a sphere, or at least anything where the solid angle is pi. But I agree that adding the generality for any solid angle will probably never be used and just adds unnecessary complication. I think that's the best approach for now (deprecating unit support in `scale` but supporting flux units) and then if in the future we want to completely remove `scale`, that is an option as long as external scaling can pick up the slack. I already started on testing some implementations, so am happy to put together the PR (and will tag you so you can look at it and comment before any decision is made). > I think that's the best approach for now (deprecating unit support in `scale` but supporting flux units) and then if in the future we want to completely remove `scale`, that is an option as long as external scaling can pick up the slack. I already started on testing some implementations, so am happy to put together the PR (and will tag you so you can look at it and comment before any decision is made). Go for it.
2021-10-28T15:32:17Z
<patch> diff --git a/astropy/modeling/physical_models.py b/astropy/modeling/physical_models.py --- a/astropy/modeling/physical_models.py +++ b/astropy/modeling/physical_models.py @@ -27,7 +27,12 @@ class BlackBody(Fittable1DModel): Blackbody temperature. scale : float or `~astropy.units.Quantity` ['dimensionless'] - Scale factor + Scale factor. If dimensionless, input units will assumed + to be in Hz and output units in (erg / (cm ** 2 * s * Hz * sr). + If not dimensionless, must be equivalent to either + (erg / (cm ** 2 * s * Hz * sr) or erg / (cm ** 2 * s * AA * sr), + in which case the result will be returned in the requested units and + the scale will be stripped of units (with the float value applied). Notes ----- @@ -70,12 +75,40 @@ class BlackBody(Fittable1DModel): scale = Parameter(default=1.0, min=0, description="Scale factor") # We allow values without units to be passed when evaluating the model, and - # in this case the input x values are assumed to be frequencies in Hz. + # in this case the input x values are assumed to be frequencies in Hz or wavelengths + # in AA (depending on the choice of output units controlled by units on scale + # and stored in self._output_units during init). _input_units_allow_dimensionless = True # We enable the spectral equivalency by default for the spectral axis input_units_equivalencies = {'x': u.spectral()} + # Store the native units returned by B_nu equation + _native_units = u.erg / (u.cm ** 2 * u.s * u.Hz * u.sr) + + # Store the base native output units. If scale is not dimensionless, it + # must be equivalent to one of these. If equivalent to SLAM, then + # input_units will expect AA for 'x', otherwise Hz. + _native_output_units = {'SNU': u.erg / (u.cm ** 2 * u.s * u.Hz * u.sr), + 'SLAM': u.erg / (u.cm ** 2 * u.s * u.AA * u.sr)} + + def __init__(self, *args, **kwargs): + scale = kwargs.get('scale', None) + + # Support scale with non-dimensionless unit by stripping the unit and + # storing as self._output_units. + if hasattr(scale, 'unit') and not scale.unit.is_equivalent(u.dimensionless_unscaled): + output_units = scale.unit + if not output_units.is_equivalent(self._native_units, u.spectral_density(1*u.AA)): + raise ValueError(f"scale units not dimensionless or in surface brightness: {output_units}") + + kwargs['scale'] = scale.value + self._output_units = output_units + else: + self._output_units = self._native_units + + return super().__init__(*args, **kwargs) + def evaluate(self, x, temperature, scale): """Evaluate the model. @@ -83,7 +116,8 @@ def evaluate(self, x, temperature, scale): ---------- x : float, `~numpy.ndarray`, or `~astropy.units.Quantity` ['frequency'] Frequency at which to compute the blackbody. If no units are given, - this defaults to Hz. + this defaults to Hz (or AA if `scale` was initialized with units + equivalent to erg / (cm ** 2 * s * AA * sr)). temperature : float, `~numpy.ndarray`, or `~astropy.units.Quantity` Temperature of the blackbody. If no units are given, this defaults @@ -119,30 +153,18 @@ def evaluate(self, x, temperature, scale): else: in_temp = temperature + if not isinstance(x, u.Quantity): + # then we assume it has input_units which depends on the + # requested output units (either Hz or AA) + in_x = u.Quantity(x, self.input_units['x']) + else: + in_x = x + # Convert to units for calculations, also force double precision with u.add_enabled_equivalencies(u.spectral() + u.temperature()): - freq = u.Quantity(x, u.Hz, dtype=np.float64) + freq = u.Quantity(in_x, u.Hz, dtype=np.float64) temp = u.Quantity(in_temp, u.K) - # check the units of scale and setup the output units - bb_unit = u.erg / (u.cm ** 2 * u.s * u.Hz * u.sr) # default unit - # use the scale that was used at initialization for determining the units to return - # to support returning the right units when fitting where units are stripped - if hasattr(self.scale, "unit") and self.scale.unit is not None: - # check that the units on scale are covertable to surface brightness units - if not self.scale.unit.is_equivalent(bb_unit, u.spectral_density(x)): - raise ValueError( - f"scale units not surface brightness: {self.scale.unit}" - ) - # use the scale passed to get the value for scaling - if hasattr(scale, "unit"): - mult_scale = scale.value - else: - mult_scale = scale - bb_unit = self.scale.unit - else: - mult_scale = scale - # Check if input values are physically possible if np.any(temp < 0): raise ValueError(f"Temperature should be positive: {temp}") @@ -158,7 +180,17 @@ def evaluate(self, x, temperature, scale): # Calculate blackbody flux bb_nu = 2.0 * const.h * freq ** 3 / (const.c ** 2 * boltzm1) / u.sr - y = mult_scale * bb_nu.to(bb_unit, u.spectral_density(freq)) + if self.scale.unit is not None: + # Will be dimensionless at this point, but may not be dimensionless_unscaled + if not hasattr(scale, 'unit'): + # during fitting, scale will be passed without units + # but we still need to convert from the input dimensionless + # to dimensionless unscaled + scale = scale * self.scale.unit + scale = scale.to(u.dimensionless_unscaled).value + + # NOTE: scale is already stripped of any input units + y = scale * bb_nu.to(self._output_units, u.spectral_density(freq)) # If the temperature parameter has no unit, we should return a unitless # value. This occurs for instance during fitting, since we drop the @@ -169,10 +201,13 @@ def evaluate(self, x, temperature, scale): @property def input_units(self): - # The input units are those of the 'x' value, which should always be - # Hz. Because we do this, and because input_units_allow_dimensionless - # is set to True, dimensionless values are assumed to be in Hz. - return {self.inputs[0]: u.Hz} + # The input units are those of the 'x' value, which will depend on the + # units compatible with the expected output units. + if self._output_units.is_equivalent(self._native_output_units['SNU']): + return {self.inputs[0]: u.Hz} + else: + # only other option is equivalent with SLAM + return {self.inputs[0]: u.AA} def _parameter_units_for_data_units(self, inputs_unit, outputs_unit): return {"temperature": u.K} @@ -180,9 +215,15 @@ def _parameter_units_for_data_units(self, inputs_unit, outputs_unit): @property def bolometric_flux(self): """Bolometric flux.""" + if self.scale.unit is not None: + # Will be dimensionless at this point, but may not be dimensionless_unscaled + scale = self.scale.quantity.to(u.dimensionless_unscaled) + else: + scale = self.scale.value + # bolometric flux in the native units of the planck function native_bolflux = ( - self.scale.value * const.sigma_sb * self.temperature ** 4 / np.pi + scale * const.sigma_sb * self.temperature ** 4 / np.pi ) # return in more "astro" units return native_bolflux.to(u.erg / (u.cm ** 2 * u.s)) </patch>
diff --git a/astropy/modeling/tests/test_physical_models.py b/astropy/modeling/tests/test_physical_models.py --- a/astropy/modeling/tests/test_physical_models.py +++ b/astropy/modeling/tests/test_physical_models.py @@ -40,6 +40,17 @@ def test_blackbody_sefanboltzman_law(): assert_quantity_allclose(b.bolometric_flux, 133.02471751812573 * u.W / (u.m * u.m)) +def test_blackbody_input_units(): + SLAM = u.erg / (u.cm ** 2 * u.s * u.AA * u.sr) + SNU = u.erg / (u.cm ** 2 * u.s * u.Hz * u.sr) + + b_lam = BlackBody(3000*u.K, scale=1*SLAM) + assert(b_lam.input_units['x'] == u.AA) + + b_nu = BlackBody(3000*u.K, scale=1*SNU) + assert(b_nu.input_units['x'] == u.Hz) + + def test_blackbody_return_units(): # return of evaluate has no units when temperature has no units b = BlackBody(1000.0 * u.K, scale=1.0) @@ -72,7 +83,7 @@ def test_blackbody_fit(): b_fit = fitter(b, wav, fnu, maxiter=1000) assert_quantity_allclose(b_fit.temperature, 2840.7438355865065 * u.K) - assert_quantity_allclose(b_fit.scale, 5.803783292762381e-17 * u.Jy / u.sr) + assert_quantity_allclose(b_fit.scale, 5.803783292762381e-17) def test_blackbody_overflow(): @@ -104,10 +115,11 @@ def test_blackbody_exceptions_and_warnings(): """Test exceptions.""" # Negative temperature - with pytest.raises(ValueError) as exc: + with pytest.raises( + ValueError, + match="Temperature should be positive: \\[-100.\\] K"): bb = BlackBody(-100 * u.K) bb(1.0 * u.micron) - assert exc.value.args[0] == "Temperature should be positive: [-100.] K" bb = BlackBody(5000 * u.K) @@ -121,11 +133,11 @@ def test_blackbody_exceptions_and_warnings(): bb(-1.0 * u.AA) assert len(w) == 1 - # Test that a non surface brightness converatable scale unit - with pytest.raises(ValueError) as exc: + # Test that a non surface brightness convertible scale unit raises an error + with pytest.raises( + ValueError, + match="scale units not dimensionless or in surface brightness: Jy"): bb = BlackBody(5000 * u.K, scale=1.0 * u.Jy) - bb(1.0 * u.micron) - assert exc.value.args[0] == "scale units not surface brightness: Jy" def test_blackbody_array_temperature(): @@ -146,6 +158,45 @@ def test_blackbody_array_temperature(): assert flux.shape == (3, 4) +def test_blackbody_dimensionless(): + """Test support for dimensionless (but not unscaled) units for scale""" + T = 3000 * u.K + r = 1e14 * u.cm + DL = 100 * u.Mpc + scale = np.pi * (r / DL)**2 + + bb1 = BlackBody(temperature=T, scale=scale) + # even though we passed scale with units, we should be able to evaluate with unitless + bb1.evaluate(0.5, T.value, scale.to_value(u.dimensionless_unscaled)) + + bb2 = BlackBody(temperature=T, scale=scale.to_value(u.dimensionless_unscaled)) + bb2.evaluate(0.5, T.value, scale.to_value(u.dimensionless_unscaled)) + + # bolometric flux for both cases should be equivalent + assert(bb1.bolometric_flux == bb2.bolometric_flux) + + +@pytest.mark.skipif("not HAS_SCIPY") +def test_blackbody_dimensionless_fit(): + T = 3000 * u.K + r = 1e14 * u.cm + DL = 100 * u.Mpc + scale = np.pi * (r / DL)**2 + + bb1 = BlackBody(temperature=T, scale=scale) + bb2 = BlackBody(temperature=T, scale=scale.to_value(u.dimensionless_unscaled)) + + fitter = LevMarLSQFitter() + + wav = np.array([0.5, 5, 10]) * u.micron + fnu = np.array([1, 10, 5]) * u.Jy / u.sr + + bb1_fit = fitter(bb1, wav, fnu, maxiter=1000) + bb2_fit = fitter(bb2, wav, fnu, maxiter=1000) + + assert(bb1_fit.temperature == bb2_fit.temperature) + + @pytest.mark.parametrize("mass", (2.0000000000000E15 * u.M_sun, 3.976819741e+45 * u.kg)) def test_NFW_evaluate(mass): """Evaluation, density, and radii validation of NFW model."""
4.3
["astropy/modeling/tests/test_physical_models.py::test_blackbody_input_units", "astropy/modeling/tests/test_physical_models.py::test_blackbody_exceptions_and_warnings", "astropy/modeling/tests/test_physical_models.py::test_blackbody_dimensionless"]
["astropy/modeling/tests/test_physical_models.py::test_blackbody_evaluate[temperature0]", "astropy/modeling/tests/test_physical_models.py::test_blackbody_evaluate[temperature1]", "astropy/modeling/tests/test_physical_models.py::test_blackbody_weins_law", "astropy/modeling/tests/test_physical_models.py::test_blackbody_sefanboltzman_law", "astropy/modeling/tests/test_physical_models.py::test_blackbody_return_units", "astropy/modeling/tests/test_physical_models.py::test_blackbody_overflow", "astropy/modeling/tests/test_physical_models.py::test_blackbody_array_temperature", "astropy/modeling/tests/test_physical_models.py::test_NFW_evaluate[mass0]", "astropy/modeling/tests/test_physical_models.py::test_NFW_evaluate[mass1]", "astropy/modeling/tests/test_physical_models.py::test_NFW_circular_velocity", "astropy/modeling/tests/test_physical_models.py::test_NFW_exceptions_and_warnings_and_misc"]
298ccb478e6bf092953bca67a3d29dc6c35f6752
astropy__astropy-12825
You will be provided with a partial code base and an issue statement explaining a problem to resolve. <issue> SkyCoord in Table breaks aggregate on group_by ### Description, actual behaviour, reproduction When putting a column of `SkyCoord`s in a `Table`, `aggregate` does not work on `group_by().groups`: ```python from astropy.table import Table import astropy.units as u from astropy.coordinates import SkyCoord import numpy as np ras = [10, 20] * u.deg decs = [32, -2] * u.deg str_col = ['foo', 'bar'] coords = SkyCoord(ra=ras, dec=decs) table = Table([str_col, coords], names=['col1', 'col2']) table.group_by('col1').groups.aggregate(np.mean) ``` fails with ``` Traceback (most recent call last): File "repro.py", line 13, in <module> table.group_by('col1').groups.aggregate(np.mean) File "astropy/table/groups.py", line 357, in aggregate new_col = col.groups.aggregate(func) File "astropy/coordinates/sky_coordinate.py", line 835, in __getattr__ raise AttributeError("'{}' object has no attribute '{}'" AttributeError: 'SkyCoord' object has no attribute 'groups' ``` This happens irregardless of the aggregation function. ### Expected behavior Aggregation works, only fails to aggregate columns where operation does not make sense. ### System Details ``` Linux-5.14.11-arch1-1-x86_64-with-glibc2.33 Python 3.9.7 (default, Aug 31 2021, 13:28:12) [GCC 11.1.0] Numpy 1.21.2 astropy 5.0.dev945+g7dfa1edb2 (no scipy or matplotlib) ``` and ``` Linux-5.14.11-arch1-1-x86_64-with-glibc2.33 Python 3.9.7 (default, Aug 31 2021, 13:28:12) [GCC 11.1.0] Numpy 1.21.2 astropy 4.3.1 Scipy 1.7.1 Matplotlib 3.4.3 ``` </issue> <code> [start of README.rst] 1 ======= 2 Astropy 3 ======= 4 5 |Actions Status| |CircleCI Status| |Azure Status| |Coverage Status| |PyPI Status| |Documentation Status| |Zenodo| 6 7 The Astropy Project (http://astropy.org/) is a community effort to develop a 8 single core package for Astronomy in Python and foster interoperability between 9 Python astronomy packages. This repository contains the core package which is 10 intended to contain much of the core functionality and some common tools needed 11 for performing astronomy and astrophysics with Python. 12 13 Releases are `registered on PyPI <https://pypi.org/project/astropy>`_, 14 and development is occurring at the 15 `project's GitHub page <http://github.com/astropy/astropy>`_. 16 17 For installation instructions, see the `online documentation <https://docs.astropy.org/>`_ 18 or `docs/install.rst <docs/install.rst>`_ in this source distribution. 19 20 Contributing Code, Documentation, or Feedback 21 --------------------------------------------- 22 23 The Astropy Project is made both by and for its users, so we welcome and 24 encourage contributions of many kinds. Our goal is to keep this a positive, 25 inclusive, successful, and growing community by abiding with the 26 `Astropy Community Code of Conduct <http://www.astropy.org/about.html#codeofconduct>`_. 27 28 More detailed information on contributing to the project or submitting feedback 29 can be found on the `contributions <http://www.astropy.org/contribute.html>`_ 30 page. A `summary of contribution guidelines <CONTRIBUTING.md>`_ can also be 31 used as a quick reference when you are ready to start writing or validating 32 code for submission. 33 34 Supporting the Project 35 ---------------------- 36 37 |NumFOCUS| |Donate| 38 39 The Astropy Project is sponsored by NumFOCUS, a 501(c)(3) nonprofit in the 40 United States. You can donate to the project by using the link above, and this 41 donation will support our mission to promote sustainable, high-level code base 42 for the astronomy community, open code development, educational materials, and 43 reproducible scientific research. 44 45 License 46 ------- 47 48 Astropy is licensed under a 3-clause BSD style license - see the 49 `LICENSE.rst <LICENSE.rst>`_ file. 50 51 .. |Actions Status| image:: https://github.com/astropy/astropy/workflows/CI/badge.svg 52 :target: https://github.com/astropy/astropy/actions 53 :alt: Astropy's GitHub Actions CI Status 54 55 .. |CircleCI Status| image:: https://img.shields.io/circleci/build/github/astropy/astropy/main?logo=circleci&label=CircleCI 56 :target: https://circleci.com/gh/astropy/astropy 57 :alt: Astropy's CircleCI Status 58 59 .. |Azure Status| image:: https://dev.azure.com/astropy-project/astropy/_apis/build/status/astropy.astropy?repoName=astropy%2Fastropy&branchName=main 60 :target: https://dev.azure.com/astropy-project/astropy 61 :alt: Astropy's Azure Pipelines Status 62 63 .. |Coverage Status| image:: https://codecov.io/gh/astropy/astropy/branch/main/graph/badge.svg 64 :target: https://codecov.io/gh/astropy/astropy 65 :alt: Astropy's Coverage Status 66 67 .. |PyPI Status| image:: https://img.shields.io/pypi/v/astropy.svg 68 :target: https://pypi.org/project/astropy 69 :alt: Astropy's PyPI Status 70 71 .. |Zenodo| image:: https://zenodo.org/badge/DOI/10.5281/zenodo.4670728.svg 72 :target: https://doi.org/10.5281/zenodo.4670728 73 :alt: Zenodo DOI 74 75 .. |Documentation Status| image:: https://img.shields.io/readthedocs/astropy/latest.svg?logo=read%20the%20docs&logoColor=white&label=Docs&version=stable 76 :target: https://docs.astropy.org/en/stable/?badge=stable 77 :alt: Documentation Status 78 79 .. |NumFOCUS| image:: https://img.shields.io/badge/powered%20by-NumFOCUS-orange.svg?style=flat&colorA=E1523D&colorB=007D8A 80 :target: http://numfocus.org 81 :alt: Powered by NumFOCUS 82 83 .. |Donate| image:: https://img.shields.io/badge/Donate-to%20Astropy-brightgreen.svg 84 :target: https://numfocus.salsalabs.org/donate-to-astropy/index.html 85 86 87 If you locally cloned this repo before 7 Apr 2021 88 ------------------------------------------------- 89 90 The primary branch for this repo has been transitioned from ``master`` to 91 ``main``. If you have a local clone of this repository and want to keep your 92 local branch in sync with this repo, you'll need to do the following in your 93 local clone from your terminal:: 94 95 git fetch --all --prune 96 # you can stop here if you don't use your local "master"/"main" branch 97 git branch -m master main 98 git branch -u origin/main main 99 100 If you are using a GUI to manage your repos you'll have to find the equivalent 101 commands as it's different for different programs. Alternatively, you can just 102 delete your local clone and re-clone! 103 [end of README.rst] [start of astropy/io/ascii/mrt.py] 1 # Licensed under a 3-clause BSD style license - see LICENSE.rst 2 """Classes to read AAS MRT table format 3 4 Ref: https://journals.aas.org/mrt-standards 5 6 :Copyright: Smithsonian Astrophysical Observatory (2021) 7 :Author: Tom Aldcroft (aldcroft@head.cfa.harvard.edu), \ 8 Suyog Garg (suyog7130@gmail.com) 9 """ 10 11 import re 12 import math 13 import warnings 14 import numpy as np 15 from io import StringIO 16 17 from . import core 18 from . import fixedwidth, cds 19 20 from astropy import units as u 21 22 from astropy.table import Table 23 from astropy.table import Column, MaskedColumn 24 from string import Template 25 from textwrap import wrap 26 27 MAX_SIZE_README_LINE = 80 28 MAX_COL_INTLIMIT = 100000 29 30 31 __doctest_skip__ = ['*'] 32 33 34 BYTE_BY_BYTE_TEMPLATE = [ 35 "Byte-by-byte Description of file: $file", 36 "--------------------------------------------------------------------------------", 37 " Bytes Format Units Label Explanations", 38 "--------------------------------------------------------------------------------", 39 "$bytebybyte", 40 "--------------------------------------------------------------------------------"] 41 42 MRT_TEMPLATE = [ 43 "Title:", 44 "Authors:", 45 "Table:", 46 "================================================================================", 47 "$bytebybyte", 48 "Notes:", 49 "--------------------------------------------------------------------------------"] 50 51 52 class MrtSplitter(fixedwidth.FixedWidthSplitter): 53 """ 54 Contains the join function to left align the MRT columns 55 when writing to a file. 56 """ 57 def join(self, vals, widths): 58 vals = [val + ' ' * (width - len(val)) for val, width in zip(vals, widths)] 59 return self.delimiter.join(vals) 60 61 62 class MrtHeader(cds.CdsHeader): 63 _subfmt = 'MRT' 64 65 def _split_float_format(self, value): 66 """ 67 Splits a Float string into different parts to find number 68 of digits after decimal and check if the value is in Scientific 69 notation. 70 71 Parameters 72 ---------- 73 value : str 74 String containing the float value to split. 75 76 Returns 77 ------- 78 fmt: (int, int, int, bool, bool) 79 List of values describing the Float sting. 80 (size, dec, ent, sign, exp) 81 size, length of the given string. 82 ent, number of digits before decimal point. 83 dec, number of digits after decimal point. 84 sign, whether or not given value signed. 85 exp, is value in Scientific notation? 86 """ 87 regfloat = re.compile(r"""(?P<sign> [+-]*) 88 (?P<ent> [^eE.]+) 89 (?P<deciPt> [.]*) 90 (?P<decimals> [0-9]*) 91 (?P<exp> [eE]*-*)[0-9]*""", 92 re.VERBOSE) 93 mo = regfloat.match(value) 94 95 if mo is None: 96 raise Exception(f'{value} is not a float number') 97 return (len(value), 98 len(mo.group('ent')), 99 len(mo.group('decimals')), 100 mo.group('sign') != "", 101 mo.group('exp') != "") 102 103 def _set_column_val_limits(self, col): 104 """ 105 Sets the ``col.min`` and ``col.max`` column attributes, 106 taking into account columns with Null values. 107 """ 108 col.max = max(col) 109 col.min = min(col) 110 if col.max is np.ma.core.MaskedConstant: 111 col.max = None 112 if col.min is np.ma.core.MaskedConstant: 113 col.min = None 114 115 def column_float_formatter(self, col): 116 """ 117 String formatter function for a column containing Float values. 118 Checks if the values in the given column are in Scientific notation, 119 by spliting the value string. It is assumed that the column either has 120 float values or Scientific notation. 121 122 A ``col.formatted_width`` attribute is added to the column. It is not added 123 if such an attribute is already present, say when the ``formats`` argument 124 is passed to the writer. A properly formatted format string is also added as 125 the ``col.format`` attribute. 126 127 Parameters 128 ---------- 129 col : A ``Table.Column`` object. 130 """ 131 # maxsize: maximum length of string containing the float value. 132 # maxent: maximum number of digits places before decimal point. 133 # maxdec: maximum number of digits places after decimal point. 134 # maxprec: maximum precision of the column values, sum of maxent and maxdec. 135 maxsize, maxprec, maxent, maxdec = 1, 0, 1, 0 136 sign = False 137 fformat = 'F' 138 139 # Find maximum sized value in the col 140 for val in col.str_vals: 141 # Skip null values 142 if val is None or val == '': 143 continue 144 145 # Find format of the Float string 146 fmt = self._split_float_format(val) 147 # If value is in Scientific notation 148 if fmt[4] is True: 149 # if the previous column value was in normal Float format 150 # set maxsize, maxprec and maxdec to default. 151 if fformat == 'F': 152 maxsize, maxprec, maxdec = 1, 0, 0 153 # Designate the column to be in Scientific notation. 154 fformat = 'E' 155 else: 156 # Move to next column value if 157 # current value is not in Scientific notation 158 # but the column is designated as such because 159 # one of the previous values was. 160 if fformat == 'E': 161 continue 162 163 if maxsize < fmt[0]: 164 maxsize = fmt[0] 165 if maxent < fmt[1]: 166 maxent = fmt[1] 167 if maxdec < fmt[2]: 168 maxdec = fmt[2] 169 if fmt[3]: 170 sign = True 171 172 if maxprec < fmt[1] + fmt[2]: 173 maxprec = fmt[1] + fmt[2] 174 175 if fformat == 'E': 176 if getattr(col, 'formatted_width', None) is None: # If ``formats`` not passed. 177 col.formatted_width = maxsize 178 if sign: 179 col.formatted_width += 1 180 # Number of digits after decimal is replaced by the precision 181 # for values in Scientific notation, when writing that Format. 182 col.fortran_format = fformat + str(col.formatted_width) + "." + str(maxprec) 183 col.format = str(col.formatted_width) + "." + str(maxdec) + "e" 184 else: 185 lead = '' 186 if getattr(col, 'formatted_width', None) is None: # If ``formats`` not passed. 187 col.formatted_width = maxent + maxdec + 1 188 if sign: 189 col.formatted_width += 1 190 elif col.format.startswith('0'): 191 # Keep leading zero, if already set in format - primarily for `seconds` columns 192 # in coordinates; may need extra case if this is to be also supported with `sign`. 193 lead = '0' 194 col.fortran_format = fformat + str(col.formatted_width) + "." + str(maxdec) 195 col.format = lead + col.fortran_format[1:] + "f" 196 197 def write_byte_by_byte(self): 198 """ 199 Writes the Byte-By-Byte description of the table. 200 201 Columns that are `astropy.coordinates.SkyCoord` or `astropy.time.TimeSeries` 202 objects or columns with values that are such objects are recognized as such, 203 and some predefined labels and description is used for them. 204 See the Vizier MRT Standard documentation in the link below for more details 205 on these. An example Byte-By-Byte table is shown here. 206 207 See: http://vizier.u-strasbg.fr/doc/catstd-3.1.htx 208 209 Example:: 210 211 -------------------------------------------------------------------------------- 212 Byte-by-byte Description of file: table.dat 213 -------------------------------------------------------------------------------- 214 Bytes Format Units Label Explanations 215 -------------------------------------------------------------------------------- 216 1- 8 A8 --- names Description of names 217 10-14 E5.1 --- e [-3160000.0/0.01] Description of e 218 16-23 F8.5 --- d [22.25/27.25] Description of d 219 25-31 E7.1 --- s [-9e+34/2.0] Description of s 220 33-35 I3 --- i [-30/67] Description of i 221 37-39 F3.1 --- sameF [5.0/5.0] Description of sameF 222 41-42 I2 --- sameI [20] Description of sameI 223 44-45 I2 h RAh Right Ascension (hour) 224 47-48 I2 min RAm Right Ascension (minute) 225 50-67 F18.15 s RAs Right Ascension (second) 226 69 A1 --- DE- Sign of Declination 227 70-71 I2 deg DEd Declination (degree) 228 73-74 I2 arcmin DEm Declination (arcmin) 229 76-91 F16.13 arcsec DEs Declination (arcsec) 230 231 -------------------------------------------------------------------------------- 232 """ 233 # Get column widths 234 vals_list = [] 235 col_str_iters = self.data.str_vals() 236 for vals in zip(*col_str_iters): 237 vals_list.append(vals) 238 239 for i, col in enumerate(self.cols): 240 col.width = max([len(vals[i]) for vals in vals_list]) 241 if self.start_line is not None: 242 col.width = max(col.width, len(col.info.name)) 243 widths = [col.width for col in self.cols] 244 245 startb = 1 # Byte count starts at 1. 246 247 # Set default width of the Bytes count column of the Byte-By-Byte table. 248 # This ``byte_count_width`` value helps align byte counts with respect 249 # to the hyphen using a format string. 250 byte_count_width = len(str(sum(widths) + len(self.cols) - 1)) 251 252 # Format string for Start Byte and End Byte 253 singlebfmt = "{:" + str(byte_count_width) + "d}" 254 fmtb = singlebfmt + "-" + singlebfmt 255 # Add trailing single whitespaces to Bytes column for better visibility. 256 singlebfmt += " " 257 fmtb += " " 258 259 # Set default width of Label and Description Byte-By-Byte columns. 260 max_label_width, max_descrip_size = 7, 16 261 262 bbb = Table(names=['Bytes', 'Format', 'Units', 'Label', 'Explanations'], 263 dtype=[str] * 5) 264 265 # Iterate over the columns to write Byte-By-Byte rows. 266 for i, col in enumerate(self.cols): 267 # Check if column is MaskedColumn 268 col.has_null = isinstance(col, MaskedColumn) 269 270 if col.format is not None: 271 col.formatted_width = max([len(sval) for sval in col.str_vals]) 272 273 # Set MRTColumn type, size and format. 274 if np.issubdtype(col.dtype, np.integer): 275 # Integer formatter 276 self._set_column_val_limits(col) 277 if getattr(col, 'formatted_width', None) is None: # If ``formats`` not passed. 278 col.formatted_width = max(len(str(col.max)), len(str(col.min))) 279 col.fortran_format = "I" + str(col.formatted_width) 280 if col.format is None: 281 col.format = ">" + col.fortran_format[1:] 282 283 elif np.issubdtype(col.dtype, np.dtype(float).type): 284 # Float formatter 285 self._set_column_val_limits(col) 286 self.column_float_formatter(col) 287 288 else: 289 # String formatter, ``np.issubdtype(col.dtype, str)`` is ``True``. 290 dtype = col.dtype.str 291 if col.has_null: 292 mcol = col 293 mcol.fill_value = "" 294 coltmp = Column(mcol.filled(), dtype=str) 295 dtype = coltmp.dtype.str 296 if getattr(col, 'formatted_width', None) is None: # If ``formats`` not passed. 297 col.formatted_width = int(re.search(r'(\d+)$', dtype).group(1)) 298 col.fortran_format = "A" + str(col.formatted_width) 299 col.format = str(col.formatted_width) + "s" 300 301 endb = col.formatted_width + startb - 1 302 303 # ``mixin`` columns converted to string valued columns will not have a name 304 # attribute. In those cases, a ``Unknown`` column label is put, indicating that 305 # such columns can be better formatted with some manipulation before calling 306 # the MRT writer. 307 if col.name is None: 308 col.name = "Unknown" 309 310 # Set column description. 311 if col.description is not None: 312 description = col.description 313 else: 314 description = "Description of " + col.name 315 316 # Set null flag in column description 317 nullflag = "" 318 if col.has_null: 319 nullflag = "?" 320 321 # Set column unit 322 if col.unit is not None: 323 col_unit = col.unit.to_string("cds") 324 elif col.name.lower().find("magnitude") > -1: 325 # ``col.unit`` can still be ``None``, if the unit of column values 326 # is ``Magnitude``, because ``astropy.units.Magnitude`` is actually a class. 327 # Unlike other units which are instances of ``astropy.units.Unit``, 328 # application of the ``Magnitude`` unit calculates the logarithm 329 # of the values. Thus, the only way to check for if the column values 330 # have ``Magnitude`` unit is to check the column name. 331 col_unit = "mag" 332 else: 333 col_unit = "---" 334 335 # Add col limit values to col description 336 lim_vals = "" 337 if (col.min and col.max and 338 not any(x in col.name for x in ['RA', 'DE', 'LON', 'LAT', 'PLN', 'PLT'])): 339 # No col limit values for coordinate columns. 340 if col.fortran_format[0] == 'I': 341 if abs(col.min) < MAX_COL_INTLIMIT and abs(col.max) < MAX_COL_INTLIMIT: 342 if col.min == col.max: 343 lim_vals = "[{0}]".format(col.min) 344 else: 345 lim_vals = "[{0}/{1}]".format(col.min, col.max) 346 elif col.fortran_format[0] in ('E', 'F'): 347 lim_vals = "[{0}/{1}]".format(math.floor(col.min * 100) / 100., 348 math.ceil(col.max * 100) / 100.) 349 350 if lim_vals != '' or nullflag != '': 351 description = "{0}{1} {2}".format(lim_vals, nullflag, description) 352 353 # Find the maximum label and description column widths. 354 if len(col.name) > max_label_width: 355 max_label_width = len(col.name) 356 if len(description) > max_descrip_size: 357 max_descrip_size = len(description) 358 359 # Add a row for the Sign of Declination in the bbb table 360 if col.name == 'DEd': 361 bbb.add_row([singlebfmt.format(startb), 362 "A1", "---", "DE-", 363 "Sign of Declination"]) 364 col.fortran_format = 'I2' 365 startb += 1 366 367 # Add Byte-By-Byte row to bbb table 368 bbb.add_row([singlebfmt.format(startb) if startb == endb 369 else fmtb.format(startb, endb), 370 "" if col.fortran_format is None else col.fortran_format, 371 col_unit, 372 "" if col.name is None else col.name, 373 description]) 374 startb = endb + 2 375 376 # Properly format bbb columns 377 bbblines = StringIO() 378 bbb.write(bbblines, format='ascii.fixed_width_no_header', 379 delimiter=' ', bookend=False, delimiter_pad=None, 380 formats={'Format': '<6s', 381 'Units': '<6s', 382 'Label': '<' + str(max_label_width) + 's', 383 'Explanations': '' + str(max_descrip_size) + 's'}) 384 385 # Get formatted bbb lines 386 bbblines = bbblines.getvalue().splitlines() 387 388 # ``nsplit`` is the number of whitespaces to prefix to long description 389 # lines in order to wrap them. It is the sum of the widths of the 390 # previous 4 columns plus the number of single spacing between them. 391 # The hyphen in the Bytes column is also counted. 392 nsplit = byte_count_width * 2 + 1 + 12 + max_label_width + 4 393 394 # Wrap line if it is too long 395 buff = "" 396 for newline in bbblines: 397 if len(newline) > MAX_SIZE_README_LINE: 398 buff += ("\n").join(wrap(newline, 399 subsequent_indent=" " * nsplit, 400 width=MAX_SIZE_README_LINE)) 401 buff += "\n" 402 else: 403 buff += newline + "\n" 404 405 # Last value of ``endb`` is the sum of column widths after formatting. 406 self.linewidth = endb 407 408 # Remove the last extra newline character from Byte-By-Byte. 409 buff = buff[:-1] 410 return buff 411 412 def write(self, lines): 413 """ 414 Writes the Header of the MRT table, aka ReadMe, which 415 also contains the Byte-By-Byte description of the table. 416 """ 417 from astropy.coordinates import SkyCoord 418 419 # Recognised ``SkyCoord.name`` forms with their default column names (helio* require SunPy). 420 coord_systems = {'galactic': ('GLAT', 'GLON', 'b', 'l'), 421 'ecliptic': ('ELAT', 'ELON', 'lat', 'lon'), # 'geocentric*ecliptic' 422 'heliographic': ('HLAT', 'HLON', 'lat', 'lon'), # '_carrington|stonyhurst' 423 'helioprojective': ('HPLT', 'HPLN', 'Ty', 'Tx')} 424 eqtnames = ['RAh', 'RAm', 'RAs', 'DEd', 'DEm', 'DEs'] 425 426 # list to store indices of columns that are modified. 427 to_pop = [] 428 429 # For columns that are instances of ``SkyCoord`` and other ``mixin`` columns 430 # or whose values are objects of these classes. 431 for i, col in enumerate(self.cols): 432 # If col is a ``Column`` object but its values are ``SkyCoord`` objects, 433 # convert the whole column to ``SkyCoord`` object, which helps in applying 434 # SkyCoord methods directly. 435 if not isinstance(col, SkyCoord) and isinstance(col[0], SkyCoord): 436 try: 437 col = SkyCoord(col) 438 except (ValueError, TypeError): 439 # If only the first value of the column is a ``SkyCoord`` object, 440 # the column cannot be converted to a ``SkyCoord`` object. 441 # These columns are converted to ``Column`` object and then converted 442 # to string valued column. 443 if not isinstance(col, Column): 444 col = Column(col) 445 col = Column([str(val) for val in col]) 446 self.cols[i] = col 447 continue 448 449 # Replace single ``SkyCoord`` column by its coordinate components if no coordinate 450 # columns of the correspoding type exist yet. 451 if isinstance(col, SkyCoord): 452 # If coordinates are given in RA/DEC, divide each them into hour/deg, 453 # minute/arcminute, second/arcsecond columns. 454 if ('ra' in col.representation_component_names.keys() and 455 len(set(eqtnames) - set(self.colnames)) == 6): 456 ra_c, dec_c = col.ra.hms, col.dec.dms 457 coords = [ra_c.h.round().astype('i1'), ra_c.m.round().astype('i1'), ra_c.s, 458 dec_c.d.round().astype('i1'), dec_c.m.round().astype('i1'), dec_c.s] 459 coord_units = [u.h, u.min, u.second, 460 u.deg, u.arcmin, u.arcsec] 461 coord_descrip = ['Right Ascension (hour)', 'Right Ascension (minute)', 462 'Right Ascension (second)', 'Declination (degree)', 463 'Declination (arcmin)', 'Declination (arcsec)'] 464 for coord, name, coord_unit, descrip in zip( 465 coords, eqtnames, coord_units, coord_descrip): 466 # Have Sign of Declination only in the DEd column. 467 if name in ['DEm', 'DEs']: 468 coord_col = Column(list(np.abs(coord)), name=name, 469 unit=coord_unit, description=descrip) 470 else: 471 coord_col = Column(list(coord), name=name, unit=coord_unit, 472 description=descrip) 473 # Set default number of digits after decimal point for the 474 # second values, and deg-min to (signed) 2-digit zero-padded integer. 475 if name == 'RAs': 476 coord_col.format = '013.10f' 477 elif name == 'DEs': 478 coord_col.format = '012.9f' 479 elif name == 'RAh': 480 coord_col.format = '2d' 481 elif name == 'DEd': 482 coord_col.format = '+03d' 483 elif name.startswith(('RA', 'DE')): 484 coord_col.format = '02d' 485 self.cols.append(coord_col) 486 to_pop.append(i) # Delete original ``SkyCoord`` column. 487 488 # For all other coordinate types, simply divide into two columns 489 # for latitude and longitude resp. with the unit used been as it is. 490 491 else: 492 frminfo = '' 493 for frame, latlon in coord_systems.items(): 494 if frame in col.name and len(set(latlon[:2]) - set(self.colnames)) == 2: 495 if frame != col.name: 496 frminfo = f' ({col.name})' 497 lon_col = Column(getattr(col, latlon[3]), name=latlon[1], 498 description=f'{frame.capitalize()} Longitude{frminfo}', 499 unit=col.representation_component_units[latlon[3]], 500 format='.12f') 501 lat_col = Column(getattr(col, latlon[2]), name=latlon[0], 502 description=f'{frame.capitalize()} Latitude{frminfo}', 503 unit=col.representation_component_units[latlon[2]], 504 format='+.12f') 505 self.cols.append(lon_col) 506 self.cols.append(lat_col) 507 to_pop.append(i) # Delete original ``SkyCoord`` column. 508 509 # Convert all other ``SkyCoord`` columns that are not in the above three 510 # representations to string valued columns. Those could either be types not 511 # supported yet (e.g. 'helioprojective'), or already present and converted. 512 # If there were any extra ``SkyCoord`` columns of one kind after the first one, 513 # then their decomposition into their component columns has been skipped. 514 # This is done in order to not create duplicate component columns. 515 # Explicit renaming of the extra coordinate component columns by appending some 516 # suffix to their name, so as to distinguish them, is not yet implemented. 517 if i not in to_pop: 518 warnings.warn(f"Coordinate system of type '{col.name}' already stored in table " 519 f"as CDS/MRT-syle columns or of unrecognized type. So column {i} " 520 f"is being skipped with designation of a string valued column " 521 f"`{self.colnames[i]}`.", UserWarning) 522 self.cols.append(Column(col.to_string(), name=self.colnames[i])) 523 to_pop.append(i) # Delete original ``SkyCoord`` column. 524 525 # Convert all other ``mixin`` columns to ``Column`` objects. 526 # Parsing these may still lead to errors! 527 elif not isinstance(col, Column): 528 col = Column(col) 529 # If column values are ``object`` types, convert them to string. 530 if np.issubdtype(col.dtype, np.dtype(object).type): 531 col = Column([str(val) for val in col]) 532 self.cols[i] = col 533 534 # Delete original ``SkyCoord`` columns, if there were any. 535 for i in to_pop[::-1]: 536 self.cols.pop(i) 537 538 # Check for any left over extra coordinate columns. 539 if any(x in self.colnames for x in ['RAh', 'DEd', 'ELON', 'GLAT']): 540 # At this point any extra ``SkyCoord`` columns should have been converted to string 541 # valued columns, together with issuance of a warning, by the coordinate parser above. 542 # This test is just left here as a safeguard. 543 for i, col in enumerate(self.cols): 544 if isinstance(col, SkyCoord): 545 self.cols[i] = Column(col.to_string(), name=self.colnames[i]) 546 message = ('Table already has coordinate system in CDS/MRT-syle columns. ' 547 f'So column {i} should have been replaced already with ' 548 f'a string valued column `{self.colnames[i]}`.') 549 raise core.InconsistentTableError(message) 550 551 # Get Byte-By-Byte description and fill the template 552 bbb_template = Template('\n'.join(BYTE_BY_BYTE_TEMPLATE)) 553 byte_by_byte = bbb_template.substitute({'file': 'table.dat', 554 'bytebybyte': self.write_byte_by_byte()}) 555 556 # Fill up the full ReadMe 557 rm_template = Template('\n'.join(MRT_TEMPLATE)) 558 readme_filled = rm_template.substitute({'bytebybyte': byte_by_byte}) 559 lines.append(readme_filled) 560 561 562 class MrtData(cds.CdsData): 563 """MRT table data reader 564 """ 565 _subfmt = 'MRT' 566 splitter_class = MrtSplitter 567 568 def write(self, lines): 569 self.splitter.delimiter = ' ' 570 fixedwidth.FixedWidthData.write(self, lines) 571 572 573 class Mrt(core.BaseReader): 574 """AAS MRT (Machine-Readable Table) format table. 575 576 **Reading** 577 :: 578 579 >>> from astropy.io import ascii 580 >>> table = ascii.read('data.mrt', format='mrt') 581 582 **Writing** 583 584 Use ``ascii.write(table, 'data.mrt', format='mrt')`` to write tables to 585 Machine Readable Table (MRT) format. 586 587 Note that the metadata of the table, apart from units, column names and 588 description, will not be written. These have to be filled in by hand later. 589 590 See also: :ref:`cds_mrt_format`. 591 592 Caveats: 593 594 * The Units and Explanations are available in the column ``unit`` and 595 ``description`` attributes, respectively. 596 * The other metadata defined by this format is not available in the output table. 597 """ 598 _format_name = 'mrt' 599 _io_registry_format_aliases = ['mrt'] 600 _io_registry_can_write = True 601 _description = 'MRT format table' 602 603 data_class = MrtData 604 header_class = MrtHeader 605 606 def write(self, table=None): 607 # Construct for writing empty table is not yet done. 608 if len(table) == 0: 609 raise NotImplementedError 610 611 self.data.header = self.header 612 self.header.position_line = None 613 self.header.start_line = None 614 615 # Create a copy of the ``table``, so that it the copy gets modified and 616 # written to the file, while the original table remains as it is. 617 table = table.copy() 618 return super().write(table) 619 [end of astropy/io/ascii/mrt.py] [start of astropy/table/groups.py] 1 # Licensed under a 3-clause BSD style license - see LICENSE.rst 2 3 import platform 4 import warnings 5 6 import numpy as np 7 from .index import get_index_by_names 8 9 from astropy.utils.exceptions import AstropyUserWarning 10 11 12 __all__ = ['TableGroups', 'ColumnGroups'] 13 14 15 def table_group_by(table, keys): 16 # index copies are unnecessary and slow down _table_group_by 17 with table.index_mode('discard_on_copy'): 18 return _table_group_by(table, keys) 19 20 21 def _table_group_by(table, keys): 22 """ 23 Get groups for ``table`` on specified ``keys``. 24 25 Parameters 26 ---------- 27 table : `Table` 28 Table to group 29 keys : str, list of str, `Table`, or Numpy array 30 Grouping key specifier 31 32 Returns 33 ------- 34 grouped_table : Table object with groups attr set accordingly 35 """ 36 from .table import Table 37 from .serialize import represent_mixins_as_columns 38 39 # Pre-convert string to tuple of strings, or Table to the underlying structured array 40 if isinstance(keys, str): 41 keys = (keys,) 42 43 if isinstance(keys, (list, tuple)): 44 for name in keys: 45 if name not in table.colnames: 46 raise ValueError(f'Table does not have key column {name!r}') 47 if table.masked and np.any(table[name].mask): 48 raise ValueError(f'Missing values in key column {name!r} are not allowed') 49 50 # Make a column slice of the table without copying 51 table_keys = table.__class__([table[key] for key in keys], copy=False) 52 53 # If available get a pre-existing index for these columns 54 table_index = get_index_by_names(table, keys) 55 grouped_by_table_cols = True 56 57 elif isinstance(keys, (np.ndarray, Table)): 58 table_keys = keys 59 if len(table_keys) != len(table): 60 raise ValueError('Input keys array length {} does not match table length {}' 61 .format(len(table_keys), len(table))) 62 table_index = None 63 grouped_by_table_cols = False 64 65 else: 66 raise TypeError('Keys input must be string, list, tuple, Table or numpy array, but got {}' 67 .format(type(keys))) 68 69 # If there is not already an available index and table_keys is a Table then ensure 70 # that all cols (including mixins) are in a form that can sorted with the code below. 71 if not table_index and isinstance(table_keys, Table): 72 table_keys = represent_mixins_as_columns(table_keys) 73 74 # Get the argsort index `idx_sort`, accounting for particulars 75 try: 76 # take advantage of index internal sort if possible 77 if table_index is not None: 78 idx_sort = table_index.sorted_data() 79 else: 80 idx_sort = table_keys.argsort(kind='mergesort') 81 stable_sort = True 82 except TypeError: 83 # Some versions (likely 1.6 and earlier) of numpy don't support 84 # 'mergesort' for all data types. MacOSX (Darwin) doesn't have a stable 85 # sort by default, nor does Windows, while Linux does (or appears to). 86 idx_sort = table_keys.argsort() 87 stable_sort = platform.system() not in ('Darwin', 'Windows') 88 89 # Finally do the actual sort of table_keys values 90 table_keys = table_keys[idx_sort] 91 92 # Get all keys 93 diffs = np.concatenate(([True], table_keys[1:] != table_keys[:-1], [True])) 94 indices = np.flatnonzero(diffs) 95 96 # If the sort is not stable (preserves original table order) then sort idx_sort in 97 # place within each group. 98 if not stable_sort: 99 for i0, i1 in zip(indices[:-1], indices[1:]): 100 idx_sort[i0:i1].sort() 101 102 # Make a new table and set the _groups to the appropriate TableGroups object. 103 # Take the subset of the original keys at the indices values (group boundaries). 104 out = table.__class__(table[idx_sort]) 105 out_keys = table_keys[indices[:-1]] 106 if isinstance(out_keys, Table): 107 out_keys.meta['grouped_by_table_cols'] = grouped_by_table_cols 108 out._groups = TableGroups(out, indices=indices, keys=out_keys) 109 110 return out 111 112 113 def column_group_by(column, keys): 114 """ 115 Get groups for ``column`` on specified ``keys`` 116 117 Parameters 118 ---------- 119 column : Column object 120 Column to group 121 keys : Table or Numpy array of same length as col 122 Grouping key specifier 123 124 Returns 125 ------- 126 grouped_column : Column object with groups attr set accordingly 127 """ 128 from .table import Table 129 from .serialize import represent_mixins_as_columns 130 131 if isinstance(keys, Table): 132 keys = represent_mixins_as_columns(keys) 133 keys = keys.as_array() 134 135 if not isinstance(keys, np.ndarray): 136 raise TypeError(f'Keys input must be numpy array, but got {type(keys)}') 137 138 if len(keys) != len(column): 139 raise ValueError('Input keys array length {} does not match column length {}' 140 .format(len(keys), len(column))) 141 142 idx_sort = keys.argsort() 143 keys = keys[idx_sort] 144 145 # Get all keys 146 diffs = np.concatenate(([True], keys[1:] != keys[:-1], [True])) 147 indices = np.flatnonzero(diffs) 148 149 # Make a new column and set the _groups to the appropriate ColumnGroups object. 150 # Take the subset of the original keys at the indices values (group boundaries). 151 out = column.__class__(column[idx_sort]) 152 out._groups = ColumnGroups(out, indices=indices, keys=keys[indices[:-1]]) 153 154 return out 155 156 157 class BaseGroups: 158 """ 159 A class to represent groups within a table of heterogeneous data. 160 161 - ``keys``: key values corresponding to each group 162 - ``indices``: index values in parent table or column corresponding to group boundaries 163 - ``aggregate()``: method to create new table by aggregating within groups 164 """ 165 @property 166 def parent(self): 167 return self.parent_column if isinstance(self, ColumnGroups) else self.parent_table 168 169 def __iter__(self): 170 self._iter_index = 0 171 return self 172 173 def next(self): 174 ii = self._iter_index 175 if ii < len(self.indices) - 1: 176 i0, i1 = self.indices[ii], self.indices[ii + 1] 177 self._iter_index += 1 178 return self.parent[i0:i1] 179 else: 180 raise StopIteration 181 __next__ = next 182 183 def __getitem__(self, item): 184 parent = self.parent 185 186 if isinstance(item, (int, np.integer)): 187 i0, i1 = self.indices[item], self.indices[item + 1] 188 out = parent[i0:i1] 189 out.groups._keys = parent.groups.keys[item] 190 else: 191 indices0, indices1 = self.indices[:-1], self.indices[1:] 192 try: 193 i0s, i1s = indices0[item], indices1[item] 194 except Exception as err: 195 raise TypeError('Index item for groups attribute must be a slice, ' 196 'numpy mask or int array') from err 197 mask = np.zeros(len(parent), dtype=bool) 198 # Is there a way to vectorize this in numpy? 199 for i0, i1 in zip(i0s, i1s): 200 mask[i0:i1] = True 201 out = parent[mask] 202 out.groups._keys = parent.groups.keys[item] 203 out.groups._indices = np.concatenate([[0], np.cumsum(i1s - i0s)]) 204 205 return out 206 207 def __repr__(self): 208 return f'<{self.__class__.__name__} indices={self.indices}>' 209 210 def __len__(self): 211 return len(self.indices) - 1 212 213 214 class ColumnGroups(BaseGroups): 215 def __init__(self, parent_column, indices=None, keys=None): 216 self.parent_column = parent_column # parent Column 217 self.parent_table = parent_column.parent_table 218 self._indices = indices 219 self._keys = keys 220 221 @property 222 def indices(self): 223 # If the parent column is in a table then use group indices from table 224 if self.parent_table: 225 return self.parent_table.groups.indices 226 else: 227 if self._indices is None: 228 return np.array([0, len(self.parent_column)]) 229 else: 230 return self._indices 231 232 @property 233 def keys(self): 234 # If the parent column is in a table then use group indices from table 235 if self.parent_table: 236 return self.parent_table.groups.keys 237 else: 238 return self._keys 239 240 def aggregate(self, func): 241 from .column import MaskedColumn 242 243 i0s, i1s = self.indices[:-1], self.indices[1:] 244 par_col = self.parent_column 245 masked = isinstance(par_col, MaskedColumn) 246 reduceat = hasattr(func, 'reduceat') 247 sum_case = func is np.sum 248 mean_case = func is np.mean 249 try: 250 if not masked and (reduceat or sum_case or mean_case): 251 if mean_case: 252 vals = np.add.reduceat(par_col, i0s) / np.diff(self.indices) 253 else: 254 if sum_case: 255 func = np.add 256 vals = func.reduceat(par_col, i0s) 257 else: 258 vals = np.array([func(par_col[i0: i1]) for i0, i1 in zip(i0s, i1s)]) 259 except Exception as err: 260 raise TypeError("Cannot aggregate column '{}' with type '{}'" 261 .format(par_col.info.name, 262 par_col.info.dtype)) from err 263 264 out = par_col.__class__(data=vals, 265 name=par_col.info.name, 266 description=par_col.info.description, 267 unit=par_col.info.unit, 268 format=par_col.info.format, 269 meta=par_col.info.meta) 270 return out 271 272 def filter(self, func): 273 """ 274 Filter groups in the Column based on evaluating function ``func`` on each 275 group sub-table. 276 277 The function which is passed to this method must accept one argument: 278 279 - ``column`` : `Column` object 280 281 It must then return either `True` or `False`. As an example, the following 282 will select all column groups with only positive values:: 283 284 def all_positive(column): 285 if np.any(column < 0): 286 return False 287 return True 288 289 Parameters 290 ---------- 291 func : function 292 Filter function 293 294 Returns 295 ------- 296 out : Column 297 New column with the aggregated rows. 298 """ 299 mask = np.empty(len(self), dtype=bool) 300 for i, group_column in enumerate(self): 301 mask[i] = func(group_column) 302 303 return self[mask] 304 305 306 class TableGroups(BaseGroups): 307 def __init__(self, parent_table, indices=None, keys=None): 308 self.parent_table = parent_table # parent Table 309 self._indices = indices 310 self._keys = keys 311 312 @property 313 def key_colnames(self): 314 """ 315 Return the names of columns in the parent table that were used for grouping. 316 """ 317 # If the table was grouped by key columns *in* the table then treat those columns 318 # differently in aggregation. In this case keys will be a Table with 319 # keys.meta['grouped_by_table_cols'] == True. Keys might not be a Table so we 320 # need to handle this. 321 grouped_by_table_cols = getattr(self.keys, 'meta', {}).get('grouped_by_table_cols', False) 322 return self.keys.colnames if grouped_by_table_cols else () 323 324 @property 325 def indices(self): 326 if self._indices is None: 327 return np.array([0, len(self.parent_table)]) 328 else: 329 return self._indices 330 331 def aggregate(self, func): 332 """ 333 Aggregate each group in the Table into a single row by applying the reduction 334 function ``func`` to group values in each column. 335 336 Parameters 337 ---------- 338 func : function 339 Function that reduces an array of values to a single value 340 341 Returns 342 ------- 343 out : Table 344 New table with the aggregated rows. 345 """ 346 347 i0s = self.indices[:-1] 348 out_cols = [] 349 parent_table = self.parent_table 350 351 for col in parent_table.columns.values(): 352 # For key columns just pick off first in each group since they are identical 353 if col.info.name in self.key_colnames: 354 new_col = col.take(i0s) 355 else: 356 try: 357 new_col = col.groups.aggregate(func) 358 except TypeError as err: 359 warnings.warn(str(err), AstropyUserWarning) 360 continue 361 362 out_cols.append(new_col) 363 364 return parent_table.__class__(out_cols, meta=parent_table.meta) 365 366 def filter(self, func): 367 """ 368 Filter groups in the Table based on evaluating function ``func`` on each 369 group sub-table. 370 371 The function which is passed to this method must accept two arguments: 372 373 - ``table`` : `Table` object 374 - ``key_colnames`` : tuple of column names in ``table`` used as keys for grouping 375 376 It must then return either `True` or `False`. As an example, the following 377 will select all table groups with only positive values in the non-key columns:: 378 379 def all_positive(table, key_colnames): 380 colnames = [name for name in table.colnames if name not in key_colnames] 381 for colname in colnames: 382 if np.any(table[colname] < 0): 383 return False 384 return True 385 386 Parameters 387 ---------- 388 func : function 389 Filter function 390 391 Returns 392 ------- 393 out : Table 394 New table with the aggregated rows. 395 """ 396 mask = np.empty(len(self), dtype=bool) 397 key_colnames = self.key_colnames 398 for i, group_table in enumerate(self): 399 mask[i] = func(group_table, key_colnames) 400 401 return self[mask] 402 403 @property 404 def keys(self): 405 return self._keys 406 [end of astropy/table/groups.py] </code> I need you to solve this issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the following format. <patch> --- a/file.py +++ b/file.py @@ -1,27 +1,35 @@ def euclidean(a, b): - while b: - a, b = b, a % b - return a + if b == 0: + return a + return euclidean(b, a % b) def bresenham(x0, y0, x1, y1): points = [] dx = abs(x1 - x0) dy = abs(y1 - y0) - sx = 1 if x0 < x1 else -1 - sy = 1 if y0 < y1 else -1 - err = dx - dy + x, y = x0, y0 + sx = -1 if x0 > x1 else 1 + sy = -1 if y0 > y1 else 1 - while True: - points.append((x0, y0)) - if x0 == x1 and y0 == y1: - break - e2 = 2 * err - if e2 > -dy: + if dx > dy: + err = dx / 2.0 + while x != x1: + points.append((x, y)) err -= dy - x0 += sx - if e2 < dx: - err += dx - y0 += sy + if err < 0: + y += sy + err += dx + x += sx + else: + err = dy / 2.0 + while y != y1: + points.append((x, y)) + err -= dx + if err < 0: + x += sx + err += dy + y += sy + points.append((x, y)) return points </patch>
astropy/astropy
43ee5806e9c6f7d58c12c1cb9287b3c61abe489d
SkyCoord in Table breaks aggregate on group_by ### Description, actual behaviour, reproduction When putting a column of `SkyCoord`s in a `Table`, `aggregate` does not work on `group_by().groups`: ```python from astropy.table import Table import astropy.units as u from astropy.coordinates import SkyCoord import numpy as np ras = [10, 20] * u.deg decs = [32, -2] * u.deg str_col = ['foo', 'bar'] coords = SkyCoord(ra=ras, dec=decs) table = Table([str_col, coords], names=['col1', 'col2']) table.group_by('col1').groups.aggregate(np.mean) ``` fails with ``` Traceback (most recent call last): File "repro.py", line 13, in <module> table.group_by('col1').groups.aggregate(np.mean) File "astropy/table/groups.py", line 357, in aggregate new_col = col.groups.aggregate(func) File "astropy/coordinates/sky_coordinate.py", line 835, in __getattr__ raise AttributeError("'{}' object has no attribute '{}'" AttributeError: 'SkyCoord' object has no attribute 'groups' ``` This happens irregardless of the aggregation function. ### Expected behavior Aggregation works, only fails to aggregate columns where operation does not make sense. ### System Details ``` Linux-5.14.11-arch1-1-x86_64-with-glibc2.33 Python 3.9.7 (default, Aug 31 2021, 13:28:12) [GCC 11.1.0] Numpy 1.21.2 astropy 5.0.dev945+g7dfa1edb2 (no scipy or matplotlib) ``` and ``` Linux-5.14.11-arch1-1-x86_64-with-glibc2.33 Python 3.9.7 (default, Aug 31 2021, 13:28:12) [GCC 11.1.0] Numpy 1.21.2 astropy 4.3.1 Scipy 1.7.1 Matplotlib 3.4.3 ```
Hmm. Maybe the logic here needs fixing: https://github.com/astropy/astropy/blob/bcde23429a076859af856d941282f3df917b8dd4/astropy/table/groups.py#L351-L360 Mostly finished with a fix for this which makes it possible to aggregate tables that have mixin columns. In cases where the aggregation makes sense (e.g. with Quantity) it will just work. In other cases a warning only.
2022-02-05T12:13:44Z
<patch> diff --git a/astropy/table/column.py b/astropy/table/column.py --- a/astropy/table/column.py +++ b/astropy/table/column.py @@ -340,7 +340,9 @@ class ColumnInfo(BaseColumnInfo): This is required when the object is used as a mixin column within a table, but can be used as a general way to store meta information. """ - attrs_from_parent = BaseColumnInfo.attr_names + attr_names = BaseColumnInfo.attr_names | {'groups'} + _attrs_no_copy = BaseColumnInfo._attrs_no_copy | {'groups'} + attrs_from_parent = attr_names _supports_indexing = True def new_like(self, cols, length, metadata_conflicts='warn', name=None): diff --git a/astropy/table/groups.py b/astropy/table/groups.py --- a/astropy/table/groups.py +++ b/astropy/table/groups.py @@ -214,7 +214,7 @@ def __len__(self): class ColumnGroups(BaseGroups): def __init__(self, parent_column, indices=None, keys=None): self.parent_column = parent_column # parent Column - self.parent_table = parent_column.parent_table + self.parent_table = parent_column.info.parent_table self._indices = indices self._keys = keys @@ -238,7 +238,8 @@ def keys(self): return self._keys def aggregate(self, func): - from .column import MaskedColumn + from .column import MaskedColumn, Column + from astropy.utils.compat import NUMPY_LT_1_20 i0s, i1s = self.indices[:-1], self.indices[1:] par_col = self.parent_column @@ -248,6 +249,15 @@ def aggregate(self, func): mean_case = func is np.mean try: if not masked and (reduceat or sum_case or mean_case): + # For numpy < 1.20 there is a bug where reduceat will fail to + # raise an exception for mixin columns that do not support the + # operation. For details see: + # https://github.com/astropy/astropy/pull/12825#issuecomment-1082412447 + # Instead we try the function directly with a 2-element version + # of the column + if NUMPY_LT_1_20 and not isinstance(par_col, Column) and len(par_col) > 0: + func(par_col[[0, 0]]) + if mean_case: vals = np.add.reduceat(par_col, i0s) / np.diff(self.indices) else: @@ -256,17 +266,18 @@ def aggregate(self, func): vals = func.reduceat(par_col, i0s) else: vals = np.array([func(par_col[i0: i1]) for i0, i1 in zip(i0s, i1s)]) + out = par_col.__class__(vals) except Exception as err: - raise TypeError("Cannot aggregate column '{}' with type '{}'" - .format(par_col.info.name, - par_col.info.dtype)) from err - - out = par_col.__class__(data=vals, - name=par_col.info.name, - description=par_col.info.description, - unit=par_col.info.unit, - format=par_col.info.format, - meta=par_col.info.meta) + raise TypeError("Cannot aggregate column '{}' with type '{}': {}" + .format(par_col.info.name, par_col.info.dtype, err)) from err + + out_info = out.info + for attr in ('name', 'unit', 'format', 'description', 'meta'): + try: + setattr(out_info, attr, getattr(par_col.info, attr)) + except AttributeError: + pass + return out def filter(self, func): @@ -354,7 +365,7 @@ def aggregate(self, func): new_col = col.take(i0s) else: try: - new_col = col.groups.aggregate(func) + new_col = col.info.groups.aggregate(func) except TypeError as err: warnings.warn(str(err), AstropyUserWarning) continue diff --git a/astropy/utils/data_info.py b/astropy/utils/data_info.py --- a/astropy/utils/data_info.py +++ b/astropy/utils/data_info.py @@ -511,7 +511,7 @@ class BaseColumnInfo(DataInfo): Note that this class is defined here so that mixins can use it without importing the table package. """ - attr_names = DataInfo.attr_names.union(['parent_table', 'indices']) + attr_names = DataInfo.attr_names | {'parent_table', 'indices'} _attrs_no_copy = set(['parent_table', 'indices']) # Context for serialization. This can be set temporarily via @@ -752,6 +752,15 @@ def name(self, name): self._attrs['name'] = name + @property + def groups(self): + # This implementation for mixin columns essentially matches the Column + # property definition. `groups` is a read-only property here and + # depends on the parent table of the column having `groups`. This will + # allow aggregating mixins as long as they support those operations. + from astropy.table import groups + return self._attrs.setdefault('groups', groups.ColumnGroups(self._parent)) + class ParentDtypeInfo(MixinInfo): """Mixin that gets info.dtype from parent""" </patch>
diff --git a/astropy/table/tests/conftest.py b/astropy/table/tests/conftest.py --- a/astropy/table/tests/conftest.py +++ b/astropy/table/tests/conftest.py @@ -178,16 +178,17 @@ def mixin_cols(request): @pytest.fixture(params=[False, True]) def T1(request): - T = Table.read([' a b c d', - ' 2 c 7.0 0', - ' 2 b 5.0 1', - ' 2 b 6.0 2', - ' 2 a 4.0 3', - ' 0 a 0.0 4', - ' 1 b 3.0 5', - ' 1 a 2.0 6', - ' 1 a 1.0 7', - ], format='ascii') + T = QTable.read([' a b c d', + ' 2 c 7.0 0', + ' 2 b 5.0 1', + ' 2 b 6.0 2', + ' 2 a 4.0 3', + ' 0 a 0.0 4', + ' 1 b 3.0 5', + ' 1 a 2.0 6', + ' 1 a 1.0 7', + ], format='ascii') + T['q'] = np.arange(len(T)) * u.m T.meta.update({'ta': 1}) T['c'].meta.update({'a': 1}) T['c'].description = 'column c' diff --git a/astropy/table/tests/test_groups.py b/astropy/table/tests/test_groups.py --- a/astropy/table/tests/test_groups.py +++ b/astropy/table/tests/test_groups.py @@ -17,7 +17,7 @@ def sort_eq(list1, list2): def test_column_group_by(T1): for masked in (False, True): - t1 = Table(T1, masked=masked) + t1 = QTable(T1, masked=masked) t1a = t1['a'].copy() # Group by a Column (i.e. numpy array) @@ -39,7 +39,7 @@ def test_table_group_by(T1): masked/unmasked tables. """ for masked in (False, True): - t1 = Table(T1, masked=masked) + t1 = QTable(T1, masked=masked) # Group by a single column key specified by name tg = t1.group_by('a') assert np.all(tg.groups.indices == np.array([0, 1, 4, 8])) @@ -47,16 +47,17 @@ def test_table_group_by(T1): assert str(tg['a'].groups) == "<ColumnGroups indices=[0 1 4 8]>" # Sorted by 'a' and in original order for rest - assert tg.pformat() == [' a b c d ', - '--- --- --- ---', - ' 0 a 0.0 4', - ' 1 b 3.0 5', - ' 1 a 2.0 6', - ' 1 a 1.0 7', - ' 2 c 7.0 0', - ' 2 b 5.0 1', - ' 2 b 6.0 2', - ' 2 a 4.0 3'] + assert tg.pformat() == [' a b c d q ', + ' m ', + '--- --- --- --- ---', + ' 0 a 0.0 4 4.0', + ' 1 b 3.0 5 5.0', + ' 1 a 2.0 6 6.0', + ' 1 a 1.0 7 7.0', + ' 2 c 7.0 0 0.0', + ' 2 b 5.0 1 1.0', + ' 2 b 6.0 2 2.0', + ' 2 a 4.0 3 3.0'] assert tg.meta['ta'] == 1 assert tg['c'].meta['a'] == 1 assert tg['c'].description == 'column c' @@ -70,16 +71,17 @@ def test_table_group_by(T1): tg = t1.group_by(keys) assert np.all(tg.groups.indices == np.array([0, 1, 3, 4, 5, 7, 8])) # Sorted by 'a', 'b' and in original order for rest - assert tg.pformat() == [' a b c d ', - '--- --- --- ---', - ' 0 a 0.0 4', - ' 1 a 2.0 6', - ' 1 a 1.0 7', - ' 1 b 3.0 5', - ' 2 a 4.0 3', - ' 2 b 5.0 1', - ' 2 b 6.0 2', - ' 2 c 7.0 0'] + assert tg.pformat() == [' a b c d q ', + ' m ', + '--- --- --- --- ---', + ' 0 a 0.0 4 4.0', + ' 1 a 2.0 6 6.0', + ' 1 a 1.0 7 7.0', + ' 1 b 3.0 5 5.0', + ' 2 a 4.0 3 3.0', + ' 2 b 5.0 1 1.0', + ' 2 b 6.0 2 2.0', + ' 2 c 7.0 0 0.0'] # Group by a Table tg2 = t1.group_by(t1['a', 'b']) @@ -92,16 +94,17 @@ def test_table_group_by(T1): # Group by a simple ndarray tg = t1.group_by(np.array([0, 1, 0, 1, 2, 1, 0, 0])) assert np.all(tg.groups.indices == np.array([0, 4, 7, 8])) - assert tg.pformat() == [' a b c d ', - '--- --- --- ---', - ' 2 c 7.0 0', - ' 2 b 6.0 2', - ' 1 a 2.0 6', - ' 1 a 1.0 7', - ' 2 b 5.0 1', - ' 2 a 4.0 3', - ' 1 b 3.0 5', - ' 0 a 0.0 4'] + assert tg.pformat() == [' a b c d q ', + ' m ', + '--- --- --- --- ---', + ' 2 c 7.0 0 0.0', + ' 2 b 6.0 2 2.0', + ' 1 a 2.0 6 6.0', + ' 1 a 1.0 7 7.0', + ' 2 b 5.0 1 1.0', + ' 2 a 4.0 3 3.0', + ' 1 b 3.0 5 5.0', + ' 0 a 0.0 4 4.0'] def test_groups_keys(T1): @@ -134,7 +137,7 @@ def test_grouped_copy(T1): Test that copying a table or column copies the groups properly """ for masked in (False, True): - t1 = Table(T1, masked=masked) + t1 = QTable(T1, masked=masked) tg = t1.group_by('a') tgc = tg.copy() assert np.all(tgc.groups.indices == tg.groups.indices) @@ -155,7 +158,7 @@ def test_grouped_slicing(T1): """ for masked in (False, True): - t1 = Table(T1, masked=masked) + t1 = QTable(T1, masked=masked) # Regular slice of a table tg = t1.group_by('a') @@ -266,11 +269,11 @@ def test_mutable_operations(T1): but adding or removing or renaming a column should retain grouping. """ for masked in (False, True): - t1 = Table(T1, masked=masked) + t1 = QTable(T1, masked=masked) # add row tg = t1.group_by('a') - tg.add_row((0, 'a', 3.0, 4)) + tg.add_row((0, 'a', 3.0, 4, 4 * u.m)) assert np.all(tg.groups.indices == np.array([0, len(tg)])) assert tg.groups.keys is None @@ -312,19 +315,20 @@ def test_mutable_operations(T1): def test_group_by_masked(T1): - t1m = Table(T1, masked=True) + t1m = QTable(T1, masked=True) t1m['c'].mask[4] = True t1m['d'].mask[5] = True - assert t1m.group_by('a').pformat() == [' a b c d ', - '--- --- --- ---', - ' 0 a -- 4', - ' 1 b 3.0 --', - ' 1 a 2.0 6', - ' 1 a 1.0 7', - ' 2 c 7.0 0', - ' 2 b 5.0 1', - ' 2 b 6.0 2', - ' 2 a 4.0 3'] + assert t1m.group_by('a').pformat() == [' a b c d q ', + ' m ', + '--- --- --- --- ---', + ' 0 a -- 4 4.0', + ' 1 b 3.0 -- 5.0', + ' 1 a 2.0 6 6.0', + ' 1 a 1.0 7 7.0', + ' 2 c 7.0 0 0.0', + ' 2 b 5.0 1 1.0', + ' 2 b 6.0 2 2.0', + ' 2 a 4.0 3 3.0'] def test_group_by_errors(T1): @@ -348,7 +352,7 @@ def test_group_by_errors(T1): T1.group_by(None) # Masked key column - t1 = Table(T1, masked=True) + t1 = QTable(T1, masked=True) t1['a'].mask[4] = True with pytest.raises(ValueError): t1.group_by('a') @@ -408,23 +412,24 @@ def test_table_aggregate(T1): # Aggregate with np.sum with masked elements. This results # in one group with no elements, hence a nan result and conversion # to float for the 'd' column. - t1m = Table(t1, masked=True) + t1m = QTable(T1, masked=True) t1m['c'].mask[4:6] = True t1m['d'].mask[4:6] = True tg = t1m.group_by('a') with pytest.warns(UserWarning, match="converting a masked element to nan"): tga = tg.groups.aggregate(np.sum) - assert tga.pformat() == [' a c d ', - '--- ---- ----', - ' 0 nan nan', - ' 1 3.0 13.0', - ' 2 22.0 6.0'] + assert tga.pformat() == [' a c d q ', + ' m ', + '--- ---- ---- ----', + ' 0 nan nan 4.0', + ' 1 3.0 13.0 18.0', + ' 2 22.0 6.0 6.0'] # Aggregrate with np.sum with masked elements, but where every # group has at least one remaining (unmasked) element. Then # the int column stays as an int. - t1m = Table(t1, masked=True) + t1m = QTable(t1, masked=True) t1m['c'].mask[5] = True t1m['d'].mask[5] = True tg = t1m.group_by('a') @@ -440,11 +445,12 @@ def test_table_aggregate(T1): tg = T1.group_by('a') with pytest.warns(AstropyUserWarning, match="Cannot aggregate column"): tga = tg.groups.aggregate(np.sum) - assert tga.pformat() == [' a c d ', - '--- ---- ---', - ' 0 0.0 4', - ' 1 6.0 18', - ' 2 22.0 6'] + assert tga.pformat() == [' a c d q ', + ' m ', + '--- ---- --- ----', + ' 0 0.0 4 4.0', + ' 1 6.0 18 18.0', + ' 2 22.0 6 6.0'] def test_table_aggregate_reduceat(T1): @@ -504,7 +510,7 @@ def test_column_aggregate(T1): Aggregate a single table column """ for masked in (False, True): - tg = Table(T1, masked=masked).group_by('a') + tg = QTable(T1, masked=masked).group_by('a') tga = tg['c'].groups.aggregate(np.sum) assert tga.pformat() == [' c ', '----', @@ -635,3 +641,16 @@ def test_group_mixins(): # Column group_by() with mixins idxg = qt['idx'].group_by(qt[mixin_keys]) assert np.all(idxg == [1, 3, 2, 0]) + + +@pytest.mark.parametrize( + 'col', [time.TimeDelta([1, 2], format='sec'), + time.Time([1, 2], format='cxcsec'), + coordinates.SkyCoord([1, 2], [3, 4], unit='deg,deg')]) +def test_group_mixins_unsupported(col): + """Test that aggregating unsupported mixins produces a warning only""" + + t = Table([[1, 1], [3, 4], col], names=['a', 'b', 'mix']) + tg = t.group_by('a') + with pytest.warns(AstropyUserWarning, match="Cannot aggregate column 'mix'"): + tg.groups.aggregate(np.sum)
4.3
["astropy/table/tests/test_groups.py::test_table_aggregate[False]", "astropy/table/tests/test_groups.py::test_table_aggregate[True]", "astropy/table/tests/test_groups.py::test_group_mixins_unsupported[col0]", "astropy/table/tests/test_groups.py::test_group_mixins_unsupported[col1]", "astropy/table/tests/test_groups.py::test_group_mixins_unsupported[col2]"]
["astropy/table/tests/test_groups.py::test_column_group_by[False]", "astropy/table/tests/test_groups.py::test_column_group_by[True]", "astropy/table/tests/test_groups.py::test_table_group_by[False]", "astropy/table/tests/test_groups.py::test_groups_keys[False]", "astropy/table/tests/test_groups.py::test_groups_keys[True]", "astropy/table/tests/test_groups.py::test_groups_iterator[False]", "astropy/table/tests/test_groups.py::test_groups_iterator[True]", "astropy/table/tests/test_groups.py::test_grouped_copy[False]", "astropy/table/tests/test_groups.py::test_grouped_copy[True]", "astropy/table/tests/test_groups.py::test_grouped_slicing[False]", "astropy/table/tests/test_groups.py::test_grouped_slicing[True]", "astropy/table/tests/test_groups.py::test_group_column_from_table[False]", "astropy/table/tests/test_groups.py::test_group_column_from_table[True]", "astropy/table/tests/test_groups.py::test_table_groups_mask_index[False]", "astropy/table/tests/test_groups.py::test_table_groups_mask_index[True]", "astropy/table/tests/test_groups.py::test_table_groups_array_index[False]", "astropy/table/tests/test_groups.py::test_table_groups_array_index[True]", "astropy/table/tests/test_groups.py::test_table_groups_slicing[False]", "astropy/table/tests/test_groups.py::test_table_groups_slicing[True]", "astropy/table/tests/test_groups.py::test_grouped_item_access[False]", "astropy/table/tests/test_groups.py::test_grouped_item_access[True]", "astropy/table/tests/test_groups.py::test_mutable_operations[False]", "astropy/table/tests/test_groups.py::test_mutable_operations[True]", "astropy/table/tests/test_groups.py::test_group_by_masked[False]", "astropy/table/tests/test_groups.py::test_group_by_errors[False]", "astropy/table/tests/test_groups.py::test_group_by_errors[True]", "astropy/table/tests/test_groups.py::test_groups_keys_meta[False]", "astropy/table/tests/test_groups.py::test_groups_keys_meta[True]", "astropy/table/tests/test_groups.py::test_table_aggregate_reduceat[False]", "astropy/table/tests/test_groups.py::test_table_aggregate_reduceat[True]", "astropy/table/tests/test_groups.py::test_column_aggregate[False]", "astropy/table/tests/test_groups.py::test_column_aggregate[True]", "astropy/table/tests/test_groups.py::test_column_aggregate_f8", "astropy/table/tests/test_groups.py::test_table_filter", "astropy/table/tests/test_groups.py::test_column_filter", "astropy/table/tests/test_groups.py::test_group_mixins"]
298ccb478e6bf092953bca67a3d29dc6c35f6752
astropy__astropy-12842
"You will be provided with a partial code base and an issue statement explaining a problem to resolv(...TRUNCATED)
astropy/astropy
3a0cd2d8cd7b459cdc1e1b97a14f3040ccc1fffc
"No longer able to read BinnedTimeSeries with datetime column saved as ECSV after upgrading from 4.2(...TRUNCATED)
"I hope you don't mind me tagging you @taldcroft as it was your commit, maybe you can help me figure(...TRUNCATED)
2022-02-12T12:38:10Z
"<patch>\ndiff --git a/astropy/time/core.py b/astropy/time/core.py\n--- a/astropy/time/core.py\n+++ (...TRUNCATED)
"diff --git a/astropy/io/ascii/tests/test_ecsv.py b/astropy/io/ascii/tests/test_ecsv.py\n--- a/astro(...TRUNCATED)
4.3
"[\"astropy/time/tests/test_basic.py::test_write_every_format_to_ecsv[datetime]\", \"astropy/time/te(...TRUNCATED)
"[\"astropy/io/ascii/tests/test_ecsv.py::astropy.io.ascii.tests.test_ecsv.test_round_trip_masked_tab(...TRUNCATED)
298ccb478e6bf092953bca67a3d29dc6c35f6752
astropy__astropy-13073
"You will be provided with a partial code base and an issue statement explaining a problem to resolv(...TRUNCATED)
astropy/astropy
43ee5806e9c6f7d58c12c1cb9287b3c61abe489d
"Document reading True/False in ASCII table as bool not str\n<!-- This comments are hidden when you (...TRUNCATED)
"Hi!\r\n\r\nI'm wondering if something as simple as this is sufficient or if you think it needs its (...TRUNCATED)
2022-04-06T16:29:58Z
"<patch>\ndiff --git a/astropy/io/ascii/core.py b/astropy/io/ascii/core.py\n--- a/astropy/io/ascii/c(...TRUNCATED)
"diff --git a/astropy/io/ascii/tests/test_read.py b/astropy/io/ascii/tests/test_read.py\n--- a/astro(...TRUNCATED)
5.0
["astropy/io/ascii/tests/test_read.py::test_read_converters_simplified"]
"[\"astropy/io/ascii/tests/test_read.py::test_convert_overflow[True]\", \"astropy/io/ascii/tests/tes(...TRUNCATED)
cdf311e0714e611d48b0a31eb1f0e2cbffab7f23
astropy__astropy-13075
"You will be provided with a partial code base and an issue statement explaining a problem to resolv(...TRUNCATED)
astropy/astropy
c660b079b6472920662ca4a0c731751a0342448c
"Register format ``html`` to ``Cosmology.write`` with nice mathjax\nCosmology can now read and write(...TRUNCATED)
"Hi. I am a new contributor and was wondering if this was still open for contribution? I would like (...TRUNCATED)
2022-04-06T19:44:23Z
"<patch>\ndiff --git a/astropy/cosmology/io/__init__.py b/astropy/cosmology/io/__init__.py\n--- a/as(...TRUNCATED)
"diff --git a/astropy/cosmology/io/tests/test_.py b/astropy/cosmology/io/tests/test_.py\n--- a/astro(...TRUNCATED)
5.0
"[\"astropy/cosmology/io/tests/test_.py::test_expected_readwrite_io\", \"astropy/cosmology/io/tests/(...TRUNCATED)
[]
cdf311e0714e611d48b0a31eb1f0e2cbffab7f23
astropy__astropy-13236
"You will be provided with a partial code base and an issue statement explaining a problem to resolv(...TRUNCATED)
astropy/astropy
6ed769d58d89380ebaa1ef52b300691eefda8928
"Consider removing auto-transform of structured column into NdarrayMixin\n<!-- This comments are hid(...TRUNCATED)
"@mhvk - I'm happy to do this PR if you think it is a good idea.\nI agree there no longer is any rea(...TRUNCATED)
2022-05-09T14:16:30Z
"<patch>\ndiff --git a/astropy/table/table.py b/astropy/table/table.py\n--- a/astropy/table/table.py(...TRUNCATED)
"diff --git a/astropy/table/tests/test_mixin.py b/astropy/table/tests/test_mixin.py\n--- a/astropy/t(...TRUNCATED)
5.0
"[\"astropy/table/tests/test_mixin.py::test_ndarray_mixin[False]\", \"astropy/table/tests/test_table(...TRUNCATED)
"[\"astropy/table/tests/test_mixin.py::test_attributes[arrayswap]\", \"astropy/table/tests/test_mixi(...TRUNCATED)
cdf311e0714e611d48b0a31eb1f0e2cbffab7f23
astropy__astropy-13417
"You will be provided with a partial code base and an issue statement explaining a problem to resolv(...TRUNCATED)
astropy/astropy
7539d76ceae146f930d4473107d9940d2fc0b74f
"FITS problem reading binary table with variable length columns\nI want to read a certain FITS file (...TRUNCATED)
"It took me a bit of time to figure out the issue, as I know almost nothing about VLA, and the `io.f(...TRUNCATED)
2022-07-01T08:50:37Z
"<patch>\ndiff --git a/astropy/io/fits/column.py b/astropy/io/fits/column.py\n--- a/astropy/io/fits/(...TRUNCATED)
"diff --git a/astropy/io/fits/tests/test_table.py b/astropy/io/fits/tests/test_table.py\n--- a/astro(...TRUNCATED)
5.0
["astropy/io/fits/tests/test_table.py::TestVLATables::test_multidim_VLA_tables"]
"[\"astropy/io/fits/tests/test_table.py::TestTableFunctions::test_constructor_copies_header\", \"ast(...TRUNCATED)
cdf311e0714e611d48b0a31eb1f0e2cbffab7f23
astropy__astropy-13453
"You will be provided with a partial code base and an issue statement explaining a problem to resolv(...TRUNCATED)
astropy/astropy
19cc80471739bcb67b7e8099246b391c355023ee
"ASCII table output to HTML does not support supplied \"formats\"\n<!-- This comments are hidden whe(...TRUNCATED)
"Welcome to Astropy 👋 and thank you for your first issue!\n\nA project member will respond to you(...TRUNCATED)
2022-07-14T10:04:40Z
"<patch>\ndiff --git a/astropy/io/ascii/html.py b/astropy/io/ascii/html.py\n--- a/astropy/io/ascii/h(...TRUNCATED)
"diff --git a/astropy/io/ascii/tests/test_html.py b/astropy/io/ascii/tests/test_html.py\n--- a/astro(...TRUNCATED)
5.0
["astropy/io/ascii/tests/test_html.py::test_write_table_formatted_columns"]
"[\"astropy/io/ascii/tests/test_html.py::test_listwriter\", \"astropy/io/ascii/tests/test_html.py::t(...TRUNCATED)
cdf311e0714e611d48b0a31eb1f0e2cbffab7f23
astropy__astropy-13462
"You will be provided with a partial code base and an issue statement explaining a problem to resolv(...TRUNCATED)
astropy/astropy
d441bfdbb8e6dc57a52d8c1b117cadd030f0657a
"TST: time/tests/test_precision.py failed in pyinstaller (computed error is different depending on t(...TRUNCATED)
"At a glance, I don't see any version change in numpy, hypothesis, etc. Is this transient? 🤔 (Res(...TRUNCATED)
2022-07-16T16:57:17Z
"<patch>\ndiff --git a/astropy/time/utils.py b/astropy/time/utils.py\n--- a/astropy/time/utils.py\n+(...TRUNCATED)
"diff --git a/astropy/time/tests/test_basic.py b/astropy/time/tests/test_basic.py\n--- a/astropy/tim(...TRUNCATED)
5.0
["astropy/time/tests/test_precision.py::test_day_frac_exact"]
"[\"astropy/time/tests/test_basic.py::TestBasic::test_different_dimensions\", \"astropy/time/tests/t(...TRUNCATED)
cdf311e0714e611d48b0a31eb1f0e2cbffab7f23
astropy__astropy-14253
"You will be provided with a partial code base and an issue statement explaining a problem to resolv(...TRUNCATED)
astropy/astropy
dd2304672cdf4ea1b6f124f9f22ec5069a13c9f5
"When should `info` be linked to a new object?\nMostly for @taldcroft - I noticed that in `Quantity`(...TRUNCATED)
"@mhvk - I basically agree with your assessment as being logical. I guess the only question is abou(...TRUNCATED)
2023-01-04T19:59:52Z
"<patch>\ndiff --git a/astropy/units/quantity.py b/astropy/units/quantity.py\n--- a/astropy/units/qu(...TRUNCATED)
"diff --git a/astropy/units/tests/test_quantity.py b/astropy/units/tests/test_quantity.py\n--- a/ast(...TRUNCATED)
5.1
"[\"astropy/units/tests/test_quantity_info.py::TestQuantityInfo::test_unary_op\", \"astropy/units/te(...TRUNCATED)
"[\"astropy/units/tests/test_quantity.py::TestQuantityCreation::test_1\", \"astropy/units/tests/test(...TRUNCATED)
5f74eacbcc7fff707a44d8eb58adaa514cb7dcb5
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
-