metadata
dict
text
stringlengths
0
40.6M
id
stringlengths
14
255
{ "filename": "__init__.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py2/plotly/validators/volume/colorbar/title/__init__.py", "type": "Python" }
import sys if sys.version_info < (3, 7): from ._text import TextValidator from ._side import SideValidator from ._font import FontValidator else: from _plotly_utils.importers import relative_import __all__, __getattr__, __dir__ = relative_import( __name__, [], ["._text.TextValidator", "._side.SideValidator", "._font.FontValidator"], )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py2@plotly@validators@volume@colorbar@title@__init__.py@.PATH_END.py
{ "filename": "ticks.py", "repo_name": "astropy/astropy", "repo_path": "astropy_extracted/astropy-main/astropy/visualization/wcsaxes/ticks.py", "type": "Python" }
# Licensed under a 3-clause BSD style license - see LICENSE.rst from collections import defaultdict import numpy as np from matplotlib import rcParams from matplotlib.lines import Line2D, Path from matplotlib.transforms import Affine2D class Ticks(Line2D): """ Ticks are derived from Line2D, and note that ticks themselves are markers. Thus, you should use set_mec, set_mew, etc. To change the tick size (length), you need to use set_ticksize. To change the direction of the ticks (ticks are in opposite direction of ticklabels by default), use set_tick_out(False). Note that Matplotlib's defaults dictionary :data:`~matplotlib.rcParams` contains default settings (color, size, width) of the form `xtick.*` and `ytick.*`. In a WCS projection, there may not be a clear relationship between axes of the projection and 'x' or 'y' axes. For this reason, we read defaults from `xtick.*`. The following settings affect the default appearance of ticks: * `xtick.direction` * `xtick.major.size` * `xtick.major.width` * `xtick.minor.size` * `xtick.color` Attributes ---------- ticks_locs : dict This is set when the ticks are drawn, and is a mapping from axis to the locations of the ticks for that axis. """ def __init__(self, frame=None, ticksize=None, **kwargs): self._frame = frame if ticksize is None: ticksize = rcParams["xtick.major.size"] self.set_ticksize(ticksize) self.set_minor_ticksize(rcParams["xtick.minor.size"]) self.set_tick_out(rcParams["xtick.direction"] == "out") self.clear() line2d_kwargs = { "color": rcParams["xtick.color"], "linewidth": rcParams["xtick.major.width"], } line2d_kwargs.update(kwargs) Line2D.__init__(self, [0.0], [0.0], **line2d_kwargs) self.set_visible_axes("all") self._display_minor_ticks = False def display_minor_ticks(self, display_minor_ticks): self._display_minor_ticks = display_minor_ticks def get_display_minor_ticks(self): return self._display_minor_ticks def set_tick_out(self, tick_out): """ set True if tick need to be rotated by 180 degree. """ self._tick_out = tick_out def get_tick_out(self): """ Return True if the tick will be rotated by 180 degree. """ return self._tick_out def set_ticksize(self, ticksize): """ set length of the ticks in points. """ self._ticksize = ticksize def get_ticksize(self): """ Return length of the ticks in points. """ return self._ticksize def set_minor_ticksize(self, ticksize): """ set length of the minor ticks in points. """ self._minor_ticksize = ticksize def get_minor_ticksize(self): """ Return length of the minor ticks in points. """ return self._minor_ticksize @property def out_size(self): if self._tick_out: return self._ticksize else: return 0.0 def set_visible_axes(self, visible_axes): self._visible_axes = visible_axes def get_visible_axes(self): if self._visible_axes == "all": return list(self._frame.keys()) else: return [x for x in self._visible_axes if x in self._frame or x == "#"] def clear(self): self.world = defaultdict(list) self.pixel = defaultdict(list) self.angle = defaultdict(list) self.disp = defaultdict(list) self.minor_world = defaultdict(list) self.minor_pixel = defaultdict(list) self.minor_angle = defaultdict(list) self.minor_disp = defaultdict(list) def add(self, axis, world, pixel, angle, axis_displacement): self.world[axis].append(world) self.pixel[axis].append(pixel) self.angle[axis].append(angle) self.disp[axis].append(axis_displacement) def get_minor_world(self): return self.minor_world def add_minor( self, minor_axis, minor_world, minor_pixel, minor_angle, minor_axis_displacement ): self.minor_world[minor_axis].append(minor_world) self.minor_pixel[minor_axis].append(minor_pixel) self.minor_angle[minor_axis].append(minor_angle) self.minor_disp[minor_axis].append(minor_axis_displacement) def __len__(self): return len(self.world) _tickvert_path = Path([[0.0, 0.0], [1.0, 0.0]]) def draw(self, renderer): """ Draw the ticks. """ self.ticks_locs = defaultdict(list) if not self.get_visible(): return offset = renderer.points_to_pixels(self.get_ticksize()) self._draw_ticks(renderer, self.pixel, self.angle, offset) if self._display_minor_ticks: offset = renderer.points_to_pixels(self.get_minor_ticksize()) self._draw_ticks(renderer, self.minor_pixel, self.minor_angle, offset) def _draw_ticks(self, renderer, pixel_array, angle_array, offset): """ Draw the minor ticks. """ path_trans = self.get_transform() gc = renderer.new_gc() gc.set_foreground(self.get_color()) gc.set_alpha(self.get_alpha()) gc.set_linewidth(self.get_linewidth()) marker_scale = Affine2D().scale(offset, offset) marker_rotation = Affine2D() marker_transform = marker_scale + marker_rotation initial_angle = 180.0 if self.get_tick_out() else 0.0 for axis in self.get_visible_axes(): if axis == "#": continue if axis not in pixel_array: continue for loc, angle in zip(pixel_array[axis], angle_array[axis]): # Set the rotation for this tick marker_rotation.rotate_deg(initial_angle + angle) # Draw the markers locs = path_trans.transform_non_affine(np.array([loc, loc])) renderer.draw_markers( gc, self._tickvert_path, marker_transform, Path(locs), path_trans.get_affine(), ) # Reset the tick rotation before moving to the next tick marker_rotation.clear() self.ticks_locs[axis].append(locs) gc.restore()
astropyREPO_NAMEastropyPATH_START.@astropy_extracted@astropy-main@astropy@visualization@wcsaxes@ticks.py@.PATH_END.py
{ "filename": "test_ebl.py", "repo_name": "andreatramacere/jetset", "repo_path": "jetset_extracted/jetset-master/jetset/tests/test_ebl.py", "type": "Python" }
import pytest from .base_class import TestBase class TestEBL(TestBase): def integration_suite(self,plot=False): self.test_ebl(plot=plot) self.test_ebl_jet(plot=plot) def test_ebl(self,plot=True): import numpy as np import matplotlib.pyplot as plt from jetset.template_2Dmodel import EBLAbsorptionTemplate ebl_dominguez = EBLAbsorptionTemplate.from_name('Dominguez_2010_v2011') ebl_finke = EBLAbsorptionTemplate.from_name('Finke_2010') ebl_franceschini = EBLAbsorptionTemplate.from_name('Franceschini_2008') z = 0.1 nu = np.logspace(20, 30, 100) ebl_dominguez.parameters.z_cosm.val = z ebl_dominguez.eval(nu=nu) ebl_finke.parameters.z_cosm.val = z ebl_finke.eval(nu=nu) ebl_franceschini.parameters.z_cosm.val = z ebl_franceschini.eval(nu=nu) if plot is True: plt.figure() ebl_franceschini.eval(nu=nu) p=ebl_dominguez.plot_model() ebl_finke.plot_model(p) ebl_franceschini.plot_model(p) p.setlim(y_max=1,y_min=-10,x_max=29) z = 3 nu = np.logspace(20, 23, 100) ebl_dominguez.parameters.z_cosm.val = z ebl_dominguez.eval(nu=nu) ebl_finke.parameters.z_cosm.val = z ebl_finke.eval(nu=nu) ebl_franceschini.parameters.z_cosm.val = z ebl_franceschini.eval(nu=nu) if plot is True: plt.figure() ebl_franceschini.eval(nu=nu) p=ebl_dominguez.plot_model() ebl_finke.plot_model(p) ebl_franceschini.plot_model(p) p.setlim(y_max=1,y_min=-.1,x_max=23) nu = 1E26 z_range = np.linspace(0.001, 1, 100) y_fr = np.zeros(z_range.size) y_fi = np.zeros(z_range.size) y_do = np.zeros(z_range.size) for ID, z in enumerate(z_range): ebl_franceschini.parameters.z_cosm.val = z ebl_finke.parameters.z_cosm.val = z ebl_dominguez.parameters.z_cosm.val = z y_fr[ID] = ebl_franceschini.eval(nu=nu, get_model=True)[0] y_fi[ID] = ebl_finke.eval(nu=nu, get_model=True)[0] y_do[ID] = ebl_dominguez.eval(nu=nu, get_model=True)[0] if plot is True: plt.figure() plt.plot(z_range, y_fr, label='%s' % ebl_franceschini.name)[0] plt.plot(z_range, y_fi, label='%s' % ebl_finke.name)[0] plt.plot(z_range, y_do, label='%s' % ebl_dominguez.name)[0] plt.xlabel('z') plt.ylabel(r'$exp^{-\tau}$') plt.legend() plt.semilogy() plt.title(r'$\nu=%1.1E Hz$' % nu) z_range = np.linspace(0.001, 1, 100) y_fr = np.zeros(z_range.size) y_fi = np.zeros(z_range.size) y_do = np.zeros(z_range.size) nu = 1E27 for ID, z in enumerate(z_range): ebl_franceschini.parameters.z_cosm.val = z ebl_finke.parameters.z_cosm.val = z ebl_dominguez.parameters.z_cosm.val = z y_fr[ID] = ebl_franceschini.eval(nu=nu, get_model=True)[0] y_fi[ID] = ebl_finke.eval(nu=nu, get_model=True)[0] y_do[ID] = ebl_dominguez.eval(nu=nu, get_model=True)[0] if plot is True: plt.figure() plt.plot(z_range, y_fr, label='%s' % ebl_franceschini.name) plt.plot(z_range, y_fi, label='%s' % ebl_finke.name) plt.plot(z_range, y_do, label='%s' % ebl_dominguez.name) plt.xlabel('z') plt.ylabel(r'$exp^{-\tau}$') plt.legend() plt.semilogy() plt.title(r'$\nu=%1.1E Hz$' % nu) def test_ebl_jet(self,plot=True): from jetset.jet_model import Jet from jetset.template_2Dmodel import EBLAbsorptionTemplate from jetset.model_manager import FitModel my_jet = Jet(electron_distribution='lppl', name='jet_flaring') my_jet.parameters.z_cosm.val = 0.01 ebl_franceschini = EBLAbsorptionTemplate.from_name('Franceschini_2008') composite_model = FitModel(nu_size=500, name='EBL corrected') composite_model.add_component(my_jet) composite_model.add_component(ebl_franceschini) composite_model.show_pars() composite_model.link_par(par_name='z_cosm', from_model='Franceschini_2008', to_model='jet_flaring') v=0.03001 my_jet.parameters.z_cosm.val = v assert (composite_model.Franceschini_2008.parameters.z_cosm.val==v) assert (composite_model.Franceschini_2008.parameters.z_cosm.linked==True) assert (composite_model.Franceschini_2008.parameters.z_cosm.val == composite_model.jet_flaring.parameters.z_cosm.val) composite_model.composite_expr = '%s*%s'%(my_jet.name,ebl_franceschini.name) composite_model.eval() if plot is True: composite_model.plot_model() composite_model.save_model('ebl_jet.pkl') new_composite_model=FitModel.load_model('ebl_jet.pkl') v=2.0 new_composite_model.jet_flaring.parameters.z_cosm.val=v assert (new_composite_model.Franceschini_2008.parameters.z_cosm.val == v) assert (new_composite_model.Franceschini_2008.parameters.z_cosm.linked == True) def test_ebl_jet_fit(self,plot=True,sed_number=2,minimizer='lsb'): from .test_model_fit import prepare_model template, jet,sed_data = prepare_model(sed_number=sed_number) from jetset.template_2Dmodel import EBLAbsorptionTemplate ebl_franceschini = EBLAbsorptionTemplate.from_name('Franceschini_2008') ebl_franceschini.show_model() from jetset.model_manager import FitModel composite_model = FitModel(nu_size=500, name='EBL corrected', template=template) composite_model.add_component(jet) composite_model.add_component(ebl_franceschini) composite_model.link_par(par_name='z_cosm', from_model='Franceschini_2008', to_model=jet.name) if template is not None: composite_model.composite_expr = '(%s+host_galaxy)*Franceschini_2008'%jet.name else: composite_model.composite_expr = '(%s)*Franceschini_2008' % jet.name assert (composite_model.Franceschini_2008.parameters.z_cosm.val == composite_model.jet_leptonic.parameters.z_cosm.val) assert (composite_model.Franceschini_2008.parameters.z_cosm.linked is True) composite_model.show_model() composite_model.eval() if plot is True: composite_model.plot_model() from jetset.minimizer import ModelMinimizer composite_model.freeze(jet, 'R_H') composite_model.freeze(jet, 'z_cosm') if minimizer == 'minuit': composite_model.jet_leptonic.parameters.gmin.fit_range = [2, 200] composite_model.jet_leptonic.parameters.gmax.fit_range = [1E5, 1E7] if template is not None: composite_model.host_galaxy.parameters.nuFnu_p_host.frozen = False composite_model.host_galaxy.parameters.nu_scale.frozen = True composite_model.jet_leptonic.parameters.beam_obj.fit_range = [5, 50] composite_model.jet_leptonic.parameters.R.fit_range = [10 ** 15.5, 10 ** 17.5] composite_model.jet_leptonic.parameters.gmax.fit_range = [1E4, 1E8] composite_model.jet_leptonic.nu_size = 200 composite_model.jet_leptonic.IC_nu_size = 100 model_minimizer = ModelMinimizer(minimizer) best_fit = model_minimizer.fit(composite_model, sed_data, 10 ** 11., 10 ** 29.0, fitname='SSC-best-fit-minuit', repeat=1) best_fit.show_report() best_fit.save_report('best-fit-%s-report.pkl' % minimizer) best_fit.bestfit_table.write('best-fit-%s-report.ecsv' % minimizer,overwrite=True) model_minimizer.save_model('model_minimizer_%s.pkl' % minimizer) model_minimizer = ModelMinimizer.load_model('model_minimizer_%s.pkl' % minimizer) composite_model.save_model('fit_model_%s.pkl' % minimizer)
andreatramacereREPO_NAMEjetsetPATH_START.@jetset_extracted@jetset-master@jetset@tests@test_ebl.py@.PATH_END.py
{ "filename": "_sizemode.py", "repo_name": "plotly/plotly.py", "repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/validators/scattermap/marker/_sizemode.py", "type": "Python" }
import _plotly_utils.basevalidators class SizemodeValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="sizemode", parent_name="scattermap.marker", **kwargs ): super(SizemodeValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), values=kwargs.pop("values", ["diameter", "area"]), **kwargs, )
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@validators@scattermap@marker@_sizemode.py@.PATH_END.py
{ "filename": "versioneer.py", "repo_name": "PAHdb/pyPAHdb", "repo_path": "pyPAHdb_extracted/pyPAHdb-master/versioneer.py", "type": "Python" }
# Version: 0.22 """The Versioneer - like a rocketeer, but for versions. The Versioneer ============== * like a rocketeer, but for versions! * https://github.com/python-versioneer/python-versioneer * Brian Warner * License: Public Domain * Compatible with: Python 3.6, 3.7, 3.8, 3.9, 3.10 and pypy3 * [![Latest Version][pypi-image]][pypi-url] * [![Build Status][travis-image]][travis-url] This is a tool for managing a recorded version number in distutils/setuptools-based python projects. The goal is to remove the tedious and error-prone "update the embedded version string" step from your release process. Making a new release should be as easy as recording a new tag in your version-control system, and maybe making new tarballs. ## Quick Install * `pip install versioneer` to somewhere in your $PATH * add a `[versioneer]` section to your setup.cfg (see [Install](INSTALL.md)) * run `versioneer install` in your source tree, commit the results * Verify version information with `python setup.py version` ## Version Identifiers Source trees come from a variety of places: * a version-control system checkout (mostly used by developers) * a nightly tarball, produced by build automation * a snapshot tarball, produced by a web-based VCS browser, like github's "tarball from tag" feature * a release tarball, produced by "setup.py sdist", distributed through PyPI Within each source tree, the version identifier (either a string or a number, this tool is format-agnostic) can come from a variety of places: * ask the VCS tool itself, e.g. "git describe" (for checkouts), which knows about recent "tags" and an absolute revision-id * the name of the directory into which the tarball was unpacked * an expanded VCS keyword ($Id$, etc) * a `_version.py` created by some earlier build step For released software, the version identifier is closely related to a VCS tag. Some projects use tag names that include more than just the version string (e.g. "myproject-1.2" instead of just "1.2"), in which case the tool needs to strip the tag prefix to extract the version identifier. For unreleased software (between tags), the version identifier should provide enough information to help developers recreate the same tree, while also giving them an idea of roughly how old the tree is (after version 1.2, before version 1.3). Many VCS systems can report a description that captures this, for example `git describe --tags --dirty --always` reports things like "0.7-1-g574ab98-dirty" to indicate that the checkout is one revision past the 0.7 tag, has a unique revision id of "574ab98", and is "dirty" (it has uncommitted changes). The version identifier is used for multiple purposes: * to allow the module to self-identify its version: `myproject.__version__` * to choose a name and prefix for a 'setup.py sdist' tarball ## Theory of Operation Versioneer works by adding a special `_version.py` file into your source tree, where your `__init__.py` can import it. This `_version.py` knows how to dynamically ask the VCS tool for version information at import time. `_version.py` also contains `$Revision$` markers, and the installation process marks `_version.py` to have this marker rewritten with a tag name during the `git archive` command. As a result, generated tarballs will contain enough information to get the proper version. To allow `setup.py` to compute a version too, a `versioneer.py` is added to the top level of your source tree, next to `setup.py` and the `setup.cfg` that configures it. This overrides several distutils/setuptools commands to compute the version when invoked, and changes `setup.py build` and `setup.py sdist` to replace `_version.py` with a small static file that contains just the generated version data. ## Installation See [INSTALL.md](./INSTALL.md) for detailed installation instructions. ## Version-String Flavors Code which uses Versioneer can learn about its version string at runtime by importing `_version` from your main `__init__.py` file and running the `get_versions()` function. From the "outside" (e.g. in `setup.py`), you can import the top-level `versioneer.py` and run `get_versions()`. Both functions return a dictionary with different flavors of version information: * `['version']`: A condensed version string, rendered using the selected style. This is the most commonly used value for the project's version string. The default "pep440" style yields strings like `0.11`, `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the "Styles" section below for alternative styles. * `['full-revisionid']`: detailed revision identifier. For Git, this is the full SHA1 commit id, e.g. "1076c978a8d3cfc70f408fe5974aa6c092c949ac". * `['date']`: Date and time of the latest `HEAD` commit. For Git, it is the commit date in ISO 8601 format. This will be None if the date is not available. * `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that this is only accurate if run in a VCS checkout, otherwise it is likely to be False or None * `['error']`: if the version string could not be computed, this will be set to a string describing the problem, otherwise it will be None. It may be useful to throw an exception in setup.py if this is set, to avoid e.g. creating tarballs with a version string of "unknown". Some variants are more useful than others. Including `full-revisionid` in a bug report should allow developers to reconstruct the exact code being tested (or indicate the presence of local changes that should be shared with the developers). `version` is suitable for display in an "about" box or a CLI `--version` output: it can be easily compared against release notes and lists of bugs fixed in various releases. The installer adds the following text to your `__init__.py` to place a basic version in `YOURPROJECT.__version__`: from ._version import get_versions __version__ = get_versions()['version'] del get_versions ## Styles The setup.cfg `style=` configuration controls how the VCS information is rendered into a version string. The default style, "pep440", produces a PEP440-compliant string, equal to the un-prefixed tag name for actual releases, and containing an additional "local version" section with more detail for in-between builds. For Git, this is TAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags --dirty --always`. For example "0.11+2.g1076c97.dirty" indicates that the tree is like the "1076c97" commit but has uncommitted changes (".dirty"), and that this commit is two revisions ("+2") beyond the "0.11" tag. For released software (exactly equal to a known tag), the identifier will only contain the stripped tag, e.g. "0.11". Other styles are available. See [details.md](details.md) in the Versioneer source tree for descriptions. ## Debugging Versioneer tries to avoid fatal errors: if something goes wrong, it will tend to return a version of "0+unknown". To investigate the problem, run `setup.py version`, which will run the version-lookup code in a verbose mode, and will display the full contents of `get_versions()` (including the `error` string, which may help identify what went wrong). ## Known Limitations Some situations are known to cause problems for Versioneer. This details the most significant ones. More can be found on Github [issues page](https://github.com/python-versioneer/python-versioneer/issues). ### Subprojects Versioneer has limited support for source trees in which `setup.py` is not in the root directory (e.g. `setup.py` and `.git/` are *not* siblings). The are two common reasons why `setup.py` might not be in the root: * Source trees which contain multiple subprojects, such as [Buildbot](https://github.com/buildbot/buildbot), which contains both "master" and "slave" subprojects, each with their own `setup.py`, `setup.cfg`, and `tox.ini`. Projects like these produce multiple PyPI distributions (and upload multiple independently-installable tarballs). * Source trees whose main purpose is to contain a C library, but which also provide bindings to Python (and perhaps other languages) in subdirectories. Versioneer will look for `.git` in parent directories, and most operations should get the right version string. However `pip` and `setuptools` have bugs and implementation details which frequently cause `pip install .` from a subproject directory to fail to find a correct version string (so it usually defaults to `0+unknown`). `pip install --editable .` should work correctly. `setup.py install` might work too. Pip-8.1.1 is known to have this problem, but hopefully it will get fixed in some later version. [Bug #38](https://github.com/python-versioneer/python-versioneer/issues/38) is tracking this issue. The discussion in [PR #61](https://github.com/python-versioneer/python-versioneer/pull/61) describes the issue from the Versioneer side in more detail. [pip PR#3176](https://github.com/pypa/pip/pull/3176) and [pip PR#3615](https://github.com/pypa/pip/pull/3615) contain work to improve pip to let Versioneer work correctly. Versioneer-0.16 and earlier only looked for a `.git` directory next to the `setup.cfg`, so subprojects were completely unsupported with those releases. ### Editable installs with setuptools <= 18.5 `setup.py develop` and `pip install --editable .` allow you to install a project into a virtualenv once, then continue editing the source code (and test) without re-installing after every change. "Entry-point scripts" (`setup(entry_points={"console_scripts": ..})`) are a convenient way to specify executable scripts that should be installed along with the python package. These both work as expected when using modern setuptools. When using setuptools-18.5 or earlier, however, certain operations will cause `pkg_resources.DistributionNotFound` errors when running the entrypoint script, which must be resolved by re-installing the package. This happens when the install happens with one version, then the egg_info data is regenerated while a different version is checked out. Many setup.py commands cause egg_info to be rebuilt (including `sdist`, `wheel`, and installing into a different virtualenv), so this can be surprising. [Bug #83](https://github.com/python-versioneer/python-versioneer/issues/83) describes this one, but upgrading to a newer version of setuptools should probably resolve it. ## Updating Versioneer To upgrade your project to a new release of Versioneer, do the following: * install the new Versioneer (`pip install -U versioneer` or equivalent) * edit `setup.cfg`, if necessary, to include any new configuration settings indicated by the release notes. See [UPGRADING](./UPGRADING.md) for details. * re-run `versioneer install` in your source tree, to replace `SRC/_version.py` * commit any changed files ## Future Directions This tool is designed to make it easily extended to other version-control systems: all VCS-specific components are in separate directories like src/git/ . The top-level `versioneer.py` script is assembled from these components by running make-versioneer.py . In the future, make-versioneer.py will take a VCS name as an argument, and will construct a version of `versioneer.py` that is specific to the given VCS. It might also take the configuration arguments that are currently provided manually during installation by editing setup.py . Alternatively, it might go the other direction and include code from all supported VCS systems, reducing the number of intermediate scripts. ## Similar projects * [setuptools_scm](https://github.com/pypa/setuptools_scm/) - a non-vendored build-time dependency * [minver](https://github.com/jbweston/miniver) - a lightweight reimplementation of versioneer * [versioningit](https://github.com/jwodder/versioningit) - a PEP 518-based setuptools plugin ## License To make Versioneer easier to embed, all its code is dedicated to the public domain. The `_version.py` that it creates is also in the public domain. Specifically, both are released under the Creative Commons "Public Domain Dedication" license (CC0-1.0), as described in https://creativecommons.org/publicdomain/zero/1.0/ . [pypi-image]: https://img.shields.io/pypi/v/versioneer.svg [pypi-url]: https://pypi.python.org/pypi/versioneer/ [travis-image]: https://img.shields.io/travis/com/python-versioneer/python-versioneer.svg [travis-url]: https://travis-ci.com/github/python-versioneer/python-versioneer """ # pylint:disable=invalid-name,import-outside-toplevel,missing-function-docstring # pylint:disable=missing-class-docstring,too-many-branches,too-many-statements # pylint:disable=raise-missing-from,too-many-lines,too-many-locals,import-error # pylint:disable=too-few-public-methods,redefined-outer-name,consider-using-with # pylint:disable=attribute-defined-outside-init,too-many-arguments import configparser import errno import json import os import re import subprocess import sys from typing import Callable, Dict import functools class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_root(): """Get the project root directory. We require that all commands are run from the project root, i.e. the directory that contains setup.py, setup.cfg, and versioneer.py . """ root = os.path.realpath(os.path.abspath(os.getcwd())) setup_py = os.path.join(root, "setup.py") versioneer_py = os.path.join(root, "versioneer.py") if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): # allow 'python path/to/setup.py COMMAND' root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) setup_py = os.path.join(root, "setup.py") versioneer_py = os.path.join(root, "versioneer.py") if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): err = ("Versioneer was unable to run the project root directory. " "Versioneer requires setup.py to be executed from " "its immediate directory (like 'python setup.py COMMAND'), " "or in a way that lets it use sys.argv[0] to find the root " "(like 'python path/to/setup.py COMMAND').") raise VersioneerBadRootError(err) try: # Certain runtime workflows (setup.py install/develop in a setuptools # tree) execute all dependencies in a single python process, so # "versioneer" may be imported multiple times, and python's shared # module-import table will cache the first one. So we can't use # os.path.dirname(__file__), as that will find whichever # versioneer.py was first imported, even in later projects. my_path = os.path.realpath(os.path.abspath(__file__)) me_dir = os.path.normcase(os.path.splitext(my_path)[0]) vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0]) if me_dir != vsr_dir: print("Warning: build in %s is using versioneer.py from %s" % (os.path.dirname(my_path), versioneer_py)) except NameError: pass return root def get_config_from_root(root): """Read the project setup.cfg file to determine Versioneer config.""" # This might raise OSError (if setup.cfg is missing), or # configparser.NoSectionError (if it lacks a [versioneer] section), or # configparser.NoOptionError (if it lacks "VCS="). See the docstring at # the top of versioneer.py for instructions on writing your setup.cfg . setup_cfg = os.path.join(root, "setup.cfg") parser = configparser.ConfigParser() with open(setup_cfg, "r") as cfg_file: parser.read_file(cfg_file) VCS = parser.get("versioneer", "VCS") # mandatory # Dict-like interface for non-mandatory entries section = parser["versioneer"] cfg = VersioneerConfig() cfg.VCS = VCS cfg.style = section.get("style", "") cfg.versionfile_source = section.get("versionfile_source") cfg.versionfile_build = section.get("versionfile_build") cfg.tag_prefix = section.get("tag_prefix") if cfg.tag_prefix in ("''", '""'): cfg.tag_prefix = "" cfg.parentdir_prefix = section.get("parentdir_prefix") cfg.verbose = section.get("verbose") return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" # these dictionaries contain VCS-specific tools LONG_VERSION_PY: Dict[str, str] = {} HANDLERS: Dict[str, Dict[str, Callable]] = {} def register_vcs_handler(vcs, method): # decorator """Create decorator to mark a method as the handler of a VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" HANDLERS.setdefault(vcs, {})[method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) process = None popen_kwargs = {} if sys.platform == "win32": # This hides the console window if pythonw.exe is used startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW popen_kwargs["startupinfo"] = startupinfo for command in commands: try: dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git process = subprocess.Popen([command] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None), **popen_kwargs) break except OSError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None, None stdout = process.communicate()[0].strip().decode() if process.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) print("stdout was %s" % stdout) return None, process.returncode return stdout, process.returncode LONG_VERSION_PY['git'] = r''' # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.22 (https://github.com/python-versioneer/python-versioneer) """Git implementation of _version.py.""" import errno import os import re import subprocess import sys from typing import Callable, Dict import functools def get_keywords(): """Get the keywords needed to look up the version information.""" # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" git_date = "%(DOLLAR)sFormat:%%ci%(DOLLAR)s" keywords = {"refnames": git_refnames, "full": git_full, "date": git_date} return keywords class VersioneerConfig: """Container for Versioneer configuration parameters.""" def get_config(): """Create, populate and return the VersioneerConfig() object.""" # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "%(STYLE)s" cfg.tag_prefix = "%(TAG_PREFIX)s" cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" cfg.verbose = False return cfg class NotThisMethod(Exception): """Exception raised if a method is not valid for the current scenario.""" LONG_VERSION_PY: Dict[str, str] = {} HANDLERS: Dict[str, Dict[str, Callable]] = {} def register_vcs_handler(vcs, method): # decorator """Create decorator to mark a method as the handler of a VCS.""" def decorate(f): """Store f in HANDLERS[vcs][method].""" if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None): """Call the given command(s).""" assert isinstance(commands, list) process = None popen_kwargs = {} if sys.platform == "win32": # This hides the console window if pythonw.exe is used startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW popen_kwargs["startupinfo"] = startupinfo for command in commands: try: dispcmd = str([command] + args) # remember shell=False, so use git.cmd on windows, not just git process = subprocess.Popen([command] + args, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None), **popen_kwargs) break except OSError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %%s" %% dispcmd) print(e) return None, None else: if verbose: print("unable to find command, tried %%s" %% (commands,)) return None, None stdout = process.communicate()[0].strip().decode() if process.returncode != 0: if verbose: print("unable to run %%s (error)" %% dispcmd) print("stdout was %%s" %% stdout) return None, process.returncode return stdout, process.returncode def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %%s but none started with prefix %%s" %% (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: with open(versionfile_abs, "r") as fobj: for line in fobj: if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) except OSError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if "refnames" not in keywords: raise NotThisMethod("Short version file found") date = keywords.get("date") if date is not None: # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] # git-2.2.0 added "%%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %%d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = {r for r in refs if re.search(r'\d', r)} if verbose: print("discarding '%%s', no digits" %% ",".join(refs - tags)) if verbose: print("likely tags: %%s" %% ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] # Filter out refs that exactly match prefix or that don't start # with a number once the prefix is stripped (mostly a concern # when prefix is '') if not re.match(r'\d', r): continue if verbose: print("picking %%s" %% r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] # GIT_DIR can interfere with correct operation of Versioneer. # It may be intended to be passed to the Versioneer-versioned project, # but that should not change where we get our version from. env = os.environ.copy() env.pop("GIT_DIR", None) runner = functools.partial(runner, env=env) _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %%s not under git control" %% root) raise NotThisMethod("'git rev-parse --git-dir' returned error") MATCH_ARGS = ["--match", "%%s*" %% tag_prefix] if tag_prefix else [] # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = runner(GITS, ["describe", "--tags", "--dirty", "--always", "--long", *MATCH_ARGS], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) # --abbrev-ref was added in git-1.6.3 if rc != 0 or branch_name is None: raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") branch_name = branch_name.strip() if branch_name == "HEAD": # If we aren't exactly on a branch, pick a branch which represents # the current commit. If all else fails, we are on a branchless # commit. branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) # --contains was added in git-1.5.4 if rc != 0 or branches is None: raise NotThisMethod("'git branch --contains' returned error") branches = branches.split("\n") # Remove the first line if we're running detached if "(" in branches[0]: branches.pop(0) # Strip off the leading "* " from the list of branches. branches = [branch[2:] for branch in branches] if "master" in branches: branch_name = "master" elif not branches: branch_name = None else: # Pick the first branch that is returned. Good or bad. branch_name = branches[0] pieces["branch"] = branch_name # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparsable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%%s'" %% describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%%s' doesn't start with prefix '%%s'" print(fmt %% (full_tag, tag_prefix)) pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" %% (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = runner(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = runner(GITS, ["show", "-s", "--format=%%ci", "HEAD"], cwd=root)[0].strip() # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_branch(pieces): """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . The ".dev0" means not master branch. Note that .dev0 sorts backwards (a feature branch will appear "older" than the master branch). Exceptions: 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0" if pieces["branch"] != "master": rendered += ".dev0" rendered += "+untagged.%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def pep440_split_post(ver): """Split pep440 version string at the post-release segment. Returns the release segments before the post-release and the post-release version number (or -1 if no post-release segment is present). """ vc = str.split(ver, ".post") return vc[0], int(vc[1] or 0) if len(vc) == 2 else None def render_pep440_pre(pieces): """TAG[.postN.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post0.devDISTANCE """ if pieces["closest-tag"]: if pieces["distance"]: # update the post release segment tag_version, post_version = pep440_split_post(pieces["closest-tag"]) rendered = tag_version if post_version is not None: rendered += ".post%%d.dev%%d" %% (post_version+1, pieces["distance"]) else: rendered += ".post0.dev%%d" %% (pieces["distance"]) else: # no commits, use the tag as the version rendered = pieces["closest-tag"] else: # exception #1 rendered = "0.post0.dev%%d" %% pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%%s" %% pieces["short"] else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%%s" %% pieces["short"] return rendered def render_pep440_post_branch(pieces): """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . The ".dev0" means not master branch. Exceptions: 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%%s" %% pieces["short"] if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += "+g%%s" %% pieces["short"] if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-branch": rendered = render_pep440_branch(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-post-branch": rendered = render_pep440_post_branch(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%%s'" %% style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for _ in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree", "date": None} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} ''' @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: with open(versionfile_abs, "r") as fobj: for line in fobj: if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) if line.strip().startswith("git_date ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["date"] = mo.group(1) except OSError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): """Get version information from git keywords.""" if "refnames" not in keywords: raise NotThisMethod("Short version file found") date = keywords.get("date") if date is not None: # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant # datestamp. However we prefer "%ci" (which expands to an "ISO-8601 # -like" string, which we must then edit to make compliant), because # it's been around since git-1.5.3, and it's too difficult to # discover which version we're using, or to work around using an # older one. date = date.strip().replace(" ", "T", 1).replace(" ", "", 1) refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = {r.strip() for r in refnames.strip("()").split(",")} # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = {r[len(TAG):] for r in refs if r.startswith(TAG)} if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = {r for r in refs if re.search(r'\d', r)} if verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] # Filter out refs that exactly match prefix or that don't start # with a number once the prefix is stripped (mostly a concern # when prefix is '') if not re.match(r'\d', r): continue if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None, "date": date} # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags", "date": None} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, runner=run_command): """Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] # GIT_DIR can interfere with correct operation of Versioneer. # It may be intended to be passed to the Versioneer-versioned project, # but that should not change where we get our version from. env = os.environ.copy() env.pop("GIT_DIR", None) runner = functools.partial(runner, env=env) _, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True) if rc != 0: if verbose: print("Directory %s not under git control" % root) raise NotThisMethod("'git rev-parse --git-dir' returned error") MATCH_ARGS = ["--match", "%s*" % tag_prefix] if tag_prefix else [] # if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty] # if there isn't one, this yields HEX[-dirty] (no NUM) describe_out, rc = runner(GITS, ["describe", "--tags", "--dirty", "--always", "--long", *MATCH_ARGS], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out, rc = runner(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) # --abbrev-ref was added in git-1.6.3 if rc != 0 or branch_name is None: raise NotThisMethod("'git rev-parse --abbrev-ref' returned error") branch_name = branch_name.strip() if branch_name == "HEAD": # If we aren't exactly on a branch, pick a branch which represents # the current commit. If all else fails, we are on a branchless # commit. branches, rc = runner(GITS, ["branch", "--contains"], cwd=root) # --contains was added in git-1.5.4 if rc != 0 or branches is None: raise NotThisMethod("'git branch --contains' returned error") branches = branches.split("\n") # Remove the first line if we're running detached if "(" in branches[0]: branches.pop(0) # Strip off the leading "* " from the list of branches. branches = [branch[2:] for branch in branches] if "master" in branches: branch_name = "master" elif not branches: branch_name = None else: # Pick the first branch that is returned. Good or bad. branch_name = branches[0] pieces["branch"] = branch_name # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparsable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out, rc = runner(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits # commit date: see ISO-8601 comment in git_versions_from_keywords() date = runner(GITS, ["show", "-s", "--format=%ci", "HEAD"], cwd=root)[0].strip() # Use only the last line. Previous lines may contain GPG signature # information. date = date.splitlines()[-1] pieces["date"] = date.strip().replace(" ", "T", 1).replace(" ", "", 1) return pieces def do_vcs_install(manifest_in, versionfile_source, ipy): """Git-specific installation logic for Versioneer. For Git, this means creating/changing .gitattributes to mark _version.py for export-subst keyword substitution. """ GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] files = [manifest_in, versionfile_source] if ipy: files.append(ipy) try: my_path = __file__ if my_path.endswith(".pyc") or my_path.endswith(".pyo"): my_path = os.path.splitext(my_path)[0] + ".py" versioneer_file = os.path.relpath(my_path) except NameError: versioneer_file = "versioneer.py" files.append(versioneer_file) present = False try: with open(".gitattributes", "r") as fobj: for line in fobj: if line.strip().startswith(versionfile_source): if "export-subst" in line.strip().split()[1:]: present = True break except OSError: pass if not present: with open(".gitattributes", "a+") as fobj: fobj.write(f"{versionfile_source} export-subst\n") files.append(".gitattributes") run_command(GITS, ["add", "--"] + files) def versions_from_parentdir(parentdir_prefix, root, verbose): """Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory """ rootdirs = [] for _ in range(3): dirname = os.path.basename(root) if dirname.startswith(parentdir_prefix): return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None, "date": None} rootdirs.append(root) root = os.path.dirname(root) # up a level if verbose: print("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") SHORT_VERSION_PY = """ # This file was generated by 'versioneer.py' (0.22) from # revision-control system data, or from the parent directory name of an # unpacked source archive. Distribution tarballs contain a pre-generated copy # of this file. import json version_json = ''' %s ''' # END VERSION_JSON def get_versions(): return json.loads(version_json) """ def versions_from_file(filename): """Try to determine the version from _version.py if present.""" try: with open(filename) as f: contents = f.read() except OSError: raise NotThisMethod("unable to read _version.py") mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", contents, re.M | re.S) if not mo: mo = re.search(r"version_json = '''\r\n(.*)''' # END VERSION_JSON", contents, re.M | re.S) if not mo: raise NotThisMethod("no version_json in _version.py") return json.loads(mo.group(1)) def write_to_version_file(filename, versions): """Write the given version number to the given _version.py file.""" os.unlink(filename) contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": ")) with open(filename, "w") as f: f.write(SHORT_VERSION_PY % contents) print("set %s to '%s'" % (filename, versions["version"])) def plus_or_dot(pieces): """Return a + if we don't already have one, else return a .""" if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_branch(pieces): """TAG[[.dev0]+DISTANCE.gHEX[.dirty]] . The ".dev0" means not master branch. Note that .dev0 sorts backwards (a feature branch will appear "older" than the master branch). Exceptions: 1: no tags. 0[.dev0]+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0" if pieces["branch"] != "master": rendered += ".dev0" rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def pep440_split_post(ver): """Split pep440 version string at the post-release segment. Returns the release segments before the post-release and the post-release version number (or -1 if no post-release segment is present). """ vc = str.split(ver, ".post") return vc[0], int(vc[1] or 0) if len(vc) == 2 else None def render_pep440_pre(pieces): """TAG[.postN.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post0.devDISTANCE """ if pieces["closest-tag"]: if pieces["distance"]: # update the post release segment tag_version, post_version = pep440_split_post(pieces["closest-tag"]) rendered = tag_version if post_version is not None: rendered += ".post%d.dev%d" % (post_version+1, pieces["distance"]) else: rendered += ".post0.dev%d" % (pieces["distance"]) else: # no commits, use the tag as the version rendered = pieces["closest-tag"] else: # exception #1 rendered = "0.post0.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces): """TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_post_branch(pieces): """TAG[.postDISTANCE[.dev0]+gHEX[.dirty]] . The ".dev0" means not master branch. Exceptions: 1: no tags. 0.postDISTANCE[.dev0]+gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["branch"] != "master": rendered += ".dev0" rendered += "+g%s" % pieces["short"] if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_old(pieces): """TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Exceptions: 1: no tags. 0.postDISTANCE[.dev0] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): """TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): """TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix) """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): """Render the given version pieces into the requested style.""" if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"], "date": None} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-branch": rendered = render_pep440_branch(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-post-branch": rendered = render_pep440_post_branch(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None, "date": pieces.get("date")} class VersioneerBadRootError(Exception): """The project root directory is unknown or missing key files.""" def get_versions(verbose=False): """Get the project version from whatever source is available. Returns dict with two keys: 'version' and 'full'. """ if "versioneer" in sys.modules: # see the discussion in cmdclass.py:get_cmdclass() del sys.modules["versioneer"] root = get_root() cfg = get_config_from_root(root) assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" handlers = HANDLERS.get(cfg.VCS) assert handlers, "unrecognized VCS '%s'" % cfg.VCS verbose = verbose or cfg.verbose assert cfg.versionfile_source is not None, \ "please set versioneer.versionfile_source" assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" versionfile_abs = os.path.join(root, cfg.versionfile_source) # extract version from first of: _version.py, VCS command (e.g. 'git # describe'), parentdir. This is meant to work for developers using a # source checkout, for users of a tarball created by 'setup.py sdist', # and for users of a tarball/zipball created by 'git archive' or github's # download-from-tag feature or the equivalent in other VCSes. get_keywords_f = handlers.get("get_keywords") from_keywords_f = handlers.get("keywords") if get_keywords_f and from_keywords_f: try: keywords = get_keywords_f(versionfile_abs) ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) if verbose: print("got version from expanded keyword %s" % ver) return ver except NotThisMethod: pass try: ver = versions_from_file(versionfile_abs) if verbose: print("got version from file %s %s" % (versionfile_abs, ver)) return ver except NotThisMethod: pass from_vcs_f = handlers.get("pieces_from_vcs") if from_vcs_f: try: pieces = from_vcs_f(cfg.tag_prefix, root, verbose) ver = render(pieces, cfg.style) if verbose: print("got version from VCS %s" % ver) return ver except NotThisMethod: pass try: if cfg.parentdir_prefix: ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) if verbose: print("got version from parentdir %s" % ver) return ver except NotThisMethod: pass if verbose: print("unable to compute version") return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version", "date": None} def get_version(): """Get the short version string for this project.""" return get_versions()["version"] def get_cmdclass(cmdclass=None): """Get the custom setuptools/distutils subclasses used by Versioneer. If the package uses a different cmdclass (e.g. one from numpy), it should be provide as an argument. """ if "versioneer" in sys.modules: del sys.modules["versioneer"] # this fixes the "python setup.py develop" case (also 'install' and # 'easy_install .'), in which subdependencies of the main project are # built (using setup.py bdist_egg) in the same python process. Assume # a main project A and a dependency B, which use different versions # of Versioneer. A's setup.py imports A's Versioneer, leaving it in # sys.modules by the time B's setup.py is executed, causing B to run # with the wrong versioneer. Setuptools wraps the sub-dep builds in a # sandbox that restores sys.modules to it's pre-build state, so the # parent is protected against the child's "import versioneer". By # removing ourselves from sys.modules here, before the child build # happens, we protect the child from the parent's versioneer too. # Also see https://github.com/python-versioneer/python-versioneer/issues/52 cmds = {} if cmdclass is None else cmdclass.copy() # we add "version" to both distutils and setuptools try: from setuptools import Command except ImportError: from distutils.core import Command class cmd_version(Command): description = "report generated version string" user_options = [] boolean_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): vers = get_versions(verbose=True) print("Version: %s" % vers["version"]) print(" full-revisionid: %s" % vers.get("full-revisionid")) print(" dirty: %s" % vers.get("dirty")) print(" date: %s" % vers.get("date")) if vers["error"]: print(" error: %s" % vers["error"]) cmds["version"] = cmd_version # we override "build_py" in both distutils and setuptools # # most invocation pathways end up running build_py: # distutils/build -> build_py # distutils/install -> distutils/build ->.. # setuptools/bdist_wheel -> distutils/install ->.. # setuptools/bdist_egg -> distutils/install_lib -> build_py # setuptools/install -> bdist_egg ->.. # setuptools/develop -> ? # pip install: # copies source tree to a tempdir before running egg_info/etc # if .git isn't copied too, 'git describe' will fail # then does setup.py bdist_wheel, or sometimes setup.py install # setup.py egg_info -> ? # we override different "build_py" commands for both environments if 'build_py' in cmds: _build_py = cmds['build_py'] elif "setuptools" in sys.modules: from setuptools.command.build_py import build_py as _build_py else: from distutils.command.build_py import build_py as _build_py class cmd_build_py(_build_py): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() _build_py.run(self) # now locate _version.py in the new build/ directory and replace # it with an updated value if cfg.versionfile_build: target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) cmds["build_py"] = cmd_build_py if 'build_ext' in cmds: _build_ext = cmds['build_ext'] elif "setuptools" in sys.modules: from setuptools.command.build_ext import build_ext as _build_ext else: from distutils.command.build_ext import build_ext as _build_ext class cmd_build_ext(_build_ext): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() _build_ext.run(self) if self.inplace: # build_ext --inplace will only build extensions in # build/lib<..> dir with no _version.py to write to. # As in place builds will already have a _version.py # in the module dir, we do not need to write one. return # now locate _version.py in the new build/ directory and replace # it with an updated value target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) cmds["build_ext"] = cmd_build_ext if "cx_Freeze" in sys.modules: # cx_freeze enabled? from cx_Freeze.dist import build_exe as _build_exe # nczeczulin reports that py2exe won't like the pep440-style string # as FILEVERSION, but it can be used for PRODUCTVERSION, e.g. # setup(console=[{ # "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION # "product_version": versioneer.get_version(), # ... class cmd_build_exe(_build_exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _build_exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) cmds["build_exe"] = cmd_build_exe del cmds["build_py"] if 'py2exe' in sys.modules: # py2exe enabled? from py2exe.distutils_buildexe import py2exe as _py2exe class cmd_py2exe(_py2exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _py2exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) cmds["py2exe"] = cmd_py2exe # we override different "sdist" commands for both environments if 'sdist' in cmds: _sdist = cmds['sdist'] elif "setuptools" in sys.modules: from setuptools.command.sdist import sdist as _sdist else: from distutils.command.sdist import sdist as _sdist class cmd_sdist(_sdist): def run(self): versions = get_versions() self._versioneer_generated_versions = versions # unless we update this, the command will keep using the old # version self.distribution.metadata.version = versions["version"] return _sdist.run(self) def make_release_tree(self, base_dir, files): root = get_root() cfg = get_config_from_root(root) _sdist.make_release_tree(self, base_dir, files) # now locate _version.py in the new base_dir directory # (remembering that it may be a hardlink) and replace it with an # updated value target_versionfile = os.path.join(base_dir, cfg.versionfile_source) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, self._versioneer_generated_versions) cmds["sdist"] = cmd_sdist return cmds CONFIG_ERROR = """ setup.cfg is missing the necessary Versioneer configuration. You need a section like: [versioneer] VCS = git style = pep440 versionfile_source = src/myproject/_version.py versionfile_build = myproject/_version.py tag_prefix = parentdir_prefix = myproject- You will also need to edit your setup.py to use the results: import versioneer setup(version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), ...) Please read the docstring in ./versioneer.py for configuration instructions, edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. """ SAMPLE_CONFIG = """ # See the docstring in versioneer.py for instructions. Note that you must # re-run 'versioneer.py setup' after changing this section, and commit the # resulting files. [versioneer] #VCS = git #style = pep440 #versionfile_source = #versionfile_build = #tag_prefix = #parentdir_prefix = """ OLD_SNIPPET = """ from ._version import get_versions __version__ = get_versions()['version'] del get_versions """ INIT_PY_SNIPPET = """ from . import {0} __version__ = {0}.get_versions()['version'] """ def do_setup(): """Do main VCS-independent setup function for installing Versioneer.""" root = get_root() try: cfg = get_config_from_root(root) except (OSError, configparser.NoSectionError, configparser.NoOptionError) as e: if isinstance(e, (OSError, configparser.NoSectionError)): print("Adding sample versioneer config to setup.cfg", file=sys.stderr) with open(os.path.join(root, "setup.cfg"), "a") as f: f.write(SAMPLE_CONFIG) print(CONFIG_ERROR, file=sys.stderr) return 1 print(" creating %s" % cfg.versionfile_source) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py") if os.path.exists(ipy): try: with open(ipy, "r") as f: old = f.read() except OSError: old = "" module = os.path.splitext(os.path.basename(cfg.versionfile_source))[0] snippet = INIT_PY_SNIPPET.format(module) if OLD_SNIPPET in old: print(" replacing boilerplate in %s" % ipy) with open(ipy, "w") as f: f.write(old.replace(OLD_SNIPPET, snippet)) elif snippet not in old: print(" appending to %s" % ipy) with open(ipy, "a") as f: f.write(snippet) else: print(" %s unmodified" % ipy) else: print(" %s doesn't exist, ok" % ipy) ipy = None # Make sure both the top-level "versioneer.py" and versionfile_source # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so # they'll be copied into source distributions. Pip won't be able to # install the package without this. manifest_in = os.path.join(root, "MANIFEST.in") simple_includes = set() try: with open(manifest_in, "r") as f: for line in f: if line.startswith("include "): for include in line.split()[1:]: simple_includes.add(include) except OSError: pass # That doesn't cover everything MANIFEST.in can do # (http://docs.python.org/2/distutils/sourcedist.html#commands), so # it might give some false negatives. Appending redundant 'include' # lines is safe, though. if "versioneer.py" not in simple_includes: print(" appending 'versioneer.py' to MANIFEST.in") with open(manifest_in, "a") as f: f.write("include versioneer.py\n") else: print(" 'versioneer.py' already in MANIFEST.in") if cfg.versionfile_source not in simple_includes: print(" appending versionfile_source ('%s') to MANIFEST.in" % cfg.versionfile_source) with open(manifest_in, "a") as f: f.write("include %s\n" % cfg.versionfile_source) else: print(" versionfile_source already in MANIFEST.in") # Make VCS-specific changes. For git, this means creating/changing # .gitattributes to mark _version.py for export-subst keyword # substitution. do_vcs_install(manifest_in, cfg.versionfile_source, ipy) return 0 def scan_setup_py(): """Validate the contents of setup.py against Versioneer's expectations.""" found = set() setters = False errors = 0 with open("setup.py", "r") as f: for line in f.readlines(): if "import versioneer" in line: found.add("import") if "versioneer.get_cmdclass()" in line: found.add("cmdclass") if "versioneer.get_version()" in line: found.add("get_version") if "versioneer.VCS" in line: setters = True if "versioneer.versionfile_source" in line: setters = True if len(found) != 3: print("") print("Your setup.py appears to be missing some important items") print("(but I might be wrong). Please make sure it has something") print("roughly like the following:") print("") print(" import versioneer") print(" setup( version=versioneer.get_version(),") print(" cmdclass=versioneer.get_cmdclass(), ...)") print("") errors += 1 if setters: print("You should remove lines like 'versioneer.VCS = ' and") print("'versioneer.versionfile_source = ' . This configuration") print("now lives in setup.cfg, and should be removed from setup.py") print("") errors += 1 return errors if __name__ == "__main__": cmd = sys.argv[1] if cmd == "setup": errors = do_setup() errors += scan_setup_py() if errors: sys.exit(1)
PAHdbREPO_NAMEpyPAHdbPATH_START.@pyPAHdb_extracted@pyPAHdb-master@versioneer.py@.PATH_END.py
{ "filename": "_autocolorscale.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py2/plotly/validators/funnel/marker/_autocolorscale.py", "type": "Python" }
import _plotly_utils.basevalidators class AutocolorscaleValidator(_plotly_utils.basevalidators.BooleanValidator): def __init__( self, plotly_name="autocolorscale", parent_name="funnel.marker", **kwargs ): super(AutocolorscaleValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), implied_edits=kwargs.pop("implied_edits", {}), role=kwargs.pop("role", "style"), **kwargs )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py2@plotly@validators@funnel@marker@_autocolorscale.py@.PATH_END.py
{ "filename": "_ticktext.py", "repo_name": "plotly/plotly.py", "repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/validators/scatterpolargl/marker/colorbar/_ticktext.py", "type": "Python" }
import _plotly_utils.basevalidators class TicktextValidator(_plotly_utils.basevalidators.DataArrayValidator): def __init__( self, plotly_name="ticktext", parent_name="scatterpolargl.marker.colorbar", **kwargs, ): super(TicktextValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), **kwargs, )
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@validators@scatterpolargl@marker@colorbar@_ticktext.py@.PATH_END.py
{ "filename": "_shadow.py", "repo_name": "plotly/plotly.py", "repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/validators/funnel/hoverlabel/font/_shadow.py", "type": "Python" }
import _plotly_utils.basevalidators class ShadowValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name="shadow", parent_name="funnel.hoverlabel.font", **kwargs ): super(ShadowValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_ok", True), edit_type=kwargs.pop("edit_type", "none"), **kwargs, )
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@validators@funnel@hoverlabel@font@_shadow.py@.PATH_END.py
{ "filename": "sharding.py", "repo_name": "jax-ml/jax", "repo_path": "jax_extracted/jax-main/jax/_src/sharding.py", "type": "Python" }
# Copyright 2021 The JAX Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from collections.abc import Mapping, Sequence import functools from jax._src.util import safe_zip, use_cpp_class, cache from jax._src import xla_bridge as xb from jax._src.lib import xla_client as xc from jax._src.op_shardings import ( are_op_shardings_equal, get_num_ways_dim_sharded, is_op_sharding_replicated, op_sharding_to_indices) Shape = tuple[int, ...] Device = xc.Device Index = tuple[slice, ...] XLADeviceAssignment = Sequence[Device] @cache(max_size=4096, trace_context_in_key=False) def _addressable_devices_indices_map( sharding: Sharding, global_shape: Shape) -> Mapping[Device, Index | None]: global_map = sharding.devices_indices_map(global_shape) if sharding.is_fully_addressable: return global_map if hasattr(sharding, '_internal_device_list'): return {d: global_map[d] for d in sharding._internal_device_list.addressable_device_list} return {d: ind for d, ind in global_map.items() if d.process_index == d.client.process_index()} @cache(max_size=4096, trace_context_in_key=False) def common_devices_indices_map( s: Sharding, global_shape: Shape) -> Mapping[Device, Index]: s.shard_shape(global_shape) # raises a good error message hlo_sharding = s._to_xla_hlo_sharding(len(global_shape)) indices = op_sharding_to_indices(hlo_sharding, global_shape, len(s._device_assignment)) return dict(safe_zip(s._device_assignment, indices)) @cache(max_size=4096, trace_context_in_key=False) def _common_shard_shape(self, global_shape: Shape) -> Shape: hlo_sharding = self._to_xla_hlo_sharding(len(global_shape)) if is_op_sharding_replicated(hlo_sharding): return global_shape partitions, _ = get_num_ways_dim_sharded(hlo_sharding) assert len(partitions) == len(global_shape), (len(partitions), len(global_shape)) out = [] for dim, (s, p) in enumerate(safe_zip(global_shape, partitions)): try: quotient, remainder = divmod(s, p) except TypeError: # TODO Figure out how to partition dynamic shapes raise NotImplementedError if remainder != 0: raise ValueError( f"Sharding {self} implies that array axis {dim} is partitioned " f"{p} times, but the dimension size is {s} " f"(full shape: {global_shape}, " f"per-dimension tiling factors: {partitions} should evenly divide " "the shape)") out.append(quotient) return tuple(out) @use_cpp_class(xc.Sharding) class Sharding: """Describes how a :class:`jax.Array` is laid out across devices. """ # Abstract methods below that subclasses should implement. @property def device_set(self) -> set[Device]: """The set of devices that this :class:`Sharding` spans. In multi-controller JAX, the set of devices is global, i.e., includes non-addressable devices from other processes. """ raise NotImplementedError('Subclasses should implement this method.') @property def is_fully_replicated(self) -> bool: """Is this sharding fully replicated? A sharding is fully replicated if each device has a complete copy of the entire data. """ raise NotImplementedError('Subclasses should implement this method.') @property def is_fully_addressable(self) -> bool: """Is this sharding fully addressable? A sharding is fully addressable if the current process can address all of the devices named in the :class:`Sharding`. ``is_fully_addressable`` is equivalent to "is_local" in multi-process JAX. """ raise NotImplementedError('Subclasses should implement this method.') @property def num_devices(self) -> int: """Number of devices that the sharding contains.""" raise NotImplementedError('Subclasses should implement this method.') @property def memory_kind(self) -> str | None: """Returns the memory kind of the sharding.""" raise NotImplementedError('Subclasses should implement this method.') def with_memory_kind(self, kind: str) -> Sharding: """Returns a new Sharding instance with the specified memory kind.""" raise NotImplementedError('Subclasses should implement this method') @property def _device_assignment(self) -> XLADeviceAssignment: raise NotImplementedError('Subclasses should implement this method.') def _to_xla_hlo_sharding(self, num_dimensions: int) -> xc.HloSharding: raise NotImplementedError('Subclasses should implement this method.') def _to_sdy_sharding(self, num_dimensions: int): raise NotImplementedError('Subclasses should implement this method.') ############################################################################# # Default implementations below that all subclasses will inherit. @functools.cached_property def addressable_devices(self) -> set[Device]: """The set of devices in the :class:`Sharding` that are addressable by the current process. """ # Add a fast path for single controller runtimes. if xb.process_count() == 1: return self.device_set return {d for d in self.device_set if d.process_index == d.client.process_index()} def addressable_devices_indices_map( self, global_shape: Shape) -> Mapping[Device, Index | None]: """A mapping from addressable devices to the slice of array data each contains. ``addressable_devices_indices_map`` contains that part of ``device_indices_map`` that applies to the addressable devices. """ return _addressable_devices_indices_map(self, global_shape) def devices_indices_map(self, global_shape: Shape) -> Mapping[Device, Index]: """Returns a mapping from devices to the array slices each contains. The mapping includes all global devices, i.e., including non-addressable devices from other processes. """ return common_devices_indices_map(self, global_shape) @functools.cached_property def _addressable_device_assignment(self) -> XLADeviceAssignment: if self.is_fully_addressable: return self._device_assignment if hasattr(self, '_internal_device_list'): return tuple(self._internal_device_list.addressable_device_list) return tuple(d for d in self._device_assignment if d.process_index == d.client.process_index()) def shard_shape(self, global_shape: Shape) -> Shape: """Returns the shape of the data on each device. The shard shape returned by this function is calculated from ``global_shape`` and the properties of the sharding. """ return _common_shard_shape(self, global_shape) def is_equivalent_to(self: Sharding, other: Sharding, ndim: int) -> bool: """Returns ``True`` if two shardings are equivalent. Two shardings are equivalent if they place the same logical array shards on the same devices. For example, a :class:`NamedSharding` may be equivalent to a :class:`PositionalSharding` if both place the same shards of the array on the same devices. """ try: return (are_op_shardings_equal(self._to_xla_hlo_sharding(ndim), other._to_xla_hlo_sharding(ndim)) and self._internal_device_list == other._internal_device_list and # type: ignore self.memory_kind == other.memory_kind) # NotImplementedError is raised by PmapSharding because it can't lower # to OpSharding. So if `other` is a PmapSharding, default to a strict # equality check. except NotImplementedError: return self == other
jax-mlREPO_NAMEjaxPATH_START.@jax_extracted@jax-main@jax@_src@sharding.py@.PATH_END.py
{ "filename": "paper_combined.py", "repo_name": "amusecode/venice", "repo_path": "venice_extracted/venice-main/src/paper_combined.py", "type": "Python" }
import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LogNorm import matplotlib.gridspec as gs import matplotlib.ticker as tck import h5py import scipy.stats as ss import argparse import os import time from amuse.units import units, constants, nbody_system from amuse.datamodel import Particles from amuse.ic.plummer import new_plummer_model from amuse.ic.brokenimf import MultiplePartIMF from amuse.community.seba.interface import SeBa from amuse.community.ph4.interface import ph4 from amuse.community.gadget2.interface import Gadget2 from amuse.community.phantom.interface import Phantom from amuse.community.fi.interface import Fi from amuse.io import write_set_to_file, read_set_from_file from amuse.ext.galactic_potentials import MWpotentialBovy2015, NFW_profile from venice import Venice, DynamicKick, dynamic_kick from test_separate import convert_magi_to_amuse plt.rcParams.update({'font.size': 12}) def clear_output_directory (output_path): os.system('rm -f {a}/*.venice'.format(a=output_path)) def minimum_mutual_freefall_time (grav1, grav2, dt, direction='11'): dt_new = -dt grav1_particles = grav1.particles.copy( filter_attributes=lambda p, attribute_name: \ attribute_name in ['mass', 'x', 'y', 'z', 'vx', 'vy', 'vz', 'radius']) grav2_particles = grav2.particles.copy( filter_attributes=lambda p, attribute_name: \ attribute_name in ['mass', 'x', 'y', 'z', 'vx', 'vy', 'vz', 'radius']) if direction[0] != '0': ax, ay, az = grav1.get_gravity_at_point(grav2_particles.radius, grav2_particles.x, grav2_particles.y, grav2_particles.z) nearest_neighbours = grav2_particles.nearest_neighbour(grav1_particles) tau_ff = ( ((grav2_particles.position - nearest_neighbours.position)**2.).sum(axis=1) / \ (ax*ax + ay*ay + az*az) )**0.25 if dt_new < 0.*dt or dt_new > tau_ff.min(): dt_new = tau_ff.min() if direction[1] != '0': ax, ay, az = grav2.get_gravity_at_point(grav1_particles.radius, grav1_particles.x, grav1_particles.y, grav1_particles.z) nearest_neighbours = grav1_particles.nearest_neighbour(grav2_particles) tau_ff = ( ((grav1_particles.position - nearest_neighbours.position)**2.).sum(axis=1) / \ (ax*ax + ay*ay + az*az) )**0.25 if dt_new < 0.*dt or dt_new > tau_ff.min(): dt_new = tau_ff.min() if dt_new < 0.*dt: dt_new = 1e6 | units.Gyr return dt_new def minimum_freefall_time_in_potential (potential, grav, dt): grav_particles = grav.particles.copy( filter_attributes=lambda p, attribute_name: \ attribute_name in ['mass', 'x', 'y', 'z', 'radius']) ax, ay, az = potential.get_gravity_at_point( grav_particles.radius, grav_particles.x, grav_particles.y, grav_particles.z) tau_ff = ( grav_particles.position.lengths()**2/(ax*ax + ay*ay + az*az) )**0.25 return tau_ff.min() def setup_combined_system (params): converter_galaxy = nbody_system.nbody_to_si(1e12|units.MSun, 1.|units.kpc) converter_cluster = nbody_system.nbody_to_si(1e3|units.MSun, 1.|units.pc) system = Venice() gravity_galaxy = MWpotentialBovy2015() system.add_code(gravity_galaxy) gravity_cluster = ph4(converter_cluster) gravity_cluster.parameters.force_sync = True system.add_code(gravity_cluster) system.kick[0][1] = dynamic_kick system.update_timescale[0][1] = lambda g1, g2, dt: params['eta_gravity']*minimum_freefall_time_in_potential( g1, g2, dt) system.io_scheme = 2 system.filepath = params['output_path'] system.save_data[1] = lambda code, filename: write_set_to_file( code.particles, filename.format(code_label='cluster', set_label='particles'), 'hdf5', overwrite_file=True, timestamp=code.model_time) codes = [gravity_galaxy, gravity_cluster] if params['perturbers'] is not None: gravity_perturbers = ph4(converter_galaxy) gravity_perturbers.parameters.force_sync = True system.add_code(gravity_perturbers) code_id = len(system.codes)-1 system.kick[code_id][1] = DynamicKick(radius_is_eps=True) system.kick[0][code_id] = DynamicKick(radius_is_eps=True) system.update_timescale[0][code_id] = lambda g1, g2, dt: params['eta_gravity']*minimum_freefall_time_in_potential( g1, g2, dt) system.update_timescale[1][code_id] = lambda g1, g2, dt: params['eta_gravity']*minimum_mutual_freefall_time( g1, g2, dt, direction='01') system.save_data[-1] = lambda code, filename: write_set_to_file( code.particles, filename.format(code_label='perturbers', set_label='particles'), 'hdf5', overwrite_file=True, timestamp=code.model_time) codes.append(gravity_perturbers) if params['stellar_evolution']: stellar = SeBa() system.add_code(stellar) code_id = len(system.codes)-1 system.add_channel(code_id, 1, from_attributes=['mass'], to_attributes=['mass']) system.update_timescale[1][code_id] = lambda g, s, dt: params['eta_stellar']*s.particles.time_step.min() system.save_data[-1] = lambda code, filename: write_set_to_file( code.particles, filename.format(code_label='stellar', set_label='particles'), 'hdf5', overwrite_file=True, timestamp=code.model_time) codes.append(stellar) return system, codes def setup_initial_conditions (codes, params): # CLUSTER kroupa_imf = MultiplePartIMF(mass_boundaries=[0.08, 0.5, 8.]|units.MSun, alphas=[-1.3, -2.3]) mass = kroupa_imf.next_mass(params['N_cluster']) if params['max_mass_cluster'] is not None: mass[:len(params['max_mass_cluster'])] = params['max_mass_cluster'] converter = nbody_system.nbody_to_si(mass.sum(), params['R_cluster']) cluster = new_plummer_model(params['N_cluster'], converter) cluster.mass = mass cluster.radius = params['eps_cluster'] cluster.x += params['dR_cluster'] cluster_com = cluster.center_of_mass() ax, ay, az = MWpotentialBovy2015().get_gravity_at_point(0.|units.pc, cluster_com[0], cluster_com[1], cluster_com[2]) a2 = ax*ax + ay*ay + az*az v2_kep = cluster_com.length()*a2**0.5 cluster.vy += ((1.-params['e_cluster'])/(1.+params['e_cluster'])*v2_kep)**0.5 codes[1].particles.add_particles(cluster) if params['stellar_evolution']: codes[2+(params['perturbers'] is not None)].particles.add_particles(cluster) # PERTURBERS if params['perturbers'] is not None: params['perturbers'].x = params['perturbers'].semimajor_axis * np.cos(params['perturbers'].argument_of_periastron) params['perturbers'].y = params['perturbers'].semimajor_axis * np.sin(params['perturbers'].argument_of_periastron) params['perturbers'].z = 0. | units.kpc params['perturbers'].velocity = [0., 0., 0.] | units.kms for i in range(len(params['perturbers'])): e = params['perturbers'][i].eccentricity ax, ay, az = MWpotentialBovy2015().get_gravity_at_point(0.|units.pc, params['perturbers'][i].x, params['perturbers'][i].y, params['perturbers'][i].z) a2 = ax*ax + ay*ay + az*az v2_kep = params['perturbers'][i].position.length()*a2**0.5 v = ((1.-e)/(1.+e)*v2_kep)**0.5 params['perturbers'][i].vx = -v * np.sin(params['perturbers'][i].argument_of_periastron) params['perturbers'][i].vy = v * np.cos(params['perturbers'][i].argument_of_periastron) codes[2].particles.add_particles(params['perturbers']) def run_combined_model (params): clear_output_directory(params['output_path']) system, codes = setup_combined_system(params) setup_initial_conditions(codes, params) system.verbose = True system.evolve_model(params['end_time']) def plot_combined_model (filepath): filepaths = [filepath + '/combined_s0_p0/', filepath + '/combined_s1_p0/', filepath + '/combined_s0_p1/', filepath + '/combined_s1_p1/' ] colors = ['C0', 'C1', 'C3', 'C7'] markers = ['o', 'x', '^', 'v'] figs = [ plt.figure(), plt.figure(figsize=(12.8, 4.8)), plt.figure(), plt.figure(figsize=(6.4, 9.6)) ] ax1 = figs[0].add_subplot(111) ax2a = figs[1].add_subplot(121, aspect='equal') ax2b = figs[1].add_subplot(122, aspect='equal') ax3 = figs[2].add_subplot(111) ax4a = figs[3].add_subplot(211) ax4b = figs[3].add_subplot(212) ax1.set_yscale('log') ax1.set_xlabel('t [Myr]') ax1.set_ylabel('dt [yr]') ax1.plot([0.], [0.], label='Cluster', c='k', ls='--') ax1.plot([0.], [0.], label='Perturbers', c='k', ls='-.') ax1.plot([0.], [0.], label='Stellar', c='k', ls=':') ax1.legend(frameon=False) ax1.set_xlim(0., 5000.) ax1.set_ylim(1e0, 3e8) ax1.xaxis.set_minor_locator(tck.MultipleLocator(250.)) ax2a.set_xlabel('x [kpc]') ax2a.set_ylabel('y [kpc]') ax2b.set_xlabel('x [kpc]') ax2b.set_ylabel('y [kpc]') ax2a.set_xlim(-100., 100.) ax2a.set_ylim(-100., 100.) ax2b.set_xlim(-10., 10.) ax2b.set_ylim(-10., 10.) ax2b.scatter([-100.], [-100.], c=colors[0], label='None', s=10., marker=markers[0]) ax2b.scatter([-100.], [-100.], c=colors[1], label='Stellar', s=10., marker=markers[1]) ax2b.scatter([-100.], [-100.], c=colors[2], label='Perturbers', s=10., marker=markers[2]) ax2b.scatter([-100.], [-100.], c=colors[3], label='Both', s=10., marker=markers[3]) ax2b.legend(loc='upper left', frameon=False) ax2a.xaxis.set_minor_locator(tck.MultipleLocator(10.)) ax2a.yaxis.set_minor_locator(tck.MultipleLocator(10.)) ax2b.xaxis.set_minor_locator(tck.MultipleLocator(1.)) ax2b.yaxis.set_minor_locator(tck.MultipleLocator(1.)) ax3.set_xlabel('$\\phi$ [rad]') ax3.set_ylabel('N') ax3.plot([0.], [0.], label='None', c=colors[0]) ax3.plot([0.], [0.], label='Stellar', c=colors[1]) ax3.plot([0.], [0.], label='Perturbers', c=colors[2]) ax3.plot([0.], [0.], label='Both', c=colors[3]) ax3.legend(frameon=False) ax4a.set_xlabel('t [Myr]') ax4a.set_ylabel('$\\sigma_R$/$\\mu_R$') ax4a.set_yscale('log') ax4a.plot([-100.], [-100.], c=colors[0], label='None') ax4a.plot([-100.], [-100.], c=colors[1], label='Stellar') ax4a.plot([-100.], [-100.], c=colors[2], label='Perturbers') ax4a.plot([-100.], [-100.], c=colors[3], label='Both') ax4a.legend(loc='upper left', frameon=False) ax4a.set_xlim(0., 5000.) ax4b.set_xlabel('t [Myr]') ax4b.set_ylabel('$\\sigma_{\\phi}$ [rad]') ax4b.set_xlim(0., 5000.) ax4b.set_ylim(0., np.pi) ax4a.xaxis.set_minor_locator(tck.MultipleLocator(250.)) ax4b.xaxis.set_minor_locator(tck.MultipleLocator(250.)) for i in range(len(filepaths)): files = os.listdir(filepaths[i]) cluster_files = list(filter(lambda filename: (filename.split('_')[0] == 'plt')*(filename.split('_')[1] == 'cluster'), files)) cluster_files.sort(key=lambda filename: filename.split('_')[3][1:]) if len(cluster_files) > 0: time = np.zeros(len(cluster_files)) | units.Myr dR = np.zeros(len(cluster_files)) dphi = np.zeros(len(cluster_files)) for j in range(len(cluster_files)): particles = read_set_from_file(filepaths[i] + cluster_files[j]) time[j] = particles.get_timestamp() R = particles.position.lengths() dR[j] = R.std()/R.mean() phi = np.arctan2(particles.y.value_in(units.kpc), particles.x.value_in(units.kpc)) # Center on 0, so there's no splitting a peak between -pi and pi phi -= np.max(phi) phi[ phi < -np.pi] += 2.*np.pi dphi[j] = np.std(phi) if i == 3: ax1.plot(time[1:].value_in(units.Myr), np.diff(time.value_in(units.yr)), ds='steps-pre', ls='--', c=colors[i]) ax2a.scatter(particles.x.value_in(units.kpc), particles.y.value_in(units.kpc), s=10., c=colors[i], marker=markers[i]) ax2b.scatter(particles.x.value_in(units.kpc), particles.y.value_in(units.kpc), s=10., c=colors[i], marker=markers[i]) phi = np.arctan2(particles.y.value_in(units.kpc), particles.x.value_in(units.kpc)) kde = ss.gaussian_kde(phi) bins = np.linspace(-1., 1., num=300)*np.pi ax3.plot(bins, kde(bins), c=colors[i]) print (np.std(phi)) ax4a.plot(time.value_in(units.Myr), dR, c=colors[i]) ax4b.plot(time.value_in(units.Myr), dphi, c=colors[i]) print (filepaths[i], "cluster", flush=True) perturbers_files = list(filter(lambda filename: (filename.split('_')[0] == 'plt')*(filename.split('_')[1] == 'perturbers'), files)) perturbers_files.sort(key=lambda filename: filename.split('_')[3][1:]) if len(perturbers_files) > 0: time = np.zeros(len(perturbers_files)) | units.Myr R_perturbers = np.zeros((len(perturbers_files), 2, 3)) | units.kpc for j in range(len(perturbers_files)): particles = read_set_from_file(filepaths[i] + perturbers_files[j]) time[j] = particles.get_timestamp() R_perturbers[j] = particles.position if i == 3: ax1.plot(time[1:].value_in(units.Myr), np.diff(time.value_in(units.yr)), ds='steps-pre', ls='-.', c=colors[i]) ax2a.plot(R_perturbers[:,0,0].value_in(units.kpc), R_perturbers[:,0,1].value_in(units.kpc), c='k', ls='--') ax2a.plot(R_perturbers[:,1,0].value_in(units.kpc), R_perturbers[:,1,1].value_in(units.kpc), c='k', ls=':') print (filepaths[i], "perturbers", flush=True) stellar_files = list(filter(lambda filename: (filename.split('_')[0] == 'plt')*(filename.split('_')[1] == 'stellar'), files)) stellar_files.sort(key=lambda filename: filename.split('_')[3][1:]) if len(stellar_files) > 0: time = np.zeros(len(stellar_files)) | units.Myr for j in range(len(stellar_files)): particles = read_set_from_file(filepaths[i] + stellar_files[j]) time[j] = particles.get_timestamp() if i == 3: ax1.plot(time[1:].value_in(units.Myr), np.diff(time.value_in(units.yr)), ds='steps-pre', ls=':', c=colors[i]) print (filepaths[i], "stellar", flush=True) figs[0].savefig('figures/combined_timesteps.pdf', bbox_inches='tight') figs[0].savefig('figures/combined_timesteps.png', bbox_inches='tight') figs[1].savefig('figures/combined_positions.pdf', bbox_inches='tight') figs[1].savefig('figures/combined_positions.png', bbox_inches='tight') figs[3].savefig('figures/combined_coordinates_std.pdf', bbox_inches='tight') figs[3].savefig('figures/combined_coordinates_std.png', bbox_inches='tight') if __name__ == '__main__': np.random.seed(42937523) parser = argparse.ArgumentParser() parser.add_argument('-s', '--stellar-evolution', dest='stellar_evolution', type=int, default=0) parser.add_argument('-p', '--perturbers', dest='perturbers', type=int, default=0) parser.add_argument('--filepath', dest='filepath', type=str, default='./data/', required=False) args = parser.parse_args() perturbers = Particles(2, mass = 1e11 | units.MSun, radius = 1. | units.kpc, eccentricity = [0., 0.], semimajor_axis = [60., 50.] | units.kpc, argument_of_periastron = [np.pi/2., np.pi] ) params = { 'end_time': 5000. | units.Myr, 'output_path': args.filepath + '/combined_s{a}_p{b}/'.format( a='1' if args.stellar_evolution else '0', b='1' if args.perturbers else '0') 'eta_gravity': 0.03, 'eta_stellar': 0.3, 'N_cluster': 100, 'R_cluster': 10. | units.pc, 'eps_cluster': 1. | units.pc, 'dR_cluster': 5. | units.kpc, 'e_cluster': 0., 'max_mass_cluster': [50., 30., 16.] | units.MSun, 'perturbers': None, 'stellar_evolution': args.stellar_evolution == True, } if args.perturbers: params['perturbers'] = perturbers run_combined_model(params) if args.perturbers and args.stellar_evolution: plot_combined_model(args.filepath) plt.show()
amusecodeREPO_NAMEvenicePATH_START.@venice_extracted@venice-main@src@paper_combined.py@.PATH_END.py
{ "filename": "README.md", "repo_name": "ESA-Datalabs/XAMI-model", "repo_path": "XAMI-model_extracted/XAMI-model-main/xami_model/mobile_sam/README.md", "type": "Markdown" }
<p float="center"> <img src="assets/logo2.png?raw=true" width="99.1%" /> </p> # Faster Segment Anything (MobileSAM) and Everything (MobileSAMv2) :pushpin: MobileSAMv2, available at [ResearchGate](https://www.researchgate.net/publication/376579294_MobileSAMv2_Faster_Segment_Anything_to_Everything) and [arXiv](https://arxiv.org/abs/2312.09579.pdf), replaces the grid-search prompt sampling in SAM with object-aware prompt sampling for faster **segment everything(SegEvery)**. :pushpin: MobileSAM, available at [ResearchGate](https://www.researchgate.net/publication/371851844_Faster_Segment_Anything_Towards_Lightweight_SAM_for_Mobile_Applications) and [arXiv](https://arxiv.org/pdf/2306.14289.pdf), replaces the heavyweight image encoder in SAM with a lightweight image encoder for faster **segment anything(SegAny)**. **Support for ONNX model export**. Feel free to test it on your devices and share your results with us. **A demo of MobileSAM** running on **CPU** is open at [hugging face demo](https://huggingface.co/spaces/dhkim2810/MobileSAM). On our own Mac i5 CPU, it takes around 3s. On the hugging face demo, the interface and inferior CPUs make it slower but still works fine. Stayed tuned for a new version with more features! You can also run a demo of MobileSAM on [your local PC](https://github.com/ChaoningZhang/MobileSAM/tree/master/app). :grapes: Media coverage and Projects that adapt from SAM to MobileSAM (Thank you all!) * **2023/07/03**: [joliGEN](https://github.com/jolibrain/joliGEN) supports MobileSAM for faster and lightweight mask refinement for image inpainting with Diffusion and GAN. * **2023/07/03**: [MobileSAM-in-the-Browser](https://github.com/akbartus/MobileSAM-in-the-Browser) shows a demo of running MobileSAM on the browser of your local PC or Mobile phone. * **2023/07/02**: [Inpaint-Anything](https://github.com/qiaoyu1002/Inpaint-Anything) supports MobileSAM for faster and lightweight Inpaint Anything * **2023/07/02**: [Personalize-SAM](https://github.com/qiaoyu1002/Personalize-SAM) supports MobileSAM for faster and lightweight Personalize Segment Anything with 1 Shot * **2023/07/01**: [MobileSAM-in-the-Browser](https://github.com/akbartus/MobileSAM-in-the-Browser) makes an example implementation of MobileSAM in the browser. * **2023/06/30**: [SegmentAnythingin3D](https://github.com/Jumpat/SegmentAnythingin3D) supports MobileSAM to segment anything in 3D efficiently. * **2023/06/30**: MobileSAM has been featured by [AK](https://twitter.com/_akhaliq?lang=en) for the second time, see the link [AK's MobileSAM tweet](https://twitter.com/_akhaliq/status/1674410573075718145). Welcome to retweet. * **2023/06/29**: [AnyLabeling](https://github.com/vietanhdev/anylabeling) supports MobileSAM for auto-labeling. * **2023/06/29**: [SonarSAM](https://github.com/wangsssky/SonarSAM) supports MobileSAM for Image encoder full-finetuing. * **2023/06/29**: [Stable Diffusion WebUIv](https://github.com/continue-revolution/sd-webui-segment-anything) supports MobileSAM. * **2023/06/28**: [Grounding-SAM](https://github.com/IDEA-Research/Grounded-Segment-Anything) supports MobileSAM with [Grounded-MobileSAM](https://github.com/IDEA-Research/Grounded-Segment-Anything/tree/main/EfficientSAM). * **2023/06/27**: MobileSAM has been featured by [AK](https://twitter.com/_akhaliq?lang=en), see the link [AK's MobileSAM tweet](https://twitter.com/_akhaliq/status/1673585099097636864). Welcome to retweet. ![MobileSAM](assets/model_diagram.jpg?raw=true) :star: **How is MobileSAM trained?** MobileSAM is trained on a single GPU with 100k datasets (1% of the original images) for less than a day. The training code will be available soon. :star: **How to Adapt from SAM to MobileSAM?** Since MobileSAM keeps exactly the same pipeline as the original SAM, we inherit pre-processing, post-processing, and all other interfaces from the original SAM. Therefore, by assuming everything is exactly the same except for a smaller image encoder, those who use the original SAM for their projects can **adapt to MobileSAM with almost zero effort**. :star: **MobileSAM performs on par with the original SAM (at least visually)** and keeps exactly the same pipeline as the original SAM except for a change on the image encoder. Specifically, we replace the original heavyweight ViT-H encoder (632M) with a much smaller Tiny-ViT (5M). On a single GPU, MobileSAM runs around 12ms per image: 8ms on the image encoder and 4ms on the mask decoder. * The comparison of ViT-based image encoder is summarzed as follows: Image Encoder | Original SAM | MobileSAM :-----------------------------------------:|:---------|:-----: Parameters | 611M | 5M Speed | 452ms | 8ms * Original SAM and MobileSAM have exactly the same prompt-guided mask decoder: Mask Decoder | Original SAM | MobileSAM :-----------------------------------------:|:---------|:-----: Parameters | 3.876M | 3.876M Speed | 4ms | 4ms * The comparison of the whole pipeline is summarized as follows: Whole Pipeline (Enc+Dec) | Original SAM | MobileSAM :-----------------------------------------:|:---------|:-----: Parameters | 615M | 9.66M Speed | 456ms | 12ms :star: **Original SAM and MobileSAM with a point as the prompt.** <p float="left"> <img src="assets/mask_point.jpg?raw=true" width="99.1%" /> </p> :star: **Original SAM and MobileSAM with a box as the prompt.** <p float="left"> <img src="assets/mask_box.jpg?raw=true" width="99.1%" /> </p> :muscle: **Is MobileSAM faster and smaller than FastSAM? Yes!** MobileSAM is around 7 times smaller and around 5 times faster than the concurrent FastSAM. The comparison of the whole pipeline is summarzed as follows: Whole Pipeline (Enc+Dec) | FastSAM | MobileSAM :-----------------------------------------:|:---------|:-----: Parameters | 68M | 9.66M Speed | 64ms |12ms :muscle: **Does MobileSAM aign better with the original SAM than FastSAM? Yes!** FastSAM is suggested to work with multiple points, thus we compare the mIoU with two prompt points (with different pixel distances) and show the resutls as follows. Higher mIoU indicates higher alignment. mIoU | FastSAM | MobileSAM :-----------------------------------------:|:---------|:-----: 100 | 0.27 | 0.73 200 | 0.33 |0.71 300 | 0.37 |0.74 400 | 0.41 |0.73 500 | 0.41 |0.73 ## Installation The code requires `python>=3.8`, as well as `pytorch>=1.7` and `torchvision>=0.8`. Please follow the instructions [here](https://pytorch.org/get-started/locally/) to install both PyTorch and TorchVision dependencies. Installing both PyTorch and TorchVision with CUDA support is strongly recommended. Install Mobile Segment Anything: ``` pip install git+https://github.com/ChaoningZhang/MobileSAM.git ``` or clone the repository locally and install with ``` git clone git@github.com:ChaoningZhang/MobileSAM.git cd MobileSAM; pip install -e . ``` ## Demo Once installed MobileSAM, you can run demo on your local PC or check out our [HuggingFace Demo](https://huggingface.co/spaces/dhkim2810/MobileSAM). It requires latest version of [gradio](https://gradio.app). ``` cd app python app.py ``` ## <a name="GettingStarted"></a>Getting Started The MobileSAM can be loaded in the following ways: ``` from mobile_sam import sam_model_registry, SamAutomaticMaskGenerator, SamPredictor model_type = "vit_t" sam_checkpoint = "./weights/mobile_sam.pt" device = "cuda" if torch.cuda.is_available() else "cpu" mobile_sam = sam_model_registry[model_type](checkpoint=sam_checkpoint) mobile_sam.to(device=device) mobile_sam.eval() predictor = SamPredictor(mobile_sam) predictor.set_image(<your_image>) masks, _, _ = predictor.predict(<input_prompts>) ``` or generate masks for an entire image: ``` from mobile_sam import SamAutomaticMaskGenerator mask_generator = SamAutomaticMaskGenerator(mobile_sam) masks = mask_generator.generate(<your_image>) ``` ## <a name="GettingStarted"></a>Getting Started (MobileSAMv2) Download the model weights from the [checkpoints](https://drive.google.com/file/d/1dE-YAG-1mFCBmao2rHDp0n-PP4eH7SjE/view?usp=sharing). After downloading the model weights, faster SegEvery with MobileSAMv2 can be simply used as follows: ``` cd MobileSAMv2 bash ./experiments/mobilesamv2.sh ``` ## ONNX Export **MobileSAM** now supports ONNX export. Export the model with ``` python scripts/export_onnx_model.py --checkpoint ./weights/mobile_sam.pt --model-type vit_t --output ./mobile_sam.onnx ``` Also check the [example notebook](https://github.com/ChaoningZhang/MobileSAM/blob/master/notebooks/onnx_model_example.ipynb) to follow detailed steps. We recommend to use `onnx==1.12.0` and `onnxruntime==1.13.1` which is tested. ## BibTex of our MobileSAM If you use MobileSAM in your research, please use the following BibTeX entry. :mega: Thank you! ```bibtex @article{mobile_sam, title={Faster Segment Anything: Towards Lightweight SAM for Mobile Applications}, author={Zhang, Chaoning and Han, Dongshen and Qiao, Yu and Kim, Jung Uk and Bae, Sung-Ho and Lee, Seungkyu and Hong, Choong Seon}, journal={arXiv preprint arXiv:2306.14289}, year={2023} } ``` ## Acknowledgement This work was supported by Institute of Information & communications Technology Planning & Evaluation (IITP) grant funded by the Korea government(MSIT) (No.RS-2022-00155911, Artificial Intelligence Convergence Innovation Human Resources Development (Kyung Hee University)) <details> <summary> <a href="https://github.com/facebookresearch/segment-anything">SAM</a> (Segment Anything) [<b>bib</b>] </summary> ```bibtex @article{kirillov2023segany, title={Segment Anything}, author={Kirillov, Alexander and Mintun, Eric and Ravi, Nikhila and Mao, Hanzi and Rolland, Chloe and Gustafson, Laura and Xiao, Tete and Whitehead, Spencer and Berg, Alexander C. and Lo, Wan-Yen and Doll{\'a}r, Piotr and Girshick, Ross}, journal={arXiv:2304.02643}, year={2023} } ``` </details> <details> <summary> <a href="https://github.com/microsoft/Cream/tree/main/TinyViT">TinyViT</a> (TinyViT: Fast Pretraining Distillation for Small Vision Transformers) [<b>bib</b>] </summary> ```bibtex @InProceedings{tiny_vit, title={TinyViT: Fast Pretraining Distillation for Small Vision Transformers}, author={Wu, Kan and Zhang, Jinnian and Peng, Houwen and Liu, Mengchen and Xiao, Bin and Fu, Jianlong and Yuan, Lu}, booktitle={European conference on computer vision (ECCV)}, year={2022} ``` </details>
ESA-DatalabsREPO_NAMEXAMI-modelPATH_START.@XAMI-model_extracted@XAMI-model-main@xami_model@mobile_sam@README.md@.PATH_END.py
{ "filename": "ops.py", "repo_name": "pandas-dev/pandas", "repo_path": "pandas_extracted/pandas-main/pandas/core/internals/ops.py", "type": "Python" }
from __future__ import annotations from typing import ( TYPE_CHECKING, NamedTuple, ) from pandas.core.dtypes.common import is_1d_only_ea_dtype if TYPE_CHECKING: from collections.abc import Iterator from pandas._libs.internals import BlockPlacement from pandas._typing import ArrayLike from pandas.core.internals.blocks import Block from pandas.core.internals.managers import BlockManager class BlockPairInfo(NamedTuple): lvals: ArrayLike rvals: ArrayLike locs: BlockPlacement left_ea: bool right_ea: bool rblk: Block def _iter_block_pairs( left: BlockManager, right: BlockManager ) -> Iterator[BlockPairInfo]: # At this point we have already checked the parent DataFrames for # assert rframe._indexed_same(lframe) for blk in left.blocks: locs = blk.mgr_locs blk_vals = blk.values left_ea = blk_vals.ndim == 1 rblks = right._slice_take_blocks_ax0(locs.indexer, only_slice=True) # Assertions are disabled for performance, but should hold: # if left_ea: # assert len(locs) == 1, locs # assert len(rblks) == 1, rblks # assert rblks[0].shape[0] == 1, rblks[0].shape for rblk in rblks: right_ea = rblk.values.ndim == 1 lvals, rvals = _get_same_shape_values(blk, rblk, left_ea, right_ea) info = BlockPairInfo(lvals, rvals, locs, left_ea, right_ea, rblk) yield info def operate_blockwise( left: BlockManager, right: BlockManager, array_op ) -> BlockManager: # At this point we have already checked the parent DataFrames for # assert rframe._indexed_same(lframe) res_blks: list[Block] = [] for lvals, rvals, locs, left_ea, right_ea, rblk in _iter_block_pairs(left, right): res_values = array_op(lvals, rvals) if ( left_ea and not right_ea and hasattr(res_values, "reshape") and not is_1d_only_ea_dtype(res_values.dtype) ): res_values = res_values.reshape(1, -1) nbs = rblk._split_op_result(res_values) # Assertions are disabled for performance, but should hold: # if right_ea or left_ea: # assert len(nbs) == 1 # else: # assert res_values.shape == lvals.shape, (res_values.shape, lvals.shape) _reset_block_mgr_locs(nbs, locs) res_blks.extend(nbs) # Assertions are disabled for performance, but should hold: # slocs = {y for nb in res_blks for y in nb.mgr_locs.as_array} # nlocs = sum(len(nb.mgr_locs.as_array) for nb in res_blks) # assert nlocs == len(left.items), (nlocs, len(left.items)) # assert len(slocs) == nlocs, (len(slocs), nlocs) # assert slocs == set(range(nlocs)), slocs new_mgr = type(right)(tuple(res_blks), axes=right.axes, verify_integrity=False) return new_mgr def _reset_block_mgr_locs(nbs: list[Block], locs) -> None: """ Reset mgr_locs to correspond to our original DataFrame. """ for nb in nbs: nblocs = locs[nb.mgr_locs.indexer] nb.mgr_locs = nblocs # Assertions are disabled for performance, but should hold: # assert len(nblocs) == nb.shape[0], (len(nblocs), nb.shape) # assert all(x in locs.as_array for x in nb.mgr_locs.as_array) def _get_same_shape_values( lblk: Block, rblk: Block, left_ea: bool, right_ea: bool ) -> tuple[ArrayLike, ArrayLike]: """ Slice lblk.values to align with rblk. Squeeze if we have EAs. """ lvals = lblk.values rvals = rblk.values # Require that the indexing into lvals be slice-like assert rblk.mgr_locs.is_slice_like, rblk.mgr_locs # TODO(EA2D): with 2D EAs only this first clause would be needed if not (left_ea or right_ea): # error: No overload variant of "__getitem__" of "ExtensionArray" matches # argument type "Tuple[Union[ndarray, slice], slice]" lvals = lvals[rblk.mgr_locs.indexer, :] # type: ignore[call-overload] assert lvals.shape == rvals.shape, (lvals.shape, rvals.shape) elif left_ea and right_ea: assert lvals.shape == rvals.shape, (lvals.shape, rvals.shape) elif right_ea: # lvals are 2D, rvals are 1D # error: No overload variant of "__getitem__" of "ExtensionArray" matches # argument type "Tuple[Union[ndarray, slice], slice]" lvals = lvals[rblk.mgr_locs.indexer, :] # type: ignore[call-overload] assert lvals.shape[0] == 1, lvals.shape lvals = lvals[0, :] else: # lvals are 1D, rvals are 2D assert rvals.shape[0] == 1, rvals.shape # error: No overload variant of "__getitem__" of "ExtensionArray" matches # argument type "Tuple[int, slice]" rvals = rvals[0, :] # type: ignore[call-overload] return lvals, rvals def blockwise_all(left: BlockManager, right: BlockManager, op) -> bool: """ Blockwise `all` reduction. """ for info in _iter_block_pairs(left, right): res = op(info.lvals, info.rvals) if not res: return False return True
pandas-devREPO_NAMEpandasPATH_START.@pandas_extracted@pandas-main@pandas@core@internals@ops.py@.PATH_END.py
{ "filename": "_colorbar.py", "repo_name": "plotly/plotly.py", "repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/graph_objs/funnel/marker/_colorbar.py", "type": "Python" }
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType import copy as _copy class ColorBar(_BaseTraceHierarchyType): # class properties # -------------------- _parent_path_str = "funnel.marker" _path_str = "funnel.marker.colorbar" _valid_props = { "bgcolor", "bordercolor", "borderwidth", "dtick", "exponentformat", "labelalias", "len", "lenmode", "minexponent", "nticks", "orientation", "outlinecolor", "outlinewidth", "separatethousands", "showexponent", "showticklabels", "showtickprefix", "showticksuffix", "thickness", "thicknessmode", "tick0", "tickangle", "tickcolor", "tickfont", "tickformat", "tickformatstopdefaults", "tickformatstops", "ticklabeloverflow", "ticklabelposition", "ticklabelstep", "ticklen", "tickmode", "tickprefix", "ticks", "ticksuffix", "ticktext", "ticktextsrc", "tickvals", "tickvalssrc", "tickwidth", "title", "x", "xanchor", "xpad", "xref", "y", "yanchor", "ypad", "yref", } # bgcolor # ------- @property def bgcolor(self): """ Sets the color of padded area. The 'bgcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str """ return self["bgcolor"] @bgcolor.setter def bgcolor(self, val): self["bgcolor"] = val # bordercolor # ----------- @property def bordercolor(self): """ Sets the axis line color. The 'bordercolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str """ return self["bordercolor"] @bordercolor.setter def bordercolor(self, val): self["bordercolor"] = val # borderwidth # ----------- @property def borderwidth(self): """ Sets the width (in px) or the border enclosing this color bar. The 'borderwidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["borderwidth"] @borderwidth.setter def borderwidth(self, val): self["borderwidth"] = val # dtick # ----- @property def dtick(self): """ Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" The 'dtick' property accepts values of any type Returns ------- Any """ return self["dtick"] @dtick.setter def dtick(self, val): self["dtick"] = val # exponentformat # -------------- @property def exponentformat(self): """ Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. The 'exponentformat' property is an enumeration that may be specified as: - One of the following enumeration values: ['none', 'e', 'E', 'power', 'SI', 'B'] Returns ------- Any """ return self["exponentformat"] @exponentformat.setter def exponentformat(self, val): self["exponentformat"] = val # labelalias # ---------- @property def labelalias(self): """ Replacement text for specific tick or hover labels. For example using {US: 'USA', CA: 'Canada'} changes US to USA and CA to Canada. The labels we would have shown must match the keys exactly, after adding any tickprefix or ticksuffix. For negative numbers the minus sign symbol used (U+2212) is wider than the regular ascii dash. That means you need to use βˆ’1 instead of -1. labelalias can be used with any axis type, and both keys (if needed) and values (if desired) can include html- like tags or MathJax. The 'labelalias' property accepts values of any type Returns ------- Any """ return self["labelalias"] @labelalias.setter def labelalias(self, val): self["labelalias"] = val # len # --- @property def len(self): """ Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends. The 'len' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["len"] @len.setter def len(self, val): self["len"] = val # lenmode # ------- @property def lenmode(self): """ Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot "fraction" or in *pixels. Use `len` to set the value. The 'lenmode' property is an enumeration that may be specified as: - One of the following enumeration values: ['fraction', 'pixels'] Returns ------- Any """ return self["lenmode"] @lenmode.setter def lenmode(self, val): self["lenmode"] = val # minexponent # ----------- @property def minexponent(self): """ Hide SI prefix for 10^n if |n| is below this number. This only has an effect when `tickformat` is "SI" or "B". The 'minexponent' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["minexponent"] @minexponent.setter def minexponent(self, val): self["minexponent"] = val # nticks # ------ @property def nticks(self): """ Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". The 'nticks' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [0, 9223372036854775807] Returns ------- int """ return self["nticks"] @nticks.setter def nticks(self, val): self["nticks"] = val # orientation # ----------- @property def orientation(self): """ Sets the orientation of the colorbar. The 'orientation' property is an enumeration that may be specified as: - One of the following enumeration values: ['h', 'v'] Returns ------- Any """ return self["orientation"] @orientation.setter def orientation(self, val): self["orientation"] = val # outlinecolor # ------------ @property def outlinecolor(self): """ Sets the axis line color. The 'outlinecolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str """ return self["outlinecolor"] @outlinecolor.setter def outlinecolor(self, val): self["outlinecolor"] = val # outlinewidth # ------------ @property def outlinewidth(self): """ Sets the width (in px) of the axis line. The 'outlinewidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["outlinewidth"] @outlinewidth.setter def outlinewidth(self, val): self["outlinewidth"] = val # separatethousands # ----------------- @property def separatethousands(self): """ If "true", even 4-digit integers are separated The 'separatethousands' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["separatethousands"] @separatethousands.setter def separatethousands(self, val): self["separatethousands"] = val # showexponent # ------------ @property def showexponent(self): """ If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. The 'showexponent' property is an enumeration that may be specified as: - One of the following enumeration values: ['all', 'first', 'last', 'none'] Returns ------- Any """ return self["showexponent"] @showexponent.setter def showexponent(self, val): self["showexponent"] = val # showticklabels # -------------- @property def showticklabels(self): """ Determines whether or not the tick labels are drawn. The 'showticklabels' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["showticklabels"] @showticklabels.setter def showticklabels(self, val): self["showticklabels"] = val # showtickprefix # -------------- @property def showtickprefix(self): """ If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. The 'showtickprefix' property is an enumeration that may be specified as: - One of the following enumeration values: ['all', 'first', 'last', 'none'] Returns ------- Any """ return self["showtickprefix"] @showtickprefix.setter def showtickprefix(self, val): self["showtickprefix"] = val # showticksuffix # -------------- @property def showticksuffix(self): """ Same as `showtickprefix` but for tick suffixes. The 'showticksuffix' property is an enumeration that may be specified as: - One of the following enumeration values: ['all', 'first', 'last', 'none'] Returns ------- Any """ return self["showticksuffix"] @showticksuffix.setter def showticksuffix(self, val): self["showticksuffix"] = val # thickness # --------- @property def thickness(self): """ Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels. The 'thickness' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["thickness"] @thickness.setter def thickness(self, val): self["thickness"] = val # thicknessmode # ------------- @property def thicknessmode(self): """ Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot "fraction" or in "pixels". Use `thickness` to set the value. The 'thicknessmode' property is an enumeration that may be specified as: - One of the following enumeration values: ['fraction', 'pixels'] Returns ------- Any """ return self["thicknessmode"] @thicknessmode.setter def thicknessmode(self, val): self["thicknessmode"] = val # tick0 # ----- @property def tick0(self): """ Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. The 'tick0' property accepts values of any type Returns ------- Any """ return self["tick0"] @tick0.setter def tick0(self, val): self["tick0"] = val # tickangle # --------- @property def tickangle(self): """ Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. The 'tickangle' property is a angle (in degrees) that may be specified as a number between -180 and 180. Numeric values outside this range are converted to the equivalent value (e.g. 270 is converted to -90). Returns ------- int|float """ return self["tickangle"] @tickangle.setter def tickangle(self, val): self["tickangle"] = val # tickcolor # --------- @property def tickcolor(self): """ Sets the tick color. The 'tickcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: aliceblue, antiquewhite, aqua, aquamarine, azure, beige, bisque, black, blanchedalmond, blue, blueviolet, brown, burlywood, cadetblue, chartreuse, chocolate, coral, cornflowerblue, cornsilk, crimson, cyan, darkblue, darkcyan, darkgoldenrod, darkgray, darkgrey, darkgreen, darkkhaki, darkmagenta, darkolivegreen, darkorange, darkorchid, darkred, darksalmon, darkseagreen, darkslateblue, darkslategray, darkslategrey, darkturquoise, darkviolet, deeppink, deepskyblue, dimgray, dimgrey, dodgerblue, firebrick, floralwhite, forestgreen, fuchsia, gainsboro, ghostwhite, gold, goldenrod, gray, grey, green, greenyellow, honeydew, hotpink, indianred, indigo, ivory, khaki, lavender, lavenderblush, lawngreen, lemonchiffon, lightblue, lightcoral, lightcyan, lightgoldenrodyellow, lightgray, lightgrey, lightgreen, lightpink, lightsalmon, lightseagreen, lightskyblue, lightslategray, lightslategrey, lightsteelblue, lightyellow, lime, limegreen, linen, magenta, maroon, mediumaquamarine, mediumblue, mediumorchid, mediumpurple, mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise, mediumvioletred, midnightblue, mintcream, mistyrose, moccasin, navajowhite, navy, oldlace, olive, olivedrab, orange, orangered, orchid, palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip, peachpuff, peru, pink, plum, powderblue, purple, red, rosybrown, royalblue, rebeccapurple, saddlebrown, salmon, sandybrown, seagreen, seashell, sienna, silver, skyblue, slateblue, slategray, slategrey, snow, springgreen, steelblue, tan, teal, thistle, tomato, turquoise, violet, wheat, white, whitesmoke, yellow, yellowgreen Returns ------- str """ return self["tickcolor"] @tickcolor.setter def tickcolor(self, val): self["tickcolor"] = val # tickfont # -------- @property def tickfont(self): """ Sets the color bar's tick label font The 'tickfont' property is an instance of Tickfont that may be specified as: - An instance of :class:`plotly.graph_objs.funnel.marker.colorbar.Tickfont` - A dict of string/value properties that will be passed to the Tickfont constructor Supported dict properties: color family HTML font family - the typeface that will be applied by the web browser. The web browser will only be able to apply a font if it is available on the system which it operates. Provide multiple font families, separated by commas, to indicate the preference in which to apply fonts if they aren't available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server, where only a select number of fonts are installed and supported. These include "Arial", "Balto", "Courier New", "Droid Sans", "Droid Serif", "Droid Sans Mono", "Gravitas One", "Old Standard TT", "Open Sans", "Overpass", "PT Sans Narrow", "Raleway", "Times New Roman". lineposition Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. shadow Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en- US/docs/Web/CSS/text-shadow for additional options. size style Sets whether a font should be styled with a normal or italic face from its family. textcase Sets capitalization of text. It can be used to make text appear in all-uppercase or all- lowercase, or with each word capitalized. variant Sets the variant of the font. weight Sets the weight (or boldness) of the font. Returns ------- plotly.graph_objs.funnel.marker.colorbar.Tickfont """ return self["tickfont"] @tickfont.setter def tickfont(self, val): self["tickfont"] = val # tickformat # ---------- @property def tickformat(self): """ Sets the tick label formatting rule using d3 formatting mini- languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" The 'tickformat' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["tickformat"] @tickformat.setter def tickformat(self, val): self["tickformat"] = val # tickformatstops # --------------- @property def tickformatstops(self): """ The 'tickformatstops' property is a tuple of instances of Tickformatstop that may be specified as: - A list or tuple of instances of plotly.graph_objs.funnel.marker.colorbar.Tickformatstop - A list or tuple of dicts of string/value properties that will be passed to the Tickformatstop constructor Supported dict properties: dtickrange range [*min*, *max*], where "min", "max" - dtick values which describe some zoom level, it is possible to omit "min" or "max" value by passing "null" enabled Determines whether or not this stop is used. If `false`, this stop is ignored even within its `dtickrange`. name When used in a template, named items are created in the output figure in addition to any items the figure already has in this array. You can modify these items in the output figure by making your own item with `templateitemname` matching this `name` alongside your modifications (including `visible: false` or `enabled: false` to hide it). Has no effect outside of a template. templateitemname Used to refer to a named item in this array in the template. Named items from the template will be created even without a matching item in the input figure, but you can modify one by making an item with `templateitemname` matching its `name`, alongside your modifications (including `visible: false` or `enabled: false` to hide it). If there is no template or no matching item, this item will be hidden unless you explicitly show it with `visible: true`. value string - dtickformat for described zoom level, the same as "tickformat" Returns ------- tuple[plotly.graph_objs.funnel.marker.colorbar.Tickformatstop] """ return self["tickformatstops"] @tickformatstops.setter def tickformatstops(self, val): self["tickformatstops"] = val # tickformatstopdefaults # ---------------------- @property def tickformatstopdefaults(self): """ When used in a template (as layout.template.data.funnel.marker. colorbar.tickformatstopdefaults), sets the default property values to use for elements of funnel.marker.colorbar.tickformatstops The 'tickformatstopdefaults' property is an instance of Tickformatstop that may be specified as: - An instance of :class:`plotly.graph_objs.funnel.marker.colorbar.Tickformatstop` - A dict of string/value properties that will be passed to the Tickformatstop constructor Supported dict properties: Returns ------- plotly.graph_objs.funnel.marker.colorbar.Tickformatstop """ return self["tickformatstopdefaults"] @tickformatstopdefaults.setter def tickformatstopdefaults(self, val): self["tickformatstopdefaults"] = val # ticklabeloverflow # ----------------- @property def ticklabeloverflow(self): """ Determines how we handle tick labels that would overflow either the graph div or the domain of the axis. The default value for inside tick labels is *hide past domain*. In other cases the default is *hide past div*. The 'ticklabeloverflow' property is an enumeration that may be specified as: - One of the following enumeration values: ['allow', 'hide past div', 'hide past domain'] Returns ------- Any """ return self["ticklabeloverflow"] @ticklabeloverflow.setter def ticklabeloverflow(self, val): self["ticklabeloverflow"] = val # ticklabelposition # ----------------- @property def ticklabelposition(self): """ Determines where tick labels are drawn relative to the ticks. Left and right options are used when `orientation` is "h", top and bottom when `orientation` is "v". The 'ticklabelposition' property is an enumeration that may be specified as: - One of the following enumeration values: ['outside', 'inside', 'outside top', 'inside top', 'outside left', 'inside left', 'outside right', 'inside right', 'outside bottom', 'inside bottom'] Returns ------- Any """ return self["ticklabelposition"] @ticklabelposition.setter def ticklabelposition(self, val): self["ticklabelposition"] = val # ticklabelstep # ------------- @property def ticklabelstep(self): """ Sets the spacing between tick labels as compared to the spacing between ticks. A value of 1 (default) means each tick gets a label. A value of 2 means shows every 2nd label. A larger value n means only every nth tick is labeled. `tick0` determines which labels are shown. Not implemented for axes with `type` "log" or "multicategory", or when `tickmode` is "array". The 'ticklabelstep' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [1, 9223372036854775807] Returns ------- int """ return self["ticklabelstep"] @ticklabelstep.setter def ticklabelstep(self, val): self["ticklabelstep"] = val # ticklen # ------- @property def ticklen(self): """ Sets the tick length (in px). The 'ticklen' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["ticklen"] @ticklen.setter def ticklen(self, val): self["ticklen"] = val # tickmode # -------- @property def tickmode(self): """ Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). The 'tickmode' property is an enumeration that may be specified as: - One of the following enumeration values: ['auto', 'linear', 'array'] Returns ------- Any """ return self["tickmode"] @tickmode.setter def tickmode(self, val): self["tickmode"] = val # tickprefix # ---------- @property def tickprefix(self): """ Sets a tick label prefix. The 'tickprefix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["tickprefix"] @tickprefix.setter def tickprefix(self, val): self["tickprefix"] = val # ticks # ----- @property def ticks(self): """ Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. The 'ticks' property is an enumeration that may be specified as: - One of the following enumeration values: ['outside', 'inside', ''] Returns ------- Any """ return self["ticks"] @ticks.setter def ticks(self, val): self["ticks"] = val # ticksuffix # ---------- @property def ticksuffix(self): """ Sets a tick label suffix. The 'ticksuffix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["ticksuffix"] @ticksuffix.setter def ticksuffix(self, val): self["ticksuffix"] = val # ticktext # -------- @property def ticktext(self): """ Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. The 'ticktext' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["ticktext"] @ticktext.setter def ticktext(self, val): self["ticktext"] = val # ticktextsrc # ----------- @property def ticktextsrc(self): """ Sets the source reference on Chart Studio Cloud for `ticktext`. The 'ticktextsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["ticktextsrc"] @ticktextsrc.setter def ticktextsrc(self, val): self["ticktextsrc"] = val # tickvals # -------- @property def tickvals(self): """ Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. The 'tickvals' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["tickvals"] @tickvals.setter def tickvals(self, val): self["tickvals"] = val # tickvalssrc # ----------- @property def tickvalssrc(self): """ Sets the source reference on Chart Studio Cloud for `tickvals`. The 'tickvalssrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["tickvalssrc"] @tickvalssrc.setter def tickvalssrc(self, val): self["tickvalssrc"] = val # tickwidth # --------- @property def tickwidth(self): """ Sets the tick width (in px). The 'tickwidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["tickwidth"] @tickwidth.setter def tickwidth(self, val): self["tickwidth"] = val # title # ----- @property def title(self): """ The 'title' property is an instance of Title that may be specified as: - An instance of :class:`plotly.graph_objs.funnel.marker.colorbar.Title` - A dict of string/value properties that will be passed to the Title constructor Supported dict properties: font Sets this color bar's title font. side Determines the location of color bar's title with respect to the color bar. Defaults to "top" when `orientation` if "v" and defaults to "right" when `orientation` if "h". text Sets the title of the color bar. Returns ------- plotly.graph_objs.funnel.marker.colorbar.Title """ return self["title"] @title.setter def title(self, val): self["title"] = val # x # - @property def x(self): """ Sets the x position with respect to `xref` of the color bar (in plot fraction). When `xref` is "paper", defaults to 1.02 when `orientation` is "v" and 0.5 when `orientation` is "h". When `xref` is "container", defaults to 1 when `orientation` is "v" and 0.5 when `orientation` is "h". Must be between 0 and 1 if `xref` is "container" and between "-2" and 3 if `xref` is "paper". The 'x' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["x"] @x.setter def x(self, val): self["x"] = val # xanchor # ------- @property def xanchor(self): """ Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the color bar. Defaults to "left" when `orientation` is "v" and "center" when `orientation` is "h". The 'xanchor' property is an enumeration that may be specified as: - One of the following enumeration values: ['left', 'center', 'right'] Returns ------- Any """ return self["xanchor"] @xanchor.setter def xanchor(self, val): self["xanchor"] = val # xpad # ---- @property def xpad(self): """ Sets the amount of padding (in px) along the x direction. The 'xpad' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["xpad"] @xpad.setter def xpad(self, val): self["xpad"] = val # xref # ---- @property def xref(self): """ Sets the container `x` refers to. "container" spans the entire `width` of the plot. "paper" refers to the width of the plotting area only. The 'xref' property is an enumeration that may be specified as: - One of the following enumeration values: ['container', 'paper'] Returns ------- Any """ return self["xref"] @xref.setter def xref(self, val): self["xref"] = val # y # - @property def y(self): """ Sets the y position with respect to `yref` of the color bar (in plot fraction). When `yref` is "paper", defaults to 0.5 when `orientation` is "v" and 1.02 when `orientation` is "h". When `yref` is "container", defaults to 0.5 when `orientation` is "v" and 1 when `orientation` is "h". Must be between 0 and 1 if `yref` is "container" and between "-2" and 3 if `yref` is "paper". The 'y' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["y"] @y.setter def y(self, val): self["y"] = val # yanchor # ------- @property def yanchor(self): """ Sets this color bar's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the color bar. Defaults to "middle" when `orientation` is "v" and "bottom" when `orientation` is "h". The 'yanchor' property is an enumeration that may be specified as: - One of the following enumeration values: ['top', 'middle', 'bottom'] Returns ------- Any """ return self["yanchor"] @yanchor.setter def yanchor(self, val): self["yanchor"] = val # ypad # ---- @property def ypad(self): """ Sets the amount of padding (in px) along the y direction. The 'ypad' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["ypad"] @ypad.setter def ypad(self, val): self["ypad"] = val # yref # ---- @property def yref(self): """ Sets the container `y` refers to. "container" spans the entire `height` of the plot. "paper" refers to the height of the plotting area only. The 'yref' property is an enumeration that may be specified as: - One of the following enumeration values: ['container', 'paper'] Returns ------- Any """ return self["yref"] @yref.setter def yref(self, val): self["yref"] = val # Self properties description # --------------------------- @property def _prop_descriptions(self): return """\ bgcolor Sets the color of padded area. bordercolor Sets the axis line color. borderwidth Sets the width (in px) or the border enclosing this color bar. dtick Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" exponentformat Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. labelalias Replacement text for specific tick or hover labels. For example using {US: 'USA', CA: 'Canada'} changes US to USA and CA to Canada. The labels we would have shown must match the keys exactly, after adding any tickprefix or ticksuffix. For negative numbers the minus sign symbol used (U+2212) is wider than the regular ascii dash. That means you need to use βˆ’1 instead of -1. labelalias can be used with any axis type, and both keys (if needed) and values (if desired) can include html-like tags or MathJax. len Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends. lenmode Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot "fraction" or in *pixels. Use `len` to set the value. minexponent Hide SI prefix for 10^n if |n| is below this number. This only has an effect when `tickformat` is "SI" or "B". nticks Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". orientation Sets the orientation of the colorbar. outlinecolor Sets the axis line color. outlinewidth Sets the width (in px) of the axis line. separatethousands If "true", even 4-digit integers are separated showexponent If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. showticklabels Determines whether or not the tick labels are drawn. showtickprefix If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. showticksuffix Same as `showtickprefix` but for tick suffixes. thickness Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels. thicknessmode Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot "fraction" or in "pixels". Use `thickness` to set the value. tick0 Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. tickangle Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. tickcolor Sets the tick color. tickfont Sets the color bar's tick label font tickformat Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" tickformatstops A tuple of :class:`plotly.graph_objects.funnel.marker.c olorbar.Tickformatstop` instances or dicts with compatible properties tickformatstopdefaults When used in a template (as layout.template.data.funnel .marker.colorbar.tickformatstopdefaults), sets the default property values to use for elements of funnel.marker.colorbar.tickformatstops ticklabeloverflow Determines how we handle tick labels that would overflow either the graph div or the domain of the axis. The default value for inside tick labels is *hide past domain*. In other cases the default is *hide past div*. ticklabelposition Determines where tick labels are drawn relative to the ticks. Left and right options are used when `orientation` is "h", top and bottom when `orientation` is "v". ticklabelstep Sets the spacing between tick labels as compared to the spacing between ticks. A value of 1 (default) means each tick gets a label. A value of 2 means shows every 2nd label. A larger value n means only every nth tick is labeled. `tick0` determines which labels are shown. Not implemented for axes with `type` "log" or "multicategory", or when `tickmode` is "array". ticklen Sets the tick length (in px). tickmode Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). tickprefix Sets a tick label prefix. ticks Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. ticksuffix Sets a tick label suffix. ticktext Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. ticktextsrc Sets the source reference on Chart Studio Cloud for `ticktext`. tickvals Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. tickvalssrc Sets the source reference on Chart Studio Cloud for `tickvals`. tickwidth Sets the tick width (in px). title :class:`plotly.graph_objects.funnel.marker.colorbar.Tit le` instance or dict with compatible properties x Sets the x position with respect to `xref` of the color bar (in plot fraction). When `xref` is "paper", defaults to 1.02 when `orientation` is "v" and 0.5 when `orientation` is "h". When `xref` is "container", defaults to 1 when `orientation` is "v" and 0.5 when `orientation` is "h". Must be between 0 and 1 if `xref` is "container" and between "-2" and 3 if `xref` is "paper". xanchor Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the color bar. Defaults to "left" when `orientation` is "v" and "center" when `orientation` is "h". xpad Sets the amount of padding (in px) along the x direction. xref Sets the container `x` refers to. "container" spans the entire `width` of the plot. "paper" refers to the width of the plotting area only. y Sets the y position with respect to `yref` of the color bar (in plot fraction). When `yref` is "paper", defaults to 0.5 when `orientation` is "v" and 1.02 when `orientation` is "h". When `yref` is "container", defaults to 0.5 when `orientation` is "v" and 1 when `orientation` is "h". Must be between 0 and 1 if `yref` is "container" and between "-2" and 3 if `yref` is "paper". yanchor Sets this color bar's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the color bar. Defaults to "middle" when `orientation` is "v" and "bottom" when `orientation` is "h". ypad Sets the amount of padding (in px) along the y direction. yref Sets the container `y` refers to. "container" spans the entire `height` of the plot. "paper" refers to the height of the plotting area only. """ def __init__( self, arg=None, bgcolor=None, bordercolor=None, borderwidth=None, dtick=None, exponentformat=None, labelalias=None, len=None, lenmode=None, minexponent=None, nticks=None, orientation=None, outlinecolor=None, outlinewidth=None, separatethousands=None, showexponent=None, showticklabels=None, showtickprefix=None, showticksuffix=None, thickness=None, thicknessmode=None, tick0=None, tickangle=None, tickcolor=None, tickfont=None, tickformat=None, tickformatstops=None, tickformatstopdefaults=None, ticklabeloverflow=None, ticklabelposition=None, ticklabelstep=None, ticklen=None, tickmode=None, tickprefix=None, ticks=None, ticksuffix=None, ticktext=None, ticktextsrc=None, tickvals=None, tickvalssrc=None, tickwidth=None, title=None, x=None, xanchor=None, xpad=None, xref=None, y=None, yanchor=None, ypad=None, yref=None, **kwargs, ): """ Construct a new ColorBar object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.funnel.marker.ColorBar` bgcolor Sets the color of padded area. bordercolor Sets the axis line color. borderwidth Sets the width (in px) or the border enclosing this color bar. dtick Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" exponentformat Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. labelalias Replacement text for specific tick or hover labels. For example using {US: 'USA', CA: 'Canada'} changes US to USA and CA to Canada. The labels we would have shown must match the keys exactly, after adding any tickprefix or ticksuffix. For negative numbers the minus sign symbol used (U+2212) is wider than the regular ascii dash. That means you need to use βˆ’1 instead of -1. labelalias can be used with any axis type, and both keys (if needed) and values (if desired) can include html-like tags or MathJax. len Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends. lenmode Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot "fraction" or in *pixels. Use `len` to set the value. minexponent Hide SI prefix for 10^n if |n| is below this number. This only has an effect when `tickformat` is "SI" or "B". nticks Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". orientation Sets the orientation of the colorbar. outlinecolor Sets the axis line color. outlinewidth Sets the width (in px) of the axis line. separatethousands If "true", even 4-digit integers are separated showexponent If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. showticklabels Determines whether or not the tick labels are drawn. showtickprefix If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. showticksuffix Same as `showtickprefix` but for tick suffixes. thickness Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels. thicknessmode Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot "fraction" or in "pixels". Use `thickness` to set the value. tick0 Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. tickangle Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. tickcolor Sets the tick color. tickfont Sets the color bar's tick label font tickformat Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" tickformatstops A tuple of :class:`plotly.graph_objects.funnel.marker.c olorbar.Tickformatstop` instances or dicts with compatible properties tickformatstopdefaults When used in a template (as layout.template.data.funnel .marker.colorbar.tickformatstopdefaults), sets the default property values to use for elements of funnel.marker.colorbar.tickformatstops ticklabeloverflow Determines how we handle tick labels that would overflow either the graph div or the domain of the axis. The default value for inside tick labels is *hide past domain*. In other cases the default is *hide past div*. ticklabelposition Determines where tick labels are drawn relative to the ticks. Left and right options are used when `orientation` is "h", top and bottom when `orientation` is "v". ticklabelstep Sets the spacing between tick labels as compared to the spacing between ticks. A value of 1 (default) means each tick gets a label. A value of 2 means shows every 2nd label. A larger value n means only every nth tick is labeled. `tick0` determines which labels are shown. Not implemented for axes with `type` "log" or "multicategory", or when `tickmode` is "array". ticklen Sets the tick length (in px). tickmode Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). tickprefix Sets a tick label prefix. ticks Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. ticksuffix Sets a tick label suffix. ticktext Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. ticktextsrc Sets the source reference on Chart Studio Cloud for `ticktext`. tickvals Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. tickvalssrc Sets the source reference on Chart Studio Cloud for `tickvals`. tickwidth Sets the tick width (in px). title :class:`plotly.graph_objects.funnel.marker.colorbar.Tit le` instance or dict with compatible properties x Sets the x position with respect to `xref` of the color bar (in plot fraction). When `xref` is "paper", defaults to 1.02 when `orientation` is "v" and 0.5 when `orientation` is "h". When `xref` is "container", defaults to 1 when `orientation` is "v" and 0.5 when `orientation` is "h". Must be between 0 and 1 if `xref` is "container" and between "-2" and 3 if `xref` is "paper". xanchor Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the color bar. Defaults to "left" when `orientation` is "v" and "center" when `orientation` is "h". xpad Sets the amount of padding (in px) along the x direction. xref Sets the container `x` refers to. "container" spans the entire `width` of the plot. "paper" refers to the width of the plotting area only. y Sets the y position with respect to `yref` of the color bar (in plot fraction). When `yref` is "paper", defaults to 0.5 when `orientation` is "v" and 1.02 when `orientation` is "h". When `yref` is "container", defaults to 0.5 when `orientation` is "v" and 1 when `orientation` is "h". Must be between 0 and 1 if `yref` is "container" and between "-2" and 3 if `yref` is "paper". yanchor Sets this color bar's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the color bar. Defaults to "middle" when `orientation` is "v" and "bottom" when `orientation` is "h". ypad Sets the amount of padding (in px) along the y direction. yref Sets the container `y` refers to. "container" spans the entire `height` of the plot. "paper" refers to the height of the plotting area only. Returns ------- ColorBar """ super(ColorBar, self).__init__("colorbar") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.funnel.marker.ColorBar constructor must be a dict or an instance of :class:`plotly.graph_objs.funnel.marker.ColorBar`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("bgcolor", None) _v = bgcolor if bgcolor is not None else _v if _v is not None: self["bgcolor"] = _v _v = arg.pop("bordercolor", None) _v = bordercolor if bordercolor is not None else _v if _v is not None: self["bordercolor"] = _v _v = arg.pop("borderwidth", None) _v = borderwidth if borderwidth is not None else _v if _v is not None: self["borderwidth"] = _v _v = arg.pop("dtick", None) _v = dtick if dtick is not None else _v if _v is not None: self["dtick"] = _v _v = arg.pop("exponentformat", None) _v = exponentformat if exponentformat is not None else _v if _v is not None: self["exponentformat"] = _v _v = arg.pop("labelalias", None) _v = labelalias if labelalias is not None else _v if _v is not None: self["labelalias"] = _v _v = arg.pop("len", None) _v = len if len is not None else _v if _v is not None: self["len"] = _v _v = arg.pop("lenmode", None) _v = lenmode if lenmode is not None else _v if _v is not None: self["lenmode"] = _v _v = arg.pop("minexponent", None) _v = minexponent if minexponent is not None else _v if _v is not None: self["minexponent"] = _v _v = arg.pop("nticks", None) _v = nticks if nticks is not None else _v if _v is not None: self["nticks"] = _v _v = arg.pop("orientation", None) _v = orientation if orientation is not None else _v if _v is not None: self["orientation"] = _v _v = arg.pop("outlinecolor", None) _v = outlinecolor if outlinecolor is not None else _v if _v is not None: self["outlinecolor"] = _v _v = arg.pop("outlinewidth", None) _v = outlinewidth if outlinewidth is not None else _v if _v is not None: self["outlinewidth"] = _v _v = arg.pop("separatethousands", None) _v = separatethousands if separatethousands is not None else _v if _v is not None: self["separatethousands"] = _v _v = arg.pop("showexponent", None) _v = showexponent if showexponent is not None else _v if _v is not None: self["showexponent"] = _v _v = arg.pop("showticklabels", None) _v = showticklabels if showticklabels is not None else _v if _v is not None: self["showticklabels"] = _v _v = arg.pop("showtickprefix", None) _v = showtickprefix if showtickprefix is not None else _v if _v is not None: self["showtickprefix"] = _v _v = arg.pop("showticksuffix", None) _v = showticksuffix if showticksuffix is not None else _v if _v is not None: self["showticksuffix"] = _v _v = arg.pop("thickness", None) _v = thickness if thickness is not None else _v if _v is not None: self["thickness"] = _v _v = arg.pop("thicknessmode", None) _v = thicknessmode if thicknessmode is not None else _v if _v is not None: self["thicknessmode"] = _v _v = arg.pop("tick0", None) _v = tick0 if tick0 is not None else _v if _v is not None: self["tick0"] = _v _v = arg.pop("tickangle", None) _v = tickangle if tickangle is not None else _v if _v is not None: self["tickangle"] = _v _v = arg.pop("tickcolor", None) _v = tickcolor if tickcolor is not None else _v if _v is not None: self["tickcolor"] = _v _v = arg.pop("tickfont", None) _v = tickfont if tickfont is not None else _v if _v is not None: self["tickfont"] = _v _v = arg.pop("tickformat", None) _v = tickformat if tickformat is not None else _v if _v is not None: self["tickformat"] = _v _v = arg.pop("tickformatstops", None) _v = tickformatstops if tickformatstops is not None else _v if _v is not None: self["tickformatstops"] = _v _v = arg.pop("tickformatstopdefaults", None) _v = tickformatstopdefaults if tickformatstopdefaults is not None else _v if _v is not None: self["tickformatstopdefaults"] = _v _v = arg.pop("ticklabeloverflow", None) _v = ticklabeloverflow if ticklabeloverflow is not None else _v if _v is not None: self["ticklabeloverflow"] = _v _v = arg.pop("ticklabelposition", None) _v = ticklabelposition if ticklabelposition is not None else _v if _v is not None: self["ticklabelposition"] = _v _v = arg.pop("ticklabelstep", None) _v = ticklabelstep if ticklabelstep is not None else _v if _v is not None: self["ticklabelstep"] = _v _v = arg.pop("ticklen", None) _v = ticklen if ticklen is not None else _v if _v is not None: self["ticklen"] = _v _v = arg.pop("tickmode", None) _v = tickmode if tickmode is not None else _v if _v is not None: self["tickmode"] = _v _v = arg.pop("tickprefix", None) _v = tickprefix if tickprefix is not None else _v if _v is not None: self["tickprefix"] = _v _v = arg.pop("ticks", None) _v = ticks if ticks is not None else _v if _v is not None: self["ticks"] = _v _v = arg.pop("ticksuffix", None) _v = ticksuffix if ticksuffix is not None else _v if _v is not None: self["ticksuffix"] = _v _v = arg.pop("ticktext", None) _v = ticktext if ticktext is not None else _v if _v is not None: self["ticktext"] = _v _v = arg.pop("ticktextsrc", None) _v = ticktextsrc if ticktextsrc is not None else _v if _v is not None: self["ticktextsrc"] = _v _v = arg.pop("tickvals", None) _v = tickvals if tickvals is not None else _v if _v is not None: self["tickvals"] = _v _v = arg.pop("tickvalssrc", None) _v = tickvalssrc if tickvalssrc is not None else _v if _v is not None: self["tickvalssrc"] = _v _v = arg.pop("tickwidth", None) _v = tickwidth if tickwidth is not None else _v if _v is not None: self["tickwidth"] = _v _v = arg.pop("title", None) _v = title if title is not None else _v if _v is not None: self["title"] = _v _v = arg.pop("x", None) _v = x if x is not None else _v if _v is not None: self["x"] = _v _v = arg.pop("xanchor", None) _v = xanchor if xanchor is not None else _v if _v is not None: self["xanchor"] = _v _v = arg.pop("xpad", None) _v = xpad if xpad is not None else _v if _v is not None: self["xpad"] = _v _v = arg.pop("xref", None) _v = xref if xref is not None else _v if _v is not None: self["xref"] = _v _v = arg.pop("y", None) _v = y if y is not None else _v if _v is not None: self["y"] = _v _v = arg.pop("yanchor", None) _v = yanchor if yanchor is not None else _v if _v is not None: self["yanchor"] = _v _v = arg.pop("ypad", None) _v = ypad if ypad is not None else _v if _v is not None: self["ypad"] = _v _v = arg.pop("yref", None) _v = yref if yref is not None else _v if _v is not None: self["yref"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@graph_objs@funnel@marker@_colorbar.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/graph_objs/image/hoverlabel/__init__.py", "type": "Python" }
import sys from typing import TYPE_CHECKING if sys.version_info < (3, 7) or TYPE_CHECKING: from ._font import Font else: from _plotly_utils.importers import relative_import __all__, __getattr__, __dir__ = relative_import(__name__, [], ["._font.Font"])
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@graph_objs@image@hoverlabel@__init__.py@.PATH_END.py
{ "filename": "test_create_cat_B_calibration_files.py", "repo_name": "cta-observatory/cta-lstchain", "repo_path": "cta-lstchain_extracted/cta-lstchain-main/lstchain/tools/tests/test_create_cat_B_calibration_files.py", "type": "Python" }
import numpy as np from ctapipe.core import run_tool from ctapipe_io_lst.constants import N_GAINS, N_PIXELS from ctapipe.io import read_table from lstchain.onsite import DEFAULT_CONFIG_CAT_B_CALIB from lstchain.tests.test_lstchain import ( test_systematics_path, test_calib_path ) def test_create_catB_calibration_file(tmp_path,interleaved_r1_file): '''Test the lstchain_create_cat_B_calibration_file tool''' from lstchain.tools.lstchain_create_cat_B_calibration_file import CatBCalibrationHDF5Writer input_path = interleaved_r1_file.parent output_path = tmp_path / "calibration_cat_B_02006.h5" stat_events = 90 ret = run_tool( CatBCalibrationHDF5Writer(), argv=[ f"--input_path={input_path}", f"--output_file={output_path}", f"--cat_A_calibration_file={test_calib_path}", f"--LSTCalibrationCalculator.systematic_correction_path={test_systematics_path}", f"--FlasherFlatFieldCalculator.sample_size={stat_events}", f"--PedestalIntegrator.sample_size={stat_events}", f"--config={DEFAULT_CONFIG_CAT_B_CALIB}", "--overwrite", ], cwd=tmp_path, ) assert ret == 0, 'Running CalibrationHDF5Writer tool failed' assert output_path.is_file(), 'Output file not written' cal_data = read_table(output_path, '/tel_1/calibration')[0] n_pe = cal_data['n_pe'] unusable_pixels = cal_data['unusable_pixels'] dc_to_pe = cal_data["dc_to_pe"] assert n_pe.shape == (N_GAINS, N_PIXELS) assert np.sum(unusable_pixels) == 4 assert np.isclose(np.median(n_pe[~unusable_pixels]), 86.34, rtol=0.1) assert np.isclose(np.median(dc_to_pe[~unusable_pixels], axis=0), 1.07, rtol=0.01)
cta-observatoryREPO_NAMEcta-lstchainPATH_START.@cta-lstchain_extracted@cta-lstchain-main@lstchain@tools@tests@test_create_cat_B_calibration_files.py@.PATH_END.py
{ "filename": "test_scalar.py", "repo_name": "ellawang44/Breidablik", "repo_path": "Breidablik_extracted/Breidablik-master/breidablik/interpolate/test_scalar.py", "type": "Python" }
from breidablik.interpolate.scalar import Scalar import numpy as np import pytest import warnings def assert_array_eq(x, y): assert np.array_equal(x, y) class Test_fit: @classmethod def setup_class(cls): cls.models = Scalar() def test_input(self): with pytest.raises(ValueError): Test_fit.models.fit(5) def test_dimension(self): with pytest.raises(ValueError): Test_fit.models.fit([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) def test_case1(self): Test_fit.models.fit([[1, 2], [3, 4]]) assert_array_eq(Test_fit.models.mean, [2, 3]) assert_array_eq(Test_fit.models.std, [1, 1]) class Test_transform: @classmethod def setup_class(cls): cls.models = Scalar() def test_existance(self): with pytest.raises(AttributeError): Test_transform.models.transform([1, 2]) def test_input(self): Test_transform.models.fit([[1, 2], [3, 4]]) with pytest.raises(ValueError): Test_transform.models.transform(5) def test_dimension(self): with pytest.raises(ValueError): Test_transform.models.transform([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) def test_dimension2(self): with pytest.raises(ValueError): Test_transform.models.transform([[1, 2, 3, 4], [1, 2, 3, 4]]) def test_case1(self): assert_array_eq(Test_transform.models.transform([[1, 2], [3, 4]]), [[-1, -1], [1, 1]]) class Test_save: @classmethod def setup_class(cls): cls.models = Scalar() def test_existance(self): with pytest.raises(AttributeError): Test_save.models.save('hi.npy') class Test_load: @classmethod def setup_class(cls): cls.models = Scalar() def test_fnferror(self): with pytest.raises(FileNotFoundError): Test_load.models.load('__this_file_should_not_exist__')
ellawang44REPO_NAMEBreidablikPATH_START.@Breidablik_extracted@Breidablik-master@breidablik@interpolate@test_scalar.py@.PATH_END.py
{ "filename": "_line.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/funnelarea/marker/_line.py", "type": "Python" }
import _plotly_utils.basevalidators class LineValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="line", parent_name="funnelarea.marker", **kwargs): super(LineValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Line"), data_docs=kwargs.pop( "data_docs", """ color Sets the color of the line enclosing each sector. Defaults to the `paper_bgcolor` value. colorsrc Sets the source reference on Chart Studio Cloud for `color`. width Sets the width (in px) of the line enclosing each sector. widthsrc Sets the source reference on Chart Studio Cloud for `width`. """, ), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@funnelarea@marker@_line.py@.PATH_END.py
{ "filename": "package_index.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/setuptools/py3/setuptools/package_index.py", "type": "Python" }
"""PyPI and direct package downloading.""" import sys import subprocess import os import re import io import shutil import socket import base64 import hashlib import itertools import configparser import html import http.client import urllib.parse import urllib.request import urllib.error from functools import wraps import setuptools from pkg_resources import ( CHECKOUT_DIST, Distribution, BINARY_DIST, normalize_path, SOURCE_DIST, Environment, find_distributions, safe_name, safe_version, to_filename, Requirement, DEVELOP_DIST, EGG_DIST, parse_version, ) from distutils import log from distutils.errors import DistutilsError from fnmatch import translate from setuptools.wheel import Wheel from setuptools.extern.more_itertools import unique_everseen from .unicode_utils import _read_utf8_with_fallback, _cfg_read_utf8_with_fallback EGG_FRAGMENT = re.compile(r'^egg=([-A-Za-z0-9_.+!]+)$') HREF = re.compile(r"""href\s*=\s*['"]?([^'"> ]+)""", re.I) PYPI_MD5 = re.compile( r'<a href="([^"#]+)">([^<]+)</a>\n\s+\(<a (?:title="MD5 hash"\n\s+)' r'href="[^?]+\?:action=show_md5&amp;digest=([0-9a-f]{32})">md5</a>\)' ) URL_SCHEME = re.compile('([-+.a-z0-9]{2,}):', re.I).match EXTENSIONS = ".tar.gz .tar.bz2 .tar .zip .tgz".split() __all__ = [ 'PackageIndex', 'distros_for_url', 'parse_bdist_wininst', 'interpret_distro_name', ] _SOCKET_TIMEOUT = 15 _tmpl = "setuptools/{setuptools.__version__} Python-urllib/{py_major}" user_agent = _tmpl.format( py_major='{}.{}'.format(*sys.version_info), setuptools=setuptools ) def parse_requirement_arg(spec): try: return Requirement.parse(spec) except ValueError as e: raise DistutilsError( "Not a URL, existing file, or requirement spec: %r" % (spec,) ) from e def parse_bdist_wininst(name): """Return (base,pyversion) or (None,None) for possible .exe name""" lower = name.lower() base, py_ver, plat = None, None, None if lower.endswith('.exe'): if lower.endswith('.win32.exe'): base = name[:-10] plat = 'win32' elif lower.startswith('.win32-py', -16): py_ver = name[-7:-4] base = name[:-16] plat = 'win32' elif lower.endswith('.win-amd64.exe'): base = name[:-14] plat = 'win-amd64' elif lower.startswith('.win-amd64-py', -20): py_ver = name[-7:-4] base = name[:-20] plat = 'win-amd64' return base, py_ver, plat def egg_info_for_url(url): parts = urllib.parse.urlparse(url) scheme, server, path, parameters, query, fragment = parts base = urllib.parse.unquote(path.split('/')[-1]) if server == 'sourceforge.net' and base == 'download': # XXX Yuck base = urllib.parse.unquote(path.split('/')[-2]) if '#' in base: base, fragment = base.split('#', 1) return base, fragment def distros_for_url(url, metadata=None): """Yield egg or source distribution objects that might be found at a URL""" base, fragment = egg_info_for_url(url) yield from distros_for_location(url, base, metadata) if fragment: match = EGG_FRAGMENT.match(fragment) if match: yield from interpret_distro_name( url, match.group(1), metadata, precedence=CHECKOUT_DIST ) def distros_for_location(location, basename, metadata=None): """Yield egg or source distribution objects based on basename""" if basename.endswith('.egg.zip'): basename = basename[:-4] # strip the .zip if basename.endswith('.egg') and '-' in basename: # only one, unambiguous interpretation return [Distribution.from_location(location, basename, metadata)] if basename.endswith('.whl') and '-' in basename: wheel = Wheel(basename) if not wheel.is_compatible(): return [] return [ Distribution( location=location, project_name=wheel.project_name, version=wheel.version, # Increase priority over eggs. precedence=EGG_DIST + 1, ) ] if basename.endswith('.exe'): win_base, py_ver, platform = parse_bdist_wininst(basename) if win_base is not None: return interpret_distro_name( location, win_base, metadata, py_ver, BINARY_DIST, platform ) # Try source distro extensions (.zip, .tgz, etc.) # for ext in EXTENSIONS: if basename.endswith(ext): basename = basename[: -len(ext)] return interpret_distro_name(location, basename, metadata) return [] # no extension matched def distros_for_filename(filename, metadata=None): """Yield possible egg or source distribution objects based on a filename""" return distros_for_location( normalize_path(filename), os.path.basename(filename), metadata ) def interpret_distro_name( location, basename, metadata, py_version=None, precedence=SOURCE_DIST, platform=None ): """Generate the interpretation of a source distro name Note: if `location` is a filesystem filename, you should call ``pkg_resources.normalize_path()`` on it before passing it to this routine! """ parts = basename.split('-') if not py_version and any(re.match(r'py\d\.\d$', p) for p in parts[2:]): # it is a bdist_dumb, not an sdist -- bail out return # find the pivot (p) that splits the name from the version. # infer the version as the first item that has a digit. for p in range(len(parts)): if parts[p][:1].isdigit(): break else: p = len(parts) yield Distribution( location, metadata, '-'.join(parts[:p]), '-'.join(parts[p:]), py_version=py_version, precedence=precedence, platform=platform, ) def unique_values(func): """ Wrap a function returning an iterable such that the resulting iterable only ever yields unique items. """ @wraps(func) def wrapper(*args, **kwargs): return unique_everseen(func(*args, **kwargs)) return wrapper REL = re.compile(r"""<([^>]*\srel\s{0,10}=\s{0,10}['"]?([^'" >]+)[^>]*)>""", re.I) """ Regex for an HTML tag with 'rel="val"' attributes. """ @unique_values def find_external_links(url, page): """Find rel="homepage" and rel="download" links in `page`, yielding URLs""" for match in REL.finditer(page): tag, rel = match.groups() rels = set(map(str.strip, rel.lower().split(','))) if 'homepage' in rels or 'download' in rels: for match in HREF.finditer(tag): yield urllib.parse.urljoin(url, htmldecode(match.group(1))) for tag in ("<th>Home Page", "<th>Download URL"): pos = page.find(tag) if pos != -1: match = HREF.search(page, pos) if match: yield urllib.parse.urljoin(url, htmldecode(match.group(1))) class ContentChecker: """ A null content checker that defines the interface for checking content """ def feed(self, block): """ Feed a block of data to the hash. """ return def is_valid(self): """ Check the hash. Return False if validation fails. """ return True def report(self, reporter, template): """ Call reporter with information about the checker (hash name) substituted into the template. """ return class HashChecker(ContentChecker): pattern = re.compile( r'(?P<hash_name>sha1|sha224|sha384|sha256|sha512|md5)=' r'(?P<expected>[a-f0-9]+)' ) def __init__(self, hash_name, expected): self.hash_name = hash_name self.hash = hashlib.new(hash_name) self.expected = expected @classmethod def from_url(cls, url): "Construct a (possibly null) ContentChecker from a URL" fragment = urllib.parse.urlparse(url)[-1] if not fragment: return ContentChecker() match = cls.pattern.search(fragment) if not match: return ContentChecker() return cls(**match.groupdict()) def feed(self, block): self.hash.update(block) def is_valid(self): return self.hash.hexdigest() == self.expected def report(self, reporter, template): msg = template % self.hash_name return reporter(msg) class PackageIndex(Environment): """A distribution index that scans web pages for download URLs""" def __init__( self, index_url="https://pypi.org/simple/", hosts=('*',), ca_bundle=None, verify_ssl=True, *args, **kw, ): super().__init__(*args, **kw) self.index_url = index_url + "/"[: not index_url.endswith('/')] self.scanned_urls = {} self.fetched_urls = {} self.package_pages = {} self.allows = re.compile('|'.join(map(translate, hosts))).match self.to_scan = [] self.opener = urllib.request.urlopen def add(self, dist): # ignore invalid versions try: parse_version(dist.version) except Exception: return None return super().add(dist) # FIXME: 'PackageIndex.process_url' is too complex (14) def process_url(self, url, retrieve=False): # noqa: C901 """Evaluate a URL as a possible download, and maybe retrieve it""" if url in self.scanned_urls and not retrieve: return self.scanned_urls[url] = True if not URL_SCHEME(url): self.process_filename(url) return else: dists = list(distros_for_url(url)) if dists: if not self.url_ok(url): return self.debug("Found link: %s", url) if dists or not retrieve or url in self.fetched_urls: list(map(self.add, dists)) return # don't need the actual page if not self.url_ok(url): self.fetched_urls[url] = True return self.info("Reading %s", url) self.fetched_urls[url] = True # prevent multiple fetch attempts tmpl = "Download error on %s: %%s -- Some packages may not be found!" f = self.open_url(url, tmpl % url) if f is None: return if isinstance(f, urllib.error.HTTPError) and f.code == 401: self.info("Authentication error: %s" % f.msg) self.fetched_urls[f.url] = True if 'html' not in f.headers.get('content-type', '').lower(): f.close() # not html, we can't process it return base = f.url # handle redirects page = f.read() if not isinstance(page, str): # In Python 3 and got bytes but want str. if isinstance(f, urllib.error.HTTPError): # Errors have no charset, assume latin1: charset = 'latin-1' else: charset = f.headers.get_param('charset') or 'latin-1' page = page.decode(charset, "ignore") f.close() for match in HREF.finditer(page): link = urllib.parse.urljoin(base, htmldecode(match.group(1))) self.process_url(link) if url.startswith(self.index_url) and getattr(f, 'code', None) != 404: page = self.process_index(url, page) def process_filename(self, fn, nested=False): # process filenames or directories if not os.path.exists(fn): self.warn("Not found: %s", fn) return if os.path.isdir(fn) and not nested: path = os.path.realpath(fn) for item in os.listdir(path): self.process_filename(os.path.join(path, item), True) dists = distros_for_filename(fn) if dists: self.debug("Found: %s", fn) list(map(self.add, dists)) def url_ok(self, url, fatal=False): s = URL_SCHEME(url) is_file = s and s.group(1).lower() == 'file' if is_file or self.allows(urllib.parse.urlparse(url)[1]): return True msg = ( "\nNote: Bypassing %s (disallowed host; see " "https://setuptools.pypa.io/en/latest/deprecated/" "easy_install.html#restricting-downloads-with-allow-hosts for details).\n" ) if fatal: raise DistutilsError(msg % url) else: self.warn(msg, url) return False def scan_egg_links(self, search_path): dirs = filter(os.path.isdir, search_path) egg_links = ( (path, entry) for path in dirs for entry in os.listdir(path) if entry.endswith('.egg-link') ) list(itertools.starmap(self.scan_egg_link, egg_links)) def scan_egg_link(self, path, entry): content = _read_utf8_with_fallback(os.path.join(path, entry)) # filter non-empty lines lines = list(filter(None, map(str.strip, content.splitlines()))) if len(lines) != 2: # format is not recognized; punt return egg_path, setup_path = lines for dist in find_distributions(os.path.join(path, egg_path)): dist.location = os.path.join(path, *lines) dist.precedence = SOURCE_DIST self.add(dist) def _scan(self, link): # Process a URL to see if it's for a package page NO_MATCH_SENTINEL = None, None if not link.startswith(self.index_url): return NO_MATCH_SENTINEL parts = list(map(urllib.parse.unquote, link[len(self.index_url) :].split('/'))) if len(parts) != 2 or '#' in parts[1]: return NO_MATCH_SENTINEL # it's a package page, sanitize and index it pkg = safe_name(parts[0]) ver = safe_version(parts[1]) self.package_pages.setdefault(pkg.lower(), {})[link] = True return to_filename(pkg), to_filename(ver) def process_index(self, url, page): """Process the contents of a PyPI page""" # process an index page into the package-page index for match in HREF.finditer(page): try: self._scan(urllib.parse.urljoin(url, htmldecode(match.group(1)))) except ValueError: pass pkg, ver = self._scan(url) # ensure this page is in the page index if not pkg: return "" # no sense double-scanning non-package pages # process individual package page for new_url in find_external_links(url, page): # Process the found URL base, frag = egg_info_for_url(new_url) if base.endswith('.py') and not frag: if ver: new_url += '#egg=%s-%s' % (pkg, ver) else: self.need_version_info(url) self.scan_url(new_url) return PYPI_MD5.sub( lambda m: '<a href="%s#md5=%s">%s</a>' % m.group(1, 3, 2), page ) def need_version_info(self, url): self.scan_all( "Page at %s links to .py file(s) without version info; an index " "scan is required.", url, ) def scan_all(self, msg=None, *args): if self.index_url not in self.fetched_urls: if msg: self.warn(msg, *args) self.info("Scanning index of all packages (this may take a while)") self.scan_url(self.index_url) def find_packages(self, requirement): self.scan_url(self.index_url + requirement.unsafe_name + '/') if not self.package_pages.get(requirement.key): # Fall back to safe version of the name self.scan_url(self.index_url + requirement.project_name + '/') if not self.package_pages.get(requirement.key): # We couldn't find the target package, so search the index page too self.not_found_in_index(requirement) for url in list(self.package_pages.get(requirement.key, ())): # scan each page that might be related to the desired package self.scan_url(url) def obtain(self, requirement, installer=None): self.prescan() self.find_packages(requirement) for dist in self[requirement.key]: if dist in requirement: return dist self.debug("%s does not match %s", requirement, dist) return super().obtain(requirement, installer) def check_hash(self, checker, filename, tfp): """ checker is a ContentChecker """ checker.report(self.debug, "Validating %%s checksum for %s" % filename) if not checker.is_valid(): tfp.close() os.unlink(filename) raise DistutilsError( "%s validation failed for %s; " "possible download problem?" % (checker.hash.name, os.path.basename(filename)) ) def add_find_links(self, urls): """Add `urls` to the list that will be prescanned for searches""" for url in urls: if ( self.to_scan is None # if we have already "gone online" or not URL_SCHEME(url) # or it's a local file/directory or url.startswith('file:') or list(distros_for_url(url)) # or a direct package link ): # then go ahead and process it now self.scan_url(url) else: # otherwise, defer retrieval till later self.to_scan.append(url) def prescan(self): """Scan urls scheduled for prescanning (e.g. --find-links)""" if self.to_scan: list(map(self.scan_url, self.to_scan)) self.to_scan = None # from now on, go ahead and process immediately def not_found_in_index(self, requirement): if self[requirement.key]: # we've seen at least one distro meth, msg = self.info, "Couldn't retrieve index page for %r" else: # no distros seen for this name, might be misspelled meth, msg = ( self.warn, "Couldn't find index page for %r (maybe misspelled?)", ) meth(msg, requirement.unsafe_name) self.scan_all() def download(self, spec, tmpdir): """Locate and/or download `spec` to `tmpdir`, returning a local path `spec` may be a ``Requirement`` object, or a string containing a URL, an existing local filename, or a project/version requirement spec (i.e. the string form of a ``Requirement`` object). If it is the URL of a .py file with an unambiguous ``#egg=name-version`` tag (i.e., one that escapes ``-`` as ``_`` throughout), a trivial ``setup.py`` is automatically created alongside the downloaded file. If `spec` is a ``Requirement`` object or a string containing a project/version requirement spec, this method returns the location of a matching distribution (possibly after downloading it to `tmpdir`). If `spec` is a locally existing file or directory name, it is simply returned unchanged. If `spec` is a URL, it is downloaded to a subpath of `tmpdir`, and the local filename is returned. Various errors may be raised if a problem occurs during downloading. """ if not isinstance(spec, Requirement): scheme = URL_SCHEME(spec) if scheme: # It's a url, download it to tmpdir found = self._download_url(spec, tmpdir) base, fragment = egg_info_for_url(spec) if base.endswith('.py'): found = self.gen_setup(found, fragment, tmpdir) return found elif os.path.exists(spec): # Existing file or directory, just return it return spec else: spec = parse_requirement_arg(spec) return getattr(self.fetch_distribution(spec, tmpdir), 'location', None) def fetch_distribution( # noqa: C901 # is too complex (14) # FIXME self, requirement, tmpdir, force_scan=False, source=False, develop_ok=False, local_index=None, ): """Obtain a distribution suitable for fulfilling `requirement` `requirement` must be a ``pkg_resources.Requirement`` instance. If necessary, or if the `force_scan` flag is set, the requirement is searched for in the (online) package index as well as the locally installed packages. If a distribution matching `requirement` is found, the returned distribution's ``location`` is the value you would have gotten from calling the ``download()`` method with the matching distribution's URL or filename. If no matching distribution is found, ``None`` is returned. If the `source` flag is set, only source distributions and source checkout links will be considered. Unless the `develop_ok` flag is set, development and system eggs (i.e., those using the ``.egg-info`` format) will be ignored. """ # process a Requirement self.info("Searching for %s", requirement) skipped = set() dist = None def find(req, env=None): if env is None: env = self # Find a matching distribution; may be called more than once for dist in env[req.key]: if dist.precedence == DEVELOP_DIST and not develop_ok: if dist not in skipped: self.warn( "Skipping development or system egg: %s", dist, ) skipped.add(dist) continue test = dist in req and (dist.precedence <= SOURCE_DIST or not source) if test: loc = self.download(dist.location, tmpdir) dist.download_location = loc if os.path.exists(dist.download_location): return dist return None if force_scan: self.prescan() self.find_packages(requirement) dist = find(requirement) if not dist and local_index is not None: dist = find(requirement, local_index) if dist is None: if self.to_scan is not None: self.prescan() dist = find(requirement) if dist is None and not force_scan: self.find_packages(requirement) dist = find(requirement) if dist is None: self.warn( "No local packages or working download links found for %s%s", (source and "a source distribution of " or ""), requirement, ) return None else: self.info("Best match: %s", dist) return dist.clone(location=dist.download_location) def fetch(self, requirement, tmpdir, force_scan=False, source=False): """Obtain a file suitable for fulfilling `requirement` DEPRECATED; use the ``fetch_distribution()`` method now instead. For backward compatibility, this routine is identical but returns the ``location`` of the downloaded distribution instead of a distribution object. """ dist = self.fetch_distribution(requirement, tmpdir, force_scan, source) if dist is not None: return dist.location return None def gen_setup(self, filename, fragment, tmpdir): match = EGG_FRAGMENT.match(fragment) dists = ( match and [ d for d in interpret_distro_name(filename, match.group(1), None) if d.version ] or [] ) if len(dists) == 1: # unambiguous ``#egg`` fragment basename = os.path.basename(filename) # Make sure the file has been downloaded to the temp dir. if os.path.dirname(filename) != tmpdir: dst = os.path.join(tmpdir, basename) if not (os.path.exists(dst) and os.path.samefile(filename, dst)): shutil.copy2(filename, dst) filename = dst with open(os.path.join(tmpdir, 'setup.py'), 'w', encoding="utf-8") as file: file.write( "from setuptools import setup\n" "setup(name=%r, version=%r, py_modules=[%r])\n" % ( dists[0].project_name, dists[0].version, os.path.splitext(basename)[0], ) ) return filename elif match: raise DistutilsError( "Can't unambiguously interpret project/version identifier %r; " "any dashes in the name or version should be escaped using " "underscores. %r" % (fragment, dists) ) else: raise DistutilsError( "Can't process plain .py files without an '#egg=name-version'" " suffix to enable automatic setup script generation." ) dl_blocksize = 8192 def _download_to(self, url, filename): self.info("Downloading %s", url) # Download the file fp = None try: checker = HashChecker.from_url(url) fp = self.open_url(url) if isinstance(fp, urllib.error.HTTPError): raise DistutilsError( "Can't download %s: %s %s" % (url, fp.code, fp.msg) ) headers = fp.info() blocknum = 0 bs = self.dl_blocksize size = -1 if "content-length" in headers: # Some servers return multiple Content-Length headers :( sizes = headers.get_all('Content-Length') size = max(map(int, sizes)) self.reporthook(url, filename, blocknum, bs, size) with open(filename, 'wb') as tfp: while True: block = fp.read(bs) if block: checker.feed(block) tfp.write(block) blocknum += 1 self.reporthook(url, filename, blocknum, bs, size) else: break self.check_hash(checker, filename, tfp) return headers finally: if fp: fp.close() def reporthook(self, url, filename, blocknum, blksize, size): pass # no-op # FIXME: def open_url(self, url, warning=None): # noqa: C901 # is too complex (12) if url.startswith('file:'): return local_open(url) try: return open_with_auth(url, self.opener) except (ValueError, http.client.InvalidURL) as v: msg = ' '.join([str(arg) for arg in v.args]) if warning: self.warn(warning, msg) else: raise DistutilsError('%s %s' % (url, msg)) from v except urllib.error.HTTPError as v: return v except urllib.error.URLError as v: if warning: self.warn(warning, v.reason) else: raise DistutilsError( "Download error for %s: %s" % (url, v.reason) ) from v except http.client.BadStatusLine as v: if warning: self.warn(warning, v.line) else: raise DistutilsError( '%s returned a bad status line. The server might be ' 'down, %s' % (url, v.line) ) from v except (http.client.HTTPException, OSError) as v: if warning: self.warn(warning, v) else: raise DistutilsError("Download error for %s: %s" % (url, v)) from v def _download_url(self, url, tmpdir): # Determine download filename # name, fragment = egg_info_for_url(url) if name: while '..' in name: name = name.replace('..', '.').replace('\\', '_') else: name = "__downloaded__" # default if URL has no path contents if name.endswith('.egg.zip'): name = name[:-4] # strip the extra .zip before download filename = os.path.join(tmpdir, name) return self._download_vcs(url, filename) or self._download_other(url, filename) @staticmethod def _resolve_vcs(url): """ >>> rvcs = PackageIndex._resolve_vcs >>> rvcs('git+http://foo/bar') 'git' >>> rvcs('hg+https://foo/bar') 'hg' >>> rvcs('git:myhost') 'git' >>> rvcs('hg:myhost') >>> rvcs('http://foo/bar') """ scheme = urllib.parse.urlsplit(url).scheme pre, sep, post = scheme.partition('+') # svn and git have their own protocol; hg does not allowed = set(['svn', 'git'] + ['hg'] * bool(sep)) return next(iter({pre} & allowed), None) def _download_vcs(self, url, spec_filename): vcs = self._resolve_vcs(url) if not vcs: return None if vcs == 'svn': raise DistutilsError( f"Invalid config, SVN download is not supported: {url}" ) filename, _, _ = spec_filename.partition('#') url, rev = self._vcs_split_rev_from_url(url) self.info(f"Doing {vcs} clone from {url} to {filename}") subprocess.check_call([vcs, 'clone', '--quiet', url, filename]) co_commands = dict( git=[vcs, '-C', filename, 'checkout', '--quiet', rev], hg=[vcs, '--cwd', filename, 'up', '-C', '-r', rev, '-q'], ) if rev is not None: self.info(f"Checking out {rev}") subprocess.check_call(co_commands[vcs]) return filename def _download_other(self, url, filename): scheme = urllib.parse.urlsplit(url).scheme if scheme == 'file': # pragma: no cover return urllib.request.url2pathname(urllib.parse.urlparse(url).path) # raise error if not allowed self.url_ok(url, True) return self._attempt_download(url, filename) def scan_url(self, url): self.process_url(url, True) def _attempt_download(self, url, filename): headers = self._download_to(url, filename) if 'html' in headers.get('content-type', '').lower(): return self._invalid_download_html(url, headers, filename) else: return filename def _invalid_download_html(self, url, headers, filename): os.unlink(filename) raise DistutilsError(f"Unexpected HTML page found at {url}") @staticmethod def _vcs_split_rev_from_url(url): """ Given a possible VCS URL, return a clean URL and resolved revision if any. >>> vsrfu = PackageIndex._vcs_split_rev_from_url >>> vsrfu('git+https://github.com/pypa/setuptools@v69.0.0#egg-info=setuptools') ('https://github.com/pypa/setuptools', 'v69.0.0') >>> vsrfu('git+https://github.com/pypa/setuptools#egg-info=setuptools') ('https://github.com/pypa/setuptools', None) >>> vsrfu('http://foo/bar') ('http://foo/bar', None) """ parts = urllib.parse.urlsplit(url) clean_scheme = parts.scheme.split('+', 1)[-1] # Some fragment identification fails no_fragment_path, _, _ = parts.path.partition('#') pre, sep, post = no_fragment_path.rpartition('@') clean_path, rev = (pre, post) if sep else (post, None) resolved = parts._replace( scheme=clean_scheme, path=clean_path, # discard the fragment fragment='', ).geturl() return resolved, rev def debug(self, msg, *args): log.debug(msg, *args) def info(self, msg, *args): log.info(msg, *args) def warn(self, msg, *args): log.warn(msg, *args) # This pattern matches a character entity reference (a decimal numeric # references, a hexadecimal numeric reference, or a named reference). entity_sub = re.compile(r'&(#(\d+|x[\da-fA-F]+)|[\w.:-]+);?').sub def decode_entity(match): what = match.group(0) return html.unescape(what) def htmldecode(text): """ Decode HTML entities in the given text. >>> htmldecode( ... 'https://../package_name-0.1.2.tar.gz' ... '?tokena=A&amp;tokenb=B">package_name-0.1.2.tar.gz') 'https://../package_name-0.1.2.tar.gz?tokena=A&tokenb=B">package_name-0.1.2.tar.gz' """ return entity_sub(decode_entity, text) def socket_timeout(timeout=15): def _socket_timeout(func): def _socket_timeout(*args, **kwargs): old_timeout = socket.getdefaulttimeout() socket.setdefaulttimeout(timeout) try: return func(*args, **kwargs) finally: socket.setdefaulttimeout(old_timeout) return _socket_timeout return _socket_timeout def _encode_auth(auth): """ Encode auth from a URL suitable for an HTTP header. >>> str(_encode_auth('username%3Apassword')) 'dXNlcm5hbWU6cGFzc3dvcmQ=' Long auth strings should not cause a newline to be inserted. >>> long_auth = 'username:' + 'password'*10 >>> chr(10) in str(_encode_auth(long_auth)) False """ auth_s = urllib.parse.unquote(auth) # convert to bytes auth_bytes = auth_s.encode() encoded_bytes = base64.b64encode(auth_bytes) # convert back to a string encoded = encoded_bytes.decode() # strip the trailing carriage return return encoded.replace('\n', '') class Credential: """ A username/password pair. Use like a namedtuple. """ def __init__(self, username, password): self.username = username self.password = password def __iter__(self): yield self.username yield self.password def __str__(self): return '%(username)s:%(password)s' % vars(self) class PyPIConfig(configparser.RawConfigParser): def __init__(self): """ Load from ~/.pypirc """ defaults = dict.fromkeys(['username', 'password', 'repository'], '') super().__init__(defaults) rc = os.path.join(os.path.expanduser('~'), '.pypirc') if os.path.exists(rc): _cfg_read_utf8_with_fallback(self, rc) @property def creds_by_repository(self): sections_with_repositories = [ section for section in self.sections() if self.get(section, 'repository').strip() ] return dict(map(self._get_repo_cred, sections_with_repositories)) def _get_repo_cred(self, section): repo = self.get(section, 'repository').strip() return repo, Credential( self.get(section, 'username').strip(), self.get(section, 'password').strip(), ) def find_credential(self, url): """ If the URL indicated appears to be a repository defined in this config, return the credential for that repository. """ for repository, cred in self.creds_by_repository.items(): if url.startswith(repository): return cred return None def open_with_auth(url, opener=urllib.request.urlopen): """Open a urllib2 request, handling HTTP authentication""" parsed = urllib.parse.urlparse(url) scheme, netloc, path, params, query, frag = parsed # Double scheme does not raise on macOS as revealed by a # failing test. We would expect "nonnumeric port". Refs #20. if netloc.endswith(':'): raise http.client.InvalidURL("nonnumeric port: ''") if scheme in ('http', 'https'): auth, address = _splituser(netloc) else: auth = None if not auth: cred = PyPIConfig().find_credential(url) if cred: auth = str(cred) info = cred.username, url log.info('Authenticating as %s for %s (from .pypirc)', *info) if auth: auth = "Basic " + _encode_auth(auth) parts = scheme, address, path, params, query, frag new_url = urllib.parse.urlunparse(parts) request = urllib.request.Request(new_url) request.add_header("Authorization", auth) else: request = urllib.request.Request(url) request.add_header('User-Agent', user_agent) fp = opener(request) if auth: # Put authentication info back into request URL if same host, # so that links found on the page will work s2, h2, path2, param2, query2, frag2 = urllib.parse.urlparse(fp.url) if s2 == scheme and h2 == address: parts = s2, netloc, path2, param2, query2, frag2 fp.url = urllib.parse.urlunparse(parts) return fp # copy of urllib.parse._splituser from Python 3.8 def _splituser(host): """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'.""" user, delim, host = host.rpartition('@') return (user if delim else None), host # adding a timeout to avoid freezing package_index open_with_auth = socket_timeout(_SOCKET_TIMEOUT)(open_with_auth) def fix_sf_url(url): return url # backward compatibility def local_open(url): """Read a local path, with special support for directories""" scheme, server, path, param, query, frag = urllib.parse.urlparse(url) filename = urllib.request.url2pathname(path) if os.path.isfile(filename): return urllib.request.urlopen(url) elif path.endswith('/') and os.path.isdir(filename): files = [] for f in os.listdir(filename): filepath = os.path.join(filename, f) if f == 'index.html': body = _read_utf8_with_fallback(filepath) break elif os.path.isdir(filepath): f += '/' files.append('<a href="{name}">{name}</a>'.format(name=f)) else: tmpl = "<html><head><title>{url}</title></head><body>{files}</body></html>" body = tmpl.format(url=url, files='\n'.join(files)) status, message = 200, "OK" else: status, message, body = 404, "Path not found", "Not found" headers = {'content-type': 'text/html'} body_stream = io.StringIO(body) return urllib.error.HTTPError(url, status, message, headers, body_stream)
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@setuptools@py3@setuptools@package_index.py@.PATH_END.py
{ "filename": "colourcorrection.py", "repo_name": "lofar-astron/PyBDSF", "repo_path": "PyBDSF_extracted/PyBDSF-master/test/colourcorrection.py", "type": "Python" }
""" This is for PyBDSF for calculating spectral index. We assume a linear spectral index in log(freq) and then each channel has a flux which is bit wrong because of the colour correction problem within that band. Now we average n such channels. There will be another error made, partly because of the colour correction now for channels (including discretisation) and the colour correction of the earlier 2nd order colour correction. This is to see how much they differ. Refer notebook for forumlae. """ import numpy as N import pylab as pl import math nchan = N.array([9, 17]) alpha_arr = N.arange(-1.3, -0.3, 0.1) deltanu = N.array([0.05e6, 0.1e6, 0.2e6]) freq = N.arange(40.0e6, 200.0e6, 10.0e6) pl1 = pl.figure() pl2 = pl.figure() pl3 = pl.figure() k = 0 for inchan, n in enumerate(nchan): for ibw, bw in enumerate(deltanu): k += 1 for ia, alpha in enumerate(alpha_arr): f_diff1 = N.zeros(len(freq)) f_diff2 = N.zeros(len(freq)) for ifreq, f in enumerate(freq): f_arr = N.arange(f-(n-1)/2*bw, f+(n+1)/2*bw, bw) f_naive = N.mean(f_arr) f1 = N.power(f_arr, alpha) f2 = N.power(f_arr, alpha-2.0) f1 = 1.0/n*N.sum(f1) f2 = 1.0/n*N.sum(f2)*bw*bw*alpha*(alpha-1.0)/24.0 f_eff1 = N.power(f1, 1.0/alpha) f_eff2 = N.power(f1+f2, 1.0/alpha) f_diff1[ifreq] = f_naive - f_eff2 f_diff2[ifreq] = f_eff1 - f_eff2 fig = pl.figure(pl1.number) adjustprops = dict(wspace=0.5, hspace=0.5) fig.subplots_adjust(**adjustprops) ax = pl.subplot(2,3,k) pl.plot(freq/1e6, f_diff1/1e3) pl.title('n='+str(n)+'; bw='+str(bw/1e6)+' MHz') pl.xlabel('Freq(MHz)') pl.ylabel('Diff in freq (kHz)') pl.setp(ax.get_xticklabels(), rotation='vertical', fontsize=12) fig = pl.figure(pl2.number) adjustprops = dict(wspace=0.5, hspace=0.5) fig.subplots_adjust(**adjustprops) ax = pl.subplot(2,3,k) pl.plot(freq/1e6, f_diff2) pl.title('n='+str(n)+'; bw='+str(bw/1e6)+' MHz') pl.xlabel('Freq(MHz)') pl.ylabel('Diff due to 2nd order (Hz)') pl.setp(ax.get_xticklabels(), rotation='vertical', fontsize=12) fig = pl.figure(pl3.number) adjustprops = dict(wspace=0.9, hspace=0.5) fig.subplots_adjust(**adjustprops) ax = pl.subplot(2,3,k) f2 = f_naive+5e6 y = f_diff1*alpha/f_naive/math.log(f_naive/(f2)) pl.plot(freq/1e6, y) pl.title('n='+str(n)+'; bw='+str(bw/1e6)+' MHz') pl.xlabel('Freq(MHz)') pl.ylabel('Error in sp.in. for f2=f1+10MHz') pl.setp(ax.get_xticklabels(), rotation='vertical', fontsize=12) pl.figure(pl1.number) pl.savefig('colourcorr_full.png') pl.figure(pl2.number) pl.savefig('colourcorr_order1-2.png') pl.figure(pl3.number) pl.savefig('colourcorr_delta_spin.png')
lofar-astronREPO_NAMEPyBDSFPATH_START.@PyBDSF_extracted@PyBDSF-master@test@colourcorrection.py@.PATH_END.py
{ "filename": "8_master_out_profiles.py", "repo_name": "ldolan05/ACID", "repo_path": "ACID_extracted/ACID-main/.other_scripts/8_master_out_profiles.py", "type": "Python" }
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 28 12:20:32 2021 @author: lucydolan """ import matplotlib.pyplot as plt from astropy.io import fits import numpy as np import math import glob from scipy.interpolate import interp1d from statistics import stdev import LSD_func_faster as LSD from scipy.optimize import curve_fit # run_name = input('Run name (all_frames or jvc):' ) run_name = 'newdepths' def gauss(x, rv, sd, height, cont): y = cont+(height*np.exp(-(x-rv)**2/(2*sd**2))) return y def findfiles(directory): filelist= glob.glob('%s*_%s.fits'%(directory, run_name)) return filelist def remove_reflex(velocities, spectrum, errors, phi, K, e, omega, v0): velo = v0 + K*(e*np.cos(omega)+np.cos(2*np.pi*phi+omega)) adjusted_velocities = velocities-velo f2 = interp1d(adjusted_velocities, spectrum, kind='linear', bounds_error=False, fill_value='extrapolate') velocity_grid = np.arange(-20,20,0.82) adjusted_spectrum = f2(velocity_grid) f2 = interp1d(adjusted_velocities, errors, kind='linear', bounds_error=False, fill_value='extrapolate') adjusted_errors = f2(velocity_grid) return velocity_grid, adjusted_spectrum, adjusted_errors def combineprofiles(spectra, errors, master, velocities): spectra = np.array(spectra) idx = np.isnan(spectra) shape_og = spectra.shape if len(spectra[idx])>0: spectra = spectra.reshape((len(spectra)*len(spectra[0]), )) for n in range(len(spectra)): if spectra[n] == np.nan: spectra[n] = (spectra[n+1]+spectra[n-1])/2 if spectra[n] == np.nan: spectra[n] = 0. spectra = spectra.reshape(shape_og) errors = np.array(errors) if master == 'no': weights_csv = np.genfromtxt('%sorder_weights.csv'%file_path, delimiter=',') orders = np.array(weights_csv[:len(spectra),0], dtype = int) weights_temp = np.array(weights_csv[:len(spectra):,1]) spectra_to_combine = [] errorss = [] weights = [] for i in orders: if np.sum(spectra[i-1])!=0: spectra_to_combine.append(list(spectra[i-1])) errorss.append(list(errors[i-1])) weights.append(weights_temp[i-1]) weights = np.array(weights/sum(weights)) else: spectra_to_combine = [] weights=[] for n in range(0, len(spectra)): if np.sum(spectra[n])!=0: spectra_to_combine.append(list(spectra[n])) temp_err = np.array(errors[n, :]) weight = (1/temp_err**2) weights.append(np.mean(weight)) weights = np.array(weights/sum(weights)) spectra_to_combine = np.array(spectra_to_combine) length, width = np.shape(spectra_to_combine) spectrum = np.zeros((1,width)) spec_errors = np.zeros((1,width)) for n in range(0,width): temp_spec = spectra_to_combine[:, n] spectrum[0,n]=sum(weights*temp_spec)/sum(weights) spec_errors[0,n]=(stdev(temp_spec)**2)*np.sqrt(sum(weights**2)) spectrum = list(np.reshape(spectrum, (width,))) spec_errors = list(np.reshape(spec_errors, (width,))) return spectrum, spec_errors, weights def continuumfit(fluxes, wavelengths, errors, poly_ord): idx = wavelengths.argsort() wavelength = wavelengths[idx] fluxe = fluxes[idx] clipped_flux = [] clipped_waves = [] binsize =100 for i in range(0, len(wavelength), binsize): waves = wavelength[i:i+binsize] flux = fluxe[i:i+binsize] indicies = flux.argsort() flux = flux[indicies] waves = waves[indicies] clipped_flux.append(flux[len(flux)-1]) clipped_waves.append(waves[len(waves)-1]) coeffs=np.polyfit(clipped_waves, clipped_flux, poly_ord) poly = np.poly1d(coeffs) fit = poly(wavelengths) flux_obs = fluxes/fit new_errors = errors/fit return flux_obs, new_errors def classify(ccf, P, t, T): #working out if in- or out- of transit #print(t, b) deltaphi = t/(2*P) #print(deltaphi) phi = (((ccf[0].header['ESO DRS BJD'])-T)/P)%1 #z = np.sqrt((a_rstar*(np.sin(2*math.pi*phi))**2)+b**2*(np.cos(2*math.pi*phi))**2) #part1=a_rstar*np.sin(2*math.pi*phi)**2 #part2=b**2*np.cos(2*math.pi*phi)**2 #z=np.sqrt(part1+part2) #print(z, phi) ''' if z < 1+rp_rstar: result = 'in' else:result = 'out' ''' phase = phi if phi < deltaphi: result ='in' elif phi > 1-deltaphi: result = 'in' else:result = 'out' #print(result) if phi>0.5: phi = phi-1 return result, phi, phase #################################################################################################################################################################### # Parameters for HD189733b P=2.21857567 #Cegla et al, 2006 - days i = 85.71*np.pi/180 #got quickly of exoplanet.eu T=2454279.436714 #cegla et al,2006 t=0.076125 #Torres et al, 2008 e =0 omega=(np.pi/2) K=0.20056 #km/s Boisse et al, 2009 v0=-2.2765#-0.1875 #km/s Boisse et al, 2009 a_rstar= 8.863 #Agol et al, 2010 rp_rstar= 0.15667 #Agol et al, 2010 u1=0.816 u2=0 #Sing et al, 2011 P=2.21857567 #Cegla et al, 2016 - days T=2454279.436714 #cegla et al,2016 a_Rs = 8.786 #Cristo et al - 8.786 b=0.687 #Cristo et al, 2022 RpRs = 0.15667 # path = '/home/lsd/Documents/Starbase/novaprime/Documents/LSD_Figures/' # save_path = '/home/lsd/Documents/Starbase/novaprime/Documents/LSD_Figures/' path = '/Users/lucydolan/Starbase/newdepths/' file_path = '/Users/lucydolan/Starbase/' months = ['August2007', 'July2007', 'July2006', 'Sep2006' ] for month in months: filelist = findfiles('%s%s'%(path,month)) velocities=np.arange(-21, 18, 0.82) frame_profiles = np.zeros((len(filelist), 3, len(np.arange(-20,20,0.82)))) for frame_no in range(len(filelist)): file = fits.open(filelist[frame_no]) order_errors = [] order_profiles = [] for order1 in range(0,71): profile_errors = file[order1].data[1] profile = file[order1].data[0] if order1>38 and order1<43: print('ignoring order %s'%order1) profile_errors = np.zeros(profile_errors.shape) profile = np.zeros(profile.shape) if order1==0: phase = file[order1].header['PHASE'] elif file[order1].header['PHASE']!=file[order1-1].header['PHASE']: raise ValueError('Phase does not match for the same frame!') order_errors.append(profile_errors) order_profiles.append(profile) spectrum, errors, weights = combineprofiles(order_profiles, order_errors, 'no', velocities) final_velocities, spectrum, errors = remove_reflex(velocities, spectrum, errors, phase, K, e, omega, v0) frame_profiles[frame_no] = [[phase-np.round(phase)]*len(spectrum), spectrum, errors] phi = frame_profiles[:, 0, 0] z = np.sqrt( ( (a_Rs)*np.sin(2 * np.pi * phi) )**2 + ( b*np.cos(2. * np.pi * phi))**2) out_idx = (z>1+RpRs) if len(frame_profiles[out_idx, 0])>1: master_out_spec, master_out_errors, master_weights = combineprofiles(frame_profiles[out_idx, 1], frame_profiles[out_idx, 2], 'yes', final_velocities) else: master_out_spec = frame_profiles[:, 1] master_out_errors = frame_profiles[:, 2] master_out = np.array([master_out_spec, master_out_errors]) #write in data hdu=fits.HDUList() #write in header for p in range(len(frame_profiles)): hdu.append(fits.PrimaryHDU(data=frame_profiles[p, 1:])) phase = frame_profiles[p, 0, 0] phi = phase z = np.sqrt( ( (a_Rs)*np.sin(2 * np.pi * phi) )**2 + ( b*np.cos(2. * np.pi * phi))**2) if z>1+RpRs: result = 'out' else: result = 'in' hdr=fits.Header() hdr['CRVAL1']=np.min(final_velocities) hdr['CDELT1']=final_velocities[1]-final_velocities[0] hdr['OBJECT']='HD189733b' hdr['NIGHT']='%s'%month hdr['K']=K hdr['V0']=v0 hdr['PHASE']=phase hdr['RESULT']=result hdu[p].header=hdr hdu.append(fits.PrimaryHDU(data=master_out)) hdr=fits.Header() hdr['CRVAL1']=np.min(final_velocities) hdr['CDELT1']=final_velocities[1]-final_velocities[0] hdr['OBJECT']='HD189733b' hdr['NIGHT']='%s'%month hdr['K']=K hdr['V0']=v0 hdr['PHASE']='master out' hdr['RESULT']='out' hdu[p+1].header=hdr hdu.writeto('%s%s_master_out_LSD_profile.fits'%(path, month), output_verify='fix', overwrite = 'True') rvs = [] for y in range(len(frame_profiles[:])): ACID_profile = frame_profiles[y, 1] ACID_errors = frame_profiles[y, 2] popt, pcov = curve_fit(gauss, final_velocities[abs(final_velocities)<5], ACID_profile[abs(final_velocities)<5], sigma = ACID_errors[abs(final_velocities)<5], absolute_sigma=True) perr = np.sqrt(np.diag(pcov)) rvs.append([popt[0], perr[0]]) rvs = np.array(rvs) plt.figure('RVs') phi = frame_profiles[:, 0, 0] z = np.sqrt( ( (a_Rs)*np.sin(2 * np.pi * phi) )**2 + ( b*np.cos(2. * np.pi * phi))**2) out_idx = (z>1+RpRs) plt.errorbar(frame_profiles[:, 0, 0], rvs[:, 0], rvs[:, 1], marker ='o', color = 'orange', linestyle='') plt.show()
ldolan05REPO_NAMEACIDPATH_START.@ACID_extracted@ACID-main@.other_scripts@8_master_out_profiles.py@.PATH_END.py
{ "filename": "optimize_qap.py", "repo_name": "scipy/scipy", "repo_path": "scipy_extracted/scipy-main/benchmarks/benchmarks/optimize_qap.py", "type": "Python" }
import numpy as np from .common import Benchmark, safe_import import os with safe_import(): from scipy.optimize import quadratic_assignment # XXX this should probably have an is_xslow with selected tests. # Even with this, it takes ~30 seconds to collect the ones to run # (even if they will all be skipped in the `setup` function). class QuadraticAssignment(Benchmark): methods = ['faq', '2opt'] probs = ["bur26a", "bur26b", "bur26c", "bur26d", "bur26e", "bur26f", "bur26g", "bur26h", "chr12a", "chr12b", "chr12c", "chr15a", "chr15b", "chr15c", "chr18a", "chr18b", "chr20a", "chr20b", "chr20c", "chr22a", "chr22b", "chr25a", "els19", "esc16a", "esc16b", "esc16c", "esc16d", "esc16e", "esc16g", "esc16h", "esc16i", "esc16j", "esc32e", "esc32g", "esc128", "had12", "had14", "had16", "had18", "had20", "kra30a", "kra30b", "kra32", "lipa20a", "lipa20b", "lipa30a", "lipa30b", "lipa40a", "lipa40b", "lipa50a", "lipa50b", "lipa60a", "lipa60b", "lipa70a", "lipa70b", "lipa80a", "lipa90a", "lipa90b", "nug12", "nug14", "nug16a", "nug16b", "nug17", "nug18", "nug20", "nug21", "nug22", "nug24", "nug25", "nug27", "nug28", "nug30", "rou12", "rou15", "rou20", "scr12", "scr15", "scr20", "sko42", "sko49", "sko56", "sko64", "sko72", "sko81", "sko90", "sko100a", "sko100b", "sko100c", "sko100d", "sko100e", "sko100f", "ste36b", "ste36c", "tai12a", "tai12b", "tai15a", "tai15b", "tai17a", "tai20a", "tai20b", "tai25a", "tai25b", "tai30a", "tai30b", "tai35a", "tai40a", "tai40b", "tai50a", "tai50b", "tai60a", "tai60b", "tai64c", "tai80a", "tai100a", "tai100b", "tai150b", "tai256c", "tho30", "tho40", "tho150", "wil50", "wil100"] params = [methods, probs] param_names = ['Method', 'QAP Problem'] def setup(self, method, qap_prob): dir_path = os.path.dirname(os.path.realpath(__file__)) datafile = np.load(os.path.join(dir_path, "qapdata/qap_probs.npz"), allow_pickle=True) slnfile = np.load(os.path.join(dir_path, "qapdata/qap_sols.npz"), allow_pickle=True) self.A = datafile[qap_prob][0] self.B = datafile[qap_prob][1] self.opt_solution = slnfile[qap_prob] self.method = method def time_evaluation(self, method, qap_prob): quadratic_assignment(self.A, self.B, self.method) def track_score(self, method, qap_prob): res = quadratic_assignment(self.A, self.B, self.method) score = int(res['fun']) percent_diff = (score - self.opt_solution) / self.opt_solution return percent_diff
scipyREPO_NAMEscipyPATH_START.@scipy_extracted@scipy-main@benchmarks@benchmarks@optimize_qap.py@.PATH_END.py
{ "filename": "test_pop_galaxy.py", "repo_name": "mirochaj/ares", "repo_path": "ares_extracted/ares-main/tests/adv/test_pop_galaxy.py", "type": "Python" }
""" test_galaxy.py Author: Jordan Mirocha Affiliation: University of Colorado at Boulder Created on: Tue May 26 14:32:20 MDT 2015 Description: """ import ares import numpy as np import matplotlib.pyplot as pl from ares.physics.Constants import cm_per_mpc, erg_per_ev, s_per_yr def test(): z = np.arange(10, 25) # Initialize a GalaxyPopulation pop = ares.populations.GalaxyPopulation(pop_sed='pl', pop_Emin=2e2, pop_Emax=1e4, pop_EminNorm=5e2, pop_EmaxNorm=8e3, pop_fX=1.0, pop_yield=2.6e39, pop_yield_units='erg/s/SFR') # Compute the luminosity density in two bands Lx1 = np.array(list(map(pop.LuminosityDensity, z))) * cm_per_mpc**3 Lx2 = np.array([pop.LuminosityDensity(zz, 2e2, 5e2) for zz in z]) * cm_per_mpc**3 # Plot 'em pl.semilogy(z, Lx1, color='k') pl.semilogy(z, Lx2, color='b') # Try again with different units erg_per_phot = pop.src.AveragePhotonEnergy(500., 8e3) * erg_per_ev y = 2.6e39 * s_per_yr / erg_per_phot pop = ares.populations.GalaxyPopulation(pop_sed='pl', pop_Emin=2e2, pop_Emax=1e4, pop_EminNorm=5e2, pop_EmaxNorm=8e3, pop_fX=1.0, pop_yield=y, pop_yield_units='photons/Msun') # Compute the luminosity density in two bands Lx1 = np.array(list(map(pop.LuminosityDensity, z))) * cm_per_mpc**3 Lx2 = np.array([pop.LuminosityDensity(zz, 2e2, 5e2) for zz in z]) * cm_per_mpc**3 # Plot 'em pl.scatter(z, Lx1, s=100, facecolors='none', color='k') pl.scatter(z, Lx2, s=100, facecolors='none', color='b') assert True if __name__ == '__main__': test()
mirochajREPO_NAMEaresPATH_START.@ares_extracted@ares-main@tests@adv@test_pop_galaxy.py@.PATH_END.py
{ "filename": "test_relative_risk.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/scipy/py3/scipy/stats/tests/test_relative_risk.py", "type": "Python" }
import pytest import numpy as np from numpy.testing import assert_allclose, assert_equal from scipy.stats.contingency import relative_risk # Test just the calculation of the relative risk, including edge # cases that result in a relative risk of 0, inf or nan. @pytest.mark.parametrize( 'exposed_cases, exposed_total, control_cases, control_total, expected_rr', [(1, 4, 3, 8, 0.25 / 0.375), (0, 10, 5, 20, 0), (0, 10, 0, 20, np.nan), (5, 15, 0, 20, np.inf)] ) def test_relative_risk(exposed_cases, exposed_total, control_cases, control_total, expected_rr): result = relative_risk(exposed_cases, exposed_total, control_cases, control_total) assert_allclose(result.relative_risk, expected_rr, rtol=1e-13) def test_relative_risk_confidence_interval(): result = relative_risk(exposed_cases=16, exposed_total=128, control_cases=24, control_total=256) rr = result.relative_risk ci = result.confidence_interval(confidence_level=0.95) # The corresponding calculation in R using the epitools package. # # > library(epitools) # > c <- matrix(c(232, 112, 24, 16), nrow=2) # > result <- riskratio(c) # > result$measure # risk ratio with 95% C.I. # Predictor estimate lower upper # Exposed1 1.000000 NA NA # Exposed2 1.333333 0.7347317 2.419628 # # The last line is the result that we want. assert_allclose(rr, 4/3) assert_allclose((ci.low, ci.high), (0.7347317, 2.419628), rtol=5e-7) def test_relative_risk_ci_conflevel0(): result = relative_risk(exposed_cases=4, exposed_total=12, control_cases=5, control_total=30) rr = result.relative_risk assert_allclose(rr, 2.0, rtol=1e-14) ci = result.confidence_interval(0) assert_allclose((ci.low, ci.high), (2.0, 2.0), rtol=1e-12) def test_relative_risk_ci_conflevel1(): result = relative_risk(exposed_cases=4, exposed_total=12, control_cases=5, control_total=30) ci = result.confidence_interval(1) assert_equal((ci.low, ci.high), (0, np.inf)) def test_relative_risk_ci_edge_cases_00(): result = relative_risk(exposed_cases=0, exposed_total=12, control_cases=0, control_total=30) assert_equal(result.relative_risk, np.nan) ci = result.confidence_interval() assert_equal((ci.low, ci.high), (np.nan, np.nan)) def test_relative_risk_ci_edge_cases_01(): result = relative_risk(exposed_cases=0, exposed_total=12, control_cases=1, control_total=30) assert_equal(result.relative_risk, 0) ci = result.confidence_interval() assert_equal((ci.low, ci.high), (0.0, np.nan)) def test_relative_risk_ci_edge_cases_10(): result = relative_risk(exposed_cases=1, exposed_total=12, control_cases=0, control_total=30) assert_equal(result.relative_risk, np.inf) ci = result.confidence_interval() assert_equal((ci.low, ci.high), (np.nan, np.inf)) @pytest.mark.parametrize('ec, et, cc, ct', [(0, 0, 10, 20), (-1, 10, 1, 5), (1, 10, 0, 0), (1, 10, -1, 4)]) def test_relative_risk_bad_value(ec, et, cc, ct): with pytest.raises(ValueError, match="must be an integer not less than"): relative_risk(ec, et, cc, ct) def test_relative_risk_bad_type(): with pytest.raises(TypeError, match="must be an integer"): relative_risk(1, 10, 2.0, 40)
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@scipy@py3@scipy@stats@tests@test_relative_risk.py@.PATH_END.py
{ "filename": "_variant.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/layout/hoverlabel/font/_variant.py", "type": "Python" }
import _plotly_utils.basevalidators class VariantValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self, plotly_name="variant", parent_name="layout.hoverlabel.font", **kwargs ): super(VariantValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), values=kwargs.pop( "values", [ "normal", "small-caps", "all-small-caps", "all-petite-caps", "petite-caps", "unicase", ], ), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@layout@hoverlabel@font@_variant.py@.PATH_END.py
{ "filename": "LAX-3D-checkpoint.ipynb", "repo_name": "sauddy/GRINN", "repo_path": "GRINN_extracted/GRINN-main/HYDRO-FINITE-DIFF/.ipynb_checkpoints/LAX-3D-checkpoint.ipynb", "type": "Jupyter Notebook" }
## 2D hydrodynamics with LAX methods @author Sayantan Date: 3 April 2023 ### 1.1 Equations The hydrostatic system with self-gravity-- For an isothermal gas, the dynamics is governed by continuity eqution and momentum equation. They are given as follows, The mass-continuity equation $$ \begin{equation} \frac{\partial \rho}{\partial t} + \nabla.(\rho \vec v) =0 \end{equation}\tag{1} $$ The momentum equation $$ \begin{eqnarray} \rho \frac{d \vec v}{ d t} = - \nabla P + \rho \vec g \\ \rho \left[\frac{\partial v}{\partial t}+ (\vec v . \nabla)\vec v \right] = - \nabla P + \rho \vec g \end{eqnarray}\tag{3} $$ The self-gravity is $$ \begin{equation} \nabla. \vec g = -4\pi G\rho \end{equation}\tag{3} $$ where $$ \begin{equation} \nabla^2 \phi = 4 \pi G \rho \end{equation}\tag{4} $$ is Poisson's equation and $$ \begin{equation} \nabla \phi = - \vec g \end{equation}\tag{5} $$ <!-- For simplicity, we consider only 1-D. Later in the paper, we will implement 2D using PINNS. $$ \begin{eqnarray} \frac{\partial \rho_1}{\partial t} + \rho_0 \frac{\partial v_1} {\partial x} = 0 \\ \rho_0 \frac{\partial v_1}{\partial t} = - c_s^{2} \frac{\partial \rho_1}{\partial x} + \rho g_{1} \\ % P_{1} = \gamma \frac{P_{0}}{\rho_0} \rho_1\\ \frac{\partial g_1}{\partial x} = - 4 \pi G \rho_1 \end{eqnarray}\tag{6} $$ #### The initial conditions is derivered using linear analysis (refer to the paper) $$ \begin{eqnarray} \rho(x,t=0) &=& \rho_{0} + \rho_{1}\cos\left(2\pi x/\lambda\right) \end{eqnarray}\tag{7} $$ When self-gravity is active and $\lambda> \lambda_{J}$ $$ \begin{eqnarray} v_{x}(x,t=0) &=& -v_{1} \sin\left(2\pi x/\lambda\right) \end{eqnarray}\tag{8} $$ where $v_1 = \frac{\alpha}{k} \frac{\rho_1}{\rho}$ and $$ \begin{eqnarray} \alpha = \sqrt{ 4 \pi G \rho_0 - c_s^2 k^2} \end{eqnarray}\tag{9} $$ however for $\lambda < \lambda_{J}$ and for non self-gravitating system $$ \begin{eqnarray} v_{x}(x) &=& v_{1} \cos\left(2\pi x/\lambda\right) \end{eqnarray}\tag{10} $$ #### Considering Periodic Boundary Conditions $$ \begin{eqnarray} \rho(x=0,t) &=& \rho (x=xmax,t)\\ v_{x}(x=t,t) &=& v_{x}(x \end{eqnarray}\tag{11} $$ <!-- $$ \begin{eqnarray} =xmax,t) \end{eqnarray}\tag{12} $$ --> --> ### 1.3 LAX Method Here the Lax method is used to integrate the flux conservative form of the continuity and momentum equations. For an equation of the form $$ \begin{equation} \frac{\partial f}{\partial t} = -\frac{\partial }{\partial x}\left(fv_x\right) - \frac{\partial }{\partial y}\left(fv_y\right) - \frac{\partial }{\partial z}\left(fv_z\right) \end{equation}\tag{6} $$ the Lax method is the finite-difference approximation in 2D, $$ \begin{equation} \frac{f^{n+1}_{i,j,k}-\left( f^{n}_{i+1,j,k} + f^{n}_{i-1,j,k}+f^{n}_{i,j+1,k} + f^{n}_{i,j-1,k} + +f^{n}_{i,j,k+1} + f^{n}_{i,j,k-1}\right)/6}{\Delta t}=-\frac{f^{n}_{i+1,j,k}v^{n}_{x,i+1,j,k}-f^{n}_{i-1,j,k}v^{n}_{x,i-1,j,k}}{2\Delta x} -\frac{f^{n}_{i,j+1,k}v^{n}_{y,i,j+1,k}-f^{n}_{i,j-1,k}v^{n}_{y,i,j-1,k}}{2\Delta y} -\frac{f^{n}_{i,j,k+1}v^{n}_{y,i,j,k+1}-f^{n}_{i,j,k-1}v^{n}_{y,i,j,k-1}}{2\Delta z} \end{equation}\tag{7} $$ Forward Time Centered Space (FTCS) method is unconditionally unstable . But the Lax method is conditionally stable if, $$ \begin{equation} \nu \equiv \frac{c\Delta t}{\Delta x} \leq 1 \end{equation}\tag{8} $$ Where $\nu$ is known as Courant number. Physically it means that the signal cannot travel more than $\Delta x$ in $\Delta t$ time. The continuity equation in 2D $$ \begin{eqnarray} \frac{\partial \rho}{\partial t} &=& -\frac{\partial}{\partial x}\left(\rho v_{x}\right) - \frac{\partial}{\partial y}\left(\rho v_{y}\right) - \frac{\partial}{\partial z}\left(\rho v_{z}\right)\\ \end{eqnarray}\tag{9} $$ The momemtum equation accumulating the components along x-axis (i vector) $$ \begin{eqnarray} \rho\frac{\partial v_{x}}{\partial t}+\rho v_{x}\frac{\partial v_{x}}{\partial x} + \rho v_{y}\frac{\partial v_{x}}{\partial y} + \rho v_{z}\frac{\partial v_{x}}{\partial z} &=& -c^{2}_{s}\frac{\partial\rho}{\partial x} + \rho g_{x} \nonumber\\ \Rightarrow \rho\frac{\partial v_{x}}{\partial t} +\frac{\partial\rho v_{x} v_{x}}{\partial x} - v_{x}\frac{\partial\rho v_{x}}{\partial x} +\frac{\partial\rho v_{y} v_{x}}{\partial y} - v_{x}\frac{\partial\rho v_{y}}{\partial y} +\frac{\partial\rho v_{z} v_{x}}{\partial z} - v_{x}\frac{\partial\rho v_{z}}{\partial z}&=& -c^{2}_{s}\frac{\partial\rho}{\partial x} + \rho g_{x} \nonumber\\ \Rightarrow \rho\frac{\partial v_{x}}{\partial t} - v_{x}\frac{\partial \rho v_{x}}{\partial x} - v_{x}\frac{\partial\rho v_{y}}{\partial y} - v_{x}\frac{\partial\rho v_{z}}{\partial z}&=&-\frac{\partial \rho v_{x} v_{x}}{\partial x}- \frac{\partial\rho v_{y} v_{x}}{\partial y} -\frac{\partial\rho v_{z} v_{x}}{\partial z} -c^{2}_{s}\frac{\partial\rho}{\partial x} + \rho g_{x} \end{eqnarray}\tag{10} $$ Now substituting equation (9) to the seconds term in the last eqn of EQ (10) we get, $$ \begin{eqnarray} \rho\frac{\partial v_{x}}{\partial t} +v_{x}\frac{\partial \rho}{\partial t} &=& -\frac{\partial\rho v_{x} v_{x}}{\partial x}- \frac{\partial\rho v_{y} v_{x}}{\partial y} -\frac{\partial\rho v_{z} v_{x}}{\partial z} -c^{2}_{s}\frac{\partial\rho}{\partial x} + \rho g_{x}\nonumber\\ \Rightarrow \frac{\partial\rho v_{x}}{\partial t} &=&-\frac{\partial\rho v_{x} v_{x}}{\partial x}- \frac{\partial\rho v_{y} v_{x}}{\partial y} -\frac{\partial\rho v_{z} v_{x}}{\partial z} -c^{2}_{s}\frac{\partial\rho}{\partial x}+ \rho g_{x}\nonumber \end{eqnarray}\tag{11} $$ #### Hence the flux conservative form of momentum equation and the continuity equation in 2D , $$ \begin{eqnarray} \frac{\partial \rho}{\partial t} &=& -\frac{\partial}{\partial x}\left(\rho v_{x}\right) - \frac{\partial}{\partial y}\left(\rho v_{y}\right) \end{eqnarray}\tag{12a} $$ $$ \begin{eqnarray} \frac{\partial\left(\rho v_{x}\right)}{\partial t} &=&-\frac{\partial}{\partial x}\left(\rho v_{x} v_{x}\right)-\frac{\partial}{\partial y}(\rho v_{y} v_{x})-\frac{\partial}{\partial z}(\rho v_{z} v_{x}) - c^{2}_{s}\frac{\partial\rho}{\partial x} + \rho g_{x} \end{eqnarray}\tag{12b} $$ #### Similarly the momentum equation in the y direction $$ \begin{eqnarray} \frac{\partial\left(\rho v_{y}\right)}{\partial t} &=&-\frac{\partial}{\partial y}\left(\rho v_{y} v_{y}\right)-\frac{\partial}{\partial x} \partial\rho v_{y} v_{x} -\frac{\partial}{\partial z}\rho v_{z} v_{x}-c^{2}_{s}\frac{\partial\rho}{\partial y} + \rho g_{y} \end{eqnarray}\tag{12c} $$ #### Similarly the momentum equation in the z direction $$ \begin{eqnarray} \frac{\partial\left(\rho v_{z}\right)}{\partial t} &=&-\frac{\partial}{\partial z}\left(\rho v_{z} v_{z}\right)-\frac{\partial}{\partial x} \partial\rho v_{z} v_{x} -\frac{\partial}{\partial y}\rho v_{z} v_{y}-c^{2}_{s}\frac{\partial\rho}{\partial y} + \rho g_{y} \end{eqnarray}\tag{12d} $$ Gas boundary and initial condition. $$ \begin{eqnarray} \rho(x) &=& \rho_{0} + \rho_{1}\cos\left(2\pi x/\lambda\right)\\ v_{x}(x) &=& v_{1} \cos\left(2\pi x/\lambda\right) or \\ \end{eqnarray}\tag{13} $$ If $\omega^2 < 0$, the system in unstable such that $4 \pi G \rho_0 > c_s^2 k^2$. The $\omega = \pm i \alpha$ where $$ \begin{eqnarray} \alpha = \sqrt{ 4 \pi G \rho_0 - c_s^2 k^2} \end{eqnarray} $$ Then the initial velocity perturbation is $$ \begin{eqnarray} v_{x}(x) &=& - v_{1} \sin\left(2\pi x/\lambda\right) \end{eqnarray} \tag{14} $$ where $$ \begin{eqnarray} i \omega \rho_1 - i k \rho_0 v_1 =& 0 \\ \nonumber v_1 =& \frac{\omega}{k}\frac{\rho_1}{\rho_0} \end{eqnarray} \tag{15} $$ In this section we use the Lax method to solve equations (12a) (12b) and (12c) are solved. Equation (6) is subsituted in (12a) (12b) and (12c) to get the following solution for $\rho$, $v_{x}$ and $v_{y}$. $$ \begin{eqnarray} \rho^{n+1}_{i,j,k}= \frac{1}{6}\left(\rho^{n}_{i+1,j,k} +\rho^{n}_{i-1,j,k} + \rho^{n}_{i,j+1,k} +\rho^{n}_{i,j-1,k}+ \rho^{n}_{i,j,k+1} +\rho^{n}_{i,j,k-1}\right)-\frac{\Delta t}{2\Delta x}\left(\rho^{n}_{i+1,j,k} v^{n}_{x,i+1,j,k}-\rho^{n}_{i-1,j,k} v^{n}_{x,i-1,j,k}\right)- \frac{\Delta t}{2\Delta y}\left(\rho^{n}_{i,j+1,k} v^{n}_{y,i,j+1,k}-\rho^{n}_{i,j+1,k} v^{n}_{y,i,j-1,k}\right) - \frac{\Delta t}{2\Delta z}\left(\rho^{n}_{i,j,k+1} v^{n}_{z,i,j,k+1}-\rho^{n}_{i,j,k-1} v^{n}_{z,i,j,k-1}\right) \end{eqnarray} \tag{16} $$ $$ \begin{equation} U^{n+1}_{i,j,k} = \frac{1}{6}\left(U^{n}_{i+1,j,k} +U^{n}_{i-1,j,k} + U^{n}_{i,j+1,k} +U^{n}_{i,j-1,k} + U^{n}_{i,j,k+1} +U^{n}_{i,j,k-1}\right)-\frac{\Delta t}{2\Delta x}\left(U^{n}_{i+1,j,k} v^{n}_{x,i+1,j,k}-U^{n}_{i-1,j,k} v^{n}_{x,i-1,j,k}\right)- \frac{\Delta t}{2\Delta y}\left(U^{n}_{i,j+1,k} v^{n}_{y,i,j+1,k}-U^{n}_{i,j-1,k} v^{n}_{y,i,j-1,k}\right) -\frac{\Delta t}{2\Delta z}\left(U^{n}_{i,j,k+1} v^{n}_{z,i,j,k+1}-U^{n}_{i,j,k-1} v^{n}_{z,i,j,k-1}\right)- \frac{c^{2}_{s}\Delta t}{2\Delta x}\left(\rho^{n}_{i+1,j,k}-\rho^{n}_{i-1,j,k}\right) -\frac{\Delta t \rho^n_{i,j,k}}{2\Delta x}\left(\phi^{n}_{i+1,j,k}-\phi^{n}_{i-1,j,k}\right) \end{equation} \tag{17} $$ $$ \begin{equation} W^{n+1}_{i,j,k} = \frac{1}{6}\left(W^{n}_{i+1,j,k} +W^{n}_{i-1,j,k} + W^{n}_{i,j+1,k} +W^{n}_{i,j-1,k} + W^{n}_{i,j,k+1} +W^{n}_{i,j,k-1}\right)-\frac{\Delta t}{2\Delta x}\left(W^{n}_{i+1,j,k} v^{n}_{x,i+1,j,k}-W^{n}_{i-1,j,k} v^{n}_{x,i-1,j,k}\right)- \frac{\Delta t}{2\Delta y}\left(W^{n}_{i,j+1,k} v^{n}_{y,i,j+1,k}-W^{n}_{i,j-1,k} v^{n}_{y,i,j-1,k}\right) - \frac{\Delta t}{2\Delta z}\left(W^{n}_{i,j,k+1} v^{n}_{z,i,j,k+1}-W^{n}_{i,j,k-1} v^{n}_{z,i,j,k-1}\right)-\frac{c^{2}_{s}\Delta t}{2\Delta y}\left(\rho^{n}_{i,j+1}-\rho^{n}_{i,j-1}\right) -\frac{\Delta t \rho^n_{i,j}}{2\Delta y}\left(\phi^{n}_{i,j+1}-\phi^{n}_{i,j-1}\right) \end{equation} \tag{18} $$ $$ \begin{equation} Z^{n+1}_{i,j,k} = \frac{1}{6}\left(Z^{n}_{i+1,j,k} +Z^{n}_{i-1,j,k} + Z^{n}_{i,j+1,k} +Z^{n}_{i,j-1,k} + Z^{n}_{i,j,k+1} +Z^{n}_{i,j,k-1}\right)-\frac{\Delta t}{2\Delta x}\left(Z^{n}_{i+1,j,k} v^{n}_{x,i+1,j,k}-Z^{n}_{i-1,j,k} v^{n}_{x,i-1,j,k}\right)- \frac{\Delta t}{2\Delta y}\left(Z^{n}_{i,j+1,k} v^{n}_{y,i,j+1,k}-Z^{n}_{i,j-1,k} v^{n}_{y,i,j-1,k}\right) - \frac{\Delta t}{2\Delta z}\left(Z^{n}_{i,j,k+1} v^{n}_{z,i,j,k+1}-Z^{n}_{i,j,k-1} v^{n}_{z,i,j,k-1}\right)-\frac{c^{2}_{s}\Delta t}{2\Delta y}\left(\rho^{n}_{i,j+1}-\rho^{n}_{i,j-1}\right) -\frac{\Delta t \rho^n_{i,j}}{2\Delta y}\left(\phi^{n}_{i,j+1}-\phi^{n}_{i,j-1}\right) \end{equation} \tag{18} $$ $$ \begin{equation} U^{n}_{j} = v^{n}_{x,i,j,k} \rho^{n}_{i,j,k} \end{equation} \tag{21} $$ $$ \begin{equation} W^{n}_{j} = v^{n}_{y,i,j,k} \rho^{n}_{i,j,k} \end{equation}\tag{2} $$ $$ \begin{equation} Z^{n}_{j} = v^{n}_{z,i,j,k} \rho^{n}_{i,j,k} \end{equation}\tag{2} $$ ```python import numpy as np import os # Import NumPy import numpy as np import matplotlib.pyplot as plt import scipy import time ## For the FFT solver from numpy.fft import fft, ifft,fft2, ifft2,fftn, ifftn from scipy import signal np.random.seed(1234) ``` ```python def fft_solver(rho,Lx,nx,Ly,ny,Lz,nz,dim = None): ''' A FFT solver that uses discrete Fast Fourier Transform to solve the Poisson Equation: We apply the correction due to the finite difference grid of phi Input: 1. The source function density in this case 2. # of grid point Nx and Ny for 2D 3. Domain Size in each dimension 4. Dim : will the updated later to work for any dimension Output: the potential phi and the field g (optional) not returned currently. ''' if dim: dx, dy ,dz = Lx / nx, Ly / ny , Lz/nz else: dx = Lx / nx, # Calculate the Fourier modes of the gas density rhohat = fftn(rho) # Calculate the wave numbers in x and y directions kx = 2 * np.pi * np.fft.fftfreq(nx, dx) ky = 2 * np.pi * np.fft.fftfreq(ny, dy) kz = 2 * np.pi * np.fft.fftfreq(nz, dz) # Construct the Laplacian operator in Fourier space kx2,ky2,kz2 = np.meshgrid(kx**2, ky**2,kz**2,indexing='ij') laplace = -(kx2 + ky2 + kz2) ## Correction for the dicrete FFT. Need to check the calculations # laplace = 2*(np.cos(kx*dx)-1)/(dx**2) + 2*(np.cos(ky*dx)-1)/(dy**2) laplace[laplace == 0] = 1e-9 # Solve for the electrostatic potential in Fourier space phihat = rhohat / laplace # Transform back to real space to obtain the solution phi = np.real(ifftn(phihat)) # dphidx = np.gradient(phi, dx) # dphidy = np.gradient(phi, dy) # return phi,dphidx, dphidy return phi ``` ## Testing the FFT solver for a cosine wave denstity ```python # Define the problem domain and grid spacing Lx, Ly, Lz = 2.0, 2.0, 2.0 Nx, Ny, Nz = 128, 128, 128 n = 10 rho = np.zeros((n,Nx,Ny,Nz)) # Define the charge density rho(x,y) x = np.linspace(0, Lx, Nx) y = np.linspace(0, Ly, Ny) z = np.linspace(0, Lz, Nz) xx,yy,zz = np.meshgrid(x,y,z,indexing='ij') print(xx[:,:,1].shape) rho[0] = np.cos(2 * np.pi * xx) print("shape",rho[0,:,:,1].shape) fig = plt.figure(figsize=(9,6)) ax = fig.add_subplot(projection='3d') surf = ax.plot_surface(xx[:,:,1],yy[:,:,1],rho[0,:,:,1], cmap='viridis') ax.set_zlabel(r"$\rho$") ax.set_xlabel("x") ax.set_ylabel("y") ax.set_title("Density") fig = plt.figure(figsize=(9,6)) ax = fig.add_subplot(projection='3d') phi = fft_solver(rho[0,:,:],Lx,Nx,Ly,Ny,Lz,Nz,dim = 3) print(phi.shape) surf = ax.plot_surface(xx[:,:,3],yy[:,:,3],phi[:,:,3], cmap='viridis') ax.set_zlabel(r"$\phi$") ax.set_xlabel("x") ax.set_ylabel("y") ax.set_title("Gravitational Potential") ``` (128, 128) shape (128, 128) (128, 128, 128) Text(0.5, 0.92, 'Gravitational Potential') ![png](output_5_2.png) ![png](output_5_3.png) ```python def lax_solution(time,N,nu,lam,num_of_waves,rho_1,gravity=False,isplot = None,comparison =None,dim_plot =None,animation=None): ''' This function solves the hydrodynamic Eqns in 1D with/without self gravity using LAX methods described above Input: Time till the system is integrated :time Number of Xgrid points : N Courant number : nu Wavelength : If lambda> lambdaJ (with gravity--> Instability) else waves propagation Number of waves : The domain size changes with this maintain periodicity Density perturbation : rho1 (for linear or non-linear perturbation) Gravity: If True it deploys the FFT routine to estimate the potential isplot(optional): if True plots the output Comparison (optional) : If True then the plots are overplotted with LT solutions for comparison Animation (optional): Not used at the moment Output: Density, velocity + (phi and g if gravity is True) isplot: True then the plots are generated ''' # rho_max = [] lam = lam # one wavelength num_of_waves = num_of_waves Lx = lam * num_of_waves # Maximum length (two wavelength) Ly = lam * num_of_waves Lz = lam * num_of_waves print("at time= ",time) ### Declaring the Constants c_s = 1.0 # % Sound Speed rho_o = 1.0 # zeroth order density nu = nu # courant number (\nu = 2 in 2d) rho_1 = rho_1 # for linear/nonlinear wave propagation const = 1 # The actual value is 4*pi G = 1.0 # Gravitational Constant ### Grid X-Y-Z-T Nx = N # The grid resolution values2d:N =(10,50,100,500) dx = float(Lx/Nx) # length spacing Ny = N # The grid resolution values2d:N =(10,50,100,500) dy = float(Ly/Ny) # length spacing Nz = N # The grid resolution values2d:N =(10,50,100,500) dz = float(Lz/Nz) # length spacing dt = nu*dx/c_s # time grid spacing ## For simplification mux = dt/(2*dx) # is the coefficient in the central differencing Eqs above muy = dt/(2*dy) # is the coefficient in the central differencing Eqs above muz = dt/(2*dz) # is the coefficient in the central differencing Eqs above n = int(time/dt) # grid points in time print("For dx = {} and dt = {} and time gridpoints n = {} ".format(dx,dt,n)) ########## Initializing the ARRAY ####################### x = np.linspace(0, Lx, Nx) y = np.linspace(0, Ly, Ny) z = np.linspace(0, Lz, Nz) xx,yy,zz = np.meshgrid(x,y,z,indexing='ij') ## Mesh for the 3D domain rho = np.zeros((n,Nx,Ny,Nz)) vx =np.zeros((n,Nx,Ny,Nz)) vy =np.zeros((n,Nx,Ny,Nz)) vz =np.zeros((n,Nx,Ny,Nz)) Px =np.zeros((n,Nx,Ny,Nz)) # The flux term U in the above equations Py =np.zeros((n,Nx,Ny,Nz)) # The flux term W in the above equations Pz =np.zeros((n,Nx,Ny,Nz)) # The flux term W in the above equations phi = np.zeros((n,Nx,Ny,Nz)) # print(xx.max(),yy.max(),zz.max()) # print("meshshape",xx.shape,yy.shape,zz.shape) ## Calculating the jeans length is gravity is Turned on if gravity: jeans = np.sqrt(4*np.pi**2*c_s**2/(const*G*rho_o)) print("Jean's Length",jeans) ######################## Initial Conditions ########################### rho[0] = rho_o + rho_1* np.cos(2*np.pi*xx/lam) # defing the density at t = 0 EQ 11 # print(rho[0,:,1,1]) # print(rho[0,:,1,1].shape,xx.shape,yy.shape,zz.shape) # plt.plot(x,rho[0,:,1,1],linewidth=1,label="FD at t={}".format(round(time,2))) # print(rho[0,:,:,1]) # print("checking the rolling") # print(np.roll(rho[0], -1, axis=0)) # print(np.roll(rho[0,:,:,:], -1, axis=1)) # print("checking the rolling") # print(np.roll(rho[0,:,:,:], -1, axis=2)) # fig = plt.figure(figsize=(9,6)) # ax = fig.add_subplot(projection='3d') # surf = ax.plot_surface(xx.T,yy.T,rho[0,:,:,:], cmap='viridis') if gravity == False: print("Propagation of Sound wave") v_1 = (c_s*rho_1)/rho_o # velocity perturbation vx[0] = v_1 * np.cos(2*np.pi*xx/lam) # the velocity at t =0 ## Linear Theory if comparison: rho_LT = rho_o + rho_1*np.cos(2*np.pi * x/lam - 2*np.pi/lam *time) rho_LT_max = np.max(rho_o + rho_1*np.cos(2*np.pi * x/lam - 2*np.pi/lam *time)) vx_LT = v_1* np.cos(2*np.pi * x/lam - 2*np.pi/lam *time) vy_LT = np.zeros(Ny) vz_LT = np.zeros(Nz) else: ######## When self-gravity is True and see EQN 12 if lam >= jeans: print("There is gravitational instabilty lam = {} > l_jean ={}".format(lam,jeans)) alpha = np.sqrt(const*G*rho_o-c_s**2*(2*np.pi/lam)**2) v_1 = (rho_1/rho_o) * (alpha/(2*np.pi/lam)) ## With gravity vx[0,:,:] = - v_1 * np.sin(2*np.pi*xx/lam) # the velocity at t =0 # print("initial vy",vy[n-1,1,:]) ##### Density values from Linear Theory at t if comparison: rho_LT = rho_o + rho_1*np.exp(alpha * time)*np.cos(2*np.pi*x/lam) rho_LT_max = np.max(rho_o + rho_1*np.exp(alpha * time)*np.cos(2*np.pi*x/lam)) vx_LT = -v_1*np.exp(alpha * time)*np.sin(2*np.pi*x/lam) vy_LT = np.zeros(Nx) vz_LT = np.zeros(Nz) else: print("There is no gravitational instabilty as lam = {} < l_jean ={}".format(lam,jeans)) alpha = np.sqrt(c_s**2*(2*np.pi/lam)**2 - const*G*rho_o) v_1 = (rho_1/rho_o) * (alpha/(2*np.pi/lam)) # velocity perturbation vx[0,:,:] = v_1 * np.cos(2*np.pi*xx/lam) # the velocity at t =0 if comparison: rho_LT = rho_o + rho_1*np.cos(alpha * time - 2*np.pi*x/lam) rho_LT_max = np.max(rho_o + rho_1*np.cos(alpha * time - 2*np.pi*xx/lam)) vx_LT = v_1*np.cos(alpha * time - 2*np.pi*x/lam) vy_LT = np.zeros((Nx)) # Calculating the potential and the field using FFT # phi[0,:,:],dphidx,dphidy = fft_solver(const*(rho[0,:,:]-rho_o),Lx,Nx,Ly,Ny,dim = 2) phi[0] = fft_solver(const*(rho[0]-rho_o),Lx,Nx,Ly,Ny,Lz,Nz,dim = 2) print("shape of Phi",phi[0].shape) # fft_solver(rho,Lx,nx,Ly,ny,dim = 2) ####### The Flux term ######### Px=rho*vx Py=rho*vy Pz=rho*vz #################################FINITE DIFFERENCE ####################### for k in range(1,n): ## Looping over time rho[k] = (1/6)*(np.roll(rho[k-1], -1, axis=0)+ np.roll(rho[k-1], 1, axis=0)\ +np.roll(rho[k-1], -1, axis=1)+ np.roll(rho[k-1], 1, axis=1)\ +np.roll(rho[k-1], -1, axis=2)+ np.roll(rho[k-1], 1, axis=2))\ -(mux*(np.roll(rho[k-1],-1,axis=0)*np.roll(vx[k-1],-1,axis=0)-np.roll(rho[k-1],1, axis=0)*np.roll(vx[k-1],1,axis=0)))\ -(muy*(np.roll(rho[k-1],-1,axis=1)*np.roll(vy[k-1],-1,axis=1)-np.roll(rho[k-1],1, axis=1)*np.roll(vy[k-1],1,axis=1))\ -(muz*(np.roll(rho[k-1],-1,axis=2)*np.roll(vz[k-1],-1,axis=2)-np.roll(rho[k-1],1, axis=2)*np.roll(vz[k-1],1,axis=2)))) if gravity == False: ## Hydro sound wave when gravity is absent Px[k] = (1/6)*(np.roll(Px[k-1],-1,axis=0)+ np.roll(Px[k-1],1,axis=0) + np.roll(Px[k-1],-1,axis=1)+ np.roll(Px[k-1],1,axis=1)\ + np.roll(Px[k-1],-1,axis=2)+ np.roll(Px[k-1],1,axis=2))\ -(mux*(np.roll(Px[k-1],-1,axis=0)*np.roll(vx[k-1],-1,axis=0)- np.roll(Px[k-1],1,axis=0)*np.roll(vx[k-1],1,axis=0)))\ -(muy*(np.roll(Px[k-1],-1,axis=1)*np.roll(vy[k-1],-1,axis=1)- np.roll(Px[k-1],1,axis=1)*np.roll(vy[k-1],1,axis=1)))\ -(muz*(np.roll(Px[k-1],-1,axis=2)*np.roll(vz[k-1],-1,axis=2)- np.roll(Px[k-1],1,axis=2)*np.roll(vz[k-1],1,axis=2)))\ -((c_s**2)*mux*(np.roll(rho[k-1],-1,axis=0)- np.roll(rho[k-1],1,axis=0))) Py[k] = (1/6)*(np.roll(Py[k-1],-1,axis=0)+ np.roll(Py[k-1],1,axis=0) + np.roll(Py[k-1],-1,axis=1)+ np.roll(Py[k-1],1,axis=1)\ + np.roll(Py[k-1],-1,axis=2)+ np.roll(Py[k-1],1,axis=2))\ -(muy*(np.roll(Py[k-1],-1,axis=1)*np.roll(vy[k-1],-1,axis=1)- np.roll(Py[k-1],1,axis=1)*np.roll(vy[k-1],1,axis=1)))\ -(mux*(np.roll(Py[k-1],-1,axis=0)*np.roll(vx[k-1],-1,axis=0)- np.roll(Py[k-1],1,axis=0)*np.roll(vx[k-1],1,axis=0)))\ -(muz*(np.roll(Py[k-1],-1,axis=2)*np.roll(vz[k-1],-1,axis=2)- np.roll(Py[k-1],1,axis=2)*np.roll(vz[k-1],1,axis=2)))\ -((c_s**2)*muy*(np.roll(rho[k-1],-1,axis=1)- np.roll(rho[k-1],1,axis=1))) Pz[k] = (1/6)*(np.roll(Pz[k-1],-1,axis=0)+ np.roll(Pz[k-1],1,axis=0) + np.roll(Pz[k-1],-1,axis=1)+ np.roll(Pz[k-1],1,axis=1)\ + np.roll(Pz[k-1],-1,axis=2)+ np.roll(Pz[k-1],1,axis=2))\ -(muz*(np.roll(Pz[k-1],-1,axis=2)*np.roll(vz[k-1],-1,axis=2)- np.roll(Pz[k-1],1,axis=2)*np.roll(vz[k-1],1,axis=2)))\ -(mux*(np.roll(Pz[k-1],-1,axis=0)*np.roll(vx[k-1],-1,axis=0)- np.roll(Pz[k-1],1,axis=0)*np.roll(vx[k-1],1,axis=0)))\ -(muy*(np.roll(Pz[k-1],-1,axis=1)*np.roll(vy[k-1],-1,axis=1)- np.roll(Pz[k-1],1,axis=1)*np.roll(vy[k-1],1,axis=1)))\ -((c_s**2)*muz*(np.roll(rho[k-1],-1,axis=2)- np.roll(rho[k-1],1,axis=2))) else: Px[k] = (1/6)*(np.roll(Px[k-1],-1,axis=0)+ np.roll(Px[k-1],1,axis=0) + np.roll(Px[k-1],-1,axis=1)+ np.roll(Px[k-1],1,axis=1)\ + np.roll(Px[k-1],-1,axis=2)+ np.roll(Px[k-1],1,axis=2))\ -(mux*(np.roll(Px[k-1],-1,axis=0)*np.roll(vx[k-1],-1,axis=0)- np.roll(Px[k-1],1,axis=0)*np.roll(vx[k-1],1,axis=0)))\ -(muy*(np.roll(Px[k-1],-1,axis=1)*np.roll(vy[k-1],-1,axis=1)- np.roll(Px[k-1],1,axis=1)*np.roll(vy[k-1],1,axis=1)))\ -(muz*(np.roll(Px[k-1],-1,axis=2)*np.roll(vz[k-1],-1,axis=2)- np.roll(Px[k-1],1,axis=2)*np.roll(vz[k-1],1,axis=2)))\ -((c_s**2)*mux*(np.roll(rho[k-1],-1,axis=0)- np.roll(rho[k-1],1,axis=0)))\ -(mux*rho[k-1]*(np.roll(phi[k-1],-1,axis=0)- np.roll(phi[k-1],1,axis=0))) Py[k] = (1/6)*(np.roll(Py[k-1],-1,axis=0)+ np.roll(Py[k-1],1,axis=0) + np.roll(Py[k-1],-1,axis=1)+ np.roll(Py[k-1],1,axis=1)\ + np.roll(Py[k-1],-1,axis=2)+ np.roll(Py[k-1],1,axis=2))\ -(muy*(np.roll(Py[k-1],-1,axis=1)*np.roll(vy[k-1],-1,axis=1)- np.roll(Py[k-1],1,axis=1)*np.roll(vy[k-1],1,axis=1)))\ -(mux*(np.roll(Py[k-1],-1,axis=0)*np.roll(vx[k-1],-1,axis=0)- np.roll(Py[k-1],1,axis=0)*np.roll(vx[k-1],1,axis=0)))\ -(muz*(np.roll(Py[k-1],-1,axis=2)*np.roll(vz[k-1],-1,axis=2)- np.roll(Py[k-1],1,axis=2)*np.roll(vz[k-1],1,axis=2)))\ -((c_s**2)*muy*(np.roll(rho[k-1],-1,axis=1)- np.roll(rho[k-1],1,axis=1)))\ -(muy*rho[k-1]*(np.roll(phi[k-1],-1,axis=1)- np.roll(phi[k-1],1,axis=1))) Pz[k] = (1/6)*(np.roll(Pz[k-1],-1,axis=0)+ np.roll(Pz[k-1],1,axis=0) + np.roll(Pz[k-1],-1,axis=1)+ np.roll(Pz[k-1],1,axis=1)\ + np.roll(Pz[k-1],-1,axis=2)+ np.roll(Pz[k-1],1,axis=2))\ -(muz*(np.roll(Pz[k-1],-1,axis=2)*np.roll(vz[k-1],-1,axis=2)- np.roll(Pz[k-1],1,axis=2)*np.roll(vz[k-1],1,axis=2)))\ -(mux*(np.roll(Pz[k-1],-1,axis=0)*np.roll(vx[k-1],-1,axis=0)- np.roll(Pz[k-1],1,axis=0)*np.roll(vx[k-1],1,axis=0)))\ -(muy*(np.roll(Pz[k-1],-1,axis=1)*np.roll(vy[k-1],-1,axis=1)- np.roll(Pz[k-1],1,axis=1)*np.roll(vy[k-1],1,axis=1)))\ -((c_s**2)*muz*(np.roll(rho[k-1],-1,axis=2)- np.roll(rho[k-1],1,axis=2)))\ -(muz*rho[k-1]*(np.roll(phi[k-1],-1,axis=2)- np.roll(phi[k-1],1,axis=2))) phi[k]= fft_solver(const*(rho[k]-rho_o),Lx,Nx,Ly,Ny,Lz,Nz,dim = 3) vx[k] = Px[k]/rho[k] ## 2-D velocity vx vy[k] = Py[k]/rho[k] ## 2-D velocity vy vz[k] = Pz[k]/rho[k] ## 2-D velocity vy rho_max = np.max(rho) ## Maximum density from the FD calculation # # ################################# PLOTTING ####################### if isplot : plt.figure(1,figsize=(6,4)) plt.plot(x,rho[n-1,:,1,1]-rho_o,linewidth=1,label="FD at t={}".format(round(time,2))) plt.legend(numpoints=1,loc='upper right',fancybox=True,shadow=True) plt.xlabel(r"$\mathbf{x}$") # plt.text(.6,.15,r"dt=%f"%(dt),fontsize=12) plt.title("At time {} and rho_1 = {}".format(time,rho_1)) plt.ylabel(r"$\mathbf{\rho - \rho_{0}}$") if comparison : plt.plot(x,rho_LT-rho_o,'--',linewidth=1,label="LT") plt.legend(numpoints=1,loc='upper right',fancybox=True,shadow=True) plt.figure(2,figsize=(6,4)) plt.plot(x,vx[n-1,:,1,1],'--',markersize=2,label="t={}".format(round(time,2))) plt.legend(numpoints=1,loc='upper right',fancybox=True,shadow=True) plt.xlabel(r"$\mathbf{x}$") plt.title(r"Lax Solution Velocity For $\rho_1$ = {}".format(rho_1)) plt.ylabel("vx") if comparison : plt.plot(x,vx_LT,'--',linewidth=1,label="LT") plt.legend(numpoints=1,loc='upper right',fancybox=True,shadow=True) plt.figure(3,figsize=(6,4)) plt.plot(y,vy[n-1,1,:,1],'--',markersize=2,label="t={}".format(round(time,2))) plt.legend(numpoints=1,loc='upper right',fancybox=True,shadow=True) plt.xlabel(r"$\mathbf{y}$") plt.title(r"Lax Solution Velocity For $\rho_1$ = {}".format(rho_1)) plt.ylabel("vy") if comparison : plt.plot(y,vy_LT,'--',linewidth=1,label="LT") plt.legend(numpoints=1,loc='upper right',fancybox=True,shadow=True) plt.figure(4,figsize=(6,4)) plt.plot(y,vz[n-1,1,1,:],'--',markersize=2,label="t={}".format(round(time,2))) plt.legend(numpoints=1,loc='upper right',fancybox=True,shadow=True) plt.xlabel(r"$\mathbf{z}$") plt.title(r"Lax Solution Velocity For $\rho_1$ = {}".format(rho_1)) plt.ylabel("vz") if comparison : plt.plot(z,vz_LT,'--',linewidth=1,label="LT") plt.legend(numpoints=1,loc='upper right',fancybox=True,shadow=True) if dim_plot == True: ## PLotting in 3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') sc = ax.scatter(xx, yy, zz, c=rho[n-1]) plt.colorbar(sc) plt.show() if gravity: #### Plotting the comparison of the \rho_max for FD and Linear Theory plt.figure(5,figsize=(6,4)) print(time, rho_LT_max) plt.scatter(time,rho_max,label="FD") plt.xlabel("t") plt.ylabel(r"$\log (\rho_{\rm max} - \rho_{0}) $") plt.yscale('log') plt.legend(numpoints=1,loc='upper left',fancybox=True,shadow=True) if comparison: plt.scatter(time,rho_LT_max,facecolors='none', edgecolors='r',label="LT") plt.legend(numpoints=1,loc='upper left',fancybox=True,shadow=True) # ## Plotting the gravitational potential (\phi) and field (g) # plt.figure(6,figsize=(6,4)) # plt.plot(x,phi[n-1,:,:],'--',markersize=2,label="t=phi at {}".format(round(time,2))) # # plt.plot(x,dphidx[n-1,:],'--',markersize=2,label="g at t={}".format(time)) # # plt.legend(numpoints=1,loc='upper right',fancybox=True,shadow=True) # plt.xlabel(r"$\mathbf{x}$") # plt.title(r"Lax Solution Phi For $\rho_1$ = {}".format(rho_1)) # plt.ylabel(r"$\Phi$") # # # else: # # # if gravity: # # # return x,rho,v,phi,dphidx,n,rho_LT,rho_LT_max,rho_max,v_LT # # # else: # # # return x,rho,v,rho_LT,rho_LT_max,rho_max,v_LT # ## Clearing the memory del rho,phi, vx,vy,vz, Px,Py,Pz ``` ```python ## Setup for the Hydro Problem lam = 7.0 # one wavelength num_of_waves = 2 # the number of waves rho_1 = 0.03; # perturbation strength nu = 0.4 N = 100 t = 1 start = time.time() ## Wihout Gravity # lax_solution(t,N,nu,lam,num_of_waves,rho_1,gravity=False,isplot = False,comparison = False) ## With Gravity lax_solution(t,N,nu,lam,num_of_waves,rho_1,gravity=True,isplot = False,comparison = False,dim_plot = True) end = time.time() print("Total time = {} sec for N= {}".format(end - start,N)) ``` at time= 1 For dx = 0.14 and dt = 0.05600000000000001 and time gridpoints n = 17 Jean's Length 6.283185307179586 There is gravitational instabilty lam = 7.0 > l_jean =6.283185307179586 shape of Phi (100, 100, 100) Total time = 2.36537504196167 sec for N= 100 ## To check the time evolution ```python time_array = np.asarray([0.5,.75,0.9]) for t in time_array: # lax_solution(time,N,nu,lam,num_of_waves,rho_1,gravity=False,isplot = True,comparison = True,animation=None) lax_solution(t,N,nu,lam,num_of_waves,rho_1,gravity=True,isplot = True,comparison = True,animation=None) ``` at time= 0.5 For dx = 0.14 and dt = 0.05600000000000001 and time gridpoints n = 8 meshshape (100, 100, 100) (100, 100, 100) (100, 100, 100) Jean's Length 6.283185307179586 There is gravitational instabilty lam = 7.0 > l_jean =6.283185307179586 shape of Phi (100, 100, 100) 0.5 1.0373975413608025 at time= 0.75 For dx = 0.14 and dt = 0.05600000000000001 and time gridpoints n = 13 meshshape (100, 100, 100) (100, 100, 100) (100, 100, 100) Jean's Length 6.283185307179586 There is gravitational instabilty lam = 7.0 > l_jean =6.283185307179586 shape of Phi (100, 100, 100) 0.75 1.041754563638694 at time= 0.9 For dx = 0.14 and dt = 0.05600000000000001 and time gridpoints n = 16 meshshape (100, 100, 100) (100, 100, 100) (100, 100, 100) Jean's Length 6.283185307179586 There is gravitational instabilty lam = 7.0 > l_jean =6.283185307179586 shape of Phi (100, 100, 100) 0.9 1.0446087946259182 ![png](output_9_1.png) ![png](output_9_2.png) ![png](output_9_3.png) ![png](output_9_4.png) ![png](output_9_5.png) ```python ```
sauddyREPO_NAMEGRINNPATH_START.@GRINN_extracted@GRINN-main@HYDRO-FINITE-DIFF@.ipynb_checkpoints@LAX-3D-checkpoint.ipynb@.PATH_END.py
{ "filename": "test_algebra.py", "repo_name": "fgbuster/fgbuster", "repo_path": "fgbuster_extracted/fgbuster-master/fgbuster/test/test_algebra.py", "type": "Python" }
#!/usr/bin/env python import unittest import numpy as np from numpy.random import uniform from numpy.testing import assert_array_almost_equal as aaae from numpy.testing import assert_allclose as aac import fgbuster.component_model as cm from fgbuster.mixingmatrix import MixingMatrix from fgbuster.algebra import (W, Wd, invAtNA, W_dB, W_dBdB, _mv, _mtm, _mm, _T, _mmm, D, comp_sep, multi_comp_sep, _mtmm, P, P_dBdB) class TestAlgebraRandom(unittest.TestCase): def setUp(self): np.random.seed(0) self.n_freq = 6 self.n_comp = 2 self.n_stokes = 3 self.n_pixels = 10 self.A = uniform(size=(self.n_freq, self.n_comp)) self.s = uniform(size=(self.n_pixels, self.n_stokes, self.n_comp)) self.d = _mv(self.A, self.s) self.invN = uniform( size=(self.n_pixels, self.n_stokes, self.n_freq, self.n_freq)) self.invN += _T(self.invN) self.invN += 10*np.eye(self.n_freq) self.invN *= 10 def test_D(self): K = np.linalg.inv(_mtm(self.A, self.A)) res = np.eye(self.n_freq) - _mmm(self.A, K, self.A.T) aaae(res, D(self.A)) def test_D_invN(self): invN = self.invN[0,0] K = np.linalg.inv(_mtmm(self.A, invN, self.A)) res = np.eye(self.n_freq) - _mmm(self.A, K, _mtm(self.A, invN)) aaae(res, D(self.A, invN)) def test_D_idempotence(self): invN = self.invN[0,0] res = D(self.A, invN) aaae(res, _mm(res, res)) def test_P(self): K = np.linalg.inv(_mtm(self.A, self.A)) res = _mmm(self.A, K, self.A.T) aaae(res, P(self.A)) def test_P_invN(self): invN = self.invN[0,0] K = np.linalg.inv(_mtmm(self.A, invN, self.A)) res = _mmm(self.A, K, _mtm(self.A, invN)) aaae(res, P(self.A, invN)) def test_P_idempotence(self): invN = self.invN[0,0] res = P(self.A, invN) aaae(res, _mm(res, res)) def test_invAtNA(self): res = np.linalg.inv(_mtm(self.A, self.A)) aaae(res, invAtNA(self.A)) def test_invAtNA_invN(self): res = np.linalg.inv(_mtm(self.A, _mm(self.invN, self.A))) aaae(res, invAtNA(self.A, self.invN)) def test_Wd_is_s(self): aaae(self.s, Wd(self.A, self.d)) def test_W_on_d_is_s(self): aaae(self.s, _mv(W(self.A), self.d)) def test_comp_sep_no_par(self): res = comp_sep(self.A, self.d, None, None, None) aaae(self.s, res.s) def test_multi_comp_sep_no_par(self): patch_ids = np.arange(self.d.shape[0]) // 2 np.random.shuffle(patch_ids) res = multi_comp_sep(self.A, self.d, None, None, None, patch_ids) aaae(self.s, res.s) class TestAlgebraPhysical(unittest.TestCase): def setUp(self): self.DX = 5e-4 # NOTE: this is a bit fine-tuned np.random.seed(0) self.n_freq = 6 self.nu = np.logspace(1, 2.5, self.n_freq) self.n_stokes = 3 self.n_pixels = 2 self.components = [cm.CMB(), cm.Dust(200.), cm.Synchrotron(70.)] self.mm = MixingMatrix(*(self.components)) self.params = [1.54, 20, -3] self.A = self.mm.eval(self.nu, *(self.params)) self.A_dB = self.mm.diff(self.nu, *(self.params)) self.A_dBdB = self.mm.diff_diff(self.nu, *(self.params)) self.invN = uniform( size=(self.n_pixels, self.n_stokes, self.n_freq, self.n_freq)) self.invN += _T(self.invN) self.invN += 10*np.eye(self.n_freq) self.invN *= 10 def test_W_dB_invN(self): W_dB_analytic = W_dB(self.A, self.A_dB, self.mm.comp_of_dB, self.invN) W_params = W(self.A, self.invN) for i in range(len(self.params)): diff_params = [p for p in self.params] diff_params[i] = self.DX + diff_params[i] diff_A = self.mm.eval(self.nu, *diff_params) diff_W = W(diff_A, self.invN) W_dB_numerical = (diff_W - W_params) / self.DX aac(W_dB_numerical, W_dB_analytic[i], rtol=1e-3) def test_W_dB(self): W_dB_analytic = W_dB(self.A, self.A_dB, self.mm.comp_of_dB) W_params = W(self.A) for i in range(len(self.params)): diff_params = [p for p in self.params] diff_params[i] = self.DX + diff_params[i] diff_A = self.mm.eval(self.nu, *diff_params) diff_W = W(diff_A) W_dB_numerical = (diff_W - W_params) / self.DX aac(W_dB_numerical, W_dB_analytic[i], rtol=1e-3) def test_P_dBdB(self): P_dBdB_analytic = P_dBdB( self.A, self.A_dB, self.A_dBdB, self.mm.comp_of_dB) def get_P_displaced(i, j): def P_displaced(i_step, j_step): diff_params = [p for p in self.params] diff_params[i] = i_step * self.DX + diff_params[i] diff_params[j] = j_step * self.DX + diff_params[j] diff_A = self.mm.eval(self.nu, *diff_params) return P(diff_A) return P_displaced for i in range(len(self.params)): for j in range(len(self.params)): Pdx = get_P_displaced(i, j) if i == j: P_dBdB_numerical = ( (-2*Pdx(0, 0) + Pdx(+1, 0) + Pdx(-1, 0)) / self.DX**2) else: P_dBdB_numerical = ( (Pdx(1, 1) - Pdx(+1, -1) - Pdx(-1, 1) + Pdx(-1, -1)) / (4 * self.DX**2)) aac(P_dBdB_numerical, P_dBdB_analytic[i][j], rtol=1.5e-1) def test_P_dBdB_invN(self): invN = self.invN[0,0] P_dBdB_analytic = P_dBdB( self.A, self.A_dB, self.A_dBdB, self.mm.comp_of_dB, invN) def get_P_displaced(i, j): def P_displaced(i_step, j_step): diff_params = [p for p in self.params] diff_params[i] = i_step * self.DX + diff_params[i] diff_params[j] = j_step * self.DX + diff_params[j] diff_A = self.mm.eval(self.nu, *diff_params) return P(diff_A, invN) return P_displaced for i in range(len(self.params)): for j in range(len(self.params)): Pdx = get_P_displaced(i, j) if i == j: P_dBdB_numerical = ( (-2*Pdx(0, 0) + Pdx(+1, 0) + Pdx(-1, 0)) / self.DX**2) else: P_dBdB_numerical = ( (Pdx(1, 1) - Pdx(+1, -1) - Pdx(-1, 1) + Pdx(-1, -1)) / (4 * self.DX**2)) aac(P_dBdB_numerical, P_dBdB_analytic[i][j], rtol=3.0e-1) def test_W_dBdB(self): W_dBdB_analytic = W_dBdB( self.A, self.A_dB, self.A_dBdB, self.mm.comp_of_dB) def get_W_displaced(i, j): def W_displaced(i_step, j_step): diff_params = [p for p in self.params] diff_params[i] = i_step * self.DX + diff_params[i] diff_params[j] = j_step * self.DX + diff_params[j] diff_A = self.mm.eval(self.nu, *diff_params) return W(diff_A) return W_displaced for i in range(len(self.params)): for j in range(len(self.params)): Wdx = get_W_displaced(i, j) if i == j: W_dBdB_numerical = ( (-2*Wdx(0, 0) + Wdx(+1, 0) + Wdx(-1, 0)) / self.DX**2) else: W_dBdB_numerical = ( (Wdx(1, 1) - Wdx(+1, -1) - Wdx(-1, 1) + Wdx(-1, -1)) / (4 * self.DX**2)) aac(W_dBdB_numerical, W_dBdB_analytic[i][j], rtol=1e-1) def test_W_dBdB_invN(self): W_dBdB_analytic = W_dBdB( self.A, self.A_dB, self.A_dBdB, self.mm.comp_of_dB, self.invN) def get_W_displaced(i, j): def W_displaced(i_step, j_step): diff_params = [p for p in self.params] diff_params[i] = i_step * self.DX + diff_params[i] diff_params[j] = j_step * self.DX + diff_params[j] diff_A = self.mm.eval(self.nu, *diff_params) return W(diff_A, self.invN) return W_displaced for i in range(len(self.params)): for j in range(len(self.params)): Wdx = get_W_displaced(i, j) if i == j: W_dBdB_numerical = ( (-2*Wdx(0, 0) + Wdx(+1, 0) + Wdx(-1, 0)) / self.DX**2) else: W_dBdB_numerical = ( (Wdx(1, 1) - Wdx(+1, -1) - Wdx(-1, 1) + Wdx(-1, -1)) / (4 * self.DX**2)) aac(W_dBdB_numerical, W_dBdB_analytic[i][j], rtol=2.5e-1) if __name__ == '__main__': unittest.main()
fgbusterREPO_NAMEfgbusterPATH_START.@fgbuster_extracted@fgbuster-master@fgbuster@test@test_algebra.py@.PATH_END.py
{ "filename": "test_signal_slot.py", "repo_name": "spacetelescope/jwst", "repo_path": "jwst_extracted/jwst-main/jwst/lib/tests/test_signal_slot.py", "type": "Python" }
"""Test signal_slot.py""" from jwst.lib import signal_slot as ss REFLECT_CALLED = 'reflect: called.' def reflect(*args): """Handler function that simply reflects the input args""" print(REFLECT_CALLED) return args def list_append(inlist, new_item): """Append new_item to inlist""" inlist.append(new_item) return inlist, new_item class AClass: def __init__(self): self.kwargs = None def set_and_reflect(self, *args, **kwargs): """Handler function that simply reflects the input args Keyword arguments become an attribute """ self.kwargs = kwargs return args def test_basic_structure(): """Test initialization and basic structure""" signal = ss.Signal() assert len(signal._slots) == 0 def test_emit(capsys): """Test emitting a signal""" signal = ss.Signal() signal.connect(reflect) signal.emit() out, err = capsys.readouterr() assert REFLECT_CALLED in out def test_implicit_emit(capsys): """Test implicating emission of signal""" signal = ss.Signal() signal.connect(reflect) signal() out, err = capsys.readouterr() assert REFLECT_CALLED in out def test_call(): """Test calling a signal and getting results""" def another_reflect(*args): return reflect(*args) signal = ss.Signal() signal.connect(reflect) signal.connect(another_reflect) result = list(signal.call('hello')) assert len(result) == 2 assert result[0] == ('hello',) assert result[1] == ('hello',) def test_reduce(): """Test reducing results to a single result""" def another_list_append(inlist, new_item): return list_append(inlist, new_item) signal = ss.Signal(list_append, another_list_append) a_list = [] result = signal.reduce(a_list, 'hello') assert len(result) == 2 assert result[0] == ['hello', 'hello'] assert result[1] == 'hello' def test_disable(): """Test disable/enable of a signal""" signal = ss.Signal() signal.connect(reflect) signal.enabled = False result = list(signal.call()) assert len(result) == 0 signal.enabled = True result = list(signal.call()) assert len(result) == 1 signal.set_enabled(False, push=True) result = list(signal.call()) assert len(result) == 0 signal.reset_enabled() result = list(signal.call()) assert len(result) == 1 def test_single_shot(): """Test single shot signals""" signal = ss.Signal() signal.connect(reflect, single_shot=True) result = list(signal.call()) assert len(result) == 1 result = list(signal.call()) assert len(result) == 0 def test_disconnect(): """Disconnect a slot""" signal = ss.Signal() signal.connect(reflect) result = list(signal.call()) assert len(result) == 1 signal.disconnect(reflect) result = list(signal.call()) assert len(result) == 0 def test_clear(): """Test clearing all slots""" signal = ss.Signal() signal.connect(reflect) result = list(signal.call()) assert len(result) == 1 signal.clear() result = list(signal.call()) assert len(result) == 0 def test_call_method(): """Test with method slots""" signal = ss.Signal() aclass = AClass() signal.connect(aclass.set_and_reflect) results = list(signal.call('hello', akeyword='look a keyword')) assert len(results) == 1 assert results[0] == ('hello', ) assert aclass.kwargs == {'akeyword': 'look a keyword'}
spacetelescopeREPO_NAMEjwstPATH_START.@jwst_extracted@jwst-main@jwst@lib@tests@test_signal_slot.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "plotly/plotly.py", "repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/validators/funnelarea/__init__.py", "type": "Python" }
import sys from typing import TYPE_CHECKING if sys.version_info < (3, 7) or TYPE_CHECKING: from ._visible import VisibleValidator from ._valuessrc import ValuessrcValidator from ._values import ValuesValidator from ._uirevision import UirevisionValidator from ._uid import UidValidator from ._title import TitleValidator from ._texttemplatesrc import TexttemplatesrcValidator from ._texttemplate import TexttemplateValidator from ._textsrc import TextsrcValidator from ._textpositionsrc import TextpositionsrcValidator from ._textposition import TextpositionValidator from ._textinfo import TextinfoValidator from ._textfont import TextfontValidator from ._text import TextValidator from ._stream import StreamValidator from ._showlegend import ShowlegendValidator from ._scalegroup import ScalegroupValidator from ._opacity import OpacityValidator from ._name import NameValidator from ._metasrc import MetasrcValidator from ._meta import MetaValidator from ._marker import MarkerValidator from ._legendwidth import LegendwidthValidator from ._legendrank import LegendrankValidator from ._legendgrouptitle import LegendgrouptitleValidator from ._legendgroup import LegendgroupValidator from ._legend import LegendValidator from ._labelssrc import LabelssrcValidator from ._labels import LabelsValidator from ._label0 import Label0Validator from ._insidetextfont import InsidetextfontValidator from ._idssrc import IdssrcValidator from ._ids import IdsValidator from ._hovertextsrc import HovertextsrcValidator from ._hovertext import HovertextValidator from ._hovertemplatesrc import HovertemplatesrcValidator from ._hovertemplate import HovertemplateValidator from ._hoverlabel import HoverlabelValidator from ._hoverinfosrc import HoverinfosrcValidator from ._hoverinfo import HoverinfoValidator from ._domain import DomainValidator from ._dlabel import DlabelValidator from ._customdatasrc import CustomdatasrcValidator from ._customdata import CustomdataValidator from ._baseratio import BaseratioValidator from ._aspectratio import AspectratioValidator else: from _plotly_utils.importers import relative_import __all__, __getattr__, __dir__ = relative_import( __name__, [], [ "._visible.VisibleValidator", "._valuessrc.ValuessrcValidator", "._values.ValuesValidator", "._uirevision.UirevisionValidator", "._uid.UidValidator", "._title.TitleValidator", "._texttemplatesrc.TexttemplatesrcValidator", "._texttemplate.TexttemplateValidator", "._textsrc.TextsrcValidator", "._textpositionsrc.TextpositionsrcValidator", "._textposition.TextpositionValidator", "._textinfo.TextinfoValidator", "._textfont.TextfontValidator", "._text.TextValidator", "._stream.StreamValidator", "._showlegend.ShowlegendValidator", "._scalegroup.ScalegroupValidator", "._opacity.OpacityValidator", "._name.NameValidator", "._metasrc.MetasrcValidator", "._meta.MetaValidator", "._marker.MarkerValidator", "._legendwidth.LegendwidthValidator", "._legendrank.LegendrankValidator", "._legendgrouptitle.LegendgrouptitleValidator", "._legendgroup.LegendgroupValidator", "._legend.LegendValidator", "._labelssrc.LabelssrcValidator", "._labels.LabelsValidator", "._label0.Label0Validator", "._insidetextfont.InsidetextfontValidator", "._idssrc.IdssrcValidator", "._ids.IdsValidator", "._hovertextsrc.HovertextsrcValidator", "._hovertext.HovertextValidator", "._hovertemplatesrc.HovertemplatesrcValidator", "._hovertemplate.HovertemplateValidator", "._hoverlabel.HoverlabelValidator", "._hoverinfosrc.HoverinfosrcValidator", "._hoverinfo.HoverinfoValidator", "._domain.DomainValidator", "._dlabel.DlabelValidator", "._customdatasrc.CustomdatasrcValidator", "._customdata.CustomdataValidator", "._baseratio.BaseratioValidator", "._aspectratio.AspectratioValidator", ], )
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@validators@funnelarea@__init__.py@.PATH_END.py
{ "filename": "20191022_Vesta.ipynb", "repo_name": "ysBach/BachYP_etal_CeresVesta_NHAO", "repo_path": "BachYP_etal_CeresVesta_NHAO_extracted/BachYP_etal_CeresVesta_NHAO-main/codes_n_data/20191022_Vesta.ipynb", "type": "Jupyter Notebook" }
```python %config InlineBackend.figure_format = 'retina' from IPython import InteractiveShell InteractiveShell.ast_node_interactivity = 'last_expr' from pathlib import Path import numpy as np import nicpolpy as nic from matplotlib import pyplot as plt from matplotlib import rcParams import warnings from astropy.utils.exceptions import AstropyWarning warnings.filterwarnings('ignore', append=True, category=AstropyWarning) ``` ```python name = "4_Vesta_20191022_NHAO_NIC" basename = "Vesta_20191022" npr = nic.NICPolReduc( name=basename, inputs=f"_original_32bit/{name}/raw/*.fits", # mflats="cal-flat_20200603-lv1/*.fits", mflats="cal-flat_20180507-lv1/*.fits", imasks="masks/*.fits", verbose=1 ) ``` ```python _ = npr.plan_mdark() ``` SKIP: Planer exists for mdark at __logs/Vesta_20191022/Vesta_20191022_plan-MDARK.csv ```python _ = npr.comb_mdark_dmask() _ = npr.plan_mmask() ``` SKIP: Summary exists for mdark at __logs/Vesta_20191022/Vesta_20191022_summ_MDARK.csv SKIP: Planer exists for mmask at __logs/Vesta_20191022/Vesta_20191022_plan-MMASK.csv ```python _ = npr.comb_mmask() ``` SKIP: Summary exists for mmask at __logs/Vesta_20191022/Vesta_20191022_summ_MMASK.csv ```python _ = npr.proc_lv1() _ = npr.plan_lv2() ``` SKIP: Summary exists for lv1 at __logs/Vesta_20191022/Vesta_20191022_summ_lv1.csv SKIP: Planer exists for lv2 at __logs/Vesta_20191022/Vesta_20191022_plan-lv2.csv ```python _ = npr.proc_lv2() # ~ 13 min/350FITS on MBP 16" [2021, macOS 12.0.1, M1Pro, 8P+2E core, GPU 16-core, RAM 16GB] _ = npr.plan_lv3() ``` SKIP: Summary exists for lv2 at __logs/Vesta_20191022/Vesta_20191022_summ_lv2.csv 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 84/84 [00:09<00:00, 9.16it/s] Saved to __logs/Vesta_20191022/Vesta_20191022_plan-lv3.csv WAIT! Modify __logs/Vesta_20191022/Vesta_20191022_plan-lv3.csv ```python _ = npr.proc_lv3() # ~ 3 min/350FITS on MBP 16" [2021, macOS 12.0.1, M1Pro, 8P+2E core, GPU 16-core, RAM 16GB] _ = npr.plan_ifrin() ``` 249it [01:31, 2.73it/s] Saving thumbnails to _lv3/Vesta_20191022/thumbs 498it [00:50, 9.90it/s] No data found for ifrin. ```python _ = npr.plan_mfrin() ``` SKIP: Planner does not exist for ifrin ```python _ = npr.comb_mfrin() ``` SKIP: Planner does not exist for mfrin ```python _ = npr.plan_lv4(add_mfrin=False) ``` Saved to __logs/Vesta_20191022/Vesta_20191022_plan-lv4.csv WAIT! Modify __logs/Vesta_20191022/Vesta_20191022_plan-lv4.csv ```python _ = npr.proc_lv4() ``` 498it [00:40, 12.39it/s] Saving thumbnails to _lv4/Vesta_20191022/thumbs 498it [00:49, 9.98it/s] ```python ```
ysBachREPO_NAMEBachYP_etal_CeresVesta_NHAOPATH_START.@BachYP_etal_CeresVesta_NHAO_extracted@BachYP_etal_CeresVesta_NHAO-main@codes_n_data@20191022_Vesta.ipynb@.PATH_END.py
{ "filename": "_ypad.py", "repo_name": "plotly/plotly.py", "repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/validators/volume/colorbar/_ypad.py", "type": "Python" }
import _plotly_utils.basevalidators class YpadValidator(_plotly_utils.basevalidators.NumberValidator): def __init__(self, plotly_name="ypad", parent_name="volume.colorbar", **kwargs): super(YpadValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), min=kwargs.pop("min", 0), **kwargs, )
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@validators@volume@colorbar@_ypad.py@.PATH_END.py
{ "filename": "model_comparison.ipynb", "repo_name": "pymc-devs/pymc", "repo_path": "pymc_extracted/pymc-main/docs/source/learn/core_notebooks/model_comparison.ipynb", "type": "Jupyter Notebook" }
```python import arviz as az import numpy as np import pymc as pm print(f"Running on PyMC v{pm.__version__}") ``` Running on PyMC v5.15.1+68.gc0b060b98.dirty ```python az.style.use("arviz-darkgrid") ``` (model_comparison)= # Model comparison To demonstrate the use of model comparison criteria in PyMC, we implement the **8 schools** example from Section 5.5 of Gelman et al (2003), which attempts to infer the effects of coaching on SAT scores of students from 8 schools. Below, we fit a **pooled model**, which assumes a single fixed effect across all schools, and a **hierarchical model** that allows for a random effect that partially pools the data. The data include the observed treatment effects (`y`) and associated standard deviations (`sigma`) in the 8 schools. ```python y = np.array([28, 8, -3, 7, -1, 1, 18, 12]) sigma = np.array([15, 10, 16, 11, 9, 11, 10, 18]) J = len(y) ``` ### Pooled model ```python with pm.Model() as pooled: # Latent pooled effect size mu = pm.Normal("mu", 0, sigma=1e6) obs = pm.Normal("obs", mu, sigma=sigma, observed=y) trace_p = pm.sample(2000) ``` Auto-assigning NUTS sampler... Initializing NUTS using jitter+adapt_diag... Multiprocess sampling (4 chains in 4 jobs) NUTS: [mu] Output() <pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"></pre> <pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"> </pre> Sampling 4 chains for 1_000 tune and 2_000 draw iterations (4_000 + 8_000 draws total) took 6 seconds. ```python az.plot_trace(trace_p); ``` ![png](output_7_0.png) ### Hierarchical model ```python with pm.Model() as hierarchical: eta = pm.Normal("eta", 0, 1, shape=J) # Hierarchical mean and SD mu = pm.Normal("mu", 0, sigma=10) tau = pm.HalfNormal("tau", 10) # Non-centered parameterization of random effect theta = pm.Deterministic("theta", mu + tau * eta) obs = pm.Normal("obs", theta, sigma=sigma, observed=y) trace_h = pm.sample(2000, target_accept=0.9) ``` Auto-assigning NUTS sampler... Initializing NUTS using jitter+adapt_diag... Multiprocess sampling (4 chains in 4 jobs) NUTS: [eta, mu, tau] Output() <pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"></pre> <pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"> </pre> Sampling 4 chains for 1_000 tune and 2_000 draw iterations (4_000 + 8_000 draws total) took 24 seconds. ```python az.plot_trace(trace_h, var_names="mu"); ``` ![png](output_10_0.png) ```python az.plot_forest(trace_h, var_names="theta"); ``` ![png](output_11_0.png) ### Leave-one-out Cross-validation (LOO) LOO cross-validation is an estimate of the out-of-sample predictive fit. In cross-validation, the data are repeatedly partitioned into training and holdout sets, iteratively fitting the model with the former and evaluating the fit with the holdout data. Vehtari et al. (2016) introduced an efficient computation of LOO from MCMC samples (without the need for re-fitting the data). This approximation is based on importance sampling. The importance weights are stabilized using a method known as Pareto-smoothed importance sampling (PSIS). ### Widely-applicable Information Criterion (WAIC) WAIC (Watanabe 2010) is a fully Bayesian criterion for estimating out-of-sample expectation, using the computed log pointwise posterior predictive density (LPPD) and correcting for the effective number of parameters to adjust for overfitting. By default ArviZ uses LOO, but WAIC is also available. ### Model log-likelihood In order to compute LOO and WAIC, ArviZ needs access to the model elemwise loglikelihood for every posterior sample. We can add it via {func}`~pymc.compute_log_likelihood`. Alternatively we can pass `idata_kwargs={"log_likelihood": True}` to {func}`~pymc.sample` to have it computed automatically at the end of sampling. ```python with pooled: pm.compute_log_likelihood(trace_p) ``` Output() <pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"></pre> <pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"> </pre> ```python pooled_loo = az.loo(trace_p) pooled_loo ``` Computed from 8000 posterior samples and 8 observations log-likelihood matrix. Estimate SE elpd_loo -30.58 1.11 p_loo 0.69 - ------ Pareto k diagnostic values: Count Pct. (-Inf, 0.5] (good) 8 100.0% (0.5, 0.7] (ok) 0 0.0% (0.7, 1] (bad) 0 0.0% (1, Inf) (very bad) 0 0.0% ```python with hierarchical: pm.compute_log_likelihood(trace_h) ``` Output() <pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"></pre> <pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"> </pre> ```python hierarchical_loo = az.loo(trace_h) hierarchical_loo ``` Computed from 8000 posterior samples and 8 observations log-likelihood matrix. Estimate SE elpd_loo -30.82 1.08 p_loo 1.17 - ------ Pareto k diagnostic values: Count Pct. (-Inf, 0.5] (good) 4 50.0% (0.5, 0.7] (ok) 4 50.0% (0.7, 1] (bad) 0 0.0% (1, Inf) (very bad) 0 0.0% ArviZ includes two convenience functions to help compare LOO for different models. The first of these functions is `compare`, which computes LOO (or WAIC) from a set of traces and models and returns a DataFrame. ```python df_comp_loo = az.compare({"hierarchical": trace_h, "pooled": trace_p}) df_comp_loo ``` <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>rank</th> <th>elpd_loo</th> <th>p_loo</th> <th>elpd_diff</th> <th>weight</th> <th>se</th> <th>dse</th> <th>warning</th> <th>scale</th> </tr> </thead> <tbody> <tr> <th>pooled</th> <td>0</td> <td>-30.578116</td> <td>0.686645</td> <td>0.000000</td> <td>1.0</td> <td>1.105891</td> <td>0.000000</td> <td>False</td> <td>log</td> </tr> <tr> <th>hierarchical</th> <td>1</td> <td>-30.820005</td> <td>1.167010</td> <td>0.241889</td> <td>0.0</td> <td>1.080954</td> <td>0.231679</td> <td>False</td> <td>log</td> </tr> </tbody> </table> </div> We have many columns, so let's check out their meaning one by one: 0. The index is the names of the models taken from the keys of the dictionary passed to `compare(.)`. 1. **rank**, the ranking of the models starting from 0 (best model) to the number of models. 2. **loo**, the values of LOO (or WAIC). The DataFrame is always sorted from best LOO/WAIC to worst. 3. **p_loo**, the value of the penalization term. We can roughly think of this value as the estimated effective number of parameters (but do not take that too seriously). 4. **d_loo**, the relative difference between the value of LOO/WAIC for the top-ranked model and the value of LOO/WAIC for each model. For this reason we will always get a value of 0 for the first model. 5. **weight**, the weights assigned to each model. These weights can be loosely interpreted as the probability of each model being true (among the compared models) given the data. 6. **se**, the standard error for the LOO/WAIC computations. The standard error can be useful to assess the uncertainty of the LOO/WAIC estimates. By default these errors are computed using stacking. 7. **dse**, the standard errors of the difference between two values of LOO/WAIC. The same way that we can compute the standard error for each value of LOO/WAIC, we can compute the standard error of the differences between two values of LOO/WAIC. Notice that both quantities are not necessarily the same, the reason is that the uncertainty about LOO/WAIC is correlated between models. This quantity is always 0 for the top-ranked model. 8. **warning**, If `True` the computation of LOO/WAIC may not be reliable. 9. **loo_scale**, the scale of the reported values. The default is the log scale as previously mentioned. Other options are deviance -- this is the log-score multiplied by -2 (this reverts the order: a lower LOO/WAIC will be better) -- and negative-log -- this is the log-score multiplied by -1 (as with the deviance scale, a lower value is better). The second convenience function takes the output of `compare` and produces a summary plot in the style of the one used in the book [Statistical Rethinking](http://xcelab.net/rm/statistical-rethinking/) by Richard McElreath (check also [this port](https://github.com/aloctavodia/Statistical-Rethinking-with-Python-and-PyMC3) of the examples in the book to PyMC). ```python az.plot_compare(df_comp_loo, insample_dev=False); ``` ![png](output_21_0.png) The empty circle represents the values of LOO and the black error bars associated with them are the values of the standard deviation of LOO. The value of the highest LOO, i.e the best estimated model, is also indicated with a vertical dashed grey line to ease comparison with other LOO values. For all models except the top-ranked one we also get a triangle indicating the value of the difference of WAIC between that model and the top model and a grey error bar indicating the standard error of the differences between the top-ranked WAIC and WAIC for each model. ### Interpretation Though we might expect the hierarchical model to outperform a complete pooling model, there is little to choose between the models in this case, given that both models gives very similar values of the information criteria. This is more clearly appreciated when we take into account the uncertainty (in terms of standard errors) of LOO and WAIC. ## Reference [Gelman, A., Hwang, J., & Vehtari, A. (2014). Understanding predictive information criteria for Bayesian models. Statistics and Computing, 24(6), 997–1016.](https://doi.org/10.1007/s11222-013-9416-2) [Vehtari, A, Gelman, A, Gabry, J. (2016). Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. Statistics and Computing](http://link.springer.com/article/10.1007/s11222-016-9696-4) ```python %load_ext watermark %watermark -n -u -v -iv -w -p xarray,pytensor ``` Last updated: Tue Jun 25 2024 Python implementation: CPython Python version : 3.11.8 IPython version : 8.22.2 xarray : 2024.2.0 pytensor: 2.20.0+3.g66439d283.dirty matplotlib: 3.8.3 numpy : 1.26.4 pymc : 5.15.0+1.g58927d608 arviz : 0.17.1 Watermark: 2.4.3 ```python ```
pymc-devsREPO_NAMEpymcPATH_START.@pymc_extracted@pymc-main@docs@source@learn@core_notebooks@model_comparison.ipynb@.PATH_END.py
{ "filename": "test_freq_attr.py", "repo_name": "pandas-dev/pandas", "repo_path": "pandas_extracted/pandas-main/pandas/tests/indexes/period/test_freq_attr.py", "type": "Python" }
import pytest from pandas.compat import PY311 from pandas import ( offsets, period_range, ) import pandas._testing as tm class TestFreq: def test_freq_setter_deprecated(self): # GH#20678 idx = period_range("2018Q1", periods=4, freq="Q") # no warning for getter with tm.assert_produces_warning(None): idx.freq # warning for setter msg = ( "property 'freq' of 'PeriodArray' object has no setter" if PY311 else "can't set attribute" ) with pytest.raises(AttributeError, match=msg): idx.freq = offsets.Day()
pandas-devREPO_NAMEpandasPATH_START.@pandas_extracted@pandas-main@pandas@tests@indexes@period@test_freq_attr.py@.PATH_END.py
{ "filename": "amadeus_full_experiment.py", "repo_name": "philbull/RadioFisher", "repo_path": "RadioFisher_extracted/RadioFisher-master/amadeus_full_experiment.py", "type": "Python" }
#!/usr/bin/python """ Calculate Fisher matrix and P(k) constraints for all redshift bins for a given experiment. """ import numpy as np import pylab as P import radiofisher as rf from radiofisher import experiments from radiofisher.units import * from mpi4py import MPI import sys comm = MPI.COMM_WORLD myid = comm.Get_rank() size = comm.Get_size() ################################################################################ # Set-up experiment parameters ################################################################################ #INPUT AS: #mpirun -n <NPROCESSORS> python full_experiment.py <EXPID> <SAREA> <BINTYPE> <BINWIDTH/NUMBER> <integration_time> <kmax> <N_kbins> #where <EXPID> is the index of the experiment in the list expt_list below, #<SAREA> has to be in degrees #<BINTYPE> 0:dz const, 1:dr const, 2:dnu const #<BINWIDTH/NUMBER> depends on the option chosen for bin type. for z and nu the bin width is given, BUT FOR R THE NUMBER OF BINS, NOT BIN WIDTH #<integration_time> [hours ] ttot total integration time in [hours] #<kmax> [Mpc^-1] kmax in the Fisher integrals #<N_kbins> simply the number of kbins to be used. #All of these parameters will enter the file name as follows: #root = "output/" + survey_name + binning + binwidth + integration_time + nkbins # Load cosmology and experimental settings e = experiments cosmo = experiments.cosmo # print "DEBUG: sNL == 0!!" # cosmo['sigma_nl'] = 1.0 # Label experiments with different settings #EXPT_LABEL = "_mg_Dz_kmg0.1" #"_mnu" #"_mg_Dz" "_baoonly" "_uls" EXPT_LABEL = "_amadeus" #"_mg_Dz_kmg0.01" expt_list = [ ( 'exptS', e.exptS ), # 0 ( 'iexptM', e.exptM ), # 1 ( 'exptL', e.exptL ), # 2 ( 'iexptL', e.exptL ), # 3 ( 'cexptL', e.exptL ), # 4 ( 'GBT', e.GBT ), # 5 ( 'Parkes', e.Parkes ), # 6 ( 'GMRT', e.GMRT ), # 7 ( 'WSRT', e.WSRT ), # 8 ( 'APERTIF', e.APERTIF ), # 9 ( 'VLBA', e.VLBA ), # 10 ( 'JVLA', e.JVLA ), # 11 ( 'iJVLA', e.JVLA ), # 12 ( 'BINGO', e.BINGO ), # 13 ( 'iBAOBAB32', e.BAOBAB32 ), # 14 ( 'iBAOBAB128', e.BAOBAB128 ), # 15 ( 'yCHIME', e.CHIME ), # 16 ( 'iAERA3', e.AERA3 ), # 17 ( 'iMFAA', e.MFAA ), # 18 ( 'yTIANLAIpath', e.TIANLAIpath ), # 19 ( 'yTIANLAI', e.TIANLAI ), # 20 ( 'yTIANLAIband2', e.TIANLAIband2 ), # 21 ( 'FAST', e.FAST ), # 22 ( 'KAT7', e.KAT7 ), # 23 ( 'iKAT7', e.KAT7 ), # 24 ( 'cKAT7', e.KAT7 ), # 25 ( 'MeerKATb1', e.MeerKATb1 ), # 26 ( 'iMeerKATb1', e.MeerKATb1 ), # 27 ( 'cMeerKATb1', e.MeerKATb1 ), # 28 ( 'MeerKATb2', e.MeerKATb2 ), # 29 ( 'iMeerKATb2', e.MeerKATb2 ), # 30 ( 'cMeerKATb2', e.MeerKATb2 ), # 31 ( 'ASKAP', e.ASKAP ), # 32 ( 'SKA1MIDbase1', e.SKA1MIDbase1 ), # 33 ( 'iSKA1MIDbase1', e.SKA1MIDbase1 ), # 34 ( 'cSKA1MIDbase1', e.SKA1MIDbase1 ), # 35 ( 'SKA1MIDbase2', e.SKA1MIDbase2 ), # 36 ( 'iSKA1MIDbase2', e.SKA1MIDbase2 ), # 37 ( 'cSKA1MIDbase2', e.SKA1MIDbase2 ), # 38 ( 'SKA1MIDfull1', e.SKA1MIDfull1 ), # 39 ( 'iSKA1MIDfull1', e.SKA1MIDfull1 ), # 40 ( 'cSKA1MIDfull1', e.SKA1MIDfull1 ), # 41 ( 'SKA1MIDfull2', e.SKA1MIDfull2 ), # 42 ( 'iSKA1MIDfull2', e.SKA1MIDfull2 ), # 43 ( 'cSKA1MIDfull2', e.SKA1MIDfull2 ), # 44 ( 'fSKA1SURbase1', e.SKA1SURbase1 ), # 45 ( 'fSKA1SURbase2', e.SKA1SURbase2 ), # 46 ( 'fSKA1SURfull1', e.SKA1SURfull1 ), # 47 ( 'fSKA1SURfull2', e.SKA1SURfull2 ), # 48 ( 'exptCV', e.exptCV ), # 49 ( 'GBTHIM', e.GBTHIM ), # 50 ( 'SKA0MID', e.SKA0MID ), # 51 ( 'fSKA0SUR', e.SKA0SUR ), # 52 ( 'SKA1MID900', e.SKA1MID900 ), # 53 ( 'SKA1MID350', e.SKA1MID350 ), # 54 ( 'iSKA1MID900', e.SKA1MID900 ), # 55 ( 'iSKA1MID350', e.SKA1MID350 ), # 56 ( 'fSKA1SUR650', e.SKA1SUR650 ), # 57 ( 'fSKA1SUR350', e.SKA1SUR350 ), # 58 ( 'aSKA1LOW', e.SKA1LOW ), # 59 ( 'SKAMID_PLUS', e.SKAMID_PLUS ), # 60 ( 'SKAMID_PLUS2', e.SKAMID_PLUS2 ), # 61 ( 'ihirax', e.HIRAX), # 62 #( 'ihirax', e.hirax), # 63 #( 'icbasehirax', e.cb_hirax), # 64 #( 'icbasehirax_2P', e.cb_hirax_2P), # 65 #( 'icbasehirax_3P', e.cb_hirax_3P), # 66 #( 'icbasehirax_10P', e.cb_hirax_10P), # 67 #( 'icbase_Ndish190_hirax', e.cb_Ndish190_hirax), #68 #( 'ihexax', e.hexax), # 69 #( 'SKA1MID1_plus_MEERKAT', e.SKA1MIDfull1_edited), #70 #( 'SKA1MID2_plus_MEERKAT', e.SKA1MIDfull2_edited), #71 #( 'MeerKATb1', e.MeerKATb1_edited ), #72 b1=UHF-band #( 'MeerKATb2', e.MeerKATb2_edited ), #73 b2=L-band #( 'icbasehirax_Ndish529', e.cb_hirax_Ndish529), #74 #( 'icbasehirax_Ndish132', e.cb_hirax_Ndish132), #75 #( 'icbasehirax_Ndish256', e.cb_hirax_Ndish256), #76 #( 'MeerKATb1_noNoise', e.MeerKATb1_noNoise), #77 #( 'MeerKATb2_noNoise', e.MeerKATb2_noNoise), #78 #( 'iCVlimitedz0to3', e.CVlimited_z0to3), #79 #( 'iCVlimitedz2to5', e.CVlimited_z2to5), #80 #( 'icbasehirax_kmax014', e.cb_hirax_kmax014), #81 ] names, expts = zip(*expt_list) names = list(names); expts = list(expts) ################################################################################ # Take command-line argument for which survey to calculate, or set manually if len(sys.argv) > 1: k = int(sys.argv[1]) try: Sarea = float(sys.argv[2]) except: Sarea = None pass try: bintype=int(sys.argv[3]) bintype_width=float(sys.argv[4]) except: bintype = None bintype_width = None try: integration_time=float(sys.argv[5]) except: integration_time=None try: kmax = float(sys.argv[6]) except: kmax = 130. #default in fisher() try: kbin_number=int(sys.argv[7]) except: kbin_number=None else: raise IndexError("Need to specify ID for experiment.") names[k] += EXPT_LABEL if myid == 0: print "="*50 print "Survey:", names[k] print "="*50 # Tweak settings depending on chosen experiment cv_limited = False if "CVlimited" in names[k]: cv_limited = True print "*"*10, "\n", "Cosmic variance-limited survey", "\n", "*"*10 expts[k]['mode'] = "dish" if names[k][0] == "i": expts[k]['mode'] = "idish" if names[k][0] == "c": expts[k]['mode'] = "combined" if names[k][0] == "y": expts[k]['mode'] = "icyl" if names[k][0] == "f": expts[k]['mode'] = "paf" if names[k][0] == "t": expts[k]['mode'] = "ipaf" if names[k][0] == "a": expts[k]['mode'] = "iaa" expt = expts[k] if Sarea is None: survey_name = names[k] root = "output/" + survey_name else: expt['Sarea'] = Sarea * (D2RAD)**2. survey_name = names[k] + "_" + str(int(Sarea)) root = "output/" + survey_name # Define redshift bins expt_zbins = rf.overlapping_expts(expt) if bintype==0: zs, zc = rf.zbins_equal_spaced(expt_zbins, dz=bintype_width) root=root+'_zbin'+str(bintype_width) elif bintype==1: bintype_width=int(bintype_width) zs, zc = rf.zbins_const_dr(expt_zbins, cosmo, bins=bintype_width) root=root+'_nrbin'+str(bintype_width) elif bintype==2: zs, zc = rf.zbins_const_dnu(expt_zbins, cosmo, dnu=bintype_width) root=root+'_nubin'+str(bintype_width) else: # zs, zc = rf.zbins_equal_spaced(expt_zbins, dz=0.1) zs, zc = rf.zbins_const_dnu(expt_zbins, cosmo, dnu=60.) if integration_time is not None: expt['ttot']=integration_time * experiments.HRS_MHZ # conversion from survey time to total integration time root=root+'_ttot'+str(np.int(integration_time))+'hours' if kmax != 130.: root = root+'_kmax'+str(kmax)+'invMpc' # Define kbins (used for output) if kbin_number is not None: kbins = np.logspace(np.log10(0.01), np.log10(1.0), kbin_number) root=root+'_nkbin'+str(kbin_number) else: kbins = np.logspace(np.log10(0.01), np.log10(1.0), 61) # print "K from 0.01 to 0.15 \n" # root = root + "_k001to015" # kbins = np.logspace(np.log10(0.01), np.log10(0.15), 61) # kbins = np.logspace(np.log10(0.001), np.log10(50.), 91)##kbins = np.logspace(-4., 0., 81) # Neutrino mass #cosmo['mnu'] = 0.1 # FIXME # Precompute cosmological functions, P(k), massive neutrinos, and T(k) for f_NL cosmo_fns = rf.background_evolution_splines(cosmo) if cosmo['mnu'] != 0.: # Massive neutrinos mnu_str = "mnu%03d" % (cosmo['mnu']*100.) fname_pk = "cache_pk_%s.dat" % mnu_str fname_nu = "cache_%s" % mnu_str survey_name += mnu_str; root += mnu_str cosmo = rf.load_power_spectrum(cosmo, fname_pk, comm=comm) mnu_fn = rf.deriv_neutrinos(cosmo, fname_nu, mnu=cosmo['mnu'], comm=comm) else: # Normal operation (no massive neutrinos or non-Gaussianity) cosmo = rf.load_power_spectrum(cosmo, "cache_pk.dat", comm=comm) mnu_fn = None # Non-Gaussianity #transfer_fn = rf.deriv_transfer(cosmo, "cache_transfer.dat", comm=comm) transfer_fn = None # Effective no. neutrinos, N_eff #Neff_fn = rf.deriv_neutrinos(cosmo, "cache_Neff", Neff=cosmo['N_eff'], comm=comm) Neff_fn = None # Optional additional parameters switches = [] #switches = ['mg', 'sdbias'] H, r, D, f = cosmo_fns ################################################################################ # Store cosmological functions ################################################################################ # Store values of cosmological functions if myid == 0: # Calculate cosmo fns. at redshift bin centroids and save _H = H(zc) _dA = r(zc) / (1. + np.array(zc)) _D = D(zc) _f = f(zc) np.savetxt(root+"-cosmofns-zc.dat", np.column_stack((zc, _H, _dA, _D, _f))) # Calculate cosmo fns. as smooth fns. of z and save zz = np.linspace(0., 1.05*np.max(zc), 1000) _H = H(zz) _dA = r(zz) / (1. + zz) _D = D(zz) _f = f(zz) np.savetxt(root+"-cosmofns-smooth.dat", np.column_stack((zz, _H, _dA, _D, _f)) ) # Precompute derivs for all processes eos_derivs = rf.eos_fisher_matrix_derivs(cosmo, cosmo_fns) ################################################################################ # Loop through redshift bins, assigning them to each process ################################################################################ print "*"*50 for key in cosmo.keys(): print "%20s: %s" % (key, cosmo[key]) print "*"*50 for key in expt.keys(): print "%20s: %s" % (key, expt[key]) print "*"*50 exit() for i in range(zs.size-1): if i % size != myid: continue print ">>> %2d working on redshift bin %2d -- z = %3.3f" % (myid, i, zc[i]) # Calculate effective experimental params. in the case of overlapping expts. Sarea_rad = Sarea*(D2RAD)**2. if Sarea is not None else None expt_eff = rf.overlapping_expts(expt, zs[i], zs[i+1], Sarea=Sarea_rad) # Calculate basic Fisher matrix # (A, bHI, Tb, sigma_NL, sigma8, n_s, f, aperp, apar, [Mnu], [fNL], [pk]*Nkbins) F_pk, kc, binning_info, paramnames = rf.fisher( zs[i], zs[i+1], cosmo, expt_eff, cosmo_fns=cosmo_fns, transfer_fn=transfer_fn, massive_nu_fn=mnu_fn, Neff_fn=Neff_fn, return_pk=True, cv_limited=cv_limited, switches=switches, kbins=kbins, kmax = kmax ) # Expand Fisher matrix with EOS parameters ##F_eos = rf.fisher_with_excluded_params(F, [10, 11, 12]) # Exclude P(k) F_eos, paramnames = rf.expand_fisher_matrix(zc[i], eos_derivs, F_pk, names=paramnames, exclude=[]) # Expand Fisher matrix for H(z), dA(z) # Replace aperp with dA(zi), using product rule. aperp(z) = dA(fid,z) / dA(z) # (And convert dA to Gpc, to help with the numerics) paramnames[paramnames.index('aperp')] = 'DA' da = r(zc[i]) / (1. + zc[i]) / 1000. # Gpc F_eos[7,:] *= -1. / da F_eos[:,7] *= -1. / da # Replace apar with H(zi)/100, using product rule. apar(z) = H(z) / H(fid,z) paramnames[paramnames.index('apar')] = 'H' F_eos[8,:] *= 1. / H(zc[i]) * 100. F_eos[:,8] *= 1. / H(zc[i]) * 100. # Save Fisher matrix and k bins np.savetxt(root+"-fisher-full-%d.dat" % i, F_eos, header=" ".join(paramnames)) if myid == 0: np.savetxt(root+"-fisher-kc.dat", kc) # Save P(k) rebinning info np.savetxt(root+"-rebin-Fbase-%d.dat" % i, np.array(binning_info['F_base']) ) np.savetxt(root+"-rebin-cumul-%d.dat" % i, np.array(binning_info['cumul']) ) np.savetxt(root+"-rebin-kgrid-%d.dat" % i, np.array(binning_info['kgrid']) ) np.savetxt(root+"-rebin-Vfac-%d.dat" % i, np.array([binning_info['Vfac'],]) ) comm.barrier() if myid == 0: print "Finished."
philbullREPO_NAMERadioFisherPATH_START.@RadioFisher_extracted@RadioFisher-master@amadeus_full_experiment.py@.PATH_END.py
{ "filename": "conf.py", "repo_name": "agurvich/FIRE_studio", "repo_path": "FIRE_studio_extracted/FIRE_studio-main/docs/source/conf.py", "type": "Python" }
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- Project information ----------------------------------------------------- project = 'firestudio' copyright = '2022, Alex Gurvich' author = 'Alex Gurvich' # The full version, including alpha/beta/rc tags release = '2.0.0' # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = [] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static']
agurvichREPO_NAMEFIRE_studioPATH_START.@FIRE_studio_extracted@FIRE_studio-main@docs@source@conf.py@.PATH_END.py
{ "filename": "base_pruner.py", "repo_name": "alibaba/TinyNeuralNetwork", "repo_path": "TinyNeuralNetwork_extracted/TinyNeuralNetwork-main/tinynn/prune/base_pruner.py", "type": "Python" }
import collections import typing from abc import ABC, abstractmethod from inspect import getsource from pprint import pformat import torch import torch.distributed as dist import torch.nn as nn from torch.nn.parallel.data_parallel import DataParallel from torch.nn.parallel.distributed import DistributedDataParallel from tinynn.graph.modifier import is_dw_conv from tinynn.graph.tracer import TraceGraph, trace from tinynn.util.train_util import DLContext, get_module_device from tinynn.util.util import conditional, get_actual_type, get_logger try: import ruamel_yaml as yaml except ModuleNotFoundError: import ruamel.yaml as yaml NEW_YAML_FLAG = "error_deprecation" in getsource(yaml.load) log = get_logger(__name__) class BasePruner(ABC): required_params = () required_context_params = () default_values = {} context_from_params_dict = {} condition_dict = {} model: nn.Module dummy_input: torch.Tensor config: typing.Union[dict, collections.OrderedDict] graph: TraceGraph context: DLContext def __init__(self, model, dummy_input, config): self.model = model self.config = config self.dummy_input = dummy_input self.graph = self.trace() @abstractmethod def prune(self): """The main function for pruning""" pass @abstractmethod def register_mask(self): """Computes the mask for the parameters in the model and register them through the maskers""" pass @abstractmethod def apply_mask(self): """Applies the masks for the parameters and updates the shape and properties of the tensors and modules""" pass def parse_config(self): """Parses the config and init the parameters of the pruner""" if isinstance(self.config, str): self.config = self.load_config(self.config) if not isinstance(self.config, dict): raise Exception('The `config` argument requires a parsed json object (e.g. dict or OrderedDict)') missing_params = set(self.required_params) - set(self.config) if len(missing_params) != 0: missing_params_str = ', '.join(missing_params) raise Exception(f'Missing param {missing_params_str} for {type(self).__name__}') for param_key, default_value in self.default_values.items(): if param_key not in self.config: self.config[param_key] = default_value type_dict = {} for cls in reversed(type(self).__mro__): if hasattr(cls, '__annotations__') and cls != BasePruner: type_dict.update(cls.__annotations__) for param_key, param_type in type_dict.items(): if param_key not in self.config: continue type_expected = False param_types = get_actual_type(param_type) for type_cand in param_types: if isinstance(self.config[param_key], type_cand): type_expected = True break if not type_expected: raise Exception(f'The type of `{param_key}` in {type(self).__name__} should be {param_type}') for param_key, predicate in self.condition_dict.items(): if predicate(self.config[param_key]) is False: raise Exception(f'The value of `{param_key}` doesn\'t meet the requirement: {getsource(predicate)}') def parse_context(self, context: DLContext): """Parses the context and copy the needed items to the pruner""" for context_key, param_keys in self.context_from_params_dict.items(): for param_key in param_keys: if param_key in self.config: setattr(context, context_key, self.config[param_key]) break filtered_context = dict(filter(lambda x: x[1], context.__dict__.items())) missing_context_items = list(set(self.required_context_params) - set(filtered_context)) if len(missing_context_items) != 0: missing_context_items_str = ', '.join(missing_context_items) raise Exception(f'Missing context items {missing_context_items_str} for {type(self).__name__}') self.context = context def summary(self): """Dumps the parameters and possibly the related context items of the pruner""" if len(self.required_params) > 0: log.info('-' * 80) log.info(f'params ({type(self).__name__}):') for k, v in self.__dict__.items(): if k in self.required_params or k in self.default_values: log.info(f'{k}: {pformat(v)}') if len(self.required_context_params) > 0: log.info('-' * 80) log.info(f'context ({type(self).__name__}):') log.info('\n'.join((f'{k}: {pformat(v)}' for k, v in self.context.__dict__.items()))) @classmethod def load_config(cls, path: str) -> dict: """Loads the configuration file and returns it as a dictionary""" with open(path, 'r') as f: if NEW_YAML_FLAG: yaml_ = yaml.YAML(typ='rt') config = yaml_.load(f) else: config = yaml.load(f, Loader=yaml.RoundTripLoader) return config @conditional(lambda: not dist.is_available() or not dist.is_initialized() or dist.get_rank() == 0) def generate_config(self, path: str, config: dict = None) -> None: """Generates a new copy the updated configuration with the given path""" if config is None: config = self.config with open(path, 'w') as f: if NEW_YAML_FLAG: yaml_ = yaml.YAML(typ='rt') yaml_.default_flow_style = False yaml_.dump(config, f) else: yaml.dump(config, f, default_flow_style=False, Dumper=yaml.RoundTripDumper) def trace(self) -> TraceGraph: with torch.no_grad(): if isinstance(self.model, DataParallel) or isinstance(self.model, DistributedDataParallel): model = self.model.module else: model = self.model old_device = get_module_device(model) model.cpu() graph = trace(model, self.dummy_input) if old_device is not None: model.to(device=old_device) return graph def reset(self): """Regenerate the TraceGraph when it is invalidated""" self.graph = self.trace() def calc_flops(self) -> int: """Calculate the flops of the given model""" # If graph is invalidated, then we need to regenerate the graph if not self.graph.inited: self.reset() graph: TraceGraph = self.graph total_ops = 0 for node in graph.forward_nodes: m = node.module remove_in_channel_count = 0 remove_out_channel_count = 0 if hasattr(m, 'masker'): if m.masker.in_remove_idx is not None: remove_in_channel_count = len(m.masker.in_remove_idx) if m.masker.ot_remove_idx is not None: remove_out_channel_count = len(m.masker.ot_remove_idx) if type(m) in (nn.Conv2d, nn.ConvTranspose2d): kernel_ops = torch.zeros(m.weight.size()[2:]).numel() bias_ops = 1 if m.bias is not None else 0 in_channels = m.in_channels - remove_in_channel_count out_channels = m.out_channels - remove_out_channel_count out_elements = node.next_tensors[0].nelement() // m.out_channels * out_channels if is_dw_conv(m): groups = in_channels else: groups = m.groups total_ops += out_elements * (in_channels // groups * kernel_ops + bias_ops) elif type(m) in (nn.BatchNorm2d,): channels = m.num_features - remove_in_channel_count nelements = node.prev_tensors[0].numel() // m.num_features * channels total_ops += 2 * nelements elif type(m) in (nn.AvgPool2d, nn.AdaptiveAvgPool2d): channels = node.prev_tensors[0].size(1) - remove_in_channel_count kernel_ops = 1 num_elements = node.prev_tensors[0].numel() // node.prev_tensors[0].size(1) * channels total_ops += kernel_ops * num_elements elif type(m) in (nn.ReLU,): channels = node.prev_tensors[0].size(1) - remove_in_channel_count kernel_ops = 1 num_elements = node.prev_tensors[0].numel() // node.prev_tensors[0].size(1) * channels total_ops += kernel_ops * num_elements elif type(m) in (nn.Linear,): in_channels = m.in_features - remove_in_channel_count out_channels = m.out_features - remove_out_channel_count total_mul = in_channels num_elements = node.next_tensors[0].numel() // m.out_features * out_channels total_ops += total_mul * num_elements return total_ops
alibabaREPO_NAMETinyNeuralNetworkPATH_START.@TinyNeuralNetwork_extracted@TinyNeuralNetwork-main@tinynn@prune@base_pruner.py@.PATH_END.py
{ "filename": "python_message.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/protobuf/py3/google/protobuf/internal/python_message.py", "type": "Python" }
# Protocol Buffers - Google's data interchange format # Copyright 2008 Google Inc. All rights reserved. # https://developers.google.com/protocol-buffers/ # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # This code is meant to work on Python 2.4 and above only. # # TODO(robinson): Helpers for verbose, common checks like seeing if a # descriptor's cpp_type is CPPTYPE_MESSAGE. """Contains a metaclass and helper functions used to create protocol message classes from Descriptor objects at runtime. Recall that a metaclass is the "type" of a class. (A class is to a metaclass what an instance is to a class.) In this case, we use the GeneratedProtocolMessageType metaclass to inject all the useful functionality into the classes output by the protocol compiler at compile-time. The upshot of all this is that the real implementation details for ALL pure-Python protocol buffers are *here in this file*. """ __author__ = 'robinson@google.com (Will Robinson)' from io import BytesIO import struct import sys import weakref # We use "as" to avoid name collisions with variables. from google.protobuf.internal import api_implementation from google.protobuf.internal import containers from google.protobuf.internal import decoder from google.protobuf.internal import encoder from google.protobuf.internal import enum_type_wrapper from google.protobuf.internal import extension_dict from google.protobuf.internal import message_listener as message_listener_mod from google.protobuf.internal import type_checkers from google.protobuf.internal import well_known_types from google.protobuf.internal import wire_format from google.protobuf import descriptor as descriptor_mod from google.protobuf import message as message_mod from google.protobuf import text_format _FieldDescriptor = descriptor_mod.FieldDescriptor _AnyFullTypeName = 'google.protobuf.Any' _ExtensionDict = extension_dict._ExtensionDict class GeneratedProtocolMessageType(type): """Metaclass for protocol message classes created at runtime from Descriptors. We add implementations for all methods described in the Message class. We also create properties to allow getting/setting all fields in the protocol message. Finally, we create slots to prevent users from accidentally "setting" nonexistent fields in the protocol message, which then wouldn't get serialized / deserialized properly. The protocol compiler currently uses this metaclass to create protocol message classes at runtime. Clients can also manually create their own classes at runtime, as in this example: mydescriptor = Descriptor(.....) factory = symbol_database.Default() factory.pool.AddDescriptor(mydescriptor) MyProtoClass = factory.GetPrototype(mydescriptor) myproto_instance = MyProtoClass() myproto.foo_field = 23 ... """ # Must be consistent with the protocol-compiler code in # proto2/compiler/internal/generator.*. _DESCRIPTOR_KEY = 'DESCRIPTOR' def __new__(cls, name, bases, dictionary): """Custom allocation for runtime-generated class types. We override __new__ because this is apparently the only place where we can meaningfully set __slots__ on the class we're creating(?). (The interplay between metaclasses and slots is not very well-documented). Args: name: Name of the class (ignored, but required by the metaclass protocol). bases: Base classes of the class we're constructing. (Should be message.Message). We ignore this field, but it's required by the metaclass protocol dictionary: The class dictionary of the class we're constructing. dictionary[_DESCRIPTOR_KEY] must contain a Descriptor object describing this protocol message type. Returns: Newly-allocated class. Raises: RuntimeError: Generated code only work with python cpp extension. """ descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY] if isinstance(descriptor, str): raise RuntimeError('The generated code only work with python cpp ' 'extension, but it is using pure python runtime.') # If a concrete class already exists for this descriptor, don't try to # create another. Doing so will break any messages that already exist with # the existing class. # # The C++ implementation appears to have its own internal `PyMessageFactory` # to achieve similar results. # # This most commonly happens in `text_format.py` when using descriptors from # a custom pool; it calls symbol_database.Global().getPrototype() on a # descriptor which already has an existing concrete class. new_class = getattr(descriptor, '_concrete_class', None) if new_class: return new_class if descriptor.full_name in well_known_types.WKTBASES: bases += (well_known_types.WKTBASES[descriptor.full_name],) _AddClassAttributesForNestedExtensions(descriptor, dictionary) _AddSlots(descriptor, dictionary) superclass = super(GeneratedProtocolMessageType, cls) new_class = superclass.__new__(cls, name, bases, dictionary) return new_class def __init__(cls, name, bases, dictionary): """Here we perform the majority of our work on the class. We add enum getters, an __init__ method, implementations of all Message methods, and properties for all fields in the protocol type. Args: name: Name of the class (ignored, but required by the metaclass protocol). bases: Base classes of the class we're constructing. (Should be message.Message). We ignore this field, but it's required by the metaclass protocol dictionary: The class dictionary of the class we're constructing. dictionary[_DESCRIPTOR_KEY] must contain a Descriptor object describing this protocol message type. """ descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY] # If this is an _existing_ class looked up via `_concrete_class` in the # __new__ method above, then we don't need to re-initialize anything. existing_class = getattr(descriptor, '_concrete_class', None) if existing_class: assert existing_class is cls, ( 'Duplicate `GeneratedProtocolMessageType` created for descriptor %r' % (descriptor.full_name)) return cls._decoders_by_tag = {} if (descriptor.has_options and descriptor.GetOptions().message_set_wire_format): cls._decoders_by_tag[decoder.MESSAGE_SET_ITEM_TAG] = ( decoder.MessageSetItemDecoder(descriptor), None) # Attach stuff to each FieldDescriptor for quick lookup later on. for field in descriptor.fields: _AttachFieldHelpers(cls, field) descriptor._concrete_class = cls # pylint: disable=protected-access _AddEnumValues(descriptor, cls) _AddInitMethod(descriptor, cls) _AddPropertiesForFields(descriptor, cls) _AddPropertiesForExtensions(descriptor, cls) _AddStaticMethods(cls) _AddMessageMethods(descriptor, cls) _AddPrivateHelperMethods(descriptor, cls) superclass = super(GeneratedProtocolMessageType, cls) superclass.__init__(name, bases, dictionary) # Stateless helpers for GeneratedProtocolMessageType below. # Outside clients should not access these directly. # # I opted not to make any of these methods on the metaclass, to make it more # clear that I'm not really using any state there and to keep clients from # thinking that they have direct access to these construction helpers. def _PropertyName(proto_field_name): """Returns the name of the public property attribute which clients can use to get and (in some cases) set the value of a protocol message field. Args: proto_field_name: The protocol message field name, exactly as it appears (or would appear) in a .proto file. """ # TODO(robinson): Escape Python keywords (e.g., yield), and test this support. # nnorwitz makes my day by writing: # """ # FYI. See the keyword module in the stdlib. This could be as simple as: # # if keyword.iskeyword(proto_field_name): # return proto_field_name + "_" # return proto_field_name # """ # Kenton says: The above is a BAD IDEA. People rely on being able to use # getattr() and setattr() to reflectively manipulate field values. If we # rename the properties, then every such user has to also make sure to apply # the same transformation. Note that currently if you name a field "yield", # you can still access it just fine using getattr/setattr -- it's not even # that cumbersome to do so. # TODO(kenton): Remove this method entirely if/when everyone agrees with my # position. return proto_field_name def _AddSlots(message_descriptor, dictionary): """Adds a __slots__ entry to dictionary, containing the names of all valid attributes for this message type. Args: message_descriptor: A Descriptor instance describing this message type. dictionary: Class dictionary to which we'll add a '__slots__' entry. """ dictionary['__slots__'] = ['_cached_byte_size', '_cached_byte_size_dirty', '_fields', '_unknown_fields', '_unknown_field_set', '_is_present_in_parent', '_listener', '_listener_for_children', '__weakref__', '_oneofs'] def _IsMessageSetExtension(field): return (field.is_extension and field.containing_type.has_options and field.containing_type.GetOptions().message_set_wire_format and field.type == _FieldDescriptor.TYPE_MESSAGE and field.label == _FieldDescriptor.LABEL_OPTIONAL) def _IsMapField(field): return (field.type == _FieldDescriptor.TYPE_MESSAGE and field.message_type.has_options and field.message_type.GetOptions().map_entry) def _IsMessageMapField(field): value_type = field.message_type.fields_by_name['value'] return value_type.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE def _AttachFieldHelpers(cls, field_descriptor): is_repeated = (field_descriptor.label == _FieldDescriptor.LABEL_REPEATED) is_map_entry = _IsMapField(field_descriptor) is_packed = field_descriptor.is_packed if is_map_entry: field_encoder = encoder.MapEncoder(field_descriptor) sizer = encoder.MapSizer(field_descriptor, _IsMessageMapField(field_descriptor)) elif _IsMessageSetExtension(field_descriptor): field_encoder = encoder.MessageSetItemEncoder(field_descriptor.number) sizer = encoder.MessageSetItemSizer(field_descriptor.number) else: field_encoder = type_checkers.TYPE_TO_ENCODER[field_descriptor.type]( field_descriptor.number, is_repeated, is_packed) sizer = type_checkers.TYPE_TO_SIZER[field_descriptor.type]( field_descriptor.number, is_repeated, is_packed) field_descriptor._encoder = field_encoder field_descriptor._sizer = sizer field_descriptor._default_constructor = _DefaultValueConstructorForField( field_descriptor) def AddDecoder(wiretype, is_packed): tag_bytes = encoder.TagBytes(field_descriptor.number, wiretype) decode_type = field_descriptor.type if (decode_type == _FieldDescriptor.TYPE_ENUM and not field_descriptor.enum_type.is_closed): decode_type = _FieldDescriptor.TYPE_INT32 oneof_descriptor = None if field_descriptor.containing_oneof is not None: oneof_descriptor = field_descriptor if is_map_entry: is_message_map = _IsMessageMapField(field_descriptor) field_decoder = decoder.MapDecoder( field_descriptor, _GetInitializeDefaultForMap(field_descriptor), is_message_map) elif decode_type == _FieldDescriptor.TYPE_STRING: field_decoder = decoder.StringDecoder( field_descriptor.number, is_repeated, is_packed, field_descriptor, field_descriptor._default_constructor, not field_descriptor.has_presence) elif field_descriptor.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: field_decoder = type_checkers.TYPE_TO_DECODER[decode_type]( field_descriptor.number, is_repeated, is_packed, field_descriptor, field_descriptor._default_constructor) else: field_decoder = type_checkers.TYPE_TO_DECODER[decode_type]( field_descriptor.number, is_repeated, is_packed, # pylint: disable=protected-access field_descriptor, field_descriptor._default_constructor, not field_descriptor.has_presence) cls._decoders_by_tag[tag_bytes] = (field_decoder, oneof_descriptor) AddDecoder(type_checkers.FIELD_TYPE_TO_WIRE_TYPE[field_descriptor.type], False) if is_repeated and wire_format.IsTypePackable(field_descriptor.type): # To support wire compatibility of adding packed = true, add a decoder for # packed values regardless of the field's options. AddDecoder(wire_format.WIRETYPE_LENGTH_DELIMITED, True) def _AddClassAttributesForNestedExtensions(descriptor, dictionary): extensions = descriptor.extensions_by_name for extension_name, extension_field in extensions.items(): assert extension_name not in dictionary dictionary[extension_name] = extension_field def _AddEnumValues(descriptor, cls): """Sets class-level attributes for all enum fields defined in this message. Also exporting a class-level object that can name enum values. Args: descriptor: Descriptor object for this message type. cls: Class we're constructing for this message type. """ for enum_type in descriptor.enum_types: setattr(cls, enum_type.name, enum_type_wrapper.EnumTypeWrapper(enum_type)) for enum_value in enum_type.values: setattr(cls, enum_value.name, enum_value.number) def _GetInitializeDefaultForMap(field): if field.label != _FieldDescriptor.LABEL_REPEATED: raise ValueError('map_entry set on non-repeated field %s' % ( field.name)) fields_by_name = field.message_type.fields_by_name key_checker = type_checkers.GetTypeChecker(fields_by_name['key']) value_field = fields_by_name['value'] if _IsMessageMapField(field): def MakeMessageMapDefault(message): return containers.MessageMap( message._listener_for_children, value_field.message_type, key_checker, field.message_type) return MakeMessageMapDefault else: value_checker = type_checkers.GetTypeChecker(value_field) def MakePrimitiveMapDefault(message): return containers.ScalarMap( message._listener_for_children, key_checker, value_checker, field.message_type) return MakePrimitiveMapDefault def _DefaultValueConstructorForField(field): """Returns a function which returns a default value for a field. Args: field: FieldDescriptor object for this field. The returned function has one argument: message: Message instance containing this field, or a weakref proxy of same. That function in turn returns a default value for this field. The default value may refer back to |message| via a weak reference. """ if _IsMapField(field): return _GetInitializeDefaultForMap(field) if field.label == _FieldDescriptor.LABEL_REPEATED: if field.has_default_value and field.default_value != []: raise ValueError('Repeated field default value not empty list: %s' % ( field.default_value)) if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: # We can't look at _concrete_class yet since it might not have # been set. (Depends on order in which we initialize the classes). message_type = field.message_type def MakeRepeatedMessageDefault(message): return containers.RepeatedCompositeFieldContainer( message._listener_for_children, field.message_type) return MakeRepeatedMessageDefault else: type_checker = type_checkers.GetTypeChecker(field) def MakeRepeatedScalarDefault(message): return containers.RepeatedScalarFieldContainer( message._listener_for_children, type_checker) return MakeRepeatedScalarDefault if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: # _concrete_class may not yet be initialized. message_type = field.message_type def MakeSubMessageDefault(message): assert getattr(message_type, '_concrete_class', None), ( 'Uninitialized concrete class found for field %r (message type %r)' % (field.full_name, message_type.full_name)) result = message_type._concrete_class() result._SetListener( _OneofListener(message, field) if field.containing_oneof is not None else message._listener_for_children) return result return MakeSubMessageDefault def MakeScalarDefault(message): # TODO(protobuf-team): This may be broken since there may not be # default_value. Combine with has_default_value somehow. return field.default_value return MakeScalarDefault def _ReraiseTypeErrorWithFieldName(message_name, field_name): """Re-raise the currently-handled TypeError with the field name added.""" exc = sys.exc_info()[1] if len(exc.args) == 1 and type(exc) is TypeError: # simple TypeError; add field name to exception message exc = TypeError('%s for field %s.%s' % (str(exc), message_name, field_name)) # re-raise possibly-amended exception with original traceback: raise exc.with_traceback(sys.exc_info()[2]) def _AddInitMethod(message_descriptor, cls): """Adds an __init__ method to cls.""" def _GetIntegerEnumValue(enum_type, value): """Convert a string or integer enum value to an integer. If the value is a string, it is converted to the enum value in enum_type with the same name. If the value is not a string, it's returned as-is. (No conversion or bounds-checking is done.) """ if isinstance(value, str): try: return enum_type.values_by_name[value].number except KeyError: raise ValueError('Enum type %s: unknown label "%s"' % ( enum_type.full_name, value)) return value def init(self, **kwargs): self._cached_byte_size = 0 self._cached_byte_size_dirty = len(kwargs) > 0 self._fields = {} # Contains a mapping from oneof field descriptors to the descriptor # of the currently set field in that oneof field. self._oneofs = {} # _unknown_fields is () when empty for efficiency, and will be turned into # a list if fields are added. self._unknown_fields = () # _unknown_field_set is None when empty for efficiency, and will be # turned into UnknownFieldSet struct if fields are added. self._unknown_field_set = None # pylint: disable=protected-access self._is_present_in_parent = False self._listener = message_listener_mod.NullMessageListener() self._listener_for_children = _Listener(self) for field_name, field_value in kwargs.items(): field = _GetFieldByName(message_descriptor, field_name) if field is None: raise TypeError('%s() got an unexpected keyword argument "%s"' % (message_descriptor.name, field_name)) if field_value is None: # field=None is the same as no field at all. continue if field.label == _FieldDescriptor.LABEL_REPEATED: copy = field._default_constructor(self) if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: # Composite if _IsMapField(field): if _IsMessageMapField(field): for key in field_value: copy[key].MergeFrom(field_value[key]) else: copy.update(field_value) else: for val in field_value: if isinstance(val, dict): copy.add(**val) else: copy.add().MergeFrom(val) else: # Scalar if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM: field_value = [_GetIntegerEnumValue(field.enum_type, val) for val in field_value] copy.extend(field_value) self._fields[field] = copy elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: copy = field._default_constructor(self) new_val = field_value if isinstance(field_value, dict): new_val = field.message_type._concrete_class(**field_value) try: copy.MergeFrom(new_val) except TypeError: _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name) self._fields[field] = copy else: if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM: field_value = _GetIntegerEnumValue(field.enum_type, field_value) try: setattr(self, field_name, field_value) except TypeError: _ReraiseTypeErrorWithFieldName(message_descriptor.name, field_name) init.__module__ = None init.__doc__ = None cls.__init__ = init def _GetFieldByName(message_descriptor, field_name): """Returns a field descriptor by field name. Args: message_descriptor: A Descriptor describing all fields in message. field_name: The name of the field to retrieve. Returns: The field descriptor associated with the field name. """ try: return message_descriptor.fields_by_name[field_name] except KeyError: raise ValueError('Protocol message %s has no "%s" field.' % (message_descriptor.name, field_name)) def _AddPropertiesForFields(descriptor, cls): """Adds properties for all fields in this protocol message type.""" for field in descriptor.fields: _AddPropertiesForField(field, cls) if descriptor.is_extendable: # _ExtensionDict is just an adaptor with no state so we allocate a new one # every time it is accessed. cls.Extensions = property(lambda self: _ExtensionDict(self)) def _AddPropertiesForField(field, cls): """Adds a public property for a protocol message field. Clients can use this property to get and (in the case of non-repeated scalar fields) directly set the value of a protocol message field. Args: field: A FieldDescriptor for this field. cls: The class we're constructing. """ # Catch it if we add other types that we should # handle specially here. assert _FieldDescriptor.MAX_CPPTYPE == 10 constant_name = field.name.upper() + '_FIELD_NUMBER' setattr(cls, constant_name, field.number) if field.label == _FieldDescriptor.LABEL_REPEATED: _AddPropertiesForRepeatedField(field, cls) elif field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: _AddPropertiesForNonRepeatedCompositeField(field, cls) else: _AddPropertiesForNonRepeatedScalarField(field, cls) class _FieldProperty(property): __slots__ = ('DESCRIPTOR',) def __init__(self, descriptor, getter, setter, doc): property.__init__(self, getter, setter, doc=doc) self.DESCRIPTOR = descriptor def _AddPropertiesForRepeatedField(field, cls): """Adds a public property for a "repeated" protocol message field. Clients can use this property to get the value of the field, which will be either a RepeatedScalarFieldContainer or RepeatedCompositeFieldContainer (see below). Note that when clients add values to these containers, we perform type-checking in the case of repeated scalar fields, and we also set any necessary "has" bits as a side-effect. Args: field: A FieldDescriptor for this field. cls: The class we're constructing. """ proto_field_name = field.name property_name = _PropertyName(proto_field_name) def getter(self): field_value = self._fields.get(field) if field_value is None: # Construct a new object to represent this field. field_value = field._default_constructor(self) # Atomically check if another thread has preempted us and, if not, swap # in the new object we just created. If someone has preempted us, we # take that object and discard ours. # WARNING: We are relying on setdefault() being atomic. This is true # in CPython but we haven't investigated others. This warning appears # in several other locations in this file. field_value = self._fields.setdefault(field, field_value) return field_value getter.__module__ = None getter.__doc__ = 'Getter for %s.' % proto_field_name # We define a setter just so we can throw an exception with a more # helpful error message. def setter(self, new_value): raise AttributeError('Assignment not allowed to repeated field ' '"%s" in protocol message object.' % proto_field_name) doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name setattr(cls, property_name, _FieldProperty(field, getter, setter, doc=doc)) def _AddPropertiesForNonRepeatedScalarField(field, cls): """Adds a public property for a nonrepeated, scalar protocol message field. Clients can use this property to get and directly set the value of the field. Note that when the client sets the value of a field by using this property, all necessary "has" bits are set as a side-effect, and we also perform type-checking. Args: field: A FieldDescriptor for this field. cls: The class we're constructing. """ proto_field_name = field.name property_name = _PropertyName(proto_field_name) type_checker = type_checkers.GetTypeChecker(field) default_value = field.default_value def getter(self): # TODO(protobuf-team): This may be broken since there may not be # default_value. Combine with has_default_value somehow. return self._fields.get(field, default_value) getter.__module__ = None getter.__doc__ = 'Getter for %s.' % proto_field_name def field_setter(self, new_value): # pylint: disable=protected-access # Testing the value for truthiness captures all of the proto3 defaults # (0, 0.0, enum 0, and False). try: new_value = type_checker.CheckValue(new_value) except TypeError as e: raise TypeError( 'Cannot set %s to %.1024r: %s' % (field.full_name, new_value, e)) if not field.has_presence and not new_value: self._fields.pop(field, None) else: self._fields[field] = new_value # Check _cached_byte_size_dirty inline to improve performance, since scalar # setters are called frequently. if not self._cached_byte_size_dirty: self._Modified() if field.containing_oneof: def setter(self, new_value): field_setter(self, new_value) self._UpdateOneofState(field) else: setter = field_setter setter.__module__ = None setter.__doc__ = 'Setter for %s.' % proto_field_name # Add a property to encapsulate the getter/setter. doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name setattr(cls, property_name, _FieldProperty(field, getter, setter, doc=doc)) def _AddPropertiesForNonRepeatedCompositeField(field, cls): """Adds a public property for a nonrepeated, composite protocol message field. A composite field is a "group" or "message" field. Clients can use this property to get the value of the field, but cannot assign to the property directly. Args: field: A FieldDescriptor for this field. cls: The class we're constructing. """ # TODO(robinson): Remove duplication with similar method # for non-repeated scalars. proto_field_name = field.name property_name = _PropertyName(proto_field_name) def getter(self): field_value = self._fields.get(field) if field_value is None: # Construct a new object to represent this field. field_value = field._default_constructor(self) # Atomically check if another thread has preempted us and, if not, swap # in the new object we just created. If someone has preempted us, we # take that object and discard ours. # WARNING: We are relying on setdefault() being atomic. This is true # in CPython but we haven't investigated others. This warning appears # in several other locations in this file. field_value = self._fields.setdefault(field, field_value) return field_value getter.__module__ = None getter.__doc__ = 'Getter for %s.' % proto_field_name # We define a setter just so we can throw an exception with a more # helpful error message. def setter(self, new_value): raise AttributeError('Assignment not allowed to composite field ' '"%s" in protocol message object.' % proto_field_name) # Add a property to encapsulate the getter. doc = 'Magic attribute generated for "%s" proto field.' % proto_field_name setattr(cls, property_name, _FieldProperty(field, getter, setter, doc=doc)) def _AddPropertiesForExtensions(descriptor, cls): """Adds properties for all fields in this protocol message type.""" extensions = descriptor.extensions_by_name for extension_name, extension_field in extensions.items(): constant_name = extension_name.upper() + '_FIELD_NUMBER' setattr(cls, constant_name, extension_field.number) # TODO(amauryfa): Migrate all users of these attributes to functions like # pool.FindExtensionByNumber(descriptor). if descriptor.file is not None: # TODO(amauryfa): Use cls.MESSAGE_FACTORY.pool when available. pool = descriptor.file.pool cls._extensions_by_number = pool._extensions_by_number[descriptor] cls._extensions_by_name = pool._extensions_by_name[descriptor] def _AddStaticMethods(cls): # TODO(robinson): This probably needs to be thread-safe(?) def RegisterExtension(field_descriptor): field_descriptor.containing_type = cls.DESCRIPTOR # TODO(amauryfa): Use cls.MESSAGE_FACTORY.pool when available. # pylint: disable=protected-access cls.DESCRIPTOR.file.pool._AddExtensionDescriptor(field_descriptor) _AttachFieldHelpers(cls, field_descriptor) cls.RegisterExtension = staticmethod(RegisterExtension) def FromString(s): message = cls() message.MergeFromString(s) return message cls.FromString = staticmethod(FromString) def _IsPresent(item): """Given a (FieldDescriptor, value) tuple from _fields, return true if the value should be included in the list returned by ListFields().""" if item[0].label == _FieldDescriptor.LABEL_REPEATED: return bool(item[1]) elif item[0].cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: return item[1]._is_present_in_parent else: return True def _AddListFieldsMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def ListFields(self): all_fields = [item for item in self._fields.items() if _IsPresent(item)] all_fields.sort(key = lambda item: item[0].number) return all_fields cls.ListFields = ListFields def _AddHasFieldMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" hassable_fields = {} for field in message_descriptor.fields: if field.label == _FieldDescriptor.LABEL_REPEATED: continue # For proto3, only submessages and fields inside a oneof have presence. if not field.has_presence: continue hassable_fields[field.name] = field # Has methods are supported for oneof descriptors. for oneof in message_descriptor.oneofs: hassable_fields[oneof.name] = oneof def HasField(self, field_name): try: field = hassable_fields[field_name] except KeyError as exc: raise ValueError('Protocol message %s has no non-repeated field "%s" ' 'nor has presence is not available for this field.' % ( message_descriptor.full_name, field_name)) from exc if isinstance(field, descriptor_mod.OneofDescriptor): try: return HasField(self, self._oneofs[field].name) except KeyError: return False else: if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: value = self._fields.get(field) return value is not None and value._is_present_in_parent else: return field in self._fields cls.HasField = HasField def _AddClearFieldMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def ClearField(self, field_name): try: field = message_descriptor.fields_by_name[field_name] except KeyError: try: field = message_descriptor.oneofs_by_name[field_name] if field in self._oneofs: field = self._oneofs[field] else: return except KeyError: raise ValueError('Protocol message %s has no "%s" field.' % (message_descriptor.name, field_name)) if field in self._fields: # To match the C++ implementation, we need to invalidate iterators # for map fields when ClearField() happens. if hasattr(self._fields[field], 'InvalidateIterators'): self._fields[field].InvalidateIterators() # Note: If the field is a sub-message, its listener will still point # at us. That's fine, because the worst than can happen is that it # will call _Modified() and invalidate our byte size. Big deal. del self._fields[field] if self._oneofs.get(field.containing_oneof, None) is field: del self._oneofs[field.containing_oneof] # Always call _Modified() -- even if nothing was changed, this is # a mutating method, and thus calling it should cause the field to become # present in the parent message. self._Modified() cls.ClearField = ClearField def _AddClearExtensionMethod(cls): """Helper for _AddMessageMethods().""" def ClearExtension(self, field_descriptor): extension_dict._VerifyExtensionHandle(self, field_descriptor) # Similar to ClearField(), above. if field_descriptor in self._fields: del self._fields[field_descriptor] self._Modified() cls.ClearExtension = ClearExtension def _AddHasExtensionMethod(cls): """Helper for _AddMessageMethods().""" def HasExtension(self, field_descriptor): extension_dict._VerifyExtensionHandle(self, field_descriptor) if field_descriptor.label == _FieldDescriptor.LABEL_REPEATED: raise KeyError('"%s" is repeated.' % field_descriptor.full_name) if field_descriptor.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: value = self._fields.get(field_descriptor) return value is not None and value._is_present_in_parent else: return field_descriptor in self._fields cls.HasExtension = HasExtension def _InternalUnpackAny(msg): """Unpacks Any message and returns the unpacked message. This internal method is different from public Any Unpack method which takes the target message as argument. _InternalUnpackAny method does not have target message type and need to find the message type in descriptor pool. Args: msg: An Any message to be unpacked. Returns: The unpacked message. """ # TODO(amauryfa): Don't use the factory of generated messages. # To make Any work with custom factories, use the message factory of the # parent message. # pylint: disable=g-import-not-at-top from google.protobuf import symbol_database factory = symbol_database.Default() type_url = msg.type_url if not type_url: return None # TODO(haberman): For now we just strip the hostname. Better logic will be # required. type_name = type_url.split('/')[-1] descriptor = factory.pool.FindMessageTypeByName(type_name) if descriptor is None: return None message_class = factory.GetPrototype(descriptor) message = message_class() message.ParseFromString(msg.value) return message def _AddEqualsMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def __eq__(self, other): if (not isinstance(other, message_mod.Message) or other.DESCRIPTOR != self.DESCRIPTOR): return False if self is other: return True if self.DESCRIPTOR.full_name == _AnyFullTypeName: any_a = _InternalUnpackAny(self) any_b = _InternalUnpackAny(other) if any_a and any_b: return any_a == any_b if not self.ListFields() == other.ListFields(): return False # TODO(jieluo): Fix UnknownFieldSet to consider MessageSet extensions, # then use it for the comparison. unknown_fields = list(self._unknown_fields) unknown_fields.sort() other_unknown_fields = list(other._unknown_fields) other_unknown_fields.sort() return unknown_fields == other_unknown_fields cls.__eq__ = __eq__ def _AddStrMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def __str__(self): return text_format.MessageToString(self) cls.__str__ = __str__ def _AddReprMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def __repr__(self): return text_format.MessageToString(self) cls.__repr__ = __repr__ def _AddUnicodeMethod(unused_message_descriptor, cls): """Helper for _AddMessageMethods().""" def __unicode__(self): return text_format.MessageToString(self, as_utf8=True).decode('utf-8') cls.__unicode__ = __unicode__ def _BytesForNonRepeatedElement(value, field_number, field_type): """Returns the number of bytes needed to serialize a non-repeated element. The returned byte count includes space for tag information and any other additional space associated with serializing value. Args: value: Value we're serializing. field_number: Field number of this value. (Since the field number is stored as part of a varint-encoded tag, this has an impact on the total bytes required to serialize the value). field_type: The type of the field. One of the TYPE_* constants within FieldDescriptor. """ try: fn = type_checkers.TYPE_TO_BYTE_SIZE_FN[field_type] return fn(field_number, value) except KeyError: raise message_mod.EncodeError('Unrecognized field type: %d' % field_type) def _AddByteSizeMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def ByteSize(self): if not self._cached_byte_size_dirty: return self._cached_byte_size size = 0 descriptor = self.DESCRIPTOR if descriptor.GetOptions().map_entry: # Fields of map entry should always be serialized. size = descriptor.fields_by_name['key']._sizer(self.key) size += descriptor.fields_by_name['value']._sizer(self.value) else: for field_descriptor, field_value in self.ListFields(): size += field_descriptor._sizer(field_value) for tag_bytes, value_bytes in self._unknown_fields: size += len(tag_bytes) + len(value_bytes) self._cached_byte_size = size self._cached_byte_size_dirty = False self._listener_for_children.dirty = False return size cls.ByteSize = ByteSize def _AddSerializeToStringMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def SerializeToString(self, **kwargs): # Check if the message has all of its required fields set. if not self.IsInitialized(): raise message_mod.EncodeError( 'Message %s is missing required fields: %s' % ( self.DESCRIPTOR.full_name, ','.join(self.FindInitializationErrors()))) return self.SerializePartialToString(**kwargs) cls.SerializeToString = SerializeToString def _AddSerializePartialToStringMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def SerializePartialToString(self, **kwargs): out = BytesIO() self._InternalSerialize(out.write, **kwargs) return out.getvalue() cls.SerializePartialToString = SerializePartialToString def InternalSerialize(self, write_bytes, deterministic=None): if deterministic is None: deterministic = ( api_implementation.IsPythonDefaultSerializationDeterministic()) else: deterministic = bool(deterministic) descriptor = self.DESCRIPTOR if descriptor.GetOptions().map_entry: # Fields of map entry should always be serialized. descriptor.fields_by_name['key']._encoder( write_bytes, self.key, deterministic) descriptor.fields_by_name['value']._encoder( write_bytes, self.value, deterministic) else: for field_descriptor, field_value in self.ListFields(): field_descriptor._encoder(write_bytes, field_value, deterministic) for tag_bytes, value_bytes in self._unknown_fields: write_bytes(tag_bytes) write_bytes(value_bytes) cls._InternalSerialize = InternalSerialize def _AddMergeFromStringMethod(message_descriptor, cls): """Helper for _AddMessageMethods().""" def MergeFromString(self, serialized): serialized = memoryview(serialized) length = len(serialized) try: if self._InternalParse(serialized, 0, length) != length: # The only reason _InternalParse would return early is if it # encountered an end-group tag. raise message_mod.DecodeError('Unexpected end-group tag.') except (IndexError, TypeError): # Now ord(buf[p:p+1]) == ord('') gets TypeError. raise message_mod.DecodeError('Truncated message.') except struct.error as e: raise message_mod.DecodeError(e) return length # Return this for legacy reasons. cls.MergeFromString = MergeFromString local_ReadTag = decoder.ReadTag local_SkipField = decoder.SkipField decoders_by_tag = cls._decoders_by_tag def InternalParse(self, buffer, pos, end): """Create a message from serialized bytes. Args: self: Message, instance of the proto message object. buffer: memoryview of the serialized data. pos: int, position to start in the serialized data. end: int, end position of the serialized data. Returns: Message object. """ # Guard against internal misuse, since this function is called internally # quite extensively, and its easy to accidentally pass bytes. assert isinstance(buffer, memoryview) self._Modified() field_dict = self._fields # pylint: disable=protected-access unknown_field_set = self._unknown_field_set while pos != end: (tag_bytes, new_pos) = local_ReadTag(buffer, pos) field_decoder, field_desc = decoders_by_tag.get(tag_bytes, (None, None)) if field_decoder is None: if not self._unknown_fields: # pylint: disable=protected-access self._unknown_fields = [] # pylint: disable=protected-access if unknown_field_set is None: # pylint: disable=protected-access self._unknown_field_set = containers.UnknownFieldSet() # pylint: disable=protected-access unknown_field_set = self._unknown_field_set # pylint: disable=protected-access (tag, _) = decoder._DecodeVarint(tag_bytes, 0) field_number, wire_type = wire_format.UnpackTag(tag) if field_number == 0: raise message_mod.DecodeError('Field number 0 is illegal.') # TODO(jieluo): remove old_pos. old_pos = new_pos (data, new_pos) = decoder._DecodeUnknownField( buffer, new_pos, wire_type) # pylint: disable=protected-access if new_pos == -1: return pos # pylint: disable=protected-access unknown_field_set._add(field_number, wire_type, data) # TODO(jieluo): remove _unknown_fields. new_pos = local_SkipField(buffer, old_pos, end, tag_bytes) if new_pos == -1: return pos self._unknown_fields.append( (tag_bytes, buffer[old_pos:new_pos].tobytes())) pos = new_pos else: pos = field_decoder(buffer, new_pos, end, self, field_dict) if field_desc: self._UpdateOneofState(field_desc) return pos cls._InternalParse = InternalParse def _AddIsInitializedMethod(message_descriptor, cls): """Adds the IsInitialized and FindInitializationError methods to the protocol message class.""" required_fields = [field for field in message_descriptor.fields if field.label == _FieldDescriptor.LABEL_REQUIRED] def IsInitialized(self, errors=None): """Checks if all required fields of a message are set. Args: errors: A list which, if provided, will be populated with the field paths of all missing required fields. Returns: True iff the specified message has all required fields set. """ # Performance is critical so we avoid HasField() and ListFields(). for field in required_fields: if (field not in self._fields or (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and not self._fields[field]._is_present_in_parent)): if errors is not None: errors.extend(self.FindInitializationErrors()) return False for field, value in list(self._fields.items()): # dict can change size! if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: if field.label == _FieldDescriptor.LABEL_REPEATED: if (field.message_type.has_options and field.message_type.GetOptions().map_entry): continue for element in value: if not element.IsInitialized(): if errors is not None: errors.extend(self.FindInitializationErrors()) return False elif value._is_present_in_parent and not value.IsInitialized(): if errors is not None: errors.extend(self.FindInitializationErrors()) return False return True cls.IsInitialized = IsInitialized def FindInitializationErrors(self): """Finds required fields which are not initialized. Returns: A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz". """ errors = [] # simplify things for field in required_fields: if not self.HasField(field.name): errors.append(field.name) for field, value in self.ListFields(): if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: if field.is_extension: name = '(%s)' % field.full_name else: name = field.name if _IsMapField(field): if _IsMessageMapField(field): for key in value: element = value[key] prefix = '%s[%s].' % (name, key) sub_errors = element.FindInitializationErrors() errors += [prefix + error for error in sub_errors] else: # ScalarMaps can't have any initialization errors. pass elif field.label == _FieldDescriptor.LABEL_REPEATED: for i in range(len(value)): element = value[i] prefix = '%s[%d].' % (name, i) sub_errors = element.FindInitializationErrors() errors += [prefix + error for error in sub_errors] else: prefix = name + '.' sub_errors = value.FindInitializationErrors() errors += [prefix + error for error in sub_errors] return errors cls.FindInitializationErrors = FindInitializationErrors def _FullyQualifiedClassName(klass): module = klass.__module__ name = getattr(klass, '__qualname__', klass.__name__) if module in (None, 'builtins', '__builtin__'): return name return module + '.' + name def _AddMergeFromMethod(cls): LABEL_REPEATED = _FieldDescriptor.LABEL_REPEATED CPPTYPE_MESSAGE = _FieldDescriptor.CPPTYPE_MESSAGE def MergeFrom(self, msg): if not isinstance(msg, cls): raise TypeError( 'Parameter to MergeFrom() must be instance of same class: ' 'expected %s got %s.' % (_FullyQualifiedClassName(cls), _FullyQualifiedClassName(msg.__class__))) assert msg is not self self._Modified() fields = self._fields for field, value in msg._fields.items(): if field.label == LABEL_REPEATED: field_value = fields.get(field) if field_value is None: # Construct a new object to represent this field. field_value = field._default_constructor(self) fields[field] = field_value field_value.MergeFrom(value) elif field.cpp_type == CPPTYPE_MESSAGE: if value._is_present_in_parent: field_value = fields.get(field) if field_value is None: # Construct a new object to represent this field. field_value = field._default_constructor(self) fields[field] = field_value field_value.MergeFrom(value) else: self._fields[field] = value if field.containing_oneof: self._UpdateOneofState(field) if msg._unknown_fields: if not self._unknown_fields: self._unknown_fields = [] self._unknown_fields.extend(msg._unknown_fields) # pylint: disable=protected-access if self._unknown_field_set is None: self._unknown_field_set = containers.UnknownFieldSet() self._unknown_field_set._extend(msg._unknown_field_set) cls.MergeFrom = MergeFrom def _AddWhichOneofMethod(message_descriptor, cls): def WhichOneof(self, oneof_name): """Returns the name of the currently set field inside a oneof, or None.""" try: field = message_descriptor.oneofs_by_name[oneof_name] except KeyError: raise ValueError( 'Protocol message has no oneof "%s" field.' % oneof_name) nested_field = self._oneofs.get(field, None) if nested_field is not None and self.HasField(nested_field.name): return nested_field.name else: return None cls.WhichOneof = WhichOneof def _Clear(self): # Clear fields. self._fields = {} self._unknown_fields = () # pylint: disable=protected-access if self._unknown_field_set is not None: self._unknown_field_set._clear() self._unknown_field_set = None self._oneofs = {} self._Modified() def _UnknownFields(self): if self._unknown_field_set is None: # pylint: disable=protected-access # pylint: disable=protected-access self._unknown_field_set = containers.UnknownFieldSet() return self._unknown_field_set # pylint: disable=protected-access def _DiscardUnknownFields(self): self._unknown_fields = [] self._unknown_field_set = None # pylint: disable=protected-access for field, value in self.ListFields(): if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: if _IsMapField(field): if _IsMessageMapField(field): for key in value: value[key].DiscardUnknownFields() elif field.label == _FieldDescriptor.LABEL_REPEATED: for sub_message in value: sub_message.DiscardUnknownFields() else: value.DiscardUnknownFields() def _SetListener(self, listener): if listener is None: self._listener = message_listener_mod.NullMessageListener() else: self._listener = listener def _AddMessageMethods(message_descriptor, cls): """Adds implementations of all Message methods to cls.""" _AddListFieldsMethod(message_descriptor, cls) _AddHasFieldMethod(message_descriptor, cls) _AddClearFieldMethod(message_descriptor, cls) if message_descriptor.is_extendable: _AddClearExtensionMethod(cls) _AddHasExtensionMethod(cls) _AddEqualsMethod(message_descriptor, cls) _AddStrMethod(message_descriptor, cls) _AddReprMethod(message_descriptor, cls) _AddUnicodeMethod(message_descriptor, cls) _AddByteSizeMethod(message_descriptor, cls) _AddSerializeToStringMethod(message_descriptor, cls) _AddSerializePartialToStringMethod(message_descriptor, cls) _AddMergeFromStringMethod(message_descriptor, cls) _AddIsInitializedMethod(message_descriptor, cls) _AddMergeFromMethod(cls) _AddWhichOneofMethod(message_descriptor, cls) # Adds methods which do not depend on cls. cls.Clear = _Clear cls.UnknownFields = _UnknownFields cls.DiscardUnknownFields = _DiscardUnknownFields cls._SetListener = _SetListener def _AddPrivateHelperMethods(message_descriptor, cls): """Adds implementation of private helper methods to cls.""" def Modified(self): """Sets the _cached_byte_size_dirty bit to true, and propagates this to our listener iff this was a state change. """ # Note: Some callers check _cached_byte_size_dirty before calling # _Modified() as an extra optimization. So, if this method is ever # changed such that it does stuff even when _cached_byte_size_dirty is # already true, the callers need to be updated. if not self._cached_byte_size_dirty: self._cached_byte_size_dirty = True self._listener_for_children.dirty = True self._is_present_in_parent = True self._listener.Modified() def _UpdateOneofState(self, field): """Sets field as the active field in its containing oneof. Will also delete currently active field in the oneof, if it is different from the argument. Does not mark the message as modified. """ other_field = self._oneofs.setdefault(field.containing_oneof, field) if other_field is not field: del self._fields[other_field] self._oneofs[field.containing_oneof] = field cls._Modified = Modified cls.SetInParent = Modified cls._UpdateOneofState = _UpdateOneofState class _Listener(object): """MessageListener implementation that a parent message registers with its child message. In order to support semantics like: foo.bar.baz.moo = 23 assert foo.HasField('bar') ...child objects must have back references to their parents. This helper class is at the heart of this support. """ def __init__(self, parent_message): """Args: parent_message: The message whose _Modified() method we should call when we receive Modified() messages. """ # This listener establishes a back reference from a child (contained) object # to its parent (containing) object. We make this a weak reference to avoid # creating cyclic garbage when the client finishes with the 'parent' object # in the tree. if isinstance(parent_message, weakref.ProxyType): self._parent_message_weakref = parent_message else: self._parent_message_weakref = weakref.proxy(parent_message) # As an optimization, we also indicate directly on the listener whether # or not the parent message is dirty. This way we can avoid traversing # up the tree in the common case. self.dirty = False def Modified(self): if self.dirty: return try: # Propagate the signal to our parents iff this is the first field set. self._parent_message_weakref._Modified() except ReferenceError: # We can get here if a client has kept a reference to a child object, # and is now setting a field on it, but the child's parent has been # garbage-collected. This is not an error. pass class _OneofListener(_Listener): """Special listener implementation for setting composite oneof fields.""" def __init__(self, parent_message, field): """Args: parent_message: The message whose _Modified() method we should call when we receive Modified() messages. field: The descriptor of the field being set in the parent message. """ super(_OneofListener, self).__init__(parent_message) self._field = field def Modified(self): """Also updates the state of the containing oneof in the parent message.""" try: self._parent_message_weakref._UpdateOneofState(self._field) super(_OneofListener, self).Modified() except ReferenceError: pass
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@protobuf@py3@google@protobuf@internal@python_message.py@.PATH_END.py
{ "filename": "mass_light_model.py", "repo_name": "aymgal/COOLEST", "repo_path": "COOLEST_extracted/COOLEST-main/coolest/template/classes/mass_light_model.py", "type": "Python" }
__author__ = 'aymgal' from typing import Tuple from coolest.template.classes.profile_list import ProfileList from coolest.template.classes.profiles import mass as mass_profiles_module from coolest.template.classes.profiles import light as light_profiles_module class MassModel(ProfileList): """Describes a mass model of a lensing entity as a list of (mass) profiles Parameters ---------- *profile_names : str Names of the mass profiles, following corresponding class names in the coolest.template.classes.profiles.mass submodule. """ def __init__(self, *profile_names: Tuple[str]) -> None: super().__init__(mass_profiles_module, *profile_names) class LightModel(ProfileList): """Describes a light model of a lensing entity as a list of (light) profiles Parameters ---------- *profile_names : str Names of the light profiles, following corresponding class names in the coolest.template.classes.profiles.light submodule. """ def __init__(self, *profile_names: Tuple[str]) -> None: super().__init__(light_profiles_module, *profile_names)
aymgalREPO_NAMECOOLESTPATH_START.@COOLEST_extracted@COOLEST-main@coolest@template@classes@mass_light_model.py@.PATH_END.py
{ "filename": "select.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/tornado/tornado-4/tornado/platform/select.py", "type": "Python" }
#!/usr/bin/env python # # Copyright 2012 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Select-based IOLoop implementation. Used as a fallback for systems that don't support epoll or kqueue. """ from __future__ import absolute_import, division, print_function import select from tornado.ioloop import IOLoop, PollIOLoop class _Select(object): """A simple, select()-based IOLoop implementation for non-Linux systems""" def __init__(self): self.read_fds = set() self.write_fds = set() self.error_fds = set() self.fd_sets = (self.read_fds, self.write_fds, self.error_fds) def close(self): pass def register(self, fd, events): if fd in self.read_fds or fd in self.write_fds or fd in self.error_fds: raise IOError("fd %s already registered" % fd) if events & IOLoop.READ: self.read_fds.add(fd) if events & IOLoop.WRITE: self.write_fds.add(fd) if events & IOLoop.ERROR: self.error_fds.add(fd) # Closed connections are reported as errors by epoll and kqueue, # but as zero-byte reads by select, so when errors are requested # we need to listen for both read and error. # self.read_fds.add(fd) def modify(self, fd, events): self.unregister(fd) self.register(fd, events) def unregister(self, fd): self.read_fds.discard(fd) self.write_fds.discard(fd) self.error_fds.discard(fd) def poll(self, timeout): readable, writeable, errors = select.select( self.read_fds, self.write_fds, self.error_fds, timeout) events = {} for fd in readable: events[fd] = events.get(fd, 0) | IOLoop.READ for fd in writeable: events[fd] = events.get(fd, 0) | IOLoop.WRITE for fd in errors: events[fd] = events.get(fd, 0) | IOLoop.ERROR return events.items() class SelectIOLoop(PollIOLoop): def initialize(self, **kwargs): super(SelectIOLoop, self).initialize(impl=_Select(), **kwargs)
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@tornado@tornado-4@tornado@platform@select.py@.PATH_END.py
{ "filename": "__main__.py", "repo_name": "astrom-tom/specstack", "repo_path": "specstack_extracted/specstack-master/specstack/__main__.py", "type": "Python" }
''' ######################################################## ##### # ##### specstack # ##### R.THOMAS # ##### 2019 # ##### Main # ##### # ######################################################## @License: GPL - see LICENCE.txt ''' ####Public General Libraries import os import sys ####third party from catscii import catscii import numpy ####local imports from . import cli from . import spec from . import plot def main(): ''' This function is the main of the catmatch. ''' try: ####get arguments from the command lien interface args = cli.CLI().arguments ###check normalisation limits lims = args.normlimits.split(',') lims = [float(lims[0]), float(lims[1])] if lims[0]>=lims[1]: print('\033[1m Normalisation limits error: l0>=l1, must be l0<l1! \033[0m') print('\033[1m Quitting... \033[0m') sys.exit() ###check if file exist if not os.path.isfile(args.speclist): print('\033[1m File %s not found \033[0m'%args.speclist) print('\033[1m Quitting... \033[0m') ##if everything is ready we start looking at the list of files ##we load the catalog catalog = catscii.load_cat(args.speclist, True) names = catalog.get_column('spec', str) redshift = catalog.get_column('redshift', float) ###we restframe all the files restframe = [] waves_0 = [] waves_f = [] allz = [] N = 0 for (i,j) in zip(names, redshift): if args.d: filespec = os.path.join(args.d, i) else: filespec = i if not os.path.isfile(filespec) and args.v is True: print('\033[1m Spectrum %s not found, skip \033[0m'%i) else: wave, flux = spec.restframe_normalised(filespec, j, lims[0], \ lims[1], args.SNR, args.v) allz.append(j) if wave != []: N += 1 restframe.append((wave, flux)) waves_0.append(wave[0]) waves_f.append(wave[-1]) ##define limits of the spectrum if not args.full: minw = max(waves_0) maxw = min(waves_f) else: minw = min(waves_0) maxw = max(waves_f) if args.v: print('\033[1m The stack spectrum will be computed between %.1f and %.1f \033[0m'%(minw, maxw)) print('\033[1m The stack spectrum will be computed from %s spectra \033[0m'%N) #print(allz) print('\033[1m The average redshift is %s \033[0m'%round(numpy.mean(allz),4)) grid = numpy.arange(minw, maxw, 1) ###and regrid all the spec rebinned = spec.regrid(restframe, grid) ##create stack stacked, std, ermean, N = spec.stack(rebinned, float(args.s)) ##and prod final_grid = numpy.arange(minw, maxw, float(args.bin)) final_stack = numpy.interp(final_grid, grid, stacked) final_std = numpy.interp(final_grid, grid, std) final_ermean = numpy.interp(final_grid, grid, ermean) final_N = numpy.interp(final_grid, grid, N) wave, flux = spec.renorm(final_grid, final_stack, 0, lims[0], lims[1], args.v) ##and save it numpy.savetxt(args.f, numpy.array([wave, flux, final_std, final_ermean, final_N]).T) ##eventually plot if args.p: plot.plot(final_grid, final_stack, final_std, final_ermean, rebinned, grid) except KeyboardInterrupt: print('quitting...') sys.exit()
astrom-tomREPO_NAMEspecstackPATH_START.@specstack_extracted@specstack-master@specstack@__main__.py@.PATH_END.py
{ "filename": "_memory.py", "repo_name": "crossbario/crossbar", "repo_path": "crossbar_extracted/crossbar-master/crossbar/edge/worker/monitor/_memory.py", "type": "Python" }
############################################################################## # # Crossbar.io # Copyright (C) Crossbar.io Technologies GmbH. All rights reserved. # ############################################################################## from twisted.internet.defer import succeed from autobahn.util import utcnow from crossbar.edge.worker.monitor._base import Monitor __all__ = ('MemoryMonitor', ) class MemoryMonitor(Monitor): """ RAM monitoring. """ ID = u'memory' def __init__(self, config=None): Monitor.__init__(self, config) def poll(self): """ Measure current stats value and return new stats. """ Monitor.poll(self) # create new, empty event # current = { # the UTC timestamp when measurement was taken u'timestamp': utcnow(), # the effective last period in secods u'last_period': self._last_period, } # FIXME: add ratio of ram usage with open("/proc/meminfo") as f: res = f.read() new = res.split() new_clean = [x.replace(":", "") for x in new if x != 'kB'] for i in range(0, len(new_clean), 2): k = u'{}'.format(new_clean[i]) current[k] = int(new_clean[i + 1]) self._last_value = current return succeed(self._last_value)
crossbarioREPO_NAMEcrossbarPATH_START.@crossbar_extracted@crossbar-master@crossbar@edge@worker@monitor@_memory.py@.PATH_END.py
{ "filename": "_sector.py", "repo_name": "plotly/plotly.py", "repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/validators/layout/polar/_sector.py", "type": "Python" }
import _plotly_utils.basevalidators class SectorValidator(_plotly_utils.basevalidators.InfoArrayValidator): def __init__(self, plotly_name="sector", parent_name="layout.polar", **kwargs): super(SectorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "plot"), items=kwargs.pop( "items", [ {"editType": "plot", "valType": "number"}, {"editType": "plot", "valType": "number"}, ], ), **kwargs, )
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@validators@layout@polar@_sector.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "jroulet/cogwheel", "repo_path": "cogwheel_extracted/cogwheel-main/cogwheel/tests/__init__.py", "type": "Python" }
jrouletREPO_NAMEcogwheelPATH_START.@cogwheel_extracted@cogwheel-main@cogwheel@tests@__init__.py@.PATH_END.py
{ "filename": "paper.md", "repo_name": "MartianColonist/POSEIDON", "repo_path": "POSEIDON_extracted/POSEIDON-main/joss/paper.md", "type": "Markdown" }
--- title: '`POSEIDON`: A Multidimensional Atmospheric Retrieval Code for Exoplanet Spectra' tags: - Python - astronomy - exoplanets - spectroscopy - atmospheric retrieval - atmospheric models - JWST authors: - name: Ryan J. MacDonald orcid: 0000-0003-4816-3469 affiliation: "1, 2, 3" affiliations: - name: Department of Astronomy, University of Michigan, 1085 S. University Ave., Ann Arbor, MI 48109, USA index: 1 - name: NHFP Sagan Fellow index: 2 - name: Department of Astronomy and Carl Sagan Institute, Cornell University, 122 Sciences Drive, Ithaca, NY 14853, USA index: 3 date: 04 January 2023 bibliography: paper.bib aas-doi: 10.3847/1538-4357/ac47fe aas-journal: Astrophysical Journal --- # Summary Exoplanet atmospheres are a dynamic and fast-changing field at the frontier of modern astronomy. Telescope observations can reveal the chemical composition, temperature, cloud properties, and (potentially) the habitability of these remote worlds. Astronomers can measure these atmospheric properties by observing how the fraction of starlight blocked by a planet passing in front of its host star changes with wavelength --- a technique called transmission spectroscopy. Since the wavelengths where different atoms and molecules absorb are already known (from laboratory measurements or quantum mechanics), astronomers can compare models of exoplanet spectra to observations to infer the chemical composition of exoplanets. `POSEIDON` is a Python package for the modelling and analysis of exoplanet spectra. `POSEIDON` has two main functions: (i) computation of model spectra for 1D, 2D, or 3D exoplanet atmospheres; and (ii) a Bayesian fitting routine (`atmospheric retrieval') that can infer the range of atmospheric properties consistent with an observed exoplanet spectrum. # Exoplanet Modelling and Atmospheric Retrieval with `POSEIDON` The first major use case for `POSEIDON` is 'forward modelling' --- illustrated on the left of \autoref{fig:POSEIDON_architecture}. A user can generate a model planet spectrum, for a given star-planet system, by providing a specific set of atmospheric properties (e.g. the chemical composition and temperature). The forward model mode allows users to explore how atmospheric properties alter an exoplanet spectrum and to produce predicted model spectra for observing proposals. The required input files (pre-computed stellar grids and an opacity database) are available to download from an online repository (linked in the documentation). The second major use case for `POSEIDON` is atmospheric retrieval --- illustrated on the right of \autoref{fig:POSEIDON_architecture}. To initialise a retrieval, a user provides an observed exoplanet spectrum and the range of atmospheric properties to be explored (i.e. the prior ranges for a set of free parameters defining a model). A Bayesian statistical sampling algorithm --- nominally [`PyMultiNest`](https://github.com/JohannesBuchner/PyMultiNest) [@Buchner:2014] --- then repeatedly calls the forward model, comparing the generated spectrum to the observations, until the parameter space is fully explored and a convergence criteria reached. The main outputs of an atmospheric retrieval are the posterior probability distributions of the model parameters and the model's Bayesian evidence. The Bayesian evidences from multiple retrievals, in turn, can be subsequently compared to compute a detection significance for each model component (e.g. the statistical confidence for a molecule being present in the planetary atmosphere). ![Schematic architecture of the `POSEIDON` atmospheric retrieval code. Users can call `POSEIDON` in two main ways: (i) to generate a model exoplanet spectrum for a specified planet atmosphere (green arrows); or (ii) to fit an observed exoplanet spectrum by statistical sampling of a model's atmospheric properties (purple arrows). The diagram highlights code inputs (circles), algorithm steps (rectangles), and code outputs (bottom green or purple boxes). \label{fig:POSEIDON_architecture}](figures/POSEIDON_Architecture_2022){width=100%} `POSEIDON` was first described in the exoplanet literature by [@MacDonald:2017]. Since then, the code has been used in 17 peer-reviewed publications [e.g., @Alam:2021; @Sedaghati:2017; @Kaltenegger:2020]. Most recently, a detailed description of `POSEIDON`'s new multidimensional forward model, `TRIDENT`, was provided by [@MacDonald:2022]. # Statement of Need Recent years have seen a substantial improvement in the number of high-quality exoplanet spectra. In particular, the newly operational JWST and a profusion of high-resolution ground-based spectrographs offer an abundance of exoplanet data. The accurate interpretation of such data requires a retrieval code that can rapidly explore complex parameter spaces describing a rich variety of atmospheric phenomena. `POSEIDON` provides the capability to model and retrieve transmission spectra of planets with inhomogeneous temperatures, compositions, and cloud properties (i.e. 2D or 3D models). Several studies have highlighted that not including these multidimensional effects can bias retrieval inferences [e.g., @Caldas:2019; @Line:2016; @MacDonald:2020; @Pluriel:2022]. However, existing open-source exoplanet retrieval codes assume 1D atmospheres for computational efficiency. `POSEIDON`, therefore, offers an open-source implementation of state-of-the-art multidimensional retrieval methods [see @MacDonald:2022 and MacDonald & Lewis, in prep.] to aid the interpretation of high-quality exoplanet spectra. In a 1D configuration, `POSEIDON` compares well with other retrieval codes. When applied to Hubble Space Telescope observations, `POSEIDON` produces consistent retrieval results with the ATMO and NEMESIS retrieval codes [@Lewis:2020; @Rathcke:2021]. Recently, [@Barstow:2022] presented a comparison of five exoplanet retrieval codes, including `POSEIDON`, which demonstrated good agreement on simulated Ariel [@Tinetti:2020] transmission spectra. `POSEIDON` also offers exceptional computational performance: a single 1D forward model over a wavelength range sufficient for JWST analyses takes 70 ms [see @MacDonald:2022, Appendix D], while publication-quality 1D retrievals typically take an hour or less. `POSEIDON` also supports multi-core retrievals via `PyMultiNest`'s MPI implementation, which achieves a roughly linear speed-up in the number of cores. Therefore, `POSEIDON` allows users to readily explore 1D retrievals on personal laptops while scaling up to multidimensional retrievals on modest clusters. # Future Developments `POSEIDON` v1.0 officially supports the modelling and retrieval of exoplanet transmission spectra in 1D, 2D, and 3D. The initial release also includes a beta version of thermal emission spectra modelling and retrieval (for cloud-free, 1D atmospheres, with no scattering), which will be developed further in future releases. Suggestions for additional features are more than welcome. # Documentation Documentation for `POSEIDON`, with step-by-step tutorials illustrating research applications, is available at [https://poseidon-retrievals.readthedocs.io/en/latest/](https://poseidon-retrievals.readthedocs.io/en/latest/). # Similar Tools The following exoplanet retrieval codes are open source: [`PLATON`](https://github.com/ideasrule/platon) [@Zhang:2019; @Zhang:2020], [`petitRADTRANS`](https://gitlab.com/mauricemolli/petitRADTRANS) [@Molliere:2019], [`CHIMERA`](https://github.com/mrline/CHIMERA) [@Line:2013], [`TauRex`](https://github.com/ucl-exoplanets/TauREx3_public) [@Waldmann:2015; @Al-Refaie:2021], [`NEMESIS`](https://github.com/nemesiscode/radtrancode) [@Irwin:2008] [`Pyrat Bay`](https://github.com/pcubillos/pyratbay) [@Cubillos:2021], and [`BART`](https://github.com/exosports/BART) [@Harrington:2022] # Acknowledgements RJM expresses gratitude to the developers of many open source Python packages used by `POSEIDON`, in particular `Numba` [@Lam:2015], `numpy` [@Harris:2020], `Matplotlib` [@Hunter:2007], `SciPy` [@Virtanen:2020], and `Spectres` [@Carnall:2017]. RJM acknowledges financial support from the UK's Science and Technology Facilities Council (STFC) during the early development of `POSEIDON` and support from NASA Grant 80NSSC20K0586 issued through the James Webb Space Telescope Guaranteed Time Observer Program. Most recently, RJM acknowledges support from NASA through the NASA Hubble Fellowship grant HST-HF2-51513.001 awarded by the Space Telescope Science Institute, which is operated by the Association of Universities for Research in Astronomy, Inc., for NASA, under contract NAS5-26555. RJM is especially grateful to Lorenzo Mugnai and Michael Zhang for excellent and helpful referee reports, and to the editor, Dan Foreman-Mackey, for his tireless efforts to encourage new people to join the open source community in astronomy. RJM thanks Nikole Lewis, Ishan Mishra, Jonathan Gomez Barrientos, John Kappelmeier, Antonia Peters, Kath Landgren, and Ruizhe Wang for helpful discussions. # References
MartianColonistREPO_NAMEPOSEIDONPATH_START.@POSEIDON_extracted@POSEIDON-main@joss@paper.md@.PATH_END.py
{ "filename": "QSO_templates.ipynb", "repo_name": "desihub/desisim", "repo_path": "desisim_extracted/desisim-main/doc/nb/QSO_templates.ipynb", "type": "Jupyter Notebook" }
# Simple tests for QSO templates A simple notebook that plays around with the templates.QSO Class. ```python import numpy as np import warnings import matplotlib.pyplot as plt from matplotlib.patches import Polygon from desisim.templates import QSO %pylab inline ``` Populating the interactive namespace from numpy and matplotlib ```python seed = 123 nmodel = 10 ``` ```python qso = QSO(minwave=3000, maxwave=5e4) ``` ### Make templates with and without the fast Lyman-alpha forest. ```python flux, wave, meta = qso.make_templates(nmodel=nmodel, zrange=(2.0, 4.0), seed=seed, nocolorcuts=True, lyaforest=False) ``` ```python flux_forest, _, meta_forest = qso.make_templates(nmodel=nmodel, zrange=(2.0, 4.0), seed=seed, nocolorcuts=True, lyaforest=True) ``` ```python meta ``` &lt;Table length=10&gt; <table id="table4596646240" class="table-striped table-bordered table-condensed"> <thead><tr><th>OBJTYPE</th><th>SUBTYPE</th><th>TEMPLATEID</th><th>SEED</th><th>REDSHIFT</th><th>MAG</th><th>DECAM_FLUX [6]</th><th>WISE_FLUX [2]</th><th>OIIFLUX</th><th>HBETAFLUX</th><th>EWOII</th><th>EWHBETA</th><th>D4000</th><th>VDISP</th><th>OIIDOUBLET</th><th>OIIIHBETA</th><th>OIIHBETA</th><th>NIIHBETA</th><th>SIIHBETA</th><th>ZMETAL</th><th>AGE</th><th>TEFF</th><th>LOGG</th><th>FEH</th></tr></thead> <thead><tr><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th>erg / (cm2 s)</th><th>erg / (cm2 s)</th><th>Angstrom</th><th>Angstrom</th><th></th><th>km / s</th><th></th><th>dex</th><th>dex</th><th>dex</th><th>dex</th><th></th><th>Gyr</th><th>K</th><th>m / s2</th><th></th></tr></thead> <thead><tr><th>str10</th><th>str10</th><th>int64</th><th>int64</th><th>float64</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th></tr></thead> <tr><td>QSO</td><td></td><td>0</td><td>2991312382</td><td>2.84621292025</td><td>21.845</td><td>1.13045 .. 1.93474</td><td>3.5364 .. 25.9223</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td></tr> <tr><td>QSO</td><td></td><td>1</td><td>3062119789</td><td>3.96152839677</td><td>20.4562</td><td>0.0979406 .. 8.01999</td><td>32.9949 .. 54.5157</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td></tr> <tr><td>QSO</td><td></td><td>2</td><td>1228959102</td><td>3.36965947717</td><td>20.4386</td><td>2.50919 .. 6.38044</td><td>5.58704 .. 33.0771</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td></tr> <tr><td>QSO</td><td></td><td>3</td><td>1840268610</td><td>2.96186380297</td><td>21.3289</td><td>1.82292 .. 3.17554</td><td>3.74577 .. 40.9519</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td></tr> <tr><td>QSO</td><td></td><td>4</td><td>974319580</td><td>2.78423503639</td><td>21.3296</td><td>1.84122 .. 2.86704</td><td>4.0844 .. 40.5941</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td></tr> <tr><td>QSO</td><td></td><td>5</td><td>2967327842</td><td>2.6863560323</td><td>21.586</td><td>1.62835 .. 3.14194</td><td>7.27288 .. 37.9606</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td></tr> <tr><td>QSO</td><td></td><td>6</td><td>2367878886</td><td>3.45809941477</td><td>22.1236</td><td>0.122572 .. 1.64596</td><td>7.81299 .. 15.1341</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td></tr> <tr><td>QSO</td><td></td><td>7</td><td>3088727057</td><td>2.87714448936</td><td>21.8111</td><td>0.928251 .. 2.73436</td><td>14.4657 .. 32.5649</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td></tr> <tr><td>QSO</td><td></td><td>8</td><td>3090095699</td><td>2.11935579322</td><td>21.5276</td><td>3.99881 .. 2.33989</td><td>52.4078 .. 131.512</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td></tr> <tr><td>QSO</td><td></td><td>9</td><td>2109339754</td><td>2.79608851066</td><td>21.8061</td><td>1.15508 .. 2.3601</td><td>7.46708 .. 35.2731</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td></tr> </table> ```python meta_forest ``` &lt;Table length=10&gt; <table id="table4664395312" class="table-striped table-bordered table-condensed"> <thead><tr><th>OBJTYPE</th><th>SUBTYPE</th><th>TEMPLATEID</th><th>SEED</th><th>REDSHIFT</th><th>MAG</th><th>DECAM_FLUX [6]</th><th>WISE_FLUX [2]</th><th>OIIFLUX</th><th>HBETAFLUX</th><th>EWOII</th><th>EWHBETA</th><th>D4000</th><th>VDISP</th><th>OIIDOUBLET</th><th>OIIIHBETA</th><th>OIIHBETA</th><th>NIIHBETA</th><th>SIIHBETA</th><th>ZMETAL</th><th>AGE</th><th>TEFF</th><th>LOGG</th><th>FEH</th></tr></thead> <thead><tr><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th>erg / (cm2 s)</th><th>erg / (cm2 s)</th><th>Angstrom</th><th>Angstrom</th><th></th><th>km / s</th><th></th><th>dex</th><th>dex</th><th>dex</th><th>dex</th><th></th><th>Gyr</th><th>K</th><th>m / s2</th><th></th></tr></thead> <thead><tr><th>str10</th><th>str10</th><th>int64</th><th>int64</th><th>float64</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th><th>float32</th></tr></thead> <tr><td>QSO</td><td>LYA</td><td>0</td><td>2991312382</td><td>2.84621292025</td><td>21.845</td><td>1.02201 .. 1.93465</td><td>3.53665 .. 25.8862</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td></tr> <tr><td>QSO</td><td>LYA</td><td>1</td><td>3062119789</td><td>3.96152839677</td><td>20.4562</td><td>0.0970256 .. 8.70275</td><td>35.8276 .. 59.1432</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td></tr> <tr><td>QSO</td><td>LYA</td><td>2</td><td>1228959102</td><td>3.36965947717</td><td>20.4386</td><td>2.22059 .. 6.37821</td><td>5.58765 .. 32.5178</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td></tr> <tr><td>QSO</td><td>LYA</td><td>3</td><td>1840268610</td><td>2.96186380297</td><td>21.3289</td><td>1.62206 .. 3.17528</td><td>3.7461 .. 40.7308</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td></tr> <tr><td>QSO</td><td>LYA</td><td>4</td><td>974319580</td><td>2.78423503639</td><td>21.3296</td><td>1.68465 .. 2.8669</td><td>4.08463 .. 40.5309</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td></tr> <tr><td>QSO</td><td>LYA</td><td>5</td><td>2967327842</td><td>2.6863560323</td><td>21.586</td><td>1.4656 .. 3.14187</td><td>7.2734 .. 37.9339</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td></tr> <tr><td>QSO</td><td>LYA</td><td>6</td><td>2367878886</td><td>3.45809941477</td><td>22.1236</td><td>0.104318 .. 1.64566</td><td>7.81413 .. 14.92</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td></tr> <tr><td>QSO</td><td>LYA</td><td>7</td><td>3088727057</td><td>2.87714448936</td><td>21.8111</td><td>0.816304 .. 2.73433</td><td>14.4665 .. 31.7727</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td></tr> <tr><td>QSO</td><td>LYA</td><td>8</td><td>3090095699</td><td>2.11935579322</td><td>21.5276</td><td>3.83194 .. 2.33984</td><td>52.3716 .. 131.417</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td></tr> <tr><td>QSO</td><td>LYA</td><td>9</td><td>2109339754</td><td>2.79608851066</td><td>21.8061</td><td>1.01241 .. 2.36004</td><td>7.46744 .. 28.6596</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td><td>-1.0</td></tr> </table> ### Show the forest ```python for ii in range(nmodel): plt.plot(wave, flux_forest[ii, :]) plt.plot(wave, flux[ii, :]) plt.xlim(3000, 6300) plt.show() ``` ![png](output_10_0.png) ![png](output_10_1.png) ![png](output_10_2.png) ![png](output_10_3.png) ![png](output_10_4.png) ![png](output_10_5.png) ![png](output_10_6.png) ![png](output_10_7.png) ![png](output_10_8.png) ![png](output_10_9.png) ### Show the effect of extrapolation ```python for ii in range(nmodel): plt.plot(wave, flux[ii, :]) #plt.xlim(3000, 200) plt.xscale('log') plt.show() ``` ![png](output_12_0.png) ![png](output_12_1.png) ![png](output_12_2.png) ![png](output_12_3.png) ![png](output_12_4.png) ![png](output_12_5.png) ![png](output_12_6.png) ![png](output_12_7.png) ![png](output_12_8.png) ![png](output_12_9.png) ### Look at the color-cuts. ```python flux1, _, meta1 = qso.make_templates(nmodel=100, seed=1, lyaforest=True, nocolorcuts=True) flux2, _, meta2 = qso.make_templates(nmodel=100, seed=1, lyaforest=True, nocolorcuts=False) ``` WARNING:templates.py:1914:make_templates: 2 spectra could not be computed given the input priors! WARNING:templates.py:1914:make_templates: 2 spectra could not be computed given the input priors! ```python fail = np.where(np.sum(flux2, axis=1) == 0)[0] fail ``` array([], dtype=int64) ```python def qso_colorbox(ax, plottype='grz'): """Draw the QSO selection boxes.""" rmaglim = 22.7 xlim = ax.get_xlim() ylim = ax.get_ylim() if plottype == 'grz-r': verts = [(xlim[0]-0.05, 17.0), (22.7, 17.0), (22.7, ylim[1]+0.05), (xlim[0]-0.05, ylim[1]+0.05) ] if plottype == 'rW1-rz': verts = None ax.axvline(x=-0.3, ls='--', color='k') ax.axvline(x=1.3, ls='--', color='k') if plottype == 'gr-rz': verts = [(-0.3, 1.3), (1.1, 1.3), (1.1, ylim[0]-0.05), (-0.3, ylim[0]-0.05) ] if verts: ax.add_patch(Polygon(verts, fill=False, ls='--', color='k')) ``` ```python def flux2colors(cat): """Convert DECam/WISE fluxes to magnitudes and colors.""" colors = dict() with warnings.catch_warnings(): # ignore missing fluxes (e.g., for QSOs) warnings.simplefilter('ignore') for ii, band in zip((1, 2, 4), ('g', 'r', 'z')): colors[band] = 22.5 - 2.5 * np.log10(cat['DECAM_FLUX'][..., ii].data) colors['grz'] = 22.5-2.5*np.log10((cat['DECAM_FLUX'][..., 1] + 0.8 * cat['DECAM_FLUX'][..., 2] + 0.5 * cat['DECAM_FLUX'][..., 4]).data / 2.3) colors['gr'] = colors['g'] - colors['r'] colors['rz'] = colors['r'] - colors['z'] return colors ``` ```python nocuts = flux2colors(meta1) cuts = flux2colors(meta2) ``` ```python fig, ax = plt.subplots() ax.scatter(nocuts['rz'], nocuts['gr'], s=14, label='No Color-cuts') ax.scatter(cuts['rz'], cuts['gr'], s=14, marker='s', alpha=0.7, label='With Color-cuts') ax.set_xlabel('$r - z$') ax.set_ylabel('$g - r$') ax.set_xlim(-1, 2.2) ax.set_ylim(-1, 2.0) ax.legend(loc='upper right') qso_colorbox(ax, 'gr-rz') ``` ![png](output_19_0.png) ```python ```
desihubREPO_NAMEdesisimPATH_START.@desisim_extracted@desisim-main@doc@nb@QSO_templates.ipynb@.PATH_END.py
{ "filename": "test_averaging.py", "repo_name": "HERA-Team/hera_cal", "repo_path": "hera_cal_extracted/hera_cal-main/hera_cal/lst_stack/tests/test_averaging.py", "type": "Python" }
import numpy as np import pytest from .. import averaging as avg from ...tests import mock_uvdata as mockuvd from hera_cal.lst_stack import LSTStack from hera_filters.dspec import dpss_operator from functools import partial from astropy import units as un class TestGetMaskedData: def setup_class(self): self.shape = (2, 3, 4, 5) self.data = np.ones(self.shape, dtype=complex) self.data_with_nans = self.data.copy() self.data_with_nans[0, 0, 0, 0] = np.nan self.nsamples = np.ones(self.shape, dtype=float) self.nsamples_with_negatives = self.nsamples.copy() self.nsamples_with_negatives[0, 0, 0, 0] = -1 self.noflags = np.zeros(self.shape, dtype=bool) self.flags = np.zeros_like(self.noflags) self.flags[0, 0, 0, 0] = True self.ten_flags = np.zeros_like(self.noflags) self.ten_flags[0, 0, [1, 2], :] = True def test_equality_for_different_modes_when_no_flags(self): d, f, n = avg.get_masked_data( self.data, self.noflags, self.nsamples, inpainted_mode=False ) di, fi, ni = avg.get_masked_data( self.data, self.noflags, self.nsamples, inpainted_mode=True ) assert np.all(d == di) assert np.all(f == fi) assert np.all(n == ni) def test_inpainted_data_gets_counted_in_inpainted_mode(self): d, f, n = avg.get_masked_data( self.data, self.noflags, self.nsamples_with_negatives, inpainted_mode=True ) assert np.all(n.mask == d.mask) # always true # the mask of data/nsamples is what tells the averager what to include # in the mean, so nothing should be flagged here (since there are no # non-inpainted flags). assert not np.any(n.mask) # however, the output flags array tells us what to include in the final # tallied nsamples, so it should have some flags (the 'inpainted' ones) assert np.sum(f) == 1 def test_inpainted_data_not_counted_in_direct_mode(self): d, f, n = avg.get_masked_data( self.data, self.noflags, self.nsamples_with_negatives, inpainted_mode=False ) assert np.all(n.mask == d.mask) assert np.all(n.mask == f) assert np.sum(f) == 1 @pytest.mark.parametrize("inpaint", (True, False)) def test_inpainted_data_with_nans(self, inpaint): # If there are nans, we can never count that data, even if it is # supposedly inpainted and unflagged d, f, n = avg.get_masked_data( self.data_with_nans, self.noflags, self.nsamples_with_negatives, inpainted_mode=inpaint, ) assert np.all(n.mask == d.mask) assert np.all(n.mask == f) assert np.sum(f) == 1 @pytest.mark.parametrize("inpaint", (True, False)) def test_inpainted_and_flagged(self, inpaint): # This shouldn't ever happen, but if data is marked as flagged, and # has negative nsamples, even though it is inpainted it should be counted # as flagged (as if it is re-flagged even after inpainting, suggesting that # the inpainting was not successful). d, f, n = avg.get_masked_data( self.data, self.flags, self.nsamples_with_negatives, inpainted_mode=inpaint ) assert np.all(n.mask == d.mask) assert np.all(n.mask == f) assert np.sum(f) == 1 @pytest.mark.parametrize("inpaint", (True, False)) def test_flagged_and_not_inpainted(self, inpaint): d, f, n = avg.get_masked_data( self.data, self.ten_flags, self.nsamples, inpainted_mode=inpaint ) assert np.all(n.mask == d.mask) assert np.all(n.mask == f) assert np.sum(f) == 10 class TestLSTAverage: def setup_class(self): self.shape = (2, 3, 4, 5) rng = np.random.default_rng(42) self.data = ( rng.standard_normal(self.shape) + rng.standard_normal(self.shape) * 1j ) self.data_with_nans = self.data.copy() self.data_with_nans[0, 0, 0, 0] = np.nan self.nsamples = np.ones(self.shape, dtype=float) self.nsamples_with_negatives = self.nsamples.copy() self.nsamples_with_negatives[0, 0, 0, 0] = -1 self.nsamples_full_input = np.ones(self.shape, dtype=float) self.nsamples_full_input[:, 0, 0, 0] = -1 self.noflags = np.zeros(self.shape, dtype=bool) self.flags = np.zeros_like(self.noflags) self.flags[0, 0, 0, 0] = True self.all_flags = np.zeros_like(self.noflags) self.all_flags[:, 0, 0, 0] = True def test_average_repeated(self): shape = (7, 8, 9) _data = np.random.random(shape) + np.random.random(shape) * 1j data = np.array([_data, _data, _data]) nsamples = np.ones_like(data) flags = np.zeros_like(data, dtype=bool) _d, _f, _n = avg.get_masked_data(data, flags, nsamples, inpainted_mode=False) data_n, flg_n, std_n, norm_n, db = avg.lst_average(_d, _n, _f) assert np.allclose(data_n, _data) assert not np.any(flg_n) assert np.allclose(std_n, 0.0) assert np.allclose(norm_n, 3.0) # Now flag the last "night" flags[-1] = True _d, _f, _n = avg.get_masked_data(data, flags, nsamples, inpainted_mode=False) data_n, flg_n, std_n, norm_n, db = avg.lst_average(_d, _n, _f) assert np.allclose(data_n, _data) assert not np.any(flg_n) assert np.allclose(std_n, 0.0) assert np.allclose(norm_n, 2.0) def test_std_simple(self): shape = (5000, 1, 2, 2) # 1000 nights, doesn't matter what the other axis is. std = 2.0 data = ( np.random.normal(scale=std, size=shape) + np.random.normal(scale=std, size=shape) * 1j ) nsamples = np.ones_like(data, dtype=float) flags = np.zeros_like(data, dtype=bool) _d, _f, _n = avg.get_masked_data(data, flags, nsamples, inpainted_mode=False) data_n, flg_n, std_n, norm_n, db = avg.lst_average(_d, _n, _f) # Check the averaged data is within 6 sigma of the population mean np.testing.assert_allclose(data_n, 0.0, atol=std * 6 / np.sqrt(shape[0])) # Check the standard deviation is within 20% of the true value np.testing.assert_allclose(std_n, std + std * 1j, rtol=0.2) assert not np.any(flg_n) @pytest.mark.parametrize("nsamples", ("ones", "random")) @pytest.mark.parametrize("flags", ("zeros", "random")) def test_std(self, nsamples, flags): shape = (5000, 1, 10, 2) # 1000 nights, doesn't matter what the other axis is. std = 2.0 if nsamples == "ones": warn = False nsamples = np.ones(shape) else: warn = True rng = np.random.default_rng(42) nsamples = rng.integers(1, 10, size=shape).astype(float) std = std / np.sqrt(nsamples) if flags == "zeros": flags = np.zeros(shape, dtype=bool) else: flags = np.random.random(shape) > 0.1 data = np.random.normal(scale=std) + np.random.normal(scale=std) * 1j flags = np.zeros(data.shape, dtype=bool) _d, _f, _n = avg.get_masked_data(data, flags, nsamples, inpainted_mode=False) if warn: with pytest.warns( UserWarning, match="Nsamples is not uniform across frequency" ): data_n, flg_n, std_n, _, _ = avg.lst_average(_d, _n, _f) else: data_n, flg_n, std_n, _, _ = avg.lst_average(_d, _n, _f) # Check the averaged data is within 6 sigma of the population mean assert np.allclose(data_n, 0.0, atol=std * 6 / np.sqrt(shape[0])) # In reality the std is infinity where flags is True std[flags] = np.inf w = 1 / np.sum(1.0 / std**2, axis=0) sample_var_expectation = sve = w * (shape[0] - 1) # Check the standard deviation is within 20% of the true value np.testing.assert_allclose(std_n, np.sqrt(sve) + np.sqrt(sve) * 1j, rtol=0.2) assert not np.any(flg_n) @pytest.mark.filterwarnings("ignore:invalid value encountered") @pytest.mark.parametrize("with_flags", (True, False)) def test_inpaint_mode_does_nothing_for_unpainted(self, with_flags: bool): # This tests that if there is nothing inpainted (i.e. nsamples is all non-negative), # then inpainted mode changes nothing -- whether we're flagging data or not. if with_flags: flg = self.flags else: flg = self.noflags # First test -- no flags should mean inpainted_mode does nothing. _d, _f, _n = avg.get_masked_data( self.data, flg, self.nsamples, inpainted_mode=False ) df, ff, stdf, nf, dbf = avg.lst_average(data=_d, nsamples=_n, flags=_f) _d, _f, _n = avg.get_masked_data( self.data, flg, self.nsamples, inpainted_mode=True ) di, fi, stdi, ni, dbi = avg.lst_average(data=_d, nsamples=_n, flags=_f) np.testing.assert_allclose(df, di) np.testing.assert_allclose(ff, fi) np.testing.assert_allclose(stdf, stdi) np.testing.assert_allclose(nf, ni) np.testing.assert_allclose(dbf, dbi) @pytest.mark.filterwarnings("ignore:invalid value encountered") def test_inpainted_data_differences_between_modes(self): # This one tests that if we have flagged but inpainted data, then inpainted # mode makes a difference. Nsamples with negatives implies inpainting, and # we use "noflags" because lst_average assumes that anything that we want to use # that's inpainted will have been unflagged. _d, _f, _n = avg.get_masked_data( self.data, self.noflags, self.nsamples_with_negatives, inpainted_mode=False ) df, ff, stdf, nf, dbf = avg.lst_average(_d, _n, _f) _d, _f, _n = avg.get_masked_data( self.data, self.noflags, self.nsamples_with_negatives, inpainted_mode=True ) di, fi, stdi, ni, dbi = avg.lst_average(_d, _n, _f) # The data and std in the fully-flagged bin should be different, but # Nsamples, Flags and Days Binned should be the same. # Flags are the same because the whole bin is not flagged -- just one night. assert not np.allclose(df.flatten()[0], di.flatten()[0]) np.testing.assert_allclose(df.flatten()[1:], di.flatten()[1:]) assert not np.allclose(stdf.flatten()[0], stdi.flatten()[0]) np.testing.assert_allclose(stdf.flatten()[1:], stdi.flatten()[1:]) np.testing.assert_allclose(ff, fi) np.testing.assert_allclose(nf, ni) np.testing.assert_allclose(dbf, dbi) @pytest.mark.filterwarnings("ignore:invalid value encountered") def test_fullbin_inpaint_differences_between_modes(self): # This one tests that if we have flagged but inpainted data, then inpainted # mode makes a difference. Nsamples with negatives implies inpainting, and # we use "noflags" because lst_average assumes that anything that we want to use # that's inpainted will have been unflagged. _d, _f, _n = avg.get_masked_data( self.data, self.noflags, self.nsamples_full_input, inpainted_mode=False ) df, ff, stdf, nf, dbf = avg.lst_average(_d, _n, _f) _d, _f, _n = avg.get_masked_data( self.data, self.noflags, self.nsamples_full_input, inpainted_mode=True ) di, fi, stdi, ni, dbi = avg.lst_average(_d, _n, _f) # The data, flags and std in the fully-flagged bin should be different, but # Nsamples, and Days Binned should be the same (zero). # Flags are NOT the same because the whole bin is flagged assert not np.allclose(df.flatten()[0], di.flatten()[0]) np.testing.assert_allclose(df.flatten()[1:], di.flatten()[1:]) assert not np.allclose(ff.flatten()[0], fi.flatten()[0]) np.testing.assert_allclose(ff.flatten()[1:], fi.flatten()[1:]) # assert not np.allclose(stdf.flatten()[0], stdi.flatten()[0]) assert not np.isfinite(stdf.flatten()[0]) assert not np.isfinite(stdi.flatten()[0]) np.testing.assert_allclose(stdf.flatten()[1:], stdi.flatten()[1:]) np.testing.assert_allclose(nf, ni) np.testing.assert_allclose(dbf, dbi) assert nf[0, 0, 0] == 0 assert dbf[0, 0, 0] == 0 def test_get_std(): data = np.linspace(0, 10, 3 * 4 * 5).reshape(3, 4, 5) nsamples = np.ones_like(data) flags = np.zeros_like(data, dtype=bool) flags[0, 0, 0] = True _d, _f, _n = avg.get_masked_data(data, flags, nsamples, inpainted_mode=False) mean = np.mean(_d, axis=0) std = avg.compute_std(_d, _n, mean=mean)[0] std2 = avg.compute_std(_d, _n)[0] assert np.all(std == std2) class TestReduceLSTBins: @classmethod def get_input_data( cls, nfreqs: int = 3, npols: int = 1, nbls: int = 6, ntimes: int = 4, ): data = np.random.random((nbls, nfreqs, npols)) # Make len(ntimes) LST bins, each with ntimes[i] time-entries, all the same # data. data = np.array([data] * ntimes) flags = np.zeros(data.shape, dtype=bool) nsamples = np.ones(data.shape, dtype=float) return data, flags, nsamples def test_one_point_per_bin(self): d, f, n = self.get_input_data(ntimes=1) rdc = avg.reduce_lst_bins(data=d, flags=f, nsamples=n) assert ( rdc["data"].shape == rdc["flags"].shape == rdc["std"].shape == rdc["nsamples"].shape ) np.testing.assert_allclose(rdc["data"], d[0]) assert not np.any(rdc["flags"]) np.testing.assert_allclose(rdc["nsamples"], 1.0) @pytest.mark.filterwarnings("ignore:invalid value encountered") def test_zerosize_bin(self): d, f, n = self.get_input_data(ntimes=0) rdc = avg.reduce_lst_bins(data=d, flags=f, nsamples=n, get_mad=True) assert np.all(np.isnan(rdc["data"])) assert np.all(rdc["flags"]) assert np.all(rdc["nsamples"] == 0.0) assert np.all(np.isinf(rdc["mad"])) assert np.all(np.isnan(rdc["median"])) def test_multi_points_per_bin_flagged(self): d, f, n = self.get_input_data(ntimes=4) f[2:] = True d[2:] = 1000.0 rdc = avg.reduce_lst_bins(data=d, flags=f, nsamples=n) assert ( rdc["data"].shape == rdc["flags"].shape == rdc["std"].shape == rdc["nsamples"].shape ) np.testing.assert_allclose(rdc["data"], d[0]) assert not np.any(rdc["flags"]) np.testing.assert_allclose(rdc["nsamples"], 2.0) def test_get_med_mad(self): d, f, n = self.get_input_data(ntimes=4) rdc = avg.reduce_lst_bins(data=d, flags=f, nsamples=n, get_mad=True) assert np.all(rdc["median"] == rdc["data"]) def test_bad_input(self): d, f, n = self.get_input_data(ntimes=4) with pytest.raises( ValueError, match="data, flags, and nsamples must all be provided" ): avg.reduce_lst_bins(data=d, flags=f) class TestAverageInpaintSimultaneouslySingleBl: """ Testing at a single-bl level makes it easier to test more cases, so we use this class to do a bunch of precision tests. """ def setup_class(self): self.rng = np.random.default_rng(42) def create_data( self, nnights=14, nfreqs=1536, add_tones: bool = False, add_noise: bool = True, gain_spread: float = 0.0, nsamples_func: callable = np.ones, flag_func: callable = partial(np.zeros, dtype=bool), ): freqs = mockuvd.PHASEII_FREQS[:nfreqs] basis = dpss_operator( freqs, filter_centers=[0], filter_half_widths=[200e-9], eigenval_cutoff=[1e-9], )[0].real ncoeff = basis.shape[-1] def gauss_noise(size, scale=1.0): return scale * ( self.rng.normal(size=size) + 1j * self.rng.normal(size=size) ) coeffs_mean = gauss_noise(ncoeff, 10) # avg dpss coeffs coeffs = coeffs_mean + gauss_noise( (nnights, ncoeff), 0.01 ) # daily variation in dpss coeffs d_true = np.einsum("nc,fc->nf", coeffs, basis) if add_tones: tones = gauss_noise((nnights, 1), 0.1) * np.exp( 2j * np.pi * freqs[None, :] * 190e-9 ) # a ripple d_true += tones # daily variation in gain gains = ( 1 + gain_spread * self.rng.uniform(size=d_true.shape[0]) - gain_spread / 2 ) d_true *= gains[:, None] nsamples = nsamples_func(d_true.shape) flags = flag_func(d_true.shape) if add_noise: n_true = gauss_noise(d_true.shape, 0.04) / nsamples**0.5 d_true += n_true nsamples[flags] *= -1 return freqs, d_true, flags, nsamples def random_nsamples(self, shape): n = self.rng.integers(1, 10, size=shape[0]).astype(float) return n[:, None] * np.ones(shape) def test_no_flags_no_nsamples(self): freqs, d, f, n = self.create_data() inp_mean, ff, model = avg.average_and_inpaint_simultaneously_single_bl( freqs=freqs, stackd=d, stackf=f, stackn=n, base_noise_var=0.04**2 * np.ones(d.shape), df=(freqs[1] - freqs[0]) * un.Hz, filter_half_widths=[200e-9], eigenval_cutoff=[1e-9], ) assert np.all(inp_mean == np.mean(d, axis=0)) @pytest.mark.parametrize("gain_spread", [0.0, 0.1, 0.5]) @pytest.mark.parametrize("add_tones", [False, True]) def test_no_flags_with_nsamples(self, gain_spread, add_tones): freqs, d, f, n = self.create_data( nsamples_func=self.random_nsamples, gain_spread=gain_spread, add_tones=add_tones, ) inp_mean, ff, model = avg.average_and_inpaint_simultaneously_single_bl( freqs=freqs, stackd=d, stackf=f, stackn=n, base_noise_var=0.04**2 * np.ones(d.shape), df=(freqs[1] - freqs[0]) * un.Hz, filter_half_widths=[200e-9], eigenval_cutoff=[1e-9], ) assert np.allclose(inp_mean, np.average(d, axis=0, weights=n)) @pytest.mark.parametrize("gain_spread", [0.0, 0.3]) @pytest.mark.parametrize("add_tones", [False, True]) @pytest.mark.parametrize("gap_size", [1, 3]) @pytest.mark.parametrize("nnights_flagged", [1, 2, 7, 13, 14]) def test_small_flag_gap(self, gain_spread, add_tones, gap_size, nnights_flagged): freqs, d, f, n = self.create_data(gain_spread=gain_spread, add_tones=add_tones) slc = slice(750, 750 + gap_size) f[:nnights_flagged, slc] = True inp_mean, ff, model = avg.average_and_inpaint_simultaneously_single_bl( freqs=freqs, stackd=d, stackf=f, stackn=n, base_noise_var=0.04**2 * np.ones(d.shape), df=(freqs[1] - freqs[0]) * un.Hz, filter_half_widths=[200e-9], eigenval_cutoff=[1e-9], ) np.testing.assert_allclose( inp_mean[slc], np.mean(d, axis=0)[slc], atol=5 * 0.04 / d.shape[0] ** 0.5, # 5-sigma ) @pytest.mark.parametrize("gain_spread", [0.0, 0.3]) @pytest.mark.parametrize("add_tones", [False, True]) @pytest.mark.parametrize("gap_size", [10, 20]) @pytest.mark.parametrize("nnights_flagged", [1, 2, 7]) def test_large_flag_gap(self, gain_spread, add_tones, gap_size, nnights_flagged): freqs, d, f, n = self.create_data(gain_spread=gain_spread, add_tones=add_tones) slc = slice(750, 750 + gap_size) f[:nnights_flagged, slc] = True inp_mean, ff, model = avg.average_and_inpaint_simultaneously_single_bl( freqs=freqs, stackd=d, stackf=f, stackn=n, base_noise_var=0.04**2 * np.ones(d.shape), df=(freqs[1] - freqs[0]) * un.Hz, filter_half_widths=[200e-9], eigenval_cutoff=[1e-9], ) np.testing.assert_allclose( inp_mean[slc], np.mean(d, axis=0)[slc], atol=5 * 0.04 / np.sqrt(d.shape[0]), # 5-sigma ) @pytest.mark.parametrize("gain_spread", [0.3]) @pytest.mark.parametrize("add_tones", [True]) @pytest.mark.parametrize("gap_size", [1, 5, 10]) @pytest.mark.parametrize("nnights_flagged", [1, 2, 7]) @pytest.mark.parametrize("bias", [1.5, 3.0]) def test_biased_flags( self, gain_spread, add_tones, gap_size, nnights_flagged, bias ): if bias > 1.5 and nnights_flagged > 5: pytest.xfail( "Expected failure of simultaneous inpainting with large bias in large gaps" ) freqs, d, f, n = self.create_data(gain_spread=gain_spread, add_tones=add_tones) slc = slice(750, 750 + gap_size) f[:nnights_flagged, slc] = True # Do the bias d[:nnights_flagged] *= bias inp_mean, ff, model = avg.average_and_inpaint_simultaneously_single_bl( freqs=freqs, stackd=d, stackf=f, stackn=n, base_noise_var=0.04**2 * np.ones(d.shape), df=(freqs[1] - freqs[0]) * un.Hz, filter_half_widths=[200e-9], eigenval_cutoff=[1e-9], ) np.testing.assert_allclose( inp_mean[slc], np.mean(d, axis=0)[slc], atol=5 * 0.04 / np.sqrt(d.shape[0]), # 5-sigma ) @pytest.mark.parametrize("gain_spread", [0.3]) @pytest.mark.parametrize("add_tones", [True]) @pytest.mark.parametrize("gap_size", [1, 5, 15]) @pytest.mark.parametrize("nnights_flagged", [1, 2, 7]) @pytest.mark.parametrize("bias", [1.0, 1.5]) def test_uneven_flags( self, gain_spread, add_tones, gap_size, nnights_flagged, bias ): freqs, d, f, n = self.create_data(gain_spread=gain_spread, add_tones=add_tones) slc = slice(750 - gap_size, 750 + gap_size) for i in range(nnights_flagged): start = 750 + np.random.randint(-gap_size // 2, gap_size // 2) end = start + gap_size _slc = slice(start, end) f[i, _slc] = True # Do the bias d[:nnights_flagged] *= bias inp_mean, ff, model = avg.average_and_inpaint_simultaneously_single_bl( freqs=freqs, stackd=d, stackf=f, stackn=n, base_noise_var=0.04**2 * np.ones(d.shape), df=(freqs[1] - freqs[0]) * un.Hz, filter_half_widths=[200e-9], eigenval_cutoff=[1e-9], ) np.testing.assert_allclose( inp_mean[slc], np.mean(d, axis=0)[slc], atol=5 * 0.04 / np.sqrt(d.shape[0]), # 5-sigma ) @pytest.mark.parametrize("gain_spread", [0.3]) @pytest.mark.parametrize("add_tones", [True]) @pytest.mark.parametrize("gap_size", [1, 5, 15]) @pytest.mark.parametrize("nnights_flagged", [1, 2, 7]) @pytest.mark.parametrize("bias", [1.0, 1.5]) def test_band_edge(self, gain_spread, add_tones, gap_size, nnights_flagged, bias): if gap_size > 1: pytest.xfail("Expected failure of simultaneous inpainting at band edge") freqs, d, f, n = self.create_data(gain_spread=gain_spread, add_tones=add_tones) slc = slice(0, gap_size) f[:nnights_flagged, slc] = True # Do the bias d[:nnights_flagged] *= bias inp_mean, ff, model = avg.average_and_inpaint_simultaneously_single_bl( freqs=freqs, stackd=d, stackf=f, stackn=n, base_noise_var=0.04**2 * np.ones(d.shape), df=(freqs[1] - freqs[0]) * un.Hz, filter_half_widths=[200e-9], eigenval_cutoff=[1e-9], ) np.testing.assert_allclose( inp_mean[slc], np.mean(d, axis=0)[slc], atol=5 * 0.04 / np.sqrt(d.shape[0]), # 5-sigma ) def test_non_uniform_nsamples(self): freqs, d, f, n = self.create_data() n[0, 1] = 25.0 with pytest.raises( ValueError, match="assumes that nsamples is constant over frequency" ): avg.average_and_inpaint_simultaneously_single_bl( freqs=freqs, stackd=d, stackf=f, stackn=n, base_noise_var=0.04**2 * np.ones(d.shape), df=(freqs[1] - freqs[0]) * un.Hz, filter_half_widths=[200e-9], ) def test_fully_flagged(self): freqs, d, f, n = self.create_data() f[:] = True data, flg, m = avg.average_and_inpaint_simultaneously_single_bl( freqs=freqs, stackd=d, stackf=f, stackn=n, base_noise_var=0.04**2 * np.ones(d.shape), df=(freqs[1] - freqs[0]) * un.Hz, filter_half_widths=[200e-9], ) assert np.all(np.isnan(data)) assert np.all(flg) def test_too_long_flag_gap(self): freqs, d, f, n = self.create_data() f[:, 100:200] = True data, flg, m = avg.average_and_inpaint_simultaneously_single_bl( freqs=freqs, stackd=d, stackf=f, stackn=n, base_noise_var=0.04**2 * np.ones(d.shape), df=(freqs[1] - freqs[0]) * un.Hz, filter_half_widths=[200e-9], max_gap_factor=1, ) assert np.all(np.isnan(data)) assert np.all(flg) def test_single_night_corner_case(self): freqs, d, f, n = self.create_data(nnights=1) data, flg, m = avg.average_and_inpaint_simultaneously_single_bl( freqs=freqs, stackd=d, stackf=f, stackn=n, base_noise_var=0.04**2 * np.ones(d.shape), df=(freqs[1] - freqs[0]) * un.Hz, filter_half_widths=[200e-9], ) assert np.all(data == d) class TestAverageInpaintSimultaneously: def setup_class(self): self.uvd = mockuvd.create_uvd_identifiable( integration_time=24 * 3600, ntimes=20, jd_start=2459844.0, antpairs=[(0, 1), (0, 2)], time_axis_faster_than_bls=False, ) self.stack = LSTStack(self.uvd) self.stack.data[1:] = self.stack.data[0] # All nights exactly the same self.auto_uvd = mockuvd.create_uvd_identifiable( integration_time=24 * 3600, ntimes=20, jd_start=2459844.0, antpairs=[(0, 0)], time_axis_faster_than_bls=False, ) self.auto_stack = LSTStack(self.auto_uvd) self.auto_stack.data[1:] = self.auto_stack.data[ 0 ] # All nights exactly the same def test_no_flags(self): lstavg, models = avg.average_and_inpaint_simultaneously( self.stack, self.auto_stack, return_models=True ) # Since there were no flags at all, there should be no models at all. assert len(models) == 0 np.testing.assert_allclose(lstavg["data"], self.stack.data[0]) def test_all_flagged(self): self.stack.flags[:] = True lstavg, models = avg.average_and_inpaint_simultaneously( self.stack, self.auto_stack, return_models=True ) self.stack.flags[:] = False assert len(models) == 0 assert np.all(np.isnan(lstavg["data"])) def test_fully_flagged_channel(self): self.stack.flags[:, 0, self.stack.Nfreqs // 2, 0] = True lstavg, models = avg.average_and_inpaint_simultaneously( self.stack, self.auto_stack, return_models=True ) self.stack.flags[:] = False assert ( len(models) == 1 ) # only one baseline actually gets a model, others are fully determined by data assert not np.any(np.isnan(lstavg["data"])) np.testing.assert_allclose( lstavg["data"][0, self.stack.Nfreqs // 2, 0], self.stack.data[0, 0, self.stack.Nfreqs // 2, 0], rtol=1e-4, ) assert lstavg["nsamples"][0, self.stack.Nfreqs // 2, 0] == 0.0 assert not lstavg["flags"][0, self.stack.Nfreqs // 2, 0] def test_fully_flagged_integration(self): self.stack.flags[0, 0, :, 0] = True lstavg, models = avg.average_and_inpaint_simultaneously( self.stack, self.auto_stack, return_models=True ) self.stack.flags[:] = False assert len(models) == 1 assert not np.any(np.isnan(lstavg["data"])) np.testing.assert_allclose( lstavg["data"][0, :, 0], self.stack.data[0, 0, :, 0], ) assert np.all(lstavg["nsamples"][0, :, 0] == len(self.stack.nights) - 1) assert not np.any(lstavg["flags"][0, :, 0]) def test_nonred_data(self): auto_uvd = mockuvd.create_uvd_identifiable( integration_time=24 * 3600, ntimes=20, jd_start=2459844.0, antpairs=[(0, 0), (1, 1)], time_axis_faster_than_bls=False, ) auto_stack = LSTStack(auto_uvd) lstavg, _ = avg.average_and_inpaint_simultaneously(self.stack, auto_stack) assert not np.any(np.isnan(lstavg['data'])) np.testing.assert_allclose(lstavg["data"], self.stack.data[0])
HERA-TeamREPO_NAMEhera_calPATH_START.@hera_cal_extracted@hera_cal-main@hera_cal@lst_stack@tests@test_averaging.py@.PATH_END.py
{ "filename": "justplotit.py", "repo_name": "natashabatalha/virga", "repo_path": "virga_extracted/virga-master/virga/justplotit.py", "type": "Python" }
from bokeh.palettes import viridis,magma from bokeh.models import ColumnDataSource, Label, LabelSet,CustomJS from bokeh.layouts import column,row,gridplot from bokeh.plotting import figure, show from bokeh.models import LinearColorMapper, LogTicker,BasicTicker, ColorBar,LogColorMapper,Legend from bokeh.palettes import magma as colfun1 from bokeh.palettes import Colorblind8 from bokeh.palettes import viridis as colfun2 from bokeh.palettes import gray as colfun3 from bokeh.palettes import Colorblind8 import bokeh.palettes as colpals from bokeh.io import output_notebook import astropy.units as u import numpy as np from . import justdoit as pyeddy def pt(out, with_condensation=True,return_condensation=False, **kwargs): """ Plot PT profiles with condensation curves. Thick lines in this pt plot signify those gases that were turned on in the run, NOT those that were recommended. Parameters ---------- out : dict Dictionary output from pyeddy run with_condensation : bool Plots condensation curves of gases. Also plots those that were turned on in the calculation with line_width=5. All others are set to 1. return_condensation : bool If true, it returns list of condenation temps for each gas, pressure grid, and a list of the gas names **kwargs : kwargs Kwargs for bokeh.figure() Returns ------- if return_condensation: fig, cond temperature curves, ,cond pressure grid , name of all available gases else: fig """ kwargs['height'] = kwargs.get('plot_height',kwargs.get('height',300)) kwargs['width'] = kwargs.get('plot_width', kwargs.get('width',600)) if 'plot_width' in kwargs.keys() : kwargs.pop('plot_width') if 'plot_height' in kwargs.keys() : kwargs.pop('plot_height') kwargs['x_axis_label'] = kwargs.get('x_axis_label','Temperature (K)') kwargs['y_axis_label'] = kwargs.get('y_axis_label','Pressure (bars)') kwargs['y_axis_type'] = kwargs.get('y_axis_type','log') ngas = len(out['condensibles']) temperature = out['temperature'] pressure = out['pressure'] condensibles = out['condensibles'] mh, mmw = out['scalar_inputs']['mh'], out['scalar_inputs']['mmw'] kwargs['y_range'] = kwargs.get('y_range',[np.max(pressure), np.min(pressure)]) fig = figure(**kwargs) if with_condensation: all_gases = pyeddy.available() cond_ts = [] recommend = [] line_width = [] for gas_name in all_gases: #case sensitive names #grab p,t from eddysed cond_p,t = pyeddy.condensation_t(gas_name, mh, mmw) cond_ts +=[t] if gas_name in condensibles: line_width += [5] else: line_width += [1] cols = magma(len(all_gases)) for i in range(len(all_gases)): fig.line(cond_ts[i],cond_p, legend_label=all_gases[i],color=cols[i],line_width=line_width[i] ) fig.line(temperature,pressure, legend_label='User',color='black',line_width=5,line_dash='dashed') plot_format(fig) if return_condensation: return fig, cond_ts,cond_p,all_gases else : return fig def radii(out,gas=None,at_pressure = 1e-3, compare=False, legend=None, p1w=300, p1h=300, p2w=300, p2h=300, color_indx=0): """ Plots the particle radii profile along with the distribution, at a certain pressure. Parameters ---------- out : dict Dictionary output from pyeddy run pressure : float,optional Pressure level to plot full distribution (bars) """ if type(out)==dict: out=[out] lines = ['solid','dashed','dashdot'] #lines = ['solid']*3 if compare: lines = ['solid']*len(out) legend_it = [] for j in range(len(out)): #compute initial distributions r_g = out[j]['mean_particle_r'] pressure = out[j]['pressure'] nl = find_nearest_1d(pressure,at_pressure) rmin = out[j]['scalar_inputs']['rmin'] nrad = out[j]['scalar_inputs']['nrad'] sig = out[j]['scalar_inputs']['sig'] ndz = out[j]['column_density'] #determine which condensed which_condensed = [False]*ndz.shape[1] # only conisider specified gas if gas is not None: indx = out[j]['condensibles'].index(gas) ndz_gas = np.unique(ndz[:,indx]) ndz_gas = ndz_gas[ndz_gas>0] if len(ndz_gas)>0 : which_condensed[indx] = True else: print(condensate + " did not condense. Choose another condensate.") import sys; sys.exit() # consider all gases else: for i in range(ndz.shape[1]): ndz_gas = np.unique(ndz[:,i]) ndz_gas = ndz_gas[ndz_gas>0] if len(ndz_gas)>0 : which_condensed[i] = True #take only those that condensed N = ndz[:, which_condensed] r_g = r_g[:,which_condensed] gas_name = list(np.array(out[j]['condensibles'])[which_condensed]) r, rup, dr = pyeddy.get_r_grid(r_min = rmin, n_radii = nrad) # different colours for different dicts if (gas is not None) or compare: length = len(out) # different colours for different gases else: length = len(gas_name) color = magma(length) color = Colorblind8[color_indx:color_indx+length] #initial radii profiles df_r_g = {i:r_g[:, gas_name.index(i)] for i in gas_name} df_r_g['pressure'] = pressure dndr = {} for i in gas_name: dndr[i]= N[nl,gas_name.index(i)]/r/np.sqrt(2*np.pi)*np.log(sig)*np.exp( - np.log(r/(r_g[nl,gas_name.index(i)]*1e-4))**2/(2*np.log(sig)**2)) #1e-4 is microns to cm dndr['r'] = r*1e4 #convert to microns if j==0: p1 = figure(width=p1w, height=p1h, title="Select Pressure Level", x_axis_type='log',y_axis_type='log',y_axis_label='Pressure (bars)',x_axis_label='Mean Particle Radius (um)', y_range=[np.max(pressure),np.min(pressure)]) p2 = figure(width=p2w, height=p2h, title="Particle Distribution at %.0e bars" %at_pressure, x_axis_type='log', y_axis_type='log', y_axis_label='dn/dr (cm-3)', x_axis_label='Particle Radius (um)', y_range=[np.max([np.min(dndr[i]), 1e-50]), np.max(dndr[i])]) #add to r_g for that plot df_r_g['average'] = [pressure[nl]]*len(pressure) df_r_g['horizontal'] = np.linspace(np.amin(r_g[r_g>0]), np.amax(r_g) , len(pressure)) s1 = ColumnDataSource(data=dict(df_r_g)) s2 = ColumnDataSource(data=dict(dndr)) for i in gas_name: if gas is not None or compare: indx = j else: indx = gas_name.index(i) f = p1.line(i, 'pressure', source=s1, alpha=1,color=color[np.mod(indx, len(color))] ,line_width=4,legend_label=i,line_dash=lines[j]) p2.line('r', i, source=s2,color=color[np.mod(indx, len(color))] ,line_width=4,line_dash=lines[j]) if compare: legend_it.append((legend[j], [f])) # r_g = out['droplet_eff_r'] # pressure = out['pressure'] # nl = find_nearest_1d(pressure,at_pressure) # rmin = out['scalar_inputs']['rmin'] # nrad = out['scalar_inputs']['nrad'] # sig = out['scalar_inputs']['sig'] # ndz = out['column_density'] # #determine which condensed # which_condensed = [False]*ndz.shape[1] # for i in range(ndz.shape[1]): # ndz_gas = np.unique(ndz[:,i]) # ndz_gas = ndz_gas[ndz_gas>0] # if len(ndz_gas)>0 : which_condensed[i] = True # color = magma(len(which_condensed)) # #take only those that condensed # N = ndz[:, which_condensed] # r_g = r_g[:,which_condensed] # gas_name = list(np.array(out['condensibles'])[which_condensed]) # r, rup, dr = pyeddy.get_r_grid(r_min = rmin, n_radii = nrad) # #initial radii profiles # df_r_g = {i:r_g[:, gas_name.index(i)] for i in gas_name} # df_r_g['pressure'] = pressure # #add to r_g for that plot # df_r_g['average'] = [pressure[nl]]*len(pressure) # df_r_g['horizontal'] = np.linspace(np.amin(r_g[r_g>0]), np.amax(r_g) , len(pressure)) p1.line('horizontal', 'average', source=s1, color='black',line_width=3,line_dash='dashed') p1.legend.location = 'bottom_left' #plot_format(p1) #plot_format(p2) if compare: legend = Legend(items=legend_it, location=(0, 0)) legend.click_policy="mute" p1.add_layout(legend, 'right') return row(p1, p2), dndr def opd_by_gas(out, gas = None, color = magma, compare=False, legend=None, **kwargs): """ Optical depth for conservative geometric scatteres separated by gas. E.g. [Fig 7 in Morley+2012](https://arxiv.org/pdf/1206.4313.pdf) Parameters ---------- out : dict Dictionary output from pyeddy run color : method Method from bokeh.palletes. e.g. bokeh.palletes.virids, bokeh.palletes.magma **kwargs : kwargs Kwargs for bokeh.figure() """ kwargs['height'] = kwargs.get('plot_height',kwargs.get('height',300)) kwargs['width'] = kwargs.get('plot_width', kwargs.get('width',400)) if 'plot_width' in kwargs.keys() : kwargs.pop('plot_width') if 'plot_height' in kwargs.keys() : kwargs.pop('plot_height') kwargs['x_axis_label'] = kwargs.get('x_axis_label','Column Optical Depth') kwargs['y_axis_label'] = kwargs.get('y_axis_label','Pressure (bars)') kwargs['y_axis_type'] = kwargs.get('y_axis_type','log') kwargs['x_axis_type'] = kwargs.get('x_axis_type','log') if type(out)==dict: out=[out] condensibles = out[0]['condensibles'] if gas is not None: indx = condensibles.index(gas) length = len(out) else: length = len(condensibles) ngas = len(condensibles) col = color(length) col = Colorblind8[:length] lines = ['solid','dashed','dotdash','dashdot'] legend_it = [] for j in range(len(out)): pressure = out[j]['pressure'] opd_by_gas = out[j]['opd_by_gas'] if j == 0: kwargs['y_range'] = kwargs.get('y_range',[np.max(pressure), np.min(pressure)]) kwargs['x_range'] = kwargs.get('x_range',[np.max([1e-6, np.min(opd_by_gas*0.9)]), np.max(opd_by_gas*1.1)]) fig = figure(**kwargs) if compare: if gas is not None: f = fig.line(opd_by_gas[:,indx], pressure, line_width=4, legend_label = condensibles[indx], color=Colorblind8[np.mod(j, len(Colorblind8))]) else: for i in range(ngas): f = fig.line(opd_by_gas[:,i], pressure,line_width=4, legend_label = condensibles[i], color=Colorblind8[np.mod(j, len(Colorblind8))], line_dash=lines[i]) legend_it.append((legend[j], [f])) else: if gas is not None: fig.line(opd_by_gas[:,indx], pressure, line_width=4, legend_label = condensibles[indx], color=col[j], line_dash=lines[j]) else: for i in range(ngas): fig.line(opd_by_gas[:,i], pressure,line_width=4, legend_label = condensibles[i], color=col[i], line_dash=lines[j]) if compare: legend = Legend(items=legend_it, location=(0, 0)) legend.click_policy="mute" fig.add_layout(legend, 'right') #plot_format(fig) return fig def condensate_mmr(out, gas=None, compare=False, legend=None, **kwargs): """ Condensate mean mass mixing ratio Parameters ---------- out : dict Dictionary output from pyeddy run color : method Method from bokeh.palletes. e.g. bokeh.palletes.virids, bokeh.palletes.magma **kwargs : kwargs Kwargs for bokeh.figure() """ kwargs['height'] = kwargs.get('plot_height',kwargs.get('height',300)) kwargs['width'] = kwargs.get('plot_width', kwargs.get('width',400)) if 'plot_width' in kwargs.keys() : kwargs.pop('plot_width') if 'plot_height' in kwargs.keys() : kwargs.pop('plot_height') kwargs['x_axis_label'] = kwargs.get('x_axis_label','Condensate MMR') kwargs['y_axis_label'] = kwargs.get('y_axis_label','Pressure (bars)') kwargs['y_axis_type'] = kwargs.get('y_axis_type','log') kwargs['x_axis_type'] = kwargs.get('x_axis_type','log') if type(out)==dict: out=[out] condensibles = out[0]['condensibles'] if gas is not None : indx = condensibles.index(gas) length = len(out) else: length = len(condensibles) ngas = len(condensibles) col = magma(length) lines = ['solid','dashed','dotdash','dashdot'] legend_it = [] for j in range(len(out)): pressure = out[j]['pressure'] cond_mmr = out[j]['condensate_mmr'] if j == 0: kwargs['y_range'] = kwargs.get('y_range',[np.max(pressure), np.min(pressure)]) kwargs['x_range'] = kwargs.get('x_range',[np.max([1e-9, np.min(cond_mmr*0.9)]), np.max(cond_mmr*1.1)]) fig = figure(**kwargs) if compare: if gas is not None: f = fig.line(cond_mmr[:,i], pressure, line_width=4, legend_label = condensibles[indx], color=Colorblind8[np.mod(j, len(Colorblind8))]) else: for i in range(ngas): label = condensibles[i] + ' ' + legend[j] f = fig.line(cond_mmr[:,i], pressure, line_width=4, legend_label = condensibles[i], color=Colorblind8[np.mod(j, len(Colorblind8))], line_dash=lines[i]) legend_it.append((legend[j], [f])) else: if gas is not None: fig.line(cond_mmr[:,indx], pressure, line_width=4, legend_label = condensibles[indx], color=Colorblind8[np.mod(j, len(Colorblind8))], line_dash=lines[j]) else: for i in range(ngas): fig.line(cond_mmr[:,i], pressure, line_width=4, legend_label = condensibles[i], color=col[i], line_dash=lines[j]) if compare: legend = Legend(items=legend_it, location=(0, 0)) legend.click_policy="mute" fig.add_layout(legend, 'right') plot_format(fig) return fig def all_optics(out): """ Maps of the wavelength dependent single scattering albedo and cloud opacity and asymmetry parameter as a function of altitude. Parameters ---------- out : dict Dictionary output from pyeddy run Returns ------- Three bokeh plots with the single scattering, optical depth, and assymetry maps """ #get into DataFrame format dat01 = pyeddy.picaso_format(out['opd_per_layer'],out['single_scattering'], out['asymmetry']) nwno=len(out['wave']) nlayer=len(out['pressure']) pressure=out['pressure'] pressure_label = 'Pressure (Bars)' wavelength_label = 'Wavelength (um)' wavelength = out['wave'] cols = colfun1(200) color_mapper = LinearColorMapper(palette=cols, low=0, high=1) #PLOT W0 scat01 = np.flip(np.reshape(dat01['w0'].values,(nlayer,nwno)),0) xr, yr = scat01.shape f01a = figure(x_range=[0, yr], y_range=[0,xr], x_axis_label=wavelength_label, y_axis_label=pressure_label, title="Single Scattering Albedo", width=300, height=300) f01a.image(image=[scat01], color_mapper=color_mapper, x=0,y=0,dh=xr,dw =yr ) color_bar = ColorBar(color_mapper=color_mapper, #ticker=LogTicker(), label_standoff=12, border_line_color=None, location=(0,0)) f01a.add_layout(color_bar, 'left') #PLOT OPD scat01 = np.flip(np.reshape(dat01['opd'].values,(nlayer,nwno)),0) xr, yr = scat01.shape cols = colfun2(200)[::-1] color_mapper = LogColorMapper(palette=cols, low=1e-3, high=10) f01 = figure(x_range=[0, yr], y_range=[0,xr], x_axis_label=wavelength_label, y_axis_label=pressure_label, title="Cloud Optical Depth Per Layer", width=320, height=300) f01.image(image=[scat01], color_mapper=color_mapper, x=0,y=0,dh=xr,dw =yr ) color_bar = ColorBar(color_mapper=color_mapper, ticker=LogTicker(), label_standoff=12, border_line_color=None, location=(0,0)) f01.add_layout(color_bar, 'left') #PLOT G0 scat01 = np.flip(np.reshape(dat01['g0'].values,(nlayer,nwno)),0) xr, yr = scat01.shape cols = colfun3(200)[::-1] color_mapper = LinearColorMapper(palette=cols, low=0, high=1) f01b = figure(x_range=[0, yr], y_range=[0,xr], x_axis_label=wavelength_label, y_axis_label=pressure_label, title="Asymmetry Parameter", width=300, height=300) f01b.image(image=[scat01], color_mapper=color_mapper, x=0,y=0,dh=xr,dw =yr ) color_bar = ColorBar(color_mapper=color_mapper, ticker=BasicTicker(), label_standoff=12, border_line_color=None, location=(0,0)) f01b.add_layout(color_bar, 'left') #CHANGE X AND Y AXIS TO BE PHYSICAL UNITS #indexes for pressure plot if (pressure is not None): pressure = ["{:.1E}".format(i) for i in pressure[::-1]] #flip since we are also flipping matrices npres = len(pressure) ipres = np.array(range(npres)) #set how many we actually want to put on the figure #hard code ten on each.. ipres = ipres[::int(npres/10)] pressure = pressure[::int(npres/10)] #create dictionary for tick marks ptick = {int(i):j for i,j in zip(ipres,pressure)} for i in [f01a, f01, f01b]: i.yaxis.ticker = ipres i.yaxis.major_label_overrides = ptick if (wavelength is not None): wave = ["{:.2F}".format(i) for i in wavelength] nwave = len(wave) iwave = np.array(range(nwave)) iwave = iwave[::int(nwave/10)] wave = wave[::int(nwave/10)] wtick = {int(i):j for i,j in zip(iwave,wave)} for i in [f01a, f01, f01b]: i.xaxis.ticker = iwave i.xaxis.major_label_overrides = wtick return gridplot([[f01a, f01,f01b]]) def all_optics_1d(out, wave_range, return_output = False,legend=None, colors = colpals.Colorblind8, **kwargs): """ Plots 1d profiles of optical depth per layer, single scattering, and asymmetry averaged over the user input wave_range. Parameters ---------- out : list or dict Either a list of output dictionaries or a single dictionary output from .compute(as_dict=True) wave_range : list min and max wavelength in microns return_output : bool Default is just to return a figure but you can also return all the 1d profiles legend : bool Default is none. Legend for each component of out **kwargs : keyword arguments Key word arguments will be supplied to each bokeh figure function """ kwargs['height'] = kwargs.get('plot_height',kwargs.get('height',300)) kwargs['width'] = kwargs.get('plot_width', kwargs.get('width',300)) if 'plot_width' in kwargs.keys() : kwargs.pop('plot_width') if 'plot_height' in kwargs.keys() : kwargs.pop('plot_height') kwargs['y_axis_type'] = kwargs.get('y_axis_type','log') if not isinstance(out, list): out = [out] pressure = out[0]['pressure'] kwargs['y_range'] = kwargs.get('y_range',[max(pressure),min(pressure)]) ssa = figure(x_axis_label='Single Scattering Albedo',**kwargs) g0 = figure(x_axis_label='Asymmetry',**kwargs) opd = figure(x_axis_label='Optical Depth',y_axis_label='Pressure (bars)', x_axis_type='log',**kwargs) for i,results in enumerate(out): inds = np.where((results['wave']>wave_range[0]) & (results['wave']<wave_range[1])) opd_dat = np.mean(results['opd_per_layer'][:,inds],axis=2)[:,0] opd.line(opd_dat, results['pressure'], color=colors[np.mod(i, len(colors))],line_width=3) g0_dat = np.mean(results['asymmetry'][:,inds],axis=2)[:,0] g0.line(g0_dat, results['pressure'], color=colors[np.mod(i, len(colors))],line_width=3) if isinstance(legend, type(None)): ssa_dat = np.mean(results['single_scattering'][:,inds],axis=2)[:,0] ssa.line(ssa_dat, results['pressure'], color=colors[np.mod(i, len(colors))],line_width=3) else: ssa_dat = np.mean(results['single_scattering'][:,inds],axis=2)[:,0] ssa.line(ssa_dat, results['pressure'], color=colors[np.mod(i, len(colors))],line_width=3, legend_label=legend[i]) ssa.legend.location='top_left' if return_output: return gridplot([[opd,ssa,g0]]), [opd_dat,ssa_dat,g0_dat] else: return gridplot([[opd,ssa,g0]]) def find_nearest_1d(array,value): #small program to find the nearest neighbor in a matrix ar , iar ,ic = np.unique(array,return_index=True,return_counts=True) idx = (np.abs(ar-value)).argmin(axis=0) if ic[idx]>1: idx = iar[idx] + (ic[idx]-1) else: idx = iar[idx] return idx def pressure_fig(**kwargs): kwargs['y_range'] = kwargs.get('y_range',[1e2,1e-6]) kwargs['height'] = kwargs.get('plot_height',kwargs.get('height',400)) kwargs['width'] = kwargs.get('plot_width', kwargs.get('width',600)) if 'plot_width' in kwargs.keys() : kwargs.pop('plot_width') if 'plot_height' in kwargs.keys() : kwargs.pop('plot_height') kwargs['x_axis_label'] = kwargs.get('x_axis_label','Temperature (K)') kwargs['y_axis_label'] = kwargs.get('y_axis_label','Pressure (bars)') kwargs['y_axis_type'] = kwargs.get('y_axis_type','log') fig = figure(**kwargs) return fig def plot_format(df): """Function to reformat plots""" df.xaxis.axis_label_text_font='times' df.yaxis.axis_label_text_font='times' df.xaxis.major_label_text_font_size='14pt' df.yaxis.major_label_text_font_size='14pt' df.xaxis.axis_label_text_font_size='14pt' df.yaxis.axis_label_text_font_size='14pt' df.xaxis.major_label_text_font='times' df.yaxis.major_label_text_font='times' df.xaxis.axis_label_text_font_style = 'bold' df.yaxis.axis_label_text_font_style = 'bold' def plot_fsed(pressure, z, scale_height, alpha, beta, epsilon=1e-2, pres_alpha=None, **kwargs): kwargs['height'] = kwargs.get('plot_height',kwargs.get('height',300)) kwargs['width'] = kwargs.get('plot_width', kwargs.get('width',700)) if 'plot_width' in kwargs.keys() : kwargs.pop('plot_width') if 'plot_height' in kwargs.keys() : kwargs.pop('plot_height') kwargs['x_axis_label'] = kwargs.get('x_axis_label','fsed') kwargs['y_axis_label'] = kwargs.get('y_axis_label','Pressure (bars)') kwargs['x_axis_type'] = kwargs.get('x_axis_type','log') kwargs['y_axis_type'] = kwargs.get('y_axis_type','log') if type(alpha) is int: alpha = [alpha] if type(beta) is int: beta = [beta] if pres_alpha is None: zstar = max(z) else: indx = find_nearest_1d(pressure, pres_alpha) zstar = z[indx] indx = find_nearest_1d(pressure, 1) H = scale_height[indx] cols = Colorblind8[:len(alpha)*len(beta)] lines = ['solid','dashed','dotted','dotdash','dashdot'] kwargs['y_range'] = kwargs.get('y_range',[np.max(pressure), np.min(pressure)]) fig = figure(**kwargs) for i in range(len(alpha)): for j in range(len(beta)): lab = "alpha=%g" %alpha[i] + ", beta=%g" %beta[j] col = Colorblind8[np.mod(i+len(alpha)*j, 8)] line = lines[np.mod(j, 5)] fsed = alpha[i] * np.exp((z-zstar)/(6*beta[j]*H)) + epsilon fig.line(fsed, pressure, legend_label=lab, color=col, line_width=5, line_dash='solid')#line) fig.legend.location = "bottom_right" return fig def fsed_from_output(out,labels,y_axis='pressure',color_indx=0,cld_bounds=False,gas_indx=None,**kwargs): if type(out)==dict: out=[out] kwargs['height'] = kwargs.get('plot_height',kwargs.get('height',300)) kwargs['width'] = kwargs.get('plot_width', kwargs.get('width',700)) if 'plot_width' in kwargs.keys() : kwargs.pop('plot_width') if 'plot_height' in kwargs.keys() : kwargs.pop('plot_height') kwargs['x_axis_label'] = kwargs.get('x_axis_label','fsed') kwargs['y_axis_label'] = kwargs.get('y_axis_label','Pressure (bars)') kwargs['x_axis_type'] = kwargs.get('x_axis_type','log') kwargs['y_axis_type'] = kwargs.get('y_axis_type','log') #kwargs['x_range'] = kwargs.get('x_range', [1e-2, 2e1]) if gas_indx is not None: title = 'Condensible = ' + str(out[0]['condensibles'][gas_indx]) kwargs['title'] = kwargs.get('title', title) cols = Colorblind8[color_indx:color_indx+len(out)] pressure = out[0]['pressure'] kwargs['y_range'] = kwargs.get('y_range',[np.max(pressure), np.min(pressure)]) fig = figure(**kwargs) min_id=[]; max_id=[] for i in range(len(out)): if gas_indx is None: x = out[i]['fsed'] else: x = out[i]['fsed'][:,gas_indx] if y_axis == 'pressure': y = out[i]['pressure'] elif y_axis == 'z': y = out[i]['altitude'] col = Colorblind8[np.mod(i+color_indx, 8)] fig.line(x, y, legend_label=labels[i], color=col, line_width=5) if cld_bounds and gas_indx is not None: low_clds = []; high_clds = [] ndz = out[i]['column_density'][:,gas_indx] nonzero = np.where(ndz>1e-3)[0] min_id.append(nonzero[0]) max_id.append(nonzero[-1]) if cld_bounds and gas_indx is not None: xmin = kwargs['x_range'][0] xmax = kwargs['x_range'][1] x1 = np.linspace(xmin,xmax,10) y1 = x1*0+y[min(min_id)] y2 = x1*0+y[max(max_id)] fig.line(x1, y1, color='black',line_width=5, line_dash='dashed') fig.line(x1, y2, color='black',line_width=5, line_dash='dashed') if labels is not None: fig.legend.location = "bottom_left" plot_format(fig) return fig
natashabatalhaREPO_NAMEvirgaPATH_START.@virga_extracted@virga-master@virga@justplotit.py@.PATH_END.py
{ "filename": "CMB_plots.py", "repo_name": "CosmicFish/CosmicFish", "repo_path": "CosmicFish_extracted/CosmicFish-master/camb/mgcamb/tests/python/CAMB_plots_lib/CMB_plots.py", "type": "Python" }
import numpy as np import matplotlib.pyplot as plt import math class CMB_plots: """ Class that contains the methods to optimally plot the CMB power spectra """ # general plot settings: color = 'red' # default color of the plot axes_label_position = 'left' # position of the y axes and y axes label negative_line_style = '--' # comparison plot settings: comparison = False # if the plot is a comparison of spectra or just the plot comparison_min = 10.0**(-3) # minimum y value of comparison plots comparison_max = 1.1*10.0**(+3) # maximum y value of comparison plots Fsky = 0.85 # fsky for cosmic variance def CosmicVariance(self,l): """ function that computes cosmic variance at a given l""" return math.sqrt(2.0/((2.0*l + 1.0)*self.Fsky)) def TT_plot(self, stream, xval, yval): """ CMB temperature power spectrum plot """ # do the plot: self.TT_p, = stream.plot( xval, yval, color = self.color ) # set x axes boundary: stream.set_xlim(np.amin(xval),np.amax(xval)) # set axes scales stream.set_xscale('Log') stream.ticklabel_format(axis='y', style='sci', scilimits=(-2,2)) # set labels stream.set_xlabel(r'$l$') stream.set_ylabel(r'$l(l+1)C_l^{TT}/ 2\pi$') # set the position of axes and label: stream.yaxis.set_label_position(self.axes_label_position) if self.axes_label_position == 'right': stream.yaxis.tick_right() # setup if comparison: if self.comparison: # plot cosmic variance ycosmicvar = np.array(map(self.CosmicVariance,xval))*100 self.CV_p, = stream.plot(xval, ycosmicvar, color = 'k') self.TT_p, = stream.plot( xval, -yval, color = self.color, linestyle=self.negative_line_style ) # set log scale stream.set_yscale('Log') # set limits and label stream.set_ylim(self.comparison_min, self.comparison_max) stream.set_ylabel(r'$\Delta C_l^{TT}/ C_l^{TT} (\%) $') def EE_plot(self,stream, xval, yval): """ CMB E mode polarization power spectrum plot """ # do the plot: self.EE_p, = stream.plot(xval, yval, color = self.color) # set x axes boundary: stream.set_xlim(np.amin(xval),np.amax(xval)) # set axes scales stream.set_xscale('Log') stream.set_yscale('Log') # set labels stream.set_xlabel(r'$l$') stream.set_ylabel(r'$l(l+1)C_l^{EE}/ 2\pi$') # set the position of axes and label: stream.yaxis.set_label_position(self.axes_label_position) if self.axes_label_position == 'right': stream.yaxis.tick_right() # setup if comparison: if self.comparison: ycosmicvar = np.array(map(self.CosmicVariance,xval))*100 self.EE_p, = stream.plot(xval, -yval, color = self.color, linestyle=self.negative_line_style) self.CV_p, = stream.plot(xval, ycosmicvar, color = 'k') stream.set_yscale('Log') stream.set_ylim(self.comparison_min, self.comparison_max) stream.set_ylabel(r'$\Delta C_l^{EE}/ C_l^{EE} (\%) $') def TE_plot(self,stream, xval, yval): """ CMB temperature E mode polarization cross correlation power spectrum plot """ # do the plot: self.TE_p, = stream.plot(xval, yval, color = self.color) self.TE_p, = stream.plot(xval, -yval, color = self.color, linestyle=self.negative_line_style) # set x axes boundary: stream.set_xlim(np.amin(xval),np.amax(xval)) # set axes scales stream.set_xscale('Log') stream.set_yscale('Log') # set labels stream.set_xlabel(r'$l$') stream.set_ylabel(r'$l(l+1)C_l^{TE}/ 2\pi$') # set the position of axes and label: stream.yaxis.set_label_position(self.axes_label_position) if self.axes_label_position == 'right': stream.yaxis.tick_right() # setup if comparison: if self.comparison: ycosmicvar = np.array(map(self.CosmicVariance,xval))*100 self.CV_p, = stream.plot(xval, ycosmicvar, color = 'k') stream.set_yscale('Log') stream.set_ylim(self.comparison_min, self.comparison_max) stream.set_ylabel(r'$\Delta C_l^{TE}/ C_l^{TE} (\%) $') def BB_plot(self,stream, xval, yval): """ CMB B mode polarization power spectrum plot """ # do the plot: self.BB_p, = stream.plot(xval, yval, color = self.color) self.BB_p, = stream.plot(xval, -yval, color = self.color, linestyle=self.negative_line_style) # set x axes boundary: stream.set_xlim(np.amin(xval),np.amax(xval)) # set axes scales stream.set_xscale('Log') stream.set_yscale('Log') # set labels stream.set_xlabel(r'$l$') stream.set_ylabel(r'$l(l+1)C_l^{BB}/ 2\pi$') # set the position of axes and label: stream.yaxis.set_label_position(self.axes_label_position) if self.axes_label_position == 'right': stream.yaxis.tick_right() # setup if comparison: if self.comparison: ycosmicvar = np.array(map(self.CosmicVariance,xval))*100 self.CV_p, = stream.plot(xval, ycosmicvar, color = 'k') stream.set_ylim(self.comparison_min, self.comparison_max) stream.set_ylabel(r'$\Delta C_l^{BB}/ C_l^{BB} (\%) $') def Phi_plot(self,stream, xval, yval): """ CMB lensing power spectrum plot """ # do the plot: self.Phi_p, = stream.plot(xval, yval, color = self.color) # set x axes boundary: stream.set_xlim(np.amin(xval),np.amax(xval)) # set axes scales stream.set_xscale('Log') stream.ticklabel_format(axis='y', style='sci', scilimits=(-2,2)) # set labels stream.set_xlabel(r'$l$') stream.set_ylabel(r'$l^4 C_l^{\Phi\Phi}$') # set the position of axes and label: stream.yaxis.set_label_position(self.axes_label_position) if self.axes_label_position == 'right': stream.yaxis.tick_right() # setup if comparison: if self.comparison: ycosmicvar = np.array(map(self.CosmicVariance,xval))*100 self.Phi_p, = stream.plot(xval, -yval, color = self.color, linestyle=self.negative_line_style) self.CV_p, = stream.plot(xval, ycosmicvar, color = 'k') stream.set_yscale('Log') stream.set_ylim(self.comparison_min, self.comparison_max) stream.set_ylabel(r'$\Delta C_l^{\Phi\Phi}/ C_l^{\Phi\Phi} (\%) $') def PhiT_plot(self,stream, xval, yval): """ CMB lensing and temperature cross correlation power spectrum plot """ # do the plot: self.PhiT_p, = stream.plot(xval, yval, color = self.color) # set x axes boundary: stream.set_xlim(np.amin(xval),np.amax(xval)) stream.ticklabel_format(axis='y', style='sci', scilimits=(-2,2)) # set axes scales stream.set_xscale('Log') # set labels stream.set_xlabel(r'$l$') stream.set_ylabel(r'$l^3 C_l^{\Phi T}$') # set the position of axes and label: stream.yaxis.set_label_position(self.axes_label_position) if self.axes_label_position == 'right': stream.yaxis.tick_right() # setup if comparison: if self.comparison: ycosmicvar = np.array(map(self.CosmicVariance,xval))*100 self.PhiT_p, = stream.plot(xval, -yval, color = self.color, linestyle=self.negative_line_style) self.CV_p, = stream.plot(xval, ycosmicvar, color = 'k') stream.set_yscale('Log') stream.set_ylim(self.comparison_min, self.comparison_max) stream.set_ylabel(r'$\Delta C_l^{\Phi T}/ C_l^{\Phi T} (\%) $') def Generic_Cl(self,stream, xval, yval): """ Generic spectrum plotter (in l-space) """ # take the abs value of y-val yval = np.array(yval) # do the plot: self.Generic_Cl_plot, = stream.plot(xval, yval, color = self.color) self.Generic_Cl_plot, = stream.plot(xval, -yval, color = self.color, linestyle=self.negative_line_style) # set x axes boundary: stream.set_xlim(np.amin(xval),np.amax(xval)) # set axes scales stream.set_xscale('Log') stream.set_yscale('Log') # set the position of axes and label: stream.yaxis.set_label_position(self.axes_label_position) if self.axes_label_position == 'right': stream.yaxis.tick_right() # setup if comparison: if self.comparison: ycosmicvar = np.array(map(self.CosmicVariance,xval))*100 self.CV_p, = stream.plot(xval, ycosmicvar, color = 'k') stream.set_ylim(self.comparison_min, self.comparison_max) def Matter_plot(self,stream, xval, yval): """ Matter power spectrum plot """ # do the plot: self.Matter_p, = stream.plot(xval, yval, color = self.color) self.Matter_p, = stream.plot(xval, -yval, color = self.color, linestyle=self.negative_line_style) # set x axes boundary: stream.set_xlim(np.amin(xval),np.amax(xval)) # set axes scales stream.set_xscale('Log') stream.set_yscale('Log') # set labels stream.set_xlabel(r'$k$') stream.set_ylabel(r'$P(k)$') # set the position of axes and label: stream.yaxis.set_label_position(self.axes_label_position) if self.axes_label_position == 'right': stream.yaxis.tick_right() # setup if comparison: if self.comparison: stream.set_yscale('Log') stream.set_ylim(self.comparison_min, self.comparison_max) stream.set_ylabel(r'$\Delta P(k)/ P(k) (\%) $') def Transfer_plot(self,stream, xval, yval): """ Transfer functions plot """ # do the plot: self.Transfer_p, = stream.plot(xval, yval, color = self.color) self.Transfer_p, = stream.plot(xval, -yval, color = self.color, linestyle=self.negative_line_style) # set x axes boundary: stream.set_xlim(np.amin(xval),np.amax(xval)) # set axes scales stream.set_xscale('Log') stream.set_yscale('Log') # set labels stream.set_ylabel(r'$T(k)$') # set the position of axes and label: stream.yaxis.set_label_position(self.axes_label_position) if self.axes_label_position == 'right': stream.yaxis.tick_right() # setup if comparison: if self.comparison: stream.set_yscale('Log') stream.set_ylim(self.comparison_min, self.comparison_max) stream.set_ylabel(r'$\Delta T(k)/ T(k) (\%) $')
CosmicFishREPO_NAMECosmicFishPATH_START.@CosmicFish_extracted@CosmicFish-master@camb@mgcamb@tests@python@CAMB_plots_lib@CMB_plots.py@.PATH_END.py
{ "filename": "_coloraxis.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/scatterpolargl/marker/line/_coloraxis.py", "type": "Python" }
import _plotly_utils.basevalidators class ColoraxisValidator(_plotly_utils.basevalidators.SubplotidValidator): def __init__( self, plotly_name="coloraxis", parent_name="scatterpolargl.marker.line", **kwargs, ): super(ColoraxisValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, dflt=kwargs.pop("dflt", None), edit_type=kwargs.pop("edit_type", "calc"), regex=kwargs.pop("regex", "/^coloraxis([2-9]|[1-9][0-9]+)?$/"), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@scatterpolargl@marker@line@_coloraxis.py@.PATH_END.py
{ "filename": "generative_inpainting_model.py", "repo_name": "giuspugl/picasso", "repo_path": "picasso_extracted/picasso-master/picasso/inpainters/generative_inpainting_model.py", "type": "Python" }
# # # This module has been slightly modified and imported from # https://github.com/JiahuiYu/generative_inpainting # # # date: 2019-08-20 # author: Jiahui Yu # python3.6 # Copyright (C) 2018 # import logging import cv2 import neuralgym as ng import tensorflow as tf from tensorflow.contrib.framework.python.ops import arg_scope from neuralgym.models import Model from neuralgym.ops.summary_ops import scalar_summary, images_summary from neuralgym.ops.summary_ops import gradients_summary from neuralgym.ops.layers import flatten, resize from neuralgym.ops.gan_ops import gan_wgan_loss, gradients_penalty from neuralgym.ops.gan_ops import random_interpolates from .generative_inpainting_ops import ( gen_conv, gen_deconv, dis_conv, random_bbox, bbox2mask, local_patch, spatial_discounting_mask, resize_mask_like, contextual_attention ) if __name__=='__main__' : logger = logging.getLogger() class InpaintCAModel(Model): """ Interface class to Generative Inpainting """ def __init__(self): super().__init__('InpaintCAModel') def build_inpaint_net(self, x, mask, config=None, reuse=False, training=True, padding='SAME', name='inpaint_net'): """Inpaint network. Args: x: incomplete image, [-1, 1] mask: mask region {0, 1} Returns: [-1, 1] as predicted image """ xin = x offset_flow = None ones_x = tf.ones_like(x)[:, :, :, 0:1] x = tf.concat([x, ones_x, ones_x*mask], axis=3) # two stage network cnum = 32 with tf.variable_scope(name, reuse=reuse ), \ arg_scope([gen_conv, gen_deconv], training=training, padding=padding): # stage1 x = gen_conv(x, cnum, 5, 1, name='conv1') x = gen_conv(x, 2*cnum, 3, 2, name='conv2_downsample') x = gen_conv(x, 2*cnum, 3, 1, name='conv3') x = gen_conv(x, 4*cnum, 3, 2, name='conv4_downsample') x = gen_conv(x, 4*cnum, 3, 1, name='conv5') x = gen_conv(x, 4*cnum, 3, 1, name='conv6') mask_s = resize_mask_like(mask, x) x = gen_conv(x, 4*cnum, 3, rate=2, name='conv7_atrous') x = gen_conv(x, 4*cnum, 3, rate=4, name='conv8_atrous') x = gen_conv(x, 4*cnum, 3, rate=8, name='conv9_atrous') x = gen_conv(x, 4*cnum, 3, rate=16, name='conv10_atrous') x = gen_conv(x, 4*cnum, 3, 1, name='conv11') x = gen_conv(x, 4*cnum, 3, 1, name='conv12') x = gen_deconv(x, 2*cnum, name='conv13_upsample') x = gen_conv(x, 2*cnum, 3, 1, name='conv14') x = gen_deconv(x, cnum, name='conv15_upsample') x = gen_conv(x, cnum//2, 3, 1, name='conv16') x = gen_conv(x, 3, 3, 1, activation=None, name='conv17') x = tf.clip_by_value(x, -1., 1.) x_stage1 = x # return x_stage1, None, None # stage2, paste result as input # x = tf.stop_gradient(x) x = x*mask + xin*(1.-mask) x.set_shape(xin.get_shape().as_list()) # conv branch xnow = tf.concat([x, ones_x, ones_x*mask], axis=3) x = gen_conv(xnow, cnum, 5, 1, name='xconv1') x = gen_conv(x, cnum, 3, 2, name='xconv2_downsample') x = gen_conv(x, 2*cnum, 3, 1, name='xconv3') x = gen_conv(x, 2*cnum, 3, 2, name='xconv4_downsample') x = gen_conv(x, 4*cnum, 3, 1, name='xconv5') x = gen_conv(x, 4*cnum, 3, 1, name='xconv6') x = gen_conv(x, 4*cnum, 3, rate=2, name='xconv7_atrous') x = gen_conv(x, 4*cnum, 3, rate=4, name='xconv8_atrous') x = gen_conv(x, 4*cnum, 3, rate=8, name='xconv9_atrous') x = gen_conv(x, 4*cnum, 3, rate=16, name='xconv10_atrous') x_hallu = x # attention branch x = gen_conv(xnow, cnum, 5, 1, name='pmconv1') x = gen_conv(x, cnum, 3, 2, name='pmconv2_downsample') x = gen_conv(x, 2*cnum, 3, 1, name='pmconv3') x = gen_conv(x, 4*cnum, 3, 2, name='pmconv4_downsample') x = gen_conv(x, 4*cnum, 3, 1, name='pmconv5') x = gen_conv(x, 4*cnum, 3, 1, name='pmconv6', activation=tf.nn.relu) x, offset_flow = contextual_attention(x, x, mask_s, 3, 1, rate=2) #contextual_attention x = gen_conv(x, 4*cnum, 3, 1, name='pmconv9') x = gen_conv(x, 4*cnum, 3, 1, name='pmconv10') pm = x x = tf.concat([x_hallu, pm], axis=3) x = gen_conv(x, 4*cnum, 3, 1, name='allconv11') x = gen_conv(x, 4*cnum, 3, 1, name='allconv12') x = gen_deconv(x, 2*cnum, name='allconv13_upsample') x = gen_conv(x, 2*cnum, 3, 1, name='allconv14') x = gen_deconv(x, cnum, name='allconv15_upsample') x = gen_conv(x, cnum//2, 3, 1, name='allconv16') x = gen_conv(x, 3, 3, 1, activation=None, name='allconv17') x_stage2 = tf.clip_by_value(x, -1., 1.) return x_stage1, x_stage2, offset_flow def build_wgan_local_discriminator(self, x, reuse=False, training=True): with tf.variable_scope('discriminator_local', reuse=reuse): cnum = 64 x = dis_conv(x, cnum, name='conv1', training=training) x = dis_conv(x, cnum*2, name='conv2', training=training) x = dis_conv(x, cnum*4, name='conv3', training=training) x = dis_conv(x, cnum*8, name='conv4', training=training) x = flatten(x, name='flatten') return x def build_wgan_global_discriminator(self, x, reuse=False, training=True): with tf.variable_scope('discriminator_global', reuse=reuse): cnum = 64 x = dis_conv(x, cnum, name='conv1', training=training) x = dis_conv(x, cnum*2, name='conv2', training=training) x = dis_conv(x, cnum*4, name='conv3', training=training) x = dis_conv(x, cnum*4, name='conv4', training=training) x = flatten(x, name='flatten') return x def build_wgan_discriminator(self, batch_local, batch_global, reuse=False, training=True): with tf.variable_scope('discriminator', reuse=reuse): dlocal = self.build_wgan_local_discriminator( batch_local, reuse=reuse, training=training) dglobal = self.build_wgan_global_discriminator( batch_global, reuse=reuse, training=training) dout_local = tf.layers.dense(dlocal, 1, name='dout_local_fc') dout_global = tf.layers.dense(dglobal, 1, name='dout_global_fc') return dout_local, dout_global def build_graph_with_losses(self, batch_data, config, training=True, summary=False, reuse=False): batch_pos = batch_data / 127.5 - 1. # generate mask, 1 represents masked point bbox = random_bbox(config) mask = bbox2mask(bbox, config, name='mask_c') batch_incomplete = batch_pos*(1.-mask) x1, x2, offset_flow = self.build_inpaint_net( batch_incomplete, mask, config, reuse=reuse, training=training, padding=config.PADDING) if config.PRETRAIN_COARSE_NETWORK: batch_predicted = x1 logger.info('Set batch_predicted to x1.') else: batch_predicted = x2 logger.info('Set batch_predicted to x2.') losses = {} # apply mask and complete image batch_complete = batch_predicted*mask + batch_incomplete*(1.-mask) # local patches local_patch_batch_pos = local_patch(batch_pos, bbox) local_patch_batch_predicted = local_patch(batch_predicted, bbox) local_patch_x1 = local_patch(x1, bbox) local_patch_x2 = local_patch(x2, bbox) local_patch_batch_complete = local_patch(batch_complete, bbox) local_patch_mask = local_patch(mask, bbox) l1_alpha = config.COARSE_L1_ALPHA losses['l1_loss'] = l1_alpha * tf.reduce_mean(tf.abs(local_patch_batch_pos - local_patch_x1)*spatial_discounting_mask(config)) if not config.PRETRAIN_COARSE_NETWORK: losses['l1_loss'] += tf.reduce_mean(tf.abs(local_patch_batch_pos - local_patch_x2)*spatial_discounting_mask(config)) losses['ae_loss'] = l1_alpha * tf.reduce_mean(tf.abs(batch_pos - x1) * (1.-mask)) if not config.PRETRAIN_COARSE_NETWORK: losses['ae_loss'] += tf.reduce_mean(tf.abs(batch_pos - x2) * (1.-mask)) losses['ae_loss'] /= tf.reduce_mean(1.-mask) if summary: scalar_summary('losses/l1_loss', losses['l1_loss']) scalar_summary('losses/ae_loss', losses['ae_loss']) viz_img = [batch_pos, batch_incomplete, batch_complete] if offset_flow is not None: viz_img.append( resize(offset_flow, scale=4, func=tf.image.resize_nearest_neighbor)) images_summary( tf.concat(viz_img, axis=2), 'raw_incomplete_predicted_complete', config.VIZ_MAX_OUT) # gan batch_pos_neg = tf.concat([batch_pos, batch_complete], axis=0) # local deterministic patch local_patch_batch_pos_neg = tf.concat([local_patch_batch_pos, local_patch_batch_complete], 0) if config.GAN_WITH_MASK: batch_pos_neg = tf.concat([batch_pos_neg, tf.tile(mask, [config.BATCH_SIZE*2, 1, 1, 1])], axis=3) # wgan with gradient penalty if config.GAN == 'wgan_gp': # seperate gan pos_neg_local, pos_neg_global = self.build_wgan_discriminator(local_patch_batch_pos_neg, batch_pos_neg, training=training, reuse=reuse) pos_local, neg_local = tf.split(pos_neg_local, 2) pos_global, neg_global = tf.split(pos_neg_global, 2) # wgan loss g_loss_local, d_loss_local = gan_wgan_loss(pos_local, neg_local, name='gan/local_gan') g_loss_global, d_loss_global = gan_wgan_loss(pos_global, neg_global, name='gan/global_gan') losses['g_loss'] = config.GLOBAL_WGAN_LOSS_ALPHA * g_loss_global + g_loss_local losses['d_loss'] = d_loss_global + d_loss_local # gp interpolates_local = random_interpolates(local_patch_batch_pos, local_patch_batch_complete) interpolates_global = random_interpolates(batch_pos, batch_complete) dout_local, dout_global = self.build_wgan_discriminator( interpolates_local, interpolates_global, reuse=True) # apply penalty penalty_local = gradients_penalty(interpolates_local, dout_local, mask=local_patch_mask) penalty_global = gradients_penalty(interpolates_global, dout_global, mask=mask) losses['gp_loss'] = config.WGAN_GP_LAMBDA * (penalty_local + penalty_global) losses['d_loss'] = losses['d_loss'] + losses['gp_loss'] if summary and not config.PRETRAIN_COARSE_NETWORK: gradients_summary(g_loss_local, batch_predicted, name='g_loss_local') gradients_summary(g_loss_global, batch_predicted, name='g_loss_global') scalar_summary('convergence/d_loss', losses['d_loss']) scalar_summary('convergence/local_d_loss', d_loss_local) scalar_summary('convergence/global_d_loss', d_loss_global) scalar_summary('gan_wgan_loss/gp_loss', losses['gp_loss']) scalar_summary('gan_wgan_loss/gp_penalty_local', penalty_local) scalar_summary('gan_wgan_loss/gp_penalty_global', penalty_global) if summary and not config.PRETRAIN_COARSE_NETWORK: # summary the magnitude of gradients from different losses w.r.t. predicted image gradients_summary(losses['g_loss'], batch_predicted, name='g_loss') gradients_summary(losses['g_loss'], x1, name='g_loss_to_x1') gradients_summary(losses['g_loss'], x2, name='g_loss_to_x2') gradients_summary(losses['l1_loss'], x1, name='l1_loss_to_x1') gradients_summary(losses['l1_loss'], x2, name='l1_loss_to_x2') gradients_summary(losses['ae_loss'], x1, name='ae_loss_to_x1') gradients_summary(losses['ae_loss'], x2, name='ae_loss_to_x2') if config.PRETRAIN_COARSE_NETWORK: losses['g_loss'] = 0 else: losses['g_loss'] = config.GAN_LOSS_ALPHA * losses['g_loss'] losses['g_loss'] += config.L1_LOSS_ALPHA * losses['l1_loss'] logger.info('Set L1_LOSS_ALPHA to %f' % config.L1_LOSS_ALPHA) logger.info('Set GAN_LOSS_ALPHA to %f' % config.GAN_LOSS_ALPHA) if config.AE_LOSS: losses['g_loss'] += config.AE_LOSS_ALPHA * losses['ae_loss'] logger.info('Set AE_LOSS_ALPHA to %f' % config.AE_LOSS_ALPHA) g_vars = tf.get_collection( tf.GraphKeys.TRAINABLE_VARIABLES, 'inpaint_net') d_vars = tf.get_collection( tf.GraphKeys.TRAINABLE_VARIABLES, 'discriminator') return g_vars, d_vars, losses def build_infer_graph(self, batch_data, config, bbox=None, name='val'): """ """ config.MAX_DELTA_HEIGHT = 0 config.MAX_DELTA_WIDTH = 0 if bbox is None: bbox = random_bbox(config) mask = bbox2mask(bbox, config, name=name+'mask_c') batch_pos = batch_data / 127.5 - 1. edges = None batch_incomplete = batch_pos*(1.-mask) # inpaint x1, x2, offset_flow = self.build_inpaint_net( batch_incomplete, mask, config, reuse=True, training=False, padding=config.PADDING) if config.PRETRAIN_COARSE_NETWORK: batch_predicted = x1 logger.info('Set batch_predicted to x1.') else: batch_predicted = x2 logger.info('Set batch_predicted to x2.') # apply mask and reconstruct batch_complete = batch_predicted*mask + batch_incomplete*(1.-mask) # global image visualization viz_img = [batch_pos, batch_incomplete, batch_complete] if offset_flow is not None: viz_img.append( resize(offset_flow, scale=4, func=tf.image.resize_nearest_neighbor)) images_summary( tf.concat(viz_img, axis=2), name+'_raw_incomplete_complete', config.VIZ_MAX_OUT) return batch_complete def build_static_infer_graph(self, batch_data, config, name): """ """ # generate mask, 1 represents masked point bbox = (tf.constant(config.HEIGHT//2), tf.constant(config.WIDTH//2), tf.constant(config.HEIGHT), tf.constant(config.WIDTH)) return self.build_infer_graph(batch_data, config, bbox, name) def build_server_graph(self, batch_data, reuse=False, is_training=False): """ """ # generate mask, 1 represents masked point batch_pos , masks = tf.split(batch_data, 2, axis=2) masks = tf.cast(masks[0:1, :, :, 0:1]>0.5, tf.float32) # image to range in -1 and 1 batch_incomplete = batch_pos * (1. - masks) # inpaint x1, x2, flow = self.build_inpaint_net( batch_incomplete, masks, reuse=reuse, training=is_training, config=None) batch_predict = x2 # apply mask and reconstruct batch_complete = batch_predict*masks + batch_incomplete*(1-masks) return batch_complete
giuspuglREPO_NAMEpicassoPATH_START.@picasso_extracted@picasso-master@picasso@inpainters@generative_inpainting_model.py@.PATH_END.py
{ "filename": "ChaplyginCDMCosmology.py", "repo_name": "ja-vazquez/SimpleMC", "repo_path": "SimpleMC_extracted/SimpleMC-master/simplemc/models/ChaplyginCDMCosmology.py", "type": "Python" }
from simplemc.models.LCDMCosmology import LCDMCosmology from simplemc.cosmo.paramDefs import As_par, Calpha_par, Ok_par class ChaplyginCDMCosmology(LCDMCosmology): """ This is CDM cosmology with Chaplygin gas. This class inherits LCDMCosmology class as the rest of the cosmological models already included in SimpleMC. :param varyas: variable As parameter :param varyalpha: variable beta parameter """ def __init__(self, varyas=True, varyalpha=True, varyOk=False, fixOm=True): self.varyas = varyas self.varyalpha = varyalpha self.varyOk = varyOk self.Ok = Ok_par.value self.As = As_par.value self.alpha = Calpha_par.value LCDMCosmology.__init__(self, fixOm=fixOm) # my free parameters. We add Ok on top of LCDM ones (we inherit LCDM) def freeParameters(self): l = LCDMCosmology.freeParameters(self) if (self.varyas): l.append(As_par) if (self.varyalpha): l.append(Calpha_par) if (self.varyOk): l.append(Ok_par) return l def updateParams(self, pars): ok = LCDMCosmology.updateParams(self, pars) if not ok: return False for p in pars: if p.name == "as": self.As = p.value elif p.name == "alpha": self.alpha = p.value elif p.name == "Ok": self.Ok = p.value self.setCurvature(self.Ok) if (abs(self.Ok) > 1.0): return False return True # this is relative hsquared as a function of a ## i.e. H(z)^2/H(z=0)^2 def RHSquared_a(self, a): NuContrib = 0 #self.NuDensity.rho(a)/self.h**2 rhow = (self.As + (1-self.As)*a**(-3*(1+self.alpha))) return (self.Obh2/self.h**2/a**3 + self.Ok/a**2+self.Omrad/a**4+NuContrib+(1.0-self.Obh2/self.h**2-self.Ok)*rhow)
ja-vazquezREPO_NAMESimpleMCPATH_START.@SimpleMC_extracted@SimpleMC-master@simplemc@models@ChaplyginCDMCosmology.py@.PATH_END.py
{ "filename": "testSegmentSegmentIntersection.py", "repo_name": "LLNL/spheral", "repo_path": "spheral_extracted/spheral-main/tests/unit/Utilities/testSegmentSegmentIntersection.py", "type": "Python" }
#ATS:test(SELF, label="2-D line segment intersections unit tests") from Spheral2d import * from SpheralTestUtilities import * import unittest # Create a global random number generator. import random rangen = random.Random() #=============================================================================== # Test our various segement-segment intersection scenarios. #=============================================================================== class TestSegmentSegmentIntersection(unittest.TestCase): #=========================================================================== # Set up, create arrays of the function values. #=========================================================================== def setUp(self): self.ntests = 100 self.multMin = 0.001 self.multMax = 1.0e5 return #=========================================================================== # Randomly distort two line segments. #=========================================================================== def randomDistortion(self, a0, a1, b0, b1): T = (rangen.uniform(self.multMin, self.multMax)* rotationMatrix(Vector(rangen.uniform(0.0, 1.0), rangen.uniform(0.0, 1.0)).unitVector())) return T*a0, T*a1, T*b0, T*b1, T #=========================================================================== # Non-overlapping #=========================================================================== def testNonOverlappingSegments(self): a0 = Vector(1.0, 1.0) a1 = Vector(2.0, 2.0) b0 = Vector(1.0, 2.0) b1 = Vector(2.0, 3.0) for i in range(self.ntests): aa0, aa1, bb0, bb1, T = self.randomDistortion(a0, a1, b0, b1) assert segmentSegmentIntersection(aa0, aa1, bb0, bb1)[0] == '0' #=========================================================================== # Intersecting #=========================================================================== def testIntersectingSegments(self): a0 = Vector(1.0, 1.0) a1 = Vector(2.0, 2.0) b0 = Vector(1.0, 2.0) b1 = Vector(2.0, 1.0) for i in range(self.ntests): aa0, aa1, bb0, bb1, T = self.randomDistortion(a0, a1, b0, b1) code, result1, result2 = segmentSegmentIntersection(aa0, aa1, bb0, bb1) assert code == '1' assert result1 == result2 assert fuzzyEqual((result1 - T*Vector(1.5, 1.5)).magnitude(), 0.0) #=========================================================================== # Intersecting at endpoint #=========================================================================== def testIntersectingSegmentsOnEndpoint(self): a0 = Vector(1.0, 1.0) a1 = Vector(2.0, 2.0) b0 = Vector(1.0, 2.0) b1 = Vector(1.5, 1.5) for i in range(self.ntests): aa0, aa1, bb0, bb1, T = self.randomDistortion(a0, a1, b0, b1) code, result1, result2 = segmentSegmentIntersection(aa0, aa1, bb0, bb1) assert code == 'v' assert result1 == result2 assert fuzzyEqual((result1 - T*Vector(1.5, 1.5)).magnitude(), 0.0) #=========================================================================== # Overlapping segments. #=========================================================================== def testOverlappingSegments(self): a0 = Vector(1.0, 1.0) a1 = Vector(2.0, 2.0) b0 = Vector(3.0, 3.0) b1 = Vector(1.5, 1.5) for i in range(self.ntests): aa0, aa1, bb0, bb1, T = self.randomDistortion(a0, a1, b0, b1) code, result1, result2 = segmentSegmentIntersection(aa0, aa1, bb0, bb1) assert code == 'e' assert result1 != result2 if result1.magnitude2() > result2.magnitude2(): result1, result2 = result2, result1 assert fuzzyEqual((result1 - T*Vector(1.5, 1.5)).magnitude(), 0.0) assert fuzzyEqual((result2 - T*Vector(2.0, 2.0)).magnitude(), 0.0) if __name__ == "__main__": unittest.main()
LLNLREPO_NAMEspheralPATH_START.@spheral_extracted@spheral-main@tests@unit@Utilities@testSegmentSegmentIntersection.py@.PATH_END.py
{ "filename": "prompt.py", "repo_name": "langchain-ai/langchain", "repo_path": "langchain_extracted/langchain-master/libs/community/langchain_community/agent_toolkits/json/prompt.py", "type": "Python" }
# flake8: noqa JSON_PREFIX = """You are an agent designed to interact with JSON. Your goal is to return a final answer by interacting with the JSON. You have access to the following tools which help you learn more about the JSON you are interacting with. Only use the below tools. Only use the information returned by the below tools to construct your final answer. Do not make up any information that is not contained in the JSON. Your input to the tools should be in the form of `data["key"][0]` where `data` is the JSON blob you are interacting with, and the syntax used is Python. You should only use keys that you know for a fact exist. You must validate that a key exists by seeing it previously when calling `json_spec_list_keys`. If you have not seen a key in one of those responses, you cannot use it. You should only add one key at a time to the path. You cannot add multiple keys at once. If you encounter a "KeyError", go back to the previous key, look at the available keys, and try again. If the question does not seem to be related to the JSON, just return "I don't know" as the answer. Always begin your interaction with the `json_spec_list_keys` tool with input "data" to see what keys exist in the JSON. Note that sometimes the value at a given path is large. In this case, you will get an error "Value is a large dictionary, should explore its keys directly". In this case, you should ALWAYS follow up by using the `json_spec_list_keys` tool to see what keys exist at that path. Do not simply refer the user to the JSON or a section of the JSON, as this is not a valid answer. Keep digging until you find the answer and explicitly return it. """ JSON_SUFFIX = """Begin!" Question: {input} Thought: I should look at the keys that exist in data to see what I have access to {agent_scratchpad}"""
langchain-aiREPO_NAMElangchainPATH_START.@langchain_extracted@langchain-master@libs@community@langchain_community@agent_toolkits@json@prompt.py@.PATH_END.py
{ "filename": "lit.cfg.py", "repo_name": "tensorflow/tensorflow", "repo_path": "tensorflow_extracted/tensorflow-master/third_party/xla/xla/lit.cfg.py", "type": "Python" }
# Copyright 2019 The OpenXLA Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Lit runner configuration.""" import os import sys import tempfile import lit.formats # copybara:uncomment_begin(google-only) # from xla.lit_google_cfg import ENV_FLAGS as google_env_flags # copybara:uncomment_end # pylint: disable=undefined-variable extra_env_flags = [] # copybara:uncomment_begin(google-only) # extra_env_flags += google_env_flags # copybara:uncomment_end config.name = "XLA" config.suffixes = [".cc", ".hlo", ".json", ".mlir", ".pbtxt", ".py"] config.test_format = lit.formats.ShTest(execute_external=True) for env in [ # Passthrough XLA_FLAGS. "XLA_FLAGS", # Propagate environment variables used by 'bazel coverage'. # These are exported by tools/coverage/collect_coverage.sh "BULK_COVERAGE_RUN", "COVERAGE", "COVERAGE_DIR", "COVERAGE_MANIFEST", "LLVM_PROFILE_FILE", "LLVM_COVERAGE_FILE", "GCOV_PREFIX", "GCOV_PREFIX_STRIP", ] + extra_env_flags: value = os.environ.get(env) if value: config.environment[env] = value # Use the most preferred temp directory. config.test_exec_root = ( os.environ.get("TEST_UNDECLARED_OUTPUTS_DIR") or os.environ.get("TEST_TMPDIR") or os.path.join(tempfile.gettempdir(), "lit") ) config.substitutions.extend([ ("%PYTHON", os.getenv("PYTHON", sys.executable) or ""), ]) if lit_config.params.get("PTX") == "GCN": config.available_features.add("IS_ROCM") # Include additional substitutions that may be defined via params config.substitutions.extend( ("%%{%s}" % key, val) for key, val in lit_config.params.items() )
tensorflowREPO_NAMEtensorflowPATH_START.@tensorflow_extracted@tensorflow-master@third_party@xla@xla@lit.cfg.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "DariaGangardt/pAGN", "repo_path": "pAGN_extracted/pAGN-main/pagn/__init__.py", "type": "Python" }
from .__version__ import * from .Sirko import * from .Thompson import *
DariaGangardtREPO_NAMEpAGNPATH_START.@pAGN_extracted@pAGN-main@pagn@__init__.py@.PATH_END.py
{ "filename": "bumps.py", "repo_name": "NNSSA/GALLUMI_public", "repo_path": "GALLUMI_public_extracted/GALLUMI_public-main/Scripts/Plotting/Ultramassive_galaxies_(raw)/Pk_with_bumps/bumps.py", "type": "Python" }
import numpy as np from classy import Class import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt plt.style.use("scientific") colors = ['purple', '#306B37', 'darkgoldenrod', '#3F7BB6', '#BF4145', "#cf630a"] cosmo = Class() args = {'P_k_max_1/Mpc': 40., 'T_ncdm': 0.71611, 'N_ur': 2.0308, 'N_ncdm': 1, 'tau_reio': 0.0544, 'n_s': 0.9649 , 'k_pivot': 0.05, 'omega_b': 0.02236, 'm_ncdm': 0.06, 'h': 0.6727, 'z_max_pk': 10.0, 'output': 'mPk, dTk', 'omega_cdm': 0.1202, 'ln10^{10}A_s': 3.045} cosmo.set(args) cosmo.compute(['lensing']) # The Gaussian bump added to the power spectrum def Gaussian_bump(k, amp, mean, sigma): k1 = 0.5 if k < k1: return 0. return amp * np.exp(-(np.log(k) - mean)**2 / (2. * sigma**2)) # Calculate the mass variance manually intead from CLASS def pk(k_arr, pk, z, amp, mean, sigma): mps = np.vectorize(lambda y: pk(y, z) * (1. + Gaussian_bump(y, amp, mean, sigma))) return mps(k_arr) ####################### UVLF_2bins_1 = np.array([1.06, 67.09780887180366]) UVLF_2bins_1_xerror = np.array([[1.06-0.5], [2.25-1.06]]) UVLF_2bins_1_yerror = np.array([[14.456526986007667], [30.59404548201624]]) UVLF_2bins_2 = np.array([4.7, 1.2508772017466772]) UVLF_2bins_2_xerror = np.array([[4.7-2.25], [10-4.7]]) UVLF_2bins_2_yerror = np.array([[0.3417109173832944], [0.7688495641124118]]) ####################### plt.figure(figsize=(8.7,7)) ax = plt.subplot(111) ax.tick_params(axis='x', which='major', pad=6) plt.tick_params(axis='both', which='major', labelsize=25) plt.tick_params(axis='both', which='minor', labelsize=25) z = 8. k_array = np.geomspace(1e-2, 20., 1000) k_array2 = np.geomspace(2e-2, 0.5, 286) k_array3 = np.geomspace(6.5, 60., 250) offsets = np.linspace(-10, 10, 150) offsets2 = np.linspace(-10, 10, 50) sigma = 0.1 # plt.fill_between(k_array[k_array<0.5], np.repeat(0., len(k_array[k_array<0.5])), np.repeat(1e9, len(k_array[k_array<0.5])), facecolor="none", color="none", hatch="xx", edgecolor="gray", linewidth=0.0, zorder=-9, alpha=1.) plt.loglog(k_array[k_array<1], k_array[k_array<1]**3 * pk(k_array[k_array<1], cosmo.pk_cb_lin, z, 10., -0.58, sigma) / 2. / np.pi**2, color=colors[3], alpha=0.8, ls=(0,(2,1,2,1)), lw=2.5) plt.loglog(k_array[k_array>3], k_array[k_array>3]**3 * pk(k_array[k_array>3], cosmo.pk_cb_lin, z, 0.7, 1.5, sigma) / 2. / np.pi**2, color=colors[2], alpha=0.8, ls=(0,(2,1,2,1)), lw=2.5) plt.loglog(k_array, k_array**3 * pk(k_array, cosmo.pk_cb_lin, z, 2., 0.5, sigma) / 2. / np.pi**2, color="black", alpha=0.8, lw=2) plt.loglog(k_array, k_array**3 * pk(k_array, cosmo.pk_cb_lin, z, 0., 1., sigma) / 2. / np.pi**2, color="black", ls=(0,(1,1)), zorder=-9) N_samp = len(k_array2) step=10 alphas2 = [np.min([0.+(0.04*i)**2.3,1]) for i in range(int(N_samp/step))][::-1] alphas3 = [np.min([0.+(0.03*i)**2.3,1]) for i in range(int(N_samp/step))][::-1] for offset in offsets: [plt.loglog(k_array2[step*i:step*(i+2)], (k_array2[step*i:step*(i+2)])**1. * 10**offset, alpha=np.min([0.+(0.03*i)**2.3,1]), color="gray", lw=1, zorder=-9) for i in range(int(N_samp/step))] [plt.loglog(k_array2[step*i:step*(i+2)], (k_array2[step*i:step*(i+2)])**(-1.) * 10**(offset+0.273), alpha=np.min([0.+(0.04*i)**2.3,1]), color="gray", lw=1, zorder=-9) for i in range(int(N_samp/step))] [plt.loglog(k_array3[step*i:step*(i+2)], (k_array3[step*i:step*(i+2)])**(-1.) * 10**(offset+0.212), alpha=alphas3[numi], color="gray", lw=1, zorder=-9) for numi, i in enumerate(range(int(N_samp/step)))] [plt.loglog(k_array3[step*i:step*(i+2)], (k_array3[step*i:step*(i+2)])**(1.) * 10**(offset), alpha=alphas2[numi2], color="gray", lw=1, zorder=-9) for numi2, i in enumerate(range(int(N_samp/step)))] # for offset in offsets2: # [plt.loglog(k_array2[step*i:step*(i+1)], (k_array2[step*i:step*(i+1)])**(-4.) * 10**(offset+0.28), alpha=np.min([0.+(0.03*i)**2,1]), color="gray", lw=1, zorder=-9) for i in range(int(N_samp/step))] plt.annotate('', xytext=(1.8, 0.67), xy=(4., 0.5), arrowprops={'arrowstyle': '-|>', 'lw':1.3, 'color': "black"}, color="black") plt.annotate('', xytext=(0.67, 0.949), xy=(1.5, 0.71), arrowprops={'arrowstyle': '<|-', 'lw':1.3, 'color': "black"}, color="black") plt.annotate('', xytext=(1.24, 1.48), xy=(1.24, 0.83), arrowprops={'arrowstyle': '-|>', 'lw':1., 'color': colors[3]}, color=colors[3]) plt.annotate('', xytext=(3.1, 1.1), xy=(3.1, 0.63), arrowprops={'arrowstyle': '<|-', 'lw':1., 'color': colors[2]}, color=colors[2]) # plt.errorbar(UVLF_2bins_1[0], UVLF_2bins_1[1], xerr=UVLF_2bins_1_xerror, yerr=UVLF_2bins_1_yerror, ls="None", marker=".", markersize=5, markeredgewidth=1.5, elinewidth=1.5, color="black", label=r"$\mathrm{UV\ LF\ (this\ work)}$", zorder=10) # plt.errorbar(UVLF_2bins_2[0], UVLF_2bins_2[1], xerr=UVLF_2bins_2_xerror, yerr=UVLF_2bins_2_yerror, ls="None", marker=".", markersize=5, markeredgewidth=1.5, elinewidth=1.5, color="black", zorder=10) ax.text(7.5, 0.052, r'$f_\star > 1$', weight='bold', fontsize=26, color="black", zorder=12, alpha=0.75, rotation=-30.8) ax.text(0.07, 0.049, r'$\mathrm{Other\ Cosmic}$', weight='bold', fontsize=26, color="black", zorder=12, alpha=0.75, rotation=-28.3) ax.text(0.1, 0.05, r'$\mathrm{Data}$', weight='bold', fontsize=26, color="black", zorder=12, alpha=0.75, rotation=-28.3) ax.text(0.624, 7.3e-3, r'$\mathrm{Hubble}$', weight='bold', fontsize=26, color="black", zorder=6, alpha=0.6) ax.text(0.59, 4e-3, r'$\mathrm{UV\ LFs}$', weight='bold', fontsize=26, color="black", zorder=6, alpha=0.6) ax.text(0.88, 1.04, r'$f_\star$', weight='bold', fontsize=23, color=colors[3], zorder=6) ax.text(2.2, 0.756, r'$f_\star$', weight='bold', fontsize=23, color=colors[2], zorder=6) lines = np.geomspace(0.1, 10, 1000) alphas = np.sin(np.linspace(0., np.pi/2, int(len(lines)/2))) alphas = np.concatenate((alphas, alphas[::-1])) for numline, line in enumerate(lines): plt.axvline(line, alpha=alphas[numline], lw=1.5, color="#dadada", zorder=-10) plt.ylabel(r'$\Delta^2_\mathrm{m}(z = 8)$', fontsize=27) plt.xlabel(r'$k\ \mathrm{[}\mathrm{Mpc^{-1}]}$', fontsize=27) plt.semilogx() plt.semilogy() plt.xlim(5e-2, 20.) plt.ylim(1e-3, 1e1) plt.savefig("pk_with_bumps.pdf")
NNSSAREPO_NAMEGALLUMI_publicPATH_START.@GALLUMI_public_extracted@GALLUMI_public-main@Scripts@Plotting@Ultramassive_galaxies_(raw)@Pk_with_bumps@bumps.py@.PATH_END.py
{ "filename": "get_objects.py", "repo_name": "GalSim-developers/GalSim", "repo_path": "GalSim_extracted/GalSim-main/devel/external/AEGIS/get_objects.py", "type": "Python" }
# Copyright (c) 2012-2023 by the GalSim developers team on GitHub # https://github.com/GalSim-developers # # This file is part of GalSim: The modular galaxy image simulation toolkit. # https://github.com/GalSim-developers/GalSim # # GalSim is free software: redistribution and use in source and binary forms, # with or without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions, and the disclaimer given in the accompanying LICENSE # file. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions, and the disclaimer given in the documentation # and/or other materials provided with the distribution. # """ Program Number: 1 Program to detect objects in a given image (segment) and make a catalog using sextractor. Objects are detected with the Hot-Cold method employed in Rix et al.(2004). Requirements: SExtractor Detection: SExtractor is run in double image mode, with objects detected in det_im_file & det_wht_file as weight map. These detected objects are then measures in each band(file_name, wht_name). SExtractor WEIGHT_TYPE is set with wht_type and det_wht_type for detection and measurement respectively. The config parameters for Hot-Cold detetction are preset and not input parametrs. The hot(faint) objects are merged with the cold(bright) catalog that aren't within buffer region --buffer. Cleanup: Since the noise in the image is not uncorrelated (dut to multidrizzle), the snr computed from sextractor needs to be modified by parameter scale factr --sf. The magnitudes computed by SExtractor have to be corrected for dust extinction. The correction function correct_extinction() in functions.py would have to be modified when running script on a survey other then AEGIS. The detected objects are then classified into stars and galaxies depending on their position in the magnitude Vs peak surface brightness plot. The separation line is set by star_galaxy_params. Objects that lie on image edge are masked. Region around saturated stars are masked: masked region set by diff_spike_params. Regions that were manually observed to have artefacts (eg.ghosts) and are to be masked are input as manual_mask_file. final catalog is renumbered begining from 0. Bright and faint seg maps are combined to form a single segmentation map. The bright seg map objects are expanded by 10 pixels. Note: Value of object in seg map will be 1 higher than NUMBER in catalog. Catalog numbers start at 0, while 0 in segmap is no object present. Stars for PSF estimation: Select upto 25 stars with the highest SNR that are not masked. If they are detected as stars in all bands, have an image in tt_starfield within 200 pixels, and do not have any other objects nearby, they are saved to a list for PSF estimation. Postage stamps of these stars are also saved for manual inspection. Output: Cleaned catalog, combined segmentation map, list of stars for PSF measurement and postage stamp images of those stars. """ import asciidata import subprocess import pyfits import os import numpy as np import functions as fn import clean_pstamp as cp from astropy.table import Table, Column, vstack class Main_param: """Class containing parameters to pass to run analysis on each segment file. it adds path name in front of file name and replace seg_id names and filter names. """ def __init__(self, args): self.seg_id = args.seg_id self.file_name = args.file_name.replace('seg_id', self.seg_id) self.wht_name = args.wht_name.replace('seg_id', self.seg_id) self.det_im_file = args.det_im_file.replace('seg_id', self.seg_id) self.det_wht_file = args.det_wht_file.replace('seg_id', self.seg_id) self.filters = args.filter_names self.out_path = args.out_path self.tt_file_path = args.tt_file_path self.sf = args.sf self.wht_type = args.wht_type self.det_wht_type = args.det_wht_type self.manual_mask_file = args.manual_mask_file self.buffer = args.buffer # making weight maps rms if args.file_path[-1] != '/': self.file_path = args.file_path + '/' else: self.file_path = args.file_path if args.wht_path[-1] != '/': self.wht_path = args.wht_path + '/' else: self.wht_path = args.wht_path self.spike_params, self.zero_point_mag = {}, {} self.gain, self.star_galaxy_params = {}, {} self.data_files, self.wht_files = {}, {} for i in range(len(self.filters)): filter1 = self.filters[i] self.data_files[filter1] = self.file_path + filter1 + '/' + self.file_name.replace('filter', filter1) self.wht_files[filter1] = self.wht_path + filter1 + '/' + self.wht_name.replace('filter', filter1) self.spike_params[filter1] = args.diff_spike_params[i] self.zero_point_mag[filter1] = args.zero_point_mag[i] self.star_galaxy_params[filter1] = args.star_galaxy_params[i] self.gain[filter1] = args.gain[i] self.det_im_file = self.file_path + self.det_im_file self.det_wht_file = self.wht_path + self.det_wht_file def run_segment(params): """Find objects in individual segments. Runs SExtractor on a segment and stores the detected objects in .cat file SExtractor input settings stored in .config file. Parameters to be measured by SExtractor are written to sex.param file. Detecting objects, Hot/Cold method : 1) SExtractor is run in dual image mode, detecting in co-added image and measuring in individual filter images to give their corresponding *_brigt.cat detected images. 2) Same step repeated with faint_config_dict SExtractor parameters and detected objects saved in .*_faint.cat. 3) Segmentation map is made for each of the _bright.cat files with regions belonging to bright objects expaned by 15 pixels. 4) Filter faint catalog: Removes objects in *_faint.cat that are masked in the segmentation map for all filters. O/p is *_filteredfaint.cat 5) Merges bright and filtered faint catalogs to give catalog of all objects. """ cat = GalaxyCatalog(params) cat.generate_catalog() class GalaxyCatalog: """Parameters to be measured by SExtractor.""" output_params = ["NUMBER", "X_IMAGE", "Y_IMAGE", "A_IMAGE", "B_IMAGE", "ALPHA_J2000", "DELTA_J2000", "XMIN_IMAGE", "XMAX_IMAGE", "YMIN_IMAGE", "YMAX_IMAGE", "FLAGS", "MU_MAX", "MAG_AUTO", "MAGERR_AUTO", "MAG_BEST", "MAGERR_BEST", "CLASS_STAR", "FLUX_RADIUS", "FLUX_AUTO", "FLUXERR_AUTO", "KRON_RADIUS", "THETA_IMAGE", "ELLIPTICITY"] # SExtractor input config values for bright object detection bright_config_dict = {'DETECT_MINAREA': 140, 'DETECT_THRESH': 2.2, 'DEBLEND_NTHRESH': 64, 'DEBLEND_MINCONT': 0.04, 'CLEAN_PARAM': 1.0, 'BACK_SIZE': 400, 'BACK_FILTERSIZE': 5, 'BACKPHOTO_TYPE': "LOCAL", 'BACKPHOTO_THICK': 200, 'PIXEL_SCALE': 0.03} # SExtractor input config values for faint object detection faint_config_dict = {'DETECT_MINAREA': 18, 'DETECT_THRESH': 1.0, 'DEBLEND_NTHRESH': 64, 'DEBLEND_MINCONT': 0.065, 'CLEAN_PARAM': 1.0, 'BACK_SIZE': 100, 'BACK_FILTERSIZE': 3, 'BACKPHOTO_TYPE': "LOCAL", 'BACKPHOTO_THICK': 200, 'PIXEL_SCALE': 0.03} def __init__(self, params): self.params = params def get_sex_op_params(self, out_dir): """Saves the names of parameters thet SExtractor must save""" param_fname = 'sex_out.param' try: param_file = open(out_dir + '/' + param_fname, 'w') except: subprocess.call(["mkdir", out_dir]) param_file = open(out_dir + '/' + param_fname, 'w') print out_dir for i in range(len(self.output_params)): param_file.write(self.output_params[i]) param_file.write("\n") param_file.close() def run_sextractor_dual(self, data_files, wht_files, use_dict, out_dir, out_name, filt): """ Runs sextractor in dual image mode""" print "Running dual:", out_name # Create config newfiles[i] and write out to a file config_ascii = asciidata.create(2, 8 + len(use_dict)) # File-Specific Configurations config_ascii[0][0] = 'CATALOG_NAME' config_ascii[1][0] = out_dir + '/' + out_name + ".cat" config_ascii[0][1] = 'PARAMETERS_NAME' config_ascii[1][1] = out_dir + "/sex_out.param" config_ascii[0][2] = 'WEIGHT_TYPE' config_ascii[1][2] = str(self.params.wht_type + ',' + self.params.det_wht_type) config_ascii[0][3] = 'WEIGHT_IMAGE' config_ascii[1][3] = str(wht_files[0] + ',' + wht_files[1]) row_counter = 4 for key, value in use_dict.iteritems(): config_ascii[0][row_counter] = key config_ascii[1][row_counter] = value row_counter += 1 config_ascii[0][row_counter] = 'CHECKIMAGE_NAME' config_ascii[1][row_counter] = out_dir + '/' + out_name + "_seg_map.fits" config_ascii[0][row_counter + 1] = 'CHECKIMAGE_TYPE' config_ascii[1][row_counter + 1] = 'SEGMENTATION' config_ascii[0][row_counter + 2] = 'MAG_ZEROPOINT' config_ascii[1][row_counter + 2] = self.params.zero_point_mag[filt] config_ascii[0][row_counter + 3] = 'GAIN' config_ascii[1][row_counter + 3] = self.params.gain[filt] config_fname = out_dir + '/' + out_name + ".config" config_ascii.writeto(config_fname) # Run sextractor and get the catalog subprocess.call(["sex", data_files[0] + "," + data_files[1], "-c", config_fname]) def add_bright_faint_column(self, cat_name, tag): """Add coloumn 'IS_BRIGHT' in catalog with name cat_name.value of column is to tag. """ catalog = Table.read(cat_name, format="ascii.sextractor") col = Column(np.ones(len(catalog)) * tag, name='IS_BRIGHT', dtype='int', description='Detected in hot mode') catalog.add_column(col) return catalog def make_new_seg(self, seg_map, out_dir, out_name): """Expands bright seg map objects by params.buffer pixels """ data = pyfits.open(seg_map)[0].data new_seg = fn.seg_expand(data, buff=self.params.buffer) new_name = out_dir + '/' + out_name + "_bright_seg_map_new.fits" if os.path.isfile(new_name) is True: subprocess.call(["rm", new_name]) pyfits.writeto(new_name, new_seg) def filter_cat_with_segmentation_map(self, faint_catalog, seg_map, out_dir, out_name): """Removes objects from the faint catalog that lie within the bright segmentation map. This is to remove multiple detections of bright objects. """ print "Filtering faint objects for section ", self.params.seg_id segmentation_file = pyfits.open(seg_map) data = segmentation_file[0].data fc = faint_catalog val = [i for i in range(len(fc)) if (data[int(fc['Y_IMAGE'][i]), int(fc['X_IMAGE'][i])] == 0)] new_catalog = faint_catalog[val] name = out_dir + '/' + out_name + "_filteredfaint.cat" new_catalog.write(name, format="ascii.basic") def merge(self, filtered_faint_catalog, bright_catalog, filt, out_dir): """ Merge objects detected in bright and filtered faint catalog. Extinction correction to magnitude is also applied here. """ print "Merging bright and faint catalogs for section", self.params.seg_id name = out_dir + '/' + filt + "_merge.cat" faint_cat = Table.read(filtered_faint_catalog, format="ascii.basic") bright_cat = Table.read(bright_catalog, format="ascii.basic") comb_cat = vstack([bright_cat, faint_cat]) # Correct magntiude for extinction corr_mag = fn.correct_extinction(comb_cat['MAG_AUTO'], filt) col = Column(corr_mag, name='MAG_CORR', description='Extinction corrected MAG_AUTO') comb_cat.add_column(col) comb_cat.write(name, format="ascii.basic") def classification(self, div_params, out_dir): """Detected objects are classified as stars or not depending on their magnitude and peak surface brightnes.""" x_max = 25.2 print "Performing star-galaxy separation for section ", self.params.seg_id for filt in self.params.filters: x_div = div_params[filt][0] y_div = div_params[filt][1] slope = div_params[filt][2] intercept = y_div - slope * x_div out_name = filt merged_catalog = out_dir + '/' + out_name + "_merge.cat" catalog = Table.read(merged_catalog, format="ascii.basic") snr = np.array(catalog['FLUX_AUTO']) / np.array(catalog['FLUXERR_AUTO']) col = Column(snr, name='SNR', description='Signal to Noise Ratio') catalog.add_column(col) # Modified SNR: Correcting of correlations in noise. A = catalog['FLUXERR_AUTO']**2 - catalog['FLUX_AUTO'] / self.params.gain[filt] new_f_err = (A / self.params.sf + catalog['FLUX_AUTO'] / self.params.gain[filt])**0.5 col = Column(new_f_err, name='NEW_FLUXERR_AUTO', description='Modified FLUXERR_AUTO') catalog.add_column(col) new_snr = np.array(catalog['FLUX_AUTO']) / new_f_err col = Column(new_snr, name='NEW_SNR', description='Modified Signal to Noise Ratio') catalog.add_column(col) col = Column(np.zeros(len(catalog)), name='IS_STAR', dtype='int') catalog.add_column(col) q = fn.is_below_boundary_table(catalog['MAG_CORR'], catalog['MU_MAX'], x_div, y_div, slope, intercept, x_max) catalog['IS_STAR'][q] = 1 col = Column(np.zeros(len(catalog)), name='IS_FAKE', dtype='int') catalog.add_column(col) q = fn.is_below_boundary_table(catalog['MAG_CORR'], catalog['MU_MAX'], x_div + 1, y_div - 2, slope, intercept - 2, x_max + 1) catalog['IS_FAKE'][q] = 1 catalog.write(out_dir + '/' + out_name + "_class.cat", format="ascii.basic") def remove_edge(self, catalog): """Remove objects lying on the image plane edge.""" print "Removing edge objects" A = (390., 321.) B = (498., 6725.) C = (6898., 7287.) D = (7002., 806.) x_min = catalog['XMIN_IMAGE'] x_max = catalog['XMAX_IMAGE'] y_min = catalog['YMIN_IMAGE'] y_max = catalog['YMAX_IMAGE'] val = np.zeros(len(catalog)) val[fn.lies_within_table(x_min, x_max, y_min, y_max, A, B, C, D)] = 1 col = Column(val, name='IN_BOUNDARY', description="Inside a masked region", dtype=int) catalog.add_column(col) return catalog def diffraction_mask_cleanup(self, catalog, diff_spike_params, mag_cutoff=19.0): """Masks objects within diffraction spikes of saturated stars.""" m = diff_spike_params[0] # slope b = diff_spike_params[1] # intercept w = diff_spike_params[2] * 0.5 # width theta = diff_spike_params[3] # angle val = np.zeros(len(catalog)) col = Column(val, name='IN_DIFF_MASK', description="Close to saturated star", dtype=int) catalog.add_column(col) print "Identifying saturated stars" cond1 = catalog['MAG_CORR'] < mag_cutoff cond2 = catalog['IS_STAR'] == 1 q, = np.where(cond1 & cond2) # exit if no saturated stars present if len(q) == 0: print 'No saturated objects found' return catalog x0 = catalog['X_IMAGE'][q] y0 = catalog['Y_IMAGE'][q] r = np.mean([catalog['A_IMAGE'][q], catalog['B_IMAGE'][q]]) * 5 flux = catalog['FLUX_AUTO'][q] l = m * flux + b x_vertices = np.array([x0-w,x0-w,x0+w,x0+w,x0+r,x0+l,x0+l,x0+r,x0+w,x0+w,x0-w,x0-w,x0-r,x0-l,x0-l,x0-r]) y_vertices = np.array([y0+r,y0+l,y0+l,y0+r,y0+w,y0+w,y0-w,y0-w,y0-r,y0-l,y0-l,y0-r,y0-w,y0-w,y0+w,y0+w]) (x_vertices, y_vertices) = fn.rotate_table(x_vertices, y_vertices, x0, y0, theta) catalog['IN_DIFF_MASK'][q] = 1 print "Identify objects in diffraction spike" Xs = np.array([catalog['XMIN_IMAGE'], catalog['XMAX_IMAGE']], dtype=int) Ys = np.array([catalog['YMIN_IMAGE'], catalog['YMAX_IMAGE']], dtype=int) bottom_pixels = [[(x, Ys[0][i]) for x in range(Xs[0][i],Xs[1][i])]for i in range(len(catalog))] top_pixels = [[(x, Ys[1][i]) for x in range(Xs[0][i], Xs[1][i])]for i in range(len(catalog))] left_pixels = [[(Xs[0][i], y) for y in range(Ys[0][i], Ys[1][i])]for i in range(len(catalog))] right_pixels = [[(Xs[1][i], y) for y in range(Ys[0][i], Ys[1][i])]for i in range(len(catalog))] for i in range(len(catalog)): pixels = bottom_pixels[i] + left_pixels[i] + top_pixels[i] + right_pixels[i] bools = [fn.inpoly(pixel[0], pixel[1], x_vertices.T[j], y_vertices.T[j]) for pixel in pixels for j in range(len(x_vertices.T))] if max(bools) == 1: catalog['IN_DIFF_MASK'][i] = 1 return catalog def manual_mask_cleanup(self, catalog, filt): """Masks regions that were observed to have artefacts upon visual inspection""" val = np.zeros(len(catalog)) col = Column(val, name='IN_MANUAL_MASK', description="In a manual mask region", dtype=int) catalog.add_column(col) mask_tab = Table.read(self.params.manual_mask_file, format='ascii.basic') q, = np.where((self.params.seg_id == mask_tab['SEG']) & (filt == mask_tab['FILTER'])) if len(q) == 0: return catalog else: for m in q: x_vertices = np.array([mask_tab['AX'][m], mask_tab['BX'][m], mask_tab['CX'][m], mask_tab['DX'][m]]) y_vertices = np.array([mask_tab['AY'][m], mask_tab['BY'][m], mask_tab['CY'][m], mask_tab['DY'][m]]) Xs = np.array([catalog['XMIN_IMAGE'], catalog['XMAX_IMAGE']], dtype=int) Ys = np.array([catalog['YMIN_IMAGE'], catalog['YMAX_IMAGE']], dtype=int) bottom_pixels = [[(x, Ys[0][i]) for x in range(Xs[0][i],Xs[1][i])]for i in range(len(catalog))] top_pixels = [[(x, Ys[1][i]) for x in range(Xs[0][i], Xs[1][i])]for i in range(len(catalog))] left_pixels = [[(Xs[0][i], y) for y in range(Ys[0][i], Ys[1][i])]for i in range(len(catalog))] right_pixels = [[(Xs[1][i], y) for y in range(Ys[0][i], Ys[1][i])]for i in range(len(catalog))] for i in range(len(catalog)): pixels = bottom_pixels[i] + left_pixels[i] + top_pixels[i] + right_pixels[i] bools = [fn.inpoly(pixel[0], pixel[1], x_vertices, y_vertices) for pixel in pixels] if max(bools) == 1: catalog['IN_MANUAL_MASK'][i] = 1 return catalog def combine_seg_map(self, filt, out_dir): """Combines bright and faint segmentation maps. Regions belonging to bright objects are expanded by 5 pixels""" cat_name = out_dir + '/' + filt + '_clean.cat' bright_name = out_dir + '/' + filt + '_bright_seg_map.fits' faint_name = out_dir + '/' + filt + '_faint_seg_map.fits' hdu1 = pyfits.open(bright_name) hdu2 = pyfits.open(faint_name) br = hdu1[0].data ft = hdu2[0].data hdu2.close() hdu1.close() cat = Table.read(cat_name, format='ascii.basic') new_seg = br # Expand bright regions by 5 pixels q, = np.where(cat['IS_BRIGHT'] == 1) for i in q: new_seg = fn.seg_expand(new_seg, buff=5, val=int(i) + 1, set_to=int(i) + 1) # +1 to account for renumbering q, = np.where(cat['IS_BRIGHT'] == 0) s = ft.shape for i in q: for j in range(s[0]): pix, = np.where((ft[j, :] == cat['OLD_NUMBER'][i]) & (new_seg[j, :] == 0)) new_seg[j][pix] = cat['NUMBER'][i] + 1 new_seg_name = out_dir + '/' + filt + '_comb_seg_map.fits' print "Bright faint combined seg map created at", new_seg_name pyfits.writeto(new_seg_name, new_seg, clobber=True) os.remove(bright_name) os.remove(faint_name) def cleanup_catalog(self, out_dir): """Removes objects on boundaries, diffraction spikes, manual mask""" for filt in self.params.filters: print "Clean up in in filter", filt out_name = filt class_catalog = out_dir + '/' + out_name + "_class.cat" catalog = Table.read(class_catalog, format="ascii.basic") # Remove objects near edges catalog = self.remove_edge(catalog) # remove objects in diffraction spike diff_spike_params = self.params.spike_params[filt] # magnitude cutoff of saturated stars is the horizontal line # in star-galaxy separation line mag_cutoff = self.params.star_galaxy_params[filt][0] catalog = self.diffraction_mask_cleanup(catalog, diff_spike_params, mag_cutoff=mag_cutoff) # remove objects in manual mask catalog = self.manual_mask_cleanup(catalog, filt) catalog = fn.renumber_table(catalog) catalog = fn.mask_it_table(catalog) # add columns to catalog that will be useful later col = Column(np.zeros(len(catalog)), name='MULTI_DET', dtype='int', description='detected in another segment') catalog.add_column(col) col = Column(['aa.0000000'] * len(catalog), name='MULTI_DET_OBJ', dtype='S12', description='object id kept') catalog.add_column(col) col = Column([filt.upper()] * len(catalog), name='BAND', description='measurement filter') catalog.add_column(col) catalog.write(out_dir + '/' + out_name + "_clean.cat", format="ascii.basic") # Make combined seg map self.combine_seg_map(filt, out_dir) def check_oth_obj(self, x0, y0, r, filt, idx, out_dir): """Checks if other objects are close to stars picked for PSF estimation""" seg_name = out_dir + '/' + filt +'_comb_seg_map.fits' seg_im = fn.get_subImage_pyfits(int(x0), int(y0), [int(r)] * 8, seg_name, None, None, save_img=False) shape = seg_im.shape num = seg_im[shape[0] / 2, shape[1] / 2] im, bl, oth, oth_segs, check = cp.div_pixels(seg_im, -1) if len(oth_segs) > 1: print "Multiple objects in star stamp for star {0}, object{1}".format(idx, oth_segs) return False return True def match_to_tt(self, catalog, out_dir, filt, best_stars, dist=200.): """Finds closest tiny tim PSF image in the tt_starfiled for each star""" tt_stars = self.params.tt_file_path + "/" + filt + "/{}_stars.txt".format(filt) print 'tt stars', tt_stars tt_table = np.loadtxt(tt_stars) # Center and size of stars in catalog. x0 = catalog['X_IMAGE'][best_stars] y0 = catalog['Y_IMAGE'][best_stars] r = catalog['FLUX_RADIUS'][best_stars] # Center of tiny tim stars. x = tt_table.T[0] y = tt_table.T[1] mult = np.ones([len(best_stars), 1]) x1 = x * mult y1 = y * mult mult = np.ones([len(x), 1]) x01 = x0 * mult y01 = y0 * mult d = ((x1 - x01.T)**2 + (y1 - y01.T)**2)**0.5 best = np.argmin(d, axis=1) check_oth = [] for i, idx in enumerate(best_stars): val = self.check_oth_obj(x0[i], y0[i], r[i], filt, idx, out_dir) check_oth.append(val) q = np.where((abs(x0 - x[best]) < dist) & (abs(y0 - y[best]) < dist) & check_oth) tt_best = best[q] matched_stars = np.array([best_stars[q], x0[q], y0[q], r[q], x[tt_best], y[tt_best]]) file_name = out_dir + '/' + filt + '_matched_stars.txt' np.savetxt(file_name, matched_stars) return matched_stars.T def check_stars(self, best_stars, filt, out_dir): """Checks if the stars selected for PSF estimation are detected as stars in all filters. If not then it removes them from the list.""" filter_list = list(self.params.filters) filter_list.remove(filt) for check_filter in filter_list: print 'Check strars from {0} in {1}'.format(filt, check_filter) cat_name = out_dir + '/' + check_filter + "_clean.cat" catalog = Table.read(cat_name, format="ascii.basic") select_stars = best_stars remove_stars = [] for i, idx in enumerate(select_stars): if catalog['IS_STAR'][np.int(idx)] == 0: remove_stars.append(i) select_stars = np.delete(best_stars, remove_stars, axis=0) return select_stars def stars_for_focus(self, out_dir): """Makes postage stamps of stars. Ordered in decreasing highest SNR""" for filt in self.params.filters: cat_name = out_dir + '/' + filt + "_clean.cat" print "Making postage stamps of stars in filter ", cat_name catalog = Table.read(cat_name, format="ascii.basic") # get indices of stars with highest SNR best_stars = fn.select_good_stars_table(catalog) select_stars = self.check_stars(best_stars, filt, out_dir) matched_stars = self.match_to_tt(catalog, out_dir, filt, select_stars) print 'Number of stars selected', len(select_stars) num = 0 for i in range(len(matched_stars)): x0 = matched_stars[i][1] y0 = matched_stars[i][2] stamp_size = matched_stars[i][3] * 8 image = self.params.data_files[filt] dir_star = out_dir + '/stars/' out_name = filt + '_' + str(int(matched_stars[i][0])) # Save image of selected stars sub = fn.get_subImage(int(x0), int(y0), int(stamp_size), image, dir_star, out_name, save_img=True) num += 1 def generate_catalog(self): # create o/p folder if doesn't exist if os.path.isdir(self.params.out_path) is False: subprocess.call(["mkdir", self.params.out_path]) print "CREATING output folder" out_dir = self.params.out_path + '/' + self.params.seg_id print "Printing outdir", out_dir # create file taht lists o/p required from SExtractor self.get_sex_op_params(out_dir) # Detection done on given added image for filt in self.params.filters: print "Measuring on filter", filt data_files = [self.params.det_im_file, self.params.data_files[filt]] wht_files = [self.params.det_wht_file, self.params.wht_files[filt]] # Create Bright catalog# print 'Sextractor input data files', data_files, wht_files self.run_sextractor_dual(data_files, wht_files, self.bright_config_dict, out_dir, filt + "_bright", filt) # Create Faint catalog# self.run_sextractor_dual(data_files, wht_files, self.faint_config_dict, out_dir, filt + "_faint", filt) out_name = filt bright_catalog_name = out_dir + '/' + filt + "_bright.cat" bright_catalog = self.add_bright_faint_column(bright_catalog_name, 1) bright_catalog.write(bright_catalog_name, format="ascii.basic") faint_catalog_name = out_dir + '/' + filt + "_faint.cat" faint_catalog = self.add_bright_faint_column(faint_catalog_name, 0) seg_map = out_dir + '/' + out_name + "_bright_seg_map.fits" self.make_new_seg(seg_map, out_dir, filt) new_seg_map = out_dir + '/' + filt + "_bright_seg_map_new.fits" self.filter_cat_with_segmentation_map(faint_catalog, new_seg_map, out_dir, filt) filtered_faint_name = out_dir + '/' + filt + "_filteredfaint.cat" # Merge filtered faint catalog and bright catalog self.merge(filtered_faint_name, bright_catalog_name, out_name, out_dir) os.remove(new_seg_map) # star-galaxy seperation self.classification(self.params.star_galaxy_params, out_dir) # Mark objects at the boundary and in diffraction spikes self.cleanup_catalog(out_dir) # pick stars for PSF estimation self.stars_for_focus(out_dir) if __name__ == '__main__': from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('--seg_id', default='1a', help="Segment id of image to run [Default:1a]") parser.add_argument('--filter_names', default=['f606w', 'f814w'], help="names of filters [Default: ['f606w','f814w']]") parser.add_argument('--file_path', default='/nfs/slac/g/ki/ki19/deuce/AEGIS/unzip/', help="Path of directory containing input images \ [Default:'/nfs/slac/g/ki/ki19/deuce/AEGIS/unzip] ") parser.add_argument('--wht_path', default='/nfs/slac/g/ki/ki19/deuce/AEGIS/unzip', help="Path of directory containing weight files \ [Default:'/nfs/slac/g/ki/ki19/deuce/AEGIS/unzip] ") parser.add_argument('--out_path', default='/nfs/slac/g/ki/ki19/deuce/AEGIS/AEGIS_catalog_full/', help="Path to where you want the output stored \ [Default: /nfs/slac/g/ki/ki19/deuce/AEGIS/AEGIS_catalog_full/]") parser.add_argument('--file_name', default='EGS_10134_seg_id_acs_wfc_filter_30mas_unrot_drz.fits', help="File name of measurement image with 'seg_id' & \ 'filter' in place of image segment id and filter \ [Default:'EGS_10134_seg_id_acs_wfc_f606w_30mas_unrot_drz.fits']") parser.add_argument('--wht_name', default='EGS_10134_seg_id_acs_wfc_filter_30mas_unrot_rms.fits', help="Name of weight map of measurement image with 'seg_id' \ and 'filter' in place of image segment id and filter \ [Default:'EGS_10134_seg_id_acs_wfc_filter_30mas_unrot_rms.fits']") parser.add_argument('--det_im_file', default='added/EGS_10134_seg_id_acs_wfc_30mas_unrot_added_drz.fits', help="File name of image to run detection on with '\ 'seg_id' in place of image segment id. \ [Default:'added/EGS_10134_seg_id_acs_wfc_30mas_unrot_added_drz.fits']") parser.add_argument('--det_wht_file', default='added/EGS_10134_seg_id_acs_wfc_30mas_unrot_added_rms.fits', help="Weight file name of image of image used in detection with ' \ 'seg_id' in place of image segment id. \ [Default:'added/EGS_10134_seg_id_acs_wfc_30mas_unrot_added_rms.fits']") parser.add_argument('--wht_type', default='MAP_RMS', help="SExtractor Weight file type for measurement image. \ Default='MAP_RMS'") parser.add_argument('--det_wht_type', default='MAP_RMS', help="SExtractor Weight file type for detection image. \ Default='MAP_RMS'") parser.add_argument('--buffer', default=15, help="Number of pixels used as buffer around bright \ objects in Hot-cold detection method.[Default:15(pixels)]") parser.add_argument('--diff_spike_params', default=[(0.0441087, 81.0863, 15.0, 2.614), (0.0448020, 92.7674, 15.0, 2.180)], help="Params of diffraction spikes in each filter. \ They must be in the same order as filter_names. \ [slope(pixels/ADU),intercept(pixels),width(pixels),angle(degrees)] \ [Default: [(0.0350087,64.0863,40.0,2.614), \ (0.0367020,77.7674,40.0,2.180)]]") parser.add_argument('--star_galaxy_params', default=[(19.95, 16.17, 0.945), (18.95, 15.11, 0.98)], help="Star galaxy seperation line parametrs \ [Default:(x_div, y_div, slope)]") parser.add_argument('--zero_point_mag', default=(26.508, 25.955), help="Zero point magnitides for each band \ [Default:(26.508, 25.955)]") parser.add_argument('--gain', default=[2260, 2100], help="Detector gain in e/ADU[Default:[2260,2100](s)]") parser.add_argument('--sf', default=0.316, help="Scale factor to correct for correlated noise \ [Default:0.316 ") parser.add_argument('--manual_mask_file', default='manual_masks.txt', help="File containing regions that are to be masked\ [Default:'manual_masks.txt']") parser.add_argument('--tt_file_path', default='/nfs/slac/g/ki/ki19/deuce/AEGIS/tt_starfield/', help="Path of directory containing modelled TT fields \ [Default:'/nfs/slac/g/ki/ki19/deuce/AEGIS/tt_starfield/']") args = parser.parse_args() params = Main_param(args) run_segment(params)
GalSim-developersREPO_NAMEGalSimPATH_START.@GalSim_extracted@GalSim-main@devel@external@AEGIS@get_objects.py@.PATH_END.py
{ "filename": "_iconsize.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/layout/map/layer/symbol/_iconsize.py", "type": "Python" }
import _plotly_utils.basevalidators class IconsizeValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="iconsize", parent_name="layout.map.layer.symbol", **kwargs ): super(IconsizeValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "plot"), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@layout@map@layer@symbol@_iconsize.py@.PATH_END.py
{ "filename": "readfof.py", "repo_name": "franciscovillaescusa/Pylians", "repo_path": "Pylians_extracted/Pylians-master/library/readfof.py", "type": "Python" }
#model read_FoF""" #readfof(Base,snapnum,endian=None) #Read FoF files from Gadget, P-FoF #Parameters: #basedir: where your FoF folder located #snapnum: snapshot number #long_ids: whether particles ids are uint32 or uint64 #swap: False or True #return structures: #TotNgroups,TotNids,GroupLen,GroupOffset,GroupMass,GroupPos,GroupIDs... #Example: #-------- #FoF_halos=readfof("/data1/villa/b500p512nu0.6z99tree",17,long_ids=True,swap=False) #Masses=FoF_halos.GroupMass #IDs=FoF_halos.GroupIDs #-------- #updated time 19 Oct 2012 by wgcui #For simulations with SFR, set SFR=True #The physical velocities of the halos are found multiplying the field #GroupVel by (1+z) import numpy as np import os, sys from struct import unpack class FoF_catalog: def __init__(self, basedir, snapnum, long_ids=False, swap=False, SFR=False, read_IDs=True, prefix='/groups_'): if long_ids: format = np.uint64 else: format = np.uint32 exts=('000'+str(snapnum))[-3:] ################# READ TAB FILES ################# fnb, skip, Final = 0, 0, False dt1 = np.dtype((np.float32,3)) dt2 = np.dtype((np.float32,6)) prefix = basedir + prefix + exts + "/group_tab_" + exts + "." while not(Final): f=open(prefix+str(fnb), 'rb') self.Ngroups = np.fromfile(f, dtype=np.int32, count=1)[0] self.TotNgroups = np.fromfile(f, dtype=np.int32, count=1)[0] self.Nids = np.fromfile(f, dtype=np.int32, count=1)[0] self.TotNids = np.fromfile(f, dtype=np.uint64, count=1)[0] self.Nfiles = np.fromfile(f, dtype=np.uint32, count=1)[0] TNG, NG = self.TotNgroups, self.Ngroups if fnb == 0: self.GroupLen = np.empty(TNG, dtype=np.int32) self.GroupOffset = np.empty(TNG, dtype=np.int32) self.GroupMass = np.empty(TNG, dtype=np.float32) self.GroupPos = np.empty(TNG, dtype=dt1) self.GroupVel = np.empty(TNG, dtype=dt1) self.GroupTLen = np.empty(TNG, dtype=dt2) self.GroupTMass = np.empty(TNG, dtype=dt2) if SFR: self.GroupSFR = np.empty(TNG, dtype=np.float32) if NG>0: locs=slice(skip,skip+NG) self.GroupLen[locs] = np.fromfile(f,dtype=np.int32,count=NG) self.GroupOffset[locs] = np.fromfile(f,dtype=np.int32,count=NG) self.GroupMass[locs] = np.fromfile(f,dtype=np.float32,count=NG) self.GroupPos[locs] = np.fromfile(f,dtype=dt1,count=NG) self.GroupVel[locs] = np.fromfile(f,dtype=dt1,count=NG) self.GroupTLen[locs] = np.fromfile(f,dtype=dt2,count=NG) self.GroupTMass[locs] = np.fromfile(f,dtype=dt2,count=NG) if SFR: self.GroupSFR[locs]=np.fromfile(f,dtype=np.float32,count=NG) skip+=NG if swap: self.GroupLen.byteswap(True) self.GroupOffset.byteswap(True) self.GroupMass.byteswap(True) self.GroupPos.byteswap(True) self.GroupVel.byteswap(True) self.GroupTLen.byteswap(True) self.GroupTMass.byteswap(True) if SFR: self.GroupSFR.byteswap(True) curpos = f.tell() f.seek(0,os.SEEK_END) if curpos != f.tell(): raise Exception("Warning: finished reading before EOF for tab file",fnb) f.close() fnb+=1 if fnb==self.Nfiles: Final=True ################# READ IDS FILES ################# if read_IDs: fnb,skip=0,0 Final=False while not(Final): fname=basedir+"/groups_" + exts +"/group_ids_"+exts +"."+str(fnb) f=open(fname,'rb') Ngroups = np.fromfile(f,dtype=np.uint32,count=1)[0] TotNgroups = np.fromfile(f,dtype=np.uint32,count=1)[0] Nids = np.fromfile(f,dtype=np.uint32,count=1)[0] TotNids = np.fromfile(f,dtype=np.uint64,count=1)[0] Nfiles = np.fromfile(f,dtype=np.uint32,count=1)[0] Send_offset = np.fromfile(f,dtype=np.uint32,count=1)[0] if fnb==0: self.GroupIDs=np.zeros(dtype=format,shape=TotNids) if Ngroups>0: if long_ids: IDs=np.fromfile(f,dtype=np.uint64,count=Nids) else: IDs=np.fromfile(f,dtype=np.uint32,count=Nids) if swap: IDs=IDs.byteswap(True) self.GroupIDs[skip:skip+Nids]=IDs[:] skip+=Nids curpos = f.tell() f.seek(0,os.SEEK_END) if curpos != f.tell(): raise Exception("Warning: finished reading before EOF for IDs file",fnb) f.close() fnb+=1 if fnb==Nfiles: Final=True # This function is used to write one single file for the FoF instead of having # many files. This will make faster the reading of the FoF file def writeFoFCatalog(fc, tabFile, idsFile=None): if fc.TotNids > (1<<32)-1: raise Exception('TotNids overflow') f = open(tabFile, 'wb') np.asarray(fc.TotNgroups).tofile(f) np.asarray(fc.TotNgroups).tofile(f) np.asarray(fc.TotNids, dtype=np.int32).tofile(f) np.asarray(fc.TotNids).tofile(f) np.asarray(1, dtype=np.uint32).tofile(f) fc.GroupLen.tofile(f) fc.GroupOffset.tofile(f) fc.GroupMass.tofile(f) fc.GroupPos.tofile(f) fc.GroupVel.tofile(f) fc.GroupTLen.tofile(f) fc.GroupTMass.tofile(f) if hasattr(fc, 'GroupSFR'): fc.GroupSFR.tofile(f) f.close() if idsFile: f = open(idsFile, 'wb') np.asarray(fc.TotNgroups).tofile(f) np.asarray(fc.TotNgroups).tofile(f) np.asarray(fc.TotNids, dtype=np.uint32).tofile(f) np.asarray(fc.TotNids).tofile(f) np.asarray(1, dtype=np.uint32).tofile(f) np.asarray(0, dtype=np.uint32).tofile(f) fc.GroupIDs.tofile(f) f.close() # This is an example on how to change files """ root = '/mnt/xfs1/home/fvillaescusa/data/Neutrino_simulations/Sims_Dec16_2/' ################################## INPUT ###################################### folders = ['0.0eV/','0.06eV/','0.10eV/','0.10eV_degenerate/', '0.15eV/','0.6eV/', '0.0eV_0.798/','0.0eV_0.807/','0.0eV_0.818/','0.0eV_0.822/', '0.0eV_s8c/','0.0eV_s8m/'] ############################################################################### # do a loop over the different cosmologies for folder in folders: # do a loop over the different realizations for i in xrange(1,101): snapdir = root + folder + '%d/'%i # do a loop over the different redshift for snapnum in [0,1,2,3]: FoF_folder = snapdir+'groups_%03d'%snapnum old_FoF_folder = snapdir+'original_groups_%03d'%snapnum if os.path.exists(FoF_folder): print '%s\t%d\t%d\texists'%(folder,i,snapnum) if os.path.exists(old_FoF_folder): continue # create new FoF file f_tab = '%s/group_tab_%03d.0'%(snapdir,snapnum) f_ids = '%s/group_ids_%03d.0'%(snapdir,snapnum) FoF = readfof.FoF_catalog(snapdir,snapnum,long_ids=False, swap=False,SFR=False) writeFoFCatalog(FoF, f_tab, idsFile=f_ids) # rename FoF folder, create new FoF folder and move files to it os.system('mv '+FoF_folder+' '+old_FoF_folder) os.system('mkdir '+FoF_folder) os.system('mv '+f_tab+' '+f_ids+' '+FoF_folder) """
franciscovillaescusaREPO_NAMEPyliansPATH_START.@Pylians_extracted@Pylians-master@library@readfof.py@.PATH_END.py
{ "filename": "test_viewer.py", "repo_name": "dendrograms/astrodendro", "repo_path": "astrodendro_extracted/astrodendro-main/astrodendro/tests/test_viewer.py", "type": "Python" }
import pytest import numpy as np import matplotlib.pyplot as plt from ..dendrogram import Dendrogram from matplotlib.backend_bases import MouseEvent DATA = np.array([[1, 3, 4, 4, 1, 4], [1, 2, 3, 2, 1, 3], [2, 1, 1, 3, 1, 2], [1, 1, 1, 1, 1, 1], [2, 3, 2, 1, 1, 2], [2, 3, 5, 3, 1, 1]]) def test_viewer(capsys): original_backend = plt.get_backend() try: plt.switch_backend('qtagg') except ImportError: pytest.skip("This test requires Qt to be installed") d = Dendrogram.compute(DATA) viewer = d.viewer() plt.show(block=False) cb = viewer.fig.canvas.callbacks cb.process('button_press_event', MouseEvent('button_press_event', viewer.fig.canvas, 660, 520, 1)) cb.process('button_press_event', MouseEvent('button_press_event', viewer.fig.canvas, 890, 800, 1)) cb.process('button_press_event', MouseEvent('button_press_event', viewer.fig.canvas, 700, 700, 1)) plt.switch_backend(original_backend) captured = capsys.readouterr() assert captured.out == "" assert captured.err == ""
dendrogramsREPO_NAMEastrodendroPATH_START.@astrodendro_extracted@astrodendro-main@astrodendro@tests@test_viewer.py@.PATH_END.py
{ "filename": "snake_sampler.py", "repo_name": "joezuntz/cosmosis", "repo_path": "cosmosis_extracted/cosmosis-main/cosmosis/samplers/snake/snake_sampler.py", "type": "Python" }
from .. import ParallelSampler from ...runtime import logs import numpy as np from .snake import Snake def posterior(p_in): #Check the normalization if (not np.all(p_in>=0)) or (not np.all(p_in<=1)): return -np.inf, ([np.nan for i in range(len(snake_pipeline.extra_saves))], -np.inf) p = snake_pipeline.denormalize_vector(p_in) results = snake_pipeline.run_results(p) return results.post, (results.extra, results.prior) class SnakeSampler(ParallelSampler): sampler_outputs = [("prior", float), ("post", float)] parallel_output = False def config(self): global snake_pipeline snake_pipeline=self.pipeline if self.is_master(): threshold = self.read_ini("threshold", float, 4.0) self.grid_size = 1.0/self.read_ini("nsample_dimension", int, 10) self.maxiter = self.read_ini("maxiter", int, 100000) origin = self.pipeline.normalize_vector(self.pipeline.start_vector()) spacing = np.repeat(self.grid_size, len(self.pipeline.varied_params)) self.snake = Snake(posterior, origin, spacing, threshold, pool=self.pool) def execute(self): X, P, E = self.snake.iterate() for (x,post,(extra, prior)) in zip(X,P,E): try: x = self.pipeline.denormalize_vector(x) self.output.parameters(x, extra, prior, post) self.distribution_hints.set_peak(x, post) except ValueError: logs.noisy("The snake is trying to escape its bounds!") def is_converged(self): if self.snake.converged(): logs.overview("Snake has converged!") logs.overview("Best post = %f Best surface point = %f" %(self.snake.best_like_ever, self.snake.best_fit_like)) return True if self.snake.iterations > self.maxiter: logs.warning("Run out of iterations.") logs.warning("Done %d, max allowed %d" % (self.snake.iterations, self.maxiter)) return True return False
joezuntzREPO_NAMEcosmosisPATH_START.@cosmosis_extracted@cosmosis-main@cosmosis@samplers@snake@snake_sampler.py@.PATH_END.py
{ "filename": "eventsource.py", "repo_name": "cta-observatory/ctapipe", "repo_path": "ctapipe_extracted/ctapipe-main/src/ctapipe/io/eventsource.py", "type": "Python" }
""" Handles reading of different event/waveform containing files """ import warnings from abc import abstractmethod from collections.abc import Generator from traitlets.config.loader import LazyConfigValue from ctapipe.atmosphere import AtmosphereDensityProfile from ..containers import ( ArrayEventContainer, ObservationBlockContainer, SchedulingBlockContainer, SimulatedShowerDistribution, SimulationConfigContainer, ) from ..core import ToolConfigurationError from ..core.component import Component, find_config_in_hierarchy from ..core.traits import CInt, Int, Path, Set, TraitError, Undefined from ..instrument import SubarrayDescription from .datalevels import DataLevel __all__ = ["EventSource"] class EventSource(Component): """ Parent class for EventSources. EventSources read input files and generate `~ctapipe.containers.ArrayEventContainer` instances when iterated over. A new EventSource should be created for each type of event file read into ctapipe, e.g. sim_telarray files are read by the `~ctapipe.io.SimTelEventSource`. EventSource provides a common high-level interface for accessing event information from different data sources (simulation or different camera file formats). Creating an EventSource for a new file format or other event source ensures that data can be accessed in a common way, regardless of the file format or data origin. EventSource itself is an abstract class, but will create an appropriate subclass if a compatible source is found for the given ``input_url``. >>> EventSource(input_url="dataset://gamma_prod5.simtel.zst") <ctapipe.io.simteleventsource.SimTelEventSource ...> An ``EventSource`` can also be created through the configuration system, by passing ``config`` or ``parent`` as appropriate. E.g. if using ``EventSource`` inside of a ``Tool``, you would do: >>> self.source = EventSource(parent=self) # doctest: +SKIP To loop through the events in a file: >>> source = EventSource(input_url="dataset://gamma_prod5.simtel.zst", max_events=2) >>> for event in source: ... print(event.count) 0 1 **NOTE**: Every time a new loop is started through the source, it tries to restart from the first event, which might not be supported by the event source. It is encouraged to use ``EventSource`` in a context manager to ensure the correct cleanups are performed when you are finished with the source: >>> with EventSource(input_url="dataset://gamma_prod5.simtel.zst", max_events=2) as source: ... for event in source: ... print(event.count) 0 1 **NOTE**: EventSource implementations should not reuse the same ArrayEventContainer, as these are mutable and may lead to errors when analyzing multiple events. Parameters ---------- input_url : str | Path Path to the input event file. max_events : int Maximum number of events to loop through in generator allowed_tels: Set or None Ids of the telescopes to be included in the data. If given, only this subset of telescopes will be present in the generated events. If None, all available telescopes are used. """ #: ctapipe_io entry points may provide EventSource implementations plugin_entry_point = "ctapipe_io" input_url = Path(help="Path to the input file containing events.").tag(config=True) max_events = Int( None, allow_none=True, help="Maximum number of events that will be read from the file", ).tag(config=True) allowed_tels = Set( trait=CInt(), default_value=None, allow_none=True, help=( "list of allowed tel_ids, others will be ignored. " "If None, all telescopes in the input stream " "will be included" ), ).tag(config=True) def __new__(cls, input_url=Undefined, config=None, parent=None, **kwargs): """ Returns a compatible subclass for given input url, either directly or via config / parent """ # needed to break recursion, as __new__ of subclass will also # call this method if cls is not EventSource: return super().__new__(cls) # check we have at least one of these to be able to determine the subclass if input_url in {None, Undefined} and config is None and parent is None: raise ValueError("One of `input_url`, `config`, `parent` is required") if input_url in {None, Undefined}: input_url = cls._find_input_url_in_config(config=config, parent=parent) subcls = cls._find_compatible_source(input_url) return super().__new__(subcls) def __init__(self, input_url=None, config=None, parent=None, **kwargs): # traitlets differentiates between not getting the kwarg # and getting the kwarg with a None value. # the latter overrides the value in the config with None, the former # enables getting it from the config. if input_url not in {None, Undefined}: kwargs["input_url"] = input_url super().__init__(config=config, parent=parent, **kwargs) self.metadata = dict(is_simulation=False) self.log.info(f"INPUT PATH = {self.input_url}") if self.max_events: self.log.info(f"Max events being read = {self.max_events}") @staticmethod @abstractmethod def is_compatible(file_path): """ Abstract method to be defined in child class. Perform a set of checks to see if the input file is compatible with this file event_source. Parameters ---------- file_path : str File path to the event file. Returns ------- compatible : bool True if file is compatible, False if it is incompatible """ @property def is_stream(self): """ Bool indicating if input is a stream. If it is then it is incompatible with `ctapipe.io.eventseeker.EventSeeker`. TODO: Define a method to detect if it is a stream Returns ------- bool If True, then input is a stream. """ return False @property @abstractmethod def subarray(self) -> SubarrayDescription: """ Obtain the subarray from the EventSource Returns ------- ctapipe.instrument.SubarrayDecription """ @property def simulation_config(self) -> dict[int, SimulationConfigContainer] | None: """The simulation configurations of all observations provided by the EventSource, or None if the source does not provide simulated data Returns ------- dict[int,ctapipe.containers.SimulationConfigContainer] | None """ return None @property @abstractmethod def observation_blocks(self) -> dict[int, ObservationBlockContainer]: """ Obtain the ObservationConfigurations from the EventSource, indexed by obs_id """ pass @property @abstractmethod def scheduling_blocks(self) -> dict[int, SchedulingBlockContainer]: """ Obtain the ObservationConfigurations from the EventSource, indexed by obs_id """ pass @property @abstractmethod def is_simulation(self) -> bool: """ Whether the currently opened file is simulated Returns ------- bool """ @property @abstractmethod def datalevels(self) -> tuple[DataLevel]: """ The datalevels provided by this event source Returns ------- tuple[ctapipe.io.DataLevel] """ def has_any_datalevel(self, datalevels) -> bool: """ Check if any of `datalevels` is in self.datalevels Parameters ---------- datalevels: Iterable Iterable of datalevels """ return any(dl in self.datalevels for dl in datalevels) @property def obs_ids(self) -> list[int]: """ The observation ids of the runs located in the file Unmerged files should only contain a single obs id. Returns ------- list[int] """ return list(self.observation_blocks.keys()) @property def atmosphere_density_profile(self) -> AtmosphereDensityProfile | None: """atmosphere density profile that can be integrated to convert between h_max and X_max. This should correspond either to what was used in a simulation, or a measurement for use with observed data. Returns ------- AtmosphereDensityProfile: profile to be used """ return None @property def simulated_shower_distributions(self) -> dict[int, SimulatedShowerDistribution]: """ The distribution of simulated showers for each obs_id. Returns ------- dict[int,ctapipe.containers.SimulatedShowerDistribution] """ return {} @abstractmethod def _generator(self) -> Generator[ArrayEventContainer, None, None]: """ Abstract method to be defined in child class. Generator where the filling of the `ctapipe.containers` occurs. Returns ------- generator """ def __iter__(self): """ Generator that iterates through `_generator`, but keeps track of `self.max_events`. Returns ------- generator """ for event in self._generator(): yield event if self.max_events and event.count >= self.max_events - 1: break def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): pass @classmethod def _find_compatible_source(cls, input_url): if input_url == "" or input_url in {None, Undefined}: raise ToolConfigurationError("EventSource: No input_url was specified") # validate input url with the traitlet validate method # to make sure it's compatible and to raise the correct error input_url = EventSource.input_url.validate(obj=None, value=input_url) available_classes = cls.non_abstract_subclasses() missing_deps = {} for name, subcls in available_classes.items(): try: if subcls.is_compatible(input_url): return subcls except ModuleNotFoundError as e: missing_deps[subcls] = e.module except Exception as e: warnings.warn(f"{name}.is_compatible raised exception: {e}") # provide a more helpful error for non-existing input_url if not input_url.exists(): raise TraitError( f"input_url {input_url} is not an existing file " " and no EventSource implementation claimed compatibility." ) available_sources = [ name for name, cls in available_classes.items() if cls not in missing_deps ] msg = ( f"Could not find compatible EventSource for input_url: {input_url!r}\n" f"in available EventSources: {available_sources}\n" "EventSources that are installed but could not be used due to missing dependencies:\n\t" + "\n\t".join( f"{source.__name__}: {missing}" for source, missing in missing_deps.items() ) ) raise ValueError(msg) @classmethod def from_url(cls, input_url, **kwargs): """ Find compatible EventSource for input_url via the `is_compatible` method of the EventSource Parameters ---------- input_url : str Filename or URL pointing to an event file kwargs Named arguments for the EventSource Returns ------- instance Instance of a compatible EventSource subclass """ subcls = cls._find_compatible_source(input_url) return subcls(input_url=input_url, **kwargs) @classmethod def _find_input_url_in_config(cls, config=None, parent=None): if config is None and parent is None: raise ValueError("One of config or parent must be provided") if config is not None and parent is not None: raise ValueError("Only one of config or parent must be provided") input_url = None # config was passed if config is not None: if not isinstance(config.input_url, LazyConfigValue): input_url = config.input_url elif not isinstance(config.EventSource.input_url, LazyConfigValue): input_url = config.EventSource.input_url else: input_url = cls.input_url.default_value # parent was passed else: # first look at appropriate position in the config hierarchy input_url = find_config_in_hierarchy(parent, "EventSource", "input_url") # if not found, check top level if isinstance(input_url, LazyConfigValue): if not isinstance(parent.config.EventSource.input_url, LazyConfigValue): input_url = parent.config.EventSource.input_url else: input_url = cls.input_url.default_value return input_url def close(self): """Close this event source. No-op by default. Should be overridden by sources needing a cleanup-step """ pass
cta-observatoryREPO_NAMEctapipePATH_START.@ctapipe_extracted@ctapipe-main@src@ctapipe@io@eventsource.py@.PATH_END.py
{ "filename": "README.md", "repo_name": "nanograv/holodeck", "repo_path": "holodeck_extracted/holodeck-main/README.md", "type": "Markdown" }
# holodeck [//]: # (Badges) [![build](https://github.com/nanograv/holodeck/actions/workflows/unit-tests-ci.yaml/badge.svg)](https://github.com/nanograv/holodeck/actions/workflows/unit-tests-ci.yaml) [![codecov](https://codecov.io/gh/nanograv/holodeck/branch/main/graph/badge.svg?token=K63WQH3ED9)](https://codecov.io/gh/nanograv/holodeck) [![Documentation Status](https://readthedocs.org/projects/holodeck-gw/badge/?version=main)](https://readthedocs.org/projects/holodeck-gw/) *Massive Black-Hole Binary Population Synthesis for Gravitational Wave Calculations ≋●≋●≋* <img src="docs/media/holodeck_logo.png" width="260" alt="holodeck logo"> This package provides a comprehensive framework for MBH binary population synthesis. The framework includes modules to perform population synthesis using a variety of methodologies from semi-analytic models, to cosmological hydrodynamic simulations, and even observationally-derived galaxy merger catalogs. ## Getting Started (1) Read the [getting started guide](https://holodeck-gw.readthedocs.io/en/main/getting_started/index.html). (2) Install `holodeck` following the [Installation](#installation) instructions below. (3) Explore the [package demonstration notebooks](https://github.com/nanograv/holodeck/tree/main/notebooks). ## Installation The `holodeck` framework is currently under substantial, active development. Stable versions are now available with `pip install holodeck-gw` (see [holodeck on pypi](https://pypi.org/project/holodeck-gw)). However, recent versions and many development tools will not generally be available with ``pip`` or ``conda`` install. `holodeck` requires ``python >= 3.9`` (with support for: ``3.9, 3.10, 3.11``). The recommended installation is: (0) OPTIONAL & recommended: create and activate a new **anaconda** environment to isolate your build: ```bash conda create --name holo311 python=3.11; conda activate holo311 ``` Note that you will need to activate this environment every time you want to use holodeck. If you're not familiar with **anaconda**, take a look at their official [Getting started guide](https://conda.io/projects/conda/en/latest/user-guide/getting-started.html#managing-python). To use your anaconda environment with jupyter notebooks, make sure to add this environment to your ipython kernels: ```bash conda install -c conda-forge ipykernel python -m ipykernel install --user --name=holo311 ``` (1) Clone the `holodeck` repository, and move into the repo directory: ```bash git clone https://github.com/nanograv/holodeck.git; cd holodeck ``` (2) Install the required external packages specified in the requirements file: ```bash pip install -r requirements.txt ``` OPTIONAL: install development requirements:: ```bash pip install -r requirements-dev.txt ``` (3) Build the required c libraries from `holodeck` `cython` code: ```bash python setup.py build_ext -i ``` (4) Perform a development/editable local installation: ```bash python setup.py develop ``` The 'editable' installation allows the code base to be modified, and have those changes take effect when using the `holodeck` module without having to rebuild/reinstall it. Note that any changes to the `cython` library files do still require a rebuild by running steps (3) and (4) above. ### MPI For some scripts (particularly for generating libraries), an MPI implementation is required (e.g. `openmpi`), along with the [mpi4py package](https://github.com/mpi4py/mpi4py). This is not included as a requirement in the `requirements.txt` file as it significantly increases the installation complexity, and is not needed for many `holodeck` use cases. If you already have an MPI implementation installed on your system, you should be able to install `mpi4py` with anaconda: `conda install mpi4py`. To see if you have `mpi4py` installed, run `python -c 'import mpi4py; print(mpi4py.__version__)'` from a terminal. **macos users**: if you are using homebrew on macos, you should be able to simply run: `brew install mpi4py` which will [include the required openmpi implementation](https://mpi4py.readthedocs.io/en/latest/install.html#macos). ## Quickstart (1) Read the [Getting Started Guide](https://holodeck-gw.readthedocs.io/en/main/getting_started/index.html). (2) Explore the [package demonstration notebooks in `holodeck/notebooks`](https://github.com/nanograv/holodeck/tree/main/notebooks). ## Documentation Full package documentation for `holodeck` is available on [readthedocs](https://holodeck-gw.readthedocs.io/en/main/). ## Contributing & Development Contributions are not only welcome but encouraged, anywhere from new modules/customizations to bug-fixes to improved documentation and usage examples. Please see [Development & Contributions](https://holodeck-gw.readthedocs.io/en/main/development.html). ## Copyright Copyright (c) 2024, NANOGrav The `holodeck` package uses an [MIT license](./LICENSE). ## Attribution & Referencing A dedicated paper on ``holodeck`` is currently in preparation, but the package is also described in the recent [astrophysics analysis from the NANOGrav 15yr dataset](https://ui.adsabs.harvard.edu/abs/2023ApJ...952L..37A/abstract). ```tex @ARTICLE{2023ApJ...952L..37A, author = {{Agazie}, Gabriella and {et al} and {Nanograv Collaboration}}, title = "{The NANOGrav 15 yr Data Set: Constraints on Supermassive Black Hole Binaries from the Gravitational-wave Background}", journal = {\apjl}, year = 2023, month = aug, volume = {952}, number = {2}, eid = {L37}, pages = {L37}, doi = {10.3847/2041-8213/ace18b}, archivePrefix = {arXiv}, eprint = {2306.16220}, primaryClass = {astro-ph.HE}, adsurl = {https://ui.adsabs.harvard.edu/abs/2023ApJ...952L..37A}, } ```
nanogravREPO_NAMEholodeckPATH_START.@holodeck_extracted@holodeck-main@README.md@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "mikecokina/elisa", "repo_path": "elisa_extracted/elisa-master/scripts/benchmark/__init__.py", "type": "Python" }
mikecokinaREPO_NAMEelisaPATH_START.@elisa_extracted@elisa-master@scripts@benchmark@__init__.py@.PATH_END.py
{ "filename": "sampleFieldListSVPHInst.cc.py", "repo_name": "LLNL/spheral", "repo_path": "spheral_extracted/spheral-main/src/SVPH/sampleFieldListSVPHInst.cc.py", "type": "Python" }
text = """ //------------------------------------------------------------------------------ // Explicit instantiation. //------------------------------------------------------------------------------ #include "SVPH/sampleFieldListSVPH.cc" #include "Geometry/Dimension.hh" namespace Spheral { using std::vector; // Scalar template FieldList<Dim< %(ndim)s >, Dim< %(ndim)s >::Scalar> sampleFieldListSVPH<Dim< %(ndim)s >, Dim< %(ndim)s >::Scalar>(const FieldList<Dim< %(ndim)s >, Dim< %(ndim)s >::Scalar>& fieldList, const FieldList<Dim< %(ndim)s >, Dim< %(ndim)s >::Vector>& position, const FieldList<Dim< %(ndim)s >, Dim< %(ndim)s >::SymTensor>& Hfield, const ConnectivityMap<Dim< %(ndim)s > >& connectivityMap, const TableKernel< Dim< %(ndim)s > >& W, const Mesh<Dim< %(ndim)s > >& mesh, const bool firstOrderConsistent); // Vector template FieldList<Dim< %(ndim)s >, Dim< %(ndim)s >::Vector> sampleFieldListSVPH<Dim< %(ndim)s >, Dim< %(ndim)s >::Vector>(const FieldList<Dim< %(ndim)s >, Dim< %(ndim)s >::Vector>& fieldList, const FieldList<Dim< %(ndim)s >, Dim< %(ndim)s >::Vector>& position, const FieldList<Dim< %(ndim)s >, Dim< %(ndim)s >::SymTensor>& Hfield, const ConnectivityMap<Dim< %(ndim)s > >& connectivityMap, const TableKernel< Dim< %(ndim)s > >& W, const Mesh<Dim< %(ndim)s > >& mesh, const bool firstOrderConsistent); // Tensor template FieldList<Dim< %(ndim)s >, Dim< %(ndim)s >::Tensor> sampleFieldListSVPH<Dim< %(ndim)s >, Dim< %(ndim)s >::Tensor>(const FieldList<Dim< %(ndim)s >, Dim< %(ndim)s >::Tensor>& fieldList, const FieldList<Dim< %(ndim)s >, Dim< %(ndim)s >::Vector>& position, const FieldList<Dim< %(ndim)s >, Dim< %(ndim)s >::SymTensor>& Hfield, const ConnectivityMap<Dim< %(ndim)s > >& connectivityMap, const TableKernel< Dim< %(ndim)s > >& W, const Mesh<Dim< %(ndim)s > >& mesh, const bool firstOrderConsistent); // SymTensor template FieldList<Dim< %(ndim)s >, Dim< %(ndim)s >::SymTensor> sampleFieldListSVPH<Dim< %(ndim)s >, Dim< %(ndim)s >::SymTensor>(const FieldList<Dim< %(ndim)s >, Dim< %(ndim)s >::SymTensor>& fieldList, const FieldList<Dim< %(ndim)s >, Dim< %(ndim)s >::Vector>& position, const FieldList<Dim< %(ndim)s >, Dim< %(ndim)s >::SymTensor>& Hfield, const ConnectivityMap<Dim< %(ndim)s > >& connectivityMap, const TableKernel< Dim< %(ndim)s > >& W, const Mesh<Dim< %(ndim)s > >& mesh, const bool firstOrderConsistent); } """
LLNLREPO_NAMEspheralPATH_START.@spheral_extracted@spheral-main@src@SVPH@sampleFieldListSVPHInst.cc.py@.PATH_END.py
{ "filename": "path.py", "repo_name": "astroufsc/chimera", "repo_path": "chimera_extracted/chimera-master/src/chimera/core/path.py", "type": "Python" }
import os from chimera.util.findplugins import find_chimera_plugins __all__ = ["ChimeraPath"] class ChimeraPath(object): def __init__(self): # Search for chimera plugins on the sys.path self._controllers_plugins, self._instruments_plugins = find_chimera_plugins() self._instruments = [os.path.join(self.root(), "instruments")] self._instruments.extend(self._instruments_plugins) self._controllers = [os.path.join(self.root(), "controllers")] self._controllers.extend(self._controllers_plugins) @staticmethod def root(): return os.path.realpath(os.path.join(os.path.abspath(__file__), "../../")) @property def instruments(self): return self._instruments @property def controllers(self): return self._controllers
astroufscREPO_NAMEchimeraPATH_START.@chimera_extracted@chimera-master@src@chimera@core@path.py@.PATH_END.py
{ "filename": "redcal_inspect_2458159.ipynb", "repo_name": "HERA-Team/H1C_IDR3_Notebooks", "repo_path": "H1C_IDR3_Notebooks-main/redcal_inspect/redcal_inspect_2458159.ipynb", "type": "Jupyter Notebook" }
# Stage 2 Redundant Calibration Nightly Notebook **Josh Dillon**, Last Revised 7/30/20 ```python import numpy as np import matplotlib.pyplot as plt import matplotlib from hera_cal import io, redcal, apply_cal from hera_qm.metrics_io import load_metric_file import glob import os from copy import deepcopy import inspect import h5py %matplotlib inline %config InlineBackend.figure_format = 'retina' ``` ```python # If you want to run this notebook locally, copy the output of the next cell into the first few lines of this cell. # JD = '2459122' # data_path = '/lustre/aoc/projects/hera/H4C/2459122' # os.environ["JULIANDATE"] = JD # os.environ["DATA_PATH"] = data_path ``` ```python # Use environment variables to figure out path to data JD = os.environ['JULIANDATE'] data_path = os.environ['DATA_PATH'] print(f'JD = "{JD}"') print(f'data_path = "{data_path}"') ``` JD = "2458159" data_path = "/lustre/aoc/projects/hera/H1C_IDR3/IDR3_2/2458159" ```python print('Looking for data in', data_path, 'on JD', JD) data_list = sorted(glob.glob(os.path.join(data_path, f'zen.{JD}.?????.sum.uvh5'))) if len(data_list) == 0: data_list = sorted(glob.glob(os.path.join(data_path, f'zen.{JD}.?????.uvh5'))) print('Found {} files.'.format(len(data_list))) ``` Looking for data in /lustre/aoc/projects/hera/H1C_IDR3/IDR3_2/2458159 on JD 2458159 Found 73 files. # Load Single File ```python # Pick middle of the night data file to examine example_file = data_list[len(data_list)//2] file_JD = '.'.join([s for s in example_file.split('.') if s.isdigit()]) ``` ```python # controls how many redundant baseline groups to plot. # 2 means the most common ee- and nn-polarized baseline. n_reds_to_plot = 2 ``` ```python # Load omnical gains and determine ex_ants hc = io.HERACal(example_file.replace('.uvh5', f'.omni.calfits')) gains, gain_flags, _, _ = hc.read() ex_ants = [ant for ant in gain_flags if np.all(gain_flags[ant])] # Load the most common redundant baselines and calibrate hd = io.HERAData(example_file) reds = redcal.get_reds(hd.antpos, pols=['ee', 'nn']) red_bl_map = {bl: red[0] for red in reds for bl in red} reds = redcal.filter_reds(reds, ex_ants=ex_ants) reds = sorted(reds, key=len, reverse=True) data, flags, nsamples = hd.read( bls=[bl for red in reds[0:n_reds_to_plot] for bl in red]) apply_cal.calibrate_in_place(data, gains, data_flags=flags, cal_flags=gain_flags) # Load omnical visibility solutions hdo = io.HERAData(example_file.replace('.uvh5', f'.omni_vis.uvh5')) omni_data, omni_flags, omni_nsamples = hdo.read( bls=[red_bl_map[red[0]] for red in reds[0:n_reds_to_plot]]) ``` # Inspect Single File ```python plt.figure(figsize=(8,8)) plt.scatter(np.array(list(hd.antpos.values()))[:,0], np.array(list(hd.antpos.values()))[:,1], c='w', s=0) for ant,pos in hd.antpos.items(): bad = ant in [ant[0] for ant in ex_ants] plt.gca().add_artist(plt.Circle(tuple(pos[0:2]), radius=7, fill=(~bad), color=['grey','r'][bad])) plt.text(pos[0],pos[1],str(ant), va='center', ha='center', color='w') plt.xlabel("Antenna East-West Position (meters)") plt.ylabel("Antenna North-South Position (meters)") plt.title('Antenna Positions on {} (Red = Flagged)'.format(file_JD)); plt.axis('equal') plt.tight_layout() plt.show() ``` ![png](output_10_0.png) ### Figure 1: Array and Flagged Antennas #### OBSERVER CHECKLIST: * Check that the array configuration looks reasonable. * Check that all flags expected to be flagged are actually flagged but also that not everything is getting flagged. ```python # Plot redundant groups for red in reds[0:n_reds_to_plot]: blvec = hd.antpos[red[0][1]] - hd.antpos[red[0][0]] for func, plot, ylabel in zip([np.abs, np.angle], [plt.semilogy, plt.plot], ['Amplitude (Arbitrary Units)', 'Phase (Radians)']): plt.figure(figsize=(16,4)) for bl in red: plot(hd.freqs/1e6, func(np.median(data[bl], axis=0))) plot(hd.freqs/1e6, func(np.median(omni_data[red_bl_map[red[0]]], axis=0)), 'k-', label='Omnical Visibility Solution') plt.xlabel('Frequency (MHz)') plt.ylabel(ylabel) plt.legend(loc='lower right') plt.title('{}-Polarized, {:f} m East, {:f} m North Visibility on {}'.format(red[0][2], blvec[0], blvec[1], file_JD)) ``` ![png](output_12_0.png) ![png](output_12_1.png) ![png](output_12_2.png) ![png](output_12_3.png) ### Figure 2: Example redundant baseline groups and omnical visibility solution for a single file. #### OBSERVER CHECKLIST: * Check that that there actually is something plotted and the data isn't all flagged somehow. * Check whether most of the baselines cluster together and that the black line follows the cluster. * Check whether there are any significant outliers (though it won't be clear as yet which antennas those are attributable to, see below). # Load Whole Day ```python # load all redcal metadata into dictionaries meta_list = [df.replace('.uvh5', f'.redcal_meta.hdf5') for df in data_list] ee_iters_dict = {} nn_iters_dict = {} dlys_dict = {} flips_dict = {} times_dict = {} lsts_dict = {} histories_dict = {} ants = set([]) for mf in meta_list: (fc_meta, omni_meta, freqs, times_dict[mf], lsts_dict[mf], antpos, histories_dict[mf]) = io.read_redcal_meta(mf) ee_iters_dict[mf] = omni_meta['iter']["['ee']"] nn_iters_dict[mf] = omni_meta['iter']["['nn']"] flips_dict[mf] = fc_meta['polarity_flips'] dlys_dict[mf] = fc_meta['dlys'] ants |= set(fc_meta['dlys'].keys()) ants = sorted(ants) times = np.hstack(list(times_dict.values())) lsts = np.hstack(list(lsts_dict.values())) ``` ```python # Load chisq and flagging info from omnical gains cal_list = [df.replace('.uvh5', f'.omni.calfits') for df in data_list] ant_flags_dict = {} chisq_ee_dict = {} chisq_nn_dict = {} cspa_med_dict = {} for cal in cal_list: hc = io.HERACal(cal) _, flags, cspa, chisq = hc.read() ant_flags_dict[cal] = {ant: np.all(flags[ant]) for ant in flags} chisq_ee_dict[cal] = chisq['Jee'] chisq_nn_dict[cal] = chisq['Jnn'] cspa_med_dict[cal] = {ant: np.nanmedian(cspa[ant], axis=1) for ant in cspa} all_flagged_dict = {ant: np.all([af[ant] for af in ant_flags_dict.values()]) for ant in ants} cspa = {ant: np.hstack([np.squeeze(cspa_med_dict[cal][ant]) / \ ~ant_flags_dict[cal][ant] for cal in cal_list]) for ant in ants} ``` invalid value encountered in true_divide divide by zero encountered in true_divide ```python # save middle-numbered ants with a minimal number of flags ants_to_save = {} for pol in ['Jee', 'Jnn']: min_flags = np.min([np.sum(~np.isfinite(cspa[ant])) for ant in cspa if ant[1] == pol]) ant_candidates = sorted([ant for ant in cspa if ant[1] == pol and np.sum(~np.isfinite(cspa[ant])) == min_flags]) Nac = len(ant_candidates) ants_to_save[pol] = ant_candidates[(Nac // 2 - 1):(Nac // 2 + 1)] # Reload omnical gains gain_dict = {} flag_dict = {} for cal in cal_list: hc = io.HERACal(cal) gains, flags, _, _ = hc.read() gain_dict[cal] = {ant: gains[ant] for pol in ants_to_save for ant in ants_to_save[pol]} flag_dict[cal] = {ant: flags[ant] for pol in ants_to_save for ant in ants_to_save[pol]} gains = {ant: np.vstack([gain_dict[cal][ant] for cal in gain_dict]) for pol in ants_to_save for ant in ants_to_save[pol]} flags = {ant: np.vstack([flag_dict[cal][ant] for cal in flag_dict]) for pol in ants_to_save for ant in ants_to_save[pol]} flag_mask = np.all([f for f in flags.values()], axis=0) ``` # Inspect Whole Day ```python # Plot delays dlys = {ant: np.hstack([dlys_dict[mf][ant] for mf in dlys_dict]) for ant in ants} dly_meds = {ant: np.nanmedian(dlys[ant]) for ant in dlys} plt.figure(figsize=(16,10)) for ant in dlys: plt.plot(times, (dlys[ant])*1e9) if np.isfinite(dly_meds[ant]): plt.text(np.min(times) - 20*np.median(np.diff(times)), 1e9*dly_meds[ant], '{}{}'.format(ant[0], ant[1][-1]), va='center', ha='right', fontsize=8) plt.gca().set_xticklabels(np.around(lsts[[min(max(np.searchsorted(times, t), 0), len(times) - 1) for t in plt.gca().get_xticks()]] * 12 / np.pi, 2)) plt.xlabel('LST (Hours)') plt.ylabel('Delay (ns)') plt.title('Firstcal Delays'); ``` All-NaN slice encountered FixedFormatter should only be used together with FixedLocator Text(0.5, 1.0, 'Firstcal Delays') ![png](output_19_2.png) ### Figure 3: Firstcal Delays Shows solved firstcal delays. These will have an arbitrary tip/tilt and offset. #### OBSERVER CHECKLIST: * Look for outliers. All antennas should be within a few hundred ns. ```python # Plot offset delays plt.figure(figsize=(16, len(ants)/7.4)) unflagged_dlys = {ant: dlys[ant] for ant in dlys if not all_flagged_dict[ant]} for n, ant in enumerate(unflagged_dlys): plt.plot(times, (dlys[ant]-dly_meds[ant])*1e9 + n, label=ant) plt.text(np.min(times) - 20*np.median(np.diff(times)), n, '{}{}'.format(ant[0], ant[1][-1]), va='center', ha='right', fontsize=8) plt.gca().set_xticklabels(np.around(lsts[[min(max(np.searchsorted(times, t), 0), len(times) - 1) for t in plt.gca().get_xticks()]] * 12 / np.pi, 2)) plt.xlabel('LST (Hours)') plt.ylabel('Delay with Arbitrary Offset (ns)') plt.title('Firstcal Delays With Arbitrary Offset'); plt.ylim([-10, len(unflagged_dlys) + 10]) ``` FixedFormatter should only be used together with FixedLocator (-10.0, 92.0) ![png](output_21_2.png) ### Figure 4: Offset Firstcal Delays Same as Figure 4, but with arbitrary offsets for each antenna. #### OBSERVER CHECKLIST: * Look for antennas that exhibit wild swings (> 10 ns) in their delay over time. ```python # Figure out oc_maxiter if np.all(['oc_maxiter' in history for history in histories_dict.values()]): history = list(histories_dict.values())[0] oc_maxiter = int(history.split('--oc_maxiter')[1].split('--')[0]) else: oc_maxiter = inspect.signature(redcal.redcal_run).parameters['oc_maxiter'].default ``` ```python # Recast from dictionaries to one big array ee_iters = np.vstack(np.array(list(ee_iters_dict.values()))) nn_iters = np.vstack(np.array(list(nn_iters_dict.values()))) plt.figure(figsize=(20,12)) my_cmap = deepcopy(matplotlib.cm.get_cmap('viridis')) my_cmap.set_under('w') my_cmap.set_over('r') for sp, iters, t in zip([121, 122], [ee_iters, nn_iters], ['ee-polarized', 'nn-polarized']): plt.subplot(sp) plt.imshow(iters, aspect='auto', cmap=my_cmap, vmin=1, vmax=oc_maxiter-1, interpolation='nearest', extent=[freqs[0]/1e6, freqs[-1]/1e6, times[-1], times[0]]) plt.title('Number of Omnical Iterations: ' + t) plt.xlabel('Frequency (MHz)') plt.ylabel('LST (Hours)') plt.gca().set_yticklabels(np.around(lsts[[min(max(np.searchsorted(times, t), 0), len(times) - 1) for t in plt.gca().get_yticks()]] * 12 / np.pi, 2)) plt.colorbar() ``` Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray You are modifying the state of a globally registered colormap. In future versions, you will not be able to modify a registered colormap in-place. To remove this warning, you can make a copy of the colormap first. cmap = copy.copy(mpl.cm.get_cmap("viridis")) You are modifying the state of a globally registered colormap. In future versions, you will not be able to modify a registered colormap in-place. To remove this warning, you can make a copy of the colormap first. cmap = copy.copy(mpl.cm.get_cmap("viridis")) FixedFormatter should only be used together with FixedLocator ![png](output_24_1.png) ### Figure 5: Number of omnical iterations per polarization Red indicates that omnical reached the maximum number of integrations. White indicates that omnical didn't run, likely because the data were flagged. #### OBSERVER CHECKLIST: * Check that few-to-no data were flagged (white) before omnical and check that this matches * Check that few-to-no data hit the maximum number of iterations for omnical (red) ```python # Make dictionary mapping antenna to the whole night of antenna flips flips = {ant: np.hstack([flips_dict[mf][ant] for mf in flips_dict]) for ant in ants} plt.figure(figsize=(16,8)) my_cmap = matplotlib.cm.get_cmap('cool') for sp, jpol, t in zip([121, 122], ['Jee', 'Jnn'], ['ee-polarized ', 'nn-polarized']): plt.subplot(sp) plt.scatter(np.array(list(hd.antpos.values()))[:,0], np.array(list(hd.antpos.values()))[:,1], c='w', s=0) for ant,pos in hd.antpos.items(): flip_frac = np.nanmean(flips[(ant, jpol)]) if np.isfinite(flip_frac): color=my_cmap(flip_frac) else: color='w' plt.gca().add_artist(plt.Circle(tuple(pos[0:2]), radius=7, fill=(~bad), color=color, ec='k')) plt.text(pos[0], pos[1], '{}:\n{}%'.format(ant, np.round(100*flip_frac,0)), va='center', ha='center', color='k') plt.xlabel("Antenna East-West Position (meters)") plt.ylabel("Antenna North-South Position (meters)") # count the number of times a self-consistent polarity flip solution was found all_flips_this_pol = [flips[ant] for ant in flips if ant[1] == jpol] success = np.round(100*np.mean(np.any(np.isfinite(all_flips_this_pol), axis=0)), 2) plt.title(t + ' Polarity Flips -- Solution Found {}% of the Time'.format(success)) plt.axis('equal') plt.tight_layout() ``` Mean of empty slice ![png](output_26_1.png) ### Figure 6: Detection of polarity-flipped antennas Blue indicates nominal operation, pink indicates polarity flips. #### OBSERVER CHECKLIST: * Check that all antennas are either nearly 100% flipped, nearly 0% flipped, or flagged. * Check that a solution for polarity flips was found a reasonable percentage of the time (ideally more than a few %) ```python # Grid and plot overall chi^2 for each polarization ee_chisq = np.vstack(np.array(list(chisq_ee_dict.values()))) nn_chisq = np.vstack(np.array(list(chisq_nn_dict.values()))) plt.figure(figsize=(20,12)) for sp, cs, t in zip([121, 122], [ee_chisq, nn_chisq], ['ee-polarized', 'nn-polarized']): plt.subplot(sp) plt.imshow(cs / ~flag_mask, aspect='auto', vmin=0, cmap='inferno', vmax=3, interpolation='nearest', extent=[freqs[0]/1e6, freqs[-1]/1e6, times[-1], times[0]]) plt.title('Overall $\chi^2$ / DoF: ' + t) plt.xlabel('Frequency (MHz)') plt.ylabel('LST (Hours)') plt.gca().set_yticklabels(np.around(lsts[[min(max(np.searchsorted(times, t), 0), len(times) - 1) for t in plt.gca().get_yticks()]] * 12 / np.pi, 2)) plt.colorbar() ``` Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray divide by zero encountered in true_divide invalid value encountered in true_divide FixedFormatter should only be used together with FixedLocator ![png](output_28_1.png) ### Figure 7 Overall $\chi^2$ / DoF #### OBSERVER CHECKLIST: * Looks for regions of large non-redundancy not directly attributable to RFI. ```python # plot all chi^2 per antenna, highlight antennas with >1.5 mean chisq per ant (median over frequency) plt.figure(figsize=(20,10)) for sp, pol, t in zip([121, 122], ['Jee', 'Jnn'], ['ee-polarized', 'nn-polarized']): plt.subplot(sp) for ant in sorted([ant for ant in ants if ant[1] == pol], key=lambda ant: np.nanmean(cspa[ant]), reverse=True): if not np.all([ant_flags_dict[cal][ant] for cal in cal_list]): if np.nanmean(cspa[ant]) > 1.5: plt.plot(times, cspa[ant], '.', label=ant) else: plt.plot(times, cspa[ant], '-', color='grey', lw=.25) plt.ylabel('Normalized Median $\chi^2$ per Antenna (unitless)') plt.gca().set_xticklabels(np.around(lsts[[min(max(np.searchsorted(times, t), 0), len(times) - 1) for t in plt.gca().get_xticks()]] * 12 / np.pi, 2)) plt.xlabel('LST (Hours)') plt.title(t + ' Antennas') plt.legend() ``` FixedFormatter should only be used together with FixedLocator FixedFormatter should only be used together with FixedLocator ![png](output_30_1.png) ### Figure 8: Normalized $\chi^2$ per antenna Antennas with chisq per ant (mean over time, median over freq) > 1.5 are colored. All other antennas are shown in grey. #### OBSERVER CHECKLIST: * Look for outliers in the chi^2 per antenna distribution ```python # Plot example gain amplitudes plt.figure(figsize=(20,12)) for sp, pol in zip([121, 122], ['Jee', 'Jnn']): plt.subplot(sp) ant = ants_to_save[pol][1] plt.title(str(ant) + ' Gain Magnitude') plt.imshow(np.abs(gains[ant]) / ~flag_mask, aspect='auto', cmap='inferno', interpolation='nearest', extent=[freqs[0]/1e6, freqs[-1]/1e6, times[-1], times[0]]) plt.clim([0,2]) plt.gca().set_yticklabels(np.around(lsts[[min(max(np.searchsorted(times, t), 0), len(times) - 1) for t in plt.gca().get_yticks()]] * 12 / np.pi, 2)) plt.colorbar() plt.xlabel('Frequency (MHz)') plt.ylabel('LST (Hours)') ``` divide by zero encountered in true_divide FixedFormatter should only be used together with FixedLocator ![png](output_32_1.png) ### Figure 9: Example Amplitudes #### OBSERVER CHECKLIST: * Looks for large discontinuities or fuzziness not attributable to RFI ```python # Plot example gain relative phases plt.figure(figsize=(20,12)) for sp, pol in zip([121, 122], ['Jee', 'Jnn']): plt.subplot(sp) ant0, ant1 = ants_to_save[pol] plt.title('Angle of gains[{}] / gains[{}]'.format(ant0, ant1)) plt.imshow(np.angle(gains[ant0] / gains[ant1]) / ~flag_mask, aspect='auto', cmap='twilight', interpolation='nearest', extent=[freqs[0]/1e6, freqs[-1]/1e6, times[-1], times[0]]) plt.gca().set_yticklabels(np.around(lsts[[min(max(np.searchsorted(times, t), 0), len(times) - 1) for t in plt.gca().get_yticks()]] * 12 / np.pi, 2)) plt.colorbar() plt.xlabel('Frequency (MHz)') plt.ylabel('LST (Hours)') ``` invalid value encountered in true_divide FixedFormatter should only be used together with FixedLocator ![png](output_34_1.png) ### Figure 10: Example Gain Phases Relative gain phases of two example antennas. #### OBSERVER CHECKLIST: * Check that these gains are relatively stable in time and that there aren't huge phase discontinuities. # Metadata ```python print(redcal.version.history_string()) ``` ------------ This file was produced by the function <module>() in <ipython-input-1-c6de44361328> using: git_branch: master git_description: v3.0-733-gd2dd8ccf git_hash: d2dd8ccf3fe43d5e5eb6a4c28ceaf4a6e3d1fcb7 git_origin: git@github.com:HERA-Team/hera_cal.git version: 3.0 ------------
HERA-TeamREPO_NAMEH1C_IDR3_NotebooksPATH_START.@H1C_IDR3_Notebooks-main@redcal_inspect@redcal_inspect_2458159.ipynb@.PATH_END.py
{ "filename": "compute_olr_h2o.py", "repo_name": "danielkoll/PyRADS", "repo_path": "PyRADS_extracted/PyRADS-master/Test01.olr/compute_olr_h2o.py", "type": "Python" }
from __future__ import division, print_function import numpy as np import sys,os sys.path.append("..") import pyrads from scipy.integrate import trapz,simps,cumtrapz ### ----------------------------------- ### Helpers class Dummy: pass ### ----------------------------------- # --- ## setup thermodynamic parameters params = Dummy() params.Rv = pyrads.phys.H2O.R # moist component params.cpv = pyrads.phys.H2O.cp params.Lvap = pyrads.phys.H2O.L_vaporization_TriplePoint params.satvap_T0 = pyrads.phys.H2O.TriplePointT params.satvap_e0 = pyrads.phys.H2O.TriplePointP params.esat = lambda T: pyrads.Thermodynamics.get_satvps(T,params.satvap_T0,params.satvap_e0,params.Rv,params.Lvap) params.R = pyrads.phys.air.R # dry component params.cp = pyrads.phys.air.cp params.ps_dry = 1e5 # surface pressure of dry component params.g = 9.8 # surface gravity params.cosThetaBar = 3./5. # average zenith angle used in 2stream eqns params.RH = 1. # relative humidity # --- ## setup resolution (vertical,spectral) N_press = 15 # for testing only! dwavenr = 0.1 # for testing only! #N_press = 60 # wavenr_min = 0.1 # [cm^-1] wavenr_max = 3500. # #dwavenr = 0.01 # Tstrat = 150. # stratospheric temperature # --- ## setup range of temperatures, and if/where output is saved to: Ts = 300. ### ----------------------------------- ## MAIN LOOP print( "wavenr_min,wavenr_max,dwave [cm^-1] = %.4f,%.4f,%.4f" % (wavenr_min,wavenr_max,dwavenr)) print( "\n") print( "N_press = %.1f" % N_press) print( "\n") print( "Surface temperature = %.1f K" % Ts) # setup grid: g = pyrads.SetupGrids.make_grid( Ts,Tstrat,N_press,wavenr_min,wavenr_max,dwavenr,params, RH=params.RH ) # compute optical thickness: # -> this is the computationally most intensive step g.tau = pyrads.OpticalThickness.compute_tau_H2ON2(g.p,g.T,g.q,g,params, RH=params.RH ) # compute Planck functions etc: # -> here: fully spectrally resolved! T_2D = np.tile( g.T, (g.Nn,1) ).T # [press x wave] g.B_surf = np.pi* pyrads.Planck.Planck_n( g.n,Ts ) # [wave] g.B = np.pi* pyrads.Planck.Planck_n( g.wave, T_2D ) # [press x wave] # compute OLR etc: olr_spec = pyrads.Get_Fluxes.Fplus_alternative(0,g) # (spectrally resolved=irradiance) olr = simps(olr_spec,g.n) print( "OLR = ",olr)
danielkollREPO_NAMEPyRADSPATH_START.@PyRADS_extracted@PyRADS-master@Test01.olr@compute_olr_h2o.py@.PATH_END.py
{ "filename": "_prefix.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/indicator/number/_prefix.py", "type": "Python" }
import _plotly_utils.basevalidators class PrefixValidator(_plotly_utils.basevalidators.StringValidator): def __init__(self, plotly_name="prefix", parent_name="indicator.number", **kwargs): super(PrefixValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "plot"), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@indicator@number@_prefix.py@.PATH_END.py
{ "filename": "survey_data.py", "repo_name": "FRBs/zdm", "repo_path": "zdm_extracted/zdm-main/zdm/survey_data.py", "type": "Python" }
""" Survey data """ from dataclasses import dataclass, field from zdm import data_class import numpy as np @dataclass class FRB(data_class.myDataClass): # None of the fields should start with an X BW: float = field( default=0., metadata={'help': "Mean Frequency (observed)", 'unit': 'MHz', 'Notation': '', }) DM: float = field( default=0., metadata={'help': "Measured DM", 'unit': 'pc/cm**3', 'Notation': '', }) DMG: float = field( default=0., metadata={'help': "Galactic contribution to DM", 'unit': 'pc/cm**3', 'Notation': '', }) FBAR: float = field( default=0., metadata={'help': "Mean frequency", 'unit': 'MHz', 'Notation': '', }) FRES: float = field( default=1., metadata={'help': "Frequency resolution", 'unit': 'MHz', 'Notation': '', }) Gb: float = field( default=1., metadata={'help': "Galactic latitude", 'unit': 'deg', 'Notation': '', }) Gl: float = field( default=1., metadata={'help': "Galactic longitude", 'unit': 'deg', 'Notation': '', }) # NREP: np.int64 = field( # default=1, # metadata={'help': "Number of repetitions detected", # 'unit': '', # 'Notation': '', # }) SNR: float = field( default=0., metadata={'help': "S/N", 'unit': '', 'Notation': '', }) SNRTHRESH: float = field( default=0., metadata={'help': "S/N threshold to detect an FRB", 'unit': '', 'Notation': '', }) THRESH: float = field( default=1., metadata={'help': "Threshold fluence used to detect an FRB", 'unit': 'Jy ms', 'Notation': '', }) TNS: str = field( default='', metadata={'help': "TNS Name", }) TRES: float = field( default=0., metadata={'help': "Time resolution", 'unit': 'ms', 'Notation': '', }) WIDTH: float = field( default=0.1, metadata={'help': "Width of the event (intrinsic??)", 'unit': 'ms', 'Notation': '', }) Z: float = field( default=-1., metadata={'help': "redshift; -1 means unlocalised", 'unit': '', 'Notation': '', }) @dataclass class Telescope(data_class.myDataClass): BEAM: str = field( default='', metadata={'help': "Beam file", }) BW: float = field( default=336., metadata={'help': "Mean Frequency (observed)", 'unit': 'MHz', 'Notation': '', }) DIAM: float = field( default=0., metadata={'help': "Individual antenna diameter", 'unit': 'm', 'Notation': '', }) DMG: float = field( default=30., metadata={'help': "Galactic contribution to DM", 'unit': 'pc/cm**3', 'Notation': '', }) NBEAMS: int = field( default=1, metadata={'help': "Number of beams/antennae", 'unit': '', 'Notation': '', }) NBINS: int = field( default=0, metadata={'help': "Number of bins for width analysis", 'unit': '', 'Notation': '', }) WMETHOD: int = field( default=2, metadata={'help': "Method of calculating FRB widths; 0 ignore, 1 std, 2 includes scattering", 'unit': '', 'Notation': '', }) WBIAS: str = field( default="Quadrature", metadata={'help': "Method to calculate width bias", 'unit': '', 'Notation': '', }) BMETHOD: int = field( default=2, metadata={'help': "Method for beam calculation. See beams.py:simplify_beam()", 'unit': '', 'Notation': '', }) DRIFT_SCAN: int = field( default=2, metadata={'help': '1: beam represents solid angle viewed at each value of b, for time Tfield \ 2: (Drift scan) beam represents time (in days) spent on any given source at sensitivity level b. \ Tfield is solid angle. Nfields then becomes a multiplier of the time.', 'unit': '', 'Notation': '' }) BTHRESH: float = field( default=0.0, metadata={'help': 'Minimum value of beam sensitivity to consider', 'unit': '', 'Notation': 'B_{\rm min}'}) THRESH: float = field( default=1., metadata={'help': "Threshold fluence used to detect an FRB", 'unit': 'Jy ms', 'Notation': '', }) FBAR: float = field( default=1300., metadata={'help': "Mean frequency", 'unit': 'MHz', 'Notation': '', }) FRES: float = field( default=1., metadata={'help': "Frequency resolution", 'unit': 'MHz', 'Notation': '', }) TRES: float = field( default=1.26, metadata={'help': "Time resolution", 'unit': 'ms', 'Notation': '', }) WIDTH: float = field( default=0.1, metadata={'help': "Intrinsic width of the event", 'unit': 'ms', 'Notation': '', }) @dataclass class Observing(data_class.myDataClass): NORM_FRB: int = field( default=0, metadata={'help': "Number of FRBs for TOBS", 'unit': '', 'Notation': '', }) NORM_REPS: int = field( default=None, metadata={'help': "Number of repeaters for TOBS", 'unit': '', 'Notation': '', }) NORM_SINGLES: int = field( default=None, metadata={'help': "Number of singles for TOBS", 'unit': '', 'Notation': '', }) TOBS: float = field( default=None, metadata={'help': "Total observing time", 'unit': 'days', 'Notation': '', }) TFIELD: float = field( default=None, metadata={'help': "Observing time per field", 'unit': 'days', 'Notation': '', }) NFIELDS: int = field( default=None, metadata={'help': "Number of observing fields", 'unit': '', 'Notation': '', }) MAX_DM: float = field( default=None, metadata={'help': "Maximum searched DM", 'unit': 'pc/cm**3', 'Notation': '', }) MAX_IDT: int = field( default=None, metadata={'help': "Maximum number of time samples seaarched (4096 for CRAFT ICS)", 'unit': '', 'Notation': '', }) MAX_LOC_DMEG: int = field( default=-1, metadata={'help': "Ignore zs with DMEG larger than 'x'. \n-1: Use all zs \n0: 'x' = smallest DMEG for an FRB without a z \n>0: 'x' = this value", 'unit': 'pc/cm**3', 'Notation': '', }) class SurveyData(data_class.myData): """ Hold the SurveyData in a convenient object """ def set_dataclasses(self): self.observing = Observing() self.telescope = Telescope() # FRBs -- Will need one per FRB # Finish init
FRBsREPO_NAMEzdmPATH_START.@zdm_extracted@zdm-main@zdm@survey_data.py@.PATH_END.py
{ "filename": "mcgreer.py", "repo_name": "gkulkarni/QLF", "repo_path": "QLF_extracted/QLF-master/mcgreer.py", "type": "Python" }
import numpy as np import matplotlib as mpl mpl.use('Agg') mpl.rcParams['text.usetex'] = True mpl.rcParams['font.family'] = 'serif' mpl.rcParams['font.serif'] = 'cm' mpl.rcParams['font.size'] = '22' import matplotlib.pyplot as plt from astropy.stats import knuth_bin_width as kbw from astropy.stats import poisson_conf_interval as pci from scipy.stats import binned_statistic as bs import cosmolopy.distance as cd cosmo = {'omega_M_0':0.3, 'omega_lambda_0':0.7, 'omega_k_0':0.0, 'h':0.7} def volume(z, area, cosmo=cosmo): omega = (area/41253.0)*4.0*np.pi # str volperstr = cd.diff_comoving_volume(z,**cosmo) # cMpc^3 str^-1 dz^-1 return omega*volperstr # cMpc^3 dz^-1 def binvol(m, zrange, bins, msel, psel, vsel, zsel): """ Calculate volume in the i'th bin. """ total_vol = 0.0 idx = -1 for i in range(len(bins)): if (m > bins[i]) and (m < bins[i+1]): idx = i idx = np.searchsorted(bins, m) mlow = bins[idx-1] mhigh = bins[idx] dm = 0.1 n = int(abs(mhigh-mlow)/dm) for i in xrange(msel.size): if (msel[i] >= mlow) and (msel[i] < mhigh): if (zsel[i] >= zrange[0]) and (zsel[i] < zrange[1]): total_vol += vsel[i]*psel[i]*dm return total_vol def get_lf(zrange, bins): z, m, p = np.loadtxt('Data/mcgreer13_dr7sample2.dat', usecols=(1, 2, 3), unpack=True) select = ((z>=zrange[0]) & (z<zrange[1])) m = m[select] p = p[select] area = 6222.0 # deg^2 dz = 0.05 dm = 0.1 zsel, msel, psel = np.loadtxt('Data/mcgreer13_dr7selfunc2.dat', usecols=(1, 2, 3), unpack=True) vol = volume(zsel, area)*dz psel[(zsel < zrange[0]) | (zsel >= zrange[1])] = 0.0 v1 = np.array([binvol(x, zrange, bins, msel, psel, vol, zsel) for x in m]) print v1.size v1_nonzero = v1[np.where(v1>0.0)] m = m[np.where(v1>0.0)] print v1_nonzero.size h = np.histogram(m,bins=bins,weights=1.0/(v1_nonzero)) nums = h[0] mags = (h[1][:-1] + h[1][1:])*0.5 dmags = np.diff(h[1])*0.5 left = mags - h[1][:-1] right = h[1][1:] - mags phi = nums logphi = np.log10(phi) # cMpc^-3 mag^-1 n = np.histogram(m,bins=bins)[0] print n nlims = pci(n,interval='frequentist-confidence') nlims *= phi/n uperr = np.log10(nlims[1]) - logphi downerr = logphi - np.log10(nlims[0]) return mags, left, right, logphi, uperr, downerr def get_lf_s82(zrange, bins): z, m, p = np.loadtxt('Data/mcgreer13_s82sample2.dat', usecols=(1, 2, 3), unpack=True) select = ((z>=zrange[0]) & (z<zrange[1])) m = m[select] p = p[select] area = 235.0 # deg^2 dz = 0.05 dm = 0.1 zsel, msel, psel = np.loadtxt('Data/mcgreer13_s82selfunc2.dat', usecols=(1, 2, 3), unpack=True) vol = volume(zsel, area)*dz psel[(zsel < zrange[0]) | (zsel >= zrange[1])] = 0.0 v1 = np.array([binvol(x, zrange, bins, msel, psel, vol, zsel) for x in m]) print v1.size v1_nonzero = v1[np.where(v1>0.0)] m = m[np.where(v1>0.0)] print v1_nonzero.size h = np.histogram(m,bins=bins,weights=1.0/(v1_nonzero)) nums = h[0] mags = (h[1][:-1] + h[1][1:])*0.5 dmags = np.diff(h[1])*0.5 left = mags - h[1][:-1] right = h[1][1:] - mags phi = nums logphi = np.log10(phi) # cMpc^-3 mag^-1 n = np.histogram(m,bins=bins)[0] nlims = pci(n,interval='frequentist-confidence') nlims *= phi/n uperr = np.log10(nlims[1]) - logphi downerr = logphi - np.log10(nlims[0]) return mags, left, right, logphi, uperr, downerr fig = plt.figure(figsize=(6, 6), dpi=100) ax = fig.add_subplot(1, 1, 1) ax.set_ylabel(r'$\log_{10}\left(\phi/\mathrm{cMpc}^{-3}\,\mathrm{mag}^{-1}\right)$') ax.set_xlabel('$M_{1450}$') ax.tick_params('both', which='major', length=7, width=1) ax.tick_params('both', which='minor', length=3, width=1) ax.tick_params('x', which='major', pad=6) # Plot binned LF from literature f = 'Data/mcgreer_dr7_published.dat' (sid, M1450, M1450_lerr, M1450_uerr, phi, phi_err) = np.loadtxt(f, unpack=True) d = phi_err * 1.0e-9 x = 10.0**phi phi_lerr = np.log10(x)-np.log10(x-d) phi_uerr = np.log10(x+d)-np.log10(x) phi_err = np.log10(phi_err * 1.0e-9) ax.errorbar(M1450, phi, ecolor='b', capsize=0, xerr=np.vstack((M1450_lerr, M1450_uerr)), yerr=np.vstack((phi_lerr, phi_uerr)), fmt='none', zorder=303) ax.scatter(M1450, phi, c='#ffffff', label='McGreer et al.\ 2013 SDSS DR7', edgecolor='b', zorder=304, s=32) # Plot binned LF from literature f = 'Data/mcgreer_s82_published.dat' (sid, M1450, M1450_lerr, M1450_uerr, phi, phi_err) = np.loadtxt(f, unpack=True) d = phi_err * 1.0e-9 x = 10.0**phi phi_lerr = np.log10(x)-np.log10(x-d) phi_uerr = np.log10(x+d)-np.log10(x) phi_err = np.log10(phi_err * 1.0e-9) ax.errorbar(M1450, phi, ecolor='r', capsize=0, xerr=np.vstack((M1450_lerr, M1450_uerr)), yerr=np.vstack((phi_lerr, phi_uerr)), fmt='none', zorder=305) ax.scatter(M1450, phi, c='#ffffff', label='McGreer et al.\ 2013 SDSS Stripe 82', edgecolor='r', zorder=306, s=32) zrange = (4.7, 5.1) bins = np.arange(-29.3, -24.0, 0.5) mags, left, right, logphi, uperr, downerr = get_lf(zrange, bins) ax.scatter(mags, logphi, c='g', edgecolor='None', zorder=306, label='Our binning (SDSS DR7)', s=35) ax.errorbar(mags, logphi, ecolor='g', capsize=0, xerr=np.vstack((left, right)), yerr=np.vstack((uperr, downerr)), fmt='None',zorder=306) zrange = (4.7, 5.1) bins = np.arange(-27.275, -23., 0.55) mags, left, right, logphi, uperr, downerr = get_lf_s82(zrange, bins) ax.scatter(mags, logphi, c='maroon', edgecolor='None', zorder=306, label='Our binning (SDSS Stripe 82)', s=35) ax.errorbar(mags, logphi, ecolor='maroon', capsize=0, xerr=np.vstack((left, right)), yerr=np.vstack((uperr, downerr)), fmt='None',zorder=306) ax.set_xlim(-29.0, -23.0) ax.set_ylim(-11.0, -6.0) plt.legend(loc='upper left', fontsize=10, handlelength=3, frameon=False, framealpha=0.0, labelspacing=.1, handletextpad=-0.4, borderpad=0.2, scatterpoints=1) plt.savefig('mcgreer.pdf', bbox_inches='tight')
gkulkarniREPO_NAMEQLFPATH_START.@QLF_extracted@QLF-master@mcgreer.py@.PATH_END.py
{ "filename": "constants.py", "repo_name": "einsteinpy/einsteinpy", "repo_path": "einsteinpy_extracted/einsteinpy-main/src/einsteinpy/symbolic/constants.py", "type": "Python" }
from sympy.core.symbol import Symbol class SymbolicConstant(Symbol): """ This class inherits from ~sympy.core.symbol.Symbol """ def __new__(cls, name, descriptive_name=None, **assumptions): """ Constructor and Initializer Parameters ---------- name : str Short, commonly accepted name of the constant. For example, 'c' for Speed of light. descriptive_name : str The extended name of the constant. For example, 'Speed of Light' for 'c'. Defaults to None. """ instance = super(SymbolicConstant, cls).__new__(cls, name, **assumptions) instance._descriptive_name = descriptive_name return instance @property def descriptive_name(self): """ Returns the extended name of the constant """ return self._descriptive_name c = SymbolicConstant("c", "Speed Of Light") G = SymbolicConstant("G", "Gravitational Constant") Cosmo_Const = SymbolicConstant("Lambda", "Cosmological Constant") eps_0 = SymbolicConstant("eps_0", "Permittivity of free space") def get_constant(name): """ Returns a symbolic instance of the constant Parameters ---------- name : str Name of the constant. Currently available names are 'c', 'G', 'Cosmo_Const', 'eps_0'. Returns ------- ~einsteinpy.symbolic.constants.SymbolicConstant An instance of the required constant """ const_dict = {"c": c, "G": G, "Cosmo_Const": Cosmo_Const, "eps_0": eps_0} return const_dict[name]
einsteinpyREPO_NAMEeinsteinpyPATH_START.@einsteinpy_extracted@einsteinpy-main@src@einsteinpy@symbolic@constants.py@.PATH_END.py
{ "filename": "txttwilio.py", "repo_name": "Majoburo/Diagnosis", "repo_path": "Diagnosis_extracted/Diagnosis-master/txttwilio.py", "type": "Python" }
from twilio.rest import Client def sentxt(account_sid, auth_token, phone, message): # Your Account Sid and Auth Token from twilio.com/console # DANGER! This is insecure. See http://twil.io/secure client = Client(account_sid, auth_token) message = client.messages \ .create( body=message, from_='+17372042250', to='+1'+phone ) #print(message.sid) return
MajoburoREPO_NAMEDiagnosisPATH_START.@Diagnosis_extracted@Diagnosis-master@txttwilio.py@.PATH_END.py
{ "filename": "test_indexing.py", "repo_name": "pandas-dev/pandas", "repo_path": "pandas_extracted/pandas-main/pandas/tests/indexes/datetimelike_/test_indexing.py", "type": "Python" }
import numpy as np import pytest import pandas as pd from pandas import ( DatetimeIndex, Index, ) import pandas._testing as tm dtlike_dtypes = [ np.dtype("timedelta64[ns]"), np.dtype("datetime64[ns]"), pd.DatetimeTZDtype("ns", "Asia/Tokyo"), pd.PeriodDtype("ns"), ] @pytest.mark.parametrize("ldtype", dtlike_dtypes) @pytest.mark.parametrize("rdtype", dtlike_dtypes) def test_get_indexer_non_unique_wrong_dtype(ldtype, rdtype): vals = np.tile(3600 * 10**9 * np.arange(3, dtype=np.int64), 2) def construct(dtype): if dtype is dtlike_dtypes[-1]: # PeriodArray will try to cast ints to strings return DatetimeIndex(vals).astype(dtype) return Index(vals, dtype=dtype) left = construct(ldtype) right = construct(rdtype) result = left.get_indexer_non_unique(right) if ldtype is rdtype: ex1 = np.array([0, 3, 1, 4, 2, 5] * 2, dtype=np.intp) ex2 = np.array([], dtype=np.intp) tm.assert_numpy_array_equal(result[0], ex1) tm.assert_numpy_array_equal(result[1], ex2) else: no_matches = np.array([-1] * 6, dtype=np.intp) missing = np.arange(6, dtype=np.intp) tm.assert_numpy_array_equal(result[0], no_matches) tm.assert_numpy_array_equal(result[1], missing)
pandas-devREPO_NAMEpandasPATH_START.@pandas_extracted@pandas-main@pandas@tests@indexes@datetimelike_@test_indexing.py@.PATH_END.py
{ "filename": "constants.py", "repo_name": "tomasstolker/species", "repo_path": "species_extracted/species-main/species/core/constants.py", "type": "Python" }
""" Physical constants in the International System of Units (SI). """ from typing import Final from astropy import constants PLANCK: Final = constants.h.value # (m2 kg s-1) LIGHT: Final = constants.c.value # (m s-1) BOLTZMANN: Final = constants.k_B.value # (J K-1) GRAVITY: Final = constants.G.value # (m3 kgβˆ’1 sβˆ’2) PARSEC: Final = constants.pc.value # (m) AU: Final = constants.au.value # (m) R_JUP: Final = constants.R_jup.value # (m) M_JUP: Final = constants.M_jup.value # (kg) L_SUN: Final = constants.L_sun.value # (W) R_SUN: Final = constants.R_sun.value # (m) M_SUN: Final = constants.M_sun.value # (kg) R_EARTH: Final = constants.R_earth.value # (m) M_EARTH: Final = constants.M_earth.value # (kg) SIGMA_SB: Final = constants.sigma_sb.value # (W mβˆ’2 Kβˆ’4) ATOMIC_MASS: Final = constants.u.value # (kg) RYDBERG: Final = constants.Ryd.value # (m-1)
tomasstolkerREPO_NAMEspeciesPATH_START.@species_extracted@species-main@species@core@constants.py@.PATH_END.py
{ "filename": "pgm.py", "repo_name": "eggplantbren/RJObject", "repo_path": "RJObject_extracted/RJObject-master/Documents/Paper/pgm.py", "type": "Python" }
""" PGM for the general problem using daft (http://daft-pgm.org/) """ import matplotlib from matplotlib import rc rc("font", family="serif", size=12) rc("text", usetex=True) matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{amsmath}"] import daft pgm = daft.PGM([5., 4.], origin=[-2.5, -1.5]) # Create the nodes pgm.add_node(daft.Node('alpha', r'$\boldsymbol{\alpha}$', 0., 2.)) pgm.add_node(daft.Node('x', r'$\mathbf{x}_i$', 0., 0.)) pgm.add_node(daft.Node('data', r'$\mathcal{D}$', 2., 0., observed=True)) pgm.add_node(daft.Node('N', r'$N$', -2., 0.)) pgm.add_node(daft.Node('hidden', r'', -1., 0., scale=0, plot_params={'alpha':0})) # Add the edges pgm.add_edge('alpha', 'x') pgm.add_edge('x', 'data') pgm.add_edge('N', 'hidden') # Add the plates pgm.add_plate(daft.Plate([-1., -1., 2., 2.], label=r'Objects $i=1, ..., N$')) pgm.render() pgm.figure.savefig("pgm.eps") pgm.figure.savefig("pgm.pdf") pgm.figure.savefig('pgm.png')
eggplantbrenREPO_NAMERJObjectPATH_START.@RJObject_extracted@RJObject-master@Documents@Paper@pgm.py@.PATH_END.py
{ "filename": "README.md", "repo_name": "changhoonhahn/provabgs", "repo_path": "provabgs_extracted/provabgs-main/README.md", "type": "Markdown" }
# PRObabilistic Value-Added Bright Galaxy Survey (PROVABGS) [![Gitter](https://badges.gitter.im/provabgs/provabgs.svg)](https://gitter.im/provabgs/provabgs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![arXiv](https://img.shields.io/badge/arXiv-2202.01809-b31b1b.svg)](https://arxiv.org/abs/2202.01809) [![arXiv](https://img.shields.io/badge/arXiv-2209.14323-b31b1b.svg)](https://arxiv.org/abs/2209.14323) The PROVABGS catalog will provide measurements of galaxy properties, such as stellar mass, star formation rate, stellar metallicity, and stellar age for >10 million galaxies of the [DESI](http://desi.lbl.gov/) Bright Galaxy Survey. Full posterior distributions of these galaxy properties will be inferred using state-of-the-art Bayesian spectral energy distribution (SED) modeling of DESI spectroscopy and photometry. The `provabgs` Python package provides - a state-of-the-art stellar population synthesis (SPS) model based on non-parametric prescription for star formation history, a metallicity history that varies over the age of the galaxy, and a flexible dust prescription. - a neural network emulator (Kwon *et al.* in prep) for the SPS model that is >100x faster than the original SPS model and enables accelerated inference. Full posteriors of the 12 SPS parameters can be derived in ~10 minutes. The emulator is currently designed for galaxies from 0 < z < 0.6. - a Bayesian inference pipeline based on the [zeus](https://github.com/minaskar/zeus) ensemble slice Markov Chain Monte Carlo (MCMC) sample. For additional details see [documentation](https://changhoonhahn.github.io/provabgs) and [Hahn *et al* (2022)](https://arxiv.org/abs/2202.01809) ## Installation To install the package, clone the github repo and use `pip` to install ```bash # clone github repo git clone https://github.com/changhoonhahn/provabgs.git cd provabgs # install pip install -e . ``` ### requirements If you only plan to use `provabgs` with the neural emulators, then `provabgs` does not require `fsps`. However, if you want to use the original SPS model, you will need to install `python-fsps`. See `python-fsps` [documentation](https://python-fsps.readthedocs.io/en/latest/) for installation instruction. If you're using `provabgs` on NERSC, see [below](#fsps-on-nersc) for some notes on installing `FSPS` on `NERSC`. ### fsps on NERSC I've been running into some issues installing and using `fsps` on NERSC. *e.g.* there's an import error with libgfotran.so.5. The following may resolve the problem... ``` module unload PrgEnv-intel module load PrgEnv-gnu ``` ## Example Checkout the [nb/example.ipybn](https://github.com/changhoonhahn/provabgs/blob/main/nb/example.ipynb) notebook for an example on conducting Bayesian SED modeling on galaxy spectra using `provabgs`. It requires less than 10 lines of code and about 10 minutes! If you're interested in conducting Bayesian SED modeling on DESI spectra in particular, check out the [nb/tutorial_desispec.ipynb](https://github.com/changhoonhahn/provabgs/blob/main/nb/tutorial_desispec.ipynb) notebook. ## Team - [ChangHoon Hahn](https://changhoonhahn.github.io) (Princeton) - Rita Tojeiro (St Andrews) - Justin Alsing (Stockholm) - James Kyubin Kwon (Berkeley) ## Contact If you have any questions or need help using the package, please raise a github issue, post a message on gitter, or contact me at changhoon.hahn@princeton.edu
changhoonhahnREPO_NAMEprovabgsPATH_START.@provabgs_extracted@provabgs-main@README.md@.PATH_END.py
{ "filename": "torch_adagrad.py", "repo_name": "fchollet/keras", "repo_path": "keras_extracted/keras-master/keras/src/backend/torch/optimizers/torch_adagrad.py", "type": "Python" }
import torch from keras.src import ops from keras.src import optimizers from keras.src.backend.torch.optimizers import torch_parallel_optimizer class Adagrad( torch_parallel_optimizer.TorchParallelOptimizer, optimizers.Adagrad ): def _parallel_update_step( self, grads, variables, learning_rate, ): keras_variables = variables variables = [v.value for v in variables] dtype = variables[0].dtype lr = ops.cast(learning_rate, dtype) accumulators = [ self._accumulators[self._get_variable_index(variable)].value for variable in keras_variables ] torch._foreach_add_(accumulators, torch._foreach_mul(grads, grads)) torch._foreach_add_( variables, torch._foreach_div( torch._foreach_mul(grads, lr), torch._foreach_sqrt( torch._foreach_add(accumulators, self.epsilon) ), ), alpha=-1, )
fcholletREPO_NAMEkerasPATH_START.@keras_extracted@keras-master@keras@src@backend@torch@optimizers@torch_adagrad.py@.PATH_END.py
{ "filename": "sf_error.py", "repo_name": "waynebhayes/SpArcFiRe", "repo_path": "SpArcFiRe_extracted/SpArcFiRe-master/scripts/SpArcFiRe-pyvenv/lib/python2.7/site-packages/scipy/special/sf_error.py", "type": "Python" }
"""Warnings and Exceptions that can be raised by special functions.""" import warnings class SpecialFunctionWarning(Warning): """Warning that can be emitted by special functions.""" pass warnings.simplefilter("always", category=SpecialFunctionWarning) class SpecialFunctionError(Exception): """Exception that can be raised by special functions.""" pass
waynebhayesREPO_NAMESpArcFiRePATH_START.@SpArcFiRe_extracted@SpArcFiRe-master@scripts@SpArcFiRe-pyvenv@lib@python2.7@site-packages@scipy@special@sf_error.py@.PATH_END.py
{ "filename": "README.md", "repo_name": "thomasorb/orbs", "repo_path": "orbs_extracted/orbs-master/README.md", "type": "Markdown" }
# ORBS [ORBS](https://github.com/thomasorb/orbs) (*Outil de RΓ©duction Binoculaire pour* [SITELLE](http://www.cfht.hawaii.edu/Instruments/Sitelle)) is a data reduction software created to process data obtained with SITELLE. Is it the reduction software used by the CFHT. Documentation may be found on https://readthedocs.org/projects/orbs/ ## Installation ### Install ORB [ORBS](https://github.com/thomasorb/orbs) depends on [ORB](https://github.com/thomasorb/orb) which must be installed first. The archive and the installation instructions for [ORB](https://github.com/thomasorb/orb) can be found on github https://github.com/thomasorb/orb ### Install ORBS #### Install specific dependencies If you have followed the installation steps for orb, you already have a conda environment named `orb3`. ```bash conda install -n orb3 -c conda-forge clint html2text distro lxml python-magic conda activate orb3 pip install gitdb --no-deps pip install smmap --no-deps pip install gitpython --no-deps pip install cadcdata --no-deps pip install cadcutils --no-deps ``` You will also need cfitsio. On Ubuntu you can install it with ``` bash sudo apt install libcfitsio5 libcfitsio-bin ``` #### Install orbs module During ORB install you have already created a folder name `orb-stable`. You can thus do ```bash cd path/to/orb-stable git clone https://github.com/thomasorb/orbs.git python setup.py install # not for developer ``` **(developer only)** ```bash cd echo '/absolute/path/to/orb-stable/orbs' >> miniconda3/envs/orb3/lib/python3.7/site-packages/conda.pth ``` Test it: ```bash conda activate orb3 # you don't need to do it if you are already in the orb3 environment python -c 'import orbs.core' ```
thomasorbREPO_NAMEorbsPATH_START.@orbs_extracted@orbs-master@README.md@.PATH_END.py
{ "filename": "simulation_handling.py", "repo_name": "yt-project/yt", "repo_path": "yt_extracted/yt-main/yt/frontends/owls/simulation_handling.py", "type": "Python" }
import os from yt.frontends.gadget.simulation_handling import GadgetSimulation class OWLSSimulation(GadgetSimulation): r""" Initialize an OWLS Simulation object. Upon creation, the parameter file is parsed and the time and redshift are calculated and stored in all_outputs. A time units dictionary is instantiated to allow for time outputs to be requested with physical time units. The get_time_series can be used to generate a DatasetSeries object. parameter_filename : str The simulation parameter file. find_outputs : bool If True, the OutputDir directory is searched for datasets. Time and redshift information are gathered by temporarily instantiating each dataset. This can be used when simulation data was created in a non-standard way, making it difficult to guess the corresponding time and redshift information. Default: False. Examples -------- >>> import yt >>> es = yt.load_simulation("my_simulation.par", "OWLS") >>> es.get_time_series() >>> for ds in es: ... print(ds.current_time) """ def __init__(self, parameter_filename, find_outputs=False): GadgetSimulation.__init__(self, parameter_filename, find_outputs=find_outputs) def _snapshot_format(self, index=None): """ The snapshot filename for a given index. Modify this for different naming conventions. """ if self.parameters["OutputDir"].startswith("/"): data_dir = self.parameters["OutputDir"] else: data_dir = os.path.join(self.directory, self.parameters["OutputDir"]) if self.parameters["NumFilesPerSnapshot"] > 1: suffix = ".0" else: suffix = "" if self.parameters["SnapFormat"] == 3: suffix += ".hdf5" if index is None: count = "*" else: count = "%03d" % index keyword = f"{self.parameters['SnapshotFileBase']}_{count}" filename = os.path.join(keyword, f"{keyword}{suffix}") return os.path.join(data_dir, filename)
yt-projectREPO_NAMEytPATH_START.@yt_extracted@yt-main@yt@frontends@owls@simulation_handling.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "langchain-ai/langchain", "repo_path": "langchain_extracted/langchain-master/libs/core/tests/unit_tests/outputs/__init__.py", "type": "Python" }
langchain-aiREPO_NAMElangchainPATH_START.@langchain_extracted@langchain-master@libs@core@tests@unit_tests@outputs@__init__.py@.PATH_END.py
{ "filename": "CONTRIBUTING.md", "repo_name": "mavrix93/LightCurvesClassifier", "repo_path": "LightCurvesClassifier_extracted/LightCurvesClassifier-master/CONTRIBUTING.md", "type": "Markdown" }
# Contributing First of all thank you for considering to contribute! The project is quite big for one person a I would really appreciate any help. ## Code style - Just follow PEP8 - Well because of legacy code package actually use camelCase for class methods (PEP8 alert) - Function comments are welcomed and should follow [numpy style](http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_numpy.html) ## Testing - `pytest` is preferred way to do it (run `pytest test`) - Current tests coverage can be definitely improved - For coverage check use `py.test --cov=lcc test` ## Where to contribute The repo can be divided into 3 areas where it can be contributed: 1) `lcc` package 2) `lcc` CLI 3) Web Interface There are a lots of "ugly" parts of the code which should be refactored...
mavrix93REPO_NAMELightCurvesClassifierPATH_START.@LightCurvesClassifier_extracted@LightCurvesClassifier-master@CONTRIBUTING.md@.PATH_END.py
{ "filename": "test_delay.py", "repo_name": "ratt-ru/QuartiCal", "repo_path": "QuartiCal_extracted/QuartiCal-main/testing/tests/gains/test_delay.py", "type": "Python" }
from copy import deepcopy import pytest import numpy as np import dask.array as da from quartical.calibration.calibrate import add_calibration_graph from testing.utils.gains import apply_gains, reference_gains @pytest.fixture(scope="module") def opts(base_opts, select_corr): # Don't overwrite base config - instead create a copy and update. _opts = deepcopy(base_opts) _opts.input_ms.select_corr = select_corr _opts.solver.terms = ['G'] _opts.solver.iter_recipe = [100] _opts.solver.propagate_flags = False _opts.solver.convergence_fraction = 1 _opts.solver.convergence_criteria = 1e-7 _opts.solver.threads = 2 _opts.G.type = "delay" _opts.G.freq_interval = 0 _opts.G.initial_estimate = True return _opts @pytest.fixture(scope="module") def raw_xds_list(read_xds_list_output): # Only use the first xds. This overloads the global fixture. return read_xds_list_output[0][:1] @pytest.fixture(scope="module") def true_gain_list(predicted_xds_list): gain_list = [] for xds in predicted_xds_list: n_ant = xds.sizes["ant"] utime_chunks = xds.UTIME_CHUNKS n_time = sum(utime_chunks) chan_chunks = xds.chunks["chan"] n_chan = xds.sizes["chan"] n_dir = xds.sizes["dir"] n_corr = xds.sizes["corr"] chan_freq = xds.CHAN_FREQ.data chan_width = chan_freq[1] - chan_freq[0] band_centre = (chan_freq[0] + chan_freq[-1]) / 2 chunking = (utime_chunks, chan_chunks, n_ant, n_dir, n_corr) da.random.seed(0) delays = da.random.uniform( size=(n_time, 1, n_ant, n_dir, n_corr), low=-1/(2*chan_width), high=1/(2*chan_width) ) delays[:, :, 0, :, :] = 0 # Zero the reference antenna for safety. amp = da.ones( (n_time, n_chan, n_ant, n_dir, n_corr), chunks=chunking ) if n_corr == 4: # This solver only considers the diagonal elements. amp *= da.array([1, 0, 0, 1]) origin_chan_freq = chan_freq - band_centre phase = 2*np.pi*delays*origin_chan_freq[None, :, None, None, None] gains = amp*da.exp(1j*phase) gain_list.append(gains) return gain_list @pytest.fixture(scope="module") def corrupted_data_xds_list(predicted_xds_list, true_gain_list): corrupted_data_xds_list = [] for xds, gains in zip(predicted_xds_list, true_gain_list): n_corr = xds.sizes["corr"] ant1 = xds.ANTENNA1.data ant2 = xds.ANTENNA2.data time = xds.TIME.data row_inds = \ time.map_blocks(lambda x: np.unique(x, return_inverse=True)[1]) model = da.ones(xds.MODEL_DATA.data.shape, dtype=np.complex128) data = da.blockwise(apply_gains, ("rfc"), model, ("rfdc"), gains, ("rfadc"), ant1, ("r"), ant2, ("r"), row_inds, ("r"), n_corr, None, align_arrays=False, concatenate=True, dtype=model.dtype) corrupted_xds = xds.assign({ "DATA": ((xds.DATA.dims), data), "MODEL_DATA": ((xds.MODEL_DATA.dims), model), "FLAG": ((xds.FLAG.dims), da.zeros_like(xds.FLAG.data)), "WEIGHT": ((xds.WEIGHT.dims), da.ones_like(xds.WEIGHT.data)) } ) corrupted_data_xds_list.append(corrupted_xds) return corrupted_data_xds_list @pytest.fixture(scope="module") def add_calibration_graph_outputs(corrupted_data_xds_list, stats_xds_list, solver_opts, chain, output_opts): # Overload this fixture as we need to use the corrupted xdss. return add_calibration_graph(corrupted_data_xds_list, stats_xds_list, solver_opts, chain, output_opts) # ----------------------------------------------------------------------------- def test_residual_magnitude(cmp_post_solve_data_xds_list): # Magnitude of the residuals should tend to zero. for xds in cmp_post_solve_data_xds_list: residual = xds._RESIDUAL.data if residual.shape[-1] == 4: residual = residual[..., (0, 3)] # Only check on-diagonal terms. np.testing.assert_array_almost_equal(np.abs(residual), 0) def test_solver_flags(cmp_post_solve_data_xds_list): # The solver should not add addiitonal flags to the test data. for xds in cmp_post_solve_data_xds_list: np.testing.assert_array_equal(xds._FLAG.data, xds.FLAG.data) def test_gains(cmp_gain_xds_lod, true_gain_list): for solved_gain_dict, true_gain in zip(cmp_gain_xds_lod, true_gain_list): solved_gain_xds = solved_gain_dict["G"] solved_gain, solved_flags = da.compute(solved_gain_xds.gains.data, solved_gain_xds.gain_flags.data) true_gain = true_gain.compute() # TODO: This could be done elsewhere. n_corr = true_gain.shape[-1] solved_gain = reference_gains(solved_gain, n_corr) true_gain = reference_gains(true_gain, n_corr) true_gain[np.where(solved_flags)] = 0 solved_gain[np.where(solved_flags)] = 0 # To ensure the missing antenna handling doesn't render this test # useless, check that we have non-zero entries first. assert np.any(solved_gain), "All gains are zero!" np.testing.assert_array_almost_equal(true_gain, solved_gain) def test_gain_flags(cmp_gain_xds_lod): for solved_gain_dict in cmp_gain_xds_lod: solved_gain_xds = solved_gain_dict["G"] solved_flags = solved_gain_xds.gain_flags.values frows, fchans, fants, fdir = np.where(solved_flags) # We know that these antennas are missing in the test data. No other # antennas should have flags. assert set(np.unique(fants)) == {18, 20} # -----------------------------------------------------------------------------
ratt-ruREPO_NAMEQuartiCalPATH_START.@QuartiCal_extracted@QuartiCal-main@testing@tests@gains@test_delay.py@.PATH_END.py
{ "filename": "fitting_backend.py", "repo_name": "spacetelescope/jdaviz", "repo_path": "jdaviz_extracted/jdaviz-main/jdaviz/configs/default/plugins/model_fitting/fitting_backend.py", "type": "Python" }
from asteval import Interpreter import multiprocessing as mp from multiprocessing import Pool import numpy as np import astropy.units as u from specutils import Spectrum1D from specutils.fitting import fit_lines __all__ = ['fit_model_to_spectrum'] def fit_model_to_spectrum(spectrum, component_list, expression, run_fitter=False, window=None, n_cpu=None): """Fits a `~astropy.modeling.CompoundModel` to a `~specutils.Spectrum1D` instance. If the input spectrum represents a spectral cube, then fits the model to every spaxel in the cube, using a multiprocessor pool running in parallel (if ``n_cpu`` is larger than 1). Parameters ---------- spectrum : `~specutils.Spectrum1D` The spectrum to be fitted. component_list : list Spectral model subcomponents stored in a list. Their ``'name'`` attribute must be unique. Each subcomponent should be an initialized object from `~astropy.modeling.Model`. expression : str The arithmetic expression that combines together the model subcomponents. The subcomponents are referred via their ``'name'`` attribute. run_fitter : bool **This is currently being ignored for 3D fits.** When `False` (the default), the function composes the compound model and returns it without fitting. window : `None` or `~specutils.SpectralRegion` See :func:`specutils.fitting.fit_lines`. n_cpu : `None` or int **This is only used for spectral cube fitting.** Number of cores to use for multiprocessing. Using all the cores at once is not recommended. If `None`, it will use max cores minus one. Set this to 1 for debugging. Returns ------- output_model : `~astropy.modeling.CompoundModel` or list The model resulting from the fit. In the case of a 1D input spectrum, a single model instance is returned. In case of a 3D spectral cube input, instead o model instances for every spaxel, a list with 2D arrays, each one storing fitted parameter values for all spaxels, is returned. output_spectrum : `~specutils.Spectrum1D` The realization of the fitted model as a spectrum. The spectrum will be 1D or 3D depending on the shape of input spectrum. """ # Initial guess for the fit. initial_model = _build_model(component_list, expression) if len(spectrum.shape) > 1: return _fit_3D(initial_model, spectrum, window=window, n_cpu=n_cpu) else: return _fit_1D(initial_model, spectrum, run_fitter, window=window) def _fit_1D(initial_model, spectrum, run_fitter, filter_non_finite=True, window=None): """ Fits an astropy CompoundModel to a Spectrum1D instance. Parameters ---------- initial_model : :class: `astropy.modeling.CompoundModel` Initial guess for the model to be fitted. spectrum : :class:`specutils.Spectrum1D` The spectrum to be fitted. run_fitter : bool When False (the default), the function composes the compound model and returns it without fitting. window : `None` or :class:`specutils.spectra.SpectralRegion` See :func:`specutils.fitting.fitmodels.fit_lines`. Returns ------- output_model : :class: `astropy.modeling.CompoundModel` The model resulting from the fit. output_spectrum : :class:`specutils.Spectrum1D` The realization of the fitted model as a spectrum. """ if run_fitter: if spectrum.uncertainty and not np.all(spectrum.uncertainty.array == 0): weights = 'unc' else: weights = None output_model = fit_lines(spectrum, initial_model, weights=weights, filter_non_finite=filter_non_finite, window=window) output_values = output_model(spectrum.spectral_axis) else: # Return without fitting. output_model = initial_model output_values = initial_model(spectrum.spectral_axis) # Build return spectrum output_spectrum = Spectrum1D(spectral_axis=spectrum.spectral_axis, flux=output_values, mask=spectrum.mask) return output_model, output_spectrum def _fit_3D(initial_model, spectrum, window=None, n_cpu=None): """ Fits an astropy CompoundModel to every spaxel in a cube using a multiprocessor pool running in parallel. Computes realizations of the models over each spaxel. Parameters ---------- initial_model : :class: `astropy.modeling.CompoundModel` Initial guess for the model to be fitted. spectrum : :class:`specutils.Spectrum1D` The spectrum that stores the cube in its 'flux' attribute. window : `None` or :class:`specutils.spectra.SpectralRegion` See :func:`specutils.fitting.fitmodels.fit_lines`. n_cpu : `None` or int Number of cores to use for multiprocessing. Using all the cores at once is not recommended. If `None`, it will use max cores minus one. Set this to 1 for debugging. Returns ------- output_model : :list: a list that stores 2D arrays. Each array contains one parameter from `astropy.modeling.CompoundModel` instances fitted to every spaxel in the input cube. output_spectrum : :class:`specutils.Spectrum1D` The spectrum that stores the fitted model values in its 'flux' attribute. """ if n_cpu is None: n_cpu = mp.cpu_count() - 1 # Generate list of all spaxels to be fitted spaxels = _generate_spaxel_list(spectrum) fitted_models = [] # Build cube with empty arrays, one per input spaxel. These # will store the flux values corresponding to the fitted # model realization over each spaxel. output_flux_cube = np.zeros(shape=spectrum.flux.shape) # Callback to collect results from workers into the cubes def collect_result(results): for i in range(len(results['x'])): x = results['x'][i] y = results['y'][i] model = results['fitted_model'][i] fitted_values = results['fitted_values'][i] # Store fitted model parameters fitted_models.append({"x": x, "y": y, "model": model}) # Store fitted values output_flux_cube[x, y, :] = fitted_values # Run multiprocessor pool to fit each spaxel and # compute model values on that same spaxel. if n_cpu > 1: results = [] pool = Pool(n_cpu) # The communication overhead of spawning a process for each *individual* # parameter set is prohibitively high (it's actually faster to run things # sequentially). Instead, chunk the spaxel list based on the number of # available processors, and have each processor do the model fitting # on the entire subset of spaxel tuples, then return the set of results. for spx in np.array_split(spaxels, n_cpu): # Worker for the multiprocess pool. worker = SpaxelWorker(spectrum.flux, spectrum.spectral_axis, initial_model, param_set=spx, window=window, mask=spectrum.mask) r = pool.apply_async(worker, callback=collect_result) results.append(r) for r in results: r.wait() pool.close() # This route is only for dev debugging because it is very slow # but exceptions will not get swallowed up by multiprocessing. else: # pragma: no cover worker = SpaxelWorker(spectrum.flux, spectrum.spectral_axis, initial_model, param_set=spaxels, window=window, mask=spectrum.mask) collect_result(worker()) # Build output 3D spectrum funit = spectrum.flux.unit output_spectrum = Spectrum1D(wcs=spectrum.wcs, flux=output_flux_cube * funit, mask=spectrum.mask) return fitted_models, output_spectrum class SpaxelWorker: """ A class with callable instances that perform fitting over a spaxel. It provides the callable for the `Pool.apply_async` function, and also holds everything necessary to perform the fit over one spaxel. Additionally, the callable computes the realization of the model just fitted, over that same spaxel. We cannot do these two steps (fit and compute) separately, since we cannot modify parameter values in an already built CompoundModel instance. We need to use the current model instance while it still exists. """ def __init__(self, flux_cube, wave_array, initial_model, param_set, window=None, mask=None): self.cube = flux_cube self.wave = wave_array self.model = initial_model self.param_set = param_set self.window = window self.mask = mask def __call__(self): results = {'x': [], 'y': [], 'fitted_model': [], 'fitted_values': []} for parameters in self.param_set: x = parameters[0] y = parameters[1] # Calling the Spectrum1D constructor for every spaxel # turned out to be less expensive than expected. Experiments # show that the cost amounts to a couple percent additional # running time in comparison with a version that uses a 3D # spectrum as input. Besides, letting an externally-created # spectrum reference into the callable somehow prevents it # to execute. This behavior was seen also with other functions # passed to the callable. flux = self.cube[x, y, :] if self.mask is not None: mask = self.mask[x, y, :] else: # If no mask is provided: mask = np.zeros_like(flux.value).astype(bool) sp = Spectrum1D(spectral_axis=self.wave, flux=flux, mask=mask) if sp.uncertainty and not np.all(sp.uncertainty.array == 0): weights = 'unc' else: weights = None fitted_model = fit_lines(sp, self.model, window=self.window, weights=weights) fitted_values = fitted_model(self.wave) results['x'].append(x) results['y'].append(y) results['fitted_model'].append(fitted_model) results['fitted_values'].append(fitted_values) return results def _build_model(component_list, expression): """ Builds an astropy CompoundModel from a list of components and an expression that links them to each other. Parameters ---------- component_list : list Spectral model subcomponents stored in a list. Their ``'name'`` attribute must be unique. Each subcomponent should be an initialized object from `astropy.modeling.models' expression : str The arithmetic expression that combines together the model subcomponents. The subcomponents are referred via their ``'name'`` attribute. Returns ------- model : :class:`astropy.modeling.CompoundModel` The model resulting from the fit. """ # The expression parser needs the subcomponents stored in a # dict, with keys taken from their names. This mechanism can # be augmented with status feedback to the UI. This requires # the code in here to be refactored to provide the necessary # hooks for the GUI (see # specviz/specviz/plugins/model_editor/models.py around lines # 200-230). model_dict = {} for component in component_list: model_dict[component.name] = component aeval = Interpreter(usersyms=model_dict) model = aeval(expression) return model def _handle_parameter_units(model, fitted_parameters_cube, param_units): """ Extracts parameter units from a CompoundModel and parameter values from a list of 2D numpy arrays, and returns a dict of 2D Quantity arrays. The dict values are keyed by the parameter names. Parameters ---------- model : :class:`astropy.modeling.CompoundModel` An instance of a model. fitted_parameters_cube : ndarray A 3D array in which the 1st dimension addresses model parameters, and the 2nd and 3rd dimensions address spaxels. param_units : list A list with each parameter's units (this is not available in the model instance itself). Returns ------- fitted_parameters_dict : dict 2D Quantity arrays keyed by parameter name """ fitted_parameters_dict = {} for index in range(len(model.parameters)): key = model.param_names[index] _ary = fitted_parameters_cube[index, :, :] fitted_parameters_dict[key] = u.Quantity(_ary, param_units[index]) return fitted_parameters_dict def _generate_spaxel_list(spectrum): """ Generates a list with tuples, each one addressing the (x,y) coordinates of a spaxel in a 3-D spectrum cube. If a mask is available, skip masked indices. Parameters ---------- spectrum : :class:`specutils.Spectrum1D` The spectrum that stores the cube in its ``'flux'`` attribute. Returns ------- spaxels : list List with spaxels """ n_x, n_y, _ = spectrum.flux.shape if spectrum.mask is None: spx = [[(x, y) for x in range(n_x)] for y in range(n_y)] else: # return only non-masked spaxels spx = [[(x, y) for x in range(n_x) if np.any(~spectrum.mask[x, y])] for y in range(n_y) if np.any(~spectrum.mask[:, y])] spaxels = [item for sublist in spx for item in sublist] return spaxels
spacetelescopeREPO_NAMEjdavizPATH_START.@jdaviz_extracted@jdaviz-main@jdaviz@configs@default@plugins@model_fitting@fitting_backend.py@.PATH_END.py
{ "filename": "run.py", "repo_name": "ratt-ru/Stimela-classic", "repo_path": "Stimela-classic_extracted/Stimela-classic-master/stimela/cargo/cab/ragavi/src/run.py", "type": "Python" }
# -*- coding: future_fstrings -*- import sys from scabha import config, parse_parameters, prun args = [config.binary] + parse_parameters(repeat=" ") # run the command if prun(args) != 0: sys.exit(1)
ratt-ruREPO_NAMEStimela-classicPATH_START.@Stimela-classic_extracted@Stimela-classic-master@stimela@cargo@cab@ragavi@src@run.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "plotly/plotly.py", "repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/graph_objs/scatter3d/line/__init__.py", "type": "Python" }
import sys from typing import TYPE_CHECKING if sys.version_info < (3, 7) or TYPE_CHECKING: from ._colorbar import ColorBar from . import colorbar else: from _plotly_utils.importers import relative_import __all__, __getattr__, __dir__ = relative_import( __name__, [".colorbar"], ["._colorbar.ColorBar"] )
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@graph_objs@scatter3d@line@__init__.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "ARCLab-MIT/kspdg", "repo_path": "kspdg_extracted/kspdg-main/src/kspdg/utils/__init__.py", "type": "Python" }
# Copyright (c) 2022, MASSACHUSETTS INSTITUTE OF TECHNOLOGY # Subject to FAR 52.227-11 – Patent Rights – Ownership by the Contractor (May 2014). # SPDX-License-Identifier: MIT
ARCLab-MITREPO_NAMEkspdgPATH_START.@kspdg_extracted@kspdg-main@src@kspdg@utils@__init__.py@.PATH_END.py
{ "filename": "_family.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/scatter/marker/colorbar/tickfont/_family.py", "type": "Python" }
import _plotly_utils.basevalidators class FamilyValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name="family", parent_name="scatter.marker.colorbar.tickfont", **kwargs, ): super(FamilyValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), no_blank=kwargs.pop("no_blank", True), strict=kwargs.pop("strict", True), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@scatter@marker@colorbar@tickfont@_family.py@.PATH_END.py
{ "filename": "__init__.py", "repo_name": "Kamuish/archi", "repo_path": "archi_extracted/archi-master/pyarchi/utils/optimization/__init__.py", "type": "Python" }
KamuishREPO_NAMEarchiPATH_START.@archi_extracted@archi-master@pyarchi@utils@optimization@__init__.py@.PATH_END.py
{ "filename": "_customdata.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/volume/_customdata.py", "type": "Python" }
import _plotly_utils.basevalidators class CustomdataValidator(_plotly_utils.basevalidators.DataArrayValidator): def __init__(self, plotly_name="customdata", parent_name="volume", **kwargs): super(CustomdataValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@volume@_customdata.py@.PATH_END.py
{ "filename": "test_wfEstimator.py", "repo_name": "lsst-ts/ts_wep", "repo_path": "ts_wep_extracted/ts_wep-main/tests/estimation/test_wfEstimator.py", "type": "Python" }
# This file is part of ts_wep. # # Developed for the LSST Telescope and Site Systems. # This product includes software developed by the LSST Project # (https://www.lsst.org). # See the COPYRIGHT file at the top-level directory of this distribution # for details of code ownership. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. import unittest import numpy as np from lsst.ts.wep.estimation import WfEstimator from lsst.ts.wep.utils import WfAlgorithmName, convertZernikesToPsfWidth from lsst.ts.wep.utils.modelUtils import forwardModelPair class TestWfEstimator(unittest.TestCase): """Test the wavefront estimator class.""" def testCreateWithDefaults(self): WfEstimator() def testBadAlgoName(self): with self.assertRaises(ValueError): WfEstimator(algoName="fake") def testBadAlgoConfig(self): with self.assertRaises(TypeError): WfEstimator(algoConfig=1) def testBadInstConfig(self): with self.assertRaises(TypeError): WfEstimator(instConfig=1) with self.assertRaises(FileNotFoundError): WfEstimator(instConfig="fake") def testBadNollIndices(self): with self.assertRaises(ValueError): WfEstimator(nollIndices=[3, 4, 5]) with self.assertRaises(ValueError): WfEstimator(nollIndices=[4, 6, 5]) with self.assertRaises(ValueError): WfEstimator(nollIndices=[4, 5, 5]) with self.assertRaises(ValueError): WfEstimator(nollIndices=[4, 5]) def testBadStartWithIntrinsic(self): with self.assertRaises(TypeError): WfEstimator(startWithIntrinsic="fake") def testBadReturnWfDev(self): with self.assertRaises(TypeError): WfEstimator(returnWfDev="fake") def testBadUnits(self): with self.assertRaises(ValueError): WfEstimator(units="parsecs") def testBadSaveHistory(self): with self.assertRaises(TypeError): WfEstimator(saveHistory="fake") def testDifferentNollIndices(self): # Get the test data zkTrue, intra, extra = forwardModelPair() # Test every wavefront algorithm for name in WfAlgorithmName: # Estimate [4, 5, 6] wfEst = WfEstimator(algoName=name, nollIndices=[4, 5, 6], units="m") zk0 = wfEst.estimateZk(intra, extra) self.assertEqual(len(zk0), 3) # Estimate with [4, 5, 6, 20, 21] wfEst = WfEstimator(algoName=name, nollIndices=[4, 5, 6, 20, 21], units="m") zk1 = wfEst.estimateZk(intra, extra) self.assertEqual(len(zk1), 5) # Make sure results are pretty similar for [4, 5, 6] self.assertLess(np.sqrt(np.sum(np.square(zk1[:-2] - zk0))), 10e-9) def testStartWithIntrinsic(self): # Get the test data zkTrue, intra, extra = forwardModelPair() # Test every wavefront algorithm for name in WfAlgorithmName: # Estimate starting with intrinsics wfEst = WfEstimator(algoName=name, startWithIntrinsic=True, units="m") zk0 = wfEst.estimateZk(intra, extra) # Estimate starting with zeros wfEst = WfEstimator(algoName=name, startWithIntrinsic=False, units="m") zk1 = wfEst.estimateZk(intra, extra) # Make sure the results are pretty similar self.assertLess(np.sqrt(np.sum(np.square(zk1 - zk0))), 80e-9) def testReturnWfDev(self): # Get the test data zkTrue, intra, extra = forwardModelPair() # Test every wavefront algorithm for name in WfAlgorithmName: # Estimate OPD wfEst = WfEstimator(algoName=name, returnWfDev=False, units="m") opd = wfEst.estimateZk(intra, extra) # Estimate wavefront deviation wfEst = WfEstimator(algoName=name, returnWfDev=True, units="m") wfDev = wfEst.estimateZk(intra, extra) # Make sure that OPD = wf dev + intrinsics zkInt = wfEst.instrument.getIntrinsicZernikes( *intra.fieldAngle, nollIndices=np.arange(opd.size) + 4, ) # Make sure the results are identical self.assertTrue(np.allclose(opd, wfDev + zkInt)) def testUnits(self): # Get the test data zkTrue, intra, extra = forwardModelPair() # Test every wavefront algorithm for name in WfAlgorithmName: zk = dict() # Test every available unit for units in ["m", "um", "nm", "arcsec"]: wfEst = WfEstimator(algoName=name, units=units) zk[units] = wfEst.estimateZk(intra, extra) self.assertTrue(np.allclose(zk["m"], zk["um"] / 1e6)) self.assertTrue(np.allclose(zk["m"], zk["nm"] / 1e9)) self.assertTrue( np.allclose( convertZernikesToPsfWidth(zk["um"]), zk["arcsec"], ) ) if __name__ == "__main__": # Do the unit test unittest.main()
lsst-tsREPO_NAMEts_wepPATH_START.@ts_wep_extracted@ts_wep-main@tests@estimation@test_wfEstimator.py@.PATH_END.py
{ "filename": "README.md", "repo_name": "philbull/FastBox", "repo_path": "FastBox_extracted/FastBox-main/README.md", "type": "Markdown" }
# FastBox [![Documentation Status](https://readthedocs.org/projects/fastbox/badge/?version=latest)](https://fastbox.readthedocs.io/en/latest/?badge=latest) Fast simulations of cosmological density fields, subject to anisotropic filtering, biasing, redshift-space distortions, foregrounds etc. This is intended to be a fast and simple simulator for post-EoR 21cm intensity maps and their cross-correlation with galaxy samples, with enough complexity to test realistic cosmological analysis methods. ## Installation To install `fastbox`, simply run `python setup.py install`. The following are required dependencies (all of which can be installed via `pip`): * `numpy>=1.18` * `scipy>=1.5` * `matplotlib>=2.2` * `scikit-learn` * `pyccl` The following optional dependencies are needed for some of the foreground modelling and filtering functions to work: * `healpy` * `lmfit` * `multiprocessing` * `GPy` ## Current features - Gaussian and log-normal density fields for any cosmology - Redshift-space transform, linear biasing etc - Arbitrary anisotropic filters as a function of kperp and kparallel - Poisson realisations of halo/galaxy samples - Radiometer noise and beam convolutions (FFT and direct convolution) - Several diffuse and point source foreground models, including GSM, Planck Sky Model, and the Battye et al. point source model. - Foreground filtering via PCA, ICA, Kernel PCA, least-squares etc. - Integration with the DESC Core Cosmology Library (`pyccl`) - Calculate power spectra, correlation functions, and their multipoles, via `nbodykit` - Detect and generate catalogues of cosmic voids
philbullREPO_NAMEFastBoxPATH_START.@FastBox_extracted@FastBox-main@README.md@.PATH_END.py
{ "filename": "data.py", "repo_name": "POSYDON-code/POSYDON", "repo_path": "POSYDON_extracted/POSYDON-main/posydon/active_learning/psy_cris/data.py", "type": "Python" }
"""Module for handling data for PSY-CRIS.""" __authors__ = [ "Kyle Akira Rocha <kylerocha2024@u.northwestern.edu>", "Scott Coughlin <scottcoughlin2014@u.northwestern.edu>", ] import numpy as np import matplotlib.pyplot as plt from matplotlib.lines import Line2D import pandas as pd import math import time from collections import OrderedDict from sklearn.neighbors import NearestNeighbors def calc_avg_dist(data, n_neighbors, neighbor=None): """Get the average distance to the nearest neighbors in the data set. (NearestNeighbors from sklearn.neighbors) Parameters ---------- data : ndarray Data to train the NearestNeighbors class on. n_neighbors : int Number of neighbors to use when finding average distance. neighbor : instance of NearestNeightbors class For passing your own object. Returns ------- avg_dist : array The average distance between nearest neighbors. g_indi : array Indicies that correspond to the nearest neighbors. """ if neighbor: neigh = neighbor else: neigh = NearestNeighbors() neigh.fit(data) # Since we pass the original data, the first nearest point is itself. If we # want 2 nearest neighbors, we ask for 3 because the first will always be 0 dist, indicies = neigh.kneighbors(data, n_neighbors=(n_neighbors + 1)) g_dist = (dist.T[1:len(dist)]).T g_indi = (indicies.T[1:len(indicies)]).T avg_dist = np.mean(g_dist, axis=1) return avg_dist, g_indi def calc_avg_p_change(data, where_nearest_neighbors, undefined_p_change_val=None): """Calculate the average fractional change in a given data set. The method uses the N nearest neighbors (calculated beforehand). Parameters ---------- data : ndarray Data set to calculate percent change. where_nearest_neighbors : dict Indicies in data for the n nearest neighbors in input space. undefined_p_change_val : optional For output with an undefined percent change (zero value), this kwarg defines what is put in its place. Defaults to nan. Returns ------- avg_p_change_holder : ndarray Each element conatins the average percent change for a given number of neighbors. If any output values are 0, then a nan is put in place of a percent change. """ where_zero = np.where(data == 0)[0] where_not_zero = np.where(data != 0)[0] if len(where_zero) == len(data): return None avg_p_change_holder = [] for n_, indicies in where_nearest_neighbors.items(): diff_holder = [] for i in range(n_): nearest_data = data[indicies.T[i]] diff_holder.append(data - nearest_data) diffs = np.array(diff_holder).T avg_diffs = np.mean(diffs, axis=1) avg_p_change = np.zeros(data.shape) avg_p_change[where_not_zero] = ( abs(avg_diffs[where_not_zero]) / data[where_not_zero] ) if undefined_p_change_val is None: avg_p_change[where_zero] = np.nan else: avg_p_change[where_zero] = undefined_p_change_val avg_p_change_holder.append(avg_p_change) return np.array(avg_p_change_holder) class TableData: """ For managing data sets used for classification and regression. Reads tables of simulation data where a single row represents one simulation. Each column in a row represents different inputs (initial conditions) and outputs (result, continuous variables). If using multiple files, each file is assumed to have the same columns. You may also directly load a pandas DataFrame instead of reading in files. Example data structure expected in files or pandas DataFrame: 0 input_1 input_2 outcome output_1 output_2 output_3 ... 1 1.5 2.6 "A" 100 0.19 - ... 2 1.5 3.0 "B" - - - ... 3 2.0 2.6 "C" - - 6 ... ... The above table has dashes '-' in output columns to indicate NaN values. You may have a similar structure if different classes have fundamentally different outputs. """ def __vb_helper(self, verbose_bool, info_string): """Help clean up verbose print statements and storing info. By default, store the passed info_string regardless of verbose_bool. """ if verbose_bool: print(info_string) self._for_info_.append(info_string) def __init__( self, table_paths, input_cols, output_cols, class_col_name, my_DataFrame=None, omit_vals=None, omit_cols=None, subset_interval=None, verbose=False, my_colors=None, neighbor=None, n_neighbors=None, undefined_p_change_val=None, read_csv_kwargs={}, **kwargs ): """Initialize the TableData instance. Parameters ---------- table_paths : list List of file paths to read in as data. if None, a pandas DataFrame is used instead input_cols : list List of names of the columns which will be considered 'input'. output_cols : list List of names of the columns which will be considered 'output'. This should include the class column name. class_col_name : str Name of column which contains classification data. my_DataFrame : pandas DataFrame, optional If given, use this instead of reading files. omit_vals : list, optional Numerical values that you wish to omit from the entire data set. If a row contains the value, the entire row is removed. (For example you may want to omit all rows if they contain "-1" or "failed".) omit_cols : list, optional Column names that you wish to omit from the data set. subset_interval : array, optional Use some subset of the data files being loaded in. An array with integers indicating the rows that will be kept. my_colors : list, optional Colors to use for classification plots. n_neighbors : list, optional List of integers that set the number of neighbors to use to calculate average distances. (default None) neighbor : instance of sklearn.neighbors.NearestNeighbors, optional To use for average distances. See function 'calc_avg_dist()'. undefined_p_change_val : optional, float Sets the undefined value used when calculating percent change fails due to zero values in the output data. Default uses nan. verbose : bool, optional Print statements with extra info. read_csv_kwargs : dict, optional Kwargs passed to the pandas function 'read_csv()'. **kwargs Extra kwargs """ start_time = time.time() self._for_info_ = [] # storing info strings # --------- data pre-processing --------- self._df_list_ = [] # data frame list self._df_index_keys_ = [] # index keys (for rows in _full_data_) self._files_ = table_paths # assumed to be one column name + string self.class_col_name = class_col_name if isinstance(my_DataFrame, pd.DataFrame): self.__vb_helper(verbose, "Using loaded Pandas DataFrame") self._full_data_ = my_DataFrame else: # Read in all data files and add to _df_list_ info_str_01 = "Reading in data from {0} file(s).".format( len(table_paths)) self.__vb_helper(verbose, info_str_01) for num, path in enumerate(table_paths): info_str_02 = "\t'{0}'".format(path) self.__vb_helper(verbose, info_str_02) df = pd.read_csv(path, **read_csv_kwargs) self._df_list_.append(df) self._df_index_keys_.append("df" + str(num)) info_str_03 = "Finished reading data.\n" self.__vb_helper(verbose, info_str_03) # _df_index_keys_ setting index of Nth file # the data is from with 'dfN'. self._full_data_ = pd.concat(self._df_list_, join="outer", ignore_index=False, keys=self._df_index_keys_, sort=True) # remove rows and columns with unwanted data if omit_vals is not None: ct = 0 # counter for j, val in enumerate(omit_vals): row_where_omit_val = np.unique(np.where( self._full_data_.values == val)[0]) df_keys_for_omit = self._full_data_.index[row_where_omit_val] self._full_data_ = self._full_data_.drop(df_keys_for_omit, axis=0) ct += len(row_where_omit_val) info_str_04 = " - Removed {0} rows containing: {1}".format( len(row_where_omit_val), omit_vals[j] ) self.__vb_helper(verbose, info_str_04) info_str_05 = "Removed a total of {0} rows.".format(ct) self.__vb_helper(verbose, info_str_05) # remove entire columns if omit_cols is not None: self._full_data_ = self._full_data_.drop(columns=omit_cols) info_str_06 = "Removed columns: {0}".format(omit_cols) self.__vb_helper(verbose, info_str_06) # use a subset of the original data table if subset_interval is not None: len_original_data = len(self._full_data_) self._full_data_ = self._full_data_.iloc[subset_interval, :] info_str_07 = ("--Using Subset--\n{0} percent of total data set.". format(len(self._full_data_) / len_original_data * 100)) self.__vb_helper(verbose, info_str_07) info_str_08 = "Total number of data points: {0}\n".format( len(self._full_data_)) self.__vb_helper(verbose, info_str_08) # column names in fully concatenated data self.col_names = np.array(self._full_data_.columns) # input and output data for usr_input in [input_cols, output_cols]: for a_name in usr_input: if a_name not in self.col_names: info_str_09 = ("\tWarning: No columns found with name " "'{0}'. Check your data.".format(a_name)) self.__vb_helper(verbose, info_str_09) # raise Warning( info_str_09 ) TODO input_cols = [i for i in input_cols if i in self.col_names] output_cols = [i for i in output_cols if i in self.col_names] self._input_ = self._full_data_[input_cols] self._output_ = self._full_data_[output_cols] # max and min for input values self._max_input_vals = [] self._min_input_vals = [] for data_column in self._input_.values.T: self._max_input_vals.append(max(data_column)) self._min_input_vals.append(min(data_column)) # --------- classification variables --------- try: self._unique_class_keys_ = np.unique( self._full_data_[class_col_name]) self._class_dtype_ = type(self._unique_class_keys_[0]) except KeyError as class_col_name: info_str_10 = "Class column {0} not in {1}".format( class_col_name, np.array(self._full_data_.keys()).astype(str) ) self.__vb_helper(False, info_str_10) raise KeyError(info_str_10) self.num_classes = len(self._unique_class_keys_) self.class_ids = np.arange(0, self.num_classes, 1, dtype=int) info_str_11 = ( "Input columns: {0}".format(len(input_cols)) + "\n" + "Output columns: {0}".format(len(output_cols)) + "\n" + "Unique classes found in '{0}': {1}".format( class_col_name, self.num_classes ) ) self.__vb_helper(verbose, info_str_11) # mapping dict - forward & backward self._class_id_mapping_ = OrderedDict() for i in self.class_ids: self._class_id_mapping_[i] = self._unique_class_keys_[i] self._class_id_mapping_[self._unique_class_keys_[i]] = i # classification column replaced with class_id self._class_col_ = self._full_data_[class_col_name].values.astype( self._class_dtype_ ) self._class_col_to_ids_ = [] for cl in self._class_col_: self._class_col_to_ids_.append(self._class_id_mapping_[cl]) if my_colors is not None: self._class_colors_ = my_colors self.__vb_helper(verbose, "Using custom class colors.") else: self._class_colors_ = ["#EC6666", "#90A245", "#F5C258", "#1668E8", "#473335", "#98C0CB", "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8"] self.__vb_helper(verbose, "Using default class colors.") # --------- regression variables --------- # make input and output dicts for each class self._regr_inputs_ = OrderedDict() self._regr_outputs_ = OrderedDict() for cls_name in self._unique_class_keys_: rows_where_class = np.where(self._output_[class_col_name] == cls_name) if len(rows_where_class[0]) == 0: info_str_extra_1 = ("\tWarning: no output with class name {0}." .format(cls_name)) self.__vb_helper(verbose, info_str_extra_1) self._regr_inputs_[cls_name] = self._input_.iloc[rows_where_class] self._regr_outputs_[cls_name] = self._output_.iloc[ rows_where_class] info_str_12 = ("\nFinding values to regress:\n" + "Num output(s) \t Class Name") self.__vb_helper(verbose, info_str_12) # find valid regression data and link it to a class self.regr_names = self._output_.columns self._num_outputs_to_regr_ = [] self._regr_dfs_per_class_ = OrderedDict() # for each class - find columns which can be converted to floats for i, tuple_output in enumerate(self._regr_outputs_.items()): output_per_class = tuple_output[1] # 0 returns key; 1 returns data # this makes sure the classification column is not part of # regression data in the case classes are integers or somthing where_no_classification = np.where( output_per_class.columns != class_col_name )[0] cols_with_float = [] bad_cols = [] # go through first row and try to convert each element to float # - also check if nan for col_num, val in zip( where_no_classification, output_per_class.iloc[0, where_no_classification], ): try: converted_val = float( val ) # if fails -> straight to except (skips next line) if math.isnan(converted_val): bad_cols.append(col_num) else: cols_with_float.append(col_num) except Exception: bad_cols.append(col_num) info_str_13 = "%7i \t '%s'" % ( len(cols_with_float), self._unique_class_keys_[i], ) self.__vb_helper(verbose, info_str_13) self._num_outputs_to_regr_.append(len(cols_with_float)) regression_vals_df = output_per_class.iloc[ :, cols_with_float ] # has the regression DataFrame for a given class # if regressable elements - link class with the df of valid floats, # else - None if len(cols_with_float) > 0: self._regr_dfs_per_class_[ self._unique_class_keys_[i] ] = regression_vals_df else: self._regr_dfs_per_class_[self._unique_class_keys_[i]] = np.nan # take Nearest Neighbors differences self._undefined_p_change_val_ = undefined_p_change_val if n_neighbors is not None: info_str_14 = ("\nCalculate Average Distances & " "Average Percent Change") self.__vb_helper(verbose, info_str_14) self._n_neighbors_ = [int(i) for i in n_neighbors] self._avg_dist_dfs_per_class_ = ( OrderedDict() ) # stores the average distances # We need distances in input space, then compare %diff in output # space for key, input_df_per_class in self._regr_inputs_.items(): self._avg_dist_dfs_per_class_[key] = OrderedDict() regr_data = self._regr_dfs_per_class_[ key ] # either a DataFrame or np.nan if isinstance(regr_data, pd.DataFrame): self.__vb_helper(verbose, "class: '{0}'".format(key)) # find nearest neighbors in input space where_nearest_neighbors = OrderedDict() for n_ in self._n_neighbors_: try: avg_dist, indicies = calc_avg_dist( input_df_per_class.values, n_, neighbor=neighbor) except ValueError as err: self.__vb_helper(verbose, "Skipping n = {0}\nError: {1}". format(n_, err)) avg_dist = None continue where_nearest_neighbors[n_] = indicies for _key, _val in regr_data.items(): # regression data data = np.array(_val.values, dtype=float) where_zero = np.where(data == 0)[0] # where_not_zero = np.where(data != 0)[0] if len(where_zero) > 0: info_str_15 = "\t -- {0} zeros in '{1}'".format( len(where_zero), _key ) self.__vb_helper(verbose, info_str_15) if len(where_zero) == len(data): self.__vb_helper( verbose, "Skipping percent change for " "{0}... All data is zero.".format(_key)) continue # Take percent difference avg_p_change = calc_avg_p_change( data, where_nearest_neighbors, undefined_p_change_val=self. _undefined_p_change_val_) if avg_p_change is None: self.__vb_helper(verbose, "None in avg_p_change!? " "This shouldn't happen...") else: # update into regr_dfs_per_class # - all data available for regression my_kwargs = OrderedDict() for i in range(np.shape(avg_p_change)[0]): new_col_str = "APC{0}_{1}".format( self._n_neighbors_[i], _key ) self.__vb_helper(verbose, "\t" + new_col_str) my_kwargs[new_col_str] = avg_p_change[i] self._regr_dfs_per_class_[key] = ( self._regr_dfs_per_class_[key].assign( **my_kwargs)) self._avg_dist_dfs_per_class_[key][_key] = avg_dist else: self.__vb_helper( verbose, "No regression data in '{0}'.".format(key) ) info_str_17 = "::: TableData created in {0:.2f} seconds :::".format( time.time() - start_time ) self.__vb_helper(verbose, info_str_17) def find_n_neighbors(self, input_data, n_neighbors, neighbor=None, return_avg_dists=False, **kwargs): """Find the N nearest neighbors of a given set of arbitrary points. Given a set of arbitrary input points, find the N nearest neighbors to each point, not including themselves. Can also return average distance from a point to its N nearest neighbors. Parameters ---------- input_data : ndarray, pandas DataFrame Data points where their nearest neighbors will be found n_neighbors : list List of integers with number of neighbors to calculate neighbor : instance of NearestNeightbors class For passing your own object. return_avg_dists : bool, optional If True, return the a dictionary with average distances between the N nearest neighbors listed in 'n_neighbors'. **kwargs class_key : str If a DataFrame is given, specifies class column name. Returns ------- where_nearest_neighbors : dict Dictionary containing the n nearest neighbors for every point in the input data. avg_distances : dict Returned if return_avg_dists is True. The average distances between the nearest neighbors. """ class_key = kwargs.pop("class_key", None) if class_key is not None: input_data = self._regr_dfs_per_class_[class_key] if isinstance(input_data, pd.DataFrame): input_data = input_data.values elif isinstance(input_data, list): input_data = np.array(input_data) elif isinstance(input_data, np.ndarray): pass else: raise ValueError( "input_data must be pandas DataFrame or numpy array") where_nearest_neighbors = OrderedDict() avg_distances = OrderedDict() for n_ in n_neighbors: avg_dist, indicies = calc_avg_dist(input_data, n_, neighbor=neighbor) where_nearest_neighbors[n_] = indicies avg_distances[n_] = avg_dist if return_avg_dists: return where_nearest_neighbors, avg_distances else: return where_nearest_neighbors def get_data(self, what_data="full", return_df=False): """Get all data contained in TableData object. The data is returned after omission of columns and rows containing specified values (if given) and taking a subset (if given) of the original data set read in as a csv or given directly as a pandas DataFrame. (Before data processing for classification and regression.) Parameters ---------- what_data: str, list, optional Default is 'full' with other options 'input', or 'output'. 'full' - original data table (after omission and subsets) 'input' - only data identified as inputs from 'full' data set 'output' - only data identified as outputs from 'full' data set return_df: bool, optional If True, return a pandas DataFrame object. If False (default), return a numpy array. Returns ------- data: tuple, ndarray or DataFrame Data before classification and regression data sorting is done. Will return tuple of len(what_data) if a list is passed. """ data_dict = { "input": self._input_, "output": self._output_, "full": self._full_data_, } if isinstance(what_data, str): my_data = data_dict[what_data.lower()] elif isinstance(what_data, list): my_data = tuple([data_dict[i.lower()] for i in what_data]) else: raise ValueError("'{0}' not supported. Try {1}.". format(what_data, data_dict.keys())) if return_df: return my_data else: return my_data.values def get_binary_mapping_per_class(self,): """Get binary mapping (0 or 1) of the class data. Get binary mapping (0 or 1) of the class data for each unique classification. For each classification, a value of 1 is given if the class data matches that classification. If they do not match, then a value of 0 is given. Example: classifications -> A, B, C class data -> [ A, B, B, A, B, C ] binary mapping -> [[1, 0, 0, 1, 0, 0] (for class A) [0, 1, 1, 0, 1, 0] (for class B) [0, 0, 0, 0, 0, 1]] (for class C) Returns ------- binary_class_data: ndarray N by M array where N is the number of classes and M is the number of classifications in the data set. Order is determined by '_unique_class_keys_'. """ cls = self._class_col_.copy() # create a different array for each class - one against all binary_class_data = [] for i in self.class_ids: where_class_is = np.where( cls == self._unique_class_keys_[i], 1, 0 ) # 1 for True, 0 for False binary_class_data.append(np.concatenate(where_class_is, axis=None)) return np.array(binary_class_data) def _return_data_(self, name, verbose=False): """Return a regular or hidden class variable.""" hidden_name = "_" + name + "_" if name in self.__dict__: return self.__dict__[name] elif hidden_name in self.__dict__: return self.__dict__[hidden_name] else: if verbose: print( "{0}, {1} not in class variables: \n{2}".format( name, hidden_name, self.__dict__ ) ) return None def get_class_data(self, what_data="full"): """Get data related to classification. Parameters ---------- what_data, str, list, optional 'class_col' (array) - Original classification data. 'unique_class_keys' (array) - Unique classes found in the classification data. 'class_col_to_ids' (array) - Original classification data replaced with their respective class IDs (integers). 'class_id_mapping' (dict) - Mapping between a classification from the original data set and its class ID. 'binary_data' (ndarray) - Iterating over the unique classes, classification data is turned into 1 or 0 if it matches the given class. See method 'get_binary_mapping_per_class()'. 'full' (tuple) - All options listed above. (Default) Returns ------- class_data: tuple, ndarray, dict An object containing the specified classification data. Will return tuple of len(what_data) if a list is passed. Default: 5 """ binary_class_data = self.get_binary_mapping_per_class() data_dict = { # simply the class column "class_col": self._class_col_, # unique values in class column "unique_class_keys": self._unique_class_keys_, # class column but class strings turned into integers (class IDs) "class_col_to_ids": self._class_col_to_ids_, # maps between a class ID and the original class string "class_id_mapping": self._class_id_mapping_, # for all classes, 1 where that class, 0 else "binary_data": binary_class_data, "full": tuple( [ self._class_col_, self._unique_class_keys_, self._class_col_to_ids_, self._class_id_mapping_, binary_class_data, ] ), } if isinstance(what_data, str): class_data = data_dict[what_data.lower()] elif isinstance(what_data, list): class_data = tuple([data_dict[i.lower()] for i in what_data]) else: raise ValueError("'{0}' not supported. Try {1}.". format(what_data, data_dict.keys())) return class_data def get_regr_data(self, what_data="full"): """Get data related to regression all sorted by class in dictionaries. Parameters ---------- what_data: str, list, optional 'input' - For each class, the input data with no cleaning. 'raw_output' - For each class, the output data with no cleaning. 'output' - For each class, the cleaned output data. 'full' - All options listed above in that respective order. Returns ------- data: tuple, ndarray or DataFrame An object containing the specified regression data. Will return tuple of len(what_data) if a list is passed. Default: 3 """ data_dict = { "input": self._regr_inputs_, "raw_output": self._regr_outputs_, "output": self._regr_dfs_per_class_, "full": tuple([self._regr_inputs_, self._regr_outputs_, self._regr_dfs_per_class_]), } if isinstance(what_data, str): regr_data = data_dict[what_data.lower()] elif isinstance(what_data, list): regr_data = tuple([data_dict[i.lower()] for i in what_data]) else: raise ValueError("'{0}' not supported. Try {1}.". format(what_data, data_dict.keys())) return regr_data def info(self): """Print info for the instance of TableData object. For output descriptions see the method 'get_info()'. """ print("File List: \n{0}".format(np.array(self._files_))) print("df Index Keys: \n{0}\n".format(np.array(self._df_index_keys_))) print("---- VERBOSE OUTPUT START ----") print(*self._for_info_, sep="\n") print("---- VERBOSE OUTPUT END ----") def get_info(self): """Return what info is printed in the 'info()' method. Returns ------- files: list File paths where data was loaded from. df_index_keys: list Index keys added to the DataFrame object once multiple files are joined together such that one can access data by file after they were joined. for_info: list Running list of print statements that include but are not limited to what is shown if 'verbose=True'. """ return tuple([self._files_, self._df_index_keys_, self._for_info_]) def plot_3D_class_data( self, axes=None, fig_size=(4, 5), mark_size=12, which_val=0, save_fig=False, plt_str="0", color_list=None, ): """Plot the 3D classification data in a 2D plot. 3 input axis with classification output. Parameters ---------- axes: list, optional By default it will order the axes as [x,y,z] in the original order the input axis were read in. To change the ordering, pass a list with the column names. Example: The default orderd is col_1, col_2, col_3. To change the horizontal axis from col_1 to col_2 you would use: 'axes = ["col_2", "col_1", "col_3"]' fig_size: tuple, optional, default = (4,5) Size of the figure. (Matplotlib figure kwarg 'fig_size') mark_size: float, optional, default = 12 Size of the scatter plot markers. (Matplotlib scatter kwarg 's') which_val: int, default = 0 Integer choosing what unique value to 'slice' on in the 3D data such that it can be plotted on 2D. (If you had x,y,z data you need to choose a z value) save_fig: bool, default = False Save the figure in the local directory. plt_str: str, default = '0' If you are saving multiple figures you can pass a string which will be added to the end of the default: "data_plot_{plt_str}.pdf" color_list: list, default = None Returns ------- matplotlib figure """ full_data = self._full_data_ input_data = self._input_ if len(input_data) == 2: print("2D input data") if len(input_data) == 3: print("3D input data") if axes is not None: first_axis, second_axis, third_axis = axes else: first_axis, second_axis, third_axis = input_data.keys() print("Axes: {0}, {1}, {2}". format(first_axis, second_axis, third_axis)) if color_list: colors = color_list print( "To set default colors for this object,\ re-istantiate using the option 'my_colors'." ) else: colors = self._class_colors_ color_dict = OrderedDict() for j, color_str in enumerate(colors): color_dict[j] = color_str # MAKE LEGEND legend_elements = [] for i, name in enumerate(self._unique_class_keys_): legend_elements.append( Line2D( [], [], marker="s", color=color_dict[i], label=name, linestyle="None", markersize=8, ) ) # -------------- # Specify value of other '3rd' axis not in 2D plot slice_value = np.unique(full_data[third_axis])[which_val] # boolean data frame where_to_slice = full_data[third_axis] == slice_value # Find all indicies (rows) that have the slice value what_index = np.where(where_to_slice)[0] IDs = np.array(self._class_col_to_ids_) data_to_plot = full_data[where_to_slice] # class IDs (ints 0->n) to color code class_to_colors = [color_dict[val] for val in IDs[what_index]] fig = plt.figure(figsize=fig_size, dpi=120) plt.title(third_axis + "= %f" % (slice_value)) plt.scatter( data_to_plot[first_axis], data_to_plot[second_axis], c=class_to_colors, cmap=None, s=mark_size, marker="s", ) plt.xlabel(first_axis) plt.ylabel(second_axis) plt.legend(handles=legend_elements, bbox_to_anchor=(1.03, 1.02)) if save_fig: plt.savefig("data_plot_{0}.pdf".format(plt_str), bbox_inches="tight") return fig def make_class_data_plot(self, fig, ax, axes_keys, my_slice_vals=None, my_class_colors=None, return_legend_handles=False, verbose=False, **kwargs): """Plot classification data on a given axis and figure. Parameters ---------- fig : Matplotlib Figure object Figure on which the plot will be made. ax : Matplotlib Axis object Axis on which a scatter plot will be drawn. axes_keys : list List containing two names of input data columns to use as horizontal and verital axes. my_slice_vals : optional, list, dict List giving values on which to slice in the axes not being plotted. Default (None) uses the first unique value found in each axis. If instead of individual values, a range is desired (e.g. 10 +/- 1) then a dict can be given with integer keys mapping to a tuple with the lower and upper range. ( e.g. {0:(9,11)} ) my_class_colors : optional, list List of colors used to represent different classes. Default (None) uses the default class colors. return_legend_handles : optional, bool Returns a list of handles that connect classes to colors. verbose : optional, bool Print useful information during runtime. **kwargs : optional Kwargs for matplotlib.pyplot.scatter() . Returns ------- fig : Matplotlib Figure object Figure object. ax : Matplotlib Axis object Updated axis after plotting. handles : optional, list List of legend handles connecting classes and their colors. Returned if 'return_legend_handles' is True. Default is False. """ # Converting class ids to colors for plotting if my_class_colors is None: class_colors = self._class_colors_ else: if not isinstance(my_class_colors, (list, np.ndarray)): raise ValueError("'my_class_colors' takes a list of strings") if verbose: print("Using my_class_colors...") class_colors = my_class_colors color_dict = OrderedDict() for j, color_str in enumerate(class_colors): color_dict[j] = color_str class_to_colors = np.array([color_dict[val] for val in self._class_col_to_ids_]) # Legend Handles (if desired) # For single plot, recomended kwarg: bbox_to_anchor = (1.03, 1.02) legend_elements = [] for i, name in enumerate(self._unique_class_keys_): legend_elements.append( Line2D( [], [], marker="s", color=color_dict[i], label=name, linestyle="None", markersize=8, ) ) # Seperate the plotting and slicing axes all_input_axes = self._input_.keys() num_dim = len(all_input_axes) # plotting_axes = [i for i in all_input_axes if i in axes_keys] slicing_axes = [i for i in all_input_axes if i not in axes_keys] # Check that user provided valid axes for ax_key in axes_keys: if ax_key not in all_input_axes: raise KeyError(ax_key) # Slicing algorithm # By default slice along the first unique element in all non-plotting # axes. We want to plot data in a constant hyperplane. That is all # points with the same values in all extra dimensions. if num_dim >= 3: running_bool_list = [] for j, slice_axis in enumerate(slicing_axes): unique_vals = np.unique(self._input_[slice_axis]) if verbose: print("Slice Axis: '{0}'".format(slice_axis)) print("\tUnique values: {0}".format(len(unique_vals))) if my_slice_vals is None: if verbose: print("\tSlice value: {0}, '{1}'". format(slice_axis, unique_vals[0])) where_this_val = np.array( self._input_[slice_axis] == unique_vals[0] ) else: if len(my_slice_vals) != len(slicing_axes): raise ValueError( "Need {0} slice value(s) and {1} given.".format( len(slicing_axes), len(my_slice_vals) ) ) if verbose: print("\tSlice val: {0}, '{1}'". format(slice_axis, my_slice_vals[j])) if isinstance(my_slice_vals, (list, np.ndarray)): where_this_val = np.array( self._input_[slice_axis] == my_slice_vals[j] ) elif isinstance(my_slice_vals, (dict, OrderedDict)): where_this_val = np.array( (self._input_[slice_axis] >= my_slice_vals[j][0]) & (self._input_[slice_axis] <= my_slice_vals[j][1]) ) else: raise ValueError( "`my_slice_vals` must be list or dict, {0} given.". format(type(my_slice_vals))) running_bool_list.append(where_this_val) # for one axis all_results = np.array( running_bool_list ).T # this is now (N_points x N_slice_axes) # For a point (row), True if all other axes contain the slice # values rows_where_all_true = np.array([i.all() for i in all_results]) x_data = self._input_[axes_keys[0]].loc[rows_where_all_true] y_data = self._input_[axes_keys[1]].loc[rows_where_all_true] class_to_colors = class_to_colors[rows_where_all_true] if verbose: print("\tN total points: {0}". format(len(self._input_[axes_keys[0]]))) print("\tN points in hyperplane: {0}\n". format(np.sum(rows_where_all_true))) else: x_data = self._input_[axes_keys[0]] y_data = self._input_[axes_keys[1]] # The actual plotting ax.scatter(x_data, y_data, c=class_to_colors, **kwargs) ax.set_xlabel(axes_keys[0]) ax.set_ylabel(axes_keys[1]) if return_legend_handles: return fig, ax, legend_elements else: return fig, ax
POSYDON-codeREPO_NAMEPOSYDONPATH_START.@POSYDON_extracted@POSYDON-main@posydon@active_learning@psy_cris@data.py@.PATH_END.py
{ "filename": "_stepdefaults.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py2/plotly/validators/layout/slider/_stepdefaults.py", "type": "Python" }
import _plotly_utils.basevalidators class StepdefaultsValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__( self, plotly_name="stepdefaults", parent_name="layout.slider", **kwargs ): super(StepdefaultsValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Step"), data_docs=kwargs.pop( "data_docs", """ """, ), **kwargs )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py2@plotly@validators@layout@slider@_stepdefaults.py@.PATH_END.py
{ "filename": "ffi.md", "repo_name": "jax-ml/jax", "repo_path": "jax_extracted/jax-main/docs/ffi.md", "type": "Markdown" }
--- jupytext: formats: ipynb,md:myst text_representation: extension: .md format_name: myst format_version: 0.13 jupytext_version: 1.16.4 kernelspec: display_name: Python 3 (ipykernel) language: python name: python3 --- (ffi-tutorial)= # Foreign function interface (FFI) _This tutorial requires JAX v0.4.31 or newer._ While a wide range of numerical operations can be easily and efficiently implemented using JAX's built in `jax.numpy` and `jax.lax` interfaces, it can sometimes be useful to explicitly call out to external compiled libraries via a "foreign function interface" (FFI). This can be particularly useful when particular operations have been previously implemented in an optimized C or CUDA library, and it would be non-trivial to reimplement these computations directly using JAX, but it can also be useful for optimizing runtime or memory performance of JAX programs. That being said, the FFI should typically be considered a last resort option because the XLA compiler that sits in the backend, or the Pallas kernel language, which provides lower level control, typically produce performant code with a lower development and maintenance cost. One point that should be taken into account when considering use of the FFI is that _JAX doesn't automatically know how to differentiate through foreign functions_. This means that if you want to use JAX's autodifferentiation capabilities alongside a foreign function, you'll also need to provide an implementation of the relevant differentiation rules. We will discuss some possible approaches below, but it is important to call this limitation out right from the start! JAX's FFI support is provided in two parts: 1. A header-only C++ library from XLA which is packaged as part of JAX as of v0.4.29 or available from the [openxla/xla](https://github.com/openxla/xla) project, and 2. A Python front end, available in the `jax.extend.ffi` submodule. In this tutorial we demonstrate the use of both of these components using a simple example, and then go on to discuss some lower-level extensions for more complicated use cases. We start by presenting the FFI on CPU, and discuss generalizations to GPU or multi-device environments below. The end-to-end code for this example and some other more advanced use cases can be found in the JAX FFI examples project on GitHub at [`examples/ffi` in the JAX repository](https://github.com/jax-ml/jax/tree/main/examples/ffi). ## A simple example To demonstrate the use of the FFI interface, we will implement a simple "root-mean-square (RMS)" normalization function. RMS normalization takes an array $x$ with shape $(N,)$ and returns $$ y_n = \frac{x_n}{\sqrt{\frac{1}{N}\sum_{n=1}^N {x_n}^2 + \epsilon}} $$ where $\epsilon$ is a tuning parameter used for numerical stability. This is a somewhat silly example, because it can be easily implemented using JAX as follows: ```{code-cell} ipython3 import jax import jax.numpy as jnp def rms_norm_ref(x, eps=1e-5): scale = jnp.sqrt(jnp.mean(jnp.square(x), axis=-1, keepdims=True) + eps) return x / scale ``` But, it's just non-trivial enough to be useful for demonstrating some key details of the FFI, while still being straightforward to understand. We will use this reference implementation to test our FFI version below. ## Backend code To begin with, we need an implementation of RMS normalization in C++ that we will expose using the FFI. This isn't meant to be particularly performant, but you could imagine that if you had some new better implementation of RMS normalization in a C++ library, it might have an interface like the following. So, here's a simple implementation of RMS normalization in C++: ```c++ #include <cmath> #include <cstdint> float ComputeRmsNorm(float eps, int64_t size, const float *x, float *y) { float sm = 0.0f; for (int64_t n = 0; n < size; ++n) { sm += x[n] * x[n]; } float scale = 1.0f / std::sqrt(sm / float(size) + eps); for (int64_t n = 0; n < size; ++n) { y[n] = x[n] * scale; } return scale; } ``` and, for our example, this is the function that we want to expose to JAX via the FFI. +++ ### C++ interface To expose our library function to JAX and XLA, we need to write a thin wrapper using the APIs provided by the header-only library in the [`xla/ffi/api`](https://github.com/openxla/xla/tree/main/xla/ffi/api) directory of the [XLA project](https://github.com/openxla/xla). For more information about this interface, take a look at [the XLA custom call documentation](https://openxla.org/xla/custom_call). The full source listing can be downloaded [here](https://github.com/jax-ml/jax/blob/main/examples/ffi/src/jax_ffi_example/rms_norm.cc), but the key implementation details are reproduced here: ```c++ #include <functional> #include <numeric> #include <utility> #include "xla/ffi/api/c_api.h" #include "xla/ffi/api/ffi.h" namespace ffi = xla::ffi; // A helper function for extracting the relevant dimensions from `ffi::Buffer`s. // In this example, we treat all leading dimensions as batch dimensions, so this // function returns the total number of elements in the buffer, and the size of // the last dimension. template <ffi::DataType T> std::pair<int64_t, int64_t> GetDims(const ffi::Buffer<T> &buffer) { auto dims = buffer.dimensions(); if (dims.size() == 0) { return std::make_pair(0, 0); } return std::make_pair(buffer.element_count(), dims.back()); } // A wrapper function providing the interface between the XLA FFI call and our // library function `ComputeRmsNorm` above. This function handles the batch // dimensions by calling `ComputeRmsNorm` within a loop. ffi::Error RmsNormImpl(float eps, ffi::Buffer<ffi::F32> x, ffi::ResultBuffer<ffi::F32> y) { auto [totalSize, lastDim] = GetDims(x); if (lastDim == 0) { return ffi::Error::InvalidArgument("RmsNorm input must be an array"); } for (int64_t n = 0; n < totalSize; n += lastDim) { ComputeRmsNorm(eps, lastDim, &(x.typed_data()[n]), &(y->typed_data()[n])); } return ffi::Error::Success(); } // Wrap `RmsNormImpl` and specify the interface to XLA. If you need to declare // this handler in a header, you can use the `XLA_FFI_DECLARE_HANDLER_SYMBOL` // macro: `XLA_FFI_DECLARE_HANDLER_SYMBOL(RmsNorm)`. XLA_FFI_DEFINE_HANDLER_SYMBOL( RmsNorm, RmsNormImpl, ffi::Ffi::Bind() .Attr<float>("eps") .Arg<ffi::Buffer<ffi::F32>>() // x .Ret<ffi::Buffer<ffi::F32>>() // y ); ``` Starting at the bottom, we're using the XLA-provided macro `XLA_FFI_DEFINE_HANDLER_SYMBOL` to generate some boilerplate which will expand into a function called `RmsNorm` with the appropriate signature. But, the important stuff here is all in the call to `ffi::Ffi::Bind()`, where we define the input and output types, and the types of any parameters. Then, in `RmsNormImpl`, we accept `ffi::Buffer` arguments which include information about the buffer shape, and pointers to the underlying data. In this implementation, we treat all leading dimensions of the buffer as batch dimensions, and perform RMS normalization over the last axis. `GetDims` is a helper function providing support for this batching behavior. We discuss this batching behavior in more detail [below](ffi-call-vmap), but the general idea is that it can be useful to transparently handle batching in the left-most dimensions of the input arguments. In this case, we treat all but the last axis as batch dimensions, but other foreign functions may require a different number of non-batch dimensions. +++ ### Building and registering an FFI handler Now that we have our minimal FFI wrapper implemented, we need to expose this function (`RmsNorm`) to Python. In this tutorial, we compile `RmsNorm` into a shared library and load it using [ctypes](https://docs.python.org/3/library/ctypes.html), but another common pattern is to use [nanobind](https://nanobind.readthedocs.io/) or [pybind11](https://pybind11.readthedocs.io/) as discussed below. To compile the shared library, we're using CMake here, but you should be able to use your favorite build system without too much trouble. ```{code-cell} ipython3 :tags: [hide-output] !cmake -DCMAKE_BUILD_TYPE=Release -B ffi/_build ffi !cmake --build ffi/_build !cmake --install ffi/_build ``` With this compiled library in hand, we now need to register this handler with XLA via the {func}`~jax.extend.ffi.register_ffi_target` function. This function expects our handler (a function pointer to the C++ function `RmsNorm`) to be wrapped in a [`PyCapsule`](https://docs.python.org/3/c-api/capsule.html). JAX provides a helper function {func}`~jax.extend.ffi.pycapsule` to help with this: ```{code-cell} ipython3 import ctypes from pathlib import Path import jax.extend as jex path = next(Path("ffi").glob("librms_norm*")) rms_norm_lib = ctypes.cdll.LoadLibrary(path) jex.ffi.register_ffi_target( "rms_norm", jex.ffi.pycapsule(rms_norm_lib.RmsNorm), platform="cpu") ``` ```{tip} If you're familiar with the legacy "custom call" API, it's worth noting that you can also use {func}`~jax.extend.ffi.register_ffi_target` to register a custom call target by manually specifying the keyword argument `api_version=0`. The default `api_version` for {func}`~jax.extend.ffi.register_ffi_target` is `1`, the new "typed" FFI API that we're using here. ``` **An alternative approach**: A common alternative pattern for exposing handlers to Python is to use [nanobind](https://nanobind.readthedocs.io/) or [pybind11](https://pybind11.readthedocs.io/) to define a tiny Python extension which can be imported. For our example here, the nanobind code would be: ```c++ #include <type_traits> #include "nanobind/nanobind.h" #include "xla/ffi/api/c_api.h" namespace nb = nanobind; template <typename T> nb::capsule EncapsulateFfiCall(T *fn) { // This check is optional, but it can be helpful for avoiding invalid handlers. static_assert(std::is_invocable_r_v<XLA_FFI_Error *, T, XLA_FFI_CallFrame *>, "Encapsulated function must be and XLA FFI handler"); return nb::capsule(reinterpret_cast<void *>(fn)); } NB_MODULE(rms_norm, m) { m.def("rms_norm", []() { return EncapsulateFfiCall(RmsNorm); }); } ``` Then, in Python we can register this handler using: ```python # Assuming that we compiled a nanobind extension called `rms_norm`: import rms_norm as rms_norm_lib jex.ffi.register_ffi_target("rms_norm", rms_norm_lib.rms_norm(), platform="cpu") ``` +++ ## Frontend code Now that we have registered our FFI handler, it is straightforward to call our C++ library from JAX using the {func}`~jax.extend.ffi.ffi_call` function: ```{code-cell} ipython3 import numpy as np def rms_norm(x, eps=1e-5): # We only implemented the `float32` version of this function, so we start by # checking the dtype. This check isn't strictly necessary because type # checking is also performed by the FFI when decoding input and output # buffers, but it can be useful to check types in Python to raise more # informative errors. if x.dtype != jnp.float32: raise ValueError("Only the float32 dtype is implemented by rms_norm") call = jex.ffi.ffi_call( # The target name must be the same string as we used to register the target # above in `register_custom_call_target` "rms_norm", # In this case, the output of our FFI function is just a single array with # the same shape and dtype as the input. We discuss a case with a more # interesting output type below. jax.ShapeDtypeStruct(x.shape, x.dtype), # The `vmap_method` parameter controls this function's behavior under `vmap` # as discussed below. vmap_method="broadcast_all", ) # Note that here we're use `numpy` (not `jax.numpy`) to specify a dtype for # the attribute `eps`. Our FFI function expects this to have the C++ `float` # type (which corresponds to numpy's `float32` type), and it must be a # static parameter (i.e. not a JAX array). return call(x, eps=np.float32(eps)) # Test that this gives the same result as our reference implementation x = jnp.linspace(-0.5, 0.5, 15).reshape((3, 5)) np.testing.assert_allclose(rms_norm(x), rms_norm_ref(x), rtol=1e-5) ``` This code cell includes a lot of inline comments which should explain most of what is happening here, but there are a few points that are worth explicitly highlighting. Most of the heavy lifting here is done by the {func}`~jax.extend.ffi.ffi_call` function, which tells JAX how to call the foreign function for a particular set of inputs. It's important to note that the first argument to {func}`~jax.extend.ffi.ffi_call` must be a string that matches the target name that we used when calling `register_custom_call_target` above. Any attributes (defined using `Attr` in the C++ wrapper above) should be passed as keyword arguments to {func}`~jax.extend.ffi.ffi_call`. Note that we explicitly cast `eps` to `np.float32` because our FFI library expects a C `float`, and we can't use `jax.numpy` here, because these parameters must be static arguments. The `vmap_method` argument to {func}`~jax.extend.ffi.ffi_call` defines how this FFI call interacts with {func}`~jax.vmap` as described next. ```{tip} If you are familiar with the earlier "custom call" interface, you might be surprised that we're not passing the problem dimensions as parameters (batch size, etc.) to {func}`~jax.extend.ffi.ffi_call`. In this earlier API, the backend had no mechanism for receiving metadata about the input arrays, but since the FFI includes dimension information with the `Buffer` objects, we no longer need to compute this using Python when lowering. One major perk of this change is {func}`~jax.extend.ffi.ffi_call` can support some simple {func}`~jax.vmap` semantics out of the box, as discussed below. ``` (ffi-call-vmap)= ### Batching with `vmap` {func}`~jax.extend.ffi.ffi_call` supports some simple {func}`~jax.vmap` semantics out of the box using the `vmap_method` parameter. The docs for {func}`~jax.pure_callback` provide more details about the `vmap_method` parameter, and the same behavior applies to {func}`~jax.extend.ffi.ffi_call`. The simplest `vmap_method` is `"sequential"`. In this case, when `vmap`ped, an `ffi_call` will be rewritten as a {func}`~jax.lax.scan` with the `ffi_call` in the body. This implementation is general purpose, but it doesn't parallelize very well. Many FFI calls provide more efficient batching behavior and, in some simple cases, the `"expand_dims"` or `"broadcast_all"` methods can be used to expose a better implementation. In this case, since we only have one input argument, `"expand_dims"` and `"broadcast_all"` actually have the same behavior. The specific assumption required to use these methods is that the foreign function knows how to handle batch dimensions. Another way of saying this is that the result of calling `ffi_call` on the batched inputs is assumed to be equal to stacking the repeated application of `ffi_call` to each element in the batched input, roughly: ```python ffi_call(xs) == jnp.stack([ffi_call(x) for x in xs]) ``` ```{tip} Note that things get a bit more complicated when we have multiple input arguments. For simplicity, we will use the `"broadcast_all"` throughout this tutorial, which guarantees that all inputs will be broadcasted to have the same batch dimensions, but it would also be possible to implement a foreign function to handle the `"expand_dims"` method. The documentation for {func}`~jax.pure_callback` includes some examples of this ``` Our implementation of `rms_norm` has the appropriate semantics, and it supports `vmap` with `vmap_method="broadcast_all"` out of the box: ```{code-cell} ipython3 np.testing.assert_allclose(jax.vmap(rms_norm)(x), jax.vmap(rms_norm_ref)(x), rtol=1e-5) ``` We can inspect the [jaxpr](jax-internals-jaxpr) of the {func}`~jax.vmap` of `rms_norm` to confirm that it isn't being rewritten using {func}`~jax.lax.scan`: ```{code-cell} ipython3 jax.make_jaxpr(jax.vmap(rms_norm))(x) ``` Using `vmap_method="sequential"`, `vmap`ping a `ffi_call` will fall back on a {func}`jax.lax.scan` with the `ffi_call` in the body: ```{code-cell} ipython3 def rms_norm_sequential(x, eps=1e-5): return jex.ffi.ffi_call( "rms_norm", jax.ShapeDtypeStruct(x.shape, x.dtype), vmap_method="sequential", )(x, eps=np.float32(eps)) jax.make_jaxpr(jax.vmap(rms_norm_sequential))(x) ``` If your foreign function provides an efficient batching rule that isn't supported by this simple `vmap_method` parameter, it might also be possible to define more flexible custom `vmap` rules using the experimental `custom_vmap` interface, but it's worth also opening an issue describing your use case on [the JAX issue tracker](https://github.com/jax-ml/jax/issues). +++ ### Differentiation Unlike with batching, {func}`~jax.extend.ffi.ffi_call` doesn't provide any default support for automatic differentiation (AD) of foreign functions. As far as JAX is concerned, the foreign function is a black box that can't be inspected to determine the appropriate behavior when differentiated. Therefore, it is the {func}`~jax.extend.ffi.ffi_call` user's responsibility to define a custom derivative rule. More details about custom derivative rules can be found in the [custom derivatives tutorial](https://jax.readthedocs.io/en/latest/notebooks/Custom_derivative_rules_for_Python_code.html), but the most common pattern used for implementing differentiation for foreign functions is to define a {func}`~jax.custom_vjp` which itself calls a foreign function. In this case, we actually define two new FFI calls: 1. `rms_norm_fwd` returns two outputs: (a) the "primal" result, and (b) the "residuals" which are used in the backwards pass. 2. `rms_norm_bwd` takes the residuals and the output co-tangents, and returns the input co-tangents. We won't get into the details of the RMS normalization backwards pass, but take a look at the [C++ source code](https://github.com/jax-ml/jax/blob/main/examples/ffi/src/jax_ffi_example/rms_norm.cc) to see how these functions are implemented on the back end. The main point to emphasize here is that the "residual" computed has a different shape than the primal output, therefore, in the {func}`~jax.extend.ffi.ffi_call` to `res_norm_fwd`, the output type has two elements with different shapes. This custom derivative rule can be wired in as follows: ```{code-cell} ipython3 jex.ffi.register_ffi_target( "rms_norm_fwd", jex.ffi.pycapsule(rms_norm_lib.RmsNormFwd), platform="cpu" ) jex.ffi.register_ffi_target( "rms_norm_bwd", jex.ffi.pycapsule(rms_norm_lib.RmsNormBwd), platform="cpu" ) def rms_norm_fwd(x, eps=1e-5): y, res = jex.ffi.ffi_call( "rms_norm_fwd", ( jax.ShapeDtypeStruct(x.shape, x.dtype), jax.ShapeDtypeStruct(x.shape[:-1], x.dtype), ), vmap_method="broadcast_all", )(x, eps=np.float32(eps)) return y, (res, x) def rms_norm_bwd(eps, res, ct): del eps res, x = res assert res.shape == ct.shape[:-1] assert x.shape == ct.shape return ( jex.ffi.ffi_call( "rms_norm_bwd", jax.ShapeDtypeStruct(ct.shape, ct.dtype), vmap_method="broadcast_all", )(res, x, ct), ) rms_norm = jax.custom_vjp(rms_norm, nondiff_argnums=(1,)) rms_norm.defvjp(rms_norm_fwd, rms_norm_bwd) # Check that this gives the right answer when compared to the reference version ct_y = jnp.ones_like(x) np.testing.assert_allclose( jax.vjp(rms_norm, x)[1](ct_y), jax.vjp(rms_norm_ref, x)[1](ct_y), rtol=1e-5 ) ``` At this point, we can use our new `rms_norm` function transparently for many JAX applications, and it will transform appropriately under the standard JAX function transformations like {func}`~jax.vmap` and {func}`~jax.grad`. One thing that this example doesn't support is forward-mode AD ({func}`jax.jvp`, for example) since {func}`~jax.custom_vjp` is restricted to reverse-mode. JAX doesn't currently expose a public API for simultaneously customizing both forward-mode and reverse-mode AD, but such an API is on the roadmap, so please [open an issue](https://github.com/jax-ml/jax/issues) describing you use case if you hit this limitation in practice. One other JAX feature that this example doesn't support is higher-order AD. It would be possible to work around this by wrapping the `res_norm_bwd` function above in a {func}`jax.custom_jvp` or {func}`jax.custom_vjp` decorator, but we won't go into the details of that advanced use case here. ## FFI calls on a GPU So far, we have been interfacing only with foreign functions running on the CPU, but JAX's FFI also supports calls to GPU code. Since this documentation page is automatically generated on a machine without access to a GPU, we can't execute any GPU-specific examples here, but we will go over the key points. When defining our FFI wrapper for CPU, the function signature that we used was: ```c++ ffi::Error RmsNormImpl(float eps, ffi::Buffer<ffi::F32> x, ffi::ResultBuffer<ffi::F32> y) ``` To update this to interface with a CUDA kernel, this signature becomes: ```c++ ffi::Error RmsNormImpl(cudaStream_t stream, float eps, ffi::Buffer<ffi::F32> x, ffi::ResultBuffer<ffi::F32> y) ``` And the handler definition is updated to include a `Ctx` in its binding: ```c++ XLA_FFI_DEFINE_HANDLER( RmsNorm, RmsNormImpl, ffi::Ffi::Bind() .Ctx<ffi::PlatformStream<cudaStream_t>>() .Attr<float>("eps") .Arg<ffi::Buffer<ffi::F32>>() // x .Ret<ffi::Buffer<ffi::F32>>() // y ); ``` Then, the `RmsNormImpl` can use the CUDA stream to launch CUDA kernels. On the front end, the registration code would be updated to specify the appropriate platform: ```python jex.ffi.register_ffi_target( "rms_norm_cuda", rms_norm_lib_cuda.rms_norm(), platform="CUDA" ) ``` ### Supporting multiple platforms To support running our `rms_norm` function on both GPU and CPU, we can combine our implementation above with the {func}`jax.lax.platform_dependent` function: ```{code-cell} ipython3 def rms_norm_cross_platform(x, eps=1e-5): assert x.dtype == jnp.float32 out_type = jax.ShapeDtypeStruct(x.shape, x.dtype) def impl(target_name): return lambda x: jex.ffi.ffi_call( target_name, out_type, vmap_method="broadcast_all", )(x, eps=np.float32(eps)) return jax.lax.platform_dependent(x, cpu=impl("rms_norm"), cuda=impl("rms_norm_cuda")) np.testing.assert_allclose(rms_norm_cross_platform(x), rms_norm_ref(x), rtol=1e-5) ``` This version of the function will call the appropriate FFI target depending on the runtime platform. As an aside, it may be interesting to note that while the jaxpr and lowered HLO both contain a reference to both FFI targets: ```{code-cell} ipython3 jax.make_jaxpr(rms_norm_cross_platform)(x) ``` ```{code-cell} ipython3 print(jax.jit(rms_norm_cross_platform).lower(x).as_text().strip()) ``` by the time the function is compiled, the appropriate FFI has been selected: ```{code-cell} ipython3 print(jax.jit(rms_norm_cross_platform).lower(x).as_text(dialect="hlo").strip()) ``` and there will be no runtime overhead to using {func}`jax.lax.platform_dependent`, and the compiled program won't include any references to unavailable FFI targets. ## Advanced topics This tutorial covers most of the basic steps that are required to get up and running with JAX's FFI, but advanced use cases may require more features. We will leave these topics to future tutorials, but here are some possibly useful references: * **Supporting multiple dtypes**: In this tutorial's example, we restricted to only support `float32` inputs and outputs, but many use cases require supporting multiple different input types. One option to handle this is to register different FFI targets for all supported input types and then use Python to select the appropriate target for {func}`jax.extend.ffi.ffi_call` depending on the input types. But, this approach could get quickly unwieldy depending on the combinatorics of the supported cases. So it is also possible to define the C++ handler to accept `ffi::AnyBuffer` instead of `ffi::Buffer<Dtype>`. Then, the input buffer will include a `element_type()` method which can be used to define the appropriate dtype dispatching logic in the backend. * **Sharding**: When using JAX's automatic data-dependent parallelism within {func}`~jax.jit`, FFI calls implemented using {func}`~jax.extend.ffi.ffi_call` don't have sufficient information to shard appropriately, so they result in a copy of the inputs to all devices and the FFI call gets executed on the full array on each device. To get around this limitation, you can use {func}`~jax.experimental.shard_map.shard_map` or {func}`~jax.experimental.custom_partitioning.custom_partitioning`. * **Stateful foreign functions**: It is also possible to use the FFI to wrap functions with associated state. There is a [low-level example included in the XLA test suite](https://github.com/openxla/xla/blob/737a7da3c5405583dc95773ac0bb11b1349fc9ea/xla/service/gpu/custom_call_test.cc#L794-L845), and a future tutorial will include more details.
jax-mlREPO_NAMEjaxPATH_START.@jax_extracted@jax-main@docs@ffi.md@.PATH_END.py
{ "filename": "scripting_sculptor_3.ipynb", "repo_name": "jtschindler/sculptor", "repo_path": "sculptor_extracted/sculptor-main/examples/notebooks/scripting_sculptor_3.ipynb", "type": "Jupyter Notebook" }
# Scripting Sculptor 03 - Fitting and Analzying models using MCMC This tutorial notebook focuses on using *Sculptor's* modules to fit and analyze a model using the maxmimum likelihood Markov Chain Monte Carlo method implemented in [LMFIT](https://lmfit.github.io/lmfit-py/index.html) using the [emcee](https://emcee.readthedocs.io/en/stable/#) backend. You can find more information on how LMFIT uses emcee [here](https://lmfit.github.io/lmfit-py/examples/example_emcee_Model_interface.html). ```python %matplotlib inline import corner import matplotlib.pyplot as plt from astropy.cosmology import FlatLambdaCDM from sculptor import specfit as scfit from sculptor import specmodel as scmod ``` [INFO] Import "sculptor_extensions" package: my_extension [INFO] Import "sculptor_extensions" package: qso [INFO] SWIRE library found. [INFO] FeII iron template of Vestergaard & Wilkes 2001 found. If you will be using these templates in your model fit and publication, please add the citation to the original work, ADS bibcode: 2001ApJS..134....1V [INFO] FeII iron template of Tsuzuki et al. 2006 found. If you will be using these templates in your model fit and publication, please add the citation to the original work, ADS bibcode: 2006ApJ...650...57T [INFO] FeII iron template of Boroson & Green 1992 found. If you will be using these templates in your model fit and publication, please add the citation to the original work, ADS bibcode: 1992ApJS...80..109B ## Fitting a model using MCMC We begin by loading the example spectrum fit to an SDSS quasar spectrum we have been using in previous tutorials. ```python # Instantiate an empty SpecFit object fit = scfit.SpecFit() # Load the example spectrum fit fit.load('../example_spectrum_fit') ``` In the next step we need to change the fitting method. Just as a reminder the full list of fitting methods is available as a globa variable in the *SpecModel* module: ```python for key in scmod.fitting_methods: print('Name: {} \n Method {}'.format(key, scmod.fitting_methods[key])) ``` Name: Levenberg-Marquardt Method leastsq Name: Nelder-Mead Method nelder Name: Maximum likelihood via Monte-Carlo Markov Chain Method emcee Name: Least-Squares minimization Method least_squares Name: Differential evolution Method differential_evolution Name: Brute force method Method brute Name: Basinhopping Method basinhopping Name: Adaptive Memory Programming for Global Optimization Method ampgo Name: L-BFGS-B Method lbfgsb Name: Powell Method powell Name: Conjugate-Gradient Method cg Name: Cobyla Method cobyla Name: BFGS Method bfgs Name: Truncated Newton Method tnc Name: Newton GLTR trust-region Method trust-krylov Name: Trust-region for constrained obtimization Method trust-constr Name: Sequential Linear Squares Programming Method slsqp Name: Simplicial Homology Global Optimization Method shgo Name: Dual Annealing Optimization Method dual_annealing Let us now set the fitting method to 'Maximum likelihood via Monte-Carlo Markov Chain'. ```python # Setting the fit method to MCMC via emcee fit.fitting_method = 'Maximum likelihood via Monte-Carlo Markov Chain' ``` This fitting method takes additional keyword arguments that specify * the number of MCMC steps (*steps*), * the number of steps considered to be the burn in phase (*burn*), which will be discarded, * the number of walkers (*nwalkers*), which should be a much larger number than your variables * the number of workers (*workers*) for multiprocessing (*workers=4* will spawn a multiprocessing-based pool with 4 parallel processes), * thin sampling accepting only 1 in every *thin* (int) samples, * whether the objective function has been weightes by measurement uncertainties (*is_weighted*, boolean), * whether a progress bar should be printed (*progress*, boolean), * and the *seed* (default: *seed=1234*). **Note:** The *is_weighted* keyword will be set to *True* by default. For a full documentation of the keyword arguments, please visit the [LMFIT emcee documentation](https://lmfit.github.io/lmfit-py/fitting.html#lmfit.minimizer.Minimizer.emcee). The list of keyword arguments can be accessed via *SpecFit.emcee_kws*. ```python for key in fit.emcee_kws: print(key, fit.emcee_kws[key]) ``` steps 1000 burn 300 thin 20 nwalkers 50 workers 1 is_weighted True progress False seed 1234 Additional keywords can be added to this dictionary, which will be passed to the *SpecModel* fit function, once the *SpecFit* fitting method has been selected to be MCMC (see above). The default values **do not automatically constitute a good default choice**. The choice of those parameters is highly dependent on the model fit (e.g., number of variable parameters). In order to properly fit the CIV emission line we will adjust them: ```python # Set the MCMC keywords fit.emcee_kws['steps'] = 2000 fit.emcee_kws['burn'] = 500 # We are fitting 6 parameters so nwalker=50 is fine fit.emcee_kws['nwalkers'] = 25 # No multiprocessing for now fit.emcee_kws['workers'] = 1 fit.emcee_kws['thin'] = 2 fit.emcee_kws['progress'] = True # Take uncertainties into account fit.emcee_kws['is_weighted'] = True ``` **Before fitting any model using MCMC it is strongly advised to fit the model with a standard algorithm (e.g., 'Levenberg-Marquardt') after setting it up and then start the MCMC fit from the best-fit parameters.** In our case we already fitted all models to the quasar spectrum before saving it. Therefore, we can immediately fit the CIV emission line model. ```python # In case we have forgotten the index of the CIV SpecModel in the fit.specmodels list. for idx, specmodel in enumerate(fit.specmodels): print(idx, specmodel.name) ``` 0 Continuum 1 SiIV_line 2 CIV_line 3 CIII]_complex 4 Abs_lines ```python # Select the CIV emission line SpecModel civ_model = fit.specmodels[2] # Fit the SpecModel using the MCMC method and emcee_kws modified above civ_model.fit() # Print the fit result print(civ_model.fit_result.fit_report()) ``` 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 2000/2000 [00:06<00:00, 288.42it/s] The chain is shorter than 50 times the integrated autocorrelation time for 7 parameter(s). Use this estimate with caution and run a longer chain! N/50 = 40; tau: [60.71255358 65.93961611 64.03676477 66.17055916 63.93059079 73.11907444 61.57293084] [[Model]] (Model(line_model_gaussian, prefix='CIV_B_') + Model(line_model_gaussian, prefix='CIV_A_')) [[Fit Statistics]] # fitting method = emcee # function evals = 50000 # data points = 309 # variables = 7 chi-square = 301.595330 reduced chi-square = 0.99866003 Akaike info crit = 6.50516627 Bayesian info crit = 32.6385552 [[Variables]] CIV_B_z: 3.21141536 +/- 8.0272e-04 (0.02%) (init = 3.209845) CIV_B_flux: 1091.60304 +/- 132.570578 (12.14%) (init = 1151.246) CIV_B_cen: 1549.06 (fixed) CIV_B_fwhm_km_s: 4704.44704 +/- 244.820184 (5.20%) (init = 4790.818) CIV_A_z: 3.20746100 +/- 0.00166939 (0.05%) (init = 3.209726) CIV_A_flux: 1880.60255 +/- 118.497872 (6.30%) (init = 1820.904) CIV_A_cen: 1549.06 (fixed) CIV_A_fwhm_km_s: 11663.2794 +/- 674.461140 (5.78%) (init = 12121.84) __lnsigma: -0.03756195 +/- 0.03824749 (101.83%) (init = 0.01) [[Correlations]] (unreported correlations are < 0.100) C(CIV_B_flux, CIV_A_flux) = -0.963 C(CIV_B_flux, CIV_B_fwhm_km_s) = 0.942 C(CIV_B_fwhm_km_s, CIV_A_flux) = -0.929 C(CIV_B_flux, CIV_A_fwhm_km_s) = 0.912 C(CIV_A_flux, CIV_A_fwhm_km_s) = -0.803 C(CIV_B_fwhm_km_s, CIV_A_fwhm_km_s) = 0.797 C(CIV_B_z, CIV_A_z) = -0.620 C(CIV_B_z, CIV_A_fwhm_km_s) = -0.576 C(CIV_B_z, CIV_B_flux) = -0.550 C(CIV_B_z, CIV_B_fwhm_km_s) = -0.520 C(CIV_B_z, CIV_A_flux) = 0.487 C(CIV_A_z, CIV_A_fwhm_km_s) = 0.374 C(CIV_B_flux, CIV_A_z) = 0.269 C(CIV_B_fwhm_km_s, CIV_A_z) = 0.242 C(CIV_A_z, CIV_A_flux) = -0.186 We visualize the fit result by plotting the CIV model fit. ```python # Plot the fitted model civ_model.plot(xlim=[5500,7500]) ``` ![png](output_16_0.png) However, much more important is that we have a look at the sampled parameter space and the posterior distributions of the fit parameters. To do this we first retrieve the sampled flat chain and the plot it using the [*corner*](https://corner.readthedocs.io/en/latest/) package. ```python # Retrieve the MCMC flat chain of the CIV model fit data = civ_model.fit_result.flatchain.to_numpy() # Visualize the flat chain fit results using the typical corner plot corner_plot = corner.corner(data, labels=civ_model.fit_result.var_names, quantiles=[0.16, 0.5, 0.84], show_titles=True, title_kwargs={"fontsize": 12} ) plt.show() ``` ![png](output_18_0.png) The posterior distributions of the fit parameters look quite well behaved. It seems we have appropriately sampled the parameter space. The plot illustrates strong covariance in some variable parameters pairs (e.g., CIV_A_amp and CIV_A_fwhm_km_s). For further analysis of the MCMC fit, we will now save the flat chain in a file using the *SpecModel.save_mcmc_chain* function, which takes a folder path as an argument. We will save the flat chain in the example fit folders. ```python # Save the MCMC flatchain to a file for analysis civ_model.save_mcmc_chain('../example_spectrum_fit') ! ls ../example_spectrum_fit/*.hdf5 ``` ../example_spectrum_fit/fit.hdf5 ../example_spectrum_fit/specmodel_0_specdata.hdf5 ../example_spectrum_fit/specmodel_1_specdata.hdf5 ../example_spectrum_fit/specmodel_2_specdata.hdf5 ../example_spectrum_fit/specmodel_3_specdata.hdf5 ../example_spectrum_fit/specmodel_4_specdata.hdf5 ../example_spectrum_fit/specmodel_CIV_line_mcmc_chain.hdf5 ../example_spectrum_fit/spectrum.hdf5 ## Analyzing the MCMC fit results It is perfectly fine to work with the parameter fit results from the MCMC fit. However, we do have the full flat chain information and, therefore, it may be better to get posterior distributions for all the properties of the continuum or feature we are interested in. In a previous notebook tutorial we covered how to use *SpecAnalysis* to analyze our model fits. To construct posterior distributions of the CIV emission line properties we will now use the high-level *SpecAnalysis* function *analyze_mcmc_results*, which uses the *SpecAnalysis.analyze_continuum* and *SpecAnalysis.analyze_emission_feature* we have introduced earlier. ```python # Import the SpecAnalysis and Cosmology modules from sculptor import specanalysis as scana from astropy.cosmology import FlatLambdaCDM ``` We begin our analysis by specfiying the Cosmology we will be using and then import the model fit. ```python # Define Cosmology for cosmological conversions cosmo = FlatLambdaCDM(H0=70, Om0=0.3, Tcmb0=2.725) # Instantiate an empty SpecFit object fit = scfit.SpecFit() # Load the example spectrum fit fit.load('../example_spectrum_fit') ``` The *analyze_mcmc_results* function is designed to automatically analyze the output of the MCMC analysis. The user specifies the folder with the MCMC output data and the function will search for any *_mcmc_chain.hdf5* files. As a second argument the function requires the full model fit information (SpecFit object). The third and fourth argument are dictionaries, *continuum_listdict* and *emission_feature_listdict*, which specify which continuum models and features should be analyzed. The *continuum_listdict* and the *emission_feature_listdict* hold the arguments for the *SpecAnalysis.analyze_continuum* and *SpecAnalysis.analyze_emission_feature* functions that will be called by the MCMC analysis procedure. The following parameters should be specified in the *continuum_listdict*: * 'model_names' - list of model function prefixes for the full continuum model * 'rest_frame_wavelengths' - list of rest-frame wavelengths (float) for which fluxes, luminosities and magnitudes should be calculated The other arguments for the *SpecAnalysis.analyze_continuum* are provided to the MCMC analysis function separately. The following parameters should be specified in the *emission_feature_listdict*: * 'feature_name' - name of the emission feature, which will be used to name the resulting measurements in the output file * 'model_names' - list of model names to create the emission feature model flux from * 'rest_frame_wavelength' - rest-frame wavelength of the emission feature Additionally, one can specify: * 'disp_range' - 2 element list holding the lower and upper dispersion boundaries flux density integration For a list of all arguments and keyword arguments, have a look at the function header: :param foldername: Path to the folder with the MCMC flat chain hdf5 files. :type foldername: string :param specfit: Sculptor model fit (SpecFit object) containing the information about the science spectrum, the SpecModels and parameters. :type specfit: sculptor.specfit.SpecFit :param continuum_dict: The *continuum_listdict* holds the arguments for the *SpecAnalysis.analyze_continuum* function that will be called by this procedure. :type continuum_dict: dictionary :param emission_feature_dictlist: The *emission_feature_listdict* hold the arguments for the *SpecAnalysis.analyze_emission_feature* functions that will be called by this procedure. :type emission_feature_dictlist: dictionary :param redshift: Source redshift :type: float :param cosmology: Cosmology for calculation of absolute properties :type cosmology: astropy.cosmology.Cosmology :param emfeat_meas: This keyword argument allows to specify the list of emission feature measurements. Currently possible measurements are ['peak_fluxden', 'peak_redsh', 'EW', 'FWHM', 'flux']. The value defaults to 'None' in which all measurements are calculated :type emfeat_meas: list(string) :param cont_meas: This keyword argument allows to specify the list of emission feature measurements. Currently possible measurements are ['peak_fluxden', 'peak_redsh', 'EW', 'FWHM', 'flux']. The value defaults to 'None' in which all measurements are calculated :type cont_meas: list(string) :param dispersion: This keyword argument allows to input a dispersion axis (e.g., wavelengths) for which the model fluxes are calculated. The value defaults to 'None', in which case the dispersion from the SpecFit spectrum is being used. :type dispersion: np.array :param width: Window width in dispersion units to calculate the average flux density in. :type width: [float, float] :param concatenate: Boolean to indicate whether the MCMC flat chain and the analysis results should be concatenated before written to file. (False = Only writes analysis results to file; True = Writes analysis results and MCMC flat chain parameter values to file) :type concatenate: bool **IMPORTANT: Only model functions that are sampled together can be analyzed together. Therefore, only model functions from ONE SpecModel can be analyzed together.** **THIS MEANS: For example, if you wanted to analyze the continuum model and the CIV emission line together using MCMC, you would have to fit them with ONE SpecModel. In our setup we have separate SpecModels for the continuum and the CIV line. Therefore, we cannot do that. However, to calculate the CIV equivalent width we need the continuum model. In this case we still need to specify the continuum model prefix for the analysis routine. It will build the best-fit continuum model and use it for the CIV analysis. As the best-fit continuum model was subtracted before the CIV line was fit using MCMC, this is the correct way of analzying the results as well.** What does the *analyze_mcmc_results* actually do? It identifies for which of the specified models (continuum/features) it can find the necessary MCMC flat chain information. If multiple continuum or feature models have been specified it will go through them one by one. For each entry in the flat chain file it will read in the model function parameters, build the model fluxes, and then analyze the model using the *SpecAnalysis.analyze_continuum* and *SpecAnalysis.analyze_emission_feature* functions. If you have very long MCMC chains, this process can easily take several minutes. A progress bar will keep you informed. What is the result of the *analyze_mcmc_results* function? The function will write an "Enhanced Character Separated Values" csv file to the same folder with the MCMC flat chain data. The csv file can be read in and then further manipulated with *astropy*. **Unit information on physical quantities is saved along with the values to the csv file.** Let us now set up both dictionaries for our example: ```python continuum_listdict = {'model_names': ['PL_'], 'rest_frame_wavelengths': [1450, 1280]} emission_feature_listdict = [{'feature_name': 'CIV', 'model_names' : ['CIV_A_', 'CIV_B_'], 'rest_frame_wavelength': 1549.06} ] ``` And then run the *analyze_mcmc_results* function: ```python scana.analyze_mcmc_results('../example_spectrum_fit', fit, continuum_listdict, emission_feature_listdict, fit.redshift, cosmo) ``` 0%| | 14/18750 [00:00<02:14, 138.92it/s] [INFO] Starting MCMC analysis [INFO] Working on output file ../example_spectrum_fit/specmodel_CIV_line_mcmc_chain.hdf5 [INFO] Analyzing emission feature CIV 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 18750/18750 [02:09<00:00, 145.09it/s] It can take a while until the MCMC anlysis finishes. The results are written into the same folder with the MCMC flat chain data. In our case we can find the analyzed results (*mcmc_analysis_CIV.csv*) in ```python ! ls ../example_spectrum_fit/ ``` 0_PL__model.json mcmc_analysis_CIV.csv 0_fitresult.json specmodel_0_FitAll_fit_report.txt 1_SiIV_A__model.json specmodel_0_specdata.hdf5 1_SiIV_B__model.json specmodel_1_FitAll_fit_report.txt 1_fitresult.json specmodel_1_specdata.hdf5 2_CIV_A__model.json specmodel_2_FitAll_fit_report.txt 2_CIV_B__model.json specmodel_2_specdata.hdf5 2_fitresult.json specmodel_3_FitAll_fit_report.txt 3_CIII__model.json specmodel_3_specdata.hdf5 3_fitresult.json specmodel_4_FitAll_fit_report.txt 4_Abs_A_model.json specmodel_4_specdata.hdf5 4_Abs_B_model.json specmodel_CIV_line_mcmc_chain.hdf5 4_fitresult.json spectrum.hdf5 fit.hdf5 The analyzed data is saved in the enhanced csv format from astropy. We use *astropy.table.QTable* to read the file in, retaining the unit information on the analyzed properties. ```python from astropy.table import QTable t = QTable.read('../example_spectrum_fit/mcmc_analysis_CIV.csv', format='ascii.ecsv') t ``` <i>QTable length=18750</i> <table id="table6461489888" class="table-striped table-bordered table-condensed"> <thead><tr><th>CIV_peak_fluxden</th><th>CIV_peak_redsh</th><th>CIV_EW</th><th>CIV_FWHM</th><th>CIV_flux</th><th>CIV_lum</th></tr></thead> <thead><tr><th>erg / (Angstrom cm2 s)</th><th></th><th>Angstrom</th><th>km / s</th><th>erg / (cm2 s)</th><th>erg / s</th></tr></thead> <thead><tr><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th><th>float64</th></tr></thead> <tr><td>1.7025458953823565e-16</td><td>3.2114519863017534</td><td>33.11496431713009</td><td>6266.596338612362</td><td>2.961265327675218e-14</td><td>2.7272731887439896e+45</td></tr> <tr><td>1.6721664115085754e-16</td><td>3.210481058669064</td><td>32.99822135043035</td><td>6460.856063522636</td><td>2.9499538664435997e-14</td><td>2.716855532259717e+45</td></tr> <tr><td>1.723933433168788e-16</td><td>3.2114519863017534</td><td>33.469930987621815</td><td>6088.369860660105</td><td>2.9935535993120595e-14</td><td>2.757010117996179e+45</td></tr> <tr><td>1.7182794771269916e-16</td><td>3.210481058669064</td><td>33.31534363653506</td><td>6173.896793403524</td><td>2.979287938638493e-14</td><td>2.743871695879414e+45</td></tr> <tr><td>1.6878815917188721e-16</td><td>3.210481058669064</td><td>33.161937379596345</td><td>6455.038209974451</td><td>2.966046822693796e-14</td><td>2.7316768614052704e+45</td></tr> <tr><td>1.7320789412335437e-16</td><td>3.2114519863017534</td><td>33.78160061683048</td><td>6330.212961485504</td><td>3.0213830308964116e-14</td><td>2.7826405341256157e+45</td></tr> <tr><td>1.6987702663876353e-16</td><td>3.2114519863017534</td><td>33.42811472924633</td><td>6367.250543886042</td><td>2.9898229578526494e-14</td><td>2.753574262946658e+45</td></tr> <tr><td>1.7002049199831065e-16</td><td>3.2114519863017534</td><td>33.37302405915962</td><td>6409.616175461986</td><td>2.9844375270940024e-14</td><td>2.7486143761102343e+45</td></tr> <tr><td>1.6755933939029979e-16</td><td>3.210481058669064</td><td>33.34759616649851</td><td>6497.096461492717</td><td>2.982464934483506e-14</td><td>2.7467976530734148e+45</td></tr> <tr><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td></tr> <tr><td>1.7230147389554056e-16</td><td>3.2114519863017534</td><td>33.37479397925696</td><td>6147.307197386451</td><td>2.9851667159581736e-14</td><td>2.749285946205694e+45</td></tr> <tr><td>1.713119163521492e-16</td><td>3.2114519863017534</td><td>33.60186777044355</td><td>6391.03239870545</td><td>3.0058406077155686e-14</td><td>2.768326236236442e+45</td></tr> <tr><td>1.699526629230714e-16</td><td>3.210481058669064</td><td>33.525326140779796</td><td>6440.871721101392</td><td>2.9989658270368215e-14</td><td>2.761994684366228e+45</td></tr> <tr><td>1.6981870118562772e-16</td><td>3.2114519863017534</td><td>33.24090141975268</td><td>6339.25589718063</td><td>2.972627229916071e-14</td><td>2.7377373005089886e+45</td></tr> <tr><td>1.7190133988262977e-16</td><td>3.210481058669064</td><td>33.99497119170071</td><td>6413.170514132771</td><td>3.039412004497653e-14</td><td>2.7992449011384977e+45</td></tr> <tr><td>1.7353516300351097e-16</td><td>3.210481058669064</td><td>33.62373692126313</td><td>6255.61972575812</td><td>3.0067364499910786e-14</td><td>2.7691512911872792e+45</td></tr> <tr><td>1.7204870649017424e-16</td><td>3.2114519863017534</td><td>33.10115578309755</td><td>6194.743638300733</td><td>2.9599731342699945e-14</td><td>2.7260831013864665e+45</td></tr> <tr><td>1.7059536939278595e-16</td><td>3.2114519863017534</td><td>33.039315764377186</td><td>6271.252179226404</td><td>2.9565184692661265e-14</td><td>2.7229014157897432e+45</td></tr> <tr><td>1.699557133889922e-16</td><td>3.210481058669064</td><td>33.63234776488099</td><td>6388.014093185133</td><td>3.0056768200666273e-14</td><td>2.7681753906977356e+45</td></tr> <tr><td>1.6877095368987712e-16</td><td>3.2114519863017534</td><td>33.377005078544634</td><td>6350.536884815106</td><td>2.984901209178342e-14</td><td>2.749041419139746e+45</td></tr> </table> With the table data we can visualize the posterior distributions for all measurements and further analyze them. ```python import numpy as np import matplotlib.pyplot as plt prop = 'CIV_EW' # Calculate median, lower and upper 1-sigma range med = np.median(t[prop]) low = np.percentile(t[prop],16) upp = np.percentile(t[prop],84) print('Property: {}'.format(prop)) print('Median: {:.2e}'.format(med)) print('Lower 1-sigma: {:.2e}'.format(low)) print('Upper 1-sigma: {:.2e}'.format(upp)) fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.hist(t[prop].value, bins=40) ax.axvline([med.value], ymin=0, ymax=1, color='#ff7f0e', lw=4, label='Median') ax.axvline(low.value, ymin=0, ymax=1, color='#ff7f0e', lw=2, ls='--', label=r'$1\sigma$ uncertainties') ax.axvline(upp.value, ymin=0, ymax=1, color='#ff7f0e', lw=2, ls='--') plt.xlabel('{} ({})'.format(prop, med.unit)) plt.ylabel('N') plt.legend() plt.show() ``` Property: CIV_EW Median: 3.33e+01 Angstrom Lower 1-sigma: 3.29e+01 Angstrom Upper 1-sigma: 3.37e+01 Angstrom ![png](output_34_1.png)
jtschindlerREPO_NAMEsculptorPATH_START.@sculptor_extracted@sculptor-main@examples@notebooks@scripting_sculptor_3.ipynb@.PATH_END.py
{ "filename": "README.md", "repo_name": "dmlc/xgboost", "repo_path": "xgboost_extracted/xgboost-master/demo/CLI/binary_classification/README.md", "type": "Markdown" }
Binary Classification ===================== This is the quick start tutorial for xgboost CLI version. Here we demonstrate how to use XGBoost for a binary classification task. Before getting started, make sure you compile xgboost in the root directory of the project by typing ```make```. The script 'runexp.sh' can be used to run the demo. Here we use [mushroom dataset](https://archive.ics.uci.edu/ml/datasets/Mushroom) from UCI machine learning repository. ### Tutorial #### Generate Input Data XGBoost takes LIBSVM format. An example of faked input data is below: ``` 1 101:1.2 102:0.03 0 1:2.1 10001:300 10002:400 ... ``` Each line represent a single instance, and in the first line '1' is the instance label,'101' and '102' are feature indices, '1.2' and '0.03' are feature values. In the binary classification case, '1' is used to indicate positive samples, and '0' is used to indicate negative samples. We also support probability values in [0,1] as label, to indicate the probability of the instance being positive. First we will transform the dataset into classic LIBSVM format and split the data into training set and test set by running: ``` python mapfeat.py python mknfold.py agaricus.txt 1 ``` The two files, 'agaricus.txt.train' and 'agaricus.txt.test' will be used as training set and test set. #### Training Then we can run the training process: ``` ../../xgboost mushroom.conf ``` mushroom.conf is the configuration for both training and testing. Each line containing the [attribute]=[value] configuration: ```conf # General Parameters, see comment for each definition # can be gbtree or gblinear booster = gbtree # choose logistic regression loss function for binary classification objective = binary:logistic # Tree Booster Parameters # step size shrinkage eta = 1.0 # minimum loss reduction required to make a further partition gamma = 1.0 # minimum sum of instance weight(hessian) needed in a child min_child_weight = 1 # maximum depth of a tree max_depth = 3 # Task Parameters # the number of round to do boosting num_round = 2 # 0 means do not save any model except the final round model save_period = 0 # The path of training data data = "agaricus.txt.train" # The path of validation data, used to monitor training process, here [test] sets name of the validation set eval[test] = "agaricus.txt.test" # The path of test data test:data = "agaricus.txt.test" ``` We use the tree booster and logistic regression objective in our setting. This indicates that we accomplish our task using classic gradient boosting regression tree(GBRT), which is a promising method for binary classification. The parameters shown in the example gives the most common ones that are needed to use xgboost. If you are interested in more parameter settings, the complete parameter settings and detailed descriptions are [here](https://xgboost.readthedocs.io/en/stable/parameter.html). Besides putting the parameters in the configuration file, we can set them by passing them as arguments as below: ``` ../../xgboost mushroom.conf max_depth=6 ``` This means that the parameter max_depth will be set as 6 rather than 3 in the conf file. When you use command line, make sure max_depth=6 is passed in as single argument, i.e. do not contain space in the argument. When a parameter setting is provided in both command line input and the config file, the command line setting will override the setting in config file. In this example, we use tree booster for gradient boosting. If you would like to use linear booster for regression, you can keep all the parameters except booster and the tree booster parameters as below: ```conf # General Parameters # choose the linear booster booster = gblinear ... # Change Tree Booster Parameters into Linear Booster Parameters # L2 regularization term on weights, default 0 lambda = 0.01 # L1 regularization term on weights, default 0 alpha = 0.01 # L2 regularization term on bias, default 0 lambda_bias = 0.01 # Regression Parameters ... ``` #### Get Predictions After training, we can use the output model to get the prediction of the test data: ``` ../../xgboost mushroom.conf task=pred model_in=0002.model ``` For binary classification, the output predictions are probability confidence scores in [0,1], corresponds to the probability of the label to be positive. #### Dump Model This is a preliminary feature, so only tree models support text dump. XGBoost can display the tree models in text or JSON files, and we can scan the model in an easy way: ``` ../../xgboost mushroom.conf task=dump model_in=0002.model name_dump=dump.raw.txt ../../xgboost mushroom.conf task=dump model_in=0002.model fmap=featmap.txt name_dump=dump.nice.txt ``` In this demo, the tree boosters obtained will be printed in dump.raw.txt and dump.nice.txt, and the latter one is easier to understand because of usage of feature mapping featmap.txt Format of ```featmap.txt: <featureid> <featurename> <q or i or int>\n ```: - Feature id must be from 0 to number of features, in sorted order. - i means this feature is binary indicator feature - q means this feature is a quantitative value, such as age, time, can be missing - int means this feature is integer value (when int is hinted, the decision boundary will be integer) #### Monitoring Progress When you run training we can find there are messages displayed on screen ``` tree train end, 1 roots, 12 extra nodes, 0 pruned nodes ,max_depth=3 [0] test-error:0.016139 boosting round 1, 0 sec elapsed tree train end, 1 roots, 10 extra nodes, 0 pruned nodes ,max_depth=3 [1] test-error:0.000000 ``` The messages for evaluation are printed into stderr, so if you want only to log the evaluation progress, simply type ``` ../../xgboost mushroom.conf 2>log.txt ``` Then you can find the following content in log.txt ``` [0] test-error:0.016139 [1] test-error:0.000000 ``` We can also monitor both training and test statistics, by adding following lines to configure ```conf eval[test] = "agaricus.txt.test" eval[trainname] = "agaricus.txt.train" ``` Run the command again, we can find the log file becomes ``` [0] test-error:0.016139 trainname-error:0.014433 [1] test-error:0.000000 trainname-error:0.001228 ``` The rule is eval[name-printed-in-log] = filename, then the file will be added to monitoring process, and evaluated each round. xgboost also supports monitoring multiple metrics, suppose we also want to monitor average log-likelihood of each prediction during training, simply add ```eval_metric=logloss``` to configure. Run again, we can find the log file becomes ``` [0] test-error:0.016139 test-negllik:0.029795 trainname-error:0.014433 trainname-negllik:0.027023 [1] test-error:0.000000 test-negllik:0.000000 trainname-error:0.001228 trainname-negllik:0.002457 ``` ### Saving Progress Models If you want to save model every two round, simply set save_period=2. You will find 0002.model in the current folder. If you want to change the output folder of models, add model_dir=foldername. By default xgboost saves the model of last round. #### Continue from Existing Model If you want to continue boosting from existing model, say 0002.model, use ``` ../../xgboost mushroom.conf model_in=0002.model num_round=2 model_out=continue.model ``` xgboost will load from 0002.model continue boosting for 2 rounds, and save output to continue.model. However, beware that the training and evaluation data specified in mushroom.conf should not change when you use this function. #### Use Multi-Threading When you are working with a large dataset, you may want to take advantage of parallelism. If your compiler supports OpenMP, xgboost is naturally multi-threaded, to set number of parallel running add ```nthread``` parameter to your configuration. Eg. ```nthread=10``` Set nthread to be the number of your real cpu (On Unix, this can be found using ```lscpu```) Some systems will have ```Thread(s) per core = 2```, for example, a 4 core cpu with 8 threads, in such case set ```nthread=4``` and not 8.
dmlcREPO_NAMExgboostPATH_START.@xgboost_extracted@xgboost-master@demo@CLI@binary_classification@README.md@.PATH_END.py
{ "filename": "_customdatasrc.py", "repo_name": "plotly/plotly.py", "repo_path": "plotly.py_extracted/plotly.py-master/packages/python/plotly/plotly/validators/treemap/_customdatasrc.py", "type": "Python" }
import _plotly_utils.basevalidators class CustomdatasrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__(self, plotly_name="customdatasrc", parent_name="treemap", **kwargs): super(CustomdatasrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "none"), **kwargs, )
plotlyREPO_NAMEplotly.pyPATH_START.@plotly.py_extracted@plotly.py-master@packages@python@plotly@plotly@validators@treemap@_customdatasrc.py@.PATH_END.py
{ "filename": "_values.py", "repo_name": "catboost/catboost", "repo_path": "catboost_extracted/catboost-master/contrib/python/plotly/py3/plotly/validators/funnelarea/_values.py", "type": "Python" }
import _plotly_utils.basevalidators class ValuesValidator(_plotly_utils.basevalidators.DataArrayValidator): def __init__(self, plotly_name="values", parent_name="funnelarea", **kwargs): super(ValuesValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), **kwargs, )
catboostREPO_NAMEcatboostPATH_START.@catboost_extracted@catboost-master@contrib@python@plotly@py3@plotly@validators@funnelarea@_values.py@.PATH_END.py
{ "filename": "extract_object_files.py", "repo_name": "tensorflow/tensorflow", "repo_path": "tensorflow_extracted/tensorflow-master/tensorflow/lite/ios/extract_object_files.py", "type": "Python" }
# Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Module for extracting object files from a compiled archive (.a) file. This module provides functionality almost identical to the 'ar -x' command, which extracts out all object files from a given archive file. This module assumes the archive is in the BSD variant format used in Apple platforms. See: https://en.wikipedia.org/wiki/Ar_(Unix)#BSD_variant This extractor has two important differences compared to the 'ar -x' command shipped with Xcode. 1. When there are multiple object files with the same name in a given archive, each file is renamed so that they are all correctly extracted without overwriting each other. 2. This module takes the destination directory as an additional parameter. Example Usage: archive_path = ... dest_dir = ... extract_object_files(archive_path, dest_dir) """ import hashlib import io import itertools import os import struct from typing import Iterator, Tuple def extract_object_files(archive_file: io.BufferedIOBase, dest_dir: str) -> None: """Extracts object files from the archive path to the destination directory. Extracts object files from the given BSD variant archive file. The extracted files are written to the destination directory, which will be created if the directory does not exist. Colliding object file names are automatically renamed upon extraction in order to avoid unintended overwriting. Args: archive_file: The archive file object pointing at its beginning. dest_dir: The destination directory path in which the extracted object files will be written. The directory will be created if it does not exist. """ if not os.path.exists(dest_dir): os.makedirs(dest_dir) _check_archive_signature(archive_file) # Keep the extracted file names and their content hash values, in order to # handle duplicate names correctly. extracted_files = dict() for name, file_content in _extract_next_file(archive_file): digest = hashlib.md5(file_content).digest() # Check if the name is already used. If so, come up with a different name by # incrementing the number suffix until it finds an unused one. # For example, if 'foo.o' is used, try 'foo_1.o', 'foo_2.o', and so on. for final_name in _generate_modified_filenames(name): if final_name not in extracted_files: extracted_files[final_name] = digest # Write the file content to the desired final path. with open(os.path.join(dest_dir, final_name), 'wb') as object_file: object_file.write(file_content) break # Skip writing this file if the same file was already extracted. elif extracted_files[final_name] == digest: break def _generate_modified_filenames(filename: str) -> Iterator[str]: """Generates the modified filenames with incremental name suffix added. This helper function first yields the given filename itself, and subsequently yields modified filenames by incrementing number suffix to the basename. Args: filename: The original filename to be modified. Yields: The original filename and then modified filenames with incremental suffix. """ yield filename base, ext = os.path.splitext(filename) for name_suffix in itertools.count(1, 1): yield '{}_{}{}'.format(base, name_suffix, ext) def _check_archive_signature(archive_file: io.BufferedIOBase) -> None: """Checks if the file has the correct archive header signature. The cursor is moved to the first available file header section after successfully checking the signature. Args: archive_file: The archive file object pointing at its beginning. Raises: RuntimeError: The archive signature is invalid. """ signature = archive_file.read(8) if signature != b'!<arch>\n': raise RuntimeError('Invalid archive file format.') def _extract_next_file( archive_file: io.BufferedIOBase) -> Iterator[Tuple[str, bytes]]: """Extracts the next available file from the archive. Reads the next available file header section and yields its filename and content in bytes as a tuple. Stops when there are no more available files in the provided archive_file. Args: archive_file: The archive file object, of which cursor is pointing to the next available file header section. Yields: The name and content of the next available file in the given archive file. Raises: RuntimeError: The archive_file is in an unknown format. """ while True: header = archive_file.read(60) if not header: return elif len(header) < 60: raise RuntimeError('Invalid file header format.') # For the details of the file header format, see: # https://en.wikipedia.org/wiki/Ar_(Unix)#File_header # We only need the file name and the size values. name, _, _, _, _, size, end = struct.unpack('=16s12s6s6s8s10s2s', header) if end != b'`\n': raise RuntimeError('Invalid file header format.') # Convert the bytes into more natural types. name = name.decode('ascii').strip() size = int(size, base=10) odd_size = size % 2 == 1 # Handle the extended filename scheme. if name.startswith('#1/'): filename_size = int(name[3:]) name = archive_file.read(filename_size).decode('utf-8').strip(' \x00') size -= filename_size file_content = archive_file.read(size) # The file contents are always 2 byte aligned, and 1 byte is padded at the # end in case the size is odd. if odd_size: archive_file.read(1) yield (name, file_content)
tensorflowREPO_NAMEtensorflowPATH_START.@tensorflow_extracted@tensorflow-master@tensorflow@lite@ios@extract_object_files.py@.PATH_END.py