diff --git a/.gitignore b/.gitignore index 3cd9498..a99d971 100644 --- a/.gitignore +++ b/.gitignore @@ -135,3 +135,9 @@ Thumbs.db *.swp *.swo *~ + +# Application outputs +applications/ + +# History files +.history/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 35bf31e..edf3210 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] ### Added +- `pybmc.rng` module: a single seeded package-wide random generator + (`DEFAULT_SEED`, `get_rng`, `set_seed`). All MCMC samplers now draw + from it by default (previously training used the unseeded legacy + global RNG while only predictions were seeded), and every sampler + accepts an explicit `seed` argument (also available as the `'seed'` + training option of `BayesianModelCombination.train()`) +- Heteroscedastic error models: the noise variance can now depend on the + distance from the training data in principal-component space + (`pc_dist`) and/or on the disagreement among model predictions + (`model_var`), linearly or quadratically (new `error_model` parameter + of `BayesianModelCombination`, new `pybmc.error_models` module and + `gibbs_sampler_heteroscedastic` Gibbs-within-Metropolis sampler with + burn-in proposal adaptation toward a target acceptance rate) +- Posterior predictive sampling with per-point variances + (`rndm_m_heteroscedastic_calculator`) +- Calibration diagnostics: `coverage_quality` (mean |empirical - nominal| + coverage) and `diagnose_coverage_shape` (under-/over-dispersion + classification) +- `mh_acceptance_rate_` attribute on `BayesianModelCombination` after + heteroscedastic training + +### Fixed +- `get_weights()` now slices the coefficient columns by the number of + kept components instead of assuming a single trailing noise parameter +- `evaluate()` now excludes points without truth values, as documented - Comprehensive docstrings for all public classes and functions - CONTRIBUTING.md with contribution guidelines - CHANGELOG.md to track project changes @@ -15,6 +40,35 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Improved README with better documentation and examples ### Changed +- Unified the error-model likelihoods: the homoscedastic model is now + trained and predicted as the constant-only special case of the + heteroscedastic machinery (`gibbs_sampler_heteroscedastic` with a + constant variance basis) instead of a separate implementation; + `gibbs_sampler` and `rndm_m_random_calculator` remain as thin + wrappers around the unified code paths +- All samplers now parametrize the noise on the variance (sigma^2) + scale: posterior samples store `sigma^2` in the trailing column(s) + for every error model, including the simplex sampler (previously the + homoscedastic and simplex samplers stored `sigma`) +- Homoscedastic training now uses a Gamma prior on `sigma^2` + (`prior_spec`) like the other error models; `nu0_chosen` and + `sigma20_chosen` now apply to the simplex sampler only +- Variance floors are applied only where positivity is not guaranteed + by construction (the sampler's data-derived initial value and + prediction-time variances of extrapolated points, both using the + single `VARIANCE_FLOOR` constant); the redundant hardcoded floors + inside the sampling loops (1e-6 homoscedastic / 1e-9 heteroscedastic) + were removed and the sampler now validates that the variance basis is + non-negative +- License changed from GPL-3.0 to MIT + +### Fixed +- The simplex sampler's Metropolis acceptance ratio was missing the + factor 1/2 of the Gaussian log-likelihood (it used + `exp(-dSSR/sigma^2)` instead of `exp(-dSSR/(2 sigma^2))`), slightly + over-concentrating the constrained posterior + +### Changed (docs) - Updated API documentation in docs/api_reference.md - Improved usage examples in docs/usage.md - Standardized docstrings to Google style throughout the codebase diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 77acac3..c8f0d43 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -78,4 +78,4 @@ When reporting issues, please include: ## License -By contributing to pybmc, you agree that your contributions will be licensed under the GPL V3 License. +By contributing to pybmc, you agree that your contributions will be licensed under the MIT License. diff --git a/LICENSE b/LICENSE index f288702..f7fbfaf 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,21 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - 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 . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. +MIT License + +Copyright (c) 2025 The pybmc developers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 8022eb5..4af701e 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,10 @@ pybmc is a Python package for performing Bayesian Model Combination (BMC) on var - **Orthogonalization**: Transform model predictions using Singular Value Decomposition (SVD) - **Bayesian Inference**: Perform Gibbs sampling for model combination - **Uncertainty Quantification**: Generate predictions with credible intervals -- **Model Evaluation**: Calculate coverage statistics for model validation +- **Heteroscedastic Error Models**: Let the predictive variance grow with the + distance from the training region and/or the disagreement among models +- **Model Evaluation**: Calculate coverage statistics and calibration + diagnostics for model validation ## Installation @@ -76,7 +79,7 @@ We welcome contributions! Please see our [Contribution Guidelines](docs/CONTRIBU ## License -This project is licensed under the GPL-3.0 License - see the [LICENSE](LICENSE) file for details. +This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. ## Citation diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index b1e2ba8..c8f0d43 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -78,4 +78,4 @@ When reporting issues, please include: ## License -By contributing to pybmc, you agree that your contributions will be licensed under the GPL-3.0 License. +By contributing to pybmc, you agree that your contributions will be licensed under the MIT License. diff --git a/docs/api_reference.md b/docs/api_reference.md index 1e7ca2c..f318045 100644 --- a/docs/api_reference.md +++ b/docs/api_reference.md @@ -8,4 +8,8 @@ This API reference provides detailed documentation for the classes and functions ::: pybmc.inference_utils -::: pybmc.sampling_utils \ No newline at end of file +::: pybmc.sampling_utils + +::: pybmc.error_models + +::: pybmc.rng diff --git a/docs/index.md b/docs/index.md index 777ebf1..4f26fd2 100644 --- a/docs/index.md +++ b/docs/index.md @@ -37,4 +37,4 @@ For questions or support, please open an issue on our [GitHub repository](https: ## License -This project is licensed under the GPL-3.0 License - see the [License](license.md) file for details. +This project is licensed under the MIT License - see the [License](license.md) file for details. diff --git a/docs/license.md b/docs/license.md index afd1adf..47386e1 100644 --- a/docs/license.md +++ b/docs/license.md @@ -1,674 +1,23 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 +# License - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. +MIT License - Preamble +Copyright (c) 2025 The pybmc developers - The GNU General Public License is a free, copyleft license for -software and other kinds of works. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS to THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - 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 . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/docs/theory.md b/docs/theory.md index c6439af..df4714e 100644 --- a/docs/theory.md +++ b/docs/theory.md @@ -47,9 +47,11 @@ By keeping only the first \(m \ll K\) singular values and vectors, we can create `pybmc` uses Gibbs sampling to draw samples from the posterior distribution of the model weights and other parameters. Gibbs sampling is a Markov Chain Monte Carlo (MCMC) algorithm that iteratively samples from the conditional distribution of each parameter given the current values of all other parameters. -### Standard Gibbs Sampler +### Standard (Unconstrained) Sampler -The standard Gibbs sampler in `pybmc` assumes a Gaussian likelihood and conjugate priors for the model parameters. The algorithm iteratively samples from the full conditional distributions of the regression coefficients (related to the model weights) and the error variance. +The unconstrained sampler in `pybmc` assumes the Gaussian likelihood \(y_i \sim \mathcal{N}(X_i \cdot b,\, \sigma_i^2)\) where the per-point variance is linear in a basis of heteroscedasticity metrics, \(\sigma_i^2 = \phi_i \cdot \theta\). Every error model shares this one likelihood: the homoscedastic model is simply the case where the basis \(\phi\) is the constant term alone, so \(\theta = [\sigma^2]\) is a single constant variance. All variance parameters are sampled on the \(\sigma^2\) scale. + +The regression coefficients \(b\) are updated with a conjugate (weighted least-squares) Gibbs step; the variance parameters \(\theta\) are updated with a positivity-constrained random-walk Metropolis-Hastings step under Gamma priors. Because \(\theta\) stays strictly positive and the training-time basis is non-negative with a leading constant term, every \(\sigma_i^2\) is positive by construction and no variance flooring is applied during sampling. ### Gibbs Sampler with Simplex Constraints @@ -77,7 +79,7 @@ At each iteration, the algorithm: 1. **Proposes** a new coefficient vector \(\boldsymbol{\beta}^*\) from a multivariate normal centered on the current value. 2. **Projects** the proposal to weight space via \(\boldsymbol{\omega}^* = \boldsymbol{\beta}^* \hat{V} + \frac{1}{K}\). 3. **Rejects** the proposal if any \(\omega_k^* < 0\) (the sum-to-one constraint is automatically satisfied by the SVD structure and the \(\frac{1}{K}\) offset). -4. **Accepts** valid proposals with probability \(\min\!\bigl(1,\; \exp\!\bigl[\bigl(\ell(\boldsymbol{\beta}^*) - \ell(\boldsymbol{\beta})\bigr) / \sigma^2\bigr]\bigr)\), where \(\ell\) is the log-likelihood. -5. **Samples** the error variance \(\sigma^2\) from its inverse-gamma full conditional. +4. **Accepts** valid proposals with the Gaussian likelihood ratio \(\min\!\bigl(1,\; \exp\!\bigl[-\bigl(\mathrm{SSR}(\boldsymbol{\beta}^*) - \mathrm{SSR}(\boldsymbol{\beta})\bigr) / (2\sigma^2)\bigr]\bigr)\), where \(\mathrm{SSR}\) is the residual sum of squares — the same homoscedastic Gaussian likelihood used by the unconstrained sampler. +5. **Samples** the error variance \(\sigma^2\) from its inverse-gamma full conditional (retained samples store \(\sigma^2\), matching the variance-scale parametrization of all other samplers). The `burn` parameter controls the number of burn-in iterations discarded before collecting samples, and the `stepsize` parameter scales the proposal covariance matrix to tune the acceptance rate. \ No newline at end of file diff --git a/docs/usage.md b/docs/usage.md index d64655f..45eb416 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -172,6 +172,109 @@ bmc.train(training_options={ }) ``` +### Heteroscedastic Error Models + +By default, `pybmc` assumes **homoscedastic** noise: a single constant variance +for every data point. In practice the combined model is often much more +uncertain far from the training data (extrapolation) or where the constituent +models disagree. Heteroscedastic error models let the noise variance depend on +two per-point metrics: + +- `pc_dist` (\(d_i\)): distance of point \(i\) from the training-data centroid in + principal-component space — grows away from the fitted region. +- `model_var` (\(v_i\)): variance among the individual model predictions at + point \(i\) — grows where the models disagree. + +Both metrics are min-max normalized with the *training* values, so +extrapolated points can exceed 1. Every error model is parametrized on the +variance (\(\sigma^2\)) scale and shares the single likelihood +\(y_i \sim \mathcal{N}(X_i \cdot b,\, \sigma_i^2)\); the homoscedastic model is +simply the special case whose variance basis is the constant term alone, so +it is trained with the same sampler rather than a separate one. The +available error models are: + +| `error_model` | Variance \(\sigma_i^2\) | +| --- | --- | +| `homoscedastic` (default) | \(\sigma^2\) | +| `hetero_pc_dist` | \(\alpha + \beta d_i\) | +| `hetero_model_var` | \(\alpha + \beta v_i\) | +| `hetero_pc_dist_quad` | \(\alpha + \beta_1 d_i + \beta_2 d_i^2\) | +| `hetero_model_var_quad` | \(\alpha + \beta_1 v_i + \beta_2 v_i^2\) | +| `hetero_combined_linear` | \(\alpha + \beta_d d_i + \beta_m v_i\) | +| `hetero_combined_quadratic` | \(\alpha + \beta_{d1} d_i + \beta_{d2} d_i^2 + \beta_{m1} v_i + \beta_{m2} v_i^2\) | + +Select an error model at initialization (or override per training run with +`training_options={"error_model": ...}`): + +```python +bmc = BayesianModelCombination( + models_list=["FRDM12", "HFB24", "D1M", "UNEDF1", "BCPM"], + data_dict=data_dict, + truth_column_name="AME2020", + error_model="hetero_model_var", # variance grows with model spread +) + +bmc.orthogonalize("BE", train_df, components_kept=3) +bmc.train(training_options={ + "iterations": 50000, + "burn": 5000, # burn-in for the Metropolis-Hastings step +}) + +print(f"MH acceptance rate: {bmc.mh_acceptance_rate_:.2%}") + +# predict() and evaluate() automatically use per-point variances +rndm_m, lower_df, median_df, upper_df = bmc.predict("BE") +``` + +The coefficients \(b\) are still updated with conjugate Gibbs steps; the +variance parameters \((\alpha, \beta, \dots)\) are sampled with a +positivity-constrained Metropolis-Hastings step under Gamma priors. During +burn-in the proposal covariance is automatically rescaled toward a target +acceptance rate of 25% (and then frozen), so the defaults work across data +scales. All tuning knobs can be overridden through `training_options` +(`proposal_scales`, `init_params`, `prior_spec`, `adapt_proposal`, +`target_acceptance`). Check `bmc.mh_acceptance_rate_` after training; if it +is far from ~25%, increase `burn` or set `proposal_scales` manually. + +### Reproducibility + +All pybmc randomness — MCMC training and posterior-predictive draws — is +driven by a single seeded package-wide generator (`pybmc.DEFAULT_SEED`), so a +fresh session that performs the same sequence of calls reproduces end to end. +`predict()`/`evaluate()` additionally default to a fixed per-call seed so +repeated calls return identical draws. To re-seed the shared generator +mid-session, or to pin an individual training run, use: + +```python +import pybmc + +pybmc.set_seed(12345) # re-seed the shared stream +bmc.train(training_options={"seed": 42, ...}) # pin one training run +rndm_m, *_ = bmc.predict("BE", seed=None) # draw from the shared stream +``` + +!!! note "Simplex constraint" + Heteroscedastic error models currently require the unconstrained weight + mode; combining them with `constraint="simplex"` raises a `ValueError`. + +To compare error models quantitatively, score the coverage curve returned by +`evaluate()` — 0 is perfect calibration, and the diagnosis tells you whether +intervals are too narrow (`underdispersed`) or too wide (`overdispersed`): + +```python +import numpy as np +from pybmc import coverage_quality, diagnose_coverage_shape + +percentiles = np.arange(0, 101, 5) + +for error_model in ["homoscedastic", "hetero_model_var", "hetero_combined_linear"]: + bmc.train(training_options={"iterations": 50000, "error_model": error_model}) + cov = bmc.evaluate() + score = coverage_quality(percentiles, cov) + diag = diagnose_coverage_shape(percentiles, cov) + print(f"{error_model:25s} score={score:6.2f} ({diag['diagnosis']})") +``` + ### Inspecting Model Weights After training, you can inspect the inferred model weights using `get_weights()`: diff --git a/pybmc/__init__.py b/pybmc/__init__.py index dfc4ce0..d338926 100644 --- a/pybmc/__init__.py +++ b/pybmc/__init__.py @@ -6,12 +6,43 @@ - Model: A model defined by input/output data - Dataset: Handles loading and preparing nuclear model datasets - BayesianModelCombination: Combines models using Bayesian inference + +Error models (see `pybmc.error_models`): +- homoscedastic (constant variance) and six heteroscedastic variants + whose variance depends on distance in principal-component space + and/or the spread among model predictions. All of them share one + likelihood and sampler; homoscedastic is the constant-only case. + +Randomness (see `pybmc.rng`): +- All samplers and posterior-predictive draws are driven by a single + seeded package-wide generator (`DEFAULT_SEED`), so runs are + reproducible end to end; use `set_seed` to re-seed mid-session. """ from .data import Dataset from .bmc import BayesianModelCombination -from .inference_utils import gibbs_sampler, gibbs_sampler_simplex, USVt_hat_extraction -from .sampling_utils import coverage +from .inference_utils import ( + gibbs_sampler, + gibbs_sampler_simplex, + gibbs_sampler_heteroscedastic, + USVt_hat_extraction, +) +from .sampling_utils import ( + coverage, + coverage_quality, + diagnose_coverage_shape, + mace, + reduced_chi_square, + DEFAULT_PREDICTIVE_SEED, +) +from .error_models import ( + VARIANCE_MODELS, + HeteroscedasticMetrics, + required_metrics, + variance_basis, + variance_parameter_names, +) +from .rng import DEFAULT_SEED, get_rng, set_seed __all__ = [ @@ -20,6 +51,20 @@ "BayesianModelCombination", "gibbs_sampler", "gibbs_sampler_simplex", + "gibbs_sampler_heteroscedastic", "USVt_hat_extraction", "coverage", + "coverage_quality", + "diagnose_coverage_shape", + "mace", + "reduced_chi_square", + "DEFAULT_PREDICTIVE_SEED", + "DEFAULT_SEED", + "get_rng", + "set_seed", + "VARIANCE_MODELS", + "HeteroscedasticMetrics", + "required_metrics", + "variance_basis", + "variance_parameter_names", ] diff --git a/pybmc/bmc.py b/pybmc/bmc.py index 05fc502..c141628 100644 --- a/pybmc/bmc.py +++ b/pybmc/bmc.py @@ -3,13 +3,28 @@ import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split import os -from .inference_utils import gibbs_sampler, gibbs_sampler_simplex, USVt_hat_extraction -from .sampling_utils import coverage, rndm_m_random_calculator +from .inference_utils import ( + gibbs_sampler_simplex, + gibbs_sampler_heteroscedastic, + USVt_hat_extraction, +) +from .sampling_utils import ( + coverage, + rndm_m_heteroscedastic_calculator, + DEFAULT_PREDICTIVE_SEED, +) +from .error_models import ( + VARIANCE_MODELS, + DEFAULT_SAMPLER_SETTINGS, + HeteroscedasticMetrics, + required_metrics, + variance_basis, +) class BayesianModelCombination: """ - The main idea of this class is to perform BMM on the set of models that we choose + The main idea of this class is to perform Bayesian Model Combination (BMC) on the set of models that we choose from the dataset class. What should this class contain: + Orthogonalization step. + Perform Bayesian inference on the training data that we extract from the Dataset class. @@ -17,9 +32,10 @@ class BayesianModelCombination: """ VALID_CONSTRAINTS = ("unconstrained", "simplex") + VALID_ERROR_MODELS = tuple(VARIANCE_MODELS) - def __init__(self, models_list, data_dict, truth_column_name, weights=None, constraint="unconstrained"): - """ + def __init__(self, models_list, data_dict, truth_column_name, weights=None, constraint="unconstrained", error_model="homoscedastic"): + """ Initialize the BayesianModelCombination class. :param models_list: List of model names @@ -31,10 +47,22 @@ def __init__(self, models_list, data_dict, truth_column_name, weights=None, cons - ``"simplex"``: Forces weights to lie on the probability simplex (each weight between 0 and 1, weights sum to 1). Uses a Metropolis-within-Gibbs sampler to enforce the constraint. + :param error_model: Noise structure of the combination. Options + (see :mod:`pybmc.error_models` for the variance forms): + - ``"homoscedastic"`` (default): A single constant variance. + - ``"hetero_pc_dist"`` / ``"hetero_pc_dist_quad"``: Variance + linear/quadratic in the distance from the training centroid + in principal-component space. + - ``"hetero_model_var"`` / ``"hetero_model_var_quad"``: Variance + linear/quadratic in the spread among model predictions. + - ``"hetero_combined_linear"`` / ``"hetero_combined_quadratic"``: + Variance depending on both metrics. + Heteroscedastic error models currently require the + ``"unconstrained"`` weight mode. """ if not isinstance(models_list, list) or not all(isinstance(model, str) for model in models_list): - raise ValueError("The 'models' should be a list of model names (strings) for Bayesian Combination.") + raise ValueError("The 'models' should be a list of model names (strings) for Bayesian Combination.") if not isinstance(data_dict, dict) or not all(isinstance(df, pd.DataFrame) for df in data_dict.values()): raise ValueError("The 'data_dict' should be a dictionary of pandas DataFrames, one per property.") if constraint not in self.VALID_CONSTRAINTS: @@ -42,15 +70,29 @@ def __init__(self, models_list, data_dict, truth_column_name, weights=None, cons f"Invalid constraint '{constraint}'. " f"Must be one of {self.VALID_CONSTRAINTS}." ) + if error_model not in self.VALID_ERROR_MODELS: + raise ValueError( + f"Invalid error model '{error_model}'. " + f"Must be one of {self.VALID_ERROR_MODELS}." + ) + if error_model != "homoscedastic" and constraint == "simplex": + raise ValueError( + "Heteroscedastic error models are not supported with the " + "'simplex' constraint; use constraint='unconstrained'." + ) - self.data_dict = data_dict - self.models_list = models_list + self.data_dict = data_dict + self.models_list = models_list self.models = [m for m in models_list if m != 'truth'] - self.weights = weights if weights is not None else None + self.weights = weights if weights is not None else None self.truth_column_name = truth_column_name self.constraint = constraint + self.error_model = error_model self.samples = None self.Vt_hat = None + self.mh_acceptance_rate_ = None + self._trained_error_model = None + self._metrics_calculator = None def orthogonalize(self, property, train_df, components_kept): @@ -94,27 +136,62 @@ def orthogonalize(self, property, train_df, components_kept): self.S_hat = S_hat self.Vt_hat_normalized = Vt_hat_normalized self._predictions_mean_train = predictions_mean_train + # Raw training predictions, needed to fit the heteroscedasticity + # metrics (PC-space centroid and normalization bounds). + self._train_model_predictions = model_predictions_train def train(self, training_options=None): """ Train the model combination using training data and optional training parameters. + All error models (the homoscedastic one included) share the + likelihood ``y_i ~ N(X_i . b, sigma_i^2)`` and are trained with + the same Gibbs-within-Metropolis sampler; the homoscedastic + model is simply the case where the variance basis is the + constant column alone, so ``sigma_i^2 = sigma^2``. + :param training_options: Dictionary of training options. Keys: - - 'iterations': (int) Number of Gibbs iterations (default 50000) + - 'iterations': (int) Number of retained Gibbs samples (default 50000) - 'sampler': (str) Override the constraint mode for this training run. ``"unconstrained"`` or ``"simplex"``. If not provided, uses the instance-level ``self.constraint`` set at initialization. + - 'error_model': (str) Override the error model for this training + run (see ``VALID_ERROR_MODELS``). If not provided, uses the + instance-level ``self.error_model`` set at initialization. + - 'seed': (int) Seed for the sampler. If not provided, the + sampler draws from the shared package-wide generator + (see :mod:`pybmc.rng`), which is seeded at import. - 'b_mean_prior': (np.ndarray) Prior mean vector (default zeros) - *(unconstrained sampler only)* + *(unconstrained sampler)* - 'b_mean_cov': (np.ndarray) Prior covariance matrix (default diag(S_hat²)) - *(unconstrained sampler only)* + *(unconstrained sampler)* - 'nu0_chosen': (float) Degrees of freedom for variance prior (default 1.0) + *(simplex sampler only)* - 'sigma20_chosen': (float) Prior variance (default 0.02) - - 'burn': (int) Burn-in iterations (default 10000) *(simplex sampler only)* + - 'burn': (int) Burn-in iterations (default 10000 for simplex, + 5000 otherwise) - 'stepsize': (float) Proposal step size (default 0.001) *(simplex sampler only)* + - 'proposal_scales': (list) Diagonal of the Metropolis-Hastings + proposal covariance for the variance parameters; sensible + per-model defaults are used if omitted + *(unconstrained sampler)* + - 'init_params': (list) Initial values for the non-constant + variance parameters *(unconstrained sampler)* + - 'prior_spec': (list of (shape, scale)) Gamma priors for the + variance parameters *(unconstrained sampler)* + - 'adapt_proposal': (bool) Rescale the proposal during burn-in + toward 'target_acceptance' (default True) + *(unconstrained sampler)* + - 'target_acceptance': (float) Acceptance rate targeted by the + burn-in adaptation (default 0.25) + *(unconstrained sampler)* + + After training with the unconstrained sampler, the + Metropolis-Hastings acceptance rate of the variance parameters + is available in ``self.mh_acceptance_rate_``. """ if training_options is None: training_options = {} @@ -127,15 +204,31 @@ def train(self, training_options=None): f"Must be one of {self.VALID_CONSTRAINTS}." ) + # Same override pattern for the error model. + error_model_mode = training_options.get('error_model', self.error_model) + if error_model_mode not in self.VALID_ERROR_MODELS: + raise ValueError( + f"Invalid error model '{error_model_mode}'. " + f"Must be one of {self.VALID_ERROR_MODELS}." + ) + if error_model_mode != "homoscedastic" and sampler_mode == "simplex": + raise ValueError( + "Heteroscedastic error models are not supported with the " + "'simplex' sampler; use the unconstrained sampler." + ) + iterations = training_options.get('iterations', 50000) num_components = self.U_hat.shape[1] S_hat = self.S_hat - nu0_chosen = training_options.get('nu0_chosen', 1.0) - sigma20_chosen = training_options.get('sigma20_chosen', 0.02) + seed = training_options.get('seed') if sampler_mode == "simplex": + nu0_chosen = training_options.get('nu0_chosen', 1.0) + sigma20_chosen = training_options.get('sigma20_chosen', 0.02) burn = training_options.get('burn', 10000) stepsize = training_options.get('stepsize', 0.001) + self._metrics_calculator = None + self.mh_acceptance_rate_ = None self.samples = gibbs_sampler_simplex( self.centered_experiment_train, self.U_hat, @@ -145,24 +238,70 @@ def train(self, training_options=None): [nu0_chosen, sigma20_chosen], burn=burn, stepsize=stepsize, + seed=seed, ) else: + settings = DEFAULT_SAMPLER_SETTINGS[error_model_mode] + terms = VARIANCE_MODELS[error_model_mode] + metric_names = required_metrics(error_model_mode) + + if metric_names: + # Fit the metrics (PC centroid, normalization bounds) on the + # training predictions, then build the variance design matrix. + self._metrics_calculator = HeteroscedasticMetrics( + metric_names + ).fit(self._train_model_predictions, self.Vt_hat) + metrics_train = self._metrics_calculator.compute( + self._train_model_predictions + ) + basis_train = variance_basis(metrics_train, terms) + else: + # Homoscedastic: the variance basis is the constant column + # alone, so theta = [sigma^2]. + self._metrics_calculator = None + basis_train = np.ones( + (len(self.centered_experiment_train), 1) + ) + b_mean_prior = training_options.get('b_mean_prior', np.zeros(num_components)) b_mean_cov = training_options.get('b_mean_cov', np.diag(S_hat**2)) - self.samples = gibbs_sampler( + self.samples, self.mh_acceptance_rate_ = gibbs_sampler_heteroscedastic( self.centered_experiment_train, self.U_hat, + basis_train, iterations, - [b_mean_prior, b_mean_cov, nu0_chosen, sigma20_chosen], + burn=training_options.get('burn', 5000), + proposal_scales=training_options.get( + 'proposal_scales', settings['proposal_scales'] + ), + init_params=training_options.get( + 'init_params', settings['init_params'] + ), + prior_spec=training_options.get( + 'prior_spec', settings['prior_spec'] + ), + b_mean_prior=b_mean_prior, + b_mean_cov=b_mean_cov, + adapt_proposal=training_options.get('adapt_proposal', True), + target_acceptance=training_options.get('target_acceptance', 0.25), + seed=seed, ) + # Remember which error model produced self.samples so that + # predict()/evaluate() use the matching predictive distribution. + self._trained_error_model = error_model_mode - def predict(self, property): + + def predict(self, property, seed=DEFAULT_PREDICTIVE_SEED): """ Predict a specified property using the model weights learned during training. :param property: The property name to predict (e.g., 'ChRad'). + :param seed: Seed for the posterior predictive draws (subsampling + of the posterior samples and the noise added on top). + Defaults to a fixed constant so repeated calls are + reproducible; pass a different value for independent draws. :return: - rndm_m: array of shape (n_samples, n_points), full posterior draws - lower_df: DataFrame with columns domain_keys + ['Predicted_Lower'] @@ -191,7 +330,9 @@ def predict(self, property): model_preds = df[available_models].values domain_df = df[domain_keys].reset_index(drop=True) - rndm_m, (lower, median, upper) = rndm_m_random_calculator(model_preds, self.samples, self.Vt_hat) + rndm_m, (lower, median, upper) = self._posterior_predictive( + model_preds, seed=seed + ) # Build output DataFrames lower_df = domain_df.copy() @@ -206,11 +347,14 @@ def predict(self, property): return rndm_m, lower_df, median_df, upper_df - def evaluate(self, domain_filter=None): + def evaluate(self, domain_filter=None, seed=DEFAULT_PREDICTIVE_SEED): """ Evaluate the model combination using coverage calculation. :param domain_filter: dict with optional domain key ranges, e.g., {"Z": (20, 30), "N": (20, 40)} + :param seed: Seed for the posterior predictive draws underlying + the coverage calculation. Defaults to a fixed constant so + repeated calls are reproducible. :return: coverage list for each percentile """ df = self.data_dict[self.current_property] @@ -229,11 +373,36 @@ def evaluate(self, domain_filter=None): else: df = df[df[col] == cond] + # Coverage is only defined where truth values exist. + df = df.dropna(subset=[self.truth_column_name]) + preds = df[self.models].to_numpy() - rndm_m, (lower, median, upper) = rndm_m_random_calculator(preds, self.samples, self.Vt_hat) + rndm_m, (lower, median, upper) = self._posterior_predictive(preds, seed=seed) return coverage(np.arange(0, 101, 5), rndm_m, df, truth_column=self.truth_column_name) + def _posterior_predictive(self, model_preds, seed=DEFAULT_PREDICTIVE_SEED): + """ + Posterior predictive draws for the given model predictions, using + the predictive distribution matching the trained error model. + + :param model_preds: Array of shape (n_points, n_models) with one + column per model in ``self.models`` order. + :param seed: Seed for the posterior predictive draws. + :return: Tuple ``(rndm_m, (lower, median, upper))``. + """ + error_model = self._trained_error_model or "homoscedastic" + terms = VARIANCE_MODELS[error_model] + if terms: + metrics = self._metrics_calculator.compute(model_preds) + basis = variance_basis(metrics, terms) + else: + # Homoscedastic: constant-only variance basis. + basis = np.ones((model_preds.shape[0], 1)) + return rndm_m_heteroscedastic_calculator( + model_preds, self.samples, self.Vt_hat, basis, seed=seed + ) + def get_weights(self, summary=True): """ Compute model weights from posterior samples. @@ -252,7 +421,10 @@ def get_weights(self, summary=True): if self.samples is None or self.Vt_hat is None: raise ValueError("Must call `orthogonalize()` and `train()` before getting weights.") - betas = self.samples[:, :-1] + # The first k columns are the PC coefficients; the remaining + # columns are variance parameters (a single sigma^2 for the + # homoscedastic model, several for heteroscedastic models). + betas = self.samples[:, : self.Vt_hat.shape[0]] n_models = self.Vt_hat.shape[1] default_weights = np.full(n_models, 1.0 / n_models) weight_matrix = betas @ self.Vt_hat + default_weights diff --git a/pybmc/error_models.py b/pybmc/error_models.py new file mode 100644 index 0000000..76ed8bf --- /dev/null +++ b/pybmc/error_models.py @@ -0,0 +1,293 @@ +"""Heteroscedastic error models for Bayesian model combination. + +All error models share the mean structure of the orthogonalized BMC +regression and differ only in how the noise variance depends on the +data point: + +============================= ==================================================== +name sigma_i^2 +============================= ==================================================== +``homoscedastic`` sigma^2 (constant) +``hetero_pc_dist`` alpha + beta * d_i +``hetero_model_var`` alpha + beta * v_i +``hetero_pc_dist_quad`` alpha + beta_1 d_i + beta_2 d_i^2 +``hetero_model_var_quad`` alpha + beta_1 v_i + beta_2 v_i^2 +``hetero_combined_linear`` alpha + beta_d d_i + beta_m v_i +``hetero_combined_quadratic`` alpha + beta_d1 d_i + beta_d2 d_i^2 + + beta_m1 v_i + beta_m2 v_i^2 +============================= ==================================================== + +with two physics-informed, per-point metrics: + +- ``pc_dist`` (``d``): Euclidean distance from the training-data centroid + in principal-component space — grows away from the fitted region. +- ``model_var`` (``v``): variance among the individual model predictions — + grows where the models disagree. + +Both metrics are min-max normalized using the *training* points only, so +values on extrapolated points can exceed 1. + +Every model — the homoscedastic one included — is parametrized on the +variance (sigma^2) scale and shares the single likelihood +``y_i ~ N(X_i . b, sigma_i^2)`` sampled by +:func:`pybmc.inference_utils.gibbs_sampler_heteroscedastic`; the +homoscedastic model is simply the case where the variance basis is the +constant column alone. +""" + +import numpy as np + +#: Floor applied to a variance only where positivity is *not* guaranteed +#: by construction: the sampler's initial constant term (estimated from +#: data residuals, which can be exactly zero for a perfect fit) and +#: prediction-time variances (the normalized metrics of extrapolated +#: points can be negative, so ``phi . theta`` can dip below zero there). +#: During sampling no floor is needed: the variance parameters are kept +#: strictly positive by the Metropolis-Hastings step and the training +#: variance basis is non-negative with a leading column of ones, so +#: every per-point variance is positive by construction. +VARIANCE_FLOOR = 1e-9 + +#: Maps each error-model name to its variance-basis terms beyond the +#: constant, as ``(metric_name, power)`` tuples. ``homoscedastic`` has no +#: terms: its variance basis is the constant column alone, and it runs +#: through the same likelihood and sampler as every other error model. +VARIANCE_MODELS = { + "homoscedastic": [], + "hetero_pc_dist": [("pc_dist", 1)], + "hetero_model_var": [("model_var", 1)], + "hetero_pc_dist_quad": [("pc_dist", 1), ("pc_dist", 2)], + "hetero_model_var_quad": [("model_var", 1), ("model_var", 2)], + "hetero_combined_linear": [("pc_dist", 1), ("model_var", 1)], + "hetero_combined_quadratic": [ + ("pc_dist", 1), + ("pc_dist", 2), + ("model_var", 1), + ("model_var", 2), + ], +} + +#: Metropolis-Hastings tuning defaults per error model: random-walk +#: proposal scales (variances of the diagonal Gaussian proposal), initial +#: values for the non-constant variance parameters, and Gamma prior +#: ``(shape, scale)`` pairs for every variance parameter (constant term +#: first). +DEFAULT_SAMPLER_SETTINGS = { + "homoscedastic": { + "proposal_scales": [0.05], + "init_params": [], + "prior_spec": [(2, 10)], + }, + "hetero_pc_dist": { + "proposal_scales": [0.05, 0.005], + "init_params": [0.01], + "prior_spec": [(2, 10), (1, 1)], + }, + "hetero_model_var": { + "proposal_scales": [0.05, 0.005], + "init_params": [0.01], + "prior_spec": [(2, 10), (1, 1)], + }, + "hetero_pc_dist_quad": { + "proposal_scales": [5e-2, 5e-3, 5e-3], + "init_params": [0.01, 0.001], + "prior_spec": [(2, 10), (2, 10), (2, 10)], + }, + "hetero_model_var_quad": { + "proposal_scales": [5e-2, 5e-3, 5e-3], + "init_params": [0.01, 0.001], + "prior_spec": [(2, 10), (2, 10), (2, 10)], + }, + "hetero_combined_linear": { + "proposal_scales": [1e-2, 1e-3, 1e-3], + "init_params": [0.01, 0.01], + "prior_spec": [(2, 10), (2, 10), (2, 10)], + }, + "hetero_combined_quadratic": { + "proposal_scales": [1e-2, 1e-3, 1e-3, 1e-3, 1e-3], + "init_params": [0.01, 0.001, 0.01, 0.001], + "prior_spec": [(2, 10)] * 5, + }, +} + + +def required_metrics(error_model): + """ + Returns the metric names an error model needs. + + Args: + error_model (str): One of the keys of `VARIANCE_MODELS`. + + Returns: + list[str]: Unique metric names (empty for ``homoscedastic``). + """ + if error_model not in VARIANCE_MODELS: + raise ValueError( + f"Unknown error model '{error_model}'. " + f"Must be one of {tuple(VARIANCE_MODELS)}." + ) + return sorted({metric for metric, _ in VARIANCE_MODELS[error_model]}) + + +def variance_parameter_names(error_model): + """ + Returns human-readable names of the variance parameters of a model. + + Args: + error_model (str): One of the keys of `VARIANCE_MODELS`. + + Returns: + list[str]: Names such as ``['alpha', 'beta_pc_dist^1', ...]``; + ``['sigma^2']`` for the homoscedastic model (whose constant term + is the variance itself). + """ + terms = VARIANCE_MODELS[error_model] if error_model in VARIANCE_MODELS else None + if terms is None: + raise ValueError( + f"Unknown error model '{error_model}'. " + f"Must be one of {tuple(VARIANCE_MODELS)}." + ) + if not terms: + return ["sigma^2"] + return ["alpha"] + [f"beta_{metric}^{power}" for metric, power in terms] + + +def pc_distance_metric(model_predictions, Vt_hat, pc_centroid): + """ + Distance of each point from a reference centroid in PC space. + + The principal-component coordinates of a point are obtained by + projecting its raw model predictions with ``Vt_hat`` (for a + row-centered SVD this is identical to projecting the centered + predictions, since the right singular vectors are orthogonal to the + all-ones direction). + + Args: + model_predictions (numpy.ndarray): Model outputs, shape + ``(n_points, n_models)``. + Vt_hat (numpy.ndarray): Scaled right singular vectors, shape + ``(components_kept, n_models)``. + pc_centroid (numpy.ndarray): Training centroid in PC space, + shape ``(components_kept,)``. + + Returns: + numpy.ndarray: Euclidean distances, shape ``(n_points,)``. + """ + pc_coords = model_predictions @ Vt_hat.T + return np.linalg.norm(pc_coords - pc_centroid, axis=1) + + +def model_variance_metric(model_predictions): + """ + Variance among the model predictions for each point (NaN-aware). + + Args: + model_predictions (numpy.ndarray): Model outputs, shape + ``(n_points, n_models)``. + + Returns: + numpy.ndarray: Per-point variance across models, shape ``(n_points,)``. + """ + return np.nanvar(model_predictions, axis=1) + + +def variance_basis(metrics, terms): + """ + Builds the variance design matrix ``phi`` for a heteroscedastic model. + + The per-point variance is ``sigma_i^2 = phi[i] . theta`` where the + first column of ``phi`` is ones (the constant term ``alpha``). + + Args: + metrics (dict[str, numpy.ndarray]): Metric arrays keyed by name. + terms (list[tuple[str, int]]): ``(metric_name, power)`` pairs. + + Returns: + numpy.ndarray: Basis matrix, shape ``(n_points, 1 + len(terms))``. + """ + n_points = len(next(iter(metrics.values()))) + columns = [np.ones(n_points)] + for metric, power in terms: + columns.append(np.asarray(metrics[metric], dtype=float) ** power) + return np.column_stack(columns) + + +class HeteroscedasticMetrics: + """ + Computes and normalizes the per-point metrics of the error models. + + The object is fit on the training model predictions: it stores the + training centroid in PC space and the training min/max of every + metric. Metrics for any other set of points are then computed + consistently and scaled with the *training* bounds, so extrapolated + points can legitimately exceed 1. + """ + + def __init__(self, metric_names): + """ + :param metric_names: Metric names to compute + (subset of ``{'pc_dist', 'model_var'}``). + """ + unknown = set(metric_names) - {"pc_dist", "model_var"} + if unknown: + raise ValueError(f"Unknown metric names: {sorted(unknown)}") + self.metric_names = list(metric_names) + self.Vt_hat = None + self.pc_centroid = None + self.bounds = {} + + def fit(self, train_model_predictions, Vt_hat): + """ + Fit the normalization on the training predictions. + + Args: + train_model_predictions (numpy.ndarray): Training model + outputs, shape ``(n_train, n_models)``. + Vt_hat (numpy.ndarray): Scaled right singular vectors from + the orthogonalization step. + + Returns: + HeteroscedasticMetrics: ``self``, for chaining. + """ + self.Vt_hat = np.asarray(Vt_hat) + self.pc_centroid = np.mean( + train_model_predictions @ self.Vt_hat.T, axis=0 + ) + train_metrics = self._raw_metrics(train_model_predictions) + self.bounds = {} + for name, values in train_metrics.items(): + lo, hi = float(np.min(values)), float(np.max(values)) + self.bounds[name] = (lo, hi) + return self + + def compute(self, model_predictions): + """ + Computes normalized metrics for a set of points. + + Args: + model_predictions (numpy.ndarray): Model outputs, shape + ``(n_points, n_models)``. + + Returns: + dict[str, numpy.ndarray]: Normalized metric arrays keyed by name. + """ + if self.Vt_hat is None: + raise ValueError("Call `fit()` before `compute()`.") + metrics = self._raw_metrics(model_predictions) + for name, values in metrics.items(): + lo, hi = self.bounds[name] + if hi > lo: + metrics[name] = (values - lo) / (hi - lo) + # A metric that is constant on the training set is left + # unscaled; the sampler treats it like an extra constant. + return metrics + + def _raw_metrics(self, model_predictions): + metrics = {} + if "pc_dist" in self.metric_names: + metrics["pc_dist"] = pc_distance_metric( + model_predictions, self.Vt_hat, self.pc_centroid + ) + if "model_var" in self.metric_names: + metrics["model_var"] = model_variance_metric(model_predictions) + return metrics diff --git a/pybmc/inference_utils.py b/pybmc/inference_utils.py index eadae4b..2c5ee43 100644 --- a/pybmc/inference_utils.py +++ b/pybmc/inference_utils.py @@ -1,67 +1,62 @@ import numpy as np +from .error_models import VARIANCE_FLOOR +from .rng import get_rng -def gibbs_sampler(y, X, iterations, prior_info): + +def gibbs_sampler(y, X, iterations, prior_info=None, burn=5000, seed=None): """ - Performs Gibbs sampling for Bayesian linear regression. + Gibbs sampler for the homoscedastic (constant-variance) model. + + The homoscedastic model is the constant-only special case of the + heteroscedastic likelihood (``sigma_i^2 = sigma^2`` for every point), + so this is a thin wrapper around `gibbs_sampler_heteroscedastic` + with a constant-only variance basis. There is no separate + homoscedastic likelihood implementation. Args: y (numpy.ndarray): Response vector (centered). X (numpy.ndarray): Design matrix. - iterations (int): Number of sampling iterations. - prior_info (tuple[numpy.ndarray, numpy.ndarray, float, float]): Prior parameters: - - `b_mean_prior` (numpy.ndarray): Prior mean for coefficients. - - `b_mean_cov` (numpy.ndarray): Prior covariance matrix. - - `nu0` (float): Prior degrees of freedom for variance. - - `sigma20` (float): Prior variance. + iterations (int): Number of retained posterior samples. + prior_info (dict, optional): Optional priors with keys + ``'b_mean_prior'``, ``'b_mean_cov'`` (Gaussian prior on the + coefficients) and ``'prior_spec'`` (Gamma ``(shape, scale)`` + prior on ``sigma^2``). See `gibbs_sampler_heteroscedastic`. + burn (int, optional): Burn-in iterations (default: 5000). + seed (int | numpy.random.Generator | None, optional): Seed for + the sampler. None (default) draws from the shared + package-wide generator (see :mod:`pybmc.rng`). Returns: - numpy.ndarray: Posterior samples `[beta, sigma]`. + numpy.ndarray: Posterior samples ``[beta_1..beta_k, sigma^2]``. """ - b_mean_prior, b_mean_cov, nu0, sigma20 = prior_info - b_mean_cov_inv = np.linalg.inv(b_mean_cov) - n = len(y) - - X_T_X = X.T.dot(X) - X_T_X_inv = np.linalg.inv(X_T_X) - - b_data = X_T_X_inv.dot(X.T).dot(y) - supermodel = X.dot(b_data) - residuals = y - supermodel - sigma2 = np.sum(residuals**2) / len(residuals) - cov_matrix = sigma2 * X_T_X_inv - - samples = [] - - # Initialize sigma2 with a small positive value to avoid division by zero - sigma2 = max(sigma2, 1e-6) - - for i in range(iterations): - # Regularize the covariance matrix to ensure it is positive definite - cov_matrix = np.linalg.inv(X_T_X / sigma2 + b_mean_cov_inv + np.eye(X_T_X.shape[0]) * 1e-6) - mean_vector = cov_matrix.dot( - b_mean_cov_inv.dot(b_mean_prior) + X.T.dot(y) / sigma2 - ) - b_current = np.random.multivariate_normal(mean_vector, cov_matrix) - - # Sample from the conditional posterior of sigma2 given bs and data - supermodel = X.dot(b_current) - residuals = y - supermodel - shape_post = (nu0 + n) / 2.0 - scale_post = (nu0 * sigma20 + np.sum(residuals**2)) / 2.0 - sigma2 = max(1 / np.random.default_rng().gamma(shape_post, 1 / scale_post), 1e-6) - - samples.append(np.append(b_current, np.sqrt(sigma2))) - - return np.array(samples) + prior_info = prior_info or {} + variance_basis = np.ones((len(y), 1)) + samples, _ = gibbs_sampler_heteroscedastic( + y, + X, + variance_basis, + iterations, + burn=burn, + prior_spec=prior_info.get("prior_spec"), + b_mean_prior=prior_info.get("b_mean_prior"), + b_mean_cov=prior_info.get("b_mean_cov"), + seed=seed, + ) + return samples def gibbs_sampler_simplex( - y, X, Vt_hat, S_hat, iterations, prior_info, burn=10000, stepsize=0.001 + y, X, Vt_hat, S_hat, iterations, prior_info, burn=10000, stepsize=0.001, + seed=None, ): """ Performs Gibbs sampling with simplex constraints on model weights. + The likelihood is the same homoscedastic Gaussian model used by the + unconstrained sampler (``y_i ~ N(X_i . b, sigma^2)``); only the + weight constraint differs. + Args: y (numpy.ndarray): Centered response vector. X (numpy.ndarray): Design matrix of principal components. @@ -71,10 +66,15 @@ def gibbs_sampler_simplex( prior_info (list[float]): `[nu0, sigma20]` - prior parameters for variance. burn (int, optional): Burn-in iterations (default: 10000). stepsize (float, optional): Proposal step size (default: 0.001). + seed (int | numpy.random.Generator | None, optional): Seed for + the sampler. None (default) draws from the shared + package-wide generator (see :mod:`pybmc.rng`). Returns: - numpy.ndarray: Posterior samples `[beta, sigma]`. + numpy.ndarray: Posterior samples ``[beta_1..beta_k, sigma^2]``. """ + rng = get_rng(seed) + bias0 = np.full(len(Vt_hat.T), 1 / len(Vt_hat.T)) nu0, sigma20 = prior_info cov_matrix_step = np.diag(S_hat**2 * stepsize**2) @@ -82,8 +82,8 @@ def gibbs_sampler_simplex( b_current = np.full(len(X.T), 0) supermodel_current = X.dot(b_current) residuals_current = y - supermodel_current - log_likelihood_current = -np.sum(residuals_current**2) - sigma2 = -log_likelihood_current / len(residuals_current) + ssr_current = np.sum(residuals_current**2) + sigma2 = ssr_current / len(residuals_current) samples = [] acceptance = 0 @@ -93,54 +93,247 @@ def gibbs_sampler_simplex( if stepsize <= 0: raise ValueError("Stepsize must be positive.") - # Burn-in phase - for i in range(burn): - b_proposed = np.random.multivariate_normal(b_current, cov_matrix_step) + for i in range(burn + iterations): + b_proposed = rng.multivariate_normal(b_current, cov_matrix_step) omegas_proposed = np.dot(b_proposed, Vt_hat) + bias0 # Skip proposals with negative weights if not np.any(omegas_proposed < 0): supermodel_proposed = X.dot(b_proposed) residuals_proposed = y - supermodel_proposed - log_likelihood_proposed = -np.sum(residuals_proposed**2) + ssr_proposed = np.sum(residuals_proposed**2) + # Gaussian likelihood ratio at fixed sigma^2: + # exp(-(SSR' - SSR) / (2 sigma^2)). acceptance_prob = min( 1, - np.exp((log_likelihood_proposed - log_likelihood_current) / sigma2), + np.exp((ssr_current - ssr_proposed) / (2 * sigma2)), ) - if np.random.uniform() < acceptance_prob: + if rng.uniform() < acceptance_prob: b_current = np.copy(b_proposed) - log_likelihood_current = log_likelihood_proposed + ssr_current = ssr_proposed + if i >= burn: + acceptance += 1 - # Sample variance + # Sample sigma^2 from its inverse-gamma full conditional + # (positive by construction). shape_post = (nu0 + n) / 2.0 - scale_post = (nu0 * sigma20 - log_likelihood_current) / 2.0 - sigma2 = 1 / np.random.default_rng().gamma(shape_post, 1 / scale_post) + scale_post = (nu0 * sigma20 + ssr_current) / 2.0 + sigma2 = 1 / rng.gamma(shape_post, 1 / scale_post) + if i >= burn: + samples.append(np.append(b_current, sigma2)) - # Sampling phase - for i in range(iterations): - b_proposed = np.random.multivariate_normal(b_current, cov_matrix_step) - omegas_proposed = np.dot(b_proposed, Vt_hat) + bias0 + return np.array(samples) - if not np.any(omegas_proposed < 0): - supermodel_proposed = X.dot(b_proposed) - residuals_proposed = y - supermodel_proposed - log_likelihood_proposed = -np.sum(residuals_proposed**2) - acceptance_prob = min( - 1, - np.exp((log_likelihood_proposed - log_likelihood_current) / sigma2), + +def gibbs_sampler_heteroscedastic( + y, + X, + variance_basis, + iterations, + burn=5000, + proposal_scales=None, + init_params=None, + prior_spec=None, + b_mean_prior=None, + b_mean_cov=None, + adapt_proposal=True, + target_acceptance=0.25, + seed=None, +): + """ + Gibbs-within-Metropolis sampler for the shared error-model likelihood. + + The regression model is ``y_i ~ N(X_i . b, sigma_i^2)`` with a + per-point variance that is linear in basis functions of the + heteroscedasticity metrics: + + ``sigma_i^2 = variance_basis[i] . theta`` + + The homoscedastic model is the special case where the basis is a + single column of ones, so ``theta = [sigma^2]`` is the constant + variance. All error models share this one likelihood. + + The coefficients ``b`` are updated with a conjugate (weighted + least-squares) Gibbs step; the variance parameters ``theta`` with a + positivity-constrained Gaussian random-walk Metropolis-Hastings step + under Gamma priors. Because ``theta`` is kept strictly positive by + the MH step and ``variance_basis`` is validated to be non-negative + with a leading column of ones, every per-point variance satisfies + ``sigma_i^2 >= theta_1 > 0`` by construction — no variance flooring + is applied during sampling. The only floor is on the *initial* + constant term, which is estimated from the data residuals and could + otherwise be exactly zero for a perfectly fitting model. + + Args: + y (numpy.ndarray): Centered response vector, shape ``(n,)``. + X (numpy.ndarray): Design matrix (principal components), shape + ``(n, k)``. + variance_basis (numpy.ndarray): Variance design matrix ``phi`` + with a leading column of ones and no negative entries, shape + ``(n, p)``. See :func:`pybmc.error_models.variance_basis`. + iterations (int): Number of retained posterior samples. + burn (int, optional): Burn-in iterations discarded before + retention (default: 5000). + proposal_scales (list[float], optional): Diagonal of the Gaussian + random-walk proposal covariance for ``theta`` (length p). + Defaults to ``[1e-2, 1e-3, ..., 1e-3]``. + init_params (list[float], optional): Initial values for the + non-constant entries of ``theta`` (length p - 1, strictly + positive). The constant term starts at the OLS residual + variance. Defaults to 0.01 for every term. + prior_spec (list[tuple[float, float]], optional): Gamma prior + ``(shape, scale)`` for each entry of ``theta`` (length p). + Defaults to ``(2, 10)`` for every parameter. + b_mean_prior (numpy.ndarray, optional): Prior mean for ``b`` + (default zeros). + b_mean_cov (numpy.ndarray, optional): Prior covariance for ``b`` + (default ``1e6 * I``, i.e. weakly informative). + adapt_proposal (bool, optional): If True (default), rescale the + proposal covariance during burn-in toward + ``target_acceptance``, so the fixed defaults work across + data scales. Adaptation stops at the end of burn-in, which + preserves detailed balance for the retained samples. + target_acceptance (float, optional): Acceptance rate targeted by + the burn-in adaptation (default: 0.25). + seed (int | numpy.random.Generator | None, optional): Seed for + the sampler. None (default) draws from the shared + package-wide generator (see :mod:`pybmc.rng`). + + Returns: + tuple[numpy.ndarray, float]: + - `samples` (numpy.ndarray): Posterior samples + ``[b_1..b_k, theta_1..theta_p]``, shape + ``(iterations, k + p)``. + - `acceptance_rate` (float): Post-burn-in MH acceptance rate. + """ + if burn < 0: + raise ValueError("Burn-in iterations must be non-negative.") + + rng = get_rng(seed) + + n_points, n_betas = X.shape + n_params = variance_basis.shape[1] + + if not np.allclose(variance_basis[:, 0], 1.0): + raise ValueError( + "The first column of 'variance_basis' must be ones " + "(the constant variance term)." + ) + if np.any(variance_basis < 0): + raise ValueError( + "'variance_basis' must be non-negative so that positive " + "variance parameters guarantee positive variances." + ) + + if proposal_scales is None: + proposal_scales = [1e-2] + [1e-3] * (n_params - 1) + if len(proposal_scales) != n_params: + raise ValueError( + f"'proposal_scales' must have length {n_params} " + f"(got {len(proposal_scales)})." + ) + proposal_cov = np.diag(np.asarray(proposal_scales, dtype=float)) + + if prior_spec is None: + prior_spec = [(2, 10)] * n_params + if len(prior_spec) != n_params: + raise ValueError( + f"'prior_spec' must have length {n_params} " + f"(got {len(prior_spec)})." + ) + prior_shapes = np.array([shape for shape, _ in prior_spec], dtype=float) + prior_scales = np.array([scale for _, scale in prior_spec], dtype=float) + + def log_likelihood(residuals, sigma2): + return -0.5 * float( + np.sum(np.log(2.0 * np.pi * sigma2) + residuals**2 / sigma2) + ) + + def log_prior(theta): + # Gamma log-density without the normalization constant, which + # cancels in the Metropolis-Hastings ratio. + return float( + np.sum((prior_shapes - 1.0) * np.log(theta) - theta / prior_scales) + ) + + if b_mean_prior is None: + b_mean_prior = np.zeros(n_betas) + if b_mean_cov is None: + b_mean_cov = np.eye(n_betas) * 1e6 + b_mean_cov_inv = np.linalg.inv(b_mean_cov) + + b_current = np.linalg.lstsq(X, y, rcond=None)[0] + if init_params is None: + init_params = [0.01] * (n_params - 1) + if len(init_params) != n_params - 1: + raise ValueError( + f"'init_params' must have length {n_params - 1} " + f"(got {len(init_params)})." + ) + if np.any(np.asarray(init_params, dtype=float) <= 0): + raise ValueError("'init_params' must be strictly positive.") + theta_current = np.concatenate( + [[max(np.var(y - X @ b_current), VARIANCE_FLOOR)], init_params] + ) + + samples = [] + accept_count = 0 + + # Burn-in adaptation of the proposal scale (Robbins-Monro style): + # every `adapt_interval` iterations the covariance is rescaled toward + # the target acceptance rate, then frozen for the sampling phase. + proposal_scale_factor = 1.0 + adapt_interval = 100 + accept_recent = 0 + + for i in range(burn + iterations): + # --- Gibbs step: b | theta (weighted least squares) --- + sigma2 = variance_basis @ theta_current + Xw = X / sigma2[:, None] + b_post_cov = np.linalg.inv( + X.T @ Xw + b_mean_cov_inv + np.eye(n_betas) * 1e-6 + ) + b_post_mean = b_post_cov @ ( + Xw.T @ y + b_mean_cov_inv @ b_mean_prior + ) + b_current = rng.multivariate_normal(b_post_mean, b_post_cov) + + # --- MH step: theta | b (positivity-constrained random walk) --- + residuals = y - X @ b_current + theta_proposed = np.atleast_1d( + rng.multivariate_normal( + theta_current, proposal_cov * proposal_scale_factor**2 ) - if np.random.uniform() < acceptance_prob: - b_current = np.copy(b_proposed) - log_likelihood_current = log_likelihood_proposed - acceptance += 1 + ) + if np.all(theta_proposed > 0): + sigma2_proposed = variance_basis @ theta_proposed + log_ratio = ( + log_likelihood(residuals, sigma2_proposed) + + log_prior(theta_proposed) + ) - ( + log_likelihood(residuals, sigma2) + + log_prior(theta_current) + ) + if np.log(rng.uniform()) < log_ratio: + theta_current = theta_proposed + if i >= burn: + accept_count += 1 + else: + accept_recent += 1 - # Sample variance - shape_post = (nu0 + n) / 2.0 - scale_post = (nu0 * sigma20 - log_likelihood_current) / 2.0 - sigma2 = 1 / np.random.default_rng().gamma(shape_post, 1 / scale_post) - samples.append(np.append(b_current, np.sqrt(sigma2))) + if adapt_proposal and i < burn and (i + 1) % adapt_interval == 0: + recent_rate = accept_recent / adapt_interval + proposal_scale_factor *= np.exp(recent_rate - target_acceptance) + proposal_scale_factor = float( + np.clip(proposal_scale_factor, 1e-6, 1e6) + ) + accept_recent = 0 - return np.array(samples) + if i >= burn: + samples.append(np.concatenate([b_current, theta_current])) + + acceptance_rate = accept_count / max(iterations, 1) + return np.array(samples), acceptance_rate def USVt_hat_extraction(U, S, Vt, components_kept): diff --git a/pybmc/rng.py b/pybmc/rng.py new file mode 100644 index 0000000..d68dbab --- /dev/null +++ b/pybmc/rng.py @@ -0,0 +1,62 @@ +"""Package-wide random-number generation. + +All stochastic pybmc routines (the MCMC samplers in +:mod:`pybmc.inference_utils` and the posterior-predictive draws in +:mod:`pybmc.sampling_utils`) obtain their generator through +:func:`get_rng`, so the whole pipeline is driven by one seeded state: + +- With ``seed=None`` a function draws from the shared package-wide + generator, which is seeded with `DEFAULT_SEED` at import time. A fresh + session that performs the same sequence of calls is therefore fully + reproducible, training included. +- With an explicit ``seed`` a function uses an independent generator + seeded with that value, so a single call is reproducible in isolation + regardless of what ran before it. + +Use `set_seed` to re-seed the shared generator mid-session (e.g. at the +top of a script or between repetitions of an experiment). +""" + +import numpy as np + +#: Seed for the shared package-wide generator (and the default for the +#: per-call reproducible posterior-predictive draws). +DEFAULT_SEED = 142858 + +_global_rng = np.random.default_rng(DEFAULT_SEED) + + +def get_rng(seed=None): + """ + Returns the generator to use for a stochastic routine. + + Args: + seed (int | numpy.random.Generator | None): If None, the shared + package-wide generator (seeded with `DEFAULT_SEED` at import, + or the last `set_seed` call). If an integer, a fresh + independent generator seeded with it. A ready-made + `numpy.random.Generator` is returned unchanged. + + Returns: + numpy.random.Generator: The generator to draw from. + """ + if seed is None: + return _global_rng + if isinstance(seed, np.random.Generator): + return seed + return np.random.default_rng(seed) + + +def set_seed(seed=DEFAULT_SEED): + """ + Re-seeds the shared package-wide generator. + + Args: + seed (int, optional): New seed (default: `DEFAULT_SEED`). + + Returns: + numpy.random.Generator: The freshly seeded shared generator. + """ + global _global_rng + _global_rng = np.random.default_rng(seed) + return _global_rng diff --git a/pybmc/sampling_utils.py b/pybmc/sampling_utils.py index cba9a4b..480d464 100644 --- a/pybmc/sampling_utils.py +++ b/pybmc/sampling_utils.py @@ -1,5 +1,18 @@ import numpy as np +from .error_models import VARIANCE_FLOOR +from .rng import DEFAULT_SEED, get_rng + +#: Default seed for posterior predictive draws (subsampling of posterior +#: samples and the noise added on top) when the caller does not supply +#: one explicitly. This is the same seed that drives the package-wide +#: generator used by the MCMC samplers (see :mod:`pybmc.rng`), so one +#: constant governs all pybmc randomness. Callers that need independent +#: draws across repeated calls (e.g. outer Monte Carlo loops) can pass +#: their own ``seed``, or ``seed=None`` to draw from the shared +#: package-wide stream instead. +DEFAULT_PREDICTIVE_SEED = DEFAULT_SEED + def coverage(percentiles, rndm_m, models_output, truth_column): """ @@ -14,7 +27,7 @@ def coverage(percentiles, rndm_m, models_output, truth_column): Returns: list[float]: Coverage percentages for each percentile. """ - # How often the model’s credible intervals actually contain the true value + # How often the model's credible intervals actually contain the true value data_total = len(rndm_m.T) # Number of data points M_evals = len(rndm_m) # Number of samples data_true = models_output[truth_column].tolist() @@ -37,50 +50,231 @@ def coverage(percentiles, rndm_m, models_output, truth_column): return coverage_results -def rndm_m_random_calculator(filtered_model_predictions, samples, Vt_hat): +def rndm_m_random_calculator( + filtered_model_predictions, samples, Vt_hat, seed=DEFAULT_PREDICTIVE_SEED +): """ - Generates posterior predictive samples and credible intervals. + Posterior predictive samples for the homoscedastic model. + + The homoscedastic model is the constant-only special case of the + heteroscedastic predictive distribution, so this delegates to + `rndm_m_heteroscedastic_calculator` with a constant-only variance + basis. Args: filtered_model_predictions (numpy.ndarray): Model predictions. - samples (numpy.ndarray): Gibbs samples `[beta, sigma]`. + samples (numpy.ndarray): Posterior samples `[beta, sigma^2]`. Vt_hat (numpy.ndarray): Normalized right singular vectors. + seed (int | None, optional): Seed for the posterior predictive + draws (subsampling of `samples` and the noise added on top). + Defaults to `DEFAULT_PREDICTIVE_SEED`; pass None to draw + from the shared package-wide stream instead. Returns: tuple[numpy.ndarray, list[numpy.ndarray]]: - `rndm_m` (numpy.ndarray): Posterior predictive samples. - `[lower, median, upper]` (list[numpy.ndarray]): Credible interval arrays. """ - np.random.seed(142858) - rng = np.random.default_rng() + constant_basis = np.ones((filtered_model_predictions.shape[0], 1)) + return rndm_m_heteroscedastic_calculator( + filtered_model_predictions, samples, Vt_hat, constant_basis, seed=seed + ) + + +def rndm_m_heteroscedastic_calculator( + filtered_model_predictions, samples, Vt_hat, variance_basis, + seed=DEFAULT_PREDICTIVE_SEED, +): + """ + Generates posterior predictive samples for any error model. + + The noise added to each prediction has a per-point variance + ``sigma_i^2 = phi_i . theta`` where ``theta`` are the variance + parameters of each posterior draw. The homoscedastic model is the + special case of a constant-only basis (a single column of ones), + handled by the `rndm_m_random_calculator` convenience wrapper. + + Args: + filtered_model_predictions (numpy.ndarray): Model predictions, + shape ``(n_points, n_models)``. + samples (numpy.ndarray): Posterior samples + ``[beta_1..beta_k, theta_1..theta_p]`` from + `gibbs_sampler_heteroscedastic`. + Vt_hat (numpy.ndarray): Normalized right singular vectors, shape + ``(k, n_models)``. + variance_basis (numpy.ndarray): Variance design matrix for the + prediction points, shape ``(n_points, p)``. + seed (int | None, optional): Seed for the posterior predictive + draws (subsampling of `samples` and the noise added on top). + Defaults to `DEFAULT_PREDICTIVE_SEED`; pass None to draw + from the shared package-wide stream instead. + + Returns: + tuple[numpy.ndarray, list[numpy.ndarray]]: + - `rndm_m` (numpy.ndarray): Posterior predictive samples. + - `[lower, median, upper]` (list[numpy.ndarray]): 95% credible + interval bounds and median. + """ + rng = get_rng(seed) n_draws = min(10000, len(samples)) replace = len(samples) < 10000 theta_rand_selected = rng.choice(samples, n_draws, replace=replace) - # Extract betas and noise std deviations - betas = theta_rand_selected[:, :-1] # shape: (10000, num_models - 1) - noise_stds = theta_rand_selected[:, -1] # shape: (10000,) + n_components = Vt_hat.shape[0] + betas = theta_rand_selected[:, :n_components] + variance_params = theta_rand_selected[:, n_components:] - # Compute model weights: shape (10000, num_models) + # Model weights and noiseless central predictions. default_weights = np.full(Vt_hat.shape[1], 1 / Vt_hat.shape[1]) - model_weights_random = ( - betas @ Vt_hat + default_weights - ) # broadcasting default_weights - - # Generate noiseless predictions: shape (10000, num_data_points) - yvals_rand_radius = ( - model_weights_random @ filtered_model_predictions.T - ) # dot product - - # Add Gaussian noise with std = noise_stds (assume diagonal covariance) - # We'll use broadcasting: noise_stds[:, None] * standard normal noise - noise = rng.standard_normal(yvals_rand_radius.shape) * noise_stds[:, None] - rndm_m = yvals_rand_radius + noise - - # Compute credible intervals - lower_radius = np.percentile(rndm_m, 2.5, axis=0) - median_radius = np.percentile(rndm_m, 50, axis=0) - upper_radius = np.percentile(rndm_m, 97.5, axis=0) - - return rndm_m, [lower_radius, median_radius, upper_radius] + model_weights_random = betas @ Vt_hat + default_weights + yvals_central = model_weights_random @ filtered_model_predictions.T + + # Per-draw, per-point variances (n_draws, n_points). The floor is + # needed here (unlike during sampling) because the normalized metrics + # of extrapolated points can be negative, so phi . theta can dip + # below zero even though every theta draw is positive. + sigma2 = variance_params @ variance_basis.T + sigma2 = np.maximum(sigma2, VARIANCE_FLOOR) + + noise = rng.standard_normal(yvals_central.shape) * np.sqrt(sigma2) + rndm_m = yvals_central + noise + + lower = np.percentile(rndm_m, 2.5, axis=0) + median = np.percentile(rndm_m, 50, axis=0) + upper = np.percentile(rndm_m, 97.5, axis=0) + + return rndm_m, [lower, median, upper] + + +def coverage_quality(percentiles, coverage_results): + """ + Scalar calibration score: mean |empirical - nominal| coverage. + + Args: + percentiles (array-like): Nominal credible-interval widths in + percent (as passed to `coverage`). + coverage_results (array-like): Empirical coverage in percent. + + Returns: + float: Mean absolute deviation in percentage points (lower is + better; 0 is perfect calibration). + """ + return float( + np.mean(np.abs(np.asarray(coverage_results) - np.asarray(percentiles))) + ) + + +def mace(rndm_m, y_true, quantile_levels=None): + """ + Mean Absolute Calibration Error (MACE): a quantile-based calibration score. + + Complementary to `coverage`/`coverage_quality`'s two-sided central-interval + view: for each one-sided quantile level ``q``, compares the empirical + fraction of true values at or below the predictive ``q``-th percentile + against ``q`` itself. + + Args: + rndm_m (numpy.ndarray): Posterior predictive draws, shape + ``(n_samples, n_points)``. + y_true (array-like): True/observed values, shape ``(n_points,)``. + quantile_levels (array-like, optional): Quantile levels in percent, + 0-100 (default: 5, 10, ..., 95). + + Returns: + float: Mean absolute deviation between empirical and nominal + quantile coverage, in percentage points (lower is better; 0 is + perfect calibration). + """ + y_true = np.asarray(y_true, dtype=float) + if quantile_levels is None: + quantile_levels = np.arange(5, 100, 5) + quantile_levels = np.asarray(quantile_levels, dtype=float) + + predicted_quantiles = np.percentile(rndm_m, quantile_levels, axis=0) + empirical = np.mean(y_true[None, :] <= predicted_quantiles, axis=1) * 100.0 + return float(np.mean(np.abs(empirical - quantile_levels))) + + +def reduced_chi_square(rndm_m, y_true): + """ + Reduced chi-squared statistic of the posterior predictive distribution. + + ``chi^2_red = mean_i[ (y_true_i - mean_i)^2 / var_i ]`` where + ``mean_i``/``var_i`` are the posterior predictive mean/variance at + point ``i``. A value near 1 indicates well-calibrated predictive + uncertainties; > 1 means the intervals are too narrow (overconfident, + "underdispersed" in the language of `diagnose_coverage_shape`); < 1 + means too wide ("overdispersed"). + + Args: + rndm_m (numpy.ndarray): Posterior predictive draws, shape + ``(n_samples, n_points)``. + y_true (array-like): True/observed values, shape ``(n_points,)``. + + Returns: + float: Reduced chi-squared statistic. + + Raises: + ValueError: If the posterior predictive variance is non-positive + at any point (a degenerate/zero-noise predictive distribution). + """ + y_true = np.asarray(y_true, dtype=float) + pred_mean = np.mean(rndm_m, axis=0) + pred_var = np.var(rndm_m, axis=0) + if np.any(pred_var <= 0): + raise ValueError( + "Posterior predictive variance must be positive at every point." + ) + return float(np.mean((y_true - pred_mean) ** 2 / pred_var)) + + +def diagnose_coverage_shape( + percentiles, coverage_results, bias_tolerance=5.0, balance_threshold=0.7 +): + """ + Classifies credible intervals as under-/over-dispersed or calibrated. + + Args: + percentiles (array-like): Nominal interval widths in percent. + coverage_results (array-like): Empirical coverage in percent. + bias_tolerance (float, optional): Mean absolute deviation + (percentage points) below which the model counts as well + calibrated (default: 5.0). + balance_threshold (float, optional): Fraction of intervals that + must lie consistently on one side of nominal to call the + direction (default: 0.7). + + Returns: + dict: Keys ``'diagnosis'`` (``'well_calibrated'`` | + ``'underdispersed'`` | ``'overdispersed'`` | ``'mixed'``), + ``'mean_bias'``, ``'mean_abs_error'``, ``'frac_below'``, + ``'frac_above'`` and ``'residuals'``. Underdispersed means the + intervals are too narrow (overconfident); overdispersed too wide. + """ + percentiles = np.asarray(percentiles, dtype=float) + coverage_results = np.asarray(coverage_results, dtype=float) + + residuals = coverage_results - percentiles + mean_bias = float(np.mean(residuals)) + mean_abs_error = float(np.mean(np.abs(residuals))) + frac_below = float(np.mean(residuals < 0)) + frac_above = float(np.mean(residuals > 0)) + + if mean_abs_error <= bias_tolerance: + diagnosis = "well_calibrated" + elif mean_bias < -bias_tolerance and frac_below >= balance_threshold: + diagnosis = "underdispersed" + elif mean_bias > bias_tolerance and frac_above >= balance_threshold: + diagnosis = "overdispersed" + else: + diagnosis = "mixed" + + return { + "diagnosis": diagnosis, + "mean_bias": mean_bias, + "mean_abs_error": mean_abs_error, + "frac_below": frac_below, + "frac_above": frac_above, + "residuals": residuals, + } diff --git a/pyproject.toml b/pyproject.toml index 40da63b..1e468c7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,7 +9,7 @@ authors = [ "Pablo Giuliani", "An Le" ] -license = "GPL-3.0" +license = "MIT" readme = "README.md" homepage = "https://github.com/ascsn/pybmc" repository = "https://github.com/ascsn/pybmc" diff --git a/tests/test_bmc.py b/tests/test_bmc.py index 60b1cd6..5392ec7 100644 --- a/tests/test_bmc.py +++ b/tests/test_bmc.py @@ -196,5 +196,42 @@ def test_bmc_evaluate(self): assert all(isinstance(c, float) for c in coverage_results) +class TestPosteriorPredictiveReproducibility(unittest.TestCase): + """Regression tests for the predict()/evaluate() seed threading.""" + + def setUp(self): + self.df = pd.DataFrame( + { + "x": [1, 2, 3, 4, 5, 6], + "truth": [11, 21, 31, 41, 51, 61], + "model1": [10, 20, 30, 40, 50, 60], + "model2": [15, 25, 35, 45, 55, 65], + "model3": [12, 30, 32, 43, 58, 67], + } + ) + self.bmc = BayesianModelCombination( + models_list=["model1", "model2", "model3", "truth"], + data_dict={"target": self.df}, + truth_column_name="truth", + ) + self.bmc.orthogonalize( + property="target", train_df=self.df.iloc[:4], components_kept=2 + ) + self.bmc.train() + + def test_predict_default_seed_is_reproducible(self): + rndm_m1, *_ = self.bmc.predict("target") + rndm_m2, *_ = self.bmc.predict("target") + np.testing.assert_array_equal(rndm_m1, rndm_m2) + + def test_predict_different_seeds_give_different_draws(self): + rndm_m1, *_ = self.bmc.predict("target", seed=1) + rndm_m2, *_ = self.bmc.predict("target", seed=2) + self.assertFalse(np.array_equal(rndm_m1, rndm_m2)) + + def test_evaluate_default_seed_is_reproducible(self): + self.assertEqual(self.bmc.evaluate(), self.bmc.evaluate()) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_error_models.py b/tests/test_error_models.py new file mode 100644 index 0000000..40f557f --- /dev/null +++ b/tests/test_error_models.py @@ -0,0 +1,449 @@ +"""Tests for the heteroscedastic error models.""" +import unittest +import numpy as np +import pandas as pd + +from pybmc.bmc import BayesianModelCombination +from pybmc.error_models import ( + VARIANCE_MODELS, + HeteroscedasticMetrics, + required_metrics, + variance_basis, + variance_parameter_names, +) +from pybmc.inference_utils import gibbs_sampler_heteroscedastic +from pybmc.sampling_utils import ( + coverage_quality, + diagnose_coverage_shape, + mace, + reduced_chi_square, +) + +HETERO_MODELS = [m for m in VARIANCE_MODELS if m != "homoscedastic"] + + +def make_heteroscedastic_data(n_points=60, n_models=4, seed=7): + """Synthetic dataset whose noise grows with the model spread.""" + rng = np.random.default_rng(seed) + x = np.linspace(0, 10, n_points) + base = 5.0 + 2.0 * x + + data = {"x": x} + preds = [] + for j in range(n_models): + # Models disagree more at large x. + offset = rng.normal(0, 0.2) + rng.normal(0, 0.05) * x + preds.append(base + offset) + data[f"model{j + 1}"] = preds[j] + + spread = np.var(np.column_stack(preds), axis=1) + noise = rng.normal(0, np.sqrt(0.05 + 2.0 * spread)) + data["truth"] = base + noise + return pd.DataFrame(data) + + +class TestErrorModelRegistry(unittest.TestCase): + def test_registry_contents(self): + self.assertIn("homoscedastic", VARIANCE_MODELS) + self.assertEqual(len(VARIANCE_MODELS), 7) + self.assertEqual(VARIANCE_MODELS["homoscedastic"], []) + self.assertEqual( + VARIANCE_MODELS["hetero_combined_quadratic"], + [("pc_dist", 1), ("pc_dist", 2), ("model_var", 1), ("model_var", 2)], + ) + + def test_required_metrics(self): + self.assertEqual(required_metrics("homoscedastic"), []) + self.assertEqual(required_metrics("hetero_pc_dist"), ["pc_dist"]) + self.assertEqual( + required_metrics("hetero_combined_linear"), + ["model_var", "pc_dist"], + ) + with self.assertRaises(ValueError): + required_metrics("bogus") + + def test_variance_parameter_names(self): + self.assertEqual(variance_parameter_names("homoscedastic"), ["sigma^2"]) + self.assertEqual( + variance_parameter_names("hetero_model_var_quad"), + ["alpha", "beta_model_var^1", "beta_model_var^2"], + ) + with self.assertRaises(ValueError): + variance_parameter_names("bogus") + + +class TestHeteroscedasticMetrics(unittest.TestCase): + def setUp(self): + rng = np.random.default_rng(0) + self.train_preds = rng.normal(size=(30, 4)) + 10 * rng.normal(size=(30, 1)) + centered = self.train_preds - self.train_preds.mean(axis=1, keepdims=True) + _, S, Vt = np.linalg.svd(centered) + self.Vt_hat = np.array([Vt[i] / S[i] for i in range(2)]) + + def test_fit_and_compute_on_training_data(self): + calc = HeteroscedasticMetrics(["pc_dist", "model_var"]).fit( + self.train_preds, self.Vt_hat + ) + metrics = calc.compute(self.train_preds) + for name in ("pc_dist", "model_var"): + self.assertEqual(metrics[name].shape, (30,)) + # Training metrics are min-max scaled to [0, 1]. + self.assertAlmostEqual(float(np.min(metrics[name])), 0.0) + self.assertAlmostEqual(float(np.max(metrics[name])), 1.0) + + def test_extrapolation_can_exceed_one(self): + calc = HeteroscedasticMetrics(["model_var"]).fit( + self.train_preds, self.Vt_hat + ) + far = self.train_preds * 10 # much larger spread among models + metrics = calc.compute(far) + self.assertGreater(float(np.max(metrics["model_var"])), 1.0) + + def test_compute_before_fit_raises(self): + calc = HeteroscedasticMetrics(["pc_dist"]) + with self.assertRaises(ValueError): + calc.compute(self.train_preds) + + def test_unknown_metric_raises(self): + with self.assertRaises(ValueError): + HeteroscedasticMetrics(["bogus"]) + + def test_variance_basis_shape(self): + calc = HeteroscedasticMetrics(["pc_dist", "model_var"]).fit( + self.train_preds, self.Vt_hat + ) + metrics = calc.compute(self.train_preds) + basis = variance_basis( + metrics, VARIANCE_MODELS["hetero_combined_quadratic"] + ) + self.assertEqual(basis.shape, (30, 5)) + np.testing.assert_allclose(basis[:, 0], 1.0) + np.testing.assert_allclose(basis[:, 2], basis[:, 1] ** 2) + + +class TestHeteroscedasticSampler(unittest.TestCase): + def setUp(self): + rng = np.random.default_rng(1) + n = 50 + self.X = rng.normal(size=(n, 2)) + metric = np.linspace(0, 1, n) + true_sigma2 = 0.1 + 0.5 * metric + self.y = self.X @ np.array([1.5, -0.5]) + rng.normal( + 0, np.sqrt(true_sigma2) + ) + self.basis = np.column_stack([np.ones(n), metric]) + + def test_sampler_shapes_and_finiteness(self): + samples, acceptance = gibbs_sampler_heteroscedastic( + self.y, self.X, self.basis, iterations=200, burn=100 + ) + self.assertEqual(samples.shape, (200, 4)) # 2 betas + alpha + beta_1 + self.assertFalse(np.any(np.isnan(samples))) + self.assertGreaterEqual(acceptance, 0.0) + self.assertLessEqual(acceptance, 1.0) + # Variance parameters stay positive. + self.assertTrue(np.all(samples[:, 2:] > 0)) + + def test_invalid_arguments_raise(self): + with self.assertRaises(ValueError): + gibbs_sampler_heteroscedastic( + self.y, self.X, self.basis, iterations=10, burn=-1 + ) + no_ones = np.column_stack([self.basis[:, 1], self.basis[:, 1]]) + with self.assertRaises(ValueError): + gibbs_sampler_heteroscedastic( + self.y, self.X, no_ones, iterations=10, burn=0 + ) + with self.assertRaises(ValueError): + gibbs_sampler_heteroscedastic( + self.y, self.X, self.basis, iterations=10, burn=0, + proposal_scales=[0.1], # wrong length + ) + negative_basis = self.basis.copy() + negative_basis[:, 1] -= 1.0 # negative entries break positivity + with self.assertRaises(ValueError): + gibbs_sampler_heteroscedastic( + self.y, self.X, negative_basis, iterations=10, burn=0 + ) + + def test_sampler_seed_reproducible(self): + s1, _ = gibbs_sampler_heteroscedastic( + self.y, self.X, self.basis, iterations=50, burn=20, seed=11 + ) + s2, _ = gibbs_sampler_heteroscedastic( + self.y, self.X, self.basis, iterations=50, burn=20, seed=11 + ) + np.testing.assert_array_equal(s1, s2) + + +class TestBMCErrorModelInit(unittest.TestCase): + def setUp(self): + self.df = make_heteroscedastic_data() + self.data_dict = {"target": self.df} + self.models = ["model1", "model2", "model3", "model4"] + + def test_default_error_model_is_homoscedastic(self): + bmc = BayesianModelCombination( + models_list=self.models, + data_dict=self.data_dict, + truth_column_name="truth", + ) + self.assertEqual(bmc.error_model, "homoscedastic") + + def test_valid_error_models_tuple(self): + self.assertEqual( + set(BayesianModelCombination.VALID_ERROR_MODELS), + set(VARIANCE_MODELS), + ) + + def test_invalid_error_model_raises(self): + with self.assertRaises(ValueError) as ctx: + BayesianModelCombination( + models_list=self.models, + data_dict=self.data_dict, + truth_column_name="truth", + error_model="bogus", + ) + self.assertIn("Invalid error model", str(ctx.exception)) + + def test_simplex_with_hetero_raises(self): + with self.assertRaises(ValueError): + BayesianModelCombination( + models_list=self.models, + data_dict=self.data_dict, + truth_column_name="truth", + constraint="simplex", + error_model="hetero_pc_dist", + ) + + def test_simplex_override_with_hetero_raises_in_train(self): + bmc = BayesianModelCombination( + models_list=self.models, + data_dict=self.data_dict, + truth_column_name="truth", + error_model="hetero_pc_dist", + ) + bmc.orthogonalize("target", self.df.iloc[:40], components_kept=2) + with self.assertRaises(ValueError): + bmc.train(training_options={"sampler": "simplex"}) + + def test_invalid_error_model_in_training_options_raises(self): + bmc = BayesianModelCombination( + models_list=self.models, + data_dict=self.data_dict, + truth_column_name="truth", + ) + bmc.orthogonalize("target", self.df.iloc[:40], components_kept=2) + with self.assertRaises(ValueError): + bmc.train(training_options={"error_model": "bogus"}) + + +class TestBMCHeteroscedasticTraining(unittest.TestCase): + def setUp(self): + self.df = make_heteroscedastic_data() + self.data_dict = {"target": self.df} + self.models = ["model1", "model2", "model3", "model4"] + self.train_df = self.df.iloc[:40] + self.components = 2 + + def _trained_bmc(self, error_model, iterations=300, burn=100): + bmc = BayesianModelCombination( + models_list=self.models, + data_dict=self.data_dict, + truth_column_name="truth", + error_model=error_model, + ) + bmc.orthogonalize("target", self.train_df, components_kept=self.components) + bmc.train(training_options={"iterations": iterations, "burn": burn}) + return bmc + + def test_all_hetero_models_train_predict_evaluate(self): + for error_model in HETERO_MODELS: + with self.subTest(error_model=error_model): + bmc = self._trained_bmc(error_model) + + n_variance_params = 1 + len(VARIANCE_MODELS[error_model]) + self.assertEqual( + bmc.samples.shape, + (300, self.components + n_variance_params), + ) + self.assertIsNotNone(bmc.mh_acceptance_rate_) + + rndm_m, lower_df, median_df, upper_df = bmc.predict("target") + self.assertEqual(rndm_m.shape[1], len(self.df)) + self.assertTrue( + np.all( + upper_df["Predicted_Upper"].values + >= lower_df["Predicted_Lower"].values + ) + ) + self.assertFalse(np.any(np.isnan(rndm_m))) + + coverage_results = bmc.evaluate() + self.assertEqual(len(coverage_results), 21) + + weights = bmc.get_weights(summary=False) + self.assertEqual(weights.shape, (300, len(self.models))) + # Weights always sum to 1 (Vt rows are orthogonal to ones). + np.testing.assert_allclose( + weights.sum(axis=1), 1.0, atol=1e-8 + ) + + def test_hetero_predict_default_seed_is_reproducible(self): + bmc = self._trained_bmc("hetero_combined_linear") + rndm_m1, *_ = bmc.predict("target") + rndm_m2, *_ = bmc.predict("target") + np.testing.assert_array_equal(rndm_m1, rndm_m2) + + def test_hetero_predict_different_seeds_give_different_draws(self): + bmc = self._trained_bmc("hetero_combined_linear") + rndm_m1, *_ = bmc.predict("target", seed=1) + rndm_m2, *_ = bmc.predict("target", seed=2) + self.assertFalse(np.array_equal(rndm_m1, rndm_m2)) + + def test_error_model_override_in_training_options(self): + bmc = BayesianModelCombination( + models_list=self.models, + data_dict=self.data_dict, + truth_column_name="truth", + ) + bmc.orthogonalize("target", self.train_df, components_kept=2) + bmc.train( + training_options={ + "iterations": 200, + "burn": 50, + "error_model": "hetero_model_var", + } + ) + # 2 betas + alpha + beta_1 + self.assertEqual(bmc.samples.shape, (200, 4)) + self.assertEqual(bmc._trained_error_model, "hetero_model_var") + + def test_retrain_homoscedastic_after_hetero(self): + bmc = self._trained_bmc("hetero_model_var") + bmc.train( + training_options={"iterations": 200, "error_model": "homoscedastic"} + ) + self.assertEqual(bmc.samples.shape, (200, 3)) # 2 betas + sigma^2 + rndm_m, *_ = bmc.predict("target") + self.assertEqual(rndm_m.shape[1], len(self.df)) + + def test_hetero_widens_intervals_at_extrapolation(self): + """Interval width should grow with the metric for a linear model.""" + bmc = self._trained_bmc("hetero_model_var", iterations=500, burn=200) + _, lower_df, _, upper_df = bmc.predict("target") + width = ( + upper_df["Predicted_Upper"].values + - lower_df["Predicted_Lower"].values + ) + spread = np.var(self.df[self.models].values, axis=1) + # The widest-interval points should be among the high-spread points. + self.assertGreater( + np.mean(width[spread > np.median(spread)]), + np.mean(width[spread <= np.median(spread)]), + ) + + +class TestCalibrationDiagnostics(unittest.TestCase): + def test_coverage_quality_perfect(self): + percentiles = np.arange(0, 101, 5) + self.assertEqual(coverage_quality(percentiles, percentiles), 0.0) + + def test_coverage_quality_offset(self): + percentiles = np.arange(0, 101, 5) + self.assertAlmostEqual( + coverage_quality(percentiles, percentiles + 3.0), 3.0 + ) + + def test_diagnose_well_calibrated(self): + percentiles = np.arange(0, 101, 5) + result = diagnose_coverage_shape(percentiles, percentiles + 1.0) + self.assertEqual(result["diagnosis"], "well_calibrated") + + def test_diagnose_underdispersed(self): + percentiles = np.arange(0, 101, 5) + coverage_results = np.maximum(percentiles - 20.0, 0.0) + result = diagnose_coverage_shape(percentiles, coverage_results) + self.assertEqual(result["diagnosis"], "underdispersed") + self.assertLess(result["mean_bias"], 0) + + def test_diagnose_overdispersed(self): + percentiles = np.arange(0, 101, 5) + coverage_results = np.minimum(percentiles + 20.0, 100.0) + result = diagnose_coverage_shape(percentiles, coverage_results) + self.assertEqual(result["diagnosis"], "overdispersed") + self.assertGreater(result["mean_bias"], 0) + + def test_diagnostics_on_bmc_evaluate_output(self): + df = make_heteroscedastic_data() + bmc = BayesianModelCombination( + models_list=["model1", "model2", "model3", "model4"], + data_dict={"target": df}, + truth_column_name="truth", + error_model="hetero_model_var", + ) + bmc.orthogonalize("target", df.iloc[:40], components_kept=2) + bmc.train(training_options={"iterations": 300, "burn": 100}) + coverage_results = bmc.evaluate() + score = coverage_quality(np.arange(0, 101, 5), coverage_results) + self.assertGreaterEqual(score, 0.0) + diag = diagnose_coverage_shape(np.arange(0, 101, 5), coverage_results) + self.assertIn( + diag["diagnosis"], + {"well_calibrated", "underdispersed", "overdispersed", "mixed"}, + ) + + +class TestMACEAndReducedChiSquare(unittest.TestCase): + def test_mace_all_points_at_predicted_value(self): + # rndm_m constant at 0, y_true == 0 everywhere: every point is + # "at or below" every predicted quantile, so empirical coverage + # is 100% regardless of the nominal quantile level. + rndm_m = np.zeros((10, 4)) + y_true = np.zeros(4) + self.assertAlmostEqual(mace(rndm_m, y_true), 50.0) + + def test_mace_custom_quantile_levels(self): + rndm_m = np.zeros((10, 4)) + y_true = np.zeros(4) + score = mace(rndm_m, y_true, quantile_levels=[50]) + self.assertAlmostEqual(score, 50.0) + + def test_mace_well_calibrated_is_small(self): + rng = np.random.default_rng(0) + n_points = 2000 + rndm_m = rng.normal(size=(5000, n_points)) + y_true = rng.normal(size=n_points) + self.assertLess(mace(rndm_m, y_true), 3.0) + + def test_mace_overconfident_is_large(self): + rng = np.random.default_rng(0) + n_points = 2000 + rndm_m = rng.normal(scale=0.1, size=(5000, n_points)) + y_true = rng.normal(scale=1.0, size=n_points) + self.assertGreater(mace(rndm_m, y_true), 20.0) + + def test_reduced_chi_square_well_calibrated(self): + rng = np.random.default_rng(1) + n_points = 5000 + pred_mean = rng.normal(size=n_points) + rndm_m = pred_mean[None, :] + rng.normal(size=(2000, n_points)) + y_true = pred_mean + rng.normal(size=n_points) + self.assertAlmostEqual(reduced_chi_square(rndm_m, y_true), 1.0, delta=0.15) + + def test_reduced_chi_square_overconfident_exceeds_one(self): + rng = np.random.default_rng(2) + n_points = 2000 + rndm_m = rng.normal(scale=0.1, size=(2000, n_points)) + y_true = rng.normal(scale=1.0, size=n_points) + self.assertGreater(reduced_chi_square(rndm_m, y_true), 5.0) + + def test_reduced_chi_square_zero_variance_raises(self): + rndm_m = np.ones((10, 3)) + y_true = np.array([1.0, 2.0, 3.0]) + with self.assertRaises(ValueError): + reduced_chi_square(rndm_m, y_true) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_inference_utils.py b/tests/test_inference_utils.py index 6991b0e..672e57b 100644 --- a/tests/test_inference_utils.py +++ b/tests/test_inference_utils.py @@ -1,22 +1,49 @@ import numpy as np import pytest -from pybmc.inference_utils import gibbs_sampler, gibbs_sampler_simplex, USVt_hat_extraction +from pybmc.inference_utils import ( + gibbs_sampler, + gibbs_sampler_simplex, + gibbs_sampler_heteroscedastic, + USVt_hat_extraction, +) + def test_gibbs_sampler(): y = np.array([1.0, 2.0, 3.0]) X = np.array([[1, 0], [0, 1], [1, 1]]) iterations = 10 - prior_info = ( - np.array([0.0, 0.0]), - np.eye(2), - 1.0, - 1.0 - ) + prior_info = { + "b_mean_prior": np.array([0.0, 0.0]), + "b_mean_cov": np.eye(2), + } - samples = gibbs_sampler(y, X, iterations, prior_info) + samples = gibbs_sampler(y, X, iterations, prior_info, burn=100) assert samples.shape == (iterations, 3) assert not np.any(np.isnan(samples)) + # Last column is the constant variance sigma^2, positive by construction. + assert np.all(samples[:, -1] > 0) + + +def test_gibbs_sampler_matches_constant_basis_heteroscedastic(): + # The homoscedastic sampler is the constant-only case of the + # heteroscedastic one: with the same seed they must agree exactly. + y = np.array([1.0, 2.0, 3.0, 2.5]) + X = np.array([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0], [0.5, 0.5]]) + samples = gibbs_sampler(y, X, 20, burn=50, seed=3) + hetero_samples, _ = gibbs_sampler_heteroscedastic( + y, X, np.ones((len(y), 1)), 20, burn=50, seed=3 + ) + np.testing.assert_array_equal(samples, hetero_samples) + + +def test_gibbs_sampler_seed_reproducible(): + y = np.array([1.0, 2.0, 3.0]) + X = np.array([[1, 0], [0, 1], [1, 1]]) + s1 = gibbs_sampler(y, X, 20, burn=50, seed=123) + s2 = gibbs_sampler(y, X, 20, burn=50, seed=123) + np.testing.assert_array_equal(s1, s2) + def test_gibbs_sampler_simplex(): y = np.array([1.0, 2.0, 3.0]) @@ -30,6 +57,21 @@ def test_gibbs_sampler_simplex(): assert samples.shape[0] == iterations assert not np.any(np.isnan(samples)) + # Last column is sigma^2, positive by construction. + assert np.all(samples[:, -1] > 0) + + +def test_gibbs_sampler_simplex_seed_reproducible(): + y = np.array([1.0, 2.0, 3.0]) + X = np.array([[1, 0], [0, 1], [1, 1]]) + Vt_hat = np.array([[0.5, 0.5], [0.5, -0.5]]) + S_hat = np.array([1.0, 0.5]) + prior_info = [1.0, 1.0] + + s1 = gibbs_sampler_simplex(y, X, Vt_hat, S_hat, 20, prior_info, burn=50, stepsize=0.01, seed=7) + s2 = gibbs_sampler_simplex(y, X, Vt_hat, S_hat, 20, prior_info, burn=50, stepsize=0.01, seed=7) + np.testing.assert_array_equal(s1, s2) + def test_USVt_hat_extraction(): U = np.array([[1, 0], [0, 1]]) @@ -44,6 +86,7 @@ def test_USVt_hat_extraction(): assert Vt_hat.shape == (2, 2) assert Vt_hat_normalized.shape == (2, 2) + def test_gibbs_sampler_simplex_edge_cases(): # Test with invalid inputs y = np.array([1.0, 2.0, 3.0]) @@ -61,6 +104,7 @@ def test_gibbs_sampler_simplex_edge_cases(): with pytest.raises(ValueError): gibbs_sampler_simplex(y, X, Vt_hat, S_hat, iterations, prior_info, stepsize=-0.01) + def test_gibbs_sampler_simplex_acceptance_rate(): y = np.array([1.0, 2.0, 3.0]) X = np.array([[1, 0], [0, 1], [1, 1]])